Skip to content

feat(vars)!: variable values live in the macOS Keychain, not in a plaintext file - #23

Merged
matinsaurralde merged 2 commits into
masterfrom
feat/13-keychain
Aug 4, 2026
Merged

matinsaurralde merged 2 commits into
masterfrom
feat/13-keychain

Conversation

@matinsaurralde

Copy link
Copy Markdown
Owner

mem vars set API_TOKEN wrote the value into ~/.mem/vars.json as 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 security without putting it in argv

security add-generic-password -w <secret> puts the secret in the process table, where ps shows it to every process on the machine. The prompting form security recommends instead needs a tty: given a pipe it exits 2, and omitting -w silently 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 -X so 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 -w works from outside mem).

Reads use -g, not -w: -w prints 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 -i truncates a command line at ~4096 bytes and executes the remainder as a new command. Verified independently against a throwaway keychain:

pedido   100 chars -> guardado   100 chars  OK
pedido  4000 chars -> guardado  4000 chars  OK
pedido  5000 chars -> guardado     0 chars  LOST
                      (rc=1  security: unknown command "AAAAAAAA…")

A value over the limit is now refused outright:

Error: value is too large for the Keychain: `security` truncates commands
longer than 3900 bytes, and this one is 10070. Store large secrets in a file
and keep the path in the variable instead.
Nothing was stored. mem does not fall back to writing the value in plaintext.

Degrading honestly

When the Keychain is unavailable — locked, CI, an authorization the user declined — mem vars set fails, quoting security'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

Error: `security` did not answer within 60s — the Keychain may be waiting for
an authorization you did not see
Nothing was stored. mem does not fall back to writing the value in plaintext.

which is the designed behaviour doing its job.

Legacy plaintext values keep resolving so nobody is locked out, but mem vars list labels each row plaintext and 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 existing exclusive_lock/atomic_write, re-reading the entry first so a concurrent vars set is not clobbered. Idempotent, and every failure leaves the plaintext copy exactly where it was.

backend is 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_live tests deselected by default that drive the real /usr/bin/security against a keychain they create and delete in tmp_path. The default suite never touches the developer's login keychain; I ran the live set and verified the login keychain was untouched.

Notes

  • ADR renumbered from 009 to 010 — 009 was taken by the picks ranking that merged first. All cross-references updated.
  • PHILOSOPHY.md and ARCHITECTURE.md were amended beyond the original brief because both stated, incorrectly, that values live in vars.json.
  • CLAUDE.md is gitignored, so its structure block still does not list keychain.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.

`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.
@matinsaurralde
matinsaurralde merged commit 8ee7236 into master Aug 4, 2026
5 checks passed
@matinsaurralde
matinsaurralde deleted the feat/13-keychain branch August 4, 2026 05:09

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/mem/storage.py

for name, value in sorted(pending.items()):
try:
keychain.set_secret(name, value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/mem/storage.py
Comment on lines +1263 to +1264
keychain.set_secret(name, value)
if keychain.get_secret(name) != value:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/mem/cli.py
_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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant