Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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.
The sentinel carries the date, time and zone, and the error adds its age;
if the value was copied before the stamp, re-collect both names.
A run that stored but could not clear the clipboard exits 3 instead of 0.

### Fixed

Expand Down
47 changes: 34 additions & 13 deletions skills/sudo-secretspec/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,18 @@ run, on a pty or not:
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).
which names the run that consumed the copy and carries its date, time, zone and age
(`... cleared by the run for NAME at 2026-10-26T01:40:59-0400 ...`, "N s ago"/"N min ago"),
and exits 1. **The age never proves the loser is harmless: the message is always
conditional.** A copy made after the stamp would have replaced the sentinel, so while the
sentinel is on the clipboard every copy the operator made was before it. **If the operator told
you they copied the value for the loser's name** (whenever they said so: their message
arrives after the copy, often after the stamp, so never compare the stamp with the message),
the named run may have taken that copy, so **both names must be re-collected, one at a time**,
each after a fresh copy (re-running only the loser leaves the named run holding the wrong
value, and its length would still pass). **Only if the operator confirms they had not copied
yet:** copy the value again. **Unsure: re-collect both.** Never read an old sentinel as "no
other run is involved".
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
Expand All @@ -213,8 +220,12 @@ than retrying, and **overwrites the clipboard itself right after the read**
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
next run sees a fresh copy or the sentinel, never the previous secret. **A failed
overwrite prints `WARNING: ... NOT cleared` and the run exits 3 instead of 0** (still
stored and notified, `--dry-run` included; its last line says "...the clipboard was NOT
cleared: overwrite it yourself, exit 3"): treat 3 as "done, but the secret may still be on the
pasteboard", never as a clean success. A run that fails otherwise keeps its code (1, 2, 130).
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
Expand All @@ -230,14 +241,21 @@ since a regex does not waive it. For those, and only those, use `--literal` with

```bash
python3 $S --secret 'NAME=desc:32' --clipboard --yes
printf 'cleared' | ~/ops/site-private/bin/clip # regardless of the exit status: `;`, never `&&`
# ONLY if it exited 3, its stdout or stderr says `NOT cleared`, or it gave no report at all
# (killed or timed out: exit 124/137, or no output). After a run that cleared, do NOT run this line.
# A run that never read the clipboard (exit 2, `bad --secret`/`bad secret name`/`bad regex`,
# `could not open the lock file`, `could not read the clipboard`): fix the call and re-run it,
# that run reads, clears and reports any sentinel; run this line only if you give up on the name.
printf 'cleared' | ~/ops/site-private/bin/clip
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).
The script clears the clipboard itself, so the `printf` line is only for the runs where
the value can still be on the pasteboard (a failed clear, or a run that died before it reported),
or for giving up on a name after a run that never read the clipboard. Do not run it before
re-running: such a run never looked at the clipboard, which may hold another run's sentinel.
After a run that cleared it would overwrite the sentinel, which names the run that consumed the
copy, and the next run could no longer tell whose copy it was.

Verified 2026-10-26 (stub `sudo-secretspec`/`pbpaste`/`pbcopy`; no live vault).

Expand Down Expand Up @@ -488,7 +506,10 @@ listener cannot reach private data through it.
an expiry you write down. A fine-grained token is `github_pat_` plus 82 characters (93 in all).
2. **Declare:** `sudo-secretspec add NAME --description "..." --optional --reason "..."`
(`--optional` so `check` stays green on hosts that never set it).
3. **Store:** the clipboard route above; then overwrite the clipboard.
3. **Store:** the clipboard route above. With `secrets-collect.py` the script clears the clipboard
itself; overwrite it by hand only on exit 3, `NOT cleared` in stdout or stderr, or no report at all,
or to give up on the name after a run that never read the clipboard (the rule under "An agent
with no terminal"); otherwise you would erase the sentinel's consumer name.
4. **Prove its reach without printing it.** Run a throwaway script under `run` that prints only
the length, the prefix and HTTP statuses, then delete the script:
```bash
Expand Down
79 changes: 61 additions & 18 deletions skills/sudo-secretspec/scripts/secrets-collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,17 @@
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.
clear reads the sentinel (it carries the date, time and zone; the error adds the age) and
fails, naming the run that consumed the copy. The age never proves that run is unrelated:
a copy made after the stamp would have replaced it, so if the operator copied the value for
this name at all, that run may have taken it and BOTH names must be re-collected, one at a
time; only if the operator had not copied yet: copy the value again; unsure: both. A same-name sentinel only needs a new copy. A SIGKILL or power
loss between the read and the clear leaves the value on the
pasteboard. A failing pbcopy prints a WARNING and the run (still storing and notifying, also
under --dry-run) exits 3 instead of 0, its last line saying the clipboard was NOT cleared;
a run that fails otherwise keeps its own code (1, 2, 130). 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.
Expand All @@ -64,6 +69,7 @@

import argparse
import contextlib
import datetime
import fcntl
import getpass
import os
Expand All @@ -80,27 +86,46 @@
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)")
AGE_IN_MINUTES_FROM = 60 # seconds: the age is shown as "N s ago" below this, "N min ago" from it
_CONSUMER = re.compile(r"cleared by the run for (\S+) at "
r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d[+-]\d{4}|\d\d:\d\d:\d\d)") # 2nd: old form
_clear_failed = False # set by clear_clipboard when pbcopy failed; main() resets it and exits 3


def is_sentinel(value: str) -> bool:
return value == CLEARED_WORD or value.startswith(CLEARED_PREFIX)


def _sentinel_age(at: str) -> float | None:
"""Seconds since the sentinel's stamp, or None when it has no date (the old HH:MM:SS form),
cannot be parsed or lies in the future."""
try:
age = time.time() - datetime.datetime.strptime(at, "%Y-%m-%dT%H:%M:%S%z").timestamp()
except ValueError:
return None
return age if age >= 0 else None


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."""
"""Why a sentinel was read. Another name's sentinel is ALWAYS conditional, whatever its age:
the run that consumed the copy may have taken a copy meant for THIS name, and the age cannot
say whether the operator copied for this name before that run read the clipboard."""
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()
age = _sentinel_age(at)
ago = ""
if age is not None:
ago = (f" ({int(age)} s ago)" if age < AGE_IN_MINUTES_FROM
else f" ({int(age // 60)} min ago)")
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")
f"consumed the copy at {at}{ago}; copy the value again")
return (f"the clipboard holds a cleared-clipboard sentinel: the run for {who} consumed a copy "
f"at {at}{ago}; if the operator copied the value for {name} before {at}, {who} now "
f"holds it: re-collect {who} too; if nothing was copied since, only copy again")


class StoreError(Exception):
Expand Down Expand Up @@ -160,15 +185,17 @@ def _ignore_cancel_signals() -> None:


def _not_cleared(e: BaseException) -> None:
global _clear_failed
_clear_failed = True
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")
mark = (f"{CLEARED_PREFIX} by the run for {name} at "
f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')}, copy the value again")
try:
subprocess.run(["pbcopy"], input=mark, text=True, check=True,
capture_output=True, env=_pb_env(), timeout=15)
Expand Down Expand Up @@ -377,6 +404,8 @@ def notify(role: str, names: list[tuple[str, int]], reason: str) -> None:


def main() -> int:
global _clear_failed
_clear_failed = False # in-process callers (tests) run main more than once
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; "
Expand All @@ -396,11 +425,25 @@ def main() -> int:
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)")
"cleared after the read, and a lock stops two runs at once. A run that "
"finds another name's sentinel prints its date, time, zone and age: compare "
"the stamp with when the value for your name was copied (before it: "
"re-collect both names one at a time; nothing copied since: copy again). "
"Exit 3 = done, but the clipboard could not be cleared: overwrite it "
"yourself. Needed for any --clipboard run with a non-tty stdin. Without "
"--clipboard it needs a terminal (hidden prompt)")
a = ap.parse_args()

rc = _run(a)
if rc == 0 and _clear_failed:
what = "dry run, nothing stored" if a.dry_run else "stored"
print(f"{what}, but the clipboard was NOT cleared: overwrite it yourself, exit 3",
flush=True)
return 3
return rc


def _run(a: argparse.Namespace) -> int:
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 "
Expand Down
Loading
Loading