# Keychain

zelk can keep its credentials in the operating system's keychain instead
of in plain files under `~/.config/zelk`. It is opt-in: the default stays
the file, and a user or a managed policy chooses the keychain.

## What zelk keeps

Each credential is a JSON document in zelk's config directory
(`$XDG_CONFIG_HOME/zelk`, else `~/.config/zelk`), kept through
`core/secret` (`secret.Document`: lock, owner checks, atomic write).

| File | Holds |
|---|---|
| `chatgpt.json` | The ChatGPT plan sign-in: an access token, a refresh token that rotates on every use, and account and client details kept after sign-out |
| `mcp-oauth.json` | Every MCP server's OAuth client and tokens, in one document. Signing out of one server keeps its client registration |
| `browser.json` | The user-browser pairing key, which lets whoever holds it drive the user's Chrome |
| `provider-keys.json` | The API keys provider profiles name by ID ([Provider keys](#provider-keys)) |

`providers.json`, the provider profiles, holds no secret of its own once
its literal keys are moved: a profile's `key` is `"#<id>"` or a `$NAME`
reference. It is replaced atomically under `provider-keys`' lock.

## Decisions

1. **The default is the file.** Whether a keychain is reachable depends on
   the session (desktop, SSH, an old tmux server, WSL, CI). Where a
   credential lives doesn't change between sessions. A default that moves
   credentials into the keychain would make a desktop sign-in unusable
   from SSH on the same machine. The keychain is a setting, which a
   managed policy can require.
2. **Literal provider keys move out of `providers.json`** into a key
   document, referenced by a stable ID (see [Provider keys](#provider-keys)).
3. **MCP config secrets stay in the config.** `$NAME` references work.
   Keychain references in the MCP config, which would also cover the
   OAuth client secret, are not yet implemented.
4. **Nothing moves by itself.** Existing documents, including literal
   provider keys, move only when the user runs `zelk credentials move`.
   The setting decides where a document goes when it is created, and
   nothing else.

## Not goals

- The MCP config's literal values (decision 3).
- `user_browser_export_session` cookie files, which are exports the user
  asked for.
- Hiding credentials from zelk itself, or from commands zelk runs outside
  a sandbox (see [What it protects](#what-it-protects-and-what-it-doesnt)).

## The setting

The setting `credential_store` is saved in `config.json`, has a row in
the TUI's Settings, and has a flag, `-credential-store`.

| Value | Where new documents go |
|---|---|
| `file` (default) | The file |
| `keychain` | The keychain. When the keychain can't be used, saving fails and the error says why. It never falls back to the file |

## Documents, markers and intents

**The file at a document's usual path decides where the document lives.**

| The file holds | The document is |
|---|---|
| Nothing (no file) | Absent |
| The document's JSON | In the file |
| A marker | In the keychain item the marker names |

The marker is a small, versioned JSON object:

```json
{"zelk_credentials": {"v": 1, "ref": {"backend": "secret-service", "id": "9f3c…", "location": "/org/freedesktop/secrets/collection/login"}, "dir": {"dev": 2049, "ino": 1311042}}}
```

- **`ref`** says exactly where the item is:
  - `backend` is `secret-service`, `macos-keychain` or
    `windows-credential-manager`;
  - `id` is 128 random bits, the item's identity;
  - `location` is the keychain file (macOS), the collection (Secret
    Service) or the target-name prefix (Windows) the item was created in. Every later operation targets that
    location, so a changed default keychain or collection can't send it
    elsewhere.
- **No folder path in the identity.** Renaming the config folder, or
  reaching it through a symlink, doesn't lose the item.
- **`dir`** is the config folder's device and inode when the item was
  created (on Windows its volume serial number and 128-bit file ID, the
  upper half in `ino_hi`). A rename keeps both. A copy, a restore from backup, or a move
  across filesystems changes them. zelk deletes an item only when `dir`
  matches the folder it is working in (see below).

**Items are never changed in place.** Every write of a document creates a
new item under a new `ref`, publishes a marker naming it, and then lets
the old item go. So an item, once published, holds one version for its
whole life. A write that is still running, or was lost, can only land on
an item no marker names.

**An intent file** sits beside the document: `<file>.intent`. It lists the
`ref`s of items that a step is about to create or let go. Each `ref`
carries its own owner: the `dir` of the marker that named it (the folder
it was created in, for a new item). It is written
and synced before the vault is touched, and removed once the step is
published, followed by a directory sync. Because an intent lives in the
same directory as the document it guards, renames and copies carry it
along with that document.

**Finishing what was started.** Every exclusive access finishes a
leftover intent before doing its own work:
1. **Sync the directory first.** The marker or document that recovery is
   about to trust may have been renamed into place by a process that died
   before its directory sync. If the sync fails, recovery stops and
   deletes nothing.
2. **Apply one rule:** an item is kept exactly when the file's current
   marker names it. Every other `ref` in the intent is deleted (a missing
   item is fine), but only when that `ref`'s own recorded owner matches
   this folder. Otherwise the item is left alone: it belongs to the
   folder this one was copied from. Ownership is judged per `ref`, never
   by the current marker, so a copy that has published its own item
   still can't delete the original's.
3. **Remove the intent and sync the directory.**

No scan of the keychain is ever needed, and nothing is deleted on the
strength of a label.

**Copies.** A copied folder's marker names the original's item.
- **Reads work.**
- **The copy's first write** creates its own item and records the copy's
  `dir`. It leaves the original's item alone, because that `ref`'s owner
  is the original. A purge, or a move to the file, works the same way.
  From then on, the two folders share nothing.
- **The original doesn't know about the copy.** Until the copy writes,
  the original's own update, move or purge can delete the item the copy
  still names. Both folders take their own lock, so the copy can't stop
  it. The copy then reads `ErrMissingItem`, never "no credentials", and
  the user signs in again there.

  Copying a config folder that holds keychain credentials is therefore
  supported only for a copy that writes before the original does. Nothing
  in zelk copies config folders. Live tests use fresh scratch folders.

**What can be left behind.** An unpublished item can survive recovery.
For example, a create whose outcome was uncertain may commit only after
recovery found the item missing. Such an item sits in the keychain,
encrypted like any other, and no marker names it, so zelk never reads
it. This is the only garbage the design can leave, and it never makes
a document wrong.

**Recognised whatever the host configured.** `credfile` checks for a
marker and an intent before decoding a document or calling an update
function:
- A marker with no vault configured for its backend returns
  `ErrInVault`, naming the backend. This covers a library user who never
  set up a keychain.
- A marker whose item is missing returns `ErrMissingItem`. That covers
  another machine sharing the home directory, a keychain reset, or a
  deleted item.
- An intent that a reader can't finish (it holds only the shared lock)
  makes the read take the exclusive lock first (next section).

No state ever reads as "no credentials", and none lets an update write a
fresh plain file. `zelk credentials purge` is the explicit way out: it
signs the user out of that document.

## Locking

- **Reads.** `Read` takes a shared lock (`flock` on Unix, a byte-range lock on Windows) on `<file>.lock`. It reads the
  file, and the item if the file holds a marker, before releasing the
  lock. Without that, a read could see a marker, lose a race with a move,
  and find the item gone.
- **Leftover intents.** If a read finds an intent, it releases the shared
  lock, takes the exclusive one, reads everything again, finishes the
  intent and reads under the exclusive lock. It never upgrades a lock it
  holds.
- **Writes.** Updates, moves and purges hold the exclusive lock
  throughout.
- **One lock per document,** never two at once, except provider edits
  (see [Provider keys](#provider-keys)). Those take `provider-keys`'
  lock and nothing else.
- **A public, lock-held API.** The lock-holding API is public so hosts
  can build transactions on it (see [Code shape](#code-shape)):

  ```go
  tx, err := doc.Begin(ctx) // exclusive lock; leftover intents finished
  defer tx.End()
  data, err := tx.Read(ctx)
  err = tx.Write(ctx, data) // file or item, as the marker says
  ```

  `Update` is `Begin`, `Read`, the caller's function, `Write`, `End`.

## Every step, crash by crash

Each step below runs under the document's exclusive lock. The rules for
files:
- **Writes.** A file is written to a synced staging file named
  `<file>.tmp`, renamed into place, and followed by a directory sync. The
  staging name is fixed, not random, so every exclusive access can remove
  a stale `<file>.tmp` that a dead process left behind. The lock means
  only one writer ever uses that name.
- **Removals.** A file is unlinked, then the directory is synced.
- **Folders.** The first exclusive access in each process syncs the
  config folder's parent, and each folder above it up to the home
  directory, before publishing anything. It does this whether or not the
  process made those folders, because a process that made them may have
  died before syncing. A power cut then can't drop a published marker
  together with its folder.
- **Order.** The step that follows waits for the sync.

**Creating a document with `keychain` set** (no file exists):
1. Write an intent with a new `ref`.
2. Put the item.
3. Write the marker.
4. Remove the intent.

| Crash after | What the next access sees | Result |
|---|---|---|
| 1 or 2 | No marker | The intent deletes the item if one exists. The document is absent, which is true: nothing was saved. |
| 3 | The marker | The intent is just removed. |

**Updating a document in the keychain** (a token renewal, a sign-out, a
new provider key):
1. Write an intent listing a new `ref` and the current one.
2. Put the new item.
3. Rename a marker naming the new `ref` over the old marker.
4. Delete the old item (only if `dir` matches).
5. Remove the intent.

| Crash after | Result |
|---|---|
| 1 or 2 | The old marker is still there. The new item is deleted, and the old version stands. |
| 3 | The new marker stands, and the old item is deleted. |
| 4 | The intent is removed. |

Step 3 commits the update. A delete in step 4 that fails (the keychain
locked, the context canceled) doesn't fail it: the intent stays, and
the next access deletes the old item, as after a crash. A second write
in the same transaction keeps that item in its own intent, so it is
never forgotten; and once the old item is gone, failing to remove the
intent doesn't fail the update either. A move to the
file commits when the file is written, the same way. Only a purge
reports a failed delete, since deleting is its purpose.

An update costs one create and one delete in the keychain, where an
in-place change would cost one replace. The extra work is the price of
never having to guess which version a half-finished write left.

**`zelk credentials move -to keychain`:**
1. Write an intent with a new `ref`.
2. Put the item.
3. Read it back and compare it with the file.
4. Rename the marker over the file.
5. Remove the intent.

Until step 4, the file still holds the document, and the intent deletes
the unpublished item.

**`zelk credentials move -to file`:**
1. Get the item.
2. Write an intent naming its `ref`.
3. Rename the document over the marker.
4. Delete the item.
5. Remove the intent.

Before step 3, the marker still names the item, so a leftover intent
keeps it. After step 3, the marker is gone, so the intent finishes the
delete.

**`zelk credentials purge`:**
1. Write an intent naming the marker's `ref`.
2. Unlink the file and sync the directory.
3. Delete the item.
4. Remove the intent.

Before step 2, the marker keeps the item. After it, the intent deletes the
item. The lock file stays.

**Signing out** isn't a purge. `zelk logout`, and signing out of an MCP
server or a provider, update the document. The document
stays where it lives, and so do the parts that outlive a sign-out: the
other MCP servers, client registrations and ChatGPT's account details.

**Results are reported as they happened.** Once a vault call returns, its
result is what zelk reports, even if the context was canceled meanwhile.
A put that went through is a success. Otherwise a canceled sign-in would
read as failed and revoke tokens it had just saved (`saveSignIn`).

**Uncertain outcomes.** A call whose outcome zelk can't know returns
`ErrUncertain`. Examples are a Secret Service prompt whose `Completed`
signal never came, or a connection lost mid-call.
- **What zelk does.** It doesn't publish the marker, and the intent
  settles the step on the next access. Because the new item was never
  published, nothing a late commit does can change which version is
  current. The worst case is the unreferenced item described above.
- **What callers do.** Callers treat `ErrUncertain` as "don't revoke, try
  again". The sign-in's new tokens may be lost, but the old document is
  intact.

**Durability is the provider's.**
- A put, then a read-back that matches, proves the provider has the
  secret. It doesn't prove the provider has written it to disk.
- **GNOME Keyring**, the tested provider, syncs its keyring file and
  renames it into place when an item changes. It doesn't sync the
  directory, so a power cut can still roll it back.
- **What a rollback looks like.** A vault that rolls back can lose a
  renewed refresh token, or the item that a newer marker names.
  - The second case reads as `ErrMissingItem`, never as "no credentials".
  - The user signs in again, through `zelk credentials purge` and
    `zelk login`.
- **KeePassXC** can delay or skip saving its database. A move, or a
  renewed refresh token, can then be lost if KeePassXC exits without
  saving.
- **KWallet** isn't tested.

The docs name the tested provider and say this. A provider crash in the
middle of `CreateItem` can also leave an item without a secret. zelk
treats an item whose secret is empty or isn't valid JSON as missing.

The fault-injection tests stop at every numbered boundary above, and at
the directory syncs. They also kill the fake vault partway through a put.

## Provider keys

- **A separate key document.** New literal keys go to a fourth credential
  document, `provider-keys`, which maps key IDs (128 random bits) to keys.
  It is created like any document, so the setting decides where it goes.
- **What a profile holds instead.** The profile's `key` becomes
  `"#<id>"`. A `$NAME` reference stays as it is.
- **Renames keep the key.** Renaming a profile doesn't touch its key.

**One lock for both files.** `provider-keys`' lock guards
`providers.json` too. Every edit runs in one transaction:
1. `Begin` on `provider-keys`.
2. Load `providers.json` fresh and apply the one edit (add, rename, remove
   or change a key).
3. If the edit adds or changes a key, write `provider-keys` with the new
   ID added.
4. Replace `providers.json` atomically, then sync the directory.
5. Write `provider-keys` without the IDs that no profile references.
6. `End`.

Through `tx.Write`, steps 3 and 5 use the protocol in
[Every step](#every-step-crash-by-crash). A crash after 3 or 4 leaves an
unreferenced key, which the next edit's step 5 removes. A profile never
points to a key that doesn't exist.

**Reads resolve the whole profile under the same lock.** A load reads
`providers.json` and `provider-keys` in one shared-lock view, and gives
each profile its key from that view. The TUI's registry builds clients,
and runs model discovery, from the profiles it loaded or last saved. So a
profile whose URL and key changed together elsewhere stays the old pair
until the registry next loads or saves, and never mixes the new key with
the old URL. A key document out of reach fails only the profiles that
name it.

**Literal keys already in `providers.json`** keep working until the user
runs `zelk credentials move` (decision 4). That command moves them into
`provider-keys`, in the same transaction, to the place the user names.
Under a managed policy of `"keychain"`, a literal key counts as a plain
document, and is refused like one.

## Backends

Each backend implements one small interface (see [Code shape](#code-shape)).

**Errors are typed, and none of them falls back to the file:**
- `ErrUnavailable`: no service.
- `ErrLocked`: the keychain is locked and zelk may not show a prompt.
- `ErrDenied`: the user, the access list or the provider refused.
- `ErrMissingItem`.
- `ErrUncertain`.
- `ErrCorrupt`, for two items with one id, or a malformed marker or
  intent.

### Prompts

Each operation is either interactive or not, and the host says which. A
background operation never starts any UI. An operation is interactive
only when a person is attending and asked for it:
- `zelk login`;
- `zelk credentials`;
- a sign-in or key entry in the TUI;
- a token renewal while the TUI is open.

Everything else is background, and gets `ErrLocked` or `ErrDenied` with
the command that fixes it:
- `exec` and `-p`;
- `zelk acp`;
- cron and watch wakes.

### Linux: the Secret Service over D-Bus

zelk talks to `org.freedesktop.secrets` on the session bus, which GNOME
Keyring, KWallet (version 5.97 and later) and KeePassXC provide. It uses
[godbus/dbus](https://github.com/godbus/dbus), which is pure Go. zelk
needs only a small part of the protocol, and we write that client
ourselves:
- `OpenSession`;
- `SearchItems` within the recorded collection, by `id`;
- `CreateItem` for new ids only, never with replace;
- `Item.GetSecret`;
- `Item.Delete`;
- `Unlock`, and `Prompt` with `Dismiss`.

Items carry the attributes `application=zelk` and `id=<id>`, and a
`document` attribute for labels only. Finding two items with one id
returns `ErrCorrupt`, and neither item is used.

**The transfer is unencrypted (the `plain` algorithm), a choice made on
purpose:**
- A process running as the same user that monitors the bus sees the
  secret as it passes.
- With GNOME Keyring, the tested provider, that process could just as well
  call `GetSecret`, so encryption would hide nothing.
- KeePassXC can ask the user before a client reads an item. A bus monitor
  gets around that check on the reads zelk makes.
- The encrypted algorithm would need finite-field Diffie-Hellman, which
  Go's standard library doesn't have, so it means crypto code of our own.

If KeePassXC support matters more than that crypto, the `dh-ietf1024`
session is not yet implemented.

**Locked collections.**
- Background: zelk doesn't call `Unlock`, and returns `ErrLocked`.
- Interactive: zelk calls `Unlock`, runs the prompt and waits for its
  `Completed` signal. On cancellation, it calls `Dismiss` and waits a
  short while for `Completed`. If that signal doesn't come, the result is
  `ErrUncertain`. The service decides where its dialog appears, which over
  SSH may be a desktop elsewhere, so zelk's message says a dialog may be
  waiting.
- Creating and deleting follow the same rules, since either can return a
  prompt.

`keyctl` (the kernel keyring) doesn't qualify. It forgets everything at
logout or reboot, and a sign-in has to outlive both.

### macOS: the login keychain through Security.framework

zelk calls the `SecItem*` functions through
[purego](https://github.com/ebitengine/purego), which works with
`CGO_ENABLED=0` on amd64 and arm64. The items are generic passwords
with service `zelk` and account `<id>`. They are created in the login
keychain, and every query is pinned to the keychain file the marker
records, through `kSecUseKeychain` and `kSecMatchSearchList`.

**Prompts.** `kSecUseAuthenticationUIFail` governs the data-protection
keychain, not the file-based login keychain, so it is not what keeps
background calls quiet:
- **The switch.** For the login keychain, the switch is
  `SecKeychainSetUserInteractionAllowed`. It is process-wide, so the
  vault holds one mutex around every keychain call. Under that mutex, it
  sets interaction on or off for the call and restores it afterwards.
- **No other keychain code.** Nothing else in zelk touches the keychain,
  so nothing else can race it.
- **Tested.** The tests cover both kinds of prompt: a locked keychain,
  and a build the access list doesn't trust.

**Interactive calls can't be canceled.** They are synchronous, so zelk
waits for the dialog. Once the call returns, its real result is reported
(see [Every step](#every-step-crash-by-crash)). zelk makes these calls only
where a person is in front of the dialog.

**The access list trusts the binary that created the item.**
- Signed release builds keep one identity across upgrades.
- Unsigned and ad-hoc development builds change identity with every
  build. After a rebuild, the first interactive access asks again.
  Background access gets `ErrDenied`, with "run `zelk credentials` to
  approve this build".
- Only signed builds are supported for unattended use, and the docs say
  so.

Not `/usr/bin/security`: the item's access list would then trust
`security`, so any command could read it with `find-generic-password -w`.

### Windows: the Credential Manager

zelk calls `CredReadW`, `CredWriteW`, `CredDeleteW`, `CredEnumerateW` and
`CredFree` in advapi32 through `golang.org/x/sys/windows`' lazy DLL
loader, so builds stay `CGO_ENABLED=0`. `x/sys/windows` has no wrappers for
them, so the declarations are our own. The items are generic credentials
(`CRED_TYPE_GENERIC`) in the user's own credential set, which Windows
encrypts with the user's key. There is no lock to open and no prompt to
show, so `WithInteractive` changes nothing. A logon session that has no
credential set, which Microsoft says a network logon doesn't, makes every
call `ErrUnavailable`, saying so.

Three limits of the platform decide the shape of the backend:

1. **A blob holds 2,560 bytes** (`CRED_MAX_CREDENTIAL_BLOB_SIZE`), and a
   ChatGPT sign-in or the MCP OAuth document can be larger.
2. **`CredWriteW` replaces silently.** It has no create-only flag. The
   only flag, `CRED_PRESERVE_CREDENTIAL_BLOB`, keeps the blob of an
   existing credential.
3. **A target name is case-insensitive** and is the only key.

**Large documents: a manifest written last.** One item is several
credentials, all named by the item's id and the namespace `zelk:`, which
no other program's credential carries:

| Target name | Blob |
|---|---|
| `zelk:<id>` | A 48-byte header, then the document's first bytes (at most 2,512) |
| `zelk:<id>:1`, `zelk:<id>:2`, … | The next 2,560 bytes of the document each |

The header is the magic `ZKC1`, the document's size, its part count and
its SHA-256. A document of 2,512 bytes or less is one credential.

- **Create** writes the parts in order and the manifest last.
- **Get** reads the manifest, then every part, and returns the document
  only when the sizes agree and the hash matches. A missing manifest, a
  missing part, a part of other bytes, a damaged header: the item "holds no
  usable document", which is `ErrMissingItem`, as the contract says for an
  item with an empty or partial secret. It is never a partial document and
  never "no credentials".
- **Delete** removes the manifest first, so the item reads as missing at
  once, and then every credential whose name is the item's, found by
  listing the prefix `zelk:<id>`, not by counting from the header. So a
  gap, a part left by a Create that died before its manifest, or a Delete
  that stopped halfway leaves nothing a second Delete can't find. Only the
  manifest and `:<digits>` parts are deleted: a credential that merely
  begins the same is left alone.

**Crashes.** The unit of publication is still the marker, as in the
contract: no marker names an item before `Create` returns. What a crash
leaves is therefore the same as for the other backends:

| Crash | What the next access sees |
|---|---|
| In Create, before the manifest | Parts, no manifest. No marker names the item, so the document's intent deletes them (`Delete` finds them by name). A `Get` of the ref says `ErrMissingItem` |
| In Create, after the manifest | A whole item, which the intent deletes or keeps by the marker, as for any item |
| In Delete | An item that reads as missing, or whole if the first delete never ran; the next `Delete` finishes it |

**Create, don't replace.** A `Document` creates each item under a fresh
128-bit id, and holds the document's file lock throughout, so two writers of
one ref don't exist inside the contract. The vault still enforces it,
because `CredWriteW` would hide the breach:

1. `Create` takes a kernel mutex named by a hash of the namespace and the
   id (`Global\zelk-credential-<hash>`), without waiting: a writer that finds
   it held is refused with `ErrCorrupt`, since another writer is
   creating this very item. The mutex is shared by every process and logon
   session of the machine.
2. It waits for the user's store mutex, then reads the manifest's name:
   an existing item is refused with `ErrCorrupt`.
3. It writes the parts and the manifest, then reads the item back and
   compares it with what it wrote. A `Create` that returns therefore proves
   the Credential Manager holds the item, and that nothing replaced it
   meanwhile; a mismatch is `ErrCorrupt`.

With concurrent writers of one ref, exactly one succeeds and the item is
that writer's, whole. A writer that doesn't take the mutex (another
program writing a `zelk:<id>` credential) is outside what zelk can
prevent; step 3 and `Get`'s hash catch the damage when they can, and
nothing a damaged item holds is ever returned.

**Serialize store mutations.** Overlapping `CredWriteW` calls can report
success for distinct targets that are then absent from both `CredReadW`
and `CredEnumerateW`. `Create` and `Delete` therefore take a second
kernel mutex named by the effective user's SID
(`Global\zelk-credential-store-<sid>`), shared across zelk processes,
logon sessions and target-name prefixes for that user. `Create` holds it
through read-back and any rollback, and `Delete` holds it from enumeration
through the final deletion. Waiting for the store is cancelable. The
per-item mutex is taken first, so a competing `Create` of the same ref is
still refused immediately. `Get` reads independently and checks every
part against the manifest.

**Failures are reported as they happened.** A call to the Credential
Manager is synchronous and local, so none returns `ErrUncertain`.
`Create` checks the context between credentials and, if it ends, removes
what it wrote. Once the manifest is written it reads the item back without
the context, so the result is what happened.

**Persistence: local machine.** Credentials are written with
`CRED_PERSIST_LOCAL_MACHINE`: they outlive the logon session and this
computer's restarts, and no other computer sees them. `CRED_PERSIST_ENTERPRISE`
would let Windows roam them to the user's other computers. The marker that
names a credential lives in the config directory on this one, so a roamed
copy would have nothing naming it on the others, and would hold a
refresh token that rotates here and nowhere else. `CRED_PERSIST_SESSION`
would drop a sign-in at logoff.

**What is left behind.** An item whose `Create` returned an error after
writing, with a delete that failed too, is parts and perhaps a manifest
no marker names, which the document's intent removes. Names are
`zelk:<32 hex digits>[:n]`, and the comment holds the document's label (for
example `zelk: ChatGPT sign-in`, with `(part n)` on parts), so the user can
see in the Windows Credential Manager, under Windows Credentials, what
zelk made.

**Durability** is Windows': `CredWriteW` returns once the credential is
in the user's credential store, and the read-back proves it can be read.
Windows doesn't promise it has reached the disk if the power fails.

## Managed policy

One key of the [managed policy](/internals/managed-policy/) concerns it:

```json
{ "credential_store": "keychain" }
```

| Value | Effect |
|---|---|
| `"keychain"` | New credentials must go to the keychain. A user's `file` is overridden with a warning (policy wins, as for other keys). A document still in a plain file is refused, by reads and by updates, with an error naming `zelk credentials move -to keychain`. That includes literal keys in `providers.json`. Where no keychain can be used, zelk still starts, but signing in, saving a key, or using a document fails with the reason. |
| `"any"` | Lifts a requirement an earlier policy file set. |

**zelk can't forbid the keychain.** No organisation needs to stop a user
from making credentials safer, so the policy has no value that does.

## What it protects and what it doesn't

**Protects:** no credential document in zelk's config directory holds a
secret in plain text, whether in the files, in backups of that directory,
or for anything that reads files under `~/.config`.
- **The secret is still stored somewhere.** How well it's protected on
  disk now depends on the vault: the macOS login keychain and a KeePassXC
  database are encrypted files of their own, and they get backed up and
  synced like any file.
- **Old backups keep old plain files.** Plain files backed up before a
  move still hold their secrets.

**Protects only where the sandbox confines inter-process communication:**

| Sandbox | Session bus or keychain reachable from a command? |
|---|---|
| bwrap, network `off` or allowlist | **Abstract-address buses: no.** The command has its own network namespace, which is where abstract sockets live. **Path-based buses: no, unless the socket is under a path bwrap binds** (the workspace, a `-sandbox-read-only` path, a toolchain directory). `/run`, the systemd default home of the bus, isn't bound. |
| bwrap, network `full` | **Abstract-address buses: reachable.** `--share-net` shares the namespace they live in, and the command filter can only refuse whole socket families. **Path-based buses:** the same as above. |
| seatbelt | **No.** The profile denies `mach-lookup` of the keychain's daemons (securityd's `com.apple.SecurityServer`, `com.apple.securityd` and its XPC name, SecurityAgent and authhost), so a sandboxed command can't read keychain items even from a keychain file it may read (`TestSeatbeltKeychain`). `trustd`, which checks TLS certificates, stays reachable. |
| MXC (Windows) | **No.** MXC denies Credential Manager access. DPAPI can decrypt any readable protected blob. |
| none (Windows) | Reachable: a program running as the user can read a credential with `CredReadW`, and list zelk's by their `zelk:` names. |
| none | Reachable (next list). |

**The bwrap warning.** When `keychain` is set and bwrap is in use, zelk
reads `DBUS_SESSION_BUS_ADDRESS` (else the systemd bus in
`$XDG_RUNTIME_DIR`). It warns once, with the sandbox note, when the bus is
an abstract socket and the network is `full`, or when the bus is a path
under the workspace or a `-sandbox-read-only` path. The toolchain
directories bwrap adds aren't checked: they hold installed tools, not
sockets.

**Doesn't protect against:**
- **Commands outside a sandbox.**
  - On Linux, a command can read an unlocked collection, unless the
    provider asks first (KeePassXC can).
  - On macOS, the keychain trusts zelk, and a command can run zelk:
    `zelk credentials move -to file` is enough. The keychain's prompt
    can't tell a person from a model.
  - On Windows, the Credential Manager doesn't ask before a program of
    the user's reads a credential, so a command can read it directly or
    run `zelk credentials move -to file`.
- **zelk itself.** zelk holds the secret in memory while it uses it.

## Code shape

- **`core/secret` (public).** It keeps every credential document:
  - `secret.Document`, with `Read`, `Begin`/`Tx`, `Update`, `Move` and `Purge`;
  - markers and intents;
  - the `Vault` interface and its typed errors;
  - `WithInteractive`, carried on the context;
  - `secrettest`, the conformance kit.

  `cmd/zelk` needs the transaction API for provider keys, and it can't
  import `core/internal`, so this has to be public.

  ```go
  // Ref names one item: backend, id and location.
  type Ref struct{ Backend, ID, Location string }

  // Vault keeps whole documents. Callers hold the document's lock around
  // every call; a Vault needs no locking of its own.
  type Vault interface {
      Backend() string
      NewRef(ctx context.Context) (Ref, error) // fresh id at the default location
      Get(ctx context.Context, r Ref) ([]byte, error)
      Create(ctx context.Context, r Ref, label string, data []byte) error // never replaces
      Delete(ctx context.Context, r Ref) error // a missing item is not an error
  }
  ```

  It takes options of its own:
  - `secret.WithVault(v)`;
  - `secret.WithNewIn(secret.InVault)` or `secret.WithNewIn(secret.InFile)`,
    which picks where new documents go;
  - `secret.WithRequireVault()`, for the managed policy.
- **The existing stores.** `chatgpt.NewFile`, `oauth.NewFile` and
  `browser` pairing build on `secret.Document` and take the same options.
- **`cmd/zelk/internal/keychain`:**
  - the linux backend (godbus plus our Secret Service client);
  - the darwin backend (purego);
  - the windows backend (the Credential Manager through advapi32);
  - `Open()`, which returns the platform's vault or `ErrUnavailable`
    with the reason.

  **Dependencies:** `github.com/godbus/dbus/v5` (linux),
  `github.com/ebitengine/purego` (darwin) and `golang.org/x/sys/windows`
  (windows), all in `cmd/zelk` only.
  Core's dependencies don't change.
- **`cmd/zelk/internal/tui/providers`.** Key IDs; edits as transactions
  on a fresh load; lookups resolved under the shared lock, from the
  profile name; a directory sync after `providers.json` is written.
- **`zelk credentials`.** It lists each document, where it lives, and
  whether that place can be used, finishing any leftover intent as it
  goes. It never shows a value. Its subcommands are
  `move -to keychain|file [doc…]` and `purge doc…`.
- **Settings and docs.** The `credential_store` setting, flag and TUI
  row, the `zelk policy` listing, the guide skill's config reference, and
  the READMEs.

## Tests

- **`secrettest`:**
  - get after create;
  - create refuses an existing id;
  - delete, including deleting a missing item;
  - `ErrMissingItem`;
  - ids kept apart;
  - an empty or partial secret read as missing.

  It runs against a fake vault, Secret Service and macOS.
- **`secret.Document` with a fake vault:**
  - a marker is recognised without a vault, through all three public
    stores (ChatGPT, MCP OAuth, pairing): `ErrInVault`, with the update
    function never called;
  - a marker whose item is missing gives `ErrMissingItem`;
  - crash injection at every numbered boundary, for creation, updates,
    moves and purge (a power cut around a directory sync is checked
    through traces, below);
  - crash injection inside recovery too, including a second crash after
    recovery's delete;
  - power cuts are checked through traces of every file and vault
    operation: no vault delete happens before the directory sync that
    follows the change letting its item go, and recovery syncs before
    anything else;
  - the next access finishes every intent left behind, and removes a
    stale `<file>.tmp`;
  - a create that commits after recovery found it missing leaves only an
    unreferenced item, and the document stays right;
  - a copied folder reads the original's item, then writes, purges and
    moves without deleting it;
  - each process syncs the config folder's ancestors on its first
    exclusive access, even over a folder another process made;
  - a copy that published its own item and then crashed before removing
    its intent doesn't delete the original's item on recovery;
  - the original deleting an item a copy still names gives the copy
    `ErrMissingItem`;
  - a put that completes after the context is canceled reports success;
  - an uncertain put leaves an intent that settles it, and a sign-in
    doesn't revoke its tokens on `ErrUncertain`;
  - a read racing a move and a purge, as a deterministic interleaving
    using the lock;
  - a read that finds an intent switches to the exclusive lock without
    deadlocking;
  - refresh rotation across two processes with the vault in place;
  - the owner and symlink checks on markers and intents.
- **Provider keys:**
  - two processes edit at once, and neither loses the other's change;
  - a crash at each step of the transaction never leaves a dangling
    reference;
  - a reader racing a key change and its cleanup never sees a missing
    key;
  - a registry holding an older load, after another process changes a
    profile's URL and key together, keeps that load's URL with that
    load's key, never a mix;
  - a registry saving an older load's profile with its key untouched
    keeps the key another process put there since when the endpoint is
    the same, and is refused when it isn't, so a key never goes to
    another URL; an edit newly naming a key the document doesn't hold is
    refused, while references a purge left behind can be mended one at
    a time;
  - a save waiting on the keychain doesn't stop the TUI reading the
    profiles;
  - checking an edited profile whose key the user left alone sends the
    saved key;
  - renaming a profile keeps its key;
  - `credentials move` converts literal keys;
  - the managed policy refuses literal keys.
- **Secret Service, integration:**
  - setup: a private bus from `dbus-run-session` with gnome-keyring, then
    KeePassXC;
  - the kit;
  - two items with one id give `ErrCorrupt`;
  - an update is a create and a delete, never `SetSecret`;
  - a changed default collection still finds the recorded one;
  - a locked collection, background (`ErrLocked`, no prompt) and
    interactive (prompt completed, and dismissed on cancel);
  - sandbox reachability: a bwrap command can't reach an abstract bus with
    network `off`, nor a path bus outside its binds, under any network
    mode;
  - the bwrap warnings fire.
- **macOS, integration:**
  - the kit runs on the runner's login keychain with unique ids, and is
    cleaned up afterwards;
  - background calls return instead of prompting, both for a locked
    keychain and for a build the access list doesn't trust;
  - it runs on the macOS job when darwin files change.
- **Windows, integration** (on Windows, with `-tags=integration`, in the user's real
  Credential Manager, under names `zelktest-<run>-<random>:` that no zelk
  credential carries):
  - the kit;
  - the platform's 2,560-byte blob limit, exactly: a blob of 2,560 bytes
    is written and one of 2,561 is refused;
  - documents of every size around the manifest's and the parts' limits
    (empty, 2,559 to 2,561, 2,512 and 2,513, one part exactly, one more,
    and 100,000 bytes) come back byte for byte in the credentials the
    layout says;
  - a crash (fault injection between any two credentials) in `Create`
    and in `Delete`, recovered on the next access, by the vault alone
    and through a `secret.Document`'s intent;
  - a missing manifest, a missing, cut or altered part and a garbage
    manifest read as `ErrMissingItem`;
  - a marker whose item is missing reads and updates as `ErrMissingItem`,
    with the update function never called;
  - `Create` of an existing ref is refused, and concurrent writers of one
    ref give exactly one whole item;
  - a writer finding the item's mutex held is refused and writes nothing;
  - distinct items can be created concurrently, and a create or delete
    waiting for a held store mutex returns when its context is canceled;
  - `Delete` leaves a credential that only has a similar name;
  - a document moves in, out and in again, and is purged;
  - every test removes its credentials when it ends, including on
    failure. The run fails if either an API enumeration or a fresh
    `cmdkey /list` process still sees targets from that run.
- **Seatbelt.** A sandboxed `security find-generic-password` fails.
- **Policy:**
  - `"keychain"` overrides `file` with a warning;
  - a plain-file document and a literal provider key are refused under it;
  - with no keychain, sign-in fails and the error says why.
