Repository navigation
fix(access): a published API key reads every other client's plaintext API key - #826
Conversation
Payload's `apiKey` base field carries no `hidden` flag and no field access, and an `afterRead` hook decrypts it. So the field came back in plaintext to any caller who reached the document — and `GET /api/clients/me` is a document every published client reaches, by the self-access bypass, before any role check runs. Restricting the collection cannot close that read, which is why this is its own layer. Declaring a same-named field merges over the auth base field (`sanitize.ts` → `mergeBaseFields`), with our properties winning the deep merge, so `encryptKey` and `decryptKey` survive and only `access.read` is added. `read` only. No role holds create or update on `clients`, and `create` is the path the admin's key regeneration and the test fixtures take. Authentication is untouched: the API-key strategy matches on the `apiKeyIndex` hash at `overrideAccess: true`. `managersOnlyFieldAccess` rather than `adminOnlyFieldAccess`, because a manager listed in `Clients.managers` is the person who installs the key. The field must sit at the top level of `Clients.fields`. `mergeBaseFields` matches by name only at the level it is handed, so a copy nested in a tab sanitizes to two `apiKey` fields instead of one. Refs #822 Claude-Session: https://claude.ai/code/session_019EBxzBUyApfvZmBQEuwgMg Co-authored-by: Claude <[email protected]>
`clients` sat in no project and was not restricted, and `isCollectionVisibleInProject` reads "in no project" as shared — so `hasPermission` step 4a granted implicit read to every published API key. The atlas widget's key ships in the browser, so a public credential read every other service's whole document, `apiKey` included, over a bare `GET /api/clients` with no `select` and no origin check. The policy the reviewer settled on 2026-09-18: admins, and the managers listed on that client. Adding the slug to `RESTRICTED_COLLECTIONS` is the whole of it. No role holds an explicit `clients` grant, so implicit shared read was the only role path there was to remove. A listed manager keeps read and update through the document-manager path in `accessConfigs.ts`, which runs after the role check fails. `GET /api/clients/me` stays, deliberately: self-access answers it at step 2, and the widget suspends on that read at every boot. The previous commit is what keeps the key out of that answer. Nothing else moves. Every in-repo `clients` read runs at `overrideAccess: true`, and the admin nav already hid the collection from non-admin managers, since `createHidden` needs a write grant and no role has one. The one visible change: an `atlas-manager` reading a submission relayed by a service they are not listed on now sees a bare id in the `UserSubmissions.client` display cell. The spec covers both layers, and each of its assertions was watched to fail against the real defect — the field override dropped, the slug removed, and the override nested in a tab, which does produce two `apiKey` fields. The fixture stores a key on the other client on purpose: with none stored, `apiKey` comes back `null` either way and the probe passes vacuously. Refs #822 Claude-Session: https://claude.ai/code/session_019EBxzBUyApfvZmBQEuwgMg Co-authored-by: Claude <[email protected]>
`access.md` described `managersOnlyFieldAccess` as the lock "for a collection that is not restricted", which stops being the whole story once `clients` is restricted and `apiKey` carries the lock. The section now says what each layer covers and what neither does alone: restriction does not reach the caller's own row, and the field lock does not stop a key reading other services. `api-clients.md` said managers regenerate keys and manage settings without saying how they reach the document. No role holds a `clients` grant, so that is the document-manager path, and now it says so. Refs #822 Claude-Session: https://claude.ai/code/session_019EBxzBUyApfvZmBQEuwgMg Co-authored-by: Claude <[email protected]>
Found by the branch-level security review, and both reproduced against a booted Payload before being fixed. **`POST /api/clients/refresh-token` returned the caller's own decrypted `apiKey` and its `mailingList` provider secret.** `refreshOperation` re-reads the document with `findByID` and no `overrideAccess: false`, so it defaults to `true` and every field lock is skipped — `meOperation` passes the flag, `refresh` does not. `disableLocalStrategy: true` does not help: `refresh` is the one auth operation that does not refuse on that flag, and the route is attached to every auth collection regardless. `stripSecretsFromClientReads` is a collection `afterRead` hook keyed on `req.user.collection === 'clients'`. A hook runs on every read path, so it holds whichever operation forgets the flag next — which is why it is a hook and not a second field lock. Server-side reads run with no user or a manager, so they are untouched, and authentication resolves before `req.user` exists and matches the `apiKeyIndex` hash anyway. **A published client could rewrite its own `apiKey`.** Self-access grants `update` on the caller's own row, and the field declared `read` access only, so a browser-shipped key could pin the credential to a value the attacker chose. The previous commit's rationale for `read`-only was wrong on its own terms: regeneration is an `update`, not a `create`, as this branch's own spec demonstrates. `managersOnlyFieldAccess` passes any manager, so locking `create` and `update` costs regeneration nothing. Both probes were watched failing before the fix: the refresh body carried the plaintext key, and the PATCH left `ATTACKER-CHOSEN-KEY` in the column. Refs #822 Claude-Session: https://claude.ai/code/session_019EBxzBUyApfvZmBQEuwgMg Co-authored-by: Claude <[email protected]>
`loadManagedDocIds` fetched whole rows through three `payload.find` calls and used `doc.id` from each. Without a `select` every row runs its full `afterRead` chain, so restricting `clients` — which routes a non-admin manager's read down this path — would have meant decrypting every managed service's `apiKey`, server-side, to collect a primary key. One `findManagedIds` helper now carries the `select` and the two casts the runtime-only slug forces, replacing three near-identical query blocks. Refs #822 Claude-Session: https://claude.ai/code/session_019EBxzBUyApfvZmBQEuwgMg Co-authored-by: Claude <[email protected]>
- Reuse `createClientAuthenticatedRequest` rather than a fifth hand-rolled client request. It typed `clientId` as `string`, which silently denied a client its own row: the self-access bypass compares `user.id === docId` strictly. Widened to `number | string`, with the hazard named. - Mirror the widget's real boot read — `SahajAtlasWeb`'s `getClient` selects nine fields at `depth: 1` and populates `regions`, not `depth: 0`. - Give key regeneration its own fixture, so no later case depends on an undeclared restore of a value an earlier one overwrote. - Assert the manager update with a value the row did not already hold. - Point the authentication case at a project collection, so it proves the key still carries its role's grants instead of repeating the `/me` case. - Trim the comments that narrated rather than carried a why, and note that `RESTRICTED_COLLECTIONS` is a holding pattern whose complement is #821. Refs #822 Claude-Session: https://claude.ai/code/session_019EBxzBUyApfvZmBQEuwgMg Co-authored-by: Claude <[email protected]>
Both rules said a field lock is what keeps a client out of `apiKey` and `mailingList`. That is only true of a read that checks access, and `POST /api/clients/refresh-token` does not — so the docs now name the second self-read, why `disableLocalStrategy` does not cover it, and the hook that does. The general rule a reader needs: when you lock a field on an auth collection, lock it and then check what else re-reads the row. Refs #822 Claude-Session: https://claude.ai/code/session_019EBxzBUyApfvZmBQEuwgMg Co-authored-by: Claude <[email protected]>
|
🚅 Deployed to the SahajCloud-pr-826 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff is the size of the problem. The two paths beyond the ticket are not scope creep — the criterion "cannot read any apiKey value, its own included" is false without them. All four Manual verification steps are admin-panel actions nothing covers.
Findings — no blockers, four consider:
documentManagers.ts:157— theselectis half-applied.stripSecretsFromClientReads.ts:26— two names can drift.Clients.ts:285— a comment restates field names.testHelpers.ts:298— the new⚠has violators.
Checked. #822's criteria vs the spec's 13 cases. #827 carries the write-side reproduction. All 12 clients reads in src/ against the new hook: none loses a value. SahajAtlasWeb fetch.ts:649 selects nine fields, no apiKey. SahajAtlasWordpress diagnostics.php:581 reads the row whole into a wp_options transient — 13 sites hold a plaintext key until this lands. ⚠ No node_modules here, so mergeBaseFields and refreshOperation went unread; the spec's 200 from refresh-token is the only evidence.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The `select` added in 2184cc1 reached three of this module's four `clients` queries. `loadDoc` still fetched the whole row, and that is the path a manager saving one service takes: `accessConfigs.ts` calls `userManagesDocument` for a single-document update, and `clients` has no `parent`, so `loadDoc` plus `documentListsUser` is the whole check. So every manager save still decrypted that service's `apiKey` server-side to answer a question about a relationship field. `DocManagerFields` already names every field this module reads off a loaded document, so the `select` is derivable rather than hand-written. The ancestor-existence `find` takes `{ id: true }` for the same reason — only `docs.length` is read from it. Refs #822 Claude-Session: https://claude.ai/code/session_01F7C2zcWPC2SFr44R1jzJu5 Co-authored-by: Claude <[email protected]>
The hook named `apiKey` and `mailingList` directly, duplicating locks `Clients.ts` declares separately, and nothing failed when the two lists disagreed. A third `managersOnlyFieldAccess` field would have been unstripped on `refresh-token` — the exact shape the hook exists to prevent — while its docblock still read as covering it. The set is now read off the sanitized collection: every flattened top-level field carrying its own `access.read`. That is where a locked field's value sits on the document, `mailingList`'s group included, since `flattenAllFields` folds collapsibles and unnamed tabs into their parent. Watched failing: with the derivation stubbed to an empty list, the `refresh-token` case in `clients-access.int.spec.ts` goes red. Refs #822 Claude-Session: https://claude.ai/code/session_01F7C2zcWPC2SFr44R1jzJu5 Co-authored-by: Claude <[email protected]>
The merge position and the write lock both carry a why. "Not to be confused with `mailingList.apiKey`" restates what the two field names already say. `docs/rules/code-comments.md` applies the razor to the comments you keep, not only the ones you cut. Refs #822 Claude-Session: https://claude.ai/code/session_01F7C2zcWPC2SFr44R1jzJu5 Co-authored-by: Claude <[email protected]>
The `⚠` added to `createClientAuthenticatedRequest` had four violators already in the tree — `api`, `available-locales`, `client-query-validation` and `pages-localize-status` each passed `String(client.id)`. None turns on self-access, so nothing was failing, but a warning a reader falsifies in one grep stops carrying weight. Narrowing `clientId` to `number` moves the hazard from prose the compiler cannot see into a type it can. Refs #822 Claude-Session: https://claude.ai/code/session_01F7C2zcWPC2SFr44R1jzJu5 Co-authored-by: Claude <[email protected]>
|
Four adversarial-review findings, all adopted. Pushed 9fd493e.
Nothing rebutted, nothing asked. Lean gate green; 150 cases passed across six integration specs. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
One question, answered from Payload 3.86.0's own source. Nothing changed, nothing pushed.
The thread stays open for you to settle. Nothing else waits on us. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
`main` landed #825, which restricts `managers` and edits the same three places this branch does. Both restrictions are wanted, so every hunk keeps both sides. - `RESTRICTED_COLLECTIONS` holds `managers` and `clients`. Both docblock entries stay. The holding-pattern note said `managers` was the one collection left outside the set and that #821 blocked the real fix; #825 settled that, so the note now says all four out-of-project collections are named and the set fails open on the fifth. - `permissions.ts` step 4a keeps `main`'s pointer to `config/projects.ts` and this branch's note that self-access already answered a client's own row. - `docs/rules/access.md` keeps both ⚠ sets. `clients` is no longer an example of "in no project, so shared", the field-lock list is five fields rather than four, and the two claims each side made about the other's collection being unrestricted are corrected. `managers-access.int.spec.ts` needed two fixes the merge exposed. It passed `String(client.id)` to `createClientAuthenticatedRequest`, which takes a `number` on this branch — the stringified id denies a client its own row through the self-access bypass. And its depth-1 `clients` case read a list, which restricting the collection now refuses outright: the case is split into the 403 and a self-access `findByID` of the caller's own row, which is where #821's property still has to hold. Both were watched failing with the restriction dropped. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0191PvAdP7nkRiqAno9irxaE
|
Merged Three claims went false and are corrected, not dropped:
One semantic conflict, the one #821 predicted. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
`stripSecretsFromClientReads` sat on `Clients` and gated on the literal slug, which read as a `clients` workaround. The hole it closes is Payload's: `refreshOperation` re-reads the row with `findByID` and no `overrideAccess: false`, so every field lock is skipped. That is true of every auth collection, and `managers` has the same route — the next `read` lock added there would leak with nothing to catch it. `accessPlugin` now attaches `stripLockedFieldsOnSelfRead` to every auth collection, after the collection's own `afterRead` hooks. The guard evaluates each field's own `read` lock against the caller instead of stripping every locked field outright, so it denies exactly what field access would have denied and stays correct on a collection whose callers are not all unprivileged. Behaviour on `clients` is unchanged: all 13 cases in `clients-access.int.spec.ts` pass, and the `refresh-token` case goes red again when the wiring is removed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YTSRAA3WWCzs8nA9t2X5Jc
Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YTSRAA3WWCzs8nA9t2X5Jc
|
One thread, adopted. Pushed 872e9e2.
The first round dismissed this as speculative because only The guard now evaluates each field's Lean gate green — 2151 unit. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
clientsjoinsRESTRICTED_COLLECTIONS, so a published key no longer reads any other service's document.Clients.apiKeycarriesmanagersOnlyFieldAccesson read, create and update.accessPlugingives every auth collection.Changes
src/plugins/access/config/projects.ts—clientsrestricted; docblock says the list is a holding pattern whose complement is fix(access): a published client key reads every manager's name and email #821.src/collections/Clients/Clients.ts— theapiKeyfield override, declared top-level somergeBaseFieldsmerges rather than appends.src/plugins/access/stripLockedFieldsOnSelfRead.ts— newafterReadguard, for the reads that skip field access.accessPluginattaches it to every auth collection, and it re-evaluates each field's ownreadlock against the caller.src/plugins/access/documentManagers.ts— every query in the module selects now,loadDocincluded.tests/int/clients-access.int.spec.ts— new, 13 cases.tests/unit/access-self-read-field-locks.spec.ts— new, 7 cases, including the plugin wiring.tests/utils/testHelpers.tsand four specs —createClientAuthenticatedRequesttakes anumberid.Preview
clientcolumn for a service they are not listed onTest results
clients-access— 13 passed;managers-access,role-based-access,api,client-hooks,globals-client-reads— 115 passedclients-access,role-based-access,api,client-query-validation,available-locales,pages-localize-status— 150 passedManual verification
managers, open that service. It must still load and save.GET /clients/meat every load.Notes for reviewer
The review found two live holes beyond the ticket, and both were reproduced before being fixed. Neither was introduced here; both would have left the ticket's own acceptance criteria false.
POST /api/clients/refresh-tokenreturned the caller's decryptedapiKeyand itsmailingListprovider secret to a browser-shipped key, with both of the ticket's layers in place.refreshOperationre-reads the row withfindByIDand nooverrideAccess: false, so field access is skipped;meOperationpasses the flag,refreshdoes not, anddisableLocalStrategydoes not refuse it. Closed with anafterReadguard rather than a second field lock, so it holds whichever operation forgets the flag next.apiKeyvia the self-accessupdatebypass. The ticket specifiedread-only on the grounds that regeneration goes throughcreate; that is wrong — regeneration is anupdate, as this branch's own spec shows.managersOnlyFieldAccesspasses any manager, so lockingcreate/updatecosts regeneration nothing.One ticket claim corrected.
docs/rules/api-clients.mdsaid "No API client can read any of it, at any depth" ofmailingList. That was false on the refresh route; it is true now, and the doc names both mechanisms.The guard is generic now, and the earlier dismissal was wrong. The first round called a generic mechanism speculative on the grounds that one
useAPIKeycollection exists. That framed the hole as an API-key one. It is not:refreshOperationskips field access on every auth collection, somanagershas the same route and the nextreadlock added there would leak with nothing to catch it.accessPluginattachesstripLockedFieldsOnSelfReadto every auth collection, after the collection's ownafterReadhooks. The guard also evaluates each field'sreadlock against the caller instead of stripping every locked field outright, which is what makes it safe on a collection whose callers are not all unprivileged.Adversarial review: four findings, all adopted.
loadDocselects too, so a manager save no longer decrypts the service's key to answer a relationship question. The guard derives its field set from the collection's ownreadlocks, so a fifth locked field needs no edit there. A comment restating two field names is gone.createClientAuthenticatedRequesttakes anumber, which makes the stringified-id hazard unrepresentable.Dismissed findings. A shared
restGethelper intests/utils/restRequest.ts, and promotingmanagerReqthere — both would pull unrelated specs into a security PR.Filed separately, not fixed here. The ticket's own "adjacent, not this ticket" note asked for a reproduction of the client write path before filing. There is one now:
roles,allowedDomainsandcanonical.verificationcarry no field access, so a published key can PATCH its own row and widen its projects, empty its origin allowlist, or claim a region's canonical URLs.Detail
Every assertion was watched failing against the real defect, per
docs/rules/testing-reqs.md. Three separate reintroductions: the field override dropped (2 fail), the slug removed fromRESTRICTED_COLLECTIONS(5 fail), and the override nested inside a tab — which really does sanitize to twoapiKeyfields, so that guard is not theoretical. With both layers removed, 8 of 13 fail. The 3 that stay green are no-regression guards (manager regeneration, oneapiKeyfield, key auth still works), which is correct for them. The first review round added a fourth reintroduction: with the hook's derivation stubbed to an empty list, therefresh-tokencase goes red, so the derived set is load-bearing rather than decorative. The second round added three more, one per new assertion: blanket-stripping instead of evaluating the lock, hard-coding the two field names, and dropping the plugin wiring — each reddens its own case, and the last also reddensrefresh-tokenin the integration spec, so the guard is reachable through the plugin rather than only unit-tested.Fixture pre-mortem. The
/clients/mecase assumes the widget's boot read. Verified againstsydevs/SahajAtlasWeb src/config/api/fetch.ts—getClientselects nine fields atdepth: 1and populatesregions. The spec now mirrors that, not thedepth: 0first draft. The other client's fixture stores a real key on purpose: with none stored,apiKeyreturnsnulleither way and the probe passes vacuously — the trap the ticket flagged.A shared helper had the bug the ticket is about, in miniature.
createClientAuthenticatedRequesttypedclientIdasstring. The self-access bypass comparesuser.id === docIdstrictly, so a stringified id silently denies a client its own row — which reads exactly like a working lock. It isnumbernow, so the compiler answers instead of a⚠; the four specs that passedString(client.id)were corrected with it.No migration.
apiKeyis an existing auth base column and the override is same-named and same-typed.pnpm generate:typesproduced no diff, anddb:migrations:create --skip-emptyproduced no file.Performance. Restricting
clientsroutes a non-admin manager's read onto the document-manager path, which fetched whole rows to collect ids — onclientsthat means decrypting every managed service's key to read a primary key. Every query indocumentManagers.tsnow selects:findManagedIdstakes{ id: true }, andloadDoctakes theDocManagerFieldsnames plusbreadcrumbs, which is the single-document path a manager's own save runs. No net-new queries on/api/access: no role held aclientsgrant before this change either, soupdatealready took that path, andresolveManagedDocIdsmemoizes the in-flight promise per request. The guard itself costs oneWeakMaplookup per document on an auth collection, andmanagerscarries noreadlock, so the loop is empty there.Altitude, deliberately not taken here. Exactly four collections sit in no project, and
managers(#821) is the only one left outsideRESTRICTED_COLLECTIONS— a complete opt-out list is an inverted default in disguise. The real fix is forhasPermissionstep 4a to test project membership directly, so a new collection fails closed. It cannot land until #821 settles how a non-admin manager still readsmanagersfor the admin relationship pickers. Said in the docblock and indocs/rules/access.mdrather than attempted.#821 conflict warning still stands. Both tickets edit
RESTRICTED_COLLECTIONSand the samedocs/rules/access.mdsection. Whichever lands second must correct the other's stated why.Rotation is still an open question on the ticket, and independent of this PR. Nothing here rotates or invalidates the three published keys.
Closes #822
🤖 Generated with Claude Code
https://claude.ai/code/session_01YTSRAA3WWCzs8nA9t2X5Jc