From e43f9fa50cb7d65082478376025dca9d611cbece Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 01:21:28 +0000 Subject: [PATCH] Hash the web password and revoke sessions server-side Store a scrypt hash (migrating a plaintext password without changing it), sign sessions with a generation that ./password and --revoke-all rotate, make logout a same-origin POST that revokes the token, add sign out everywhere, and close proxied websockets whose session ends. Enforce a strength rule for new passwords, back off logins per client and server-wide, check Origin on login, tighten next, add security headers and a __Host- cookie over https. --- scripts/manage.py | 4 + scripts/password.py | 176 +++++++++++++++++++++-- scripts/setup-native.py | 38 +++-- scripts/test_password.py | 92 ++++++++++-- scripts/test_setup_native.py | 16 ++- scripts/uninstall.py | 5 +- web/serve.mjs | 266 ++++++++++++++++++++++++----------- web/src/authStore.js | 233 ++++++++++++++++++++++++++++++ web/src/loginLimiter.js | 79 +++++++++++ web/src/passwordPolicy.js | 76 ++++++++++ web/src/peerRelay.js | 2 + web/src/peerTransport.js | 2 +- web/src/sessionSockets.js | 30 ++++ web/src/webSecurity.js | 72 ++++++++++ web/test/authProxy.test.mjs | 183 ++++++++++++++++++++++++ web/test/authReload.test.mjs | 9 +- web/test/authStore.test.mjs | 195 +++++++++++++++++++++++++ 17 files changed, 1353 insertions(+), 125 deletions(-) create mode 100644 web/src/authStore.js create mode 100644 web/src/loginLimiter.js create mode 100644 web/src/passwordPolicy.js create mode 100644 web/src/sessionSockets.js create mode 100644 web/src/webSecurity.js create mode 100644 web/test/authProxy.test.mjs create mode 100644 web/test/authStore.test.mjs diff --git a/scripts/manage.py b/scripts/manage.py index 9f958559..ebd1a99f 100644 --- a/scripts/manage.py +++ b/scripts/manage.py @@ -416,6 +416,10 @@ def supervise(config): PIPELINES_NTFY_PUBLIC_URL=config["public_url"], PIPELINES_NTFY_TOKEN_FILE=str(root / "secrets/publisher-token")) env.pop("PIPELINES_NTFY_TOKEN", None) + if config.get("web"): + # The server verifies step-up re-authentication against the + # web sign-in password file (read-only). + env["PIPELINES_WEB_AUTH_FILE"] = config["web"]["auth_file"] server_command = [str(root / "bin/pipelines-server"), "-addr", server_address(config), "-db", str(root / "data/pipelines.db")] if config.get("allow_authoring") is True: diff --git a/scripts/password.py b/scripts/password.py index 9c2b854a..d8232cb9 100644 --- a/scripts/password.py +++ b/scripts/password.py @@ -1,15 +1,119 @@ #!/usr/bin/env python3 -"""Change the local Pipelines web sign-in password without restarting services.""" +"""Change the local Pipelines web sign-in password, or sign out every device. + +The password is stored only as a scrypt hash. Every change (and --revoke-all) +rotates the cookie secret and the session generation, so each signed-in +browser and device must sign in again; open connections are closed within a +few seconds. No service restart is needed. +""" import argparse +import base64 import fcntl import getpass +import hashlib +import hmac import json import os from pathlib import Path +import re +import secrets import stat import sys import tempfile +# scrypt cost: 32 MiB and roughly a tenth of a second per check. The hash +# records its parameters, so they can be raised later without a migration. +SCRYPT_N, SCRYPT_R, SCRYPT_P, SCRYPT_KEY = 1 << 15, 8, 1, 32 +SCRYPT_MAXMEM = 64 * 1024 * 1024 + +PASSWORD_RULE = ("Use at least 16 characters, or a passphrase of 4 or more random words " + "separated by spaces or dashes (15 characters or more in all). Common words, " + "keyboard runs and repeated characters do not count towards the length.") + +# Kept in step with web/src/passwordPolicy.js. +COMMON = ("password", "passwort", "pipelines", "pipeline", "qwerty", "azerty", "letmein", + "welcome", "admin", "administrator", "iloveyou", "monkey", "dragon", "master", + "secret", "login", "changeme", "default", "football", "baseball", "sunshine", + "princess", "shadow", "trustno", "superman", "hello", "test", "guest", "root") +SEPARATORS = re.compile(r"[\s\-_.,;:+/]+") + + +def _runs(text): + """Remove runs of 3+ repeated characters and 4+ consecutive characters.""" + out, i = [], 0 + while i < len(text): + j = i + 1 + while j < len(text) and text[j] == text[i]: + j += 1 + if j - i >= 3: + i = j + continue + for step in (1, -1): + j = i + 1 + while j < len(text) and ord(text[j]) - ord(text[j - 1]) == step: + j += 1 + if j - i >= 4: + break + else: + out.append(text[i]) + i += 1 + continue + i = j + return "".join(out) + + +def _substance(password): + """The characters left once common words, runs and separators are removed.""" + text = password.lower() + for word in sorted(COMMON, key=len, reverse=True): + text = text.replace(word, "") + for row in ("qwertyuiop", "asdfghjkl", "zxcvbnm", "1234567890"): + for size in range(len(row), 3, -1): + for start in range(len(row) - size + 1): + text = text.replace(row[start:start + size], "") + return SEPARATORS.sub("", _runs(text)) + + +def password_problem(password): + """Why a new password is too weak, or None. See PASSWORD_RULE.""" + if len(password) > 1024: + return "Choose a password of at most 1024 characters." + words = [word.lower() for word in SEPARATORS.split(password) if word] + passphrase = (len(words) >= 4 and len(set(words)) >= 4 and all(len(word) >= 3 for word in words) + and len(password) >= 15 and len(_substance(password)) >= 12) + if passphrase: + return None + if len(password) < 16: + return "Too short. " + PASSWORD_RULE + if len(set(password)) < 8 or len(_substance(password)) < 12: + return "Too predictable. " + PASSWORD_RULE + return None + + +def _b64(raw): + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + +def hash_password(password, *, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P): + salt = secrets.token_bytes(16) + key = hashlib.scrypt(password.encode(), salt=salt, n=n, r=r, p=p, maxmem=SCRYPT_MAXMEM, dklen=SCRYPT_KEY) + return f"scrypt${n}${r}${p}${_b64(salt)}${_b64(key)}" + + +def verify_password(stored, candidate): + """Constant-time check of candidate against a stored scrypt hash.""" + try: + scheme, n, r, p, salt, key = stored.split("$") + if scheme != "scrypt": + return False + pad = lambda value: base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + expected = pad(key) + derived = hashlib.scrypt(candidate.encode(), salt=pad(salt), n=int(n), r=int(r), p=int(p), + maxmem=SCRYPT_MAXMEM, dklen=len(expected)) + except (ValueError, TypeError): + return False + return hmac.compare_digest(derived, expected) + def auth_path(*, prefix=None, home=None, environ=None): home = Path(home or Path.home()) @@ -31,6 +135,17 @@ def auth_path(*, prefix=None, home=None, environ=None): return home / ".config/pipelines/web-auth.json" +def valid_auth(data): + """Whether data is a usable web auth file: a scrypt hash (or a legacy + plaintext password the proxy has not migrated yet) and a cookie secret.""" + if not isinstance(data, dict) or not isinstance(data.get("secret"), str) or len(data["secret"]) < 32: + return False + stored = data.get("password_hash") + if isinstance(stored, str): + return stored.startswith("scrypt$") and stored.count("$") == 5 + return isinstance(data.get("password"), str) and len(data["password"]) >= 8 + + def read_auth(path): path = Path(path) info = path.lstat() @@ -39,21 +154,27 @@ def read_auth(path): 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: + if not valid_auth(data): 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") +def _rotate(data): + """Invalidate every session: a new cookie secret and session generation.""" + generation = data.get("generation") + data["generation"] = (generation if isinstance(generation, int) and generation >= 0 else 0) + 1 + data["secret"] = secrets.token_urlsafe(48) + + +def update_auth(path, mutate): + """Apply mutate to the auth file atomically, under a directory lock.""" 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 + mutate(data) descriptor, temporary = tempfile.mkstemp(prefix=".pipelines-password-", dir=path.parent) try: with os.fdopen(descriptor, "w") as output: @@ -72,26 +193,57 @@ def change_password(path, password): os.close(directory) +def change_password(path, password): + problem = password_problem(password) + if problem: + raise ValueError(problem) + stored = hash_password(password) + + def mutate(data): + data.pop("password", None) + data["password_hash"] = stored + data["password_weak"] = False + _rotate(data) + + update_auth(path, mutate) + + +def revoke_all(path): + update_auth(path, _rotate) + + def main(): - parser = argparse.ArgumentParser(description=__doc__) + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--prefix", type=Path, help="Installation prefix (or PIPELINES_PREFIX)") + parser.add_argument("--revoke-all", action="store_true", + help="Sign out every browser and device without changing the password") args = parser.parse_args() path = auth_path(prefix=args.prefix) - read_auth(path) + data, _ = read_auth(path) + if args.revoke_all: + revoke_all(path) + print("Every browser and device was signed out; sign in again with the same password.") + return if not sys.stdin.isatty(): raise ValueError("Run ./password in an interactive terminal (SSH with a TTY is supported)") + if data.get("password_weak") is True: + print("Warning: the current web password is weak. " + PASSWORD_RULE, file=sys.stderr) + print(PASSWORD_RULE) while True: password = getpass.getpass("New Pipelines password: ") + problem = password_problem(password) + if problem: + print(problem, file=sys.stderr) + continue 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: + if 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.") + print("Every browser and device was signed out and must sign in with the new password.") + print("The notification password is unchanged.") if __name__ == "__main__": diff --git a/scripts/setup-native.py b/scripts/setup-native.py index 7ed9bdde..7a5e7153 100644 --- a/scripts/setup-native.py +++ b/scripts/setup-native.py @@ -44,6 +44,7 @@ lan = module("lan_address", "lan-address.py") release_lookup = module("resolve_releases", "resolve-releases.py") tokens = module("save_ntfy_token", "save-ntfy-token.py") app_build = module("app_build", "app_build.py") +web_password = module("pipelines_password", "password.py") DEFAULT_PREFIX = Path.home() / ".local/share/pipelines" MARKER = "pipelines-install.json" @@ -348,16 +349,17 @@ class Setup: or Path.home() / ".config/pipelines/web-auth.json").expanduser().resolve() if auth.exists(): data = json.loads(auth.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): + if not web_password.valid_auth(data): raise ValueError(f"Invalid existing web auth file; retained unchanged: {auth}") if auth.stat().st_mode & 0o077: raise ValueError(f"Web auth file must be private (chmod 600): {auth}") else: password = self.choose_password() + self.chosen_web_password = password auth.parent.mkdir(mode=0o700, parents=True, exist_ok=True) - self._write_atomic(auth, (json.dumps({"password": password, + # Only a scrypt hash is stored (see scripts/password.py). + self._write_atomic(auth, (json.dumps({"password_hash": web_password.hash_password(password), + "password_weak": False, "generation": 0, "secret": secrets.token_urlsafe(48)}) + "\n").encode(), 0o600) target = prefix / "lib/web" shutil.copytree(Path(__file__).resolve().parents[1] / "web", target, dirs_exist_ok=True, @@ -374,17 +376,20 @@ class Setup: PIPELINES_WEB_PASSWORD answers it without a terminal (automation).""" given = self.environ.get("PIPELINES_WEB_PASSWORD") if given is not None: - if len(given) < 8: - raise ValueError("PIPELINES_WEB_PASSWORD must be at least 8 characters") + problem = web_password.password_problem(given) + if problem: + raise ValueError(f"PIPELINES_WEB_PASSWORD is too weak. {problem}") return given if not sys.stdin.isatty(): raise ValueError("Choose the web sign-in password: rerun ./install in a terminal, " - "or set PIPELINES_WEB_PASSWORD (at least 8 characters)") + "or set PIPELINES_WEB_PASSWORD. " + web_password.PASSWORD_RULE) print("This computer has no web sign-in yet. Choose the password for the web app and phone.") + print(web_password.PASSWORD_RULE) while True: - first = getpass.getpass("Web password (at least 8 characters): ") - if len(first) < 8: - print("Too short; use at least 8 characters.") + first = getpass.getpass("Web password: ") + problem = web_password.password_problem(first) + if problem: + print(problem) continue if getpass.getpass("Repeat the password: ") != first: print("The passwords did not match; try again.") @@ -673,6 +678,17 @@ class Setup: process.kill() process.wait() + def reader_password(self, web): + """The phone's ntfy password, which matches the web password: the one + chosen during this install, else a not yet migrated plaintext file. A + hashed file has no plaintext; an existing ntfy account keeps its own + password and a new one is asked for on the terminal.""" + chosen = getattr(self, "chosen_web_password", None) + if chosen is not None: + return chosen + legacy = json.loads(Path(web["auth_file"]).read_text()).get("password") + return legacy if isinstance(legacy, str) else None + def bootstrap_ntfy(self, prefix, config_path, reader_password=None): def run_ntfy(args, capture=False, interactive=False, password=None): return self.ntfy(prefix, config_path, list(args), capture=capture, password=password) @@ -856,7 +872,7 @@ class Setup: else: self.migrate_docker(prefix, args.replace_data) self.bootstrap_ntfy(prefix, config_path, - reader_password=json.loads(Path(web["auth_file"]).read_text())["password"]) + reader_password=self.reader_password(web)) timezone = args.timezone if not timezone: try: diff --git a/scripts/test_password.py b/scripts/test_password.py index 5383109b..15684a62 100644 --- a/scripts/test_password.py +++ b/scripts/test_password.py @@ -12,6 +12,9 @@ password = importlib.util.module_from_spec(spec) spec.loader.exec_module(password) +NEW = "tulip orbit canyon ember" + + class PasswordTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory(prefix="pipelines-password-test-") @@ -36,12 +39,61 @@ class PasswordTests(unittest.TestCase): 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") + def test_change_stores_a_hash_rotates_sessions_and_keeps_metadata(self): + password.change_password(self.auth, NEW) result = json.loads(self.auth.read_text()) - self.assertEqual(result, dict(self.original, password="new password")) + self.assertNotIn("password", result) + self.assertNotIn(NEW, self.auth.read_text()) + self.assertTrue(result["password_hash"].startswith("scrypt$32768$8$1$")) + self.assertTrue(password.verify_password(result["password_hash"], NEW)) + self.assertFalse(password.verify_password(result["password_hash"], "old password")) + self.assertIs(result["password_weak"], False) + self.assertNotEqual(result["secret"], self.original["secret"]) + self.assertGreaterEqual(len(result["secret"]), 32) + self.assertEqual(result["generation"], 1) + self.assertEqual(result["other"], "preserve") self.assertEqual(self.auth.stat().st_mode & 0o777, 0o600) self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) + password.change_password(self.auth, "k7#Rv9!qLm2@Xz4s") + self.assertEqual(json.loads(self.auth.read_text())["generation"], 2) + + def test_revoke_all_rotates_secret_and_generation_but_keeps_password(self): + password.change_password(self.auth, NEW) + before = json.loads(self.auth.read_text()) + password.revoke_all(self.auth) + after = json.loads(self.auth.read_text()) + self.assertEqual(after["password_hash"], before["password_hash"]) + self.assertEqual(after["generation"], before["generation"] + 1) + self.assertNotEqual(after["secret"], before["secret"]) + + def test_revoke_all_cli_needs_no_terminal_and_prints_no_secret(self): + output = io.StringIO() + with patch.object(password.sys, "argv", ["password", "--revoke-all"]), \ + patch.object(password, "auth_path", return_value=self.auth), \ + patch.object(password.sys.stdin, "isatty", return_value=False), \ + patch.object(password.sys, "stdout", output): + password.main() + result = json.loads(self.auth.read_text()) + self.assertEqual(result["generation"], 1) + self.assertEqual(result["password"], "old password") # unchanged, still the proxy's to migrate + self.assertIn("signed out", output.getvalue()) + for value in ("old password", result["secret"], self.original["secret"]): + self.assertNotIn(value, output.getvalue()) + + def test_strength_rule(self): + for strong in (NEW, "correct horse battery staple", "k7#Rv9!qLm2@Xz4s", "cat dog sun red"): + self.assertIsNone(password.password_problem(strong), strong) + for weak in ("short", "old password", "J8m!x2Lq0#vR9tZ", "password password password", + "a" * 20, "Password12345678!", "qwertyuiop1234567890", "password welcome admin letmein", + "dog dog dog dog dog"): + self.assertIsNotNone(password.password_problem(weak), weak) + + def test_hash_matches_rfc7914_scrypt_and_rejects_garbage(self): + stored = password.hash_password("pleaseletmein", n=16384) + self.assertTrue(password.verify_password(stored, "pleaseletmein")) + self.assertFalse(password.verify_password(stored, "pleaseletmeim")) + self.assertFalse(password.verify_password("scrypt$x", "pleaseletmein")) + self.assertFalse(password.verify_password("plain$1$1$1$a$b", "pleaseletmein")) def test_short_password_does_not_modify_auth(self): with self.assertRaises(ValueError): @@ -52,25 +104,25 @@ class PasswordTests(unittest.TestCase): link = self.home / "link.json" link.symlink_to(self.auth) with self.assertRaises(ValueError): - password.change_password(link, "new password") + password.change_password(link, NEW) 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") + password.change_password(self.auth, NEW) self.auth.chmod(0o600) self.auth.write_text("{broken") with self.assertRaises(ValueError): - password.change_password(self.auth, "new password") + password.change_password(self.auth, NEW) 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") + password.change_password(self.auth, NEW) self.assertEqual(self.auth.read_bytes(), before) self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) @@ -82,7 +134,7 @@ class PasswordTests(unittest.TestCase): 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") + password.change_password(self.auth, NEW) self.assertEqual(len(calls), 1) def test_file_changed_during_update_is_not_overwritten(self): @@ -92,10 +144,24 @@ class PasswordTests(unittest.TestCase): 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") + password.change_password(self.auth, NEW) self.assertEqual(json.loads(self.auth.read_text())["password"], "changed elsewhere") self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) + def test_cli_warns_once_about_a_weak_current_password(self): + self.auth.write_text(json.dumps(dict(self.original, password_weak=True))) + 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=[NEW, NEW]), \ + patch.object(password.sys, "stdout", io.StringIO()), \ + patch.object(password.sys, "stderr", errors): + password.main() + self.assertEqual(errors.getvalue().count("weak"), 1) + self.assertIs(json.loads(self.auth.read_text())["password_weak"], False) + 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() @@ -103,14 +169,16 @@ class PasswordTests(unittest.TestCase): 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"]), \ + "tiny9", "first strong password here", "wrong confirmation", NEW, NEW]), \ 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.assertTrue(password.verify_password(json.loads(self.auth.read_text())["password_hash"], NEW)) self.assertIn("do not match", errors.getvalue()) + self.assertIn("Too short", errors.getvalue()) self.assertIn("No service restart", output.getvalue()) - for value in ("first password", "wrong confirmation", "new password", "old password"): + self.assertIn("signed out", output.getvalue()) + for value in ("tiny9", "first strong password here", "wrong confirmation", NEW, "old password"): self.assertNotIn(value, output.getvalue() + errors.getvalue()) def test_cli_refuses_non_tty_before_prompting(self): diff --git a/scripts/test_setup_native.py b/scripts/test_setup_native.py index 8a74f682..409091cb 100644 --- a/scripts/test_setup_native.py +++ b/scripts/test_setup_native.py @@ -140,7 +140,7 @@ class SetupNativeTests(unittest.TestCase): return setup_native.Setup(directory, prefix=Path(directory) / "prefix", runner=recorder, resolver=resolution, popen=fake_ntfy_serve, environ={"XDG_CONFIG_HOME": str(Path(directory) / "config"), - "PIPELINES_WEB_PASSWORD": "chosen-password"}) + "PIPELINES_WEB_PASSWORD": "chosen tulip orbit canyon"}) @staticmethod def which_all(opencode="/usr/bin/opencode", pi=None, cc="/usr/bin/cc"): @@ -247,7 +247,10 @@ class SetupNativeTests(unittest.TestCase): installer.configure_web(prefix, setup_native.arguments([])) self.assertEqual(auth.read_bytes(), before) self.assertEqual(auth.stat().st_mode & 0o777, 0o600) - self.assertEqual(json.loads(before)["password"], "chosen-password") + stored = json.loads(before) + self.assertNotIn("password", stored) + self.assertNotIn(b"chosen tulip", before) + self.assertTrue(setup_native.web_password.verify_password(stored["password_hash"], "chosen tulip orbit canyon")) self.assertTrue(Path(web["script"]).is_file()) # The web app is built in Docker once and installed for the proxy. self.assertTrue(installer.runner.has("docker", "run", "pipelines-app-build", "web")) @@ -269,16 +272,17 @@ class SetupNativeTests(unittest.TestCase): installer.configure_web(prefix, setup_native.arguments([])) installer.environ["PIPELINES_WEB_PASSWORD"] = "short" with patch.object(setup_native.shutil, "which", side_effect=self.which_all()): - with self.assertRaisesRegex(ValueError, "at least 8"): + with self.assertRaisesRegex(ValueError, "too weak"): installer.configure_web(prefix, setup_native.arguments([])) installer.environ.pop("PIPELINES_WEB_PASSWORD") with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \ patch.object(setup_native.sys.stdin, "isatty", return_value=True), \ patch.object(setup_native.getpass, "getpass", - side_effect=["short", "typed-password", "other-password", - "typed-password", "typed-password"]): + side_effect=["short", "typed tulip orbit canyon", "other tulip orbit canyon", + "typed tulip orbit canyon", "typed tulip orbit canyon"]): web = installer.configure_web(prefix, setup_native.arguments([])) - self.assertEqual(json.loads(Path(web["auth_file"]).read_text())["password"], "typed-password") + stored = json.loads(Path(web["auth_file"]).read_text())["password_hash"] + self.assertTrue(setup_native.web_password.verify_password(stored, "typed tulip orbit canyon")) def test_fresh_install_skips_docker_migration(self): args = setup_native.arguments(["--fresh"]) diff --git a/scripts/uninstall.py b/scripts/uninstall.py index 90da20a8..4f47164b 100644 --- a/scripts/uninstall.py +++ b/scripts/uninstall.py @@ -73,9 +73,12 @@ class Uninstall: # A custom credential file must actually be a Pipelines login store. if path.exists(): data = json.loads(path.read_text()) - if not isinstance(data, dict) or not isinstance(data.get("password"), str) or not isinstance(data.get("secret"), str): + if not isinstance(data, dict) or not isinstance(data.get("password", data.get("password_hash")), str) \ + or not isinstance(data.get("secret"), str): raise ValueError("Custom web credentials are not a Pipelines password file") roots.add(path) + # The proxy's signed-out session list beside it (web/serve.mjs). + roots.add(self.safe(path.with_name(path.name + ".sessions.json"))) return {self.safe(path) for path in roots} def preflight(self): diff --git a/web/serve.mjs b/web/serve.mjs index 1f8e316d..4485f271 100644 --- a/web/serve.mjs +++ b/web/serve.mjs @@ -18,14 +18,27 @@ // // The default host is 127.0.0.1. Use --host 0.0.0.0 only on a trusted LAN/VPN. import { createServer, request } from "node:http"; -import { createHmac, timingSafeEqual, randomBytes } from "node:crypto"; -import { createReadStream, readFileSync } from "node:fs"; +import { createReadStream } from "node:fs"; import { homedir } from "node:os"; import { readFile, stat } from "node:fs/promises"; import { extname, join, normalize, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import net from "node:net"; import { sameOriginUpgrade } from "./src/proxySecurity.js"; +import { AuthStore, verifyPassword } from "./src/authStore.js"; +import { LoginLimiter, clientKey } from "./src/loginLimiter.js"; +import { PASSWORD_RULE } from "./src/passwordPolicy.js"; +import { SessionSockets } from "./src/sessionSockets.js"; +import { + HOST_SESSION_COOKIE, + SESSION_COOKIE, + applySecurityHeaders, + isHttps, + pageHeaders, + safeNext, + sameOriginRequest, + sessionCookieName, +} from "./src/webSecurity.js"; import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js"; // The proxy's own directory holds the sign-in page's icons. @@ -46,20 +59,12 @@ const UPDATES = flag(process.argv, "--updates", "") ? resolve(flag(process.argv, const AUTH_DISABLED = process.env.PIPELINES_WEB_AUTH === "disabled"; const AUTH_FILE = process.env.PIPELINES_WEB_AUTH_FILE ?? join(homedir(), ".config", "pipelines", "web-auth.json"); -const SESSION_COOKIE = "pipelines_session"; +const store = AUTH_DISABLED ? null : new AuthStore(AUTH_FILE); function loadAuth(fatal = true) { if (AUTH_DISABLED) return null; try { - const parsed = JSON.parse(readFileSync(AUTH_FILE, "utf8")); - if ( - typeof parsed.password === "string" && - parsed.password.length >= 8 && - typeof parsed.secret === "string" && - parsed.secret.length >= 32 - ) { - return { password: parsed.password, secret: parsed.secret }; - } + return store.load(); } catch { // Fall through to the refusal below. } @@ -69,7 +74,41 @@ function loadAuth(fatal = true) { } let auth = loadAuth(); -function refreshAuth() { auth = loadAuth(false); } +// Every upgraded browser socket remembers its session token, so a sign-out, +// a password change or an expiry closes it (on the event, and on a timer). +const sockets = new SessionSockets(); +function sweepSockets() { + sockets.sweep((token) => { + try { + return store.check(token) !== null; + } catch { + return false; + } + }); +} + +/** Reloads the credential; a new password or secret closes every socket. */ +function refreshAuth() { + const previous = auth; + try { + auth = loadAuth(false); + } catch (error) { + // Fail closed: an unusable credential file ends every open connection. + sockets.sweep(() => false); + throw error; + } + if (previous && auth && (previous.secret !== auth.secret || previous.generation !== auth.generation)) sweepSockets(); +} + +const SWEEP_MS = Math.max(200, Number(process.env.PIPELINES_WEB_SWEEP_MS) || 5000); +if (!AUTH_DISABLED) { + setInterval(() => { + try { + refreshAuth(); + sweepSockets(); + } catch {} + }, SWEEP_MS).unref(); +} function cookieValue(req, name) { for (const part of String(req.headers.cookie ?? "").split(";")) { @@ -86,47 +125,44 @@ function cookieValue(req, name) { return ""; } -function signSession(expires) { - const payload = `${expires}.${randomBytes(18).toString("base64url")}`; - return `${payload}.${createHmac("sha256", auth.secret).update(payload).digest("base64url")}`; +/** The request's session token (the https cookie name first). */ +function sessionValue(req) { + return cookieValue(req, HOST_SESSION_COOKIE) || cookieValue(req, SESSION_COOKIE); } const SESSION_LONG_SECONDS = 30 * 24 * 60 * 60; const SESSION_SHORT_SECONDS = 12 * 60 * 60; -function sessionToken(remember = false) { - const ttl = remember ? SESSION_LONG_SECONDS : SESSION_SHORT_SECONDS; - return signSession(Math.floor(Date.now() / 1000) + ttl); -} - -function validSession(value) { - if (!auth || typeof value !== "string") return false; - const parts = value.split("."); - if (parts.length !== 2 && parts.length !== 3) return false; - const expires = parts[0], signature = parts.at(-1); - if (!/^\d+$/.test(expires) || !signature) return false; - const expected = createHmac("sha256", auth.secret).update(parts.slice(0, -1).join(".")).digest(); - let given; +/** The request's live session, or null. */ +function session(req) { + if (!auth) return null; try { - given = Buffer.from(signature, "base64url"); + return store.check(sessionValue(req)); } catch { - return false; + return null; } - if (given.length !== expected.length || !timingSafeEqual(given, expected)) return false; - return Number(expires) > Math.floor(Date.now() / 1000); } function isAuthed(req) { - return !auth || validSession(cookieValue(req, SESSION_COOKIE)); + return !auth || session(req) !== null; } -const peerRelay = new PeerRelay((req) => AUTH_DISABLED ? "test-auth-disabled" : cookieValue(req, SESSION_COOKIE)); +const peerRelay = new PeerRelay((req) => AUTH_DISABLED ? "test-auth-disabled" : sessionValue(req)); -function passwordOk(candidate) { +// Password checks are scrypt (32 MiB each); a few run at once and the rest +// are answered 429 rather than queued without bound. +const VERIFY_LIMIT = 4; +let verifying = 0; +async function passwordOk(candidate) { if (!auth) return true; - const given = Buffer.from(String(candidate ?? "")); - const expected = Buffer.from(auth.password); - return given.length === expected.length && timingSafeEqual(given, expected); + const value = String(candidate ?? ""); + if (value.length > 4096) return false; + verifying++; + try { + return await verifyPassword(auth.hash, value); + } finally { + verifying--; + } } function sessionCookie(req, remember = false) { @@ -134,40 +170,65 @@ function sessionCookie(req, remember = false) { // a top-level navigation, and a Strict cookie is withheld on that first // request, which made a remembered session look forgotten. Lax still keeps // the cookie off cross-site subresource and POST requests. - const bits = [`${SESSION_COOKIE}=${sessionToken(remember)}`, "Path=/", "HttpOnly", "SameSite=Lax"]; + const { token } = store.issue(remember ? SESSION_LONG_SECONDS : SESSION_SHORT_SECONDS); + const bits = [`${sessionCookieName(req)}=${token}`, "Path=/", "HttpOnly", "SameSite=Lax"]; // Remember me persists the cookie; otherwise it is a browser-session cookie // (and the signed token itself expires after 12 hours). if (remember) { const expires = new Date(Date.now() + SESSION_LONG_SECONDS * 1000).toUTCString(); bits.push(`Max-Age=${SESSION_LONG_SECONDS}`, `Expires=${expires}`); } - // Tailscale terminates TLS and usually forwards the scheme; when it does, the - // cookie is Secure. A direct plain-http LAN visit still works without it. - const forwarded = String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim(); - if (forwarded === "https") bits.push("Secure"); + // Tailscale terminates TLS and forwards the scheme; then the cookie is + // Secure and host-locked (__Host-). A plain-http LAN visit keeps the plain name. + if (isHttps(req)) bits.push("Secure"); return bits.join("; "); } -/** Small per-address brake on password guessing. */ -const loginFailures = new Map(); -function loginBlocked(address) { - const entry = loginFailures.get(address); - return Boolean(entry && entry.until > Date.now()); -} -function noteLoginFailure(address) { - const now = Date.now(); - const entry = loginFailures.get(address) ?? { count: 0, until: 0 }; - entry.count += 1; - if (entry.count >= 8) { - entry.count = 0; - entry.until = now + 30_000; - } - loginFailures.set(address, entry); +/** Set-Cookie values that clear both session cookie names. */ +function clearedCookies(req) { + const cleared = [`${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`]; + if (isHttps(req)) cleared.push(`${HOST_SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Secure; Max-Age=0`); + return cleared; } -function safeNext(value) { - const next = String(value ?? ""); - return next.startsWith("/") && !next.startsWith("//") ? next : "/"; +/** Ends one session: server-side revocation, its relayed peers and sockets. */ +function signOut(req) { + const token = sessionValue(req); + peerRelay.forget(req); + try { + store.revoke(token); + } catch {} + sweepSockets(); +} + +const limiter = new LoginLimiter(); + +function logoutPage() { + return ` + + + + + +Pipelines ยท sign out + + + +
+

Sign out

+

Sign this browser out of Pipelines.

+
+
+ +`; } function loginPage({ next = "/", error = "" } = {}) { @@ -212,7 +273,7 @@ function loginPage({ next = "/", error = "" } = {}) {

Pipelines

Sign in to reach this server.

- + @@ -394,6 +455,7 @@ function proxyArtifact(req, res) { } const server = createServer(async (req, res) => { + applySecurityHeaders(req, res); try { refreshAuth(); } catch { res.writeHead(503, { "Content-Type": "text/plain", "Cache-Control": "no-store" }).end("Web authentication unavailable"); return; @@ -412,6 +474,10 @@ const server = createServer(async (req, res) => { return; } } + if (!auth && (pathname === "/api/session" || pathname === "/api/sessions/revoke-all")) { + res.writeHead(404, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"error":"sign-in is disabled"}'); + return; + } if (auth) { if (pathname === "/login" && req.method === "GET") { if (isAuthed(req)) { @@ -419,36 +485,54 @@ const server = createServer(async (req, res) => { return; } const next = new URL(req.url ?? "/login", "http://localhost").searchParams.get("next") ?? "/"; - res - .writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }) - .end(loginPage({ next: safeNext(next) })); + res.writeHead(200, pageHeaders()).end(loginPage({ next: safeNext(next) })); return; } else if (pathname === "/login" && req.method === "POST") { - const body = await readRequestBody(req).catch(() => ""); - const fields = new URLSearchParams(body); - const address = req.socket.remoteAddress ?? ""; - if (loginBlocked(address)) { - res - .writeHead(429, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }) - .end(loginPage({ error: "Too many attempts. Wait 30 seconds." })); + // Login CSRF: a cross-site form must not sign the browser in to this server. + if (!sameOriginRequest(req)) { + req.resume(); + res.writeHead(403, pageHeaders()).end(loginPage({ error: "Sign-in refused: the form came from another site." })); return; } - if (!passwordOk(fields.get("password"))) { - noteLoginFailure(address); + const body = await readRequestBody(req).catch(() => ""); + const fields = new URLSearchParams(body); + const key = clientKey(req); + const wait = limiter.blocked(key); + if (wait > 0 || verifying >= VERIFY_LIMIT) { + const seconds = Math.max(1, Math.ceil(wait / 1000)); res - .writeHead(401, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }) + .writeHead(429, pageHeaders({ "Retry-After": String(seconds) })) + .end(loginPage({ next: safeNext(fields.get("next")), error: `Too many attempts. Wait ${seconds} seconds.` })); + return; + } + if (!(await passwordOk(fields.get("password")))) { + limiter.fail(key); + res + .writeHead(401, pageHeaders()) .end(loginPage({ next: safeNext(fields.get("next")), error: "Wrong password." })); return; } + limiter.succeed(key); const remember = fields.get("remember") === "on"; res.setHeader("Set-Cookie", sessionCookie(req, remember)); res.writeHead(303, { Location: safeNext(fields.get("next")) }).end(); return; - } else if (pathname === "/logout") { - peerRelay.forget(req); - res.setHeader("Set-Cookie", `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`); + } else if (pathname === "/logout" && req.method === "POST") { + // Signing out is state-changing: POST from this origin only. + if (!sameOriginRequest(req)) { + req.resume(); + res.writeHead(403, pageHeaders()).end(logoutPage()); + return; + } + req.resume(); + signOut(req); + res.setHeader("Set-Cookie", clearedCookies(req)); res.writeHead(303, { Location: "/login" }).end(); return; + } else if (pathname === "/logout") { + // A link (or a cross-site page) only reaches a confirmation button. + res.writeHead(200, pageHeaders()).end(logoutPage()); + return; } else if (!isAuthed(req)) { const wantsHtml = String(req.headers.accept ?? "").includes("text/html"); if (req.method === "GET" && wantsHtml && !pathname.startsWith("/api/") && !pathname.startsWith("/peers/")) { @@ -459,6 +543,28 @@ const server = createServer(async (req, res) => { .writeHead(401, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" }) .end("Sign in required\n"); return; + } else if (pathname === "/api/session" && req.method === "GET") { + const current = session(req); + res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end( + JSON.stringify({ + weak_password: auth.weak === true, + password_rule: PASSWORD_RULE, + expires_at: new Date(current.expires * 1000).toISOString(), + }), + ); + return; + } else if (pathname === "/api/sessions/revoke-all" && req.method === "POST") { + req.resume(); + if (!sameOriginRequest(req)) { + res.writeHead(403, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"error":"cross-site request refused"}'); + return; + } + peerRelay.forget(req); + store.revokeAll(); + sweepSockets(); + res.setHeader("Set-Cookie", clearedCookies(req)); + res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"revoked":true}'); + return; } } if (pathname === "/api/discovery" && req.method === "GET") { @@ -576,6 +682,8 @@ server.on("upgrade", (req, clientSocket, clientHead) => { clientSocket.destroy(); return; } + // Closed again when this session is signed out, revoked or expires. + if (auth) sockets.track(clientSocket, sessionValue(req)); if (peerRelay.upgrade(req, clientSocket, clientHead)) return; if (pathname !== "/connect") { clientSocket.destroy(); diff --git a/web/src/authStore.js b/web/src/authStore.js new file mode 100644 index 00000000..5f26bf35 --- /dev/null +++ b/web/src/authStore.js @@ -0,0 +1,233 @@ +// The web sign-in credential and its sessions. +// +// web-auth.json (0600, outside the repository) holds: +// password_hash "scrypt$N$r$p$$" (unpadded base64url); the same +// hash scripts/password.py writes and the Go server verifies +// for step-up re-authentication +// password_weak true when the stored password predates the strength rule +// secret the cookie HMAC key +// generation bumped (with a new secret) by every password change and by +// `./password --revoke-all` +// A file still holding a plaintext "password" is migrated to a hash the first +// time it is loaded; the password itself does not change. +// +// Sessions are signed tokens "v2.....". +// .sessions.json (0600, written only by this proxy) records signed +// out token ids until they expire and a "not_before" time for "sign out +// everywhere" from Settings. +import { createHmac, randomBytes, scrypt, scryptSync, timingSafeEqual } from "node:crypto"; +import { closeSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; +import { passwordProblem } from "./passwordPolicy.js"; + +export const SCRYPT = { N: 1 << 15, r: 8, p: 1, keyLength: 32 }; +const MAXMEM = 64 * 1024 * 1024; +/** Signed-out token ids kept until they expire; the soonest to expire go first. */ +export const REVOKED_LIMIT = 10000; + +const b64 = (buffer) => Buffer.from(buffer).toString("base64url"); + +export function hashPassword(password, { N, r, p, keyLength } = SCRYPT) { + const salt = randomBytes(16); + const key = scryptSync(String(password), salt, keyLength, { N, r, p, maxmem: MAXMEM }); + return `scrypt$${N}$${r}$${p}$${b64(salt)}$${b64(key)}`; +} + +export function parseHash(value) { + const parts = String(value ?? "").split("$"); + if (parts.length !== 6 || parts[0] !== "scrypt") return null; + const [N, r, p] = parts.slice(1, 4).map((part) => (/^\d{1,7}$/.test(part) ? Number(part) : 0)); + const salt = Buffer.from(parts[4], "base64url"); + const key = Buffer.from(parts[5], "base64url"); + if (N < 2 || N > 1 << 20 || (N & (N - 1)) !== 0 || r < 1 || r > 32 || p < 1 || p > 16) return null; + if (salt.length < 8 || key.length < 16 || key.length > 64) return null; + return { N, r, p, salt, key }; +} + +/** Constant-time check of candidate against a stored hash. */ +export function verifyPassword(stored, candidate) { + const parsed = parseHash(stored); + if (!parsed) return Promise.resolve(false); + const { N, r, p, salt, key } = parsed; + return new Promise((done) => { + scrypt(String(candidate ?? ""), salt, key.length, { N, r, p, maxmem: MAXMEM }, (error, derived) => { + done(!error && derived.length === key.length && timingSafeEqual(derived, key)); + }); + }); +} + +/** Writes data to path through a private temporary file and a rename. */ +function writePrivateAtomic(path, text, unchanged) { + const temporary = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}`); + const fd = openSync(temporary, "wx", 0o600); + try { + writeSync(fd, text); + fsyncSync(fd); + } finally { + closeSync(fd); + } + try { + if (unchanged && !unchanged()) throw new Error("file changed during the update"); + renameSync(temporary, path); + } catch (error) { + try { + unlinkSync(temporary); + } catch {} + throw error; + } +} + +const signature = (info) => `${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`; + +export class AuthStore { + constructor(file, { now = Date.now, log = (line) => console.error(line) } = {}) { + this.file = file; + this.sessionsFile = `${file}.sessions.json`; + this.now = now; + this.log = log; + this.state = null; + this.stamp = ""; + this.notBefore = 0; + this.revoked = new Map(); // id -> expires (seconds) + this.revokedGeneration = null; + this.loadSessions(); + } + + /** The current credential; throws when the file is missing or invalid. */ + load() { + const info = lstatSync(this.file); + if (!info.isFile()) throw new Error("web auth file is not a regular file"); + if (this.state && signature(info) === this.stamp) return this.state; + const parsed = JSON.parse(readFileSync(this.file, "utf8")); + if (!parsed || typeof parsed !== "object" || typeof parsed.secret !== "string" || parsed.secret.length < 32) + throw new Error("web auth file has no valid secret"); + let hash = parsed.password_hash; + let weak = parsed.password_weak === true; + if (typeof hash !== "string" && typeof parsed.password === "string" && parsed.password.length >= 8) { + ({ hash, weak } = this.migrate(parsed, info)); + } + if (!parseHash(hash)) throw new Error("web auth file has no valid password hash"); + const generation = Number.isSafeInteger(parsed.generation) && parsed.generation >= 0 ? parsed.generation : 0; + this.state = { hash, weak, secret: parsed.secret, generation }; + // Re-stat: a successful migration replaced the file. + try { + this.stamp = signature(lstatSync(this.file)); + } catch { + this.stamp = ""; + } + if (this.revokedGeneration !== generation) { + // A new generation already invalidates every older token. + this.revoked.clear(); + this.notBefore = 0; + this.revokedGeneration = generation; + } + return this.state; + } + + /** Replaces a plaintext password by its hash, keeping the password itself. */ + migrate(parsed, info) { + const hash = hashPassword(parsed.password); + const weak = passwordProblem(parsed.password) !== null; + const next = { ...parsed, password_hash: hash, password_weak: weak }; + delete next.password; + if (this.state) { + // A plaintext password written over a running proxy's file is a password + // change: like ./password, it signs every session out. + const generation = Number.isSafeInteger(parsed.generation) && parsed.generation >= 0 ? parsed.generation : 0; + next.generation = generation + 1; + next.secret = randomBytes(48).toString("base64url"); + parsed.generation = next.generation; + parsed.secret = next.secret; + } + try { + writePrivateAtomic(this.file, `${JSON.stringify(next, null, 2)}\n`, () => { + const current = lstatSync(this.file); + return signature(current) === signature(info); + }); + this.log(`web auth: stored the sign-in password as a scrypt hash${weak ? "; it is weak, choose a stronger one with ./password" : ""}`); + } catch (error) { + // Signing in keeps working from the in-memory hash until the file changes. + this.log(`web auth: could not migrate the password file to a hash (${error.message})`); + } + return { hash, weak }; + } + + loadSessions() { + try { + const parsed = JSON.parse(readFileSync(this.sessionsFile, "utf8")); + this.revokedGeneration = Number.isSafeInteger(parsed.generation) ? parsed.generation : null; + this.notBefore = Number.isFinite(parsed.not_before) ? parsed.not_before : 0; + for (const [id, expires] of Object.entries(parsed.revoked ?? {})) + if (/^[A-Za-z0-9_-]{8,64}$/.test(id) && Number.isFinite(expires)) this.revoked.set(id, expires); + } catch { + // No list yet (or unreadable): nothing has been signed out. + } + } + + saveSessions() { + const nowSeconds = Math.floor(this.now() / 1000); + for (const [id, expires] of this.revoked) if (expires <= nowSeconds) this.revoked.delete(id); + if (this.revoked.size > REVOKED_LIMIT) { + const sorted = [...this.revoked].sort((a, b) => a[1] - b[1]); + this.revoked = new Map(sorted.slice(sorted.length - REVOKED_LIMIT)); + } + const body = { + generation: this.revokedGeneration, + not_before: this.notBefore, + revoked: Object.fromEntries(this.revoked), + }; + try { + writePrivateAtomic(this.sessionsFile, `${JSON.stringify(body)}\n`); + } catch (error) { + // The revocation still holds in memory until the proxy restarts. + this.log(`web auth: could not record signed-out sessions (${error.message})`); + } + } + + mac(payload) { + return createHmac("sha256", this.load().secret).update(payload).digest(); + } + + /** A new signed session token valid for ttlSeconds. */ + issue(ttlSeconds) { + const { generation } = this.load(); + const now = this.now(); + const expires = Math.floor(now / 1000) + ttlSeconds; + const payload = `v2.${generation}.${now}.${expires}.${randomBytes(18).toString("base64url")}`; + return { token: `${payload}.${b64(this.mac(payload))}`, expires }; + } + + /** The session a token names, or null when it is forged, old or revoked. */ + check(token) { + if (typeof token !== "string" || token.length > 256) return null; + const parts = token.split("."); + if (parts.length !== 6 || parts[0] !== "v2") return null; + const [, generation, issued, expires, id, mac] = parts; + if (![generation, issued, expires].every((part) => /^\d{1,16}$/.test(part))) return null; + const state = this.load(); + const expected = this.mac(parts.slice(0, 5).join(".")); + const given = Buffer.from(mac, "base64url"); + if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null; + if (Number(generation) !== state.generation) return null; + if (Number(expires) <= Math.floor(this.now() / 1000)) return null; + if (Number(issued) <= this.notBefore || this.revoked.has(id)) return null; + return { id, expires: Number(expires), issued: Number(issued) }; + } + + /** Signs one token out (server-side logout). */ + revoke(token) { + const session = this.check(token); + if (!session) return false; + this.revoked.set(session.id, session.expires); + this.saveSessions(); + return true; + } + + /** Signs every token issued so far out ("Sign out everywhere"). */ + revokeAll() { + this.load(); + this.notBefore = Math.max(this.now(), this.notBefore + 1); + this.revoked.clear(); + this.saveSessions(); + } +} diff --git a/web/src/loginLimiter.js b/web/src/loginLimiter.js new file mode 100644 index 00000000..1d7b6e6e --- /dev/null +++ b/web/src/loginLimiter.js @@ -0,0 +1,79 @@ +// A brake on password guessing: per client exponential backoff after a few +// free failures, plus a server-wide sliding window so many clients (or one +// client behind many addresses) cannot keep guessing. The per-client map is +// bounded; the least recently failed client is evicted first. + +export class LoginLimiter { + constructor({ + now = Date.now, + freeFailures = 5, + baseMs = 1000, + maxMs = 15 * 60 * 1000, + idleMs = 60 * 60 * 1000, + maxKeys = 1024, + globalLimit = 50, + globalWindowMs = 5 * 60 * 1000, + } = {}) { + Object.assign(this, { now, freeFailures, baseMs, maxMs, idleMs, maxKeys, globalLimit, globalWindowMs }); + this.clients = new Map(); // key -> { count, until, last }; insertion order = recency + this.recent = []; // failure times, oldest first, at most globalLimit + } + + prune(now) { + while (this.recent.length && this.recent[0] <= now - this.globalWindowMs) this.recent.shift(); + } + + /** Milliseconds key must wait before its next attempt (0: go ahead). */ + blocked(key) { + const now = this.now(); + this.prune(now); + let wait = 0; + if (this.recent.length >= this.globalLimit) wait = this.recent[0] + this.globalWindowMs - now; + const entry = this.clients.get(key); + if (entry && now - entry.last > this.idleMs) this.clients.delete(key); + else if (entry && entry.until > now) wait = Math.max(wait, entry.until - now); + return Math.max(0, wait); + } + + fail(key) { + const now = this.now(); + this.prune(now); + this.recent.push(now); + if (this.recent.length > this.globalLimit) this.recent.shift(); + const entry = this.clients.get(key) ?? { count: 0, until: 0, last: now }; + this.clients.delete(key); + entry.count += 1; + entry.last = now; + if (entry.count >= this.freeFailures) { + const doublings = Math.min(entry.count - this.freeFailures, 20); + entry.until = now + Math.min(this.baseMs * 2 ** doublings, this.maxMs); + } + this.clients.set(key, entry); + while (this.clients.size > this.maxKeys) this.clients.delete(this.clients.keys().next().value); + } + + succeed(key) { + this.clients.delete(key); + } +} + +const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]); + +/** + * The client a login attempt is charged to. Behind `tailscale serve` every + * request arrives from loopback, so there (and only there: a loopback peer + * that carries Tailscale's identity headers) the tailnet user, else the + * forwarded address, names the client. Any other request is its socket + * address. A local process could forge these headers, but it already runs on + * the machine; the global window still bounds it. + */ +export function clientKey(req) { + const address = req.socket?.remoteAddress ?? ""; + if (LOOPBACK.has(address) && Object.keys(req.headers).some((name) => name.startsWith("tailscale-"))) { + const login = String(req.headers["tailscale-user-login"] ?? "").trim().toLowerCase(); + if (login) return `tailscale:${login.slice(0, 256)}`; + const forwarded = String(req.headers["x-forwarded-for"] ?? "").split(",")[0].trim(); + if (forwarded) return `forwarded:${forwarded.slice(0, 64)}`; + } + return `address:${address}`; +} diff --git a/web/src/passwordPolicy.js b/web/src/passwordPolicy.js new file mode 100644 index 00000000..5b79f37d --- /dev/null +++ b/web/src/passwordPolicy.js @@ -0,0 +1,76 @@ +// The strength rule for a new web password, kept in step with +// scripts/password.py (which enforces it). The proxy only uses it to mark a +// migrated plaintext password as weak, so Settings can warn about it once. + +export const PASSWORD_RULE = + "Use at least 16 characters, or a passphrase of 4 or more random words " + + "separated by spaces or dashes (15 characters or more in all). Common words, " + + "keyboard runs and repeated characters do not count towards the length."; + +const COMMON = [ + "password", "passwort", "pipelines", "pipeline", "qwerty", "azerty", "letmein", + "welcome", "admin", "administrator", "iloveyou", "monkey", "dragon", "master", + "secret", "login", "changeme", "default", "football", "baseball", "sunshine", + "princess", "shadow", "trustno", "superman", "hello", "test", "guest", "root", +].sort((a, b) => b.length - a.length); +const ROWS = ["qwertyuiop", "asdfghjkl", "zxcvbnm", "1234567890"]; +const SEPARATORS = /[\s\-_.,;:+/]+/g; + +/** Removes runs of 3+ repeated characters and 4+ consecutive characters. */ +function withoutRuns(text) { + const chars = [...text]; + const out = []; + let i = 0; + while (i < chars.length) { + let j = i + 1; + while (j < chars.length && chars[j] === chars[i]) j++; + if (j - i >= 3) { + i = j; + continue; + } + let run = 0; + for (const step of [1, -1]) { + j = i + 1; + while (j < chars.length && chars[j].codePointAt(0) - chars[j - 1].codePointAt(0) === step) j++; + if (j - i >= 4) { + run = j; + break; + } + } + if (run) { + i = run; + continue; + } + out.push(chars[i]); + i++; + } + return out.join(""); +} + +function substance(password) { + let text = password.toLowerCase(); + for (const word of COMMON) text = text.split(word).join(""); + for (const row of ROWS) + for (let size = row.length; size > 3; size--) + for (let start = 0; start + size <= row.length; start++) + text = text.split(row.slice(start, start + size)).join(""); + return withoutRuns(text).replace(SEPARATORS, ""); +} + +/** Why a new password is too weak, or null. Lengths count code points. */ +export function passwordProblem(password) { + const value = String(password ?? ""); + const length = [...value].length; + if (length > 1024) return "Choose a password of at most 1024 characters."; + const words = value.split(SEPARATORS).filter(Boolean).map((word) => word.toLowerCase()); + const passphrase = + words.length >= 4 && + new Set(words).size >= 4 && + words.every((word) => [...word].length >= 3) && + length >= 15 && + [...substance(value)].length >= 12; + if (passphrase) return null; + if (length < 16) return `Too short. ${PASSWORD_RULE}`; + if (new Set(value).size < 8 || [...substance(value)].length < 12) return `Too predictable. ${PASSWORD_RULE}`; + return null; +} diff --git a/web/src/peerRelay.js b/web/src/peerRelay.js index 18525a84..2c00b175 100644 --- a/web/src/peerRelay.js +++ b/web/src/peerRelay.js @@ -61,6 +61,8 @@ export class PeerRelay extends PeerRegistry { "x-upload-name", "x-chat-file-name", "x-pipelines-upload-name", + // The remote machine's own step-up token (POST /files). + "x-pipelines-elevation", ]) if (req.headers[name]) headers[name] = req.headers[name]; const upstream = remoteRequest(target.url, { diff --git a/web/src/peerTransport.js b/web/src/peerTransport.js index ffcbc2f7..781ff7a2 100644 --- a/web/src/peerTransport.js +++ b/web/src/peerTransport.js @@ -75,7 +75,7 @@ export function boundedRequest( export function sessionCookie(response) { return (response.headers["set-cookie"] ?? []) .map((value) => value.split(";")[0]) - .filter((value) => value.startsWith("pipelines_session=")) + .filter((value) => value.startsWith("pipelines_session=") || value.startsWith("__Host-pipelines_session=")) .join("; "); } diff --git a/web/src/sessionSockets.js b/web/src/sessionSockets.js new file mode 100644 index 00000000..aca6d25b --- /dev/null +++ b/web/src/sessionSockets.js @@ -0,0 +1,30 @@ +// The upgraded browser sockets (the /connect websocket and relayed peer +// sockets), each with the session token it was opened with. A sweep destroys +// every socket whose session is no longer valid: signed out, signed out +// everywhere, expired, or issued before a password change. +export class SessionSockets { + constructor() { + this.sockets = new Map(); // socket -> token + } + + track(socket, token) { + this.sockets.set(socket, token); + socket.once("close", () => this.sockets.delete(socket)); + } + + get size() { + return this.sockets.size; + } + + /** Destroys the sockets whose token valid() rejects; returns how many. */ + sweep(valid) { + let closed = 0; + for (const [socket, token] of this.sockets) { + if (valid(token)) continue; + this.sockets.delete(socket); + socket.destroy(); + closed++; + } + return closed; + } +} diff --git a/web/src/webSecurity.js b/web/src/webSecurity.js new file mode 100644 index 00000000..5f3d1b4d --- /dev/null +++ b/web/src/webSecurity.js @@ -0,0 +1,72 @@ +// Browser-facing hygiene for the proxy: request origin checks, the post-login +// redirect target, the session cookie's name and the security headers. +import { sameOriginUpgrade } from "./proxySecurity.js"; + +export const SESSION_COOKIE = "pipelines_session"; +/** Over https the cookie is host-locked (Secure, Path=/, no Domain). */ +export const HOST_SESSION_COOKIE = "__Host-pipelines_session"; + +/** Whether the browser reached the proxy over https (Tailscale serve). */ +export function isHttps(req) { + const forwarded = String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim().toLowerCase(); + return forwarded === "https" || Boolean(req.socket?.encrypted); +} + +export function sessionCookieName(req) { + return isHttps(req) ? HOST_SESSION_COOKIE : SESSION_COOKIE; +} + +/** + * Whether a state-changing request comes from this origin. Browsers send + * Origin on every POST; a native client (the app, curl, a peer proxy) sends + * none and has no ambient cookies to abuse. `Origin: null` and a cross-site + * Sec-Fetch-Site are refused. + */ +export function sameOriginRequest(req) { + const origin = req.headers.origin; + const site = req.headers["sec-fetch-site"]; + if (site && !["same-origin", "none"].includes(String(site))) return false; + if (origin === undefined) return true; + return sameOriginUpgrade(origin, req.headers.host); +} + +/** + * The local path to return to after signing in: one "/" followed by anything + * but "/" or "\" (which browsers treat as another host), no backslashes or + * control characters anywhere, else "/". + */ +export function safeNext(value) { + const next = String(value ?? ""); + if (next.length > 2048 || !/^\/(?![/\\])/.test(next) || /[\\\u0000-\u001f\u007f]/.test(next)) return "/"; + return next; +} + +/** The proxy's own pages (sign-in, sign-out) are never framed and run no script. */ +export const PAGE_POLICY = + "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; form-action 'self'; " + + "frame-ancestors 'none'; base-uri 'none'"; + +/** + * Headers every response starts with. The app frames only its own documents + * (sandboxed srcdoc HTML previews), so same-origin framing stays allowed; a + * response that sets its own value (for example a sandboxing CSP) overrides + * these at writeHead. HSTS only on https. + */ +export function applySecurityHeaders(req, res) { + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Referrer-Policy", "same-origin"); + res.setHeader("X-Frame-Options", "SAMEORIGIN"); + res.setHeader("Content-Security-Policy", "frame-ancestors 'self'"); + if (isHttps(req)) res.setHeader("Strict-Transport-Security", "max-age=31536000"); +} + +/** Marks a response as one of the proxy's own pages. */ +export function pageHeaders(extra = {}) { + return { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "no-store", + "Content-Security-Policy": PAGE_POLICY, + "X-Frame-Options": "DENY", + ...extra, + }; +} diff --git a/web/test/authProxy.test.mjs b/web/test/authProxy.test.mjs new file mode 100644 index 00000000..88c53ee1 --- /dev/null +++ b/web/test/authProxy.test.mjs @@ -0,0 +1,183 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import net from "node:net"; +import { once } from "node:events"; +import { hashPassword } from "../src/authStore.js"; + +const here = fileURLToPath(new URL("..", import.meta.url)); +const PASSWORD = "tulip orbit canyon ember"; + +async function freePort() { + const server = net.createServer().listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address(); + await new Promise((done) => server.close(done)); + return port; +} + +/** A stand-in Pipelines server that accepts every websocket upgrade and holds it. */ +async function fakeUpstream(t) { + const held = new Set(); + const server = net.createServer((socket) => { + held.add(socket); + socket.once("data", () => socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")); + socket.on("error", () => {}); + socket.on("close", () => held.delete(socket)); + }).listen(0, "127.0.0.1"); + await once(server, "listening"); + t.after(() => { for (const socket of held) socket.destroy(); return new Promise((done) => server.close(done)); }); + return server.address().port; +} + +async function startProxy(t, authData) { + const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-proxy-")); + t.after(() => rm(dir, { recursive: true, force: true })); + const auth = join(dir, "web-auth.json"); + await writeFile(auth, JSON.stringify(authData), { mode: 0o600 }); + const upstream = await fakeUpstream(t); + const port = await freePort(); + const child = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--root", join(dir, "absent"), + "--pipelines", `127.0.0.1:${upstream}`], { + cwd: here, + env: { ...process.env, PIPELINES_WEB_AUTH: "", PIPELINES_WEB_AUTH_FILE: auth, PIPELINES_WEB_SWEEP_MS: "200" }, + stdio: ["ignore", "pipe", "pipe"], + }); + t.after(async () => { const exited = once(child, "exit"); child.kill(); await exited; }); + await once(child.stdout, "data"); + const base = `http://127.0.0.1:${port}`; + return { auth, port, base, host: `127.0.0.1:${port}` }; +} + +const login = (proxy, headers = {}, password = PASSWORD) => + fetch(proxy.base + "/login", { method: "POST", body: new URLSearchParams({ password, next: "/runs/1" }), redirect: "manual", headers }); +const cookieOf = (response) => response.headers.get("set-cookie").split(";")[0]; +const signedIn = async (proxy, cookie) => + (await fetch(proxy.base + "/login", { headers: { Cookie: cookie }, redirect: "manual" })).status === 302; + +/** Opens /connect through the proxy and resolves when the 101 arrives. */ +async function openSocket(proxy, cookie) { + const socket = net.connect(proxy.port, "127.0.0.1"); + await once(socket, "connect"); + socket.write(`GET /connect HTTP/1.1\r\nHost: ${proxy.host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` + + `Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\nCookie: ${cookie}\r\n\r\n`); + const [chunk] = await once(socket, "data"); + assert.match(chunk.toString(), /^HTTP\/1.1 101/); + const closed = once(socket, "close"); + socket.on("error", () => {}); + return { socket, closed }; +} + +const within = (promise, ms, what) => + Promise.race([promise, new Promise((_, fail) => setTimeout(() => fail(new Error(`${what} not within ${ms} ms`)), ms))]); + +test("login: Origin check, safe next, headers and the cookie prefix", async (t) => { + const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 0 }); + const cross = await login(proxy, { Origin: "https://evil.example" }); + assert.equal(cross.status, 403); + assert.equal(cross.headers.get("set-cookie"), null); + const page = await fetch(proxy.base + "/login?next=/%5Cevil.com"); + const html = await page.text(); + assert.match(html, /name="next" value="\/"/); + assert.match(page.headers.get("content-security-policy"), /frame-ancestors 'none'/); + assert.match(page.headers.get("content-security-policy"), /default-src 'none'/); + assert.equal(page.headers.get("x-frame-options"), "DENY"); + assert.equal(page.headers.get("x-content-type-options"), "nosniff"); + assert.equal(page.headers.get("referrer-policy"), "same-origin"); + assert.equal(page.headers.get("strict-transport-security"), null); + const ok = await login(proxy, { Origin: proxy.base }); + assert.equal(ok.status, 303); + assert.equal(ok.headers.get("location"), "/runs/1"); + assert.match(ok.headers.get("set-cookie"), /^pipelines_session=v2\./); + assert.doesNotMatch(ok.headers.get("set-cookie"), /Secure/); + // An app response may be framed by the app itself only. + const app = await fetch(proxy.base + "/runs/1", { headers: { Cookie: cookieOf(ok) } }); + assert.equal(app.headers.get("x-frame-options"), "SAMEORIGIN"); + assert.match(app.headers.get("content-security-policy"), /frame-ancestors 'self'/); + // Over https (Tailscale serve): __Host- prefix, Secure, HSTS. + const https = await login(proxy, { "X-Forwarded-Proto": "https" }); + const secure = https.headers.get("set-cookie"); + assert.match(secure, /^__Host-pipelines_session=v2\./); + assert.match(secure, /; Path=\/;/); + assert.match(secure, /; Secure/); + assert.doesNotMatch(secure, /Domain=/i); + assert.match(https.headers.get("strict-transport-security"), /max-age=\d+/); + assert.equal(await signedIn(proxy, cookieOf(https)), true); + // A native client (no Origin) still signs in. + assert.equal((await login(proxy)).status, 303); +}); + +test("logout is a same-origin POST that revokes the token and closes its sockets", async (t) => { + const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40) }); + const a = cookieOf(await login(proxy)); + const b = cookieOf(await login(proxy)); + const ws = await openSocket(proxy, a); + const other = await openSocket(proxy, b); + // GET only shows a button; a cross-site POST is refused. + const page = await fetch(proxy.base + "/logout", { headers: { Cookie: a }, redirect: "manual" }); + assert.equal(page.status, 200); + assert.match(await page.text(), /method="post" action="\/logout"/); + assert.equal((await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: a, Origin: "https://evil.example" }, redirect: "manual" })).status, 403); + assert.equal(await signedIn(proxy, a), true); + const out = await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: a, Origin: proxy.base }, redirect: "manual" }); + assert.equal(out.status, 303); + assert.match(out.headers.get("set-cookie"), /pipelines_session=; .*Max-Age=0/); + // The copied cookie no longer works anywhere, and its socket is gone. + assert.equal(await signedIn(proxy, a), false); + await within(ws.closed, 2000, "the signed-out socket closing"); + assert.equal(await signedIn(proxy, b), true); + assert.equal(other.socket.destroyed, false); + other.socket.destroy(); +}); + +test("a password change revokes every session and closes open websockets", async (t) => { + const data = { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 4 }; + const proxy = await startProxy(t, data); + const cookie = cookieOf(await login(proxy)); + const ws = await openSocket(proxy, cookie); + // What ./password writes: a new hash, secret and generation, atomically. + const next = { ...data, password_hash: hashPassword("ember canyon orbit tulip"), secret: "n".repeat(40), generation: 5 }; + await writeFile(proxy.auth + ".next", JSON.stringify(next), { mode: 0o600 }); + await rename(proxy.auth + ".next", proxy.auth); + await within(ws.closed, 3000, "the websocket closing after the password change"); + assert.equal(await signedIn(proxy, cookie), false); + assert.equal((await login(proxy)).status, 401); + assert.equal((await login(proxy, {}, "ember canyon orbit tulip")).status, 303); +}); + +test("sign out everywhere from Settings, the session report and the weak-password warning", async (t) => { + const proxy = await startProxy(t, { password: "old-password", secret: "s".repeat(40) }); + // The migration kept the old password working and stored only a hash. + const first = await login(proxy, {}, "old-password"); + assert.equal(first.status, 303); + const stored = JSON.parse(await readFile(proxy.auth, "utf8")); + assert.equal(stored.password, undefined); + assert.match(stored.password_hash, /^scrypt\$/); + const a = cookieOf(first); + const b = cookieOf(await login(proxy, {}, "old-password")); + assert.equal((await fetch(proxy.base + "/api/session")).status, 401); + const report = await (await fetch(proxy.base + "/api/session", { headers: { Cookie: a } })).json(); + assert.equal(report.weak_password, true); + assert.match(report.password_rule, /16 characters/); + const ws = await openSocket(proxy, b); + assert.equal((await fetch(proxy.base + "/api/sessions/revoke-all", { method: "POST", headers: { Cookie: a, Origin: "https://evil.example" } })).status, 403); + const revoke = await fetch(proxy.base + "/api/sessions/revoke-all", { method: "POST", headers: { Cookie: a, Origin: proxy.base } }); + assert.equal(revoke.status, 200); + assert.deepEqual(await revoke.json(), { revoked: true }); + await within(ws.closed, 2000, "every socket closing"); + assert.equal(await signedIn(proxy, a), false); + assert.equal(await signedIn(proxy, b), false); + assert.equal(await signedIn(proxy, cookieOf(await login(proxy, {}, "old-password"))), true); +}); + +test("repeated wrong passwords are slowed down", async (t) => { + const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40) }); + for (let i = 0; i < 5; i++) assert.equal((await login(proxy, {}, "wrong")).status, 401); + const blocked = await login(proxy, {}, PASSWORD); + assert.equal(blocked.status, 429); + assert.ok(Number(blocked.headers.get("retry-after")) >= 1); +}); diff --git a/web/test/authReload.test.mjs b/web/test/authReload.test.mjs index a597f2a6..2c2a8f3f 100644 --- a/web/test/authReload.test.mjs +++ b/web/test/authReload.test.mjs @@ -27,11 +27,14 @@ test("atomic password updates take effect without restart and fail closed on inv const cookie = first.headers.get("set-cookie").split(";")[0]; await writeFile(auth + ".next", JSON.stringify({ ...data, password:"new-password" })); await rename(auth + ".next",auth); assert.equal((await login("old-password")).status,401); - assert.equal((await login("new-password")).status,303); - assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,302); + const second = await login("new-password"); assert.equal(second.status,303); + // A changed password signs the earlier session out; the new one is signed in. + assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,200); + const cookie2 = second.headers.get("set-cookie").split(";")[0]; + assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,302); await writeFile(auth + ".next", "malformed"); await rename(auth + ".next",auth); assert.equal((await login("new-password")).status,503); - assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,503); + assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,503); await writeFile(auth,JSON.stringify(data)); assert.equal((await login("old-password")).status,303); }); diff --git a/web/test/authStore.test.mjs b/web/test/authStore.test.mjs new file mode 100644 index 00000000..be17168e --- /dev/null +++ b/web/test/authStore.test.mjs @@ -0,0 +1,195 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, stat, writeFile, rename } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { AuthStore, REVOKED_LIMIT, hashPassword, parseHash, verifyPassword } from "../src/authStore.js"; +import { passwordProblem } from "../src/passwordPolicy.js"; +import { LoginLimiter, clientKey } from "../src/loginLimiter.js"; +import { safeNext, sameOriginRequest, isHttps, sessionCookieName } from "../src/webSecurity.js"; +import { SessionSockets } from "../src/sessionSockets.js"; + +const CHEAP = { N: 1024, r: 8, p: 1, keyLength: 32 }; + +async function fixture(t, data) { + const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-store-")); + t.after(() => rm(dir, { recursive: true, force: true })); + const file = join(dir, "web-auth.json"); + await writeFile(file, JSON.stringify(data), { mode: 0o600 }); + return file; +} + +const replace = async (file, data) => { + await writeFile(`${file}.next`, JSON.stringify(data), { mode: 0o600 }); + await rename(`${file}.next`, file); +}; + +test("hashes are scrypt with recorded parameters and verify in constant time", async () => { + const stored = hashPassword("tulip orbit canyon ember", CHEAP); + assert.match(stored, /^scrypt\$1024\$8\$1\$[A-Za-z0-9_-]+\$[A-Za-z0-9_-]+$/); + assert.ok(parseHash(stored)); + assert.equal(await verifyPassword(stored, "tulip orbit canyon ember"), true); + assert.equal(await verifyPassword(stored, "tulip orbit canyon embers"), false); + assert.equal(await verifyPassword("scrypt$1000$8$1$AAAAAAAAAAA$BBBBBBBBBBBBBBBBBBBBBB", "x"), false); + assert.equal(parseHash("plain"), null); +}); + +test("a plaintext password migrates to a hash without changing it", async (t) => { + const file = await fixture(t, { password: "old-password", secret: "s".repeat(40), other: "kept" }); + const logs = []; + const store = new AuthStore(file, { log: (line) => logs.push(line) }); + const state = store.load(); + const written = JSON.parse(await readFile(file, "utf8")); + assert.equal(written.password, undefined); + assert.equal(written.other, "kept"); + assert.equal(written.password_weak, true); + assert.equal(written.secret, "s".repeat(40)); // first start: sessions stay valid + assert.equal(state.weak, true); + assert.equal(await verifyPassword(written.password_hash, "old-password"), true); + assert.equal((await stat(file)).mode & 0o777, 0o600); + assert.ok(!logs.join("\n").includes("old-password")); + // A strong plaintext is not flagged. + const strong = await fixture(t, { password: "tulip orbit canyon ember", secret: "s".repeat(40) }); + assert.equal(new AuthStore(strong, { log() {} }).load().weak, false); +}); + +test("a plaintext password written over a running proxy signs every session out", async (t) => { + const file = await fixture(t, { password_hash: hashPassword("first passphrase here ok", CHEAP), secret: "s".repeat(40), generation: 3 }); + const store = new AuthStore(file, { log() {} }); + const { token } = store.issue(60); + await replace(file, { password: "new-password", secret: "s".repeat(40), generation: 3 }); + assert.equal(store.check(token), null); + const written = JSON.parse(await readFile(file, "utf8")); + assert.equal(written.generation, 4); + assert.notEqual(written.secret, "s".repeat(40)); +}); + +test("tokens: signature, expiry, generation, logout and sign out everywhere", async (t) => { + let now = 1_800_000_000_000; + const data = { password_hash: hashPassword("tulip orbit canyon ember", CHEAP), secret: "s".repeat(40), generation: 1 }; + const file = await fixture(t, data); + const store = new AuthStore(file, { now: () => now, log() {} }); + const a = store.issue(60).token; + const b = store.issue(3600).token; + assert.ok(store.check(a)); + assert.equal(store.check(a.slice(0, -2) + (a.endsWith("A") ? "BB" : "AA")), null); + assert.equal(store.check(a.replace(/^v2\.1\./, "v2.2.")), null); + assert.equal(store.check("1800000000.abc.def"), null); // the old unversioned format + // Server-side logout of one token leaves the other. + assert.equal(store.revoke(a), true); + assert.equal(store.check(a), null); + assert.ok(store.check(b)); + // The list survives a proxy restart. + assert.equal(new AuthStore(file, { now: () => now, log() {} }).check(a), null); + assert.equal(((await stat(`${file}.sessions.json`)).mode & 0o777), 0o600); + // Expiry. + now += 61_000; + const c = store.issue(60).token; + now += 1000; + assert.ok(store.check(c)); + now += 60_000; + assert.equal(store.check(c), null); + // Sign out everywhere: every earlier token, but not a later sign-in. + const d = store.issue(3600).token; + now += 1; + store.revokeAll(); + assert.equal(store.check(b), null); + assert.equal(store.check(d), null); + now += 1; + const e = store.issue(3600).token; + assert.ok(store.check(e)); + assert.ok(new AuthStore(file, { now: () => now, log() {} }).check(e)); + assert.equal(new AuthStore(file, { now: () => now, log() {} }).check(d), null); + // ./password (new secret and generation) ends every session. + await replace(file, { ...data, secret: "t".repeat(40), generation: 2 }); + assert.equal(store.check(e), null); + const f = store.issue(3600).token; + assert.ok(store.check(f)); +}); + +test("the signed-out list is bounded, dropping the soonest to expire", async (t) => { + const file = await fixture(t, { password_hash: hashPassword("tulip orbit canyon ember", CHEAP), secret: "s".repeat(40) }); + const store = new AuthStore(file, { now: () => 1_000_000, log() {} }); + store.load(); + for (let i = 0; i < REVOKED_LIMIT + 5; i++) store.revoked.set(`token-id-${String(i).padStart(6, "0")}`, 10_000 + i); + store.saveSessions(); + assert.equal(store.revoked.size, REVOKED_LIMIT); + assert.ok(!store.revoked.has("token-id-000000")); + assert.ok(store.revoked.has(`token-id-${String(REVOKED_LIMIT + 4).padStart(6, "0")}`)); +}); + +test("the strength rule matches scripts/password.py", () => { + for (const strong of ["tulip orbit canyon ember", "correct horse battery staple", "k7#Rv9!qLm2@Xz4s", "cat dog sun red"]) + assert.equal(passwordProblem(strong), null, strong); + for (const weak of ["short", "old password", "J8m!x2Lq0#vR9tZ", "password password password", "a".repeat(20), + "Password12345678!", "qwertyuiop1234567890", "password welcome admin letmein", "dog dog dog dog dog"]) + assert.notEqual(passwordProblem(weak), null, weak); +}); + +test("limiter: per-client backoff, success reset, global cap and bounded eviction", () => { + let now = 0; + const limiter = new LoginLimiter({ now: () => now, freeFailures: 3, baseMs: 1000, maxKeys: 4, globalLimit: 10, globalWindowMs: 60_000 }); + for (let i = 0; i < 2; i++) limiter.fail("a"); + assert.equal(limiter.blocked("a"), 0); + limiter.fail("a"); + assert.equal(limiter.blocked("a"), 1000); + limiter.fail("a"); + assert.equal(limiter.blocked("a"), 2000); // doubles + assert.equal(limiter.blocked("b"), 0); + limiter.succeed("a"); + assert.equal(limiter.blocked("a"), 0); + // Eviction keeps at most maxKeys clients, the least recent leaving first. + for (const key of ["k1", "k2", "k3", "k4", "k5"]) limiter.fail(key); + assert.equal(limiter.clients.size, 4); + assert.ok(!limiter.clients.has("k1")); + // The global window: ten failures from anyone block everyone. + now = 120_000; + for (let i = 0; i < 10; i++) limiter.fail(`spread-${i}`); + assert.ok(limiter.blocked("someone-new") > 0); + assert.ok(limiter.recent.length <= 10); + now += 60_000; + assert.equal(limiter.blocked("someone-new"), 0); +}); + +test("the limiter charges Tailscale users only behind a loopback Tailscale proxy", () => { + const req = (address, headers) => ({ socket: { remoteAddress: address }, headers }); + assert.equal(clientKey(req("127.0.0.1", { "tailscale-user-login": "Alan@Example.com" })), "tailscale:alan@example.com"); + assert.equal(clientKey(req("::1", { "tailscale-user-name": "x", "x-forwarded-for": "100.64.0.7, 1.1.1.1" })), "forwarded:100.64.0.7"); + assert.equal(clientKey(req("127.0.0.1", { "x-forwarded-for": "100.64.0.7" })), "address:127.0.0.1"); + assert.equal(clientKey(req("192.168.1.5", { "tailscale-user-login": "forged@example.com" })), "address:192.168.1.5"); +}); + +test("next targets stay on this origin", () => { + for (const good of ["/", "/runs/12", "/chat?x=1#y", "/a/b//c"]) assert.equal(safeNext(good), good); + for (const bad of ["//evil.com", "/\\evil.com", "\\\\evil.com", "https://evil.com", "evil", "/ok\\path", "/a\nb", "", null]) + assert.equal(safeNext(bad), "/", String(bad)); +}); + +test("origin checks, https detection and cookie naming", () => { + const req = (headers, encrypted = false) => ({ headers: { host: "pipelines.example:8443", ...headers }, socket: { encrypted } }); + assert.equal(sameOriginRequest(req({})), true); + assert.equal(sameOriginRequest(req({ origin: "https://pipelines.example:8443" })), true); + assert.equal(sameOriginRequest(req({ origin: "https://evil.example" })), false); + assert.equal(sameOriginRequest(req({ origin: "null" })), false); + assert.equal(sameOriginRequest(req({ "sec-fetch-site": "cross-site" })), false); + assert.equal(sameOriginRequest(req({ "sec-fetch-site": "same-site", origin: "https://pipelines.example:8443" })), false); + assert.equal(isHttps(req({ "x-forwarded-proto": "https" })), true); + assert.equal(isHttps(req({})), false); + assert.equal(sessionCookieName(req({ "x-forwarded-proto": "https" })), "__Host-pipelines_session"); + assert.equal(sessionCookieName(req({})), "pipelines_session"); +}); + +test("socket sweep destroys only sockets whose session is gone", async () => { + const { EventEmitter } = await import("node:events"); + const sockets = new SessionSockets(); + const make = () => Object.assign(new EventEmitter(), { destroyed: false, destroy() { this.destroyed = true; this.emit("close"); } }); + const keep = make(), drop = make(); + sockets.track(keep, "good"); + sockets.track(drop, "bad"); + assert.equal(sockets.sweep((token) => token === "good"), 1); + assert.equal(drop.destroyed, true); + assert.equal(keep.destroyed, false); + assert.equal(sockets.size, 1); + keep.emit("close"); + assert.equal(sockets.size, 0); +});