Skip to content

fix(access)!: gate version reads on edit authority, not login - #752

Merged
sydevs-bot merged 9 commits into
mainfrom
claude/fix-719-readversions
Sep 10, 2026
Merged

sydevs-bot merged 9 commits into
mainfrom
claude/fix-719-readversions

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • readVersions was unset on every collection and global, so any published client's API key could read drafts through /api/{collection}/versions.
  • It now derives from the entity's own update authority: anyone who may edit reads the history, nobody else.
  • Behaviour change: a read-only manager loses the History tab. Live preview is untouched.

Changes

  • src/plugins/access/accessConfigs.ts — withVersionHistoryAccess, which derives readVersions from an access config's own update: it drops the version-row id, and translates a returned Where with appendVersionToQueryKey.
  • 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 — a Version 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

  • Lean gate: ✓ lint, typecheck, typecheck:tests, test:unit (1671 passed)
  • Targeted specs: tests/int/role-based-access.int.spec.ts — 65 passed, 9 of them new
  • Build: N/A — Railway builds the preview

Each new assertion was verified by reintroducing the defect it covers and watching it go red:

Mutation Cases that fail
Drop the readVersions derivation 5 of 9
Drop the appendVersionToQueryKey translation the document-manager case, and the atlas-manager event case
Forward args.id to update the by-ID case

Manual verification

  1. As a manager holding only meditations-editor, open an App Card — the Versions tab should be gone.
  2. As an admin, open a Page — the Versions tab still lists rows, and restoring a version still works.
  3. With the admin live preview open on a draft Page, confirm the external frontend still renders the draft.

Notes for reviewer

Three findings from the review pass were filed rather than fixed here, to keep this PR to one behaviour:

One judgement call worth checking: web-translator holds translate on pages, and hasPermission treats a collection-level translate as update. 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 to update.

The shape, after two reviews (adfc807). Your first review asked for withVersionHistoryAccess to go, inline. Inlined, its four lines became fifteen in each of accessPlugin's two branches — a mutated local access plus both ⚠ comments, twice — and your second review asked for that back out. ab09a91 is now reverted exactly: the five files match 5650f6c byte 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 update rather 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. accessPlugin spreads ...collection.access over the generated config. Deriving readVersions inside createAccessConfig would bind it to an update an 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 own readVersions keeps it.

Why the Where needs translating. update returns 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 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 rows.

Two Where shapes, not one. Every other case proves the translation for { id: { in } }. events is the one collection whose update returns something else: scopeRegionSubtreeWrite hands back { or: [{ region: { in } }, { manager: { equals } }] }, the only shape exercising appendVersionToQueryKey's recursion into or and two version. paths at once. That case fails loudly rather than quietly without the translation — region is not a path on _events_v, so the read throws Cannot find field for path at region. Worth checking events rather than assuming, given #745: it does not diverge here, because excludeFinishedEvents filters list reads for API clients only.

Why args.id is dropped. findVersionByID calls access with the version row's primary key, not the document's. Forwarded, the self-access bypass would hand a client row N of _clients_v because its own id is N, and userManagesDocument would 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.drafts on pages (src/collections/Pages/Pages.ts), app-cards (src/collections/AppCards/AppCards.ts) and events (src/collections/Events/Events.ts); the project collection lists (src/plugins/access/config/projects.ts); the web-translator, meditations-editor and atlas-manager grants (src/plugins/access/config/roles.ts); drafts on wm-web-translations (src/globals/WeMeditateWebTranslations/WeMeditateWebTranslations.ts).

Where the narrative lives. docs/rules/access.md, which loads on any edit under src/plugins/access/. The two runtime invariants — drop the version-row id, translate the Where — are short comments on the lines they guard.

Review findings dismissed. The spec keeps a local versionSelect rather than reusing idOnlySelect() — it reproduces the original #719 probe shape verbatim, which is the point of that case. Hoisting the duplicated managerUser helper to file scope was skipped: five unrelated const managerUser = testData.dummyUser(...) locals in the same file would shadow it. The new block drops the wrapper instead, since createManager already attaches collection.

Closes #719

🤖 Generated with Claude Code

https://claude.ai/code/session_01Uxg4pdjbYCKTComgDSverY

`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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-752 September 9, 2026 16:42 Destroyed
@railway-app

railway-app Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-752 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Sep 10, 2026 at 3:03 am UTC
1 service not affected by this PR
  • mailpit

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 9, 2026
@sydevs-bot

sydevs-bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 02:58Z address-review · attempt 1 · session · done
  • 02:58Z address-review · attempt 1 · session
  • 01:28Z address-review · attempt 1 · session · done
  • 01:28Z address-review · attempt 1 · session
  • 17:01Z address-review · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 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 Where shape: atlas-manager event history (accessConfigs.ts:230)
  • should-fix — the JSDoc restates the new docs/rules/access.md section (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

Comment thread src/plugins/access/accessConfigs.ts Resolved
Comment thread src/plugins/access/accessConfigs.ts Resolved
Comment thread src/plugins/access/accessConfigs.ts Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 9, 2026
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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-752 September 9, 2026 17:09 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Two adopted, one rebutted. Pushed through 5650f6c.

  • Adopted — untested Where shape: added the atlas-manager event case, the one or-shaped Where that reaches a versions query (5650f6c).
  • Adopted — duplicated JSDoc: cut to a summary plus a pointer to access.md, with the two runtime invariants as comments on the lines they guard (8cea57f).
  • Rebutted — wrapper placement: kept in accessConfigs.ts, since that module builds every access function accessPlugin wires. Left open for you.

Lean gate green. tests/int/role-based-access.int.spec.ts — 65 passed, 9 of them new. Each new assertion was checked by reintroducing the defect and watching it go red.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 9, 2026
@sydevs-bot
sydevs-bot requested a review from Ardnived September 9, 2026 17:18
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

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

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

This draft has had no CI activity for hours and no session holds it. Comment or push to wake me.

🤖 sydevs dispatcher

@sydevs-bot
sydevs-bot marked this pull request as ready for review September 10, 2026 01:21

@Ardnived Ardnived left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The whole withVersionHistoryAccess feels like unnecessary abstraction, let's keep it simpler and easier to read by keeping it inline

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 10, 2026
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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-752 September 10, 2026 01:36 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Adopted. withVersionHistoryAccess is gone — pushed edb2f92.

  • Adopted — wrapper placement: the derivation is now inline in accessPlugin.ts, where each merged access config is built. accessConfigs.ts is untouched by this PR, so it drops an export, an import, and a docs table edit. The four lines now appear twice, once per branch — the trade you asked for.

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.

Lean gate green. tests/int/role-based-access.int.spec.ts — 65 passed, the same 9 version cases. They are the proof the inline version is wired: they assert denial, so an underived readVersions fails them.

main merged in.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 10, 2026

@Ardnived Ardnived left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The last set of changes since my last comment has made things even more complicated, revert it.

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 10, 2026
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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-752 September 10, 2026 03:01 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Reverted. withVersionHistoryAccess is back — adfc807.

ab09a91 (the inline derivation) is reverted exactly: the five files match 5650f6c byte for byte. The merge of main stays.

Why the inline version read worse than the wrapper: its four lines became fifteen in each of accessPlugin's two branches — a mutated local access plus both ⚠ comments, twice.

Behaviour never moved across either step. Lean gate green. tests/int/role-based-access.int.spec.ts — 65 passed, the same 9 version cases.

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 accessPlugin.ts.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 10, 2026
@sydevs-bot
sydevs-bot merged commit 1c94903 into main Sep 10, 2026
14 checks passed
@sydevs-bot
sydevs-bot deleted the claude/fix-719-readversions branch September 10, 2026 04:45
@sydevs-bot sydevs-bot moved this from Revising to Done in SYDevelopers Technical Roadmap Sep 10, 2026

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-752 — adfc8076 Deployed Sep 10, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

fix(access)!: readVersions is unset on every collection, so any API client can read drafts through /api/{collection}/versions

3 participants