diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d1195ca1..eb94cc4d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `skills/sudo-secretspec/scripts/secrets-collect.py` gained `--yes` for agents + without a terminal: with `--clipboard` it takes one secret per run from the + clipboard, requires an exact length, refuses stale or already-consumed + copies (the sentinel names the run that consumed it), clears the clipboard + right after the read under a per-user lock so parallel runs cannot store one + copy twice, reports partial stores, and never prints value characters. + Piped answers without `--yes` and `--yes` without `--clipboard` are refused. + ### Fixed - Concurrent opens of a history-enabled sqlite vault no longer fail with diff --git a/skills/sudo-secretspec/SKILL.md b/skills/sudo-secretspec/SKILL.md index 69ad34c4d..aaee9ad43 100644 --- a/skills/sudo-secretspec/SKILL.md +++ b/skills/sudo-secretspec/SKILL.md @@ -142,16 +142,19 @@ python3 $S \ python3 $S --secret 'FOO_API_KEY=the API key' # one value python3 $S --secret 'OVH_ENDPOINT=API endpoint' --literal # not a key: skip the alnum check -python3 $S --secret 'NAME=desc:8' --dry-run # validate only, store nothing +python3 $S --secret 'NAME=desc:8' --dry-run # validate only, store nothing (with --clipboard --yes it still consumes and clears the copy) python3 $S --secret 'NAME=desc' --clipboard # read from pbpaste instead of typing ``` 1. **It prompts for each value with the input hidden** (`getpass`), so nothing is echoed — not into the scrollback, not into shell history, not into the process table (values reach `set` on stdin, never in argv). -2. **All-or-nothing:** nothing is stored until every value is collected and the - operator confirms the summary, so Ctrl-C or a closed stdin leaves the store - exactly as it was. Verified 2026-10-25. +2. **Nothing is stored until every value is collected, checked and (without + `--yes`) confirmed**, so Ctrl-C or a closed stdin before that leaves the store + exactly as it was. The store loop itself is **not** atomic: a failure or + Ctrl-C part-way prints `stored=[...] not_stored=[...]` (and `unknown=[...]` + for the value in flight) and exits non-zero. Nothing is rolled back, because + an overwritten old value is gone — re-run for the names listed as not stored. 3. **It refuses a value that cannot be a key.** Alphanumeric-plus-`_`/`-` by default, with the offending characters named — which is what catches the masked-UI-rendering case above *before* it is stored. `--literal` for @@ -159,12 +162,85 @@ python3 $S --secret 'NAME=desc' --clipboard # read from pbpaste instead o 4. **It prints names and lengths only**, and the `--notify-to ROLE` message carries names and lengths only. 5. **EOF is "no", never a crash** — safe under a pipe or a closed stdin. +6. **Typed mode needs a terminal.** The hidden prompt is `getpass`: with no + terminal at all it falls back to reading stdin, so a value piped in (without + `--clipboard`) is accepted today, but only by that accident, and it went through + the caller's command line. Do not do it; `--yes` without `--clipboard` and with a + non-tty stdin is refused (exit 2) for exactly that reason. The declaring agent still declares the names first (`add --optional`), and still proves the result with `run` (a length), never `get`. This script replaces the "ask the human, then pipe" dance; it does not replace the declaration or the verification. +**An agent with no terminal** cannot answer the final prompt or press Enter, so +use `--clipboard --yes`. Every rule below applies to **any** `--clipboard --yes` +run, on a pty or not: + +1. **Run it only after the operator says the value is copied.** It reads and + then overwrites whatever is on the clipboard; run too early and it consumes + (and clears) something unrelated, and prints that content's length and + character classes into your transcript. `--dry-run` consumes and clears the + copy too, so it is not a free rehearsal. +2. **ONE secret per run, and never two runs at once: issue the commands + sequentially, each after a fresh copy, never as parallel tool calls.** The + clipboard cannot change between secrets (more than one `--secret` exits 2). A + per-user lock (`~/Library/Caches/secrets-collect.lock`, not under `$TMPDIR`, so + two harnesses share it) is held from before `pbpaste` until after the clear. A + second run waits about 10 s for it, then exits 1 ("another secrets-collect run + holds the clipboard lock"); one that gets in after the clear reads the sentinel, + which names the run that consumed the copy (`... cleared by the run for NAME at + HH:MM:SS ...`), and exits 1. **A parallel loser is not harmless:** the winner may + have taken a copy meant for the loser's name, so **both names must be + re-collected, one at a time**, each after a fresh copy. Re-running only the + loser leaves the winner holding the wrong value (its length would still pass). +3. **The spec MUST carry the expected length** (`NAME=desc:32`), else exit 2. A + regex does not count: the spec cannot carry both, and a regex can match + stale prose (`.+`); if you need a pattern, pin the length in it and use it + interactively. With no human at the prompt the length is the only freshness + check, so a mismatch aborts **without prompting** (nothing stored). The + alphanumeric shape check applies (a regex does not waive it; only + `--literal` does), and `cleared` and the script's own sentinel are refused. +4. **`--clipboard` with a non-tty stdin and no `--yes` exits 2** ("a non-tty + stdin is not the operator"): piped Enter/`y` answers never stand in for the + operator. `--yes` without `--clipboard` and with a non-tty stdin also exits 2. + +`--yes` skips the "Store these?" prompt and the Enter wait; every check and +stdin-only delivery are unchanged. It reads `pbpaste` once, aborts (exit 1, +nothing stored) on an empty, non-UTF-8, bad-shape or wrong-length value rather +than retrying, and **overwrites the clipboard itself right after the read** +(in a `finally`, so a stored, rejected or interrupted run clears it; SIGINT, +SIGTERM and SIGHUP are blocked while the overwrite runs, so one that arrives +then is delivered after it. A SIGKILL or power loss between the read and the +clear cannot be caught, and neither can a `pbcopy` that fails). The +next run sees a fresh copy or the sentinel, never the previous secret. A failed +overwrite prints `WARNING: ... NOT cleared`. The rejection text gives a count +and character classes, never the characters. A clipboard that was stale +**before the first run** and has the same shape and length cannot be detected: +have the operator copy, say so in chat, then run. SIGTERM/SIGHUP mid-store gets +the same `PARTIAL STORE` report as Ctrl-C. + +Do **not** use `--literal` for a key: it removes the shape check. It is for +endpoints and URLs (and then still give `:LEN`). **One exception:** a key whose +alphabet includes `/`, `+` or `=` (AWS secret access keys, Azure keys, other +base64 material) is rejected by the alphanumeric check and has no other route, +since a regex does not waive it. For those, and only those, use `--literal` with +`:LEN` still required (LEN is then the only check), and verify the shape under +`run` afterwards as above. + +```bash +python3 $S --secret 'NAME=desc:32' --clipboard --yes +printf 'cleared' | ~/ops/site-private/bin/clip # regardless of the exit status: `;`, never `&&` +sudo-secretspec run -- sh -c 'echo ${#NAME}' +``` + +The script clears the clipboard itself; the second line is the belt for the +runs where it died before the read (or printed the WARNING). Run it whether or +not the first line succeeded, so a secret never stays on the pasteboard (clipboard +managers, Universal Clipboard). + +Verified 2026-10-26 (stub `sudo-secretspec`/`pbpaste`/`pbcopy`; no live vault). + ### Giving a consumer a secret it reads itself diff --git a/skills/sudo-secretspec/scripts/secrets-collect.py b/skills/sudo-secretspec/scripts/secrets-collect.py index cd3ed3e71..46c44fe43 100755 --- a/skills/sudo-secretspec/scripts/secrets-collect.py +++ b/skills/sudo-secretspec/scripts/secrets-collect.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Collect several secret values interactively, validate each, store them all-or-nothing. +"""Collect several secret values interactively, validate each, store them in one pass. Any agent, any provider. The operator runs it; the agent reads the result from the store. @@ -19,6 +19,11 @@ secrets-collect.py ... --dry-run # validate only; store nothing, notify nobody secrets-collect.py ... --clipboard # read each value from pbpaste instead of typing + # no terminal (an agent): ONE secret per run, no prompts, LEN REQUIRED. Run it only after the + # operator says the value is copied, and never two at once (a lock makes a second one fail) + # (keys with `/+=` in the alphabet, e.g. AWS secret keys: add --literal, :LEN still required) + secrets-collect.py --secret 'NAME=desc:32' --clipboard --yes + Why this exists: an agent that needs values from a human must never ask the human to paste them into a chat. That puts the value in a transcript, which is the one thing the house rules forbid. This script is the safe path: the human types into a hidden prompt, the value goes straight to @@ -26,21 +31,80 @@ Properties, each deliberate: 1. Input is hidden (getpass) — not echoed, so not in the scrollback, and not in shell history. - 2. All-or-nothing — nothing is stored until every value is collected and confirmed, so an - abort (Ctrl-C, closed stdin) leaves the store exactly as it was, never half-populated. + 2. Nothing is stored until every value is collected and checked (and, without --yes, confirmed), + so an abort (Ctrl-C, closed stdin) before that leaves the store exactly as it was. Once the + store loop starts it is NOT atomic: a failure or Ctrl-C mid-loop prints + `stored=[...] not_stored=[...]` (and `unknown=[...]` for the one in flight), exit non-zero. + Nothing is rolled back, because an overwritten old value is gone. 3. Values reach sudo-secretspec on stdin, never in argv (so not in the process table). - 4. Only names and lengths are ever printed. + 4. Only names and lengths are ever printed. In the no-terminal mode (an agent's transcript) a + rejected value is described by a count and character classes, never the characters. 5. The notification message carries names and lengths, never values. 6. EOF is treated as "no", never a crash. + 7. --clipboard --yes (tty or not) cannot tell a fresh copy from a stale clipboard by looking + at it, so it (a) requires an expected LEN in the spec (a regex does not count) and aborts on + a mismatch without prompting, (b) refuses the sentinels `cleared` and anything starting + CLEARED_PREFIX, (c) overwrites the clipboard with a sentinel naming this run's NAME, in a + `finally` right after the read (stored, rejected, or an exception or SIGINT/SIGTERM/SIGHUP + during the read or later; those three signals are blocked while pbcopy runs, so one that + arrives then is delivered after the clear), and (d) holds an exclusive per-user lock + (~/Library/Caches/secrets-collect.lock, not under TMPDIR) from before pbpaste until after + that overwrite. A second run waits about 10 s, then exits 1; one that gets in after the + clear reads the sentinel and fails, naming the run that consumed the copy: that run may have + taken a copy meant for the loser's name, so BOTH names must be re-collected. A SIGKILL or + power loss between the read and the clear, or a failing pbcopy (a WARNING is printed), leaves + the value on the pasteboard. A clipboard that was stale before the FIRST run and happens to + have the same shape and length is not detectable; --dry-run reads and clears too, so it + consumes the operator's copy. + --clipboard with a non-tty stdin and no --yes is refused: piped answers are not the operator. + 8. A clipboard value identical to one already collected in the same run is refused (the + clipboard did not change between secrets), so a pty cannot read one value into N names. """ from __future__ import annotations import argparse +import contextlib +import fcntl import getpass import os +import pwd import re +import signal import subprocess import sys +import time +import unicodedata + +_CANCEL_SIGNALS = {signal.SIGINT, signal.SIGTERM, signal.SIGHUP} + +CLEARED_PREFIX = "secrets-collect: clipboard cleared" # every sentinel this script ever wrote +CLEARED_WORD = "cleared" +LOCK_WAIT = 10.0 # seconds a second run waits for the clipboard lock before giving up +_CONSUMER = re.compile(r"cleared by the run for (\S+) at (\d\d:\d\d:\d\d)") + + +def is_sentinel(value: str) -> bool: + return value == CLEARED_WORD or value.startswith(CLEARED_PREFIX) + + +def sentinel_error(value: str, name: str) -> str: + """Why a sentinel was read. A run that lost the lock race read the winner's sentinel, and the + winner may have taken a copy meant for THIS name, so say who consumed it.""" + m = _CONSUMER.search(value) + if not m: + return ("the clipboard holds a cleared-clipboard sentinel: no fresh copy was made since " + "the last clear") + who, at = m.groups() + if who == name: + return (f"the clipboard holds a cleared-clipboard sentinel: an earlier run for {name} " + f"consumed the copy at {at}; copy the value again") + return (f"the clipboard holds a cleared-clipboard sentinel: the run for {who} consumed this " + f"copy at {at}; if the copy was for {name}, {who} now holds that value: " + f"re-collect {who} too") + + +class StoreError(Exception): + pass def ask(prompt: str, default: bool = False) -> bool: @@ -70,22 +134,146 @@ def parse_spec(spec: str) -> tuple[str, str, int | None, str | None]: length = int(tail) elif tail: pattern = tail + if pattern: + try: + re.compile(pattern) + except re.error as e: + raise SystemExit(f"bad regex in --secret {name!r}: {e}") from None return name, desc.strip() or name, length, pattern -def read_value(label: str, from_clipboard: bool) -> str: - """One value, hidden if from the terminal. Retries on an empty read.""" +def _pb_env() -> dict[str, str]: + """pbcopy and pbpaste both need this: an agent shell's LC_CTYPE=C mangles non-ASCII text.""" + return dict(os.environ, LC_CTYPE="UTF-8") + + +def _ignore_cancel_signals() -> None: + """SIG_IGN for SIGINT/SIGTERM/SIGHUP. A signal that already arrived is still tripped and + would raise inside this very loop, so retry: once all three are ignored it is dropped.""" + for sig in sorted(_CANCEL_SIGNALS): + while True: + try: + signal.signal(sig, signal.SIG_IGN) + break + except KeyboardInterrupt: + continue + + +def _not_cleared(e: BaseException) -> None: + print(f" WARNING: the clipboard was NOT cleared ({type(e).__name__}); " + "overwrite it yourself", file=sys.stderr) + + +def clear_clipboard(name: str) -> None: + """Overwrite the pasteboard with a sentinel naming the run that consumed the copy, so a later + run cannot read this secret again and a loser of a lock race can say whom to re-collect.""" + mark = (f"{CLEARED_PREFIX} by the run for {name} at {time.strftime('%H:%M:%S')}, " + "copy the value again") + try: + subprocess.run(["pbcopy"], input=mark, text=True, check=True, + capture_output=True, env=_pb_env(), timeout=15) + except Exception as e: # noqa: BLE001 + _not_cleared(e) + except BaseException as e: # an interrupt that got through: still say so, then let it go on + _not_cleared(e) + raise + + +def lock_path() -> str: + """Per user, not per TMPDIR: the pasteboard is shared by every process of the login session, + so two harnesses with different TMPDIRs must still meet at one lock. SECRETS_COLLECT_LOCK_DIR + exists for the tests; nothing else sets it.""" + d = os.environ.get("SECRETS_COLLECT_LOCK_DIR") or os.path.join( + pwd.getpwuid(os.getuid()).pw_dir, "Library", "Caches") + os.makedirs(d, mode=0o700, exist_ok=True) + return os.path.join(d, "secrets-collect.lock") + + +@contextlib.contextmanager +def clipboard_lock(): + """Per-user exclusive lock held from before pbpaste until after the clear, so two parallel + no-terminal runs cannot both read the same copy. Taken with LOCK_NB and retried for LOCK_WAIT + seconds; a second run that cannot get it exits 1 rather than block without a word.""" + path = "(unknown)" + try: + path = lock_path() + fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600) + except OSError as e: + print(f" could not open the lock file {path}: {type(e).__name__}", file=sys.stderr) + raise SystemExit(1) + try: + deadline = time.monotonic() + LOCK_WAIT + while True: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= deadline: + print(" another secrets-collect run holds the clipboard lock; " + "wait for it to finish and run this one again", file=sys.stderr) + raise SystemExit(1) + time.sleep(0.05) + yield + finally: + os.close(fd) # closing releases the flock + + +def read_and_clear(name: str) -> bytes: + """pbpaste, then overwrite the clipboard in a finally, so an interrupt right after the read + still clears. A pbpaste that failed read nothing, and a sentinel holds nothing secret (and + names the run that really consumed the copy), so both leave the clipboard alone. SIGINT, + SIGTERM and SIGHUP are blocked (pbcopy inherits the mask, so a group signal cannot kill it + either) while the overwrite runs; a signal that arrived meanwhile is delivered right after.""" + leave = False + try: + data = subprocess.run(["pbpaste"], capture_output=True, check=True, + env=_pb_env()).stdout + leave = is_sentinel(data.decode("utf-8", "replace").strip()) + return data + except (subprocess.CalledProcessError, OSError): + leave = True + raise + finally: + if not leave: + old = signal.pthread_sigmask(signal.SIG_BLOCK, _CANCEL_SIGNALS) + try: + clear_clipboard(name) + finally: + signal.pthread_sigmask(signal.SIG_SETMASK, old) + + +def read_value(label: str, from_clipboard: bool, no_wait: bool = False, name: str = "?") -> str: + """One value, hidden if from the terminal. Retries on an empty read. + + no_wait (clipboard, no terminal): read pbpaste once, no Enter wait, no retry -- the + clipboard cannot change, so an empty read or a retry would only loop forever -- and + overwrite the clipboard at once. Error text never carries clipboard bytes.""" while True: if from_clipboard: - print(f" Copy {label} to the clipboard, then press Enter.") try: - input(" [Enter when copied] ") - raw = subprocess.run(["pbpaste"], capture_output=True, text=True, check=True).stdout + if no_wait: + print(f" Reading {label} from the clipboard (no terminal, no wait).") + with clipboard_lock(): + data = read_and_clear(name) + else: + print(f" Copy {label} to the clipboard, then press Enter.") + input(" [Enter when copied] ") + data = subprocess.run(["pbpaste"], capture_output=True, check=True, + env=_pb_env()).stdout + try: + raw = data.decode("utf-8") + except UnicodeDecodeError: + print(" the clipboard is not valid UTF-8 text", file=sys.stderr) + if no_wait: + raise SystemExit(1) + continue except EOFError: print(" no input available — aborting rather than guessing", file=sys.stderr) raise SystemExit(1) except Exception as e: # noqa: BLE001 - print(f" could not read the clipboard: {e}", file=sys.stderr) + print(f" could not read the clipboard: {type(e).__name__}", file=sys.stderr) + if no_wait: + raise SystemExit(1) continue else: try: @@ -96,21 +284,47 @@ def read_value(label: str, from_clipboard: bool) -> str: value = raw.strip() if value: return value + if no_wait: + print(" the clipboard is empty — aborting, nothing stored", file=sys.stderr) + raise SystemExit(1) + print(" empty — try again (Ctrl-C to abort)") -def check(value: str, length: int | None, pattern: str | None, literal: bool) -> str | None: - """Return an error string, or None if acceptable. A length mismatch warns, not blocks.""" +def _classes(bad: set[str]) -> str: + out = set() + for c in bad: + if c.isspace(): + out.add("whitespace") + elif ord(c) > 127: + out.add("non-ASCII") + elif unicodedata.category(c).startswith("C"): + out.add("control") + else: + out.add("punctuation") + return ", ".join(sorted(out)) + + +def check(value: str, length: int | None, pattern: str | None, literal: bool, + no_wait: bool = False) -> str | None: + """Return an error string, or None if acceptable. + + A length mismatch warns (asks) interactively; with no_wait there is nobody to ask and the + length is the freshness check, so it blocks.""" if pattern and not re.fullmatch(pattern, value): return f"does not match the required pattern {pattern!r}" - if literal or pattern: - return None - # API keys are alphanumeric (plus - and _); punctuation is the signature of a mis-copied - # UI rendering — a masked box or a copied label — which passes a length check and is not a key. - if not re.fullmatch(r"[A-Za-z0-9_\-]+", value): - bad = sorted({c for c in value if not re.match(r"[A-Za-z0-9_\-]", c)}) - return (f"contains characters {bad!r} that API keys do not have — that is usually a " - f"mis-copied UI rendering (a masked box, a label), not a key") + if not literal: + # API keys are alphanumeric (plus - and _); punctuation is the signature of a mis-copied + # UI rendering — a masked box or a copied label — which passes a length check and is not a key. + if not re.fullmatch(r"[A-Za-z0-9_\-]+", value): + bad = {c for c in value if not re.match(r"[A-Za-z0-9_\-]", c)} + if no_wait: + return (f"{len(bad)} distinct character(s) of class [{_classes(bad)}] that API keys " + f"do not have — usually a mis-copied UI rendering or a stale clipboard") + return (f"contains characters {sorted(bad)!r} that API keys do not have — that is usually " + f"a mis-copied UI rendering (a masked box, a label), not a key") if length is not None and len(value) != length: + if no_wait: + return f"{len(value)} characters; the expected length is {length} (stale clipboard?)" print(f" ⚠ {len(value)} characters; the expected length is {length}.") print(" Not necessarily wrong, but check you copied the whole value.") if not ask(" Use it anyway? [y/N] "): @@ -120,12 +334,24 @@ def check(value: str, length: int | None, pattern: str | None, literal: bool) -> def store(name: str, value: str, reason: str) -> None: """Store one value via sudo-secretspec, on stdin, never argv.""" - proc = subprocess.run( - ["sudo-secretspec", "set", name, "--reason", reason], - input=value, text=True, capture_output=True, - ) + try: + proc = subprocess.run( + ["sudo-secretspec", "set", name, "--reason", reason], + input=value, text=True, capture_output=True, + ) + except OSError as e: + raise StoreError(f"FAILED to store {name}: {type(e).__name__}") from None if proc.returncode != 0: - raise SystemExit(f"FAILED to store {name}: {proc.stderr.strip()}") + raise StoreError(f"FAILED to store {name}: {proc.stderr.strip()}") + + +def report_partial(stored: list[str], rest: list[str], unknown: str | None = None) -> None: + """The store loop is not atomic; say exactly what was and was not stored.""" + msg = f"stored=[{', '.join(stored)}] not_stored=[{', '.join(rest)}]" + if unknown: + msg += f" unknown=[{unknown}] (in flight)" + print(f"PARTIAL STORE: {msg}" if stored or unknown else f"nothing was stored: {msg}", + file=sys.stderr) def notify(role: str, names: list[tuple[str, int]], reason: str) -> None: @@ -149,50 +375,99 @@ def notify(role: str, names: list[tuple[str, int]], reason: str) -> None: print(f" could NOT notify {role} ({proc.returncode}): {proc.stderr.strip()}", file=sys.stderr) print(" The values ARE stored; tell the agent in the chat instead.", file=sys.stderr) - print(" empty — try again (Ctrl-C to abort)") - def main() -> int: - ap = argparse.ArgumentParser(description="Collect and store secret values, all-or-nothing.") + ap = argparse.ArgumentParser(description="Collect and store secret values (see the module docstring).") ap.add_argument("--secret", action="append", required=True, metavar="NAME=DESC[:LEN]", - help="repeatable; LEN is an expected character count (warns on mismatch)") + help="repeatable; LEN is an expected character count (warns on mismatch; " + "REQUIRED, with a mismatch aborting, under --clipboard --yes)") ap.add_argument("--reason", default="store values supplied by the operator", help="the reason recorded in the audit ledger") ap.add_argument("--notify-to", metavar="ROLE", help="tell this peer-role when done (names and lengths only)") ap.add_argument("--literal", action="store_true", - help="values are not API keys (no alphanumeric check) — endpoints, URLs") + help="values are not API keys (no alphanumeric check) — endpoints, URLs only; " + "an agent must not use it for a key, except one whose alphabet includes " + "/+= (AWS secret keys, Azure keys), with :LEN still required") ap.add_argument("--dry-run", action="store_true", help="validate but store nothing and notify nobody") ap.add_argument("--clipboard", action="store_true", help="read each value from pbpaste instead of typing it") + ap.add_argument("--yes", action="store_true", + help="skip the final 'Store these?' prompt. With --clipboard it also skips the " + "Enter wait (tty or not): ONE secret per run, LEN required, the clipboard is " + "cleared after the read, and a lock stops two runs at once. Needed for any " + "--clipboard run with a non-tty stdin. Without --clipboard it needs a " + "terminal (hidden prompt)") a = ap.parse_args() + tty = sys.stdin.isatty() + if a.yes and not a.clipboard and not tty: + print("refusing: --yes without --clipboard needs a terminal; a value piped on stdin " + "went through the caller's command line", file=sys.stderr) + return 2 + if a.clipboard and not a.yes and not tty: + print("refusing: a non-tty stdin is not the operator; use --yes (with LEN) for " + "--clipboard without a terminal", file=sys.stderr) + return 2 + no_wait = a.clipboard and a.yes + if a.clipboard and (no_wait or not tty) and len(a.secret) > 1: + print("refusing: --clipboard --yes (or a non-tty stdin) takes ONE --secret per run " + "(the clipboard cannot change between secrets)", file=sys.stderr) + return 2 + specs = [parse_spec(s) for s in a.secret] + if no_wait and any(length is None for _, _, length, _ in specs): + print("refusing: --clipboard --yes needs an expected length in the spec " + "(--secret 'NAME=desc:32'; a regex does not count, the spec cannot carry both) — " + "the length is the check that the clipboard is fresh", file=sys.stderr) + return 2 + + def _cancel(signum, frame): # a harness cancel (SIGTERM/SIGHUP) gets the same report as Ctrl-C + raise KeyboardInterrupt + signal.signal(signal.SIGTERM, _cancel) + signal.signal(signal.SIGHUP, _cancel) print(f"{len(specs)} value(s) to collect, stored in sudo-secretspec") - print("Input is hidden; nothing is echoed. Nothing is stored until you confirm at the end.") + if a.yes: + print("Input is hidden; nothing is echoed. --yes: there is no final confirmation; every " + "check still applies before anything is stored.") + else: + print("Input is hidden; nothing is echoed. Nothing is stored until you confirm at the end.") if a.dry_run: print("\n*** DRY RUN — nothing will be stored and nobody will be notified ***") print() collected: list[tuple[str, str]] = [] + stored: list[str] = [] + inflight: str | None = None + storing = False + notifying = False try: for i, (name, desc, length, pattern) in enumerate(specs, 1): print(f"[{i}/{len(specs)}] {name}") while True: - value = read_value(desc, a.clipboard) - err = check(value, length, pattern, a.literal) + value = read_value(desc, a.clipboard, no_wait, name) + err = None + if a.clipboard and is_sentinel(value): + err = sentinel_error(value, name) + elif a.clipboard and any(value == v for _, v in collected): + err = "identical to a value already collected — the clipboard did not change" + else: + err = check(value, length, pattern, a.literal, no_wait) if err is None: break print(f" ✗ {err}") + if no_wait: + print("Aborted — nothing was stored.", file=sys.stderr) + return 1 collected.append((name, value)) print(f" ✓ {name} accepted ({len(value)} characters)\n") print("Ready to store:") for name, value in collected: print(f" {name} (len={len(value)})") - if not ask("\nStore these? [y/N] "): + if not a.yes and not ask("\nStore these? [y/N] "): print("Aborted — nothing was stored.") return 1 @@ -200,19 +475,41 @@ def main() -> int: print("\nDRY RUN: skipping the store and the notification.") return 0 + storing = True for name, value in collected: - store(name, value, a.reason) + inflight = name + try: + store(name, value, a.reason) + except StoreError as e: + print(str(e), file=sys.stderr) + report_partial(stored, [n for n, _ in collected if n not in stored]) + return 1 + stored.append(name) + inflight = None print(f" stored {name}") + notifying = True if a.notify_to: notify(a.notify_to, [(n, len(v)) for n, v in collected], a.reason) print("\nDone.") return 0 except KeyboardInterrupt: - print("\nAborted — nothing was stored.", file=sys.stderr) + # a second signal, or a SIGHUP whose terminal is gone, must not cut the report short + _ignore_cancel_signals() + try: + if notifying: + print("\nInterrupted while notifying; every value IS stored.", file=sys.stderr) + elif storing: + print("\nInterrupted while storing.", file=sys.stderr) + report_partial(stored, + [n for n, _ in collected if n not in stored and n != inflight], + inflight) + else: + print("\nAborted — nothing was stored.", file=sys.stderr) + except OSError: + pass return 130 if __name__ == "__main__": sys.exit(main()) - diff --git a/tests/sudo_postinstall/test_secrets_collect.py b/tests/sudo_postinstall/test_secrets_collect.py new file mode 100644 index 000000000..7406141c6 --- /dev/null +++ b/tests/sudo_postinstall/test_secrets_collect.py @@ -0,0 +1,567 @@ +"""secrets-collect.py with stub `sudo-secretspec`, `pbpaste`, `pbcopy` on PATH; no real vault or clipboard. + +Every subprocess has a hard timeout: a mutant that loops must fail, not hang CI. +""" +import importlib.util +import os +import pty +import re +import signal +import stat +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[2] / "skills/sudo-secretspec/scripts/secrets-collect.py" +VALUE = "s3cretVALUE0123" +LEN = len(VALUE) +OLD_MARK = "secrets-collect: clipboard cleared, copy the value again" # round 1/2 sentinel +CLEARED = re.compile(r"secrets-collect: clipboard cleared by the run for (\w+) at " + r"\d\d:\d\d:\d\d, copy the value again") +TIMEOUT = 10 + + +@pytest.fixture +def env(tmp_path): + bindir = tmp_path / "bin" + bindir.mkdir() + log = tmp_path / "calls.log" + clip = tmp_path / "clip" + clip.write_text(VALUE) + + def stub(name, body): + p = bindir / name + p.write_text("#!/bin/sh\n" + body) + p.chmod(p.stat().st_mode | stat.S_IXUSR) + + stub("sudo-secretspec", f'echo "ARGV: $*" >> {log}\n' + f'cat {clip} > {tmp_path}/clip_at_store\n' + f'if [ "$2" = "$FAIL_NAME" ]; then echo boom >&2; exit 1; fi\n' + f'if [ "$2" = "$INT_NAME" ]; then kill -INT $PPID; sleep 5; fi\n' + f'if [ "$2" = "$TERM_NAME" ]; then kill -TERM $PPID; sleep 5; fi\n' + f'if [ "$2" = "$BURST_NAME" ]; then kill -INT $PPID; kill -TERM $PPID; ' + f'kill -HUP $PPID; sleep 5; fi\n' + f'cat >> {log}\necho >> {log}\n') + stub("pbpaste", f"cat {clip}\n") + stub("pbcopy", f"cat > {clip}\n") + e = dict(os.environ, PATH=f"{bindir}:{os.environ['PATH']}", TMPDIR=str(tmp_path), + SECRETS_COLLECT_LOCK_DIR=str(tmp_path / "lock")) + for k in ("FAIL_NAME", "INT_NAME", "TERM_NAME", "BURST_NAME"): + e.pop(k, None) + return e, log, clip, bindir + + +def _sigint_default(): + signal.signal(signal.SIGINT, signal.SIG_DFL) # so python installs its KeyboardInterrupt handler + + +def cleared_by(text): + """The NAME the clipboard's sentinel says consumed the copy, or None if it is not one.""" + m = CLEARED.fullmatch(text) + return m.group(1) if m else None + + +def run(env, args, stdin="", extra_env=None): + e = dict(env[0], **(extra_env or {})) + # own session: no controlling tty, so getpass reads the piped stdin even under a terminal + return subprocess.run([sys.executable, str(SCRIPT), *args], input=stdin, text=True, + capture_output=True, env=e, timeout=TIMEOUT, preexec_fn=_sigint_default, + start_new_session=True) + + +def calls(log): + return log.read_text() if log.exists() else "" + + +def run_pty(env, args, keys): + """Run with a real terminal on stdin; `keys` is what the 'operator' types. Returns (rc, out, err).""" + master, slave = pty.openpty() + p = subprocess.Popen([sys.executable, str(SCRIPT), *args], stdin=slave, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, env=env[0], preexec_fn=_sigint_default) + os.close(slave) + if keys: + os.write(master, keys) + try: + so, se = p.communicate(timeout=TIMEOUT) + finally: + os.close(master) + if p.poll() is None: + p.kill() + return p.returncode, so, se + + +def yes_args(spec=f"A=a:{LEN}", *more): + return ["--secret", spec, "--clipboard", "--yes", *more] + + +def out(r): + return r.stdout + r.stderr + + +# --- the accepted path ------------------------------------------------------------------- + +def test_yes_stores_via_stdin_not_argv(env): + _, log, clip, _ = env + r = run(env, yes_args()) + assert r.returncode == 0, r.stderr + text = calls(log) + argv = next(l for l in text.splitlines() if l.startswith("ARGV")) + assert argv == "ARGV: set A --reason store values supplied by the operator" + assert VALUE in text.replace(argv, "") + assert VALUE not in out(r) + + +def test_literal_with_matching_length_stores(env): + _, log, _, _ = env + r = run(env, ["--secret", f"A=a:{LEN}", "--literal", "--clipboard", "--yes"]) + assert r.returncode == 0, r.stderr + assert VALUE in calls(log) + + +# --- finding 1: stale clipboard, sentinel ------------------------------------------------- + +def test_clipboard_is_cleared_after_a_successful_read(env): + _, _, clip, _ = env + assert run(env, yes_args()).returncode == 0 + assert cleared_by(clip.read_text()) == "A" + # cleared BEFORE the store, not after: the store's own view of the clipboard is the sentinel + assert cleared_by((clip.parent / "clip_at_store").read_text()) == "A" + + +def test_second_run_without_a_fresh_copy_stores_nothing(env): + _, log, clip, _ = env + assert run(env, yes_args("A=a:%d" % LEN)).returncode == 0 + log.unlink() + # even a spec that fits the sentinel + r = run(env, yes_args("B=b:%d" % len(clip.read_text()), "--literal")) + assert r.returncode == 1 + assert calls(log) == "" + assert "sentinel" in out(r) + # it names the run that consumed the copy, since that run may have taken B's value + assert re.search(r"the run for A consumed this copy at \d\d:\d\d:\d\d", out(r)) + assert "re-collect A too" in out(r) + assert "nothing was copied" not in out(r) + + +def test_second_run_for_the_same_name_says_so(env): + _, log, clip, _ = env + assert run(env, yes_args("A=a:%d" % LEN)).returncode == 0 + r = run(env, yes_args("A=a:%d" % len(clip.read_text()), "--literal")) + assert r.returncode == 1 + assert "an earlier run for A consumed the copy at" in out(r) + assert "re-collect" not in out(r) + + +@pytest.mark.parametrize("stale", [ + "cleared", OLD_MARK, + "secrets-collect: clipboard cleared by the run for Z at 01:02:03, copy the value again"]) +def test_sentinels_refused_even_when_length_and_literal_fit(env, stale): + _, log, clip, _ = env + clip.write_text(stale) + r = run(env, ["--secret", f"A=a:{len(stale)}", "--literal", "--clipboard", "--yes"]) + assert r.returncode == 1 + assert calls(log) == "" + + +def test_no_terminal_mode_requires_length_or_regex(env): + _, log, clip, _ = env + r = run(env, ["--secret", "A=a", "--clipboard", "--yes"]) + assert r.returncode == 2 + assert calls(log) == "" + assert clip.read_text() == VALUE # refused before touching the clipboard + + +def test_regex_only_spec_is_refused_without_touching_the_clipboard(env): + _, log, clip, _ = env + r = run(env, ["--secret", "A=a:s3cret[A-Za-z0-9]+", "--clipboard", "--yes"]) + assert r.returncode == 2 + assert "length" in r.stderr + assert calls(log) == "" + assert clip.read_text() == VALUE + + +def test_malformed_regex_fails_before_the_clipboard_is_read(env): + _, log, clip, _ = env + r = run(env, ["--secret", "A=a:[unclosed", "--clipboard", "--yes"]) + assert r.returncode != 0 + assert "Traceback" not in r.stderr and "bad regex" in r.stderr + assert clip.read_text() == VALUE + assert calls(log) == "" + + +def _load_module(): + spec = importlib.util.spec_from_file_location("secrets_collect_under_test", SCRIPT) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def _check_fn(): + return _load_module().check + + +def test_regex_must_match_the_whole_value_and_keeps_the_shape_check(): + check = _check_fn() + pat = "s3cret[A-Za-z0-9]+" + assert check(VALUE, None, pat, False) is None + assert check("xx" + VALUE + "!!", None, pat, False) is not None # fullmatch, not search + assert check("xx" + VALUE, None, pat, False) is not None + # a regex alone does not waive the alphanumeric shape check; --literal does + assert check("see https://example.com/x", None, ".+", False) is not None + assert check("see https://example.com/x", None, ".+", True) is None + + +def test_clipboard_cleared_on_every_failure_path_after_the_read(env): + _, log, clip, _ = env + clip.write_text("not alnum !!") + assert run(env, yes_args("A=a:12")).returncode == 1 + assert cleared_by(clip.read_text()) == "A" + clip.write_text(VALUE) + assert run(env, yes_args("A=a:99")).returncode == 1 # length mismatch + assert cleared_by(clip.read_text()) == "A" + clip.write_text(VALUE) + r = run(env, yes_args(), extra_env={"FAIL_NAME": "A"}) # store failure + assert r.returncode == 1 + assert cleared_by(clip.read_text()) == "A" + + +def test_pbcopy_failure_is_loud(env): + _, _, clip, bindir = env + (bindir / "pbcopy").write_text("#!/bin/sh\nexit 1\n") + r = run(env, yes_args()) + assert "NOT cleared" in r.stderr + assert clip.read_text() == VALUE + + +# --- findings 2/12a/3: piped answers are not the operator ------------------------------------ + +def test_clipboard_with_piped_stdin_and_no_yes_is_refused(env): + _, log, clip, _ = env + r = run(env, ["--secret", f"A=a:{LEN}", "--clipboard"], stdin="\ny\n") + assert r.returncode == 2 + assert "use --yes" in r.stderr + assert calls(log) == "" + assert clip.read_text() == VALUE # refused before the clipboard was read + + +def test_interactive_clipboard_without_yes_waits_for_enter_and_does_not_clear(env): + _, log, clip, _ = env + r, so, se = run_pty(env, ["--secret", f"A=a:{LEN}", "--clipboard"], b"\ny\n") + assert r == 0, se + assert "[Enter when copied]" in so + assert VALUE in calls(log) + assert clip.read_text() == VALUE # a human at the keyboard: no self-clear + + +def test_yes_on_a_pty_gets_the_no_terminal_protections(env): + _, log, clip, _ = env + # no LEN: refused before the clipboard is touched, even though stdin is a terminal + r, so, se = run_pty(env, ["--secret", "A=a", "--clipboard", "--yes"], b"") + assert r == 2, se + assert clip.read_text() == VALUE + assert calls(log) == "" + # with LEN: stores without any Enter being sent, and clears + r, so, se = run_pty(env, yes_args(), b"") + assert r == 0, se + assert VALUE in calls(log) + assert cleared_by(clip.read_text()) == "A" + # a second run on the pty fails closed on the sentinel instead of waiting for input forever + log.unlink() + r, so, se = run_pty(env, yes_args("B=b:%d" % LEN), b"") + assert r == 1 + assert calls(log) == "" + + +@pytest.mark.parametrize("own_tmpdirs", [False, True]) +def test_parallel_runs_store_the_copy_at_most_once(env, tmp_path, own_tmpdirs): + _, log, clip, bindir = env + # a slow pbpaste holds the first run between its read and its clear, and a slow pbcopy + # makes the clear itself long enough that a clear outside the lock lets run 2 read the value + (bindir / "pbpaste").write_text(f"#!/bin/sh\ncat {clip}\nsleep 1\n") + (bindir / "pbcopy").write_text(f"#!/bin/sh\nsleep 1\ncat > {clip}\n") + names = ("A", "B") + procs = [] + for n in names: + e = dict(env[0]) + if own_tmpdirs: # two harnesses with their own TMPDIR still share one pasteboard + (tmp_path / f"tmp{n}").mkdir() + e["TMPDIR"] = str(tmp_path / f"tmp{n}") + procs.append(subprocess.Popen( + [sys.executable, str(SCRIPT), *yes_args(f"{n}=x:{LEN}")], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=e, + preexec_fn=_sigint_default, start_new_session=True)) + try: + res = [(p.communicate(timeout=TIMEOUT), p.returncode) for p in procs] + finally: + for p in procs: + if p.poll() is None: + p.kill() + rcs = sorted(rc for _, rc in res) + assert rcs == [0, 1], res + assert calls(log).count("ARGV: set") == 1 + winner = names[[rc for _, rc in res].index(0)] + loser_out = res[1 - names.index(winner)][0] + assert cleared_by(clip.read_text()) == winner + assert f"the run for {winner} consumed this copy" in "".join(loser_out) + assert f"re-collect {winner} too" in "".join(loser_out) + + +def test_group_signal_during_the_clear_cannot_leave_the_secret(env, tmp_path): + _, log, clip, bindir = env + started = tmp_path / "pbcopy_started" + (bindir / "pbcopy").write_text(f"#!/bin/sh\ntouch {started}\nsleep 1\ncat > {clip}\n") + p = subprocess.Popen([sys.executable, str(SCRIPT), *yes_args()], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env[0], + preexec_fn=_sigint_default, start_new_session=True) + try: + deadline = time.monotonic() + 5 + while not started.exists() and time.monotonic() < deadline: + time.sleep(0.02) + assert started.exists() + os.killpg(p.pid, signal.SIGTERM) # a harness cancel, or Ctrl-C, hits pbcopy too + so, se = p.communicate(timeout=TIMEOUT) + finally: + if p.poll() is None: + p.kill() + assert p.returncode == 130, se + assert cleared_by(clip.read_text()) == "A" # pbcopy finished: the signal waited for it + assert "NOT cleared" not in se + assert calls(log) == "" # and the run still stops: the signal is delivered after the clear + + +@pytest.mark.parametrize("sig", ["TERM", "HUP"]) +def test_signal_between_the_read_and_the_clear_still_clears(env, sig): + _, log, clip, bindir = env + (bindir / "pbpaste").write_text(f"#!/bin/sh\ncat {clip}\nkill -{sig} $PPID\nsleep 1\n") + r = run(env, yes_args()) + assert r.returncode == 130, out(r) + assert cleared_by(clip.read_text()) == "A" + assert calls(log) == "" + + +def test_lock_contention_exits_with_a_message_after_the_wait(tmp_path, monkeypatch, capsys): + m = _load_module() + monkeypatch.setenv("SECRETS_COLLECT_LOCK_DIR", str(tmp_path)) + monkeypatch.setattr(m, "LOCK_WAIT", 0.3) + with m.clipboard_lock(): + t0 = time.monotonic() + with pytest.raises(SystemExit) as ei: + with m.clipboard_lock(): + pytest.fail("got a lock that another holder has") + assert ei.value.code == 1 + assert time.monotonic() - t0 >= 0.3 # it retried, it did not give up at once + assert "another secrets-collect run holds the clipboard lock" in capsys.readouterr().err + with m.clipboard_lock(): # and the lock is released when the holder leaves + pass + + +@pytest.mark.skipif(os.geteuid() == 0, reason="root opens a mode-000 file") +def test_unopenable_lock_file_is_reported_as_the_lock(env, tmp_path): + _, log, clip, _ = env + (tmp_path / "lock").mkdir() + f = tmp_path / "lock" / "secrets-collect.lock" + f.write_text("") + f.chmod(0) + r = run(env, yes_args()) + assert r.returncode == 1 + assert f"could not open the lock file {f}" in r.stderr + assert "could not read the clipboard" not in r.stderr + assert clip.read_text() == VALUE and calls(log) == "" + + +# --- findings 3, 4: partial stores --------------------------------------------------------- + +TWO = ["--secret", "A=a", "--secret", "B=b"] + + +def test_partial_store_failure_names_stored_and_not_stored(env): + _, log, _, _ = env + r = run(env, TWO, stdin="v1\nv2\ny\n", extra_env={"FAIL_NAME": "B"}) + assert r.returncode == 1 + assert "stored=[A] not_stored=[B]" in r.stderr + assert "PARTIAL" in r.stderr + assert "ARGV: set A" in calls(log) + assert "nothing was stored" not in r.stderr + + +def test_first_store_failure_says_nothing_stored(env): + r = run(env, TWO, stdin="v1\nv2\ny\n", extra_env={"FAIL_NAME": "A"}) + assert r.returncode == 1 + assert "stored=[] not_stored=[A, B]" in r.stderr + assert "nothing was stored" in r.stderr and "PARTIAL" not in r.stderr + + +def test_ctrl_c_during_store_is_not_reported_as_nothing_stored(env): + _, log, _, _ = env + r = run(env, TWO + ["--secret", "C=c"], stdin="v1\nv2\nv3\ny\n", extra_env={"INT_NAME": "B"}) + assert r.returncode == 130 + assert "nothing was stored" not in out(r) + assert "stored=[A] not_stored=[C] unknown=[B]" in r.stderr + + +def test_sigterm_during_store_gets_the_partial_report(env): + r = run(env, TWO + ["--secret", "C=c"], stdin="v1\nv2\nv3\ny\n", extra_env={"TERM_NAME": "B"}) + assert r.returncode == 130 + assert "stored=[A] not_stored=[C] unknown=[B]" in r.stderr + + +def test_a_burst_of_signals_does_not_cut_the_partial_report_short(env): + r = run(env, TWO + ["--secret", "C=c"], stdin="v1\nv2\nv3\ny\n", extra_env={"BURST_NAME": "B"}) + assert r.returncode == 130 + assert "Traceback" not in r.stderr + assert "stored=[A] not_stored=[C] unknown=[B]" in r.stderr + + +def test_interrupt_during_notify_says_so_and_not_storing(env): + _, log, _, bindir = env + (bindir / "python3").write_text("#!/bin/sh\nkill -INT $PPID\nsleep 5\n") + (bindir / "python3").chmod(0o755) + r = run(env, TWO + ["--notify-to", "x"], stdin="v1\nv2\ny\n") + assert r.returncode == 130 + assert "Interrupted while notifying" in r.stderr + assert "while storing" not in r.stderr and "PARTIAL" not in r.stderr + assert "ARGV: set A" in calls(log) and "ARGV: set B" in calls(log) + + +def test_eof_at_confirmation_says_nothing_stored(env): + r = run(env, ["--secret", "A=a"], stdin="v1\n") + assert r.returncode == 1 + assert "nothing was stored" in out(r) + + +# --- finding 5: no value characters in the agent's transcript ------------------------------- + +def test_bad_shape_stores_nothing_and_echoes_no_characters(env): + _, log, clip, _ = env + clip.write_text("ab!#$ cd") + r = run(env, yes_args("A=a:8")) + assert r.returncode == 1 + assert calls(log) == "" + o = out(r) + for leaked in ("!", "#", "$", "ab", "cd"): + assert leaked not in o.replace("Aborted", "").replace("abort", ""), leaked + assert "punctuation" in o and "whitespace" in o + + +def test_non_utf8_clipboard_aborts_without_the_byte(env): + _, log, clip, bindir = env + (bindir / "pbpaste").write_text("#!/bin/sh\nprintf 'ab\\351cd'\n") + r = run(env, yes_args("A=a:5")) + assert r.returncode == 1 + assert calls(log) == "" + o = out(r) + assert "0xe9" not in o and "position" not in o + assert "ab" not in o and "\\xe9" not in o and "cd" not in o + assert cleared_by(clip.read_text()) == "A" # the decode-failure path cleared it too + + +def test_pbpaste_gets_the_utf8_locale_like_pbcopy(env): + _, log, clip, bindir = env + (bindir / "pbpaste").write_text(f'#!/bin/sh\necho "$LC_CTYPE" > {clip}.lc\ncat {clip}\n') + r = run(env, yes_args(), extra_env={"LC_CTYPE": "C"}) + assert r.returncode == 0, out(r) + assert Path(f"{clip}.lc").read_text().strip() == "UTF-8" + + +# --- finding 6: pty / identical values ------------------------------------------------------- + +def test_same_clipboard_for_two_names_is_refused_on_a_tty(env, tmp_path): + _, log, clip, bindir = env + (tmp_path / "clip2").write_text("fresh2VALUE0123") + (bindir / "pbpaste").write_text( + f"#!/bin/sh\nn=$(cat {tmp_path}/cnt 2>/dev/null || echo 0); n=$((n+1)); echo $n > {tmp_path}/cnt\n" + f"if [ $n -ge 3 ]; then cat {tmp_path}/clip2; else cat {clip}; fi\n") + # interactive (no --yes): Enter for A; Enter for B (same clipboard: refused); Enter again + # (fresh copy); then the final confirmation + rc, so, se = run_pty(env, ["--secret", f"A=a:{LEN}", "--secret", f"B=b:{LEN}", "--clipboard"], + b"\n\n\ny\n") + assert rc == 0, se + assert "identical to a value already collected" in so + text = calls(log) + assert text.count(VALUE) == 1 # the stale read never became B + assert text.index(VALUE) < text.index("fresh2VALUE0123") + + +def test_yes_with_two_secrets_is_refused_even_on_a_tty(env): + _, log, clip, _ = env + rc, so, se = run_pty(env, ["--secret", f"A=a:{LEN}", "--secret", f"B=b:{LEN}", + "--clipboard", "--yes"], b"") + assert rc == 2, se + assert calls(log) == "" + assert clip.read_text() == VALUE + + +# --- finding 7 --------------------------------------------------------------------------- + +def test_yes_without_clipboard_and_piped_stdin_refused(env): + _, log, _, _ = env + r = run(env, ["--secret", "A=a", "--yes"], stdin="pipedVALUE\n") + assert r.returncode == 2 + assert calls(log) == "" + + +# --- finding 8 ----------------------------------------------------------------------------- + +def test_length_mismatch_aborts_without_reading_stdin(env): + _, log, _, _ = env + r = run(env, yes_args("A=a:32"), stdin="y\n") + assert r.returncode == 1 + assert calls(log) == "" + assert "Use it anyway" not in r.stdout + assert "expected length is 32" in r.stdout + + +def test_literal_does_not_waive_the_length_in_no_terminal_mode(env): + _, log, _, _ = env + r = run(env, ["--secret", "A=a:32", "--literal", "--clipboard", "--yes"], stdin="y\n") + assert r.returncode == 1 + assert calls(log) == "" + + +def test_interactive_length_mismatch_still_asks(env): + _, log, _, _ = env + rc, so, se = run_pty(env, ["--secret", "A=a:32", "--clipboard"], b"\ny\ny\n") + assert rc == 0, se + assert "Use it anyway" in so + assert VALUE in calls(log) + + +# --- findings 5/12b: other aborts ------------------------------------------------------------- + +def test_empty_clipboard_aborts_not_loops(env): + _, log, clip, _ = env + clip.write_text(" \n") + r = run(env, yes_args()) + assert r.returncode == 1 + assert calls(log) == "" + assert "empty" in r.stderr + + +def test_pbpaste_failure_aborts(env): + _, log, clip, bindir = env + (bindir / "pbpaste").write_text("#!/bin/sh\nexit 1\n") + r = run(env, yes_args()) + assert r.returncode == 1 + assert calls(log) == "" + assert clip.read_text() == VALUE # nothing was read, so nothing is overwritten + + +def test_multi_secret_clipboard_without_tty_refused_with_and_without_yes(env): + _, log, _, _ = env + for extra in (["--yes"], []): + r = run(env, ["--secret", "A=a:15", "--secret", "B=b:15", "--clipboard", *extra]) + assert r.returncode == 2 + assert calls(log) == "" + + +# --- finding 10 -------------------------------------------------------------------------- + +def test_banner_does_not_promise_a_confirmation_under_yes(env): + r = run(env, yes_args()) + assert "until you confirm" not in r.stdout + env[2].write_text(VALUE) # the first run cleared it + rc, so, se = run_pty(env, ["--secret", "A=a:15", "--clipboard"], b"\ny\n") + assert "until you confirm" in so