Repository navigation
feat(vars)!: variable values live in the macOS Keychain, not in a plaintext file - #23
Conversation
`mem vars set API_TOKEN` wrote the token into ~/.mem/vars.json in cleartext. 0600 stops other users and nothing else — not a backup, not a synced folder, not an npm postinstall running as you, not a stolen unlocked disk. For a tool whose first principle is privacy, that file was the weakest thing in it. Values now live in the Keychain (service `mem-cli-vars`, account = the variable name), encrypted at rest and mediated by the OS. vars.json is demoted to an index of which variables exist. The secret never enters argv. `security -w <secret>` — the documented form — puts it in the process table for any `ps` to read, and the prompting alternative needs a tty (with a pipe it exits 2; omitting -w silently stores an *empty* password). So writes go over stdin to `security -i`, hex-encoded with -X: no argv exposure, and no quoting scheme to get wrong for a value carrying quotes, backslashes or newlines. Reads use -g rather than -w, because -w prints printable data and binary data identically — a 32-char hex API key would decode into garbage. Migration is confirm-then-delete, per variable, under the existing lock: write, read back, compare, and only then rewrite vars.json without the value. Every failure mode leaves the plaintext copy for the next attempt. It runs on first use and is idempotent. Degradation is loud. With the Keychain unavailable, `mem vars set` fails and stores nothing — no plaintext fallback under a promise of encryption. Values that could not be migrated keep working and are listed as `plaintext`, with a warning, every time. Also: `mem vars set NAME` finally hides what is typed, as the README always claimed, and warns when a value is passed inline that it was visible to `ps` and captured into the user's own history. Honest limits: `security -i` truncates command lines at 4096 chars and executes the head — observed storing a silently truncated secret — so values over ~2 KB are refused rather than mangled; `mem forget` now costs one `security` call per stored variable, because matching a value means reading it. Tests stub the subprocess boundary with an in-memory model of `security` whose -g output format is reproduced from recorded real output, so the default suite never touches the developer's login keychain. The genuine end-to-end tests are marked `keychain_live` and use a throwaway keychain.
The constitution says the plain-text files are the only source of truth and forbids storage whose loss would lose user data. Moving variable values into the Keychain contradicts that as written, so it is amended in public with the argument attached rather than left as a quiet exception: a secret is the one kind of data where "you can cat it" is a defect. ADR-009 states what `security` actually does — established by running it, not by reading the man page — and why each alternative loses: doing nothing, an encrypted file with a passphrase, a keyring library, `-w` in argv, a pty, our own hex-in-the-item encoding, and a silent plaintext fallback. It states the cost just as plainly: a subprocess per read, a possible OS prompt, macOS only, and mem now writing outside ~/.mem.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6fee6b51bf
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| for name, value in sorted(pending.items()): | ||
| try: | ||
| keychain.set_secret(name, value) |
There was a problem hiding this comment.
Serialize migration writes with concurrent setters
When first-use migration overlaps mem vars set for the same name in another shell, both operations write the Keychain before taking exclusive_lock(). If the setter writes the new value and this line subsequently writes the legacy value, the later re-read of vars.json cannot detect that the Keychain value was clobbered; both commands can complete with the old credential remaining. Hold the shared lock across the per-name Keychain/index transition or otherwise compare-and-swap the Keychain item.
Useful? React with 👍 / 👎.
| keychain.set_secret(name, value) | ||
| if keychain.get_secret(name) != value: |
There was a problem hiding this comment.
Roll back the Keychain write when verification fails
If set_secret() succeeds but the subsequent read is denied, times out, or returns a mismatch, this function raises after already changing the Keychain. For a new name this leaves an orphaned secret; for an existing name it overwrites the prior credential even though the CLI reports “Nothing was stored.” Preserve and restore the previous item, or delete the newly created item, when verification fails.
Useful? React with 👍 / 👎.
| _sync_var_backend() | ||
| # Only the variables this run actually needs are fetched from the | ||
| # Keychain — one subprocess each, and each one a possible OS prompt. | ||
| stored, unreadable = storage.load_var_values(all_vars) |
There was a problem hiding this comment.
Skip Keychain reads for higher-priority variable sources
When a variable is supplied inline or through the environment, this still runs security to fetch its stored value even though resolve_variables() will discard it. Because each lookup may display a Keychain authorization prompt or wait for the 60-second timeout, commands such as mem run group TOKEN=... can be delayed or interrupted unnecessarily. Filter out names already satisfied by inline arguments or os.environ before calling load_var_values().
Useful? React with 👍 / 👎.
mem vars set API_TOKENwrote the value into~/.mem/vars.jsonas plaintext, mode 0600. For a tool whose entire pitch is privacy-first, that was the weakest thing in it: any backup, synced folder, malicious postinstall, or stolen unlocked disk got every credential the user had stored.macOS has a purpose-built answer, and this project has already decided to double down on Apple. Values now go to the Keychain — encrypted at rest under the login password, with access mediated by the OS.
Getting a secret to
securitywithout putting it inargvsecurity add-generic-password -w <secret>puts the secret in the process table, wherepsshows it to every process on the machine. The prompting formsecurityrecommends instead needs a tty: given a pipe it exits 2, and omitting-wsilently stores an empty password.So mem writes through
security -i, which reads commands from stdin — argv is only["/usr/bin/security", "-i"]. The value is hex-encoded with-Xso the interactive tokenizer cannot mangle quotes, backslashes or newlines, while the stored item still holds the real bytes (security find-generic-password -s mem-cli-vars -a NAME -wworks from outside mem).Reads use
-g, not-w:-wprints printable and binary data identically, so a hex-looking API key would come back decoded into garbage.The hazard that forced a hard size limit
security -itruncates a command line at ~4096 bytes and executes the remainder as a new command. Verified independently against a throwaway keychain:A value over the limit is now refused outright:
Degrading honestly
When the Keychain is unavailable — locked, CI, an authorization the user declined —
mem vars setfails, quotingsecurity's own message, and writes nothing. There is no plaintext fallback under a promise of encryption.Confirmed by accident while testing this: a sandboxed run hit an invisible authorization prompt and produced
which is the designed behaviour doing its job.
Legacy plaintext values keep resolving so nobody is locked out, but
mem vars listlabels each rowplaintextand warns every time, and migration retries on every invocation.Migration cannot lose a value
Per variable: write → read back → compare → only then rewrite
vars.json, under the existingexclusive_lock/atomic_write, re-reading the entry first so a concurrentvars setis not clobbered. Idempotent, and every failure leaves the plaintext copy exactly where it was.backendis derived from the absence of a value on read, never trusted from the file — so an entry cannot claim to be encrypted while still holding a secret.Tests
1197 passed (master: 1103), plus 12
keychain_livetests deselected by default that drive the real/usr/bin/securityagainst a keychain they create and delete intmp_path. The default suite never touches the developer's login keychain; I ran the live set and verified the login keychain was untouched.Notes
PHILOSOPHY.mdandARCHITECTURE.mdwere amended beyond the original brief because both stated, incorrectly, that values live invars.json.CLAUDE.mdis gitignored, so its structure block still does not listkeychain.py.Breaking change
Values move out of
vars.json. Migration is automatic on first use; nothing needs to be re-entered. A machine without a usable Keychain can no longer store new variables at all — deliberately, since the alternative is writing plaintext while claiming otherwise.