Add interactive password change command without service restart

This commit is contained in:
2026-11-08 21:45:51 +00:00
parent 8016108558
commit 543e3f063a
5 changed files with 266 additions and 2 deletions
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Change the local Pipelines web sign-in password without restarting services."""
import argparse
import fcntl
import getpass
import json
import os
from pathlib import Path
import stat
import sys
import tempfile
def auth_path(*, prefix=None, home=None, environ=None):
home = Path(home or Path.home())
env = os.environ if environ is None else environ
selected = Path(prefix or env.get("PIPELINES_PREFIX") or home / ".local/share/pipelines").expanduser().resolve()
explicit = env.get("PIPELINES_WEB_AUTH_FILE")
if explicit:
return Path(explicit).expanduser().absolute()
manifest = selected / "pipelines-install.json"
if manifest.exists():
if manifest.is_symlink() or manifest.stat().st_uid != os.getuid():
raise ValueError("Refusing an unsafe installation manifest")
data = json.loads(manifest.read_text())
if data.get("format") != 1 or data.get("prefix") != str(selected):
raise ValueError("Invalid Pipelines installation manifest")
recorded = (data.get("web") or {}).get("auth_file")
if recorded:
return Path(recorded).expanduser().absolute()
return home / ".config/pipelines/web-auth.json"
def read_auth(path):
path = Path(path)
info = path.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid():
raise ValueError("Password file must be a regular file owned by this user")
if info.st_mode & 0o077:
raise ValueError(f"Password file must be private: chmod 600 '{path}'")
data = json.loads(path.read_text())
if not isinstance(data, dict) or not isinstance(data.get("password"), str) or len(data["password"]) < 8 or not isinstance(data.get("secret"), str) or len(data["secret"]) < 32:
raise ValueError("Invalid Pipelines password file; it was retained unchanged")
return data, info
def change_password(path, password):
if len(password) < 8:
raise ValueError("Choose a password of at least 8 characters")
path = Path(path)
# Lock the directory inode, which remains stable across atomic file replaces.
directory = os.open(path.parent, os.O_RDONLY)
try:
fcntl.flock(directory, fcntl.LOCK_EX)
data, original = read_auth(path)
data["password"] = password
descriptor, temporary = tempfile.mkstemp(prefix=".pipelines-password-", dir=path.parent)
try:
with os.fdopen(descriptor, "w") as output:
os.fchmod(output.fileno(), 0o600)
json.dump(data, output, indent=2)
output.write("\n")
output.flush()
os.fsync(output.fileno())
current = path.lstat()
if (current.st_dev, current.st_ino, current.st_mtime_ns, current.st_size) != (original.st_dev, original.st_ino, original.st_mtime_ns, original.st_size):
raise ValueError("Password file changed during the update; retry the command")
os.replace(temporary, path)
finally:
Path(temporary).unlink(missing_ok=True)
finally:
os.close(directory)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--prefix", type=Path, help="Installation prefix (or PIPELINES_PREFIX)")
args = parser.parse_args()
path = auth_path(prefix=args.prefix)
read_auth(path)
if not sys.stdin.isatty():
raise ValueError("Run ./password in an interactive terminal (SSH with a TTY is supported)")
while True:
password = getpass.getpass("New Pipelines password: ")
confirmation = getpass.getpass("Confirm new password: ")
if len(password) < 8:
print("Choose a password of at least 8 characters.", file=sys.stderr)
elif password != confirmation:
print("Passwords do not match. Try again.", file=sys.stderr)
else:
break
change_password(path, password)
print("Web sign-in password changed. No service restart is needed.")
print("Existing sessions remain signed in. The notification password is unchanged.")
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, KeyboardInterrupt) as error:
sys.exit(f"Password not changed: {error}")
+124
View File
@@ -0,0 +1,124 @@
import importlib.util
import json
import io
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location("pipelines_password", Path(__file__).with_name("password.py"))
password = importlib.util.module_from_spec(spec)
spec.loader.exec_module(password)
class PasswordTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="pipelines-password-test-")
self.addCleanup(self.temporary.cleanup)
self.home = Path(self.temporary.name).resolve()
self.auth = self.home / ".config/pipelines/web-auth.json"
self.auth.parent.mkdir(parents=True)
self.original = {"password": "old password", "secret": "s" * 32, "other": "preserve"}
self.auth.write_text(json.dumps(self.original))
self.auth.chmod(0o600)
def test_default_path_works_for_partial_install_without_manifest(self):
self.assertEqual(password.auth_path(home=self.home, environ={}), self.auth)
def test_manifest_custom_auth_and_explicit_environment(self):
prefix = self.home / "installation"
prefix.mkdir()
recorded = self.home / "custom-auth.json"
(prefix / "pipelines-install.json").write_text(json.dumps({
"format": 1, "prefix": str(prefix), "web": {"auth_file": str(recorded)}}))
self.assertEqual(password.auth_path(home=self.home, prefix=prefix, environ={}), recorded)
self.assertEqual(password.auth_path(home=self.home, prefix=prefix,
environ={"PIPELINES_WEB_AUTH_FILE": str(self.auth)}), self.auth)
def test_change_preserves_cookie_secret_metadata_and_private_permissions(self):
password.change_password(self.auth, "new password")
result = json.loads(self.auth.read_text())
self.assertEqual(result, dict(self.original, password="new password"))
self.assertEqual(self.auth.stat().st_mode & 0o777, 0o600)
self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), [])
def test_short_password_does_not_modify_auth(self):
with self.assertRaises(ValueError):
password.change_password(self.auth, "short")
self.assertEqual(json.loads(self.auth.read_text()), self.original)
def test_symlinked_password_is_refused_and_target_untouched(self):
link = self.home / "link.json"
link.symlink_to(self.auth)
with self.assertRaises(ValueError):
password.change_password(link, "new password")
self.assertEqual(json.loads(self.auth.read_text()), self.original)
self.assertTrue(link.is_symlink())
def test_public_or_malformed_auth_is_not_replaced(self):
self.auth.chmod(0o644)
with self.assertRaisesRegex(ValueError, "private"):
password.change_password(self.auth, "new password")
self.auth.chmod(0o600)
self.auth.write_text("{broken")
with self.assertRaises(ValueError):
password.change_password(self.auth, "new password")
self.assertEqual(self.auth.read_text(), "{broken")
def test_replacement_failure_preserves_original_and_cleans_staging(self):
before = self.auth.read_bytes()
with patch.object(password.os, "replace", side_effect=OSError("fixture failure")):
with self.assertRaises(OSError):
password.change_password(self.auth, "new password")
self.assertEqual(self.auth.read_bytes(), before)
self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), [])
def test_atomic_replace_occurs_on_destination_filesystem(self):
replace = os.replace
calls = []
def checked_replace(source, target):
calls.append((source, target))
self.assertEqual(Path(source).parent, self.auth.parent)
return replace(source, target)
with patch.object(password.os, "replace", side_effect=checked_replace):
password.change_password(self.auth, "new password")
self.assertEqual(len(calls), 1)
def test_file_changed_during_update_is_not_overwritten(self):
replace = os.fsync
def external_update(descriptor):
self.auth.write_text(json.dumps(dict(self.original, password="changed elsewhere")))
return replace(descriptor)
with patch.object(password.os, "fsync", side_effect=external_update):
with self.assertRaisesRegex(ValueError, "changed during"):
password.change_password(self.auth, "new password")
self.assertEqual(json.loads(self.auth.read_text())["password"], "changed elsewhere")
self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), [])
def test_cli_retries_mismatch_and_does_not_print_password(self):
output = io.StringIO()
errors = io.StringIO()
with patch.object(password.sys, "argv", ["password"]), \
patch.object(password, "auth_path", return_value=self.auth), \
patch.object(password.sys.stdin, "isatty", return_value=True), \
patch.object(password.getpass, "getpass", side_effect=[
"first password", "wrong confirmation", "new password", "new password"]), \
patch.object(password.sys, "stdout", output), \
patch.object(password.sys, "stderr", errors):
password.main()
self.assertEqual(json.loads(self.auth.read_text())["password"], "new password")
self.assertIn("do not match", errors.getvalue())
self.assertIn("No service restart", output.getvalue())
for value in ("first password", "wrong confirmation", "new password", "old password"):
self.assertNotIn(value, output.getvalue() + errors.getvalue())
def test_cli_refuses_non_tty_before_prompting(self):
with patch.object(password.sys, "argv", ["password"]), \
patch.object(password, "auth_path", return_value=self.auth), \
patch.object(password.sys.stdin, "isatty", return_value=False), \
patch.object(password.getpass, "getpass") as prompt:
with self.assertRaisesRegex(ValueError, "interactive terminal"):
password.main()
prompt.assert_not_called()
self.assertEqual(json.loads(self.auth.read_text()), self.original)