# Service accounts

<!-- toc -->
- [The problem it solves](#the-problem-it-solves)
- [The shape](#the-shape)
- [The two rules](#the-two-rules)
- [Reading one](#reading-one)
- [The header each service expects](#the-header-each-service-expects)
- [A credential from the environment](#a-credential-from-the-environment)
- [A credential named after its account](#a-credential-named-after-its-account)
- [Refusals](#refusals)
- [Migration](#migration)
- [The gate that keeps it the only reader](#the-gate-that-keeps-it-the-only-reader)
- [What is not here yet](#what-is-not-here-yet)
<!-- /toc -->

One credential, described in one place: which service it belongs to, where it
may be sent, and which credential-store items hold it.

## The problem it solves

Split across `global.hosts`, `global.keychainMapping` and
`global.identities[].servicePatMap`, a credential is three unrelated lookups:
a host from one, a store item name from another, sometimes an identity-specific
item from a third. Nothing joins them, so nothing is in a position to notice
when one account's host is handed another account's token. A person with two
GitHub accounts, or a production and a test Jira, has no way to say which token
belongs to which, and
`keychainMapping` has room for exactly one of each.

## The shape

```json
{
  "global": {
    "serviceAccounts": [
      {
        "id": "jira-acme",
        "service": "jira",
        "label": "Acme Jira",
        "default": true,
        "identityId": "alice",
        "scope": { "host": "jira.acme.example", "extraHosts": [] },
        "secrets": { "token": "Acme_Jira_Access_Token" }
      }
    ],
    "serviceOptOuts": []
  }
}
```

`secrets` holds item **names**, never values. `id` is how run state, flags and
the audit trail name an account, so it never changes once written. `label` is
what a person reads in a picker. `scope` says where the secret may go; what it
accepts depends on the service:

| Kind | Services | Scope | Where the secret may be sent |
|---|---|---|---|
| hosted | jira, confluence, bitbucket, fortify, graylog, jenkins | `host` required, `extraHosts`; graylog also `environment` | the account's own hosts |
| vendor | github, npm | `host` names another instance; github also `owners` | the vendor's hosts, or the named instance |
| vendor-fixed | figma, firebase, google_play, appstore_connect | firebase and google_play take `projectId` | a fixed list the account cannot widen |
| local | figma_mcp, vercel, claude_oauth, supabase | none | nowhere: handed to a local tool |
| endpoint | usage_ingest | none | the host in `global.usageLog.endpoint` |

## The two rules

**A secret is never produced without a destination that was checked.** A request
that names no host gets a refusal, not the default account. A host no account
covers gets a refusal, not the nearest match. "I do not know which token this
host wants" and "here is the token I had" are different answers, and the second
one is how a token reaches a host it was never issued for.

**An unmigrated file resolves identically.** While `serviceAccounts` is absent
the same entries are derived in memory from the flat keys. A missing array is
not a refusal; it is the old shape, read the new way.

## Reading one

Everything goes through `$HOME/.claude/lib/service-account.mjs`, or
`service-account.sh` for shell callers, which execs the same module.

```bash
service-account.sh select --service jira --url https://jira.acme.example/rest
service-account.sh token  --service jira --url https://jira.acme.example/rest
service-account.sh list   --service github
service-account.sh check
```

`token` writes the raw secret to stdout with no trailing newline. Everything
else writes one JSON line. On a refusal stdout is empty and one JSON line goes
to stderr, carrying `reason`, a sentence of `message`, and a `remedy` naming the
one thing to do next.

`items` lists every store item name the accounts refer to, with the account and
slot that refers to it. Names only, never values: it is the one listing that is
safe to print, and it stays that way by never reading the store at all.

`curl-config` is how a secret reaches an outbound request: the URL, a scheme
lock and the header live in one curl config, and redirects are refused, so
nothing can point curl elsewhere between the check and the request.

Shell callers get the same four things from `lib/_service-account.sh`, which is
sourced rather than run: `sa_cfg` writes a config only curl reads and removes it
when the shell exits, `sa_host` gives the host of the chosen account, `sa_token`
is there for the few callers that cannot use a config, and `sa_explain` turns a
refusal into a sentence. A fetcher that builds its own `-H "Authorization: ..."`
is a fetcher that can carry it through a redirect.

## The header each service expects

The scheme is a fact about the service, not a choice at the call site:

| scheme | header |
|---|---|
| `bearer` (default) | `Authorization: Bearer <token>` |
| `basic` | `Authorization: Basic base64(<username slot>:<token>)` |
| `basic-token-user` | `Authorization: Basic base64(<token>:)` |
| `basic-or-bearer` | basic when the account carries a username, bearer when it does not |
| `figma-pat` | `X-Figma-Token: <token>` |
| `fortify-token` | `Authorization: FortifyToken base64(<token>)` |

`basic` reads the username through the store, because that slot holds an item
name like every other one. Reading it as the username itself would send the
store's item name as the login and fail like a wrong password.

## A credential from the environment

A CI job, a container, and a person trying the pipeline before running setup all
supply a credential the same way: an environment variable. The resolver answers
from one when a variable holds something, as an account called `env:<service>`.

It is not a worse secret, but it is a differently bound one, because nobody said
which host it belongs to. So it reaches only what is already known: a host a
configured account covers, the vendor's own hosts, whatever its own `*_HOST`
variable names, and loopback. It never wins a destination a configured account
also covers, and it never becomes the default.

Loopback is also the one place `http` is allowed, for any credential. A local
model server, a mock and a dev instance all live at `127.0.0.1` with no
certificate, and refusing them outright is what pushes people to turn the check
off for everything; loopback is the one destination with no network to carry
the request, so there is nothing on the wire to protect. Everywhere else `http`
is `insecure-url`, refused before the store is touched. The destination rule is
unchanged underneath: a loopback address still has to be one the account names.

The URL in that config is one this module serialized, never the string it was
handed. The two differ more than they look: the URL parser silently removes
tab, CR and LF and rewrites a backslash as a slash, while a curl config is read
a line at a time. `https://good.example/x` followed by a newline and
`url = https://evil.example/` names `good.example` to a host check and is two
`url` directives to curl - and the `header` line applies to both. So a URL
carrying a control character or a backslash is refused outright, by
`normalizeHost`, before anything is selected; and `curl-config` parses the URL a
second time and checks its hostname against the host the secret was bound to.

## A credential named after its account

A team that holds one credential per instance tells them apart by naming the
store item after the account: the short id, then the provider, then the rest
(`b_jira_access_token` for account `b`). `global.accounts[]` carries that
account's hosts under the same id.

Neither half names the other, so the pairing is made at the one moment both are
in hand: a request that asks by item name. The id read out of the name picks
the entry, and that entry supplies the single host the item may be sent to -
its own `jiraHost` / `bitbucketHost` / `confluenceHost`, or the host the file
names for the service when the entry declares none. An id the file does not
list is `unknown-account`, never the default account: resolving it to whichever
account came first is the pairing this module exists to refuse.

```
--item B_Jira_Access_Token   ->  account jira-b, host jira.b.example.com
--item B_Jira_Access_Token --host jira.example.com
                             ->  no-account-for-target
```

The second line is the point: B's credential does not reach A's host because a
caller asked for it.

## Refusals

| reason | exit | when |
|---|---|---|
| `invalid-request` | 3 | no such service, slot, or sub-command |
| `not-configured` | 1 | nothing configured for this service (carries `optedOut`) |
| `unknown-account` | 1 | an id no account carries |
| `slot-missing` | 1 | the account has nothing in that slot |
| `secret-missing` | 1 | the item it names is not in the store |
| `store-unavailable` | 2 | no credential backend on this machine |
| `store-error` | 4 | the backend failed |
| `secret-locked` | 5 | the store is locked |
| `prefs-unreadable` | 6 | the preferences file does not parse |
| `invalid-config` | 6 | the accounts do not hold together |
| `destination-required` | 7 | a secret was asked for with no destination |
| `insecure-url` | 7 | not https outside loopback, or userinfo in the URL |
| `host-mismatch` | 7 | a named account, and a destination outside it |
| `no-account-for-target` | 7 | no account covers the destination |
| `identity-mismatch` | 7 | every match belongs to another identity |
| `not-sendable` | 7 | an outbound request for a local-only credential |
| `ambiguous` | 8 | several fit and nothing tells them apart |
| `needs-pairing` | 8 | the account has a secret but no host yet |

## Migration

`migrate-prefs.mjs` derives the array from the flat keys, and will not guess.
Where the file holds one token and one host for a service, that is the only
pairing the data allows and it is written. Where it holds more of either and
nothing says which goes with which, the entry is written with `unresolved`
instead of a host; the resolver refuses it and setup asks a person which host it
belongs to. Skipping the question asks again next run - only the explicit
permanent choice stops it.

The flat keys stay. `keychainMapping`, `hosts` and `credentialHosts` remain the
projection of each service's default account, so the toolkit server and people's
own scripts keep reading the same answers. `writeAccounts` is the only writer of
`serviceAccounts`, and it writes the array and the keys it projects into in one
replacement.

## The gate that keeps it the only reader

`lint-credential-reads.mjs` counts the lines that still read `keychainMapping`,
`credentialHosts` or `global.hosts`, or call the credential store, outside the
resolver. It is a per-file ratchet against
`pipeline/scripts/fixtures/credential-reads-baseline.txt`: a file may carry
fewer than its baseline, never more, and a file absent from the baseline may
carry none. The resolver is the join only while it is the only reader - a caller
that looks a key up itself has reintroduced the gap for its own request.

## What is not here yet

The entity, the resolver, the migration and the gate are in. Callers are moving
over a batch at a time, and the baseline is what says how far that has got. The
"add another account" flow in setup, and the picker that uses it, come after.
