diff --git a/docs/install.md b/docs/install.md index 6bbe8a16..fbd8bfda 100644 --- a/docs/install.md +++ b/docs/install.md @@ -319,8 +319,20 @@ the installer rather than being reset. The same password is given to the ntfy `phone-reader` account when that account is first created; existing ntfy accounts keep their passwords. -To change the web password, edit `password` in `web-auth.json` (keep it 0600) -and run `pipelines restart`. +After updating the installation, change the web sign-in password from the +checkout with: + +```sh +./password +``` + +It prompts twice without echoing the password, requires at least eight +characters, and writes the private password file atomically. The updated web +proxy picks it up on the next request; no service restart is needed, and existing +sessions and running tasks remain connected. SSH is supported with an interactive +TTY. This changes the web/app sign-in password; the ntfy notification account's +password is unchanged. `--prefix PATH` selects another installation, and +`PIPELINES_WEB_AUTH_FILE` selects an explicitly configured password file. ## Upgrading diff --git a/docs/notes/password-command.md b/docs/notes/password-command.md new file mode 100644 index 00000000..d2c162d5 --- /dev/null +++ b/docs/notes/password-command.md @@ -0,0 +1,24 @@ +# Password command + +Added checkout entry point `./password` with twice-entered hidden input and an +8-character minimum. It uses the existing installation's recorded password file, +explicit PIPELINES_WEB_AUTH_FILE, or default private file for partial installs. +Password arguments are not accepted, and non-TTY use is refused before prompting. + +The helper validates file ownership, regular-file type, permissions and auth JSON; +stages on the destination filesystem, fsyncs content and atomically replaces the +file. Concurrent helper updates serialize on the parent directory lock, and an +external change detected during staging is not overwritten. Cookie secret and +unknown metadata remain unchanged, preserving existing sessions. No service, +background task, provider credential or ntfy account is modified. + +Runtime use requires the updated proxy's per-request auth reload, implemented in +the browser-discovery/relay lane. Merely updating a checkout does not replace an +already-running installed proxy. The helper does not kill a proxy: the existing +supervisor would treat that as a fatal service exit. + +Verification: 11 focused tests passed, covering custom/default/partial-install +paths, private ownership boundaries, old-file preservation on errors, same-device +atomic replacement, external-write refusal, prompt retry/privacy and non-TTY +refusal. Wrapper help, shell syntax, Python compilation and diff checks passed. +No operator password or running service was changed during testing. diff --git a/password b/password new file mode 100755 index 00000000..699e68e8 --- /dev/null +++ b/password @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec python3 "$(dirname "$0")/scripts/password.py" "$@" diff --git a/scripts/password.py b/scripts/password.py new file mode 100644 index 00000000..9c2b854a --- /dev/null +++ b/scripts/password.py @@ -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}") diff --git a/scripts/test_password.py b/scripts/test_password.py new file mode 100644 index 00000000..5383109b --- /dev/null +++ b/scripts/test_password.py @@ -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)