Repository navigation
fix(cli): refuse to send a saved token to a different server origin - #2452
Conversation
The target URL (`--server`, `FIRST_TREE_SERVER_URL`, config) and the persisted credential are resolved independently and were never compared, so pointing the CLI at another origin sent the token minted for production to it (SEC-023). Reproduced end to end: with `credentials.json` bound to `https://prod.example` and only `FIRST_TREE_SERVER_URL` pointed at a local server, `agent list --remote` delivered `Authorization: Bearer <prod token>` to that server. Bind every transport that carries the stored token: - `cliFetch` guards its own requests (all direct `fetch` sites now go through it, including `tree init` and `org bind-tree`), and - the SDK instances a command builds use `accessTokenForOrigin(serverUrl)` instead of `ensureFreshAccessToken()`. Only a token that matches the credential store is checked, so login codes, admin tokens and one-shot exchange tokens are unaffected. Origins compare by scheme/host/port via `URL`, so equivalent spellings are not rejected, and the refusal message names the real remedy (`logout` + `login <code>`) rather than a flag that does not exist. Not covered here: the daemon's own connection (`core/client-runtime.ts`, WebSocket + SDK), which speaks to the server recorded at login. A hand-edited `client.yaml` can still point it elsewhere.
yuezengwu
left a comment
There was a problem hiding this comment.
The CLI can load a saved token and later pass that captured value to transport. The new origin check rereads the credentials file and returns early on a token mismatch. If credentials change between those steps, the captured credential is no longer checked against its issuing origin. Please carry origin together with the token returned by the load or refresh step and check that pair at the transport boundary. A mocked rotation between resolution and transport can cover the case.
… file The origin check re-read `credentials.json` at transport time and returned early when the token was no longer in the store. A refresh, or a re-login in another terminal, rewrites that file, so a token captured before the rewrite was no longer checked at all and the transport sent it to a foreign origin (SEC-023). Carry the pair instead: `loadCredentials`/`saveCredentials` record token → origin, and the transport check consults that memory first, falling back to the file only for a token this process has not seen. The memory is bounded to the most recent pairs, and a file-derived match is remembered too so a later rotation cannot disarm it either. Cases: load the production token, rewrite the store for staging, send the captured token → still refused; send the rotated token to staging → allowed. The first fails against the previous implementation (the request goes out).
|
Fixed — The check now carries the origin with the token instead of re-deriving it from the file:
That closes the window you described: the captured token is compared against the origin that issued it, whatever the file says by the time it reaches the transport. Cases:
|
yuezengwu
left a comment
There was a problem hiding this comment.
The single-rotation case now passes, but the process-wide cache can evict an origin while a caller still holds the resolved credential. An evicted credential that is also absent from the current file then takes the unknown-token pass-through. Please attach the issuing origin to the credential returned by load or refresh and retain that pair through the request. Keep the intentional foreign-token path explicit and separate from file-derived credentials. A mock can verify that a held credential retains its origin independently of later load activity.
…oken table
Review follow-up on SEC-023. The in-process token→origin map could evict an
origin while a caller still held the resolved credential; if that credential had
also left the store (a refresh or a re-login rewrote it), the check fell through
to the unknown-token path and the request went out.
Attach the origin where the token is obtained and carry the pair:
- `ensureFreshBoundAccessToken()` returns `{ token, origin }`, built from the same
credential snapshot the refresh talks to, so the pair describes whoever minted
the token no matter what the file says later;
- `assertBoundCredentialOrigin(serverUrl, credential)` is a pure function of the
pair — no file read, no process-wide memory, nothing to evict;
- `accessTokenForOrigin`, the daemon's connection auth, the runtime-repair fetch
and the capability/skill uploads all take or resolve the pair;
- `cliFetch` keeps a check, now named and documented as file-derived: it can
only classify a token the store still contains, and a token it does not know is
the explicit login-code / one-shot-exchange path.
The eviction scenario becomes a test: hold a production credential, load 32 more
from other origins, rewrite the store, and the held pair still refuses the foreign
origin. `accessTokenForOrigin` is asserted to keep refusing after the store is
rewritten mid-request.
|
Pushed You are right, and the root cause was the shape of the previous fix: a What changed export type BoundCredential = { readonly token: string; readonly origin: string | null };
The two paths are now explicit and separate, as you asked
The second is named for what it is. A token the store does not contain is the login-code / one-shot exchange path, and that pass-through is stated in the doc comment rather than being an incidental fallback. Verification
I want to be explicit about the one behaviour this trades away: the round-1 case "a token captured from the store, then the store rewritten, then sent through Suites: |
…strap mock SEC-023 resolves credentials through `ensureFreshBoundAccessToken`, which the `tree init` suite's narrow `core/bootstrap.js` mock did not provide: the SDK token provider threw, the seed preflight classified the throw, and ten cases reported the mock error instead of their own behaviour. The mock now derives the pair from the string accessor it already stubs, with a null origin so the origin assertion abstains — these cases do not test origins.
|
Full-suite numbers, plus one test-mock fix I had to make on top of
I verified this by running the same eight files at The fix I had to add ( The first full run showed 30 failures, 10 of them new: So ten cases were reporting the mock gap rather than their own behaviour. The mock now derives the pair from the string accessor it already stubs: ensureFreshBoundAccessToken: async (...args: unknown[]) => ({
token: await bootstrapMocks.ensureFreshAccessToken(...args),
origin: null, // these cases never check an origin, so the assertion abstains
}),Worth naming as a trade-off rather than hiding it: any path that starts resolving through a new export will break hand-written bootstrap mocks the same way. If you would rather have these suites spread
|
yuezengwu
left a comment
There was a problem hiding this comment.
The credential pair fixes the eviction problem for the migrated callers. The remote agent-list and organization-binding commands still use the token-only accessor and pass the resulting string to cliFetch, which only recognizes tokens present in the current file. Please migrate the direct CLI request paths that already know their destination to accessTokenForOrigin or pass the bound credential to transport. Verify at a real command entry point with mocked credential rotation and a mocked transport. Keep one-shot credentials distinct from the persisted-token path.
…stination Review follow-up. The pair removed the eviction problem where it was applied, but the direct command paths still resolved a bare token with `ensureFreshAccessToken()` and handed the string to `cliFetch`, whose check can only classify a token the current file still contains. Every request path that knows its destination now resolves the pair: - commands: `agent list/status/create/reset/bind`, `agent session list/control`, `chat open`, `org bind-tree`, `logout`'s client retire, and both `tree init` server phases; - SDK token resolvers: `login` and `daemon start` name-migration resolvers; - daemon helpers: `listPinnedAgents`, `reconcileLocalRuntimeProviders`, `uploadClientCapabilities`, `uploadAgentSkills` take the `BoundCredential` (the first two previously took a string). `cliFetch` keeps its file-derived check, which is now the only place a token is classified from the store: one-shot credentials (login code, freshly exchanged token) still pass through, and that is stated where it happens. Tests: two real command entry points (`agent list --remote` and `org bind-tree`) assert that nothing is sent to an override origin, that the bound accessor is the one used, and that a rotation of the store to the destination's origin then allows the request.
Five suites replace `core/bootstrap.js` (and, in one case, the `core/index.js` barrel) with an explicit export list. Any request path that starts resolving through the bound accessor then hits a mock hole instead of its own behaviour: 26 cases reported `No "ensureFreshBoundAccessToken" export` and 4 reported the same for `accessTokenForOrigin`. Each mock now derives the bound form from the string accessor it already drives, so a stub, a one-shot rejection or a reset applies to both without mirroring. `tsc`, `biome ci`, and the full `apps/cli` suite are clean: 18 failures, all of them the pre-existing macOS/environment set (context-byo-repository, context-project-resolver, context-skill-loader, migrate-agent-dirs, tree-init-command-extra).
|
Pushed Every request path that knows its destination now takes the pair, not a bare token:
Entry-point verification, as asked — two real commands, real
The accessor counters are produced by a Full If you would rather have those suites spread |
The block-form factories introduced indentation the formatter rejects, and `biome check .` (what CI runs) reports those as errors while `biome ci` did not — so the previous push passed locally and failed on the lint job. Also drops the `ensureFreshAccessToken` import the daemon no longer uses.
|
CI follow-up in |
yuezengwu
left a comment
There was a problem hiding this comment.
The command migrations cover the agent-list and organization-binding paths from the prior review. The agent config commands still resolve their destination and then obtain a bare token through ensureFreshAdminToken. Their shared fetchers use the file-derived check, so a credential held across the commands' requests has no durable issuing origin. Please use the bound accessor for these commands too, and cover the shared fetch path with a mocked credential update. Preserve the separate behavior for one-shot credentials.
The config commands resolved their destination, then took a bare token from `ensureFreshAdminToken()` and passed the string through the shared fetchers. Those fetchers rely on `cliFetch`'s file-derived check, which has to answer "which origin issued this token?" by consulting the credential file at request time — and deliberately lets through tokens the file does not contain. A credential held across a command's several requests therefore had no durable issuing origin: a re-login in another terminal mid-command re-pointed the answer, and a token that had been rotated away became unclassifiable. `credentialForOrigin` returns the pair (token + issuer) for a known destination; the commands now bind once and the shared fetchers take the pair, asserting it against the URL they are about to call. The guarantee no longer depends on the file's contents at request time. One-shot credentials (login code exchange) are untouched and still use their own path. Tests: the fetch helper refuses a credential bound to another origin without sending anything, and keeps using the pair it was handed after the store rotates. Both fail if the boundary assertion is removed.
|
Fixed in What changed
Coverage you asked for (
Both fail if
|
yuezengwu
left a comment
There was a problem hiding this comment.
The config commands now carry the bound credential as requested. The interactive agent add flow (core/prompt.ts) and the multi-request onboardCreate flow (core/onboard.ts) still pass bare saved tokens to cliFetch. Those calls fall back to the mutable credentials-file check rather than carrying the issuing origin, so the binding still depends on which credentials are on disk at send time. Please use the same destination-bound accessor in both paths and update their existing mocked tests.
`promptAddAgent` and `onboardCreate` resolved their destination and then took a bare token from `ensureFreshAccessToken()`, handing the string to `cliFetch` — whose guard answers "which origin issued this?" by reading the credentials file at request time, and deliberately lets through tokens the file no longer holds. `onboardCreate` makes several requests with that one string, so a re-login in another terminal mid-flow could retarget what the guard believes. Both now bind once through `credentialForOrigin(serverUrl)`, the same accessor the agent-config commands use. Their existing mocked tests mock that accessor instead of the token function, so a regression to the bare token leaves the credential undefined and the flow fails rather than silently passing.
|
Both remaining paths migrated in
|
The mock swap alone does not fail a regression: the bootstrap mock still answers `ensureFreshAccessToken` with a string, and neither suite asserts the Authorization header, so a command that went back to the bare accessor would pass with `Bearer undefined`. Both flows now assert the bound accessor was called with the resolved server and that the token accessor was not called.
|
Correction to my previous comment: the mock swap alone would not have caught a regression — the bootstrap mock still answers
expect(credentialForOriginMock).toHaveBeenCalledWith("http://first-tree.test");
expect(ensureFreshAccessTokenMock).not.toHaveBeenCalled();onboard-core + prompt-core 14/14, |
yuezengwu
left a comment
There was a problem hiding this comment.
The agent-add and onboarding flows now obtain credentials bound to the destination they use, and the tests verify they no longer call the bare accessor. The fixed onboarding destination is reused across its requests. CI and CLA passed on this head, and 64 focused tests passed on the combined tree against current main.
Summary
credentials.jsonrecords the server a token was minted for, but every command resolved its target independently (--server,FIRST_TREE_SERVER_URL,client.yaml). Nothing compared the two, so an override shipped a production token to whatever URL it named.Closes #1629 (SEC-023).
Reproduction
Local HTTP server as the "attacker origin",
credentials.jsonbound tohttps://prod.example, onlyFIRST_TREE_SERVER_URLpointed at the local server, real command:The production access token reached the local server.
Already correct before this PR, for the record:
/auth/refreshusescredentials.serverUrl, so a stale token is not refreshed against the override. The exposed half is "send the token you already hold".Fix
Bind every transport that carries the stored token, not just the ones a reviewer happens to find:
cliFetchcompares the canonical origins (scheme/host/port viaURL, sohttps://PROD.exampleandhttps://prod.example:443compare equal) and fails closed with both origins named.accessTokenForOrigin(serverUrl):_shared/member.ts,_shared/local-agent.ts,agent/prune.ts,context/activate.ts,_shared/doctor-checks.ts,runtime-provider-reconcile.ts.fetchsites intree initandorg bind-treego throughcliFetch, and an origin refusal is re-thrown instead of being swallowed by their "degrade to a network error" catch.Only a token that matches the credential store is checked, so the login exchange, admin tokens and one-shot tokens are untouched. The refusal message names the real remedy:
Validation
npx vitest run apps/cli/src/__tests__/credential-origin.test.ts→ 6 passed. Against the previous code the same two behavioural cases fail asfetch failedand "the command returned normally".agent list --remoteunder the attack above is refused in-process and the local server receives zero requests (asserted on the recorded requests, not on the error text alone).accessTokenForOriginpositive and negative.tree init,org bind-tree,doctor,agent prune,context activate,agent config,cli-fetch): 91 passed, 1 failure that also fails on unmodifiedmainlocally (tree-init-command-extra, macOS/var↔/private/varsymlink aliasing, reported as [Bug] macOS: any workspace under an aliased path (/tmp, /var, ~/symlinked-dir) refuses to bootstrap #2449).apps/cli/src/__tests__(1822 tests): 20 failures on this branch vs 18 on unmodifiedmain; the two extraclient-switch-transaction-extracases pass 22/22 when that file runs alone (load-dependent flake, not reproducible).npx tsc --noEmitinapps/cliclean;npx biome checkclean.Change Surface
apps/clipublic CLI or help outputNotes
docs/onboarding-guide.mddocuments the binding next toFIRST_TREE_SERVER_URL.core/client-runtime.ts, WebSocket + SDK) speaks to the server recorded inclient.yaml, so a hand-editedclient.yamlcan still point it at another origin. Closing that needs the same check on the connection layer; happy to add it here if you prefer one PR.client.yamlandcredentials.jsonhad already drifted will now get a clear error instead of a silent send;loginrewrites both, andlogoutclears them.