From 851f9ed4ef2092bb517ab1ada25c1c7a1a8fad5a Mon Sep 17 00:00:00 2001 From: Matias Date: Tue, 4 Aug 2026 01:58:45 -0300 Subject: [PATCH 1/2] feat(vars)!: store variable values in the macOS Keychain, not plaintext MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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 ` — 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. --- pyproject.toml | 3 +- src/mem/cli.py | 155 ++++++-- src/mem/keychain.py | 352 ++++++++++++++++++ src/mem/models.py | 41 +- src/mem/storage.py | 309 +++++++++++++++- src/mem/variables.py | 22 +- tests/conftest.py | 162 +++++++- tests/test_e2e.py | 7 +- tests/test_keychain.py | 803 ++++++++++++++++++++++++++++++++++++++++ tests/test_variables.py | 40 +- 10 files changed, 1827 insertions(+), 67 deletions(-) create mode 100644 src/mem/keychain.py create mode 100644 tests/test_keychain.py diff --git a/pyproject.toml b/pyproject.toml index 241396f..40ccd62 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -76,10 +76,11 @@ testpaths = ["tests"] # Branch coverage is on because mem is mostly branching I/O: line coverage # reports a `try/except` or an `if not path.exists()` as covered after the # happy path alone, which is exactly the half that never gets tested. -addopts = "-m 'not ai and not perf' --cov=mem --cov-branch --cov-report=term-missing" +addopts = "-m 'not ai and not perf and not keychain_live' --cov=mem --cov-branch --cov-report=term-missing" markers = [ "ai: requires the real on-device Apple Foundation Models runtime (deselected by default)", "perf: wall-clock measurement, too machine-dependent to gate a PR (deselected by default)", + "keychain_live: drives the REAL /usr/bin/security against a throwaway keychain (deselected by default)", ] [tool.coverage.run] diff --git a/src/mem/cli.py b/src/mem/cli.py index 6dca595..fa3f468 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -811,9 +811,18 @@ def run( resolved: dict[str, tuple[str, str]] = {} if all_vars: - vars_data = storage.read_vars_file() unique_var_list = list(all_vars.values()) + _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) + if unreadable: + err_console.print( + f"[yellow]![/] Could not read from the Keychain: " + f"{safe(', '.join(sorted(unreadable)))}" + ) + # In --yes mode, check for unresolvable variables first if yes: missing = [] @@ -822,7 +831,7 @@ def run( if ( name not in inline_args and name not in os.environ - and name not in vars_data.vars + and name not in stored and v.default is None ): missing.append(name) @@ -836,7 +845,7 @@ def run( resolved = resolve_variables( unique_var_list, inline_args, - vars_data.vars, + stored, allow_prompt=not yes, ) @@ -845,14 +854,10 @@ def run( for name, (value, source) in resolved.items(): console.print(f" [green]✓[/] ${safe(name)} resolved from {safe(source)}") - # Update last_used for store-resolved variables - updated_store = False - for name, (_value, source) in resolved.items(): - if source == "store" and name in vars_data.vars: - vars_data.vars[name].last_used = int(time.time()) - updated_store = True - if updated_store: - storage.write_vars_file(vars_data) + storage.touch_vars( + [name for name, (_value, source) in resolved.items() if source == "store"], + int(time.time()), + ) # Values are handed to the shell through the environment and the command is # run verbatim, so the shell expands $NAME itself. Splicing the value into @@ -1467,9 +1472,39 @@ def saved_edit(global_flag: bool) -> None: # --- Variable store subgroup --- +def _sync_var_backend() -> None: + """Move any plaintext values into the Keychain, out loud. + + Called from every command that reads or writes the variable store, so the + migration happens on first use rather than waiting for a maintenance + command nobody runs. It is a no-op — one file read — once the store is + clean. + + Both outcomes are announced on stderr, every time. A silent migration + would leave the user unable to tell whether their tokens are encrypted, + and a silent *failure* would leave them believing they are when they are + not. stderr keeps it out of `--json` and out of pipes. + """ + from mem import storage + + result = storage.migrate_vars_to_keychain() + if result.migrated: + err_console.print( + f"Moved {result.migrated} variable value(s) from " + f"{safe(str(storage.VARS_FILE))} into the macOS Keychain." + ) + if result.failed: + err_console.print( + f"[yellow]![/] {len(result.failed)} variable(s) are still stored " + f"in plaintext: {safe(', '.join(result.failed))}" + ) + if result.reason: + err_console.print(f" {safe(result.reason)}") + + @cli.group(name="vars") def vars_grp() -> None: - """Manage persistent variables.""" + """Manage persistent variables (values live in the macOS Keychain).""" @vars_grp.command(name="set") @@ -1479,37 +1514,66 @@ def vars_set(name: str, value: str | None) -> None: """Set a persistent variable value.""" import re - from mem import storage - from mem.models import StoredVariable + from mem import keychain, storage if not re.match(r"^[A-Z][A-Z0-9_]+$", name): raise click.ClickException( f"Invalid variable name '{name}'. Use uppercase letters, digits, and underscores." ) + _sync_var_backend() + if value is None: - value = click.prompt(f" Value for {name}") + # hide_input because this is the prompt the README promises behaves + # "like sudo" — and because the value typed here is, by construction, + # the one the user did not want on their screen. + value = click.prompt(f" Value for {name}", hide_input=True) + else: + # mem's own argv is the last place a secret can still leak: it was + # visible to `ps` while this command ran, and mem's shell hook has + # already written the whole command line into the history it keeps. + err_console.print( + "[dim]Note: the value was passed on the command line, so it is in " + "your shell history and was visible to `ps`. Run `mem vars set " + f"{safe(name)}` with no value for a hidden prompt.[/]" + ) - vars_data = storage.read_vars_file() - vars_data.vars[name] = StoredVariable(value=value, last_used=0) - storage.write_vars_file(vars_data) - err_console.print(f"Stored: {name}") + try: + storage.set_var(name, value) + except keychain.KeychainError as exc: + # No plaintext fallback, deliberately. See ADR-009: a tool that + # promises the Keychain and quietly writes cleartext when the Keychain + # is busy is more dangerous than one that never promised anything. + raise click.ClickException( + f"{exc}\nNothing was stored. mem does not fall back to writing " + f"the value in plaintext." + ) from exc + + err_console.print(f"Stored: {name} (macOS Keychain)") @vars_grp.command(name="list") @click.option("--json", "as_json", is_flag=True, help="Output as JSON") def vars_list(as_json: bool) -> None: """List stored variables (values hidden).""" - from mem import storage + from mem import keychain, storage + + _sync_var_backend() vars_data = storage.read_vars_file() + reason = keychain.unavailable_reason() if as_json: output = { "variables": [ - {"name": name, "last_used": sv.last_used} + {"name": name, "backend": sv.backend, "last_used": sv.last_used} for name, sv in sorted(vars_data.vars.items()) - ] + ], + "keychain": { + "service": keychain.SERVICE, + "available": reason is None, + "reason": reason, + }, } click.echo(json.dumps(output, indent=2)) return @@ -1518,13 +1582,32 @@ def vars_list(as_json: bool) -> None: console.print("No stored variables.") return - console.print("\nStored variables (values hidden)") + console.print( + f"\nStored variables (values hidden) — macOS Keychain, service " + f"'{safe(keychain.SERVICE)}'" + ) + plaintext = 0 for name, sv in sorted(vars_data.vars.items()): if sv.last_used == 0: time_str = "never used" else: time_str = f"last used {_relative_time(sv.last_used)}" - console.print(f" {safe(fit(name, 20))} {time_str}") + # The backend is printed per value, not once for the store: a store + # that is half migrated is exactly the case where a single header + # would be a lie about half the rows. + if sv.backend == "plaintext": + plaintext += 1 + where = "[yellow]plaintext[/]" + else: + where = "[green]keychain [/]" + console.print(f" {safe(fit(name, 20))} {where} {time_str}") + + if plaintext: + console.print( + f"\n [yellow]![/] {plaintext} value(s) are still in plaintext in " + f"{safe(str(storage.VARS_FILE))}." + ) + console.print(f" {safe(reason or 'Run any mem vars command to retry.')}") console.print() @@ -1532,15 +1615,16 @@ def vars_list(as_json: bool) -> None: @click.argument("name") def vars_remove(name: str) -> None: """Remove a stored variable.""" - from mem import storage + from mem import keychain, storage - vars_data = storage.read_vars_file() + try: + existed = storage.remove_var(name) + except keychain.KeychainError as exc: + raise click.ClickException(f"{exc}\n'{name}' was left untouched.") from exc - if name not in vars_data.vars: + if not existed: raise click.ClickException(f"Variable '{name}' not found.") - del vars_data.vars[name] - storage.write_vars_file(vars_data) err_console.print(f"Removed: {name}") @@ -1562,10 +1646,15 @@ def vars_clear(yes: bool) -> None: if not click.confirm(f"Clear all {count} variable(s)?", default=False): return - from mem.models import VarsFile - - storage.write_vars_file(VarsFile()) - err_console.print(f"Cleared {count} variable(s).") + removed, kept = storage.clear_vars() + err_console.print(f"Cleared {removed} variable(s).") + if kept: + raise click.ClickException( + "Could not remove from the Keychain: " + + ", ".join(kept) + + "\nThey are still listed by `mem vars list`; try again once the " + "Keychain is unlocked." + ) # --- Agent access (MCP) --- diff --git a/src/mem/keychain.py b/src/mem/keychain.py new file mode 100644 index 0000000..0b69ea1 --- /dev/null +++ b/src/mem/keychain.py @@ -0,0 +1,352 @@ +"""macOS Keychain backend for mem's variable store. + +mem stores variable *values* — API tokens, database passwords, bastion +hostnames — in the login Keychain instead of in a plaintext file. The +Keychain encrypts them at rest under the user's login password and mediates +access through the OS, which a 0600 file cannot do: anything running as the +user (a backup, a synced folder, a malicious postinstall script, someone with +the unlocked disk) can read a 0600 file, and nothing warns you about it. + +The whole backend is `/usr/bin/security`, driven with `subprocess`. That is a +hard requirement, not a preference: mem takes no new dependencies +(Constitution Principle I forbids anything that could drag a networking +library in), and `security` ships with every macOS install, so there is +nothing to install and nothing to trust beyond the OS itself. + +Three details of `security` shape this module, all established by running it +rather than by reading the man page: + +**1. The secret never goes in argv.** ``security add-generic-password -w +`` is the documented form, and it is also the form that puts the +secret in the process table where any process on the machine can read it with +``ps``. ``security``'s own help says so ("Use of the -p or -w options is +insecure"). Its suggested alternative — ``-w`` as the last option, which +prompts — needs a controlling terminal: with a pipe on stdin it exits 2, and +with ``-w`` omitted entirely it silently stores an *empty* password. So the +prompt is unusable from a program. What does work is ``security -i``, the +tool's interactive mode: it reads command lines from **stdin**, so the secret +travels down a pipe our own process owns and argv contains only +``["/usr/bin/security", "-i"]``. + +**2. Values are handed over hex-encoded (``-X``).** ``security -i`` splits +its input lines into words with shell-like quoting, so a value containing a +quote, a backslash or a newline could not be passed as text without inventing +a quoting scheme — and a quoting bug here means a silently corrupted secret. +``-X`` takes the password as hexadecimal, which is ``[0-9a-f]`` and therefore +immune to the tokenizer. The value is still stored as the real bytes: reading +the item back with ``security find-generic-password -w`` outside mem returns +the actual secret, so mem is not a lock-in layer over your own credentials. + +**3. Reading back uses ``-g``, not ``-w``.** ``-w`` prints the password raw +when it is printable and as bare lowercase hex when it is not — and those two +are indistinguishable, so a perfectly ordinary 32-character hex API key reads +back as 16 bytes of binary garbage. ``-g`` is unambiguous: it prints +``password: 0x ""`` whenever the value contains anything +outside printable ASCII (or a backslash), and ``password: ""`` when it +does not — and in that second case no escaping is possible, so stripping the +outer quotes is exact. + +The one honest limitation: ``security -i`` truncates input lines at 4096 +characters, and it does not fail cleanly when it does — it executes the +truncated head as a command. Observed directly: an 8 KB value produced a +Keychain item holding a silently truncated secret. Values are therefore +length-checked against the exact command line before it is sent, and a value +that would not fit is refused (:class:`KeychainValueTooLong`) rather than +half-stored. That caps a value at roughly 2 KB — ample for tokens and +passwords, not enough for a 4096-bit private key. +""" + +from __future__ import annotations + +import os +import re +import subprocess +import sys + +# The generic-password "service" every mem variable is filed under. Chosen to +# be unmistakably mem's own and greppable: searching Keychain Access for +# "mem-cli" finds exactly mem's items and nothing else. +SERVICE = "mem-cli-vars" + +SECURITY_BIN = "/usr/bin/security" + +# `security` exit code for errSecItemNotFound. It is the one non-zero status +# that is not an error: it means "no such variable", which callers handle. +_ITEM_NOT_FOUND = 44 + +# Ceiling on one `security -i` input line. The real limit is 4096 characters, +# past which the tool splits the line and runs the head as a command — which +# for us would mean storing a truncated secret. 3900 leaves room for the +# terminating newline and for any future option added to the command. +_MAX_COMMAND_LINE = 3900 + +# Every `security` call is bounded. The Keychain can put up an authorization +# dialog, and mem runs inside the user's shell prompt: without a timeout a +# dialog nobody is looking at would hang the terminal forever. 60s is long +# enough for a user who is actually there to click "Allow". +_TIMEOUT_SECONDS = 60 + +# Variable names and keychain paths are interpolated into the command line +# that `security -i` parses, so both are restricted to characters that cannot +# start a new word, quote, or command. Without this a variable named +# `A\ndelete-generic-password ...` would be a command injection into our own +# subprocess — the exact class of bug this module exists to avoid. +_SAFE_NAME = re.compile(r"^[A-Za-z0-9_.-]+$") +_SAFE_PATH = re.compile(r"^[A-Za-z0-9_./-]+$") + +# Prefix of the line `find-generic-password -g` writes to stderr. +_PASSWORD_PREFIX = "password: " + +# Environment override naming the keychain to use. Unset — the normal case — +# means the user's default (login) keychain. It exists so the end-to-end test +# can point mem at a throwaway keychain instead of the developer's own, and it +# doubles as the escape hatch for anyone who keeps credentials in a separate +# keychain. +KEYCHAIN_ENV = "MEM_KEYCHAIN" + + +class KeychainError(RuntimeError): + """A Keychain operation failed. The message is meant for the user.""" + + +class KeychainUnavailable(KeychainError): + """The Keychain cannot be reached at all. + + Not macOS, no `security` binary, a locked keychain, or a user who declined + the access prompt. Separate from :class:`KeychainError` because it is the + case where mem must refuse to store a secret rather than fall back to + plaintext. + """ + + +class KeychainValueTooLong(KeychainError): + """The value does not fit in one `security -i` command line.""" + + +def unavailable_reason() -> str | None: + """Why the Keychain cannot be used, or None if it looks usable. + + Deliberately cheap and syntactic: platform and binary only, no subprocess. + A locked keychain or a declined authorization prompt cannot be detected + without actually performing an operation, so those surface as a + :class:`KeychainUnavailable` from the operation itself, carrying + `security`'s own message. Guessing here would mean either a subprocess on + every `mem run`, or a confident answer that is wrong. + """ + if sys.platform != "darwin": + return f"the macOS Keychain is not available on this platform ({sys.platform})" + if not os.access(SECURITY_BIN, os.X_OK): + return f"{SECURITY_BIN} is missing or not executable" + return None + + +def is_available() -> bool: + """Whether the Keychain backend can be attempted at all.""" + return unavailable_reason() is None + + +def label_for(name: str) -> str: + """Keychain Access display name for a variable. + + The default label is the service name, which would show every mem variable + as an identical row. Prefixing keeps them sorted together and still names + the variable. No spaces: the label goes through the `security -i` + tokenizer. + """ + return f"{SERVICE}:{name}" + + +def _keychain_path() -> str | None: + """The keychain file to operate on, or None for the user's default.""" + path = os.environ.get(KEYCHAIN_ENV) + if not path: + return None + if not _SAFE_PATH.match(path): + raise KeychainError( + f"{KEYCHAIN_ENV} contains characters mem will not pass to " + f"`security`: {path!r}" + ) + return path + + +def _validate_name(name: str) -> None: + """Reject a variable name that could alter the command `security` runs.""" + if not _SAFE_NAME.match(name): + raise KeychainError( + f"Refusing to use {name!r} as a Keychain account name: only " + f"letters, digits, '_', '.' and '-' are allowed." + ) + + +def _run(argv: list[str], stdin: bytes = b"") -> tuple[int, bytes, bytes]: + """Run `security` and return (returncode, stdout, stderr). + + The single point where this module touches the OS, so tests can replace it + with an in-memory keychain and the default suite never goes near the + developer's real one. + """ + try: + proc = subprocess.run( + argv, + input=stdin, + capture_output=True, + timeout=_TIMEOUT_SECONDS, + ) + except FileNotFoundError as exc: # security binary vanished mid-flight + raise KeychainUnavailable(f"{SECURITY_BIN} is not available") from exc + except subprocess.TimeoutExpired as exc: + raise KeychainUnavailable( + f"`security` did not answer within {_TIMEOUT_SECONDS}s — the " + f"Keychain may be waiting for an authorization you did not see" + ) from exc + except OSError as exc: + raise KeychainUnavailable(f"could not run {SECURITY_BIN}: {exc}") from exc + return proc.returncode, proc.stdout, proc.stderr + + +def _fail(action: str, stderr: bytes) -> KeychainUnavailable: + """Build the error for a failed `security` call, quoting its own message. + + `security`'s messages ("The user name or passphrase you entered is not + correct", "User interaction is not allowed") say more about what went + wrong than anything mem could infer, so they are passed through verbatim + rather than replaced with a generic sentence. + """ + detail = stderr.decode("utf-8", errors="replace").strip().splitlines() + message = detail[0] if detail else "no output" + return KeychainUnavailable(f"{action} failed: {message}") + + +def _interactive_line(command: str) -> None: + """Send one command line to `security -i`, raising on failure. + + Length is checked here rather than by the caller because this is the only + place that knows the final line, and a line over the limit is not a + rejected command — it is a truncated one that `security` happily executes. + """ + encoded = command.encode("utf-8") + if len(encoded) > _MAX_COMMAND_LINE: + raise KeychainValueTooLong( + "value is too large for the Keychain: `security` truncates " + f"commands longer than {_MAX_COMMAND_LINE} bytes, and this one " + f"is {len(encoded)}. Store large secrets in a file and keep the " + "path in the variable instead." + ) + code, _out, err = _run([SECURITY_BIN, "-i"], stdin=encoded + b"\n") + if code != 0: + raise _fail("Keychain write", err) + + +def set_secret(name: str, value: str) -> None: + """Store (or replace) a variable's value in the Keychain. + + ``-U`` updates an existing item instead of failing, which makes + ``mem vars set`` on an existing name do what the user means. The value + goes over stdin as hex; see the module docstring for why both halves of + that matter. + """ + _validate_name(name) + payload = value.encode("utf-8") + # `-X ""` is a parse error ("must specify valid hex digits"), so the empty + # value — legitimate: a variable can be deliberately empty — takes the one + # text form with no quoting risk at all. + data = f"-X {payload.hex()}" if payload else '-w ""' + parts = [ + "add-generic-password", + "-U", + "-s", + SERVICE, + "-a", + name, + "-l", + label_for(name), + data, + ] + path = _keychain_path() + if path: + parts.append(path) + _interactive_line(" ".join(parts)) + + +def get_secret(name: str) -> str | None: + """Read a variable's value back, or None if the Keychain has no such item. + + Raises :class:`KeychainError` when the item exists but cannot be read — + a locked keychain, a denied prompt, or output mem does not understand. + Returning None there would be indistinguishable from "never stored", and + mem would go on to prompt the user for a value it already has. + """ + _validate_name(name) + argv = [SECURITY_BIN, "find-generic-password", "-s", SERVICE, "-a", name, "-g"] + path = _keychain_path() + if path: + argv.append(path) + code, _out, err = _run(argv) + if code == _ITEM_NOT_FOUND: + return None + if code != 0: + raise _fail("Keychain read", err) + return parse_password_output(err) + + +def delete_secret(name: str) -> bool: + """Remove a variable from the Keychain. False if it was not there.""" + _validate_name(name) + argv = [SECURITY_BIN, "delete-generic-password", "-s", SERVICE, "-a", name] + path = _keychain_path() + if path: + argv.append(path) + code, _out, err = _run(argv) + if code == _ITEM_NOT_FOUND: + return False + if code != 0: + raise _fail("Keychain delete", err) + return True + + +def parse_password_output(stderr: bytes) -> str: + """Extract the secret from `find-generic-password -g` output. + + Public so the exact format `security` emits can be pinned by tests against + recorded real output — the parsing, not the subprocess, is where a wrong + answer would silently corrupt a credential. + + Two forms, and which one appears is decided by the data, not by us: + + - ``password: 0x6C696E65310A "line1\\012"`` when the value contains any + byte outside printable ASCII, or a backslash. The hex is authoritative. + - ``password: "inter secret"`` otherwise. Nothing inside can be escaped — + a backslash would have forced the hex form — so the outer quotes come + off and what remains is the value byte for byte, including any embedded + double quotes (``a"b`` really does print as ``"a"b"``). + + An empty value prints as ``password: `` with nothing after it. + """ + text = stderr.decode("utf-8", errors="replace") + for line in text.splitlines(): + if not line.startswith(_PASSWORD_PREFIX): + continue + body = line[len(_PASSWORD_PREFIX) :] + if body.startswith("0x"): + digits = body[2:].split(" ", 1)[0] + try: + raw = bytes.fromhex(digits) + except ValueError as exc: + raise KeychainError( + f"Keychain returned password data mem cannot decode: {body!r}" + ) from exc + try: + return raw.decode("utf-8") + except UnicodeDecodeError as exc: + raise KeychainError( + "Keychain item is not valid UTF-8, so it cannot be used " + "as a variable value" + ) from exc + if body == "": + return "" + if len(body) >= 2 and body.startswith('"') and body.endswith('"'): + return body[1:-1] + raise KeychainError( + f"Keychain returned password data in an unexpected format: {body!r}" + ) + raise KeychainError("Keychain returned no password data") diff --git a/src/mem/models.py b/src/mem/models.py index be20a4c..5d262a1 100644 --- a/src/mem/models.py +++ b/src/mem/models.py @@ -6,7 +6,7 @@ from __future__ import annotations -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, computed_field class CapturedCommand(BaseModel): @@ -129,14 +129,47 @@ class VarDeclaration(BaseModel): class StoredVariable(BaseModel): - """A persistent variable value managed by mem vars.""" + """One entry in the persistent variable store managed by ``mem vars``. + + Two shapes exist, and which one an entry has *is* which backend holds its + value: + + - ``value is None`` — the value lives in the macOS Keychain, under the + service :data:`mem.keychain.SERVICE` and the variable's name as the + account. This is what every entry written since ADR-009 looks like. + - ``value`` is a string — a plaintext value from before the Keychain + backend existed, or one whose migration has not succeeded yet. Still + readable so nobody's setup breaks, never written by mem today. + + Deriving the backend from the absence of the value, rather than storing a + ``backend`` field next to it, is deliberate: a field could disagree with + reality, and the dangerous direction of that disagreement is a file that + claims "keychain" while holding the secret in cleartext. Here the claim + *is* the absence, so it cannot lie. + """ - value: str + value: str | None = None last_used: int = 0 + @computed_field # type: ignore[prop-decorator] + @property + def backend(self) -> str: + """Where this variable's value actually lives. + + Serialized into vars.json so the file explains itself to anyone who + cats it, and recomputed on every read — an entry hand-edited to say + ``"backend": "keychain"`` while carrying a value is still treated, + correctly, as plaintext. + """ + return "plaintext" if self.value is not None else "keychain" + class VarsFile(BaseModel): - """On-disk representation of the persistent variable store.""" + """On-disk representation of the persistent variable store. + + An index, not a vault: it records which variables exist and when they were + last used. Since ADR-009 the values themselves are in the Keychain. + """ vars: dict[str, StoredVariable] = {} diff --git a/src/mem/storage.py b/src/mem/storage.py index a6497ba..0717c8c 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -21,9 +21,9 @@ from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path -from typing import Iterable, Iterator, Sequence +from typing import Iterable, Iterator, NamedTuple, Sequence -from mem import _fsutil +from mem import _fsutil, keychain from mem._fsutil import FILE_MODE, atomic_write from mem._fsutil import fsync_dir as _fsync_dir from mem._fsutil import harden_dir as _harden_dir @@ -34,6 +34,7 @@ CapturedCommand, GroupFile, PatternFile, + StoredVariable, VarsFile, WorkSession, ) @@ -767,22 +768,63 @@ def _entry_matches(entry: dict, query: str) -> bool: def _scrub_vars(query: str) -> None: - """Drop stored variables whose value is the forgotten text.""" + """Drop stored variables whose name or value carries the forgotten text. + + Matching a Keychain-backed variable costs one ``security`` call per + variable, because the value is no longer in the file mem can read. That is + the right trade here and only here: ``mem forget`` is rare, explicit and + destructive, and the alternative — matching on names alone — would report + success while leaving the secret in the Keychain. + + A value that cannot be read is kept and reported. Deleting it would throw + away a credential on a guess, and silently keeping it would let ``forget`` + claim a completeness it did not achieve. + """ if not VARS_FILE.exists(): return - try: - data = json.loads(VARS_FILE.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): + data = read_vars_file() + doomed: list[str] = [] + for name, entry in sorted(data.vars.items()): + if query in name: + doomed.append(name) + continue + if entry.value is not None: + if query in entry.value: + doomed.append(name) + continue + try: + value = keychain.get_secret(name) + except keychain.KeychainError as exc: + print( + f"warning: could not check variable {name} against the " + f"Keychain, leaving it in place ({exc})", + file=sys.stderr, + ) + continue + if value is not None and query in value: + doomed.append(name) + + if not doomed: return - stored = data.get("vars", {}) - kept = { - name: v - for name, v in stored.items() - if query not in v.get("value", "") and query not in name - } - if len(kept) != len(stored): - data["vars"] = kept - atomic_write(VARS_FILE, json.dumps(data, indent=2, ensure_ascii=False)) + + scrubbed = False + for name in doomed: + try: + keychain.delete_secret(name) + except keychain.KeychainError as exc: + # The index entry stays too. A name the user can still see is a + # name they can retry `mem vars remove` on; dropping it would + # leave the secret in the Keychain with nothing pointing at it. + print( + f"warning: could not remove variable {name} from the " + f"Keychain, leaving it in place ({exc})", + file=sys.stderr, + ) + continue + data.vars.pop(name, None) + scrubbed = True + if scrubbed: + write_vars_file(data) def _scrub_session_state(query: str) -> None: @@ -1022,10 +1064,14 @@ def write_group_file(path: Path, data: GroupFile) -> None: def read_vars_file() -> VarsFile: - """Read the persistent variable store. Returns empty if missing/corrupted. + """Read the persistent variable *index*. Returns empty if missing/corrupted. The vars file is global (not repo-scoped) because credentials and environment values typically apply across projects. + + Since ADR-009 this file records which variables exist, not what they are: + values live in the macOS Keychain. Entries written by an older mem still + carry their value here until :func:`migrate_vars_to_keychain` moves it. """ if not VARS_FILE.exists(): return VarsFile() @@ -1040,10 +1086,12 @@ def read_vars_file() -> VarsFile: def write_vars_file(data: VarsFile) -> None: - """Write the variable store atomically with restrictive permissions. + """Write the variable index atomically with restrictive permissions. - Uses tmp+rename pattern for crash safety. File permissions are set - to 0600 (owner read/write only) since the file may contain secrets. + Uses tmp+rename pattern for crash safety. File permissions are still 0600: + the values are in the Keychain now, but the list of variable names is + itself worth keeping to ourselves, and any not-yet-migrated entry is a + cleartext secret. """ with exclusive_lock(): atomic_write(VARS_FILE, data.model_dump_json(indent=2)) @@ -1127,3 +1175,226 @@ def read_agent_audit() -> Iterator[AgentAuditEntry]: f"warning: skipping corrupted line {line_num} in {path.name}", file=sys.stderr, ) + + +class MigrationResult(NamedTuple): + """Outcome of one :func:`migrate_vars_to_keychain` pass. + + ``failed`` names the variables still sitting in plaintext, and ``reason`` + says why in one line the user can act on. Both are empty on the ordinary + path where there was nothing left to move. + """ + + migrated: int + failed: list[str] + reason: str | None + + +def migrate_vars_to_keychain() -> MigrationResult: + """Move any plaintext values out of vars.json and into the Keychain. + + Idempotent and cheap to call on every command that touches the store: the + steady state is one file read that finds nothing to do. + + The ordering is the whole point. For each variable mem writes the value to + the Keychain, **reads it back and compares**, and only then rewrites + vars.json without it. A crash, a locked keychain or a declined prompt at + any point leaves the plaintext copy exactly where it was, and the next + invocation tries again — so the worst case is a value that is still + insecure, never a value that is gone. + + The re-read under the lock before rewriting guards the other direction: a + concurrent ``mem vars set`` may have replaced the entry since this pass + started, and dropping *its* value because we confirmed the old one would + be data loss disguised as a migration. + """ + pending = { + name: sv.value + for name, sv in read_vars_file().vars.items() + if sv.value is not None + } + if not pending: + return MigrationResult(0, [], None) + + reason = keychain.unavailable_reason() + if reason is not None: + return MigrationResult(0, sorted(pending), reason) + + migrated = 0 + failed: list[str] = [] + failure_reason: str | None = None + + for name, value in sorted(pending.items()): + try: + keychain.set_secret(name, value) + if keychain.get_secret(name) != value: + raise keychain.KeychainError( + "the Keychain did not return the value just written" + ) + except keychain.KeychainError as exc: + failed.append(name) + failure_reason = failure_reason or str(exc) + continue + + with exclusive_lock(): + current = read_vars_file() + entry = current.vars.get(name) + if entry is None or entry.value != value: + continue # someone changed it under us; leave it to the next pass + current.vars[name] = StoredVariable(value=None, last_used=entry.last_used) + write_vars_file(current) + migrated += 1 + + return MigrationResult(migrated, failed, failure_reason) + + +def set_var(name: str, value: str, last_used: int = 0) -> None: + """Store a variable's value in the Keychain and record it in the index. + + Raises :class:`mem.keychain.KeychainError` — and writes nothing at all — + when the Keychain refuses. There is deliberately no plaintext fallback: + mem promising encryption and quietly delivering a 0600 file would be worse + than the plaintext store it replaced, because the user would stop + worrying about it. + + The value is read back before the index is touched, so a name only appears + in ``mem vars list`` once the value behind it is genuinely retrievable. + """ + keychain.set_secret(name, value) + if keychain.get_secret(name) != value: + raise keychain.KeychainError( + f"Keychain accepted {name} but did not return the same value; " + f"refusing to record it" + ) + with exclusive_lock(): + data = read_vars_file() + data.vars[name] = StoredVariable(value=None, last_used=last_used) + write_vars_file(data) + + +def get_var_value(name: str) -> str | None: + """Value of one stored variable, from whichever backend holds it. + + None means "mem has no such variable". A Keychain that exists but cannot + be read raises instead — see :func:`mem.keychain.get_secret` for why that + distinction is worth keeping. + """ + entry = read_vars_file().vars.get(name) + if entry is None: + return None + if entry.value is not None: + return entry.value # not migrated yet + return keychain.get_secret(name) + + +def load_var_values( + names: Iterable[str], +) -> tuple[dict[str, StoredVariable], list[str]]: + """Load the store entries for *names*, with their values filled in. + + Returns ``(entries, unreadable)``. Only the requested names are fetched: + every Keychain read is a subprocess and potentially an OS prompt, so + listing a runbook must not pull every secret the user owns out of the + Keychain just to print a tick next to a name. + + A variable whose value cannot be read is reported in ``unreadable`` and + left out of ``entries``, so resolution falls through to the next source + instead of silently substituting an empty string. The caller is expected + to tell the user. + """ + stored = read_vars_file().vars + entries: dict[str, StoredVariable] = {} + unreadable: list[str] = [] + for name in names: + entry = stored.get(name) + if entry is None: + continue + if entry.value is not None: + entries[name] = entry + continue + try: + value = keychain.get_secret(name) + except keychain.KeychainError: + unreadable.append(name) + continue + if value is None: + # In the index but not in the Keychain: the item was deleted with + # Keychain Access, or a migration was interrupted after the file + # was rewritten. Not resolvable, and not silently an empty value. + unreadable.append(name) + continue + entries[name] = StoredVariable(value=value, last_used=entry.last_used) + return entries, unreadable + + +def touch_vars(names: Iterable[str], when: int) -> None: + """Record that variables were just used. + + Read-modify-write of the index under the lock, so two shells running + runbooks at the same moment cannot lose each other's entries — the + previous version of this read outside the lock and wrote the whole file + back. + """ + names = list(names) + if not names: + return + with exclusive_lock(): + data = read_vars_file() + changed = False + for name in names: + entry = data.vars.get(name) + if entry is not None: + entry.last_used = when + changed = True + if changed: + write_vars_file(data) + + +def remove_var(name: str) -> bool: + """Delete a variable from both the Keychain and the index. + + False if the index had no such name. The Keychain item is deleted even + then: an item that exists there but not in the index is exactly what a + half-failed earlier removal leaves behind, and leaving a secret + encrypted-but-orphaned would make ``mem vars remove`` a lie. + + The Keychain goes first so that a Keychain failure leaves the store + untouched and the error honest. The reverse order can only ever fail + *after* the name is gone from the index, which is the state where the user + is told the secret was removed and it was not. + """ + keychain.delete_secret(name) + with exclusive_lock(): + data = read_vars_file() + existed = name in data.vars + if existed: + del data.vars[name] + write_vars_file(data) + return existed + + +def clear_vars() -> tuple[int, list[str]]: + """Delete every stored variable from both backends. + + Returns ``(removed, kept)``, where ``kept`` names the variables whose + Keychain item could not be deleted. Those keep their index entry too: a + name the user can still see and retry is recoverable, an orphaned secret + with nothing pointing at it is not. + """ + data = read_vars_file() + removed: list[str] = [] + kept: list[str] = [] + for name in sorted(data.vars): + try: + keychain.delete_secret(name) + except keychain.KeychainError: + kept.append(name) + continue + removed.append(name) + + with exclusive_lock(): + current = read_vars_file() + for name in removed: + current.vars.pop(name, None) + write_vars_file(current) + return len(removed), kept diff --git a/src/mem/variables.py b/src/mem/variables.py index 0fcfb8e..2853f2b 100644 --- a/src/mem/variables.py +++ b/src/mem/variables.py @@ -128,14 +128,16 @@ def resolve_variables( Priority chain (highest to lowest): 1. Inline arguments (VAR=VALUE passed to mem run) 2. Shell environment (os.environ) - 3. Persistent store (~/.mem/vars.json) + 3. Persistent store (`mem vars`, values held in the macOS Keychain) 4. Default value (from --var NAME=default at save time) 5. Interactive prompt (visible input) Args: var_list: Variable declarations from the saved command. inline_args: {name: value} from command-line VAR=VALUE pairs. - stored_vars: dict from VarsFile.vars (StoredVariable objects with .value). + stored_vars: {name: StoredVariable} with values already loaded, as + returned by storage.load_var_values(). Entries whose value is + None are ignored — the store knows the name but not the value. prompt_fn: Optional callable for prompting (for testing). Defaults to click.prompt. allow_prompt: If False, skip interactive prompts (for --yes mode). @@ -166,9 +168,15 @@ def resolve_variables( resolved[name] = (env_val, "environment") continue - # Priority 3: persistent store - if name in stored_vars: - resolved[name] = (stored_vars[name].value, "store") + # Priority 3: persistent store. + # + # A value of None means the store holds the name but the value could + # not be loaded from the Keychain. Treating that as a resolution would + # export the string "None" into the child environment; falling through + # is what lets the default, or the user, still supply a real value. + stored = stored_vars.get(name) + if stored is not None and stored.value is not None: + resolved[name] = (stored.value, "store") continue # Priority 4: default value (resolve immediately when prompts disabled) @@ -218,6 +226,10 @@ def check_resolution_status( Only checks non-interactive sources (env, store, default). Does not check inline args (those are runtime-only). + + ``stored_vars`` is the store *index* — membership only. Printing a listing + deliberately does not read the Keychain: that would be one subprocess per + variable, and potentially an OS authorization prompt, for a tick mark. """ if stored_vars is None: stored_vars = {} diff --git a/tests/conftest.py b/tests/conftest.py index 0e63d16..251dda5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,6 @@ """Shared test fixtures for the mem test suite. -Two invariants are enforced here for *every* test, whether it asks for them +Three invariants are enforced here for *every* test, whether it asks for them or not: 1. **No test may ever touch the developer's real ``~/.mem``.** ``tmp_mem_dir`` @@ -12,10 +12,17 @@ inference costs seconds per call and its output is non-deterministic, so the unit suite pretends the SDK is unavailable unless a test explicitly opts in with ``@pytest.mark.ai`` (deselected by default via ``addopts``). + +3. **No test may touch the developer's real Keychain.** ``fake_keychain`` is + ``autouse`` and replaces the single function in ``mem.keychain`` that + spawns ``/usr/bin/security`` with an in-memory model of that binary. Tests + marked ``keychain_live`` (deselected by default) keep the real one, and + point it at a throwaway keychain file of their own. """ from __future__ import annotations +import shlex import sys import time from pathlib import Path @@ -24,6 +31,7 @@ import pytest +from mem import keychain from mem import models from mem import patterns from mem import storage @@ -122,6 +130,158 @@ def _no_real_inference( monkeypatch.setattr(patterns, "_apple_fm_available", lambda: False) +class FakeKeychain: + """An in-memory model of ``/usr/bin/security``, accurate where it matters. + + Substituted for :func:`mem.keychain._run`, so everything above it — the + command line mem builds, the hex encoding, the parsing of the output — is + exercised for real. Only the process boundary is faked. + + The fidelity that earns this its keep is :meth:`_render_password`: the + output format of ``find-generic-password -g`` is reproduced from output + recorded off the real binary, including the rule that decides between the + quoted and the hexadecimal form. mem's decoder is only as correct as that + rule, so guessing it here would make the round-trip tests agree with a + fiction. + """ + + #: Real `security -i` truncates an input line here and executes the head, + #: which is how a too-long value became a *silently truncated* Keychain + #: item. mem must never hand it a line this long. + MAX_LINE = 4096 + + def __init__(self) -> None: + self.items: dict[tuple[str, str], bytes] = {} + #: Every (argv, stdin) pair, so tests can assert what reached the + #: process table. + self.calls: list[tuple[list[str], bytes]] = [] + #: When set, every operation fails with this message — a locked + #: keychain, or a user who clicked Deny. + self.failure: str | None = None + + # -- helpers ---------------------------------------------------------- + + def secret(self, name: str, service: str = keychain.SERVICE) -> str | None: + """The stored value for a variable, decoded, or None.""" + raw = self.items.get((service, name)) + return None if raw is None else raw.decode("utf-8") + + @staticmethod + def _render_password(data: bytes) -> bytes: + """Reproduce what ``find-generic-password -g`` writes to stderr.""" + if not data: + return b"password: \n" + # Verified against the real tool: a backslash forces the hex form even + # though it is printable, while a double quote does not. + printable = all(0x20 <= b <= 0x7E and b != 0x5C for b in data) + if printable: + return b'password: "' + data + b'"\n' + escaped = bytearray() + for byte in data: + if 0x20 <= byte <= 0x7E and byte != 0x5C: + escaped.append(byte) + else: + escaped += f"\\{byte:03o}".encode("ascii") + return b"password: 0x" + data.hex().upper().encode() + b' "' + escaped + b'"\n' + + @staticmethod + def _not_found() -> tuple[int, bytes, bytes]: + return ( + 44, + b"", + b"security: SecKeychainSearchCopyNext: The specified item could " + b"not be found in the keychain.\n", + ) + + # -- the fake binary -------------------------------------------------- + + def run(self, argv: list[str], stdin: bytes = b"") -> tuple[int, bytes, bytes]: + """Stand in for :func:`mem.keychain._run`.""" + self.calls.append((list(argv), stdin)) + if self.failure is not None: + return 1, b"", f"security: {self.failure}\n".encode() + + if argv[1:] == ["-i"]: + line = stdin.decode("utf-8").rstrip("\n") + assert len(line) <= self.MAX_LINE, ( + "mem sent security a command line long enough to be truncated " + "and half-executed" + ) + return self._interactive(shlex.split(line)) + return self._command(argv[1:]) + + def _interactive(self, tokens: list[str]) -> tuple[int, bytes, bytes]: + assert tokens[0] == "add-generic-password", tokens + opts = self._options(tokens[1:]) + service, account = opts["-s"], opts["-a"] + if "-X" in opts: + data = bytes.fromhex(opts["-X"]) + else: + data = opts.get("-w", "").encode("utf-8") + if (service, account) in self.items and "-U" not in opts: + return 1, b"", b"security: The specified item already exists.\n" + self.items[(service, account)] = data + return 0, b"", b"" + + def _command(self, tokens: list[str]) -> tuple[int, bytes, bytes]: + verb, opts = tokens[0], self._options(tokens[1:]) + key = (opts["-s"], opts["-a"]) + if verb == "find-generic-password": + if key not in self.items: + return self._not_found() + return 0, b'keychain: "fake"\n', self._render_password(self.items[key]) + if verb == "delete-generic-password": + if key not in self.items: + return self._not_found() + del self.items[key] + return 0, b"password has been deleted.\n", b"" + raise AssertionError(f"unexpected security command: {verb}") + + @staticmethod + def _options(tokens: list[str]) -> dict[str, str]: + """Parse `security`'s flags, keeping value-less flags like -U and -g.""" + opts: dict[str, str] = {} + i = 0 + while i < len(tokens): + token = tokens[i] + if not token.startswith("-"): + opts.setdefault("keychain", token) + i += 1 + elif token in {"-U", "-g", "-w"} and ( + i + 1 >= len(tokens) or tokens[i + 1].startswith("-") + ): + opts[token] = "" + i += 1 + elif token in {"-s", "-a", "-l", "-X", "-w"}: + opts[token] = tokens[i + 1] + i += 2 + else: + opts[token] = "" + i += 1 + return opts + + +@pytest.fixture(autouse=True) +def fake_keychain( + request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch +) -> FakeKeychain: + """Keep ``/usr/bin/security`` away from the developer's login keychain. + + Autouse for the same reason ``tmp_mem_dir`` is: a test that forgot to ask + for isolation would not fail, it would quietly write the fixture's fake + tokens into the real Keychain and leave them there. The default suite must + be runnable on a laptop without side effects. + + Tests marked ``keychain_live`` keep the real subprocess — they are + deselected by default and supply their own throwaway keychain. + """ + fake = FakeKeychain() + if "keychain_live" not in request.keywords: + monkeypatch.delenv(keychain.KEYCHAIN_ENV, raising=False) + monkeypatch.setattr(keychain, "_run", fake.run) + return fake + + @pytest.fixture def git_repo(tmp_path: Path) -> Path: """Create a real (empty) git repository in a temp dir and return its root. diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 57e3ad1..6e741dd 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -464,7 +464,12 @@ def test_cli_writes_only_inside_mem_dir(self, home: Path, workdir: Path) -> None ["stats"], ["save", "echo hi", "--comment", "greeting"], ["list"], - ["vars", "set", "TOKEN", "abc"], + # `vars set` is deliberately absent: since ADR-009 it writes the + # value into the macOS Keychain, and this test runs a real + # subprocess, so it would file a token in the developer's own + # login keychain — outside this fake HOME, where the containment + # assertions below cannot even see it. It is covered by the + # stubbed unit tests and by the `keychain_live` suite. ["vars", "list"], ["--version"], ] diff --git a/tests/test_keychain.py b/tests/test_keychain.py new file mode 100644 index 0000000..d3dc091 --- /dev/null +++ b/tests/test_keychain.py @@ -0,0 +1,803 @@ +"""Tests for `mem.keychain` and the Keychain-backed variable store. + +`mem vars set` used to write API tokens into `~/.mem/vars.json` in cleartext. +Since ADR-009 the value goes into the macOS Keychain and the file keeps only +the name. This file pins the four properties that make that worth doing: + +1. **The secret never reaches argv.** `security -w ` puts the value in + the process table, where any user on the machine can read it with `ps`. mem + sends it down stdin to `security -i` instead, and the test asserts on the + argv the subprocess boundary actually received. +2. **The value survives the round trip byte for byte.** Shell metacharacters, + newlines, non-ASCII, an empty value, and — the nasty one — a value that is + itself valid hexadecimal, which the obvious reading path (`-w`) decodes + into binary garbage. +3. **Migration cannot lose a value.** The plaintext copy is deleted only after + the Keychain has been read back and agrees. Every failure mode leaves it + where it was, and the next run retries. +4. **Failure is loud.** With the Keychain unavailable, `mem vars set` refuses + and writes nothing — it never quietly falls back to plaintext under a + promise of encryption — and `mem vars list` says which backend every value + is actually in. + +The `security` binary is never executed here: `conftest.FakeKeychain` replaces +`mem.keychain._run`, so everything above the process boundary (the command +line, the hex encoding, the output parsing) runs for real. The one test that +does drive the real binary is marked ``keychain_live``, is deselected by +default, and points `security` at a throwaway keychain file it creates and +deletes itself — run it with ``pytest -m keychain_live``. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path +from unittest.mock import patch + +import pytest +from click.testing import CliRunner + +from mem import keychain, storage +from mem.cli import cli +from mem.models import Group, GroupCommand, GroupFile, StoredVariable, VarsFile + +from conftest import FakeKeychain + +# Captured at import time, before the autouse fake replaces it, so the two +# tests that need the real wrapper (with `subprocess.run` itself stubbed) can +# put it back. +REAL_RUN = keychain._run + +# Values chosen to break a naive implementation. Each one killed a plausible +# design during development. +NASTY_VALUES: dict[str, str] = { + "plain": "hunter2", + "spaces": " lead and trail ", + "metacharacters": "a; rm -rf / && echo $(whoami) `id` |pipe| 'q' \"d\"", + "backslashes": "C:\\path\\to\\thing\\", + "quotes": "say \"hi\" and 'bye'", + "newlines": "-----BEGIN KEY-----\nline2\nline3\n-----END KEY-----", + "non_ascii": "contrasña-☃-Ω-🔐", + "empty": "", + # Reads back from `security -w` as a bare hex string, indistinguishable + # from binary password data. This is why mem reads with -g. + "looks_like_hex": "deadbeefcafebabe0123456789abcdef", + "tab_and_control": "a\tb\x0bc", +} + + +def _write_vars_json(**values: str) -> None: + """Seed vars.json the way a pre-Keychain mem left it: values in the file.""" + storage.write_vars_file( + VarsFile(vars={name: StoredVariable(value=v) for name, v in values.items()}) + ) + + +def _raw_vars_json() -> str: + """The vars.json bytes as they are on disk.""" + return storage.VARS_FILE.read_text(encoding="utf-8") + + +# --------------------------------------------------------------------------- +# 1. The secret must never appear in argv +# --------------------------------------------------------------------------- + + +class TestSecretStaysOutOfArgv: + """Contract: `ps` must never be able to show a stored value.""" + + def test_write_passes_the_value_on_stdin(self, fake_keychain: FakeKeychain) -> None: + secret = "sk-live-9Xq2TESTONLYnotarealkey" + keychain.set_secret("API_TOKEN", secret) + + argv, stdin = fake_keychain.calls[-1] + assert argv == ["/usr/bin/security", "-i"], argv + assert ( + secret in stdin.decode("utf-8") or secret.encode().hex() in stdin.decode() + ) + + @pytest.mark.parametrize("value", sorted(set(NASTY_VALUES.values()))) + def test_no_call_ever_carries_the_value_in_argv( + self, fake_keychain: FakeKeychain, value: str + ) -> None: + """Not the write, not the read-back, not the delete.""" + keychain.set_secret("API_TOKEN", value) + keychain.get_secret("API_TOKEN") + keychain.delete_secret("API_TOKEN") + + if not value: + return # the empty string is a substring of everything + for argv, _stdin in fake_keychain.calls: + joined = " ".join(argv) + assert value not in joined, f"value leaked into argv: {argv}" + assert value.encode("utf-8").hex() not in joined + + def test_cli_set_never_puts_the_value_in_argv( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + secret = "sk-live-9Xq2TESTONLYnotarealkey" + result = CliRunner().invoke( + cli, ["vars", "set", "API_TOKEN"], input=f"{secret}\n" + ) + + assert result.exit_code == 0, result.output + for argv, _stdin in fake_keychain.calls: + assert secret not in " ".join(argv) + + +# --------------------------------------------------------------------------- +# 2. Values survive the round trip +# --------------------------------------------------------------------------- + + +class TestRoundTrip: + """Contract: what comes out is exactly what went in.""" + + @pytest.mark.parametrize(("label", "value"), sorted(NASTY_VALUES.items())) + def test_value_round_trips(self, label: str, value: str) -> None: + keychain.set_secret("API_TOKEN", value) + assert keychain.get_secret("API_TOKEN") == value + + @pytest.mark.parametrize(("label", "value"), sorted(NASTY_VALUES.items())) + def test_value_round_trips_through_the_store( + self, tmp_mem_dir: Path, label: str, value: str + ) -> None: + storage.set_var("API_TOKEN", value) + assert storage.get_var_value("API_TOKEN") == value + assert value not in _raw_vars_json() or value == "" + + def test_overwriting_replaces_the_value(self) -> None: + keychain.set_secret("API_TOKEN", "first") + keychain.set_secret("API_TOKEN", "second") + assert keychain.get_secret("API_TOKEN") == "second" + + def test_missing_item_is_none_not_an_error(self) -> None: + assert keychain.get_secret("NEVER_SET") is None + + def test_item_is_labelled_for_keychain_access( + self, fake_keychain: FakeKeychain + ) -> None: + """The Keychain Access row has to say which variable it is.""" + keychain.set_secret("API_TOKEN", "x") + _argv, stdin = fake_keychain.calls[-1] + line = stdin.decode() + assert f"-s {keychain.SERVICE}" in line + assert "-a API_TOKEN" in line + assert f"-l {keychain.SERVICE}:API_TOKEN" in line + + +# --------------------------------------------------------------------------- +# 3. Parsing `security find-generic-password -g` +# --------------------------------------------------------------------------- + + +# Recorded verbatim from the real /usr/bin/security on macOS 15, by storing +# each value and reading it back. The decoder is only correct if it agrees +# with these bytes, so they are pinned rather than generated. +RECORDED_OUTPUT: list[tuple[str, bytes, str]] = [ + ("printable", b'password: "inter secret"\n', "inter secret"), + ("hex_looking", b'password: "deadbeef"\n', "deadbeef"), + ("embedded_quote", b'password: "a"b"\n', 'a"b'), + ("punctuation", b'password: "~%^&*()|;<>"\n', "~%^&*()|;<>"), + ("outer_spaces", b'password: " lead and trail "\n', " lead and trail "), + ("empty", b"password: \n", ""), + ("backslash", b'password: 0x6122625C63 "a"b\\134c"\n', 'a"b\\c'), + ( + "newline", + b'password: 0x6C696E65310A6C696E6532 "line1\\012line2"\n', + "line1\nline2", + ), + ( + "non_ascii", + b'password: 0x636F6E74726173C3B16120E29883 "contras\\303\\261a \\342\\230\\203"\n', + "contrasña ☃", + ), + ( + "trailing_newline", + b'password: 0x747261696C696E670A "trailing\\012"\n', + "trailing\n", + ), +] + + +class TestPasswordOutputParsing: + """Contract: mem decodes `security -g` output exactly, or refuses to guess.""" + + @pytest.mark.parametrize( + ("raw", "expected"), + [(raw, expected) for _id, raw, expected in RECORDED_OUTPUT], + ids=[case[0] for case in RECORDED_OUTPUT], + ) + def test_recorded_real_output_decodes(self, raw: bytes, expected: str) -> None: + assert keychain.parse_password_output(raw) == expected + + def test_hex_looking_value_is_not_hex_decoded(self) -> None: + """The bug that rules out reading with `-w`. + + A 32-character hex API key is printable, so `security -w` prints it + raw — byte for byte identical to how it prints *binary* data. Anything + that hex-decodes on sight turns the user's key into 16 bytes of + garbage. The `-g` form never does, because binary data always carries + the `0x` prefix. + """ + assert ( + keychain.parse_password_output(b'password: "deadbeefcafebabe"\n') + == "deadbeefcafebabe" + ) + + def test_malformed_hex_raises_instead_of_guessing(self) -> None: + with pytest.raises(keychain.KeychainError): + keychain.parse_password_output(b'password: 0xZZTOP "??"\n') + + def test_unparseable_output_raises_instead_of_guessing(self) -> None: + with pytest.raises(keychain.KeychainError): + keychain.parse_password_output(b"password: not-quoted-and-not-hex\n") + + def test_absent_password_line_raises(self) -> None: + with pytest.raises(keychain.KeychainError): + keychain.parse_password_output(b"keychain: nothing to see\n") + + def test_non_utf8_item_is_rejected(self) -> None: + with pytest.raises(keychain.KeychainError): + keychain.parse_password_output(b'password: 0xFFFE "\\377\\376"\n') + + +# --------------------------------------------------------------------------- +# 4. Guards on what mem is willing to hand to `security` +# --------------------------------------------------------------------------- + + +class TestCommandLineGuards: + """Contract: nothing user-controlled can restructure the command.""" + + @pytest.mark.parametrize( + "name", + [ + "API TOKEN", + "API\ndelete-generic-password -s mem-cli-vars -a OTHER", + "API;OTHER", + 'API" -a OTHER "', + "API$(whoami)", + "", + ], + ) + def test_a_hostile_name_is_refused( + self, fake_keychain: FakeKeychain, name: str + ) -> None: + """`security -i` parses a command line, so a name is a code path. + + A newline in an account name would be a second command for mem's own + subprocess to run — the injection this module exists to avoid. + """ + with pytest.raises(keychain.KeychainError): + keychain.set_secret(name, "x") + assert fake_keychain.calls == [] + + def test_value_too_long_is_refused_not_truncated( + self, fake_keychain: FakeKeychain + ) -> None: + """Real `security -i` truncates at 4096 chars and runs the head. + + Observed on the real binary: an 8 KB value produced a Keychain item + containing a silently truncated secret. Refusing is the only safe + answer available. + """ + with pytest.raises(keychain.KeychainValueTooLong): + keychain.set_secret("BIG", "A" * 4000) + assert fake_keychain.calls == [] + + def test_a_value_just_under_the_limit_still_works(self) -> None: + value = "A" * 1800 + keychain.set_secret("BIG", value) + assert keychain.get_secret("BIG") == value + + def test_a_named_keychain_is_used_for_every_operation( + self, monkeypatch: pytest.MonkeyPatch, fake_keychain: FakeKeychain + ) -> None: + """MEM_KEYCHAIN must reach the write, the read and the delete alike. + + Missing it on one of the three would send that operation to the + *default* keychain — which is how a probe of `security` put a + truncated secret in a real login keychain during development. + """ + monkeypatch.setenv(keychain.KEYCHAIN_ENV, "/tmp/mem-test.keychain") + keychain.set_secret("API_TOKEN", "x") + keychain.get_secret("API_TOKEN") + keychain.delete_secret("API_TOKEN") + + for argv, stdin in fake_keychain.calls: + assert "/tmp/mem-test.keychain" in " ".join(argv) + stdin.decode() + + def test_hostile_keychain_path_is_refused( + self, monkeypatch: pytest.MonkeyPatch, fake_keychain: FakeKeychain + ) -> None: + monkeypatch.setenv(keychain.KEYCHAIN_ENV, "/tmp/x; rm -rf /") + with pytest.raises(keychain.KeychainError): + keychain.set_secret("API_TOKEN", "x") + + +# --------------------------------------------------------------------------- +# 5. Availability +# --------------------------------------------------------------------------- + + +class TestAvailability: + """Contract: mem knows when it cannot use the Keychain, and says so.""" + + def test_available_on_macos_with_the_binary(self) -> None: + if sys.platform == "darwin" and os.access(keychain.SECURITY_BIN, os.X_OK): + assert keychain.is_available() + assert keychain.unavailable_reason() is None + + def test_unavailable_off_macos(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(keychain.sys, "platform", "linux") + assert not keychain.is_available() + assert "linux" in (keychain.unavailable_reason() or "") + + def test_unavailable_without_the_binary( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setattr(keychain.sys, "platform", "darwin") + monkeypatch.setattr(keychain.os, "access", lambda *a, **kw: False) + assert not keychain.is_available() + assert keychain.SECURITY_BIN in (keychain.unavailable_reason() or "") + + def test_a_locked_keychain_raises_with_the_os_message( + self, fake_keychain: FakeKeychain + ) -> None: + """`security`'s own wording explains more than mem could.""" + fake_keychain.failure = "User interaction is not allowed." + with pytest.raises(keychain.KeychainUnavailable) as excinfo: + keychain.set_secret("API_TOKEN", "x") + assert "User interaction is not allowed." in str(excinfo.value) + + def test_a_missing_binary_at_call_time_is_unavailable( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + def boom(*_args: object, **_kwargs: object) -> None: + raise FileNotFoundError(keychain.SECURITY_BIN) + + monkeypatch.setattr(keychain, "_run", REAL_RUN) + monkeypatch.setattr(keychain.subprocess, "run", boom) + with pytest.raises(keychain.KeychainUnavailable): + keychain._run([keychain.SECURITY_BIN, "-i"]) + + def test_an_unrunnable_security_is_unavailable( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Out of file descriptors, no fork available — still not a crash.""" + + def boom(*_args: object, **_kwargs: object) -> None: + raise OSError(24, "Too many open files") + + monkeypatch.setattr(keychain, "_run", REAL_RUN) + monkeypatch.setattr(keychain.subprocess, "run", boom) + with pytest.raises(keychain.KeychainUnavailable): + keychain._run([keychain.SECURITY_BIN, "-i"]) + + def test_a_hung_security_is_unavailable_not_a_hang( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """An authorization dialog nobody answers must not wedge the shell.""" + + def timeout(*_args: object, **kwargs: object) -> None: + raise subprocess.TimeoutExpired(cmd="security", timeout=1) + + monkeypatch.setattr(keychain, "_run", REAL_RUN) + monkeypatch.setattr(keychain.subprocess, "run", timeout) + with pytest.raises(keychain.KeychainUnavailable): + keychain._run([keychain.SECURITY_BIN, "-i"]) + + +# --------------------------------------------------------------------------- +# 6. Migration off the plaintext file +# --------------------------------------------------------------------------- + + +class TestMigration: + """Contract: values move into the Keychain, and none is ever lost.""" + + def test_plaintext_values_move_into_the_keychain( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + _write_vars_json(API_TOKEN="sk-live-TESTONLY", DB_HOST="staging.db") + + result = storage.migrate_vars_to_keychain() + + assert result.migrated == 2 + assert result.failed == [] + assert fake_keychain.secret("API_TOKEN") == "sk-live-TESTONLY" + assert fake_keychain.secret("DB_HOST") == "staging.db" + + def test_the_file_no_longer_holds_the_secret(self, tmp_mem_dir: Path) -> None: + _write_vars_json(API_TOKEN="sk-live-TESTONLY") + storage.migrate_vars_to_keychain() + + raw = _raw_vars_json() + assert "sk-live-TESTONLY" not in raw + assert "API_TOKEN" in raw, "the name must survive; only the value moves" + assert json.loads(raw)["vars"]["API_TOKEN"]["backend"] == "keychain" + + def test_last_used_survives_the_move(self, tmp_mem_dir: Path) -> None: + storage.write_vars_file( + VarsFile( + vars={"API_TOKEN": StoredVariable(value="x", last_used=1700000000)} + ) + ) + storage.migrate_vars_to_keychain() + assert storage.read_vars_file().vars["API_TOKEN"].last_used == 1700000000 + + def test_migration_is_idempotent( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + _write_vars_json(API_TOKEN="sk-live-TESTONLY") + assert storage.migrate_vars_to_keychain().migrated == 1 + + before = _raw_vars_json() + calls = len(fake_keychain.calls) + + second = storage.migrate_vars_to_keychain() + + assert second == storage.MigrationResult(0, [], None) + assert _raw_vars_json() == before + assert len(fake_keychain.calls) == calls, ( + "a clean store must cost no subprocess" + ) + assert storage.get_var_value("API_TOKEN") == "sk-live-TESTONLY" + + def test_a_failed_write_leaves_the_plaintext_value_alone( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + """The Keychain is locked halfway through the upgrade.""" + _write_vars_json(API_TOKEN="sk-live-TESTONLY") + fake_keychain.failure = ( + "The user name or passphrase you entered is not correct." + ) + + result = storage.migrate_vars_to_keychain() + + assert result.migrated == 0 + assert result.failed == ["API_TOKEN"] + assert "not correct" in (result.reason or "") + assert storage.read_vars_file().vars["API_TOKEN"].value == "sk-live-TESTONLY" + assert storage.get_var_value("API_TOKEN") == "sk-live-TESTONLY" + + def test_a_write_that_cannot_be_read_back_is_not_trusted( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain, monkeypatch + ) -> None: + """Confirmation, not optimism, is what permits the delete. + + Here `security` accepts the write and reports success, but the item + cannot be read back. If mem deleted the plaintext copy on the strength + of the exit code alone, the value would now exist nowhere. + """ + _write_vars_json(API_TOKEN="sk-live-TESTONLY") + monkeypatch.setattr(keychain, "get_secret", lambda _name: None) + + result = storage.migrate_vars_to_keychain() + + assert result.failed == ["API_TOKEN"] + assert storage.read_vars_file().vars["API_TOKEN"].value == "sk-live-TESTONLY" + + def test_migration_is_reported_when_it_happens(self, tmp_mem_dir: Path) -> None: + _write_vars_json(API_TOKEN="sk-live-TESTONLY") + result = CliRunner().invoke(cli, ["vars", "list"]) + + assert result.exit_code == 0, result.output + assert "into the macOS Keychain" in result.output + assert "sk-live-TESTONLY" not in result.output + + def test_a_keychainless_platform_reports_instead_of_migrating( + self, tmp_mem_dir: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _write_vars_json(API_TOKEN="sk-live-TESTONLY") + monkeypatch.setattr(keychain.sys, "platform", "linux") + + result = storage.migrate_vars_to_keychain() + + assert result.migrated == 0 + assert result.failed == ["API_TOKEN"] + assert "linux" in (result.reason or "") + assert storage.get_var_value("API_TOKEN") == "sk-live-TESTONLY" + + +# --------------------------------------------------------------------------- +# 7. Degradation is visible, and never silently plaintext +# --------------------------------------------------------------------------- + + +class TestDegradation: + """Contract: mem fails loudly rather than writing a secret in cleartext.""" + + def test_set_fails_when_the_keychain_is_unavailable( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + fake_keychain.failure = "User interaction is not allowed." + + result = CliRunner().invoke( + cli, ["vars", "set", "API_TOKEN", "sk-live-TESTONLY"] + ) + + assert result.exit_code != 0 + assert "User interaction is not allowed." in result.output + assert "does not fall back" in result.output + + def test_a_refused_set_writes_nothing_anywhere( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + fake_keychain.failure = "User interaction is not allowed." + + CliRunner().invoke(cli, ["vars", "set", "API_TOKEN", "sk-live-TESTONLY"]) + + assert storage.read_vars_file().vars == {} + if storage.VARS_FILE.exists(): + assert "sk-live-TESTONLY" not in _raw_vars_json() + + def test_list_names_the_backend_of_every_value( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + """A half-migrated store must not be described by one header line.""" + storage.set_var("SAFE_ONE", "in-the-keychain") + data = storage.read_vars_file() + data.vars["LEGACY_ONE"] = StoredVariable(value="still-plaintext") + storage.write_vars_file(data) + fake_keychain.failure = "User interaction is not allowed." + + result = CliRunner().invoke(cli, ["vars", "list"]) + + assert result.exit_code == 0, result.output + assert "SAFE_ONE" in result.output + assert "keychain" in result.output + assert "LEGACY_ONE" in result.output + assert "plaintext" in result.output + assert "still-plaintext" not in result.output + assert "in-the-keychain" not in result.output + + def test_list_json_reports_the_backend(self, tmp_mem_dir: Path) -> None: + storage.set_var("API_TOKEN", "sk-live-TESTONLY") + result = CliRunner().invoke(cli, ["vars", "list", "--json"]) + + payload = json.loads(result.output) + assert payload["variables"] == [ + {"name": "API_TOKEN", "backend": "keychain", "last_used": 0} + ] + assert payload["keychain"]["service"] == keychain.SERVICE + assert "sk-live-TESTONLY" not in result.output + + def test_inline_value_warns_that_it_was_visible(self, tmp_mem_dir: Path) -> None: + """mem's own argv is the last place a secret can still leak.""" + result = CliRunner().invoke(cli, ["vars", "set", "API_TOKEN", "hunter2"]) + + assert result.exit_code == 0, result.output + assert "visible to `ps`" in result.output + + def test_the_prompt_hides_what_is_typed( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + """The README promises "hidden input (like sudo)"; assert the flag. + + Checking the captured output instead would prove nothing: CliRunner + does not echo stdin either way, so the test would pass with the + echoing prompt this replaced. + """ + with patch("click.prompt", return_value="sk-live-TESTONLY") as prompt: + result = CliRunner().invoke(cli, ["vars", "set", "API_TOKEN"]) + + assert result.exit_code == 0, result.output + assert prompt.call_args.kwargs["hide_input"] is True + assert fake_keychain.secret("API_TOKEN") == "sk-live-TESTONLY" + assert "sk-live-TESTONLY" not in result.output + + def test_an_unreadable_value_does_not_become_the_string_none( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + """A variable mem cannot read is unresolved, not resolved to garbage.""" + storage.set_var("API_TOKEN", "sk-live-TESTONLY") + fake_keychain.failure = "User interaction is not allowed." + + entries, unreadable = storage.load_var_values(["API_TOKEN"]) + + assert entries == {} + assert unreadable == ["API_TOKEN"] + + def test_run_says_which_variable_it_could_not_read( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + storage.set_var("API_TOKEN", "sk-live-TESTONLY") + storage.write_group_file( + storage.GROUPS_GLOBAL_FILE, + GroupFile( + groups={ + "test": Group( + commands=[ + GroupCommand( + cmd="true $API_TOKEN", + vars=[{"name": "API_TOKEN", "default": "fallback"}], + ) + ] + ) + } + ), + ) + fake_keychain.failure = "User interaction is not allowed." + + result = CliRunner().invoke(cli, ["run", "test", "--global", "--yes"]) + + assert "Could not read from the Keychain" in result.output + assert "API_TOKEN" in result.output + + +# --------------------------------------------------------------------------- +# 8. Removal really removes +# --------------------------------------------------------------------------- + + +class TestRemoval: + """Contract: after `mem vars remove`, the secret is gone from both halves.""" + + def test_remove_deletes_the_keychain_item( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + storage.set_var("API_TOKEN", "sk-live-TESTONLY") + + result = CliRunner().invoke(cli, ["vars", "remove", "API_TOKEN"]) + + assert result.exit_code == 0, result.output + assert fake_keychain.items == {} + assert storage.read_vars_file().vars == {} + assert keychain.get_secret("API_TOKEN") is None + + def test_remove_reports_an_unknown_name(self, tmp_mem_dir: Path) -> None: + result = CliRunner().invoke(cli, ["vars", "remove", "NOPE"]) + assert result.exit_code != 0 + assert "not found" in result.output + + def test_remove_cleans_up_an_orphaned_keychain_item( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + """The index lost the name but the Keychain still holds the secret.""" + keychain.set_secret("API_TOKEN", "sk-live-TESTONLY") + + assert storage.remove_var("API_TOKEN") is False + assert fake_keychain.items == {} + + def test_a_failed_delete_keeps_the_name_visible( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + """A name the user can retry beats a secret nothing points at.""" + storage.set_var("API_TOKEN", "sk-live-TESTONLY") + fake_keychain.failure = "User interaction is not allowed." + + result = CliRunner().invoke(cli, ["vars", "remove", "API_TOKEN"]) + + assert result.exit_code != 0 + assert "API_TOKEN" in storage.read_vars_file().vars + + def test_clear_empties_both_backends( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + storage.set_var("API_TOKEN", "one") + storage.set_var("DB_HOST", "two") + + result = CliRunner().invoke(cli, ["vars", "clear", "--yes"]) + + assert result.exit_code == 0, result.output + assert fake_keychain.items == {} + assert storage.read_vars_file().vars == {} + + def test_clear_keeps_what_it_could_not_delete( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + storage.set_var("API_TOKEN", "one") + fake_keychain.failure = "User interaction is not allowed." + + result = CliRunner().invoke(cli, ["vars", "clear", "--yes"]) + + assert result.exit_code != 0 + assert "API_TOKEN" in storage.read_vars_file().vars + assert fake_keychain.secret("API_TOKEN") == "one" + + def test_forget_removes_a_keychain_backed_value( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + """`mem forget` promises no traces anywhere — the Keychain included.""" + storage.set_var("API_TOKEN", "sk-live-TESTONLY") + + storage.forget_commands("sk-live-TESTONLY") + + assert fake_keychain.items == {} + assert storage.read_vars_file().vars == {} + + def test_forget_keeps_an_unrelated_value( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain + ) -> None: + storage.set_var("API_TOKEN", "sk-live-TESTONLY") + + storage.forget_commands("something-else") + + assert fake_keychain.secret("API_TOKEN") == "sk-live-TESTONLY" + + def test_forget_keeps_a_value_it_could_not_check( + self, tmp_mem_dir: Path, fake_keychain: FakeKeychain, capsys + ) -> None: + """Deleting on a guess would throw away a credential.""" + storage.set_var("API_TOKEN", "sk-live-TESTONLY") + fake_keychain.failure = "User interaction is not allowed." + + storage.forget_commands("sk-live-TESTONLY") + + assert "API_TOKEN" in storage.read_vars_file().vars + assert "could not check" in capsys.readouterr().err + + +# --------------------------------------------------------------------------- +# 9. The real binary, deselected by default +# --------------------------------------------------------------------------- + + +@pytest.mark.keychain_live +class TestAgainstTheRealSecurityBinary: + """End-to-end against `/usr/bin/security`, on a keychain we throw away. + + Deselected by default (`-m 'not keychain_live'`), because the default + suite must never touch the developer's login keychain. Run deliberately + with ``pytest -m keychain_live``. Everything here goes to a keychain file + created in ``tmp_path`` and deleted afterwards; ``MEM_KEYCHAIN`` is what + keeps `security` pointed at it. + """ + + @pytest.fixture() + def throwaway_keychain( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> Path: + if sys.platform != "darwin": + pytest.skip("no macOS Keychain on this platform") + path = tmp_path / "mem-test.keychain" + subprocess.run( + ["security", "create-keychain", "-p", "test-passphrase", str(path)], + check=True, + capture_output=True, + ) + subprocess.run( + ["security", "unlock-keychain", "-p", "test-passphrase", str(path)], + check=True, + capture_output=True, + ) + monkeypatch.setenv(keychain.KEYCHAIN_ENV, str(path)) + yield path + subprocess.run( + ["security", "delete-keychain", str(path)], check=False, capture_output=True + ) + + @pytest.mark.parametrize(("label", "value"), sorted(NASTY_VALUES.items())) + def test_real_round_trip( + self, throwaway_keychain: Path, label: str, value: str + ) -> None: + keychain.set_secret("MEM_TEST_VAR", value) + assert keychain.get_secret("MEM_TEST_VAR") == value + assert keychain.delete_secret("MEM_TEST_VAR") is True + assert keychain.get_secret("MEM_TEST_VAR") is None + + def test_real_migration(self, throwaway_keychain: Path, tmp_mem_dir: Path) -> None: + _write_vars_json(MEM_TEST_VAR="sk-live-TESTONLY") + + assert storage.migrate_vars_to_keychain().migrated == 1 + assert "sk-live-TESTONLY" not in _raw_vars_json() + assert storage.get_var_value("MEM_TEST_VAR") == "sk-live-TESTONLY" + + storage.remove_var("MEM_TEST_VAR") + + def test_real_secret_is_absent_from_the_process_table( + self, throwaway_keychain: Path + ) -> None: + """The write is a real fork/exec; nothing about it may show in `ps`.""" + value = "sk-live-9Xq2TESTONLYnotarealkey" + keychain.set_secret("MEM_TEST_VAR", value) + listing = subprocess.run( + ["ps", "-Ao", "args"], capture_output=True, text=True, check=True + ).stdout + assert value not in listing + keychain.delete_secret("MEM_TEST_VAR") diff --git a/tests/test_variables.py b/tests/test_variables.py index 01f3550..a1882b6 100644 --- a/tests/test_variables.py +++ b/tests/test_variables.py @@ -2,8 +2,9 @@ resolution status, and AI credential detection. `variables.py` is the module where secrets live: values pulled from the -persistent store (`~/.mem/vars.json`), from the environment, or typed by the -user at a hidden prompt are handed to the shell that `mem run` spawns. They +persistent store (the macOS Keychain since ADR-009, indexed by +`~/.mem/vars.json`), from the environment, or typed by the user at a hidden +prompt are handed to the shell that `mem run` spawns. They reach it through the child's environment and are expanded by the shell — never spliced into the command text, which is what made every value a potential injection. This file pins down the two properties that matter: @@ -373,6 +374,33 @@ def test_allow_prompt_false_never_prompts(self) -> None: ) prompt.assert_not_called() + def test_a_store_entry_without_a_value_is_not_a_resolution(self) -> None: + """Contract: an unreadable Keychain value falls through, silently sane. + + Since ADR-009 the store index knows a variable's *name* without + necessarily being able to produce its value — a locked Keychain, a + declined prompt, an item deleted in Keychain Access. Treating the + entry as resolved would export the string "None" into the child + environment; the value has to come from somewhere real instead. + """ + resolved = variables.resolve_variables( + [_decl("API_TOKEN", default="fallback")], + inline_args={}, + stored_vars={"API_TOKEN": StoredVariable(value=None)}, + allow_prompt=False, + ) + assert resolved == {"API_TOKEN": ("fallback", "default")} + + def test_a_store_entry_with_a_value_still_wins(self) -> None: + """The other half of the same contract: a loaded value resolves.""" + resolved = variables.resolve_variables( + [_decl("API_TOKEN", default="fallback")], + inline_args={}, + stored_vars=_store(API_TOKEN="real"), + allow_prompt=False, + ) + assert resolved == {"API_TOKEN": ("real", "store")} + # --------------------------------------------------------------------------- # 3. Substitution: prefix collisions and escapes @@ -687,7 +715,13 @@ def test_imported_runbook_default_is_hidden_from_the_run_preview( class TestVarsFilePermissions: - """Contract: the file holding secrets is never readable by other users.""" + """Contract: the vars file is never readable by other users. + + Still load-bearing after ADR-009 moved the values into the Keychain: the + file keeps the list of variable *names*, which is worth keeping private on + its own, and it holds real cleartext for any entry whose migration has not + succeeded yet. + """ def test_vars_file_is_owner_only(self, tmp_mem_dir: Path) -> None: """Contract: vars.json ends up at mode 0600.""" From 6fee6b51bf4e7a77a419956a5366f37fae1b35c8 Mon Sep 17 00:00:00 2001 From: Matias Date: Tue, 4 Aug 2026 01:58:52 -0300 Subject: [PATCH 2/2] docs(adr): record ADR-009 and amend Principle III for credentials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- ARCHITECTURE.md | 18 ++++- PHILOSOPHY.md | 13 ++++ README.md | 31 +++++++- .../010-keychain-for-variable-values.md | 78 +++++++++++++++++++ 4 files changed, 134 insertions(+), 6 deletions(-) create mode 100644 docs/decisions/010-keychain-for-variable-values.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 2b56592..2ae5f4f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -234,7 +234,7 @@ Parse inline VAR=VALUE arguments Resolve all variables upfront (before any execution): 1. Inline arguments ← highest priority 2. Shell environment (os.environ) - 3. Persistent store (~/.mem/vars.json) + 3. Persistent store (macOS Keychain, indexed by ~/.mem/vars.json) 4. Default value (from --var at save time) 5. Interactive prompt ← last resort ▼ @@ -324,13 +324,19 @@ Execute commands with substituted values } ``` -### Variable Store (`vars.json`) +### Variable Store (`vars.json` + macOS Keychain) + +An index, not a vault. The values are Keychain items under the service +`mem-cli-vars` with the variable name as the account +([ADR-010](docs/decisions/010-keychain-for-variable-values.md)); `value` is +`null` for every entry mem writes, and a non-null one is a pre-ADR-010 +plaintext value awaiting migration. ```json { "vars": { - "API_TOKEN": { "value": "sk-abc123...", "last_used": 1709600000 }, - "DB_HOST": { "value": "staging.db.internal", "last_used": 1709500000 } + "API_TOKEN": { "value": null, "last_used": 1709600000, "backend": "keychain" }, + "DB_HOST": { "value": null, "last_used": 1709500000, "backend": "keychain" } } } ``` @@ -399,6 +405,10 @@ Design points: - **The access flag is read per request**, so `mem agent disable` takes effect without restarting the client. +`backend` is derived from the absence of `value` on every read, never trusted +from the file — so an entry cannot claim to be encrypted while holding a +secret. + ## Session Boundary Detection A new session begins when either condition is met: diff --git a/PHILOSOPHY.md b/PHILOSOPHY.md index 72a200f..de2c1d2 100644 --- a/PHILOSOPHY.md +++ b/PHILOSOPHY.md @@ -61,6 +61,13 @@ shell conventions. and never a second write path — deleting it loses nothing ([ADR-005](docs/decisions/005-derived-index-jsonl-source-of-truth.md)). Any storage whose loss would lose user data is forbidden. +- One exception, and only one: a **credential** is held by the OS + keychain rather than by a file mem writes + ([ADR-010](docs/decisions/010-keychain-for-variable-values.md)). + It is still a single source of truth, it is still readable without + mem (`security find-generic-password`, Keychain Access), and mem + keeps no copy of it. A secret is the one kind of data where + "you can `cat` it" is a defect and not a feature. - CLI output supports both human-readable (default) and JSON (`--json`) formats. - mem reads from stdin and writes results to stdout; errors @@ -144,6 +151,12 @@ never silently. "no second source of truth". A local, derived, rebuildable index is permitted; storage whose loss would lose user data is not. See [ADR-005](docs/decisions/005-derived-index-jsonl-source-of-truth.md). +- **2026-08-04** — Principle III: one carve-out for credentials. Values + set with `mem vars` live in the macOS Keychain, encrypted at rest, + instead of in plaintext JSON — because "human-readable" is the wrong + guarantee for an API token, and 0600 stops other users but not + backups, sync folders, or anything else running as you. + See [ADR-010](docs/decisions/010-keychain-for-variable-values.md). - **2026-08-04** — Principle I: strengthened. Explicitly no sockets, no listeners, no localhost, and no transitive networking dependencies; stdio pipes are explicitly not networking. diff --git a/README.md b/README.md index 8164ffd..3274441 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,7 @@ When `mem run` encounters variables, it resolves them in this order: 1. **Inline arguments** — `mem run api API_TOKEN=abc123` 2. **Shell environment** — `export API_TOKEN=abc123` -3. **Persistent store** — `mem vars set API_TOKEN` +3. **Persistent store** — `mem vars set API_TOKEN` (macOS Keychain) 4. **Default value** — from `--var NAME=default` at save time 5. **Interactive prompt** — asks you, only as a last resort @@ -247,11 +247,38 @@ For values that persist across sessions but shouldn't be in `.zshrc`: ```bash mem vars set API_TOKEN # hidden input (like sudo) mem vars set DB_HOST staging.db # inline for non-sensitive values -mem vars list # shows names only, never values +mem vars list # shows names and backend, never values mem vars remove API_TOKEN mem vars clear ``` +**Values live in the macOS Keychain**, not in a file ([ADR-010](docs/decisions/010-keychain-for-variable-values.md)). They are encrypted at rest under your login password, and mem hands them to `/usr/bin/security` over a pipe — never on a command line, where `ps` would show them to every process on the machine. + +```bash +# Everything mem stores is filed under one service, and it is yours: +security find-generic-password -s mem-cli-vars -a API_TOKEN -w +``` + +They are also visible in **Keychain Access** under the service `mem-cli-vars`, listed as `mem-cli-vars:API_TOKEN`. + +If you used `mem vars` before this landed, your values are moved out of `~/.mem/vars.json` and into the Keychain the first time you run any `mem vars` command — one at a time, and each plaintext copy is deleted only after the Keychain has been read back and agrees. `vars.json` stays as the index of *which* variables exist: + +```json +{"vars": {"API_TOKEN": {"value": null, "last_used": 0, "backend": "keychain"}}} +``` + +**When the Keychain is not available** — a locked keychain, a declined authorization prompt, a non-macOS machine — `mem vars set` fails and stores nothing. It does not fall back to writing your token in cleartext under a promise of encryption. Values that could not be migrated keep working and are listed as `plaintext`, with a warning, every time: + +``` +Stored variables (values hidden) — macOS Keychain, service 'mem-cli-vars' + API_TOKEN keychain last used 2h ago + LEGACY_TOKEN plaintext never used + + ! 1 value(s) are still in plaintext in ~/.mem/vars.json. +``` + +Two limits worth knowing: a value is capped at roughly 2 KB (`security` truncates longer command lines instead of failing, so mem refuses them), and `mem forget` has to ask the Keychain for each stored value in order to match it — the only place mem reads them all. + ### Variable status in listings `mem list` shows whether each variable is ready: diff --git a/docs/decisions/010-keychain-for-variable-values.md b/docs/decisions/010-keychain-for-variable-values.md new file mode 100644 index 0000000..0356e41 --- /dev/null +++ b/docs/decisions/010-keychain-for-variable-values.md @@ -0,0 +1,78 @@ +# ADR-010: Variable Values Live in the macOS Keychain, Not in a 0600 File + +**Status**: Accepted — amends PHILOSOPHY.md (Principle III) for the variable store only. +**Date**: 2026-08-04 + +## Context + +`mem vars set API_TOKEN` wrote the value into `~/.mem/vars.json` as cleartext JSON, mode 0600: + +```json +{"vars": {"API_TOKEN": {"value": "sk-live-…", "last_used": 0}}} +``` + +0600 stops *other users*. It stops nothing else, and nothing else is the actual threat model for a developer laptop: + +- Time Machine, Backblaze, or any backup agent copies it verbatim, and the copy is not 0600 anywhere it lands. +- A `~/Dropbox`-style synced folder, or a dotfiles repo that globbed too widely, publishes it. +- Every process running as the user reads it without so much as a prompt — an `npm install` postinstall script, a VS Code extension, a `curl | sh` that went badly. +- A stolen machine that was awake or a disk image taken from it gives it up directly. + +For a tool whose first principle is *privacy* and whose README says "your shell history never leaves the machine", a plaintext file of API tokens and database passwords was the weakest thing in it — and the one that would appear in the first security review. + +macOS ships the purpose-built answer, and this project has already decided to lean into the platform (ADR-002, ADR-006, ADR-008): the **Keychain**. Items are encrypted at rest with a key derived from the login password, the login keychain locks with the session, and access is mediated by the OS rather than by file permissions. + +The constraint is that `security(1)` is the only way in without a dependency, and `security` is a tool with sharp edges. Everything below was established by running it, not by reading the man page: + +| Behaviour | Observed | +|---|---| +| `-w ` | Documented, and puts the secret in `argv` — `security`'s own help says "Use of the -p or -w options is insecure" | +| `-w` as the last option (prompts) | Needs a controlling terminal: with a pipe on stdin it exits 2, and with `-w` omitted entirely it silently stores an **empty** password | +| `security -i` | Reads command lines from **stdin**; `argv` is just `["security", "-i"]` | +| `-X ` | Takes the value as hexadecimal — no quoting, no metacharacters, no newlines | +| `find-generic-password -w` | Prints printable data raw and binary data as bare hex — **indistinguishable**, so a 32-character hex API key decodes into 16 bytes of garbage | +| `find-generic-password -g` | Unambiguous: `password: 0x ""` for anything non-printable, `password: ""` otherwise | +| `security -i` line length | Truncates at 4096 characters **and executes the truncated head**. An 8 KB value produced a Keychain item holding a silently truncated secret | + +## Decision + +**Variable values are stored in the macOS Keychain as generic passwords.** `~/.mem/vars.json` remains, demoted to an index: which variables exist and when each was last used. + +Concretely: + +- **Service** `mem-cli-vars`, **account** = the variable name, **label** `mem-cli-vars:API_TOKEN`. One `grep` in Keychain Access finds everything mem owns and nothing else. +- **Writes go over stdin**, via `security -i`, hex-encoded with `-X`. The secret never appears in `argv`, so `ps` never shows it; the hex sidesteps the interactive tokenizer entirely, so a value containing `"`, `\`, `$(…)` or a newline cannot be misparsed. The item still holds the **real bytes**, so `security find-generic-password -s mem-cli-vars -a API_TOKEN -w` returns the user's own secret without mem in the loop. +- **Reads use `-g`**, never `-w`, for the disambiguation reason in the table above. +- **A value that would not fit in one command line is refused** (`KeychainValueTooLong`), because the alternative is a truncated secret stored under a name that claims to be intact. That caps a value at roughly 2 KB. +- **Migration is confirm-then-delete, per variable.** Write to the Keychain → read it back → compare → only then rewrite `vars.json` without the value, under the existing `exclusive_lock` and `atomic_write`. It runs on first use of any `mem vars` command and on the `mem run` resolution path, it is idempotent, and every failure mode leaves the plaintext copy exactly where it was for the next attempt to find. +- **There is no plaintext fallback for new values.** When the Keychain is unavailable, `mem vars set` fails, says why in `security`'s own words, and stores nothing. +- **Values that could not be migrated keep working**, and are reported as `plaintext` in `mem vars list` with a warning, every time. Refusing to read them would punish the user for the state of their keychain, and deleting them would be data loss. +- **The backend is derived, not declared.** An entry is Keychain-backed *because* it has no value in the file. A `backend` field that could disagree with the file's contents would eventually claim "keychain" over a cleartext secret. + +## Cost of this decision (stated plainly) + +- **A subprocess per read.** ~15 ms per variable, on `mem run` only, and only for the variables that run actually needs. Listing a runbook deliberately does not read values. +- **A possible OS prompt.** `security` is trusted to read what `security` created, so in practice mem does not trigger the "wants to access your keychain" dialog — but a locked keychain, a keychain-access reset, or a login-password change can, and mem cannot predict it. Every call is therefore bounded by a 60 s timeout, so a dialog nobody sees fails the command instead of wedging the shell. +- **macOS only.** The variable store now genuinely does not work off macOS, where before it degraded to a file that worked everywhere. mem is a macOS tool by decision; this makes it true of one more subsystem. +- **`mem forget` costs one `security` call per stored variable**, because matching a value requires reading it. It is rare, explicit and destructive; the alternative — matching on names only — would report success while leaving the secret in the Keychain. +- **mem now writes outside `~/.mem`.** Uninstalling by `rm -rf ~/.mem` leaves the Keychain items behind. `mem vars clear` is the way to take them back, and the items are visible and deletable in Keychain Access. +- **The old plaintext may survive on disk.** Migration replaces `vars.json` atomically, but the previous contents can persist in unallocated blocks. The Keychain protects future writes; it cannot un-write the past. + +## Alternatives Considered + +- **Do nothing — keep the 0600 file.** Rejected. It is the threat model above, unanswered, in the one project whose entire pitch is privacy. "Nobody else can read your files" is a claim about multi-user Unix in 1985, not about a laptop running a package manager. +- **Encrypt the file with a passphrase mem asks for.** Rejected on three counts. It would need a KDF and an AEAD (`hashlib.pbkdf2_hmac` exists; a well-reviewed AEAD in the stdlib does not — rolling our own is exactly the mistake this ADR is trying to avoid). It would prompt on every `mem run`, which Principle V ("a tool that nags will be uninstalled within a day") rules out, and caching the derived key to avoid that recreates a smaller version of the original problem. And the passphrase would in practice be the login password, typed into a CLI instead of into the OS — strictly worse than letting the OS hold it. +- **Keychain via a library (`keyring`, `pyobjc`).** Rejected: new dependencies, which is a hard constitutional rule, and both are far larger than the ~250 lines of `subprocess` this replaces. `keyring` also brings a plugin architecture whose backends are decided at runtime by what is installed — the opposite of a tool that can state where a secret is. +- **`security add-generic-password -w ` (the documented form).** Rejected: `argv` is world-readable through `ps`. Any process on the machine can watch for it. This is the single detail that most implementations get wrong. +- **The `-w` prompt, driven through a pty.** Rejected after testing: with a pipe on stdin it is a usage error, and a pty in canonical mode caps a line at 1024 bytes and cannot carry a newline — so it is both smaller and less capable than `security -i`, for more machinery. +- **Store our own hex encoding as the password text** (so `-w` reads unambiguously). Rejected: it makes the item unreadable to anything but mem. `security find-generic-password -w` and Keychain Access would show the user hexadecimal instead of their own token, which turns a credential store into lock-in. Parsing `-g` is a few lines of ours; opacity would be the user's forever. +- **Split long values across several Keychain items.** Rejected as complexity for a case that does not exist: a variable is a shell value, and 2 KB is far past any token or password. A private key belongs in a file whose *path* is the variable. +- **Silently fall back to plaintext when the Keychain is unavailable.** Rejected, emphatically. It is the most dangerous option on this list: the user reads "values are stored in the Keychain", believes it, and stops treating `~/.mem` as sensitive — while mem quietly writes cleartext on exactly the machines (CI, a locked laptop, a shared box) where it matters most. A failure the user sees is worth more than a success that is not true. + +## Consequences + +- `vars.json` becomes an index, and its `value` field is `null` for every entry mem writes from now on. It stays 0600: the *list* of variable names is worth keeping private on its own, and any not-yet-migrated entry is still a cleartext secret. +- Principle III says the plain-text files are the only source of truth. For variable **values** that is no longer true, and this ADR is the public amendment rather than a quiet exception. The properties the principle exists to protect still hold: there is exactly one source of truth for a value, it is not mem's private format, and the user can read it without mem (`security find-generic-password`, Keychain Access). No mem-owned second copy exists anywhere. +- The test suite must never touch the developer's login keychain, so `conftest.FakeKeychain` replaces the single function that spawns `security`, and the genuine end-to-end tests are marked `keychain_live` — deselected by default, run with `pytest -m keychain_live`, and pointed at a throwaway keychain via `MEM_KEYCHAIN`. +- `mem vars set NAME` now hides what is typed, as the README always claimed it did. Passing the value inline still works and now warns that it was visible to `ps` and captured into the user's own shell history — mem's `argv` is the last place a secret can still leak, and mem is the thing recording it. +- Anyone porting mem beyond macOS inherits a clear seam: `mem/keychain.py` is the whole backend, and `unavailable_reason()` is where another platform's answer would go.