Merge branch 'worktree-agent-a7f96a1eb9a56587d'
# Conflicts: # cmd/pipelines-server/main.go # internal/server/websocket.go # scripts/manage.py # scripts/setup-native.py # web/serve.mjs # web/src/peerRelay.js
This commit is contained in:
@@ -439,6 +439,10 @@ def supervise(config):
|
||||
# The server requires, and the proxy and every child CLI send, the
|
||||
# shared token in this file (installs from before it have none).
|
||||
env.update(server_token_env(config))
|
||||
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:
|
||||
|
||||
+164
-12
@@ -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__":
|
||||
|
||||
+27
-11
@@ -45,6 +45,7 @@ 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_access = module("web_access", "web_access.py")
|
||||
web_password = module("pipelines_password", "password.py")
|
||||
|
||||
DEFAULT_PREFIX = Path.home() / ".local/share/pipelines"
|
||||
MARKER = "pipelines-install.json"
|
||||
@@ -351,16 +352,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)
|
||||
server_token = self.ensure_server_token(auth.parent / "server-token")
|
||||
target = prefix / "lib/web"
|
||||
@@ -395,17 +397,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.")
|
||||
@@ -695,6 +700,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)
|
||||
@@ -880,7 +896,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:
|
||||
|
||||
+80
-12
@@ -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):
|
||||
|
||||
@@ -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"))
|
||||
@@ -287,16 +290,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"])
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user