Repository navigation
fix(access)!: gate version reads on edit authority, not login - #752
Conversation
`findVersions`, `findVersionByID` and `countVersions` — and their globals
twins — read `access.readVersions` and nothing else. `accessPlugin` never
wrote it, and Payload's fallback for an unset `readVersions` is
`executeAccess`'s permissive one: "is anyone logged in". An API key
satisfies that, and the gate returns `true` rather than a `Where`, so no
constraint is combined into the query.
The result, reproduced against a real Postgres on 2026-09-06: a
`sahaj-atlas-client` that cannot read `pages` at all read an unpublished
page's title through `findVersions`. The published-only restriction lives
in the `read` branch of `createAccessConfig`, which that path never
consults. Blast radius was every collection with `versions.drafts`
(`pages`, `meditations`, `app_cards`, `events`, `clients`) plus the three
translations globals, reachable with any published client's API key.
`createAccessConfig` now produces `readVersions`, delegating to the
collection's own `update` function — the role table, the document-manager
grant and the Atlas region-subtree scoping all already answer "may this
user edit this document", so this reuses that answer instead of defining
a second authority that can drift. The globals branch gets it through the
same spread.
The delegated `Where` is passed through `appendVersionToQueryKey` first.
`update` returns a query over documents; a versions operation combines the
access result straight into a query over the versions collection with no
remapping of its own, where the document sits under `version.` and its id
is `parent`. Untranslated, `{ id: { in: [7] } }` matches version rows by
their own primary key — a wrong answer that still returns documents.
Behaviour changes deliberately: a manager who may only read a collection
loses its History tab, since `/api/access` computes `readVersions` from
this same function. Live preview is unaffected — it reads drafts through
`find`/`findByID` with `draft: true`, which resolves against `read`.
Closes #719
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UCTmkhcoN7uKbgpdiHRPw5
Findings from the /simplify pass, all applied: Altitude: `readVersions` was derived inside `createAccessConfig`, one step before `accessPlugin` spreads `...collection.access` over the result. A collection that overrode `update` would have kept a `readVersions` bound to the plugin's now-unused function — the exact drift the delegation exists to prevent. No collection or global overrides collection-level access today, so this was latent, but the seam was wrong. `withVersionHistoryAccess` now wraps the merged config in `accessPlugin`, and leaves an explicit `readVersions` override alone. Reuse: the hand-rolled `typeof result === 'object' && result !== null` guard is `hasWhereAccessResult`, which payload exports and pairs with `appendVersionToQueryKey` in `replaceWithDraftIfAvailable` — the function the doc comment already cites as precedent. Using it also drops a non-null assertion the caller had already made unnecessary. Tests: dropped a no-op `managerUser` re-spread (`createManager` already attaches `collection`), replaced a full-table version fetch with the one-row lookup it was searching for, and folded four subsumed assertions into the set equality that implies them. The spec docblock now points at the implementation's docblock instead of restating it. Both mutations re-verified after the refactor: removing the derivation fails 5 of the 8 new cases, removing the `Where` translation fails the document-manager scoping case. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01UCTmkhcoN7uKbgpdiHRPw5
Found by the branch security review, and confirmed by mutation: with the
id forwarded, a page editor read version row 15, whose parent is page 13 —
a page they do not manage.
`findVersionByID` calls access with the VERSION ROW's primary key, not the
document's. Those are two independent sequences that overlap in range, so
forwarding `args.id` to `update` made every id-sensitive branch answer about
the wrong document:
- the self-access bypass grants a client row N of `_clients_v` because the
client's own id is N, and `clients` has drafts;
- `userManagesDocument` grants any row whose number happens to match a page
the caller manages;
- `scopeRegionSubtreeWrite` loads an event by a version-row id.
Stripping the id makes `update` answer at the list level. `findVersionByID`
then ANDs that `Where` with `{ id: { equals: <row> } }` itself, so the
decision is the same one, reached correctly, with no extra query.
Not a regression against main — `readVersions` was unset there, so these
calls returned true for any authenticated caller. But it was a hole this
change would otherwise have left open on the by-ID path while closing it on
the list path.
The spec exercises it through the id collision the fixture already builds
deliberately, and asserts against the colliding row's real parent rather
than a named fixture: which page owns that id depends on how many versions
earlier cases in the file wrote, and pinning the decoy passed alone and
failed in the full run.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UCTmkhcoN7uKbgpdiHRPw5
The collections guide's access summary listed every gate but version history, which now has one. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01UCTmkhcoN7uKbgpdiHRPw5
|
🚅 Deployed to the SahajCloud-pr-752 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 ticket: ~35 lines of real code in two files, no refactor riding along. Delegating to update beats a second authority, and wrapping the merged config is a better seam than AC1 asked for.
Gap: the translated Where is proven only for { id: { in } }. events has drafts, and an atlas-manager's update returns { or: [{ region }, { manager }] } — no spec touches it.
Findings
- should-fix — untested
Whereshape: atlas-manager event history (accessConfigs.ts:230) - should-fix — the JSDoc restates the new
docs/rules/access.mdsection (accessConfigs.ts:172) - consider — both call sites sit in
accessPlugin.ts; should the wrapper? (accessConfigs.ts:220)
Checked: #719, the full diff, and accessConfigs, accessPlugin, permissions, bypassPermissions, regionSubtreeAccess whole. Dropping id cannot widen: self-access needs user.id === docId. No entity sets readVersions or overrides access. Globals' update returns booleans, so no translation runs. Six of six ACs have a spec.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The block on `withVersionHistoryAccess` and the "Version history is edit authority" section in `docs/rules/access.md` said the same four things in the same order, several sentences verbatim. That rule file loads on any edit under `src/plugins/access/`, so the next reader already has the narrative — the second copy is the one that drifts. Keeps a two-line summary plus the pointer, and moves the two runtime invariants (drop the version-row id, translate the `Where`) to short comments on the lines they guard. The merged-config invariant stays in the JSDoc: it governs the call site, not a line inside the function. No behaviour change. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Qus9cVYV1xwpQp6Lds3QEr
Every other version-history case proved the translated `Where` for
`{ id: { in } }`. `events` is the one collection whose `update` returns a
`Where` keyed on something else: `scopeRegionSubtreeWrite` hands back
`{ or: [{ region: { in } }, { manager: { equals } }] }`, which is the only
shape exercising `appendVersionToQueryKey`'s recursion into `or` and two
`version.` paths at once. Nothing covered it.
The new case gives an atlas-manager a country > city > venue subtree, puts
one event inside it and one in a separate branch, and asserts the versions
read returns the first parent and not the second. Both events carry a
filler `manager`, so the second half of the `or` matches neither and the
region clause carries the whole decision.
Verified by deleting the translation and watching it go red: `region` is
not a path on `_events_v`, so the read throws `Cannot find field for path
at region` rather than returning wrong rows.
`events` was worth checking rather than assuming, because #745 shows the
versions path can diverge per collection. It does not here:
`excludeFinishedEvents` filters list reads for API clients only, so a
manager's versions read reaches the access layer unmodified.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Qus9cVYV1xwpQp6Lds3QEr
|
Two adopted, one rebutted. Pushed through 5650f6c.
Lean gate green. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
I could not mark ready here — the dispatch token is not allowed to. Everything else on this item is done, so this is the one step left for you. 🤖 sydevs dispatcher |
|
This draft has had no CI activity for hours and no session holds it. Comment or push to wake me. 🤖 sydevs dispatcher |
Ardnived
left a comment
There was a problem hiding this comment.
The whole withVersionHistoryAccess feels like unnecessary abstraction, let's keep it simpler and easier to read by keeping it inline
Ardnived asked for the `withVersionHistoryAccess` wrapper to go: a generic higher-order function over the whole access config was more machinery than the four lines it held, and it split the rule from the two places that apply it. `accessPlugin` now derives `readVersions` where it builds each merged access config, in the collections and globals branches. Behaviour is unchanged — same merged-config seam, same dropped version-row id, same `Where` translation, same respect for an entity that sets its own `readVersions`. The narrative already lives in `docs/rules/access.md`, so only the two runtime invariants stay as comments on the lines they guard. Docs and the spec's pointer follow the rename. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01UaSoiK3ZLiA9VbGxM7YfTF
|
Adopted.
Behaviour is unchanged: same merged-config seam, same dropped version-row id, same Lean gate green.
🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Ardnived
left a comment
There was a problem hiding this comment.
The last set of changes since my last comment has made things even more complicated, revert it.
Reverts ab09a91. Ardnived's first review asked for the wrapper to go and the derivation to sit inline. Inlined, the four lines became fifteen in each of the two branches of `accessPlugin` — a mutated local `access` object plus both ⚠ comments, twice. The second review read that as harder, not easier, and asked for it back. Behaviour is unchanged either way: same merged-config seam, same dropped version-row id, same `Where` translation, same respect for an entity that sets its own `readVersions`. This is a shape decision, and the reviewer settles it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Uxg4pdjbYCKTComgDSverY
|
Reverted.
Why the inline version read worse than the wrapper: its four lines became fifteen in each of Behaviour never moved across either step. Lean gate green. Your two reviews point opposite ways, so tell me which shape you want if neither is it. A third option I did not take: keep it inline but as a one-line named helper in 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
readVersionswas unset on every collection and global, so any published client's API key could read drafts through/api/{collection}/versions.updateauthority: anyone who may edit reads the history, nobody else.Changes
src/plugins/access/accessConfigs.ts—withVersionHistoryAccess, which derivesreadVersionsfrom an access config's ownupdate: it drops the version-rowid, and translates a returnedWherewithappendVersionToQueryKey.src/plugins/access/accessPlugin.ts— wraps the merged access config with it, in both the collections and globals branches.tests/int/role-based-access.int.spec.ts— aVersion history access (readVersions)block, nine cases.docs/rules/access.md,src/collections/AGENTS.md— the rule and its two runtime invariants.Preview
https://sahajcloud-sahajcloud-pr-752.up.railway.app — Railway rebuilds it a few minutes after each push.
Test results
lint,typecheck,typecheck:tests,test:unit(1671 passed)tests/int/role-based-access.int.spec.ts— 65 passed, 9 of them newEach new assertion was verified by reintroducing the defect it covers and watching it go red:
readVersionsderivationappendVersionToQueryKeytranslationargs.idtoupdateManual verification
meditations-editor, open an App Card — the Versions tab should be gone.Notes for reviewer
Three findings from the review pass were filed rather than fixed here, to keep this PR to one behaviour:
unlockis unset, so any client API key can clear a manager's login lockout #748 —unlockis the same unset-key bug and is still open: any client API key can clear a manager's login lockout. Same root cause, but "who may unlock" is a decision, so it is not a mechanical follow-on./api/accesscall for a non-admin manager, and up to 12 per Event edit-view render, because Payload evaluatesupdateandreadVersionsindependently. Most of that duplication predates this PR; this roughly doubles it. Worth knowing before merge — say so if you would rather hold this until the memo lands.readbeforeOperation hook also fires onfindVersions#745 —findVersionsonmeditationsthrows a 400 for every caller, admin included, becausefilterMeditationsByLocalefires on the versions path. Pre-existing and independent, but it is why the read-only-manager case usesapp-cardsrather than the more obviousmeditations.One judgement call worth checking:
web-translatorholdstranslateon pages, andhasPermissiontreats a collection-leveltranslateasupdate. So a translator keeps the History tab on pages. That reads correct to me — they can edit pages, and history is how a translator sees what changed — but it is the least obvious consequence of mapping toupdate.The shape, after two reviews (adfc807). Your first review asked for
withVersionHistoryAccessto go, inline. Inlined, its four lines became fifteen in each ofaccessPlugin's two branches — a mutated localaccessplus both ⚠ comments, twice — and your second review asked for that back out.ab09a91is now reverted exactly: the five files match5650f6cbyte for byte. Behaviour never moved across either step. If neither shape is the one you want, say which and I will take it there.Detail
Why
updaterather than a new rule. The role table, the document-manager grant, and the Atlas region-subtree scoping all already answer "may this user edit this document". A second authority would be a second thing to keep in step.Why the wrapper is applied in
accessPlugin.accessPluginspreads...collection.accessover the generated config. DerivingreadVersionsinsidecreateAccessConfigwould bind it to anupdatean override had already replaced — the exact drift the delegation exists to prevent. No entity overrides collection-level access today, so this was latent, but the seam was wrong. An entity that sets its ownreadVersionskeeps it.Why the
Whereneeds translating.updatereturns a query over documents. Every versions operation combines the access result straight into a query over the versions collection with no remapping of its own, where a document's fields sit underversion.and its id isparent. Untranslated,{ id: { in: [7] } }matches version rows by their own primary key — a wrong answer that still returns rows.Two
Whereshapes, not one. Every other case proves the translation for{ id: { in } }.eventsis the one collection whoseupdatereturns something else:scopeRegionSubtreeWritehands back{ or: [{ region: { in } }, { manager: { equals } }] }, the only shape exercisingappendVersionToQueryKey's recursion intoorand twoversion.paths at once. That case fails loudly rather than quietly without the translation —regionis not a path on_events_v, so the read throwsCannot find field for path at region. Worth checkingeventsrather than assuming, given #745: it does not diverge here, becauseexcludeFinishedEventsfilters list reads for API clients only.Why
args.idis dropped.findVersionByIDcalls access with the version row's primary key, not the document's. Forwarded, the self-access bypass would hand a client rowNof_clients_vbecause its own id isN, anduserManagesDocumentwould grant any row whose number matched a page the caller manages. Confirmed by mutation: a page editor read version row 15, parent page 13, which they do not manage.A trap the specs had to work around. Page ids and version-row ids are independent sequences that line up 1:1 in a fresh schema where each page has one version — so the untranslated query returns the right rows by coincidence, and the scoping assertions passed with the translation deleted. The fixture now writes extra versions to offset the sequences, and pins that offset so the case cannot silently go vacuous again.
Fixture pre-mortem. Each assumption was checked against the real config, not inferred:
versions.draftsonpages(src/collections/Pages/Pages.ts),app-cards(src/collections/AppCards/AppCards.ts) andevents(src/collections/Events/Events.ts); the project collection lists (src/plugins/access/config/projects.ts); theweb-translator,meditations-editorandatlas-managergrants (src/plugins/access/config/roles.ts); drafts onwm-web-translations(src/globals/WeMeditateWebTranslations/WeMeditateWebTranslations.ts).Where the narrative lives.
docs/rules/access.md, which loads on any edit undersrc/plugins/access/. The two runtime invariants — drop the version-row id, translate theWhere— are short comments on the lines they guard.Review findings dismissed. The spec keeps a local
versionSelectrather than reusingidOnlySelect()— it reproduces the original #719 probe shape verbatim, which is the point of that case. Hoisting the duplicatedmanagerUserhelper to file scope was skipped: five unrelatedconst managerUser = testData.dummyUser(...)locals in the same file would shadow it. The new block drops the wrapper instead, sincecreateManageralready attachescollection.Closes #719
🤖 Generated with Claude Code
https://claude.ai/code/session_01Uxg4pdjbYCKTComgDSverY