Skip to content

fix(access): resolve manager roles at every locale, not just English - #668

Merged
sydevs-bot merged 7 commits into
mainfrom
claude/fix-localized-manager-roles
Sep 2, 2026
Merged

sydevs-bot merged 7 commits into
mainfrom
claude/fix-localized-manager-roles

Conversation

@sydevs-bot

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

Copy link
Copy Markdown
Contributor

Summary

A manager whose roles are assigned in a non-default locale could not use the admin at all. The cause was one missing read: Managers.roles is localized, and every path that populated the authenticated user resolved it at the default locale — so req.user.roles was a flat English array, never the per-locale record src/plugins/access is written against.

The per-locale model was therefore inert at runtime, in both directions:

  • Over-grant (invisible, and the more serious half) — every manager's English roles applied in all 19 locales.
  • Under-grant (the reported bug) — a manager with no English roles got an empty array, saw "No Projects Available", and had an English-only locale dropdown, so their own locale was unreachable.

⚠ This tightens access. Anyone relying on their English roles leaking into other locales loses that the moment it deploys. Audit Managers role assignments before deploying, per the ticket's deployment note.

Where the mechanism lives

src/plugins/access/localizedRolesAuth.ts — one file, one export (withLocalizedRoleAuth). accessPlugin attaches it; Managers.ts configures none of it and carries only a four-line comment saying where it lives.

Attachment keys on the condition, not the slug: an auth collection whose roles field is localized. So Clients is skipped for a stated reason (its roles is flat), and a future auth collection with localized roles is covered on arrival rather than broken silently.

It is four reads rather than one because Payload re-loads the manager at four moments, each at a single locale:

Moment Without it
the auth strategy, every authenticated request req.user.roles is flat — every server-side access check is wrong
afterLogin the first user the admin holds is flat
afterMe AuthProvider calls /me on mount and overwrites the strategy — right projects on first paint, then "No Projects Available"
afterRefresh a tab left open reverts mid-session

Registration order makes the strategy safe: custom strategies are collected first and local-jwt is appended last, and executeAuthStrategies returns on the first strategy yielding a user — so this runs in front of the default rather than replacing it.

hasPermission's locale is a RoleScope, and requests cannot name the privileged one

Scope Meaning Who chooses it
a LocaleCode roles in that locale every ordinary check
'union' roles in any locale the call site, statically — admin nav visibility alone
undefined nothing resolvable → deny ?locale=all, and any locale not in LOCALES

Every request-to-scope translation goes through roleScopeFromLocale, which validates against LOCALES rather than casting. That replaced four hand-written copies that had already drifted — and the fourth (EventSubmissions/review.ts) answered ?locale=all with 'union' where the other three denied it.

Writing it once surfaced a privilege escalation none of the four copies showed. req.locale is a request-supplied string and RoleScope has a non-locale member, so a plain cast let ?locale=union name the privileged scope and hand a manager their roles from all 19 locales — exactly the over-grant #665 exists to remove. Found because the assertion written for it went red against the first implementation, which did cast.

'union' survives as something a call site opts into, never something a caller can be talked into. Payload's hidden?: ((args: { user: ClientUser }) => boolean) signature (types.d.ts:414) offers no locale at all, and getVisibleEntities treats a throw as hidden — so scoping nav visibility otherwise empties the sidebar of every collection and global for every non-admin manager.

Two behaviour changes worth your eye

1. ?locale=all now denies a manager where it used to grant (200 → 403). This is the ticket's open question 1, implemented as the apparent original intent: a request for every locale at once names no locale to evaluate roles in, and the previous grant was the flat array leaking through — not a decision. The admin UI never sends it (publish-all-locales is a body flag, not a query locale), so it reaches hand-rolled API calls only. Clients are unaffected throughout, since Clients.roles is not localized.

2. The locale dropdown no longer force-adds English, lists only locales the manager holds a role in, and orders them most-roles-first. That first entry is also where Payload lands them, so the ordering is real behaviour rather than cosmetics. A manager with roles in no locale still gets English and still sees the banner.

Test results

  • Unit ✓ 117 files / 1534 tests
  • Integration ✓ 67 files / 1137 tests — the full lane, not a targeted spec, because the access plugin applies to every collection so nothing narrower bounds the blast radius
  • lint ✓ · typecheck ✓ · typecheck:tests ✓

Three new unit specs (localizedRoles.spec.ts, localizedRoleScope.spec.ts, localizedRolesAuth.spec.ts), plus two integration cases that authenticate for real through payload.auth — the mock-only gap that let this bug live.

Every new assertion was made to fail before being kept — including one that revealed a guard with no coverage at all

Per .claude/rules/tests.md, each defect was reintroduced at the site that would really cause it:

Defect reintroduced Result
Force-add English in filterAvailableLocales 2 red
Drop the role-count ranking (fall back to LOCALES order) 3 red
Remove the custom auth strategy — the bug itself 2 red (both integration cases)
extractRoles resolves across all locales regardless of scope 2 red
Attach predicate ignores localized 1 red
Attach replaces a collection's own hooks instead of appending 1 red
Remove locale: 'union' from createHidden 0 red — nothing covered it

That last row is the useful one. The union scope in createHidden is what keeps the admin sidebar from emptying for every non-admin manager, and removing it broke nothing in the suite. tests/unit/localizedRoleScope.spec.ts exists because of that, and it now goes red on exactly that removal.

Library behaviours read from node_modules/ rather than assumed

Each of these would produce a silent wrong answer if taken on trust:

  • local-jwt passes no locale. auth/strategies/jwt.js:67-71 calls payload.findByID({ id, collection, depth }), and createLocalReq then sets req.locale = localization.defaultLocale. This is the root cause, confirmed in source.
  • JWTAuthentication is exported from payload (index.d.ts:509), so the strategy wraps it rather than reimplementing the session check, the _verified gate and the autoLogin fallbacks.
  • Custom strategies run BEFORE local-jwt, which is appended last (index.js:437-446). Adding one does not disable the default.
  • executeAuthStrategies swallows thrown errors (lines 21-26) and falls through to the next strategy. So a hydration failure that threw would silently restore the flat, over-granting shape — the strategy therefore catches and returns an empty role record instead. Fails closed and visibly ("No Projects Available") rather than open and silently.
  • afterLogin runs BEFORE the field-level afterRead pass in login.js, which resolves localized fields at the request locale. That ordering is noted in the hook's docblock; the load-bearing hook is afterMe, and that is the one the integration test asserts.
  • hidden receives { user } and nothing else — payload/dist/collections/config/types.d.ts:414. No req, no locale, no way to obtain one.
The test-suite assertions that certified the bug, and what changed

tests/int/role-based-access.int.spec.ts asserted against flat arrays with no locale at nine sites — including inside describe('Localized Manager Roles'). Those passed only because of the Array.isArray short-circuit, so the suite did not merely miss this bug, it encoded it as the expected contract. They are rewritten to the per-locale shape with an explicit locale, not extended.

testData.createManager accepted a { en, cs } roles object and wrote only roles.en, so the manager in the bug report — roles in a non-English locale only — was unconstructible. It now writes every locale it is given, creating at the first and updating for the rest, since a single create only stores the locale it was created at.

_verified: true is set explicitly on the managers in the new login tests: Managers configures auth.verify, and create does not imply it the way first-register does.

Review rounds — what your feedback changed

Round 1 (8 threads, all resolved). The largest change was structural, and it was yours: the strategy and the three hooks moved out of src/collections/Managers/ into the access plugin as one file, and the plugin now attaches them itself. Two files → one, six exports → one, Managers.ts −18 lines.

Two threads produced defects rather than tidying:

  • Unifying the req.locale translation exposed the ?locale=union escalation described above.
  • Deriving LocalizedRoles from Manager['roles'] rather than hand-writing it revealed the hand-written type was wider than the truth — RoleSlug includes client roles like wemeditate-web-client, which a manager's record should never accept.

A defect of mine reached CI in this round. Rewriting the wiring as a predicate left it scanning only top-level fields, and Managers.roles sits inside a tabs field — so the entire fix was inert on the branch while lint, typecheck and 1527 unit tests passed. Two integration assertions caught it. Fixed in 8d200a5 using Payload's own flattenTopLevelFields, which encodes the distinction that matters: tabs/row/collapsible children are still manager.roles, while group/array children sit at a different data path and must not match. The spec now pins both directions. The cause was my own unit fixture declaring roles at the top level because that was easier to write than the real config.

Round 2 (2 threads, both resolved).

What I did NOT verify

Steps 4–8 of the ticket's verification checklist require driving the admin UI in a browser against a seeded database — the landing redirect settling on ?locale=fr, the header label agreeing with req.locale, and the banner not reappearing after /me and the refresh timer fire. I could not run those, and the redirect in particular is Payload's own behaviour that this PR activates by dropping forced-English rather than implements. Worth a manual pass before merge.

Closes #665

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


🤖 Generated with Claude Code

https://claude.ai/code/session_01F2BczvDrd7opTwedpZHZ6L

`Managers.roles` is localized, but every path that populated the
authenticated user resolved it at the default locale — so `req.user.roles`
was a flat English array, never the per-locale record the access plugin is
written against. The per-locale model was inert at runtime in both
directions: every manager's English roles applied in all 19 locales
(over-grant), and a manager with no English roles was locked out of the
admin entirely (the reported bug).

Two reads put it right, and both are needed. `localizedRolesStrategy` wraps
Payload's `JWTAuthentication` and re-reads roles at `locale: 'all'`, fixing
`req.user`; `afterMe`/`afterRefresh`/`afterLogin` do the same for the three
auth responses, which re-read the document themselves and would otherwise
overwrite the record the moment the admin client calls `/me`.

`hasPermission`'s `locale` is now a `RoleScope`, so each caller states what
it means rather than relying on an absent value: a LocaleCode, `'union'`
(admin nav visibility, which Payload invokes with no locale — scoping it
otherwise empties the sidebar for every non-admin manager), or nothing,
which denies.

Also: `filterAvailableLocales` no longer force-adds English, ranks locales
by role count and never returns empty; `review.ts` threads a locale, which
it must or every non-admin manager 403s.

Two behaviour changes worth naming. This TIGHTENS access — anyone relying
on English roles leaking into other locales loses that on deploy. And
`?locale=all` now denies a manager where the flat array used to leak
through and grant (200 -> 403); the admin UI never sends it, so this
reaches hand-rolled API calls only. Clients are unaffected throughout.

Closes #665

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018oiV3fKDoPhKcjhX39LvWp
@sydevs-bot
sydevs-bot requested a review from Ardnived September 1, 2026 00:44
@railway-app

railway-app Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Sep 1, 2026 at 8:54 pm
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-668 September 1, 2026 00:45 Destroyed
…se roles

All three auth-response hooks run INSIDE an open transaction — `login.js`
opens at :190, runs `afterLogin` at :263 and commits at :321, and
`refresh.js` is the same shape. `hydrateLocalizedRoles` was called with no
`req`, so it took a SECOND pool connection while the first was still held.
Under concurrency that exhausts the pool and the lane stops making progress
rather than failing, which is not a mode any gate reports usefully.

Passing the caller's own `req` would fix the connection but reintroduce
#609: `createLocalReq` assigns `req.locale` onto the object it is given, so
`locale: 'all'` would leak into every later step of the operation.

`localeIsolatedReq` is exactly the pair of properties needed — `transactionID`
carries by reference so the read joins the existing transaction, while
`locale` becomes the copy's own.

The auth strategy still passes nothing, correctly: it runs in
`executeAuthStrategies`, before any operation, so there is no transaction to
join and no caller locale to protect.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018oiV3fKDoPhKcjhX39LvWp
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-668 September 1, 2026 00:56 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Found and fixed a defect of my own while watching CI — pushed 354ef6c. Worth reading even though the code change is one argument, because the failure mode is one no gate reports usefully.

The first CI run sat on pnpm test for over an hour (this repo's whole job normally takes ~20 min). Rather than call it a slow runner, I went looking for a mechanism, and there was one:

All three auth-response hooks run inside an open transaction — login.js opens at :190, runs afterLogin at :263, commits at :321; refresh.js is the same shape. hydrateLocalizedRoles was called with no req, so it took a second pool connection while the first was still held. Every login held two. Under concurrency that exhausts the pool and the lane stops making progress rather than failing — no error, no red check, just a job that never ends.

The fix is localeIsolatedReq(req), which this repo already has for the neighbouring trap:

Option Result
no req (what I shipped) second connection → pool exhaustion
the caller's own req joins the transaction, but createLocalReq repoints req.locale to 'all' for the rest of the operation — #609
localeIsolatedReq(req) transactionID carries by reference so the read joins the transaction; locale becomes the copy's own

The auth strategy still passes nothing, and that is correct: it runs in executeAuthStrategies, before any operation, so there is no transaction to join and no caller locale to protect. The asymmetry is documented at both call sites.

⚠ I have not proven this was the cause of the hang — I cancelled nothing and the original job may simply have been slow. What I can say is that the double-connection-inside-a-transaction was real, was mine, and is the kind of thing that passes every local gate. It passed mine: full integration lane green at 67 files / 1137 tests both before and after, because a 6-fork local run against a fresh Postgres has the headroom to absorb it.

Re-validated on 354ef6c: lint · typecheck · typecheck:tests · 115 files / 1518 unit · 67 files / 1137 integration, all green.

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


Generated by Claude Code

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Correction to my previous comment: there was no hang. The first CI run was healthy.

Run 33455977217 started 00:44:26Z and ended 00:56:53Z — 12m27s, normal for this job, and it ended cancelled because my own push superseded it (concurrency: cancel-in-progress), not because it stalled.

My "over an hour on pnpm test" was an artifact of comparing GitHub's timestamps against this sandbox's clock, which runs ~70 minutes ahead of them. I never actually measured elapsed time; I subtracted two clocks that do not agree. Same shape as the mistake the last run recorded — reading a signal from one layer as evidence about another.

Keep 354ef6c anyway, on its own merits. The defect it fixes is real and independent of the imaginary hang: the auth-response hooks demonstrably run inside an open transaction (login.js :190 → :263 → :321), and the read demonstrably took a second pool connection there. That is a latent pool-exhaustion risk under load whether or not it ever fired in CI. What changes is the evidence for it — source-read, not observed — so treat it as defence in depth rather than a fix for something seen in the wild.

What still stands unchanged: full gate green on 354ef6c (lint · typecheck · typecheck:tests · 115 files / 1518 unit · 67 files / 1137 integration), and localeIsolatedReq is the right call regardless, since passing the raw req would have reintroduced #609.

Sorry for the noise on the thread — better a correction than a wrong claim left standing in a PR you are about to review.

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


Generated by Claude Code

@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.

Overall it feels like we are adding a ton of additional layers and methods to handle something which should be relatively simple. Take a step back and consider our whole system more holistically, how can we create a system that works in-line with PayloadCMS instead of fighting it?

Comment thread src/collections/Managers/Managers.ts Resolved
Comment thread src/plugins/access/accessConfigs.ts Resolved
Comment thread src/plugins/access/localizedRoles.ts Resolved
Comment thread src/plugins/access/localizedRoles.ts Resolved
Comment thread src/plugins/access/types.ts Resolved
…o the plugin

Addresses the eight review threads on #668. Three of them turned out to be
pointing at the same defect, and one of the fixes exposed a second.

**`?locale=all` was answered two different ways.** The translation from
`req.locale` (a request-supplied string that also carries `'all'`) to `RoleScope`
was written out at four call sites, and the fourth disagreed: EventSubmissions'
review endpoint resolved `'all'` to `'union'` — a role in ANY locale grants —
while collection access, global access and the Frames endpoint denied it. Same
request shape, opposite answer, decided by which file you were in.
`roleScopeFromLocale` is now the one statement of it, and it denies, matching
the three that agreed and the policy the PR body documents.

**Writing it once surfaced a privilege escalation the four copies had hidden.**
`RoleScope` has one non-locale member, so casting `req.locale` into it lets
`?locale=union` NAME the privileged scope: a manager would get their roles from
all 19 locales at once — precisely the over-grant #665 exists to remove. The
helper therefore returns a scope only for a configured locale. The assertion
covering this went red against the first version of the helper, which is how it
was found.

**The auth wiring moves from Managers.ts to the access plugin.** The strategy
and the three auth-response hooks are the plugin's mechanism, not the
collection's, so `withLocalizedRoleAuth` now attaches all four and accessPlugin
applies it. Managers.ts keeps a comment and no wiring. The predicate is the
pair that actually causes the bug — an auth collection whose `roles` field is
localized — rather than the slug `managers`, so `Clients` is skipped for a
stated reason and a future auth collection is not silently broken.

The three hooks stay three: `login`, `/me` and `/refresh-token` each re-read the
manager at a single locale, at different moments, and Payload exposes no single
point covering them. `localizedRolesAuth.ts` opens with the table of which
moment each one closes.

`LocalizedRoles` now derives its element type from `Manager['roles']`. Only the
per-locale keying is ours. Doing so caught that `Manager['roles']` and
`RoleSlug` are NOT the same set — `RoleSlug` includes client roles — so
`unionRoles` widened to accept both collections' shapes rather than pretending
they are one.

Also drops the nine-line comment on the `?locale=all` line, which the helper's
docblock now carries in one place instead of at every call site.

New: `tests/unit/localizedRolesAuth.spec.ts` covers the attach decision itself.
The wiring became a predicate rather than an explicit list, and a predicate that
stops matching takes the whole fix offline with nothing in this lane to notice.

Every new assertion was made to fail at the site that would really cause it:
`'all'`→`'union'` (2 red), predicate ignoring `localized` (1 red), attach
replacing rather than appending (1 red).

Gates: lint · typecheck · typecheck:tests · 115 files / 1523 unit — all green.
The integration lane needs PostgreSQL, which this environment has none of (#663);
CI runs it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q9dYn2dB8wsmyCBYURXM6K
# Conflicts:
#	.claude/rules/access.md
#	.claude/rules/access.md~HEAD
#	tests/utils/testData.ts
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-668 September 1, 2026 18:45 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

All eight threads answered; six are addressed and resolved, two are open questions for you. Pushed cf1e302 (the changes) and 2c4569f (merge of main, which had moved under this branch).

Your review found more than eight nits — three of the threads were pointing at the same defect, and fixing it exposed a second one that all four copies had hidden.

?locale=all was answered two different ways. The req.locale → RoleScope translation was hand-written at four call sites and the fourth disagreed: EventSubmissions/review.ts resolved 'all' to 'union' (a role in any locale grants) while collection access, global access and Frames/by-narrator denied it. Now one function, roleScopeFromLocale, and it denies.

Writing it once surfaced a privilege escalation. RoleScope has a non-locale member, so casting a request-supplied req.locale into it lets ?locale=union name the privileged scope — a manager would get their roles from all 19 locales at once, the exact over-grant #665 exists to remove. The helper validates against LOCALES instead of casting. I found this because the assertion I wrote went red against my own first version, which did cast.

The auth wiring moved into the plugin, as you asked, and accessPlugin now attaches it. Managers.ts has no auth-hook configuration at all — it keys on the condition (an auth collection whose roles field is localized) rather than the slug, so Clients is skipped for a stated reason and a future auth collection is covered on arrival.

Two things still with you

  1. localizedRolesAuth.ts:56 — should unionRoles be renamed to something that names its one legitimate caller (rolesForNavVisibility)? Your call; I did not want to slip a rename into a PR you are mid-review on.
  2. types.ts — three of TypedAuthUser's four members are genuinely redundant with payload-types.ts, and one (currentProject) is wrong rather than merely duplicated. I did not unpick it: it touches every access consumer and is a diffuse refactor to bolt onto a locale bugfix. Happy to file it as its own ticket — the thread has the table.
What changed, and the gates
Thread Outcome
review.ts:38 — why translate, is union right? ✅ union was wrong; one helper, denies
localizedRolesHooks.ts — belongs in the plugin? ✅ moved; two files → one, six exports → one
localizedRolesStrategy.ts — same ✅ merged into the same file
Managers.ts:81 — higher level than three hooks? ✅ plugin attaches all four; Managers.ts −18 lines
accessConfigs.ts:99 — comment necessary? ✅ deleted, both copies
localizedRoles.ts:35 — import from payload-types? ✅ done; caught that the hand-written type was wider than the truth
localizedRoles.ts:56 — is unionRoles necessary? ⏸ yes — hidden?: ((args: { user }) => boolean) is Payload's whole signature, verified in collections/config/types.d.ts:414. Rename is your call
types.ts — drop definitions? ⏸ three can go, but not in this PR

The three hooks stayed three, and I could not argue them down: login, /me and /refresh-token each re-read the manager at a single locale at different moments, and Payload exposes no single point covering them. The file opens with the table of which moment each one closes, so the next reader gets the argument instead of three functions.

New spec — tests/unit/localizedRolesAuth.spec.ts. The wiring became a predicate rather than an explicit list, and a predicate that stops matching takes the whole fix offline with nothing in the unit lane to notice.

Every new assertion was made to fail at the site that would really cause it: 'all'→'union' (2 red), predicate ignoring localized (1 red), attach replacing rather than appending (1 red).

Gates: lint · typecheck · typecheck:tests · 116 files / 1527 unit — all green. The integration lane needs PostgreSQL and this environment has none (#663), so CI is the first thing to run it; that matters more than usual on an access change, and the access plugin now rewrites every collection's auth config.

Also repointed the .claude/rules/* references this branch carried, since #669 moved those files out from under it while it was open.

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


Generated by Claude Code

CI's integration lane caught what my own unit spec could not: the predicate
deciding which collections get the localized-roles auth strategy scanned
`collection.fields` directly, and `Managers.roles` lives inside a `tabs` field.
It never matched, so the strategy and all three auth hooks were attached to
nothing and #665's fix was entirely inert on the branch — with lint, typecheck
and 1527 unit tests all green.

`flattenTopLevelFields` (Payload's own) is the right tool rather than a
hand-rolled walk, because it encodes exactly the distinction that matters:
`tabs`, `row` and `collapsible` are presentational, so their children are still
top-level data (`manager.roles`), while `group` and `array` children sit at a
different path and are NOT the field `hydrateLocalizedRoles` selects. A
recursive walk that descended into groups would silently hydrate the wrong
field.

**The spec's fixture was the defect.** It declared `roles` at the top level —
easier to write than the real config, and therefore not covering the real
config. It now nests `roles` in a `tabs` field exactly as Managers does, with
added cases for the flat shape and for a `group`, which must NOT match.

Reintroducing the top-level-only scan now turns that spec red (2 failures);
before this commit it stayed green through the real failure.

Gates: lint · typecheck · typecheck:tests · 117 files / 1534 unit — green.
Integration still needs CI (no PostgreSQL here, #663), which is the whole
lesson of this commit.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q9dYn2dB8wsmyCBYURXM6K
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-668 September 1, 2026 19:03 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

CI went red on my last push and I have fixed it — but the failure is worth reading, because for one commit this PR did nothing at all while every local gate passed. Pushed 8d200a5.

Moving the wiring into the plugin (your review) meant replacing an explicit list of four hook registrations with a predicate: is this an auth collection whose roles field is localized? The predicate scanned collection.fields directly — and Managers.roles lives inside a tabs field, so it never matched. The strategy and all three hooks were attached to nothing, and #665's fix was completely inert on the branch.

Green on lint, typecheck, typecheck:tests and 1527 unit tests throughout. role-based-access.int.spec.ts — the two cases that authenticate for real — is the only thing in this repo that could see it.

My unit spec's fixture was the actual defect. It declared roles at the top level, which was easier to write than the real config and therefore was not covering the real config. It now nests roles in a tabs field exactly as Managers does; reintroducing the top-level-only scan turns it red, and before this commit it stayed green through the real failure.

Why flattenTopLevelFields rather than a recursive walk

Payload's own utility encodes the distinction that matters, and a hand-rolled recursion would have got it wrong in the other direction:

Container Children's data path Should match?
tabs, row, collapsible manager.roles — presentational only yes
group, array manager.group.roles no — not the field hydrateLocalizedRoles selects

A walk that descended into everything would attach the strategy for a group.roles and then hydrate the wrong field, silently. The spec now pins both directions.

On your "is this complicating things" instinct — this is the cost of the predicate, and it is fair to weigh it. What I would say for it: the failure was loud (two integration assertions, naming the exact behaviour), it is now covered in the unit lane, and the alternative — an explicit list in Managers.ts — is what you asked me to remove and what would silently omit the next auth collection. Happy to go back to an explicit registration in the plugin if you would rather have the obviousness; say so and I will.

CI is re-running on 8d200a5. I will not be awake to watch it land — if it is red again, that is on the next run's list.

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


Generated by Claude Code

@Ardnived

Ardnived commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

@sydevs-bot I've responded to some of your review comments.

@Ardnived Ardnived assigned sydevs-bot and unassigned Ardnived Sep 1, 2026
`unionRoles` described the set operation; `rolesForAllLocales` describes
the question a caller is entitled to ask. Reviewer's wording, adopted as
given.

The rename is the second half of making `'union'` unreachable from a
request. The first half was `roleScopeFromLocale`, which stopped a
request-supplied `?locale=union` from naming the privileged scope. What
remains is the helper itself, and its risk is a second caller adopting it
by mistake — a name that reads as a generic set union invites that, where
one that says "all locales" reads as the deliberate widening it is.

No behaviour change: one exported symbol, three call sites, one spec
describe block. The docblock stating the single legitimate caller
(admin-nav visibility, which Payload invokes with no locale) is unchanged
and still the real guard.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01F2BczvDrd7opTwedpZHZ6L
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-668 September 1, 2026 20:51 Destroyed
@sydevs-bot sydevs-bot assigned Ardnived and unassigned sydevs-bot Sep 1, 2026
@Ardnived Ardnived assigned sydevs-bot and unassigned Ardnived Sep 2, 2026
@sydevs-bot
sydevs-bot merged commit 9d43dff into main Sep 2, 2026
2 checks passed
sydevs-bot pushed a commit that referenced this pull request Sep 5, 2026
Three admin components call the REST API with a hand-rolled fetch that
sends no `?locale=`. Payload resolves such a request at the default
locale, and every role gate then evaluates the manager's English roles.
Since #668 made roles genuinely per-locale, a manager whose roles live
only in another locale is denied on all three surfaces.

Confirmed on the reported record: managers/504's `roles` is
`{"fr":["path-editor","meditations-editor"]}` — no `en` key at all, so
`roles['en'] || []` is empty and `hasPermission` returns false.

- FrameEditor/hooks.ts — the locale joins the SWR key, so switching the
  admin locale refetches for free.
- ThumbnailCell — the loader is a module singleton, not a hook, so the
  locale threads through `load()` and the batch key becomes
  `relationTo:locale`. Two locales must not share a batch: the response
  is gated per locale, so merging them would answer one locale's cells
  from the other's request.
- EventSubmissionActions — both URLs carry it. DELETE is not
  locale-gated today, but consistency costs nothing.

Fixed on the client, not the server: the gates are deliberate and
documented, and Payload's own fetches already send the locale.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY
sydevs-bot added a commit that referenced this pull request Sep 6, 2026
…711)

* fix(admin): send the active locale on hand-rolled admin REST fetches

Three admin components call the REST API with a hand-rolled fetch that
sends no `?locale=`. Payload resolves such a request at the default
locale, and every role gate then evaluates the manager's English roles.
Since #668 made roles genuinely per-locale, a manager whose roles live
only in another locale is denied on all three surfaces.

Confirmed on the reported record: managers/504's `roles` is
`{"fr":["path-editor","meditations-editor"]}` — no `en` key at all, so
`roles['en'] || []` is empty and `hasPermission` returns false.

- FrameEditor/hooks.ts — the locale joins the SWR key, so switching the
  admin locale refetches for free.
- ThumbnailCell — the loader is a module singleton, not a hook, so the
  locale threads through `load()` and the batch key becomes
  `relationTo:locale`. Two locales must not share a batch: the response
  is gated per locale, so merging them would answer one locale's cells
  from the other's request.
- EventSubmissionActions — both URLs carry it. DELETE is not
  locale-gated today, but consistency costs nothing.

Fixed on the client, not the server: the gates are deliberate and
documented, and Payload's own fetches already send the locale.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY

* test(admin): cover the locale gate over the real REST pipeline

The suite was green through the bug because nothing drove Payload's REST
pipeline as a manager with roles only in a non-default locale. The
handler-level specs build `req` by hand and hardcode `locale: 'en'`, so
none of them could see how `req.locale` is derived — which is exactly
where #701 lived.

- restRequest: `createRestClientAs(env, manager)` logs in any manager,
  and the caller now takes a method and a JSON body. `createRestClient`
  keeps its signature and delegates.
- frames-by-narrator: three REST cases for a French-only
  meditations-editor — no `?locale` → 403, `?locale=fr` → 200,
  `?locale=en` → 403.
- event-submissions-review: the same three for an `atlas-manager` on
  `POST /:id/review`. A sibling file, not a suite in
  event-submissions.int.spec.ts, because `getPayload` caches per config
  and a second createTestEnvironment in one file returns the first.
- relationshipDocLoader: locale forwarding, per-locale batching, and the
  default fetcher's URL — the code a comment called "not worth a unit
  test", where the defect was.

Fixture pre-mortem: `testData.createManager` writes a per-locale roles
object one locale at a time (verified in tests/utils/testData.ts), so
`{ fr: [...] }` really does leave `roles.en` empty — checked against the
reported production record, managers/504, whose roles carry no `en` key.
`anchorRegion` must be a city or venue, so the review fixture anchors on
a city under the managed country (prepareSubmission.ts:101).

Every new assertion was confirmed failing first: flipping each fixture's
locale to `en` turns all six REST cases red, dropping `locale` from the
loader's query object turns the URL case red, and collapsing the batch
key to `relationTo` turns the batching case red.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY

* docs(access): a hand-rolled admin fetch must send the active locale

The rule #701 turned on, stated where each audience reads: the role-scope
section of the access rules, and the direct-Payload-access section of the
admin UI rules.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY

* fix(admin): pin the two unasserted locale call sites, and narrow the rule

Adversarial review on #711 raised four threads. All four applied.

The written rule in `docs/rules/access.md` was the deliverable #701 chose
instead of a shared helper, and it said "on every request" while four
hand-rolled admin fetches legitimately do not send a locale. A reader who
greps `fetch('/api/` found four counter-examples with nothing to tell them
apart, so the rule read as approximate. It now names the condition — the
endpoint or collection runs a per-locale `hasPermission` — and tables every
call site on each side of it. `docs/rules/admin-ui.md` carried the same
overbroad claim and now defers to it.

Of the three call sites the fix touches, only the loader's URL was pinned.
The two carrying the user-visible half rested on inspection, with the manual
browser pass skipped, on a Critical bug live in production. Both now build
their URL in a pure module — `framesByNarratorKey` in the FrameEditor's
existing `utils.ts`, `eventSubmissionActionUrl` in a new `EventSubmissions/urls.ts`
— spec'd in `tests/unit/admin-locale-urls.spec.ts`. This is the reviewer's
option 2; option 1 needs a browser this run has no dev server for.

Both builders return `null` without a locale, which also settles the third
thread: the same falsy `code` was handled three different ways, and the
EventSubmissions site interpolated it unguarded. `?locale=undefined` is
rewritten to the default locale by `sanitizeLocales`, so that path
reproduced the #701 403 silently. It now reports the failure instead.

Comment cleanups: the spec docblock's dangling `The` and its argument with
the sentence it replaced, and `relationshipDocLoader.ts`'s stale "a single
request per relationTo", which the batch-key comment below it contradicted.

Every new assertion confirmed failing first, at its own site: dropping the
locale from the frames key turns 4 red, dropping the guard from the
submission URL turns 1 red.

Gate: lint, typecheck, typecheck:tests, test:unit (125 files, 1601 tests).
Rebased onto main after #703 merged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Po2VWfKLXuT5TtZRysSDmk

---------

Co-authored-by: Claude <[email protected]>
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
…o the plugin

Addresses the eight review threads on #668. Three of them turned out to be
pointing at the same defect, and one of the fixes exposed a second.

**`?locale=all` was answered two different ways.** The translation from
`req.locale` (a request-supplied string that also carries `'all'`) to `RoleScope`
was written out at four call sites, and the fourth disagreed: EventSubmissions'
review endpoint resolved `'all'` to `'union'` — a role in ANY locale grants —
while collection access, global access and the Frames endpoint denied it. Same
request shape, opposite answer, decided by which file you were in.
`roleScopeFromLocale` is now the one statement of it, and it denies, matching
the three that agreed and the policy the PR body documents.

**Writing it once surfaced a privilege escalation the four copies had hidden.**
`RoleScope` has one non-locale member, so casting `req.locale` into it lets
`?locale=union` NAME the privileged scope: a manager would get their roles from
all 19 locales at once — precisely the over-grant #665 exists to remove. The
helper therefore returns a scope only for a configured locale. The assertion
covering this went red against the first version of the helper, which is how it
was found.

**The auth wiring moves from Managers.ts to the access plugin.** The strategy
and the three auth-response hooks are the plugin's mechanism, not the
collection's, so `withLocalizedRoleAuth` now attaches all four and accessPlugin
applies it. Managers.ts keeps a comment and no wiring. The predicate is the
pair that actually causes the bug — an auth collection whose `roles` field is
localized — rather than the slug `managers`, so `Clients` is skipped for a
stated reason and a future auth collection is not silently broken.

The three hooks stay three: `login`, `/me` and `/refresh-token` each re-read the
manager at a single locale, at different moments, and Payload exposes no single
point covering them. `localizedRolesAuth.ts` opens with the table of which
moment each one closes.

`LocalizedRoles` now derives its element type from `Manager['roles']`. Only the
per-locale keying is ours. Doing so caught that `Manager['roles']` and
`RoleSlug` are NOT the same set — `RoleSlug` includes client roles — so
`unionRoles` widened to accept both collections' shapes rather than pretending
they are one.

Also drops the nine-line comment on the `?locale=all` line, which the helper's
docblock now carries in one place instead of at every call site.

New: `tests/unit/localizedRolesAuth.spec.ts` covers the attach decision itself.
The wiring became a predicate rather than an explicit list, and a predicate that
stops matching takes the whole fix offline with nothing in this lane to notice.

Every new assertion was made to fail at the site that would really cause it:
`'all'`→`'union'` (2 red), predicate ignoring `localized` (1 red), attach
replacing rather than appending (1 red).

Gates: lint · typecheck · typecheck:tests · 115 files / 1523 unit — all green.
The integration lane needs PostgreSQL, which this environment has none of (#663);
CI runs it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q9dYn2dB8wsmyCBYURXM6K
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
Three admin components call the REST API with a hand-rolled fetch that
sends no `?locale=`. Payload resolves such a request at the default
locale, and every role gate then evaluates the manager's English roles.
Since #668 made roles genuinely per-locale, a manager whose roles live
only in another locale is denied on all three surfaces.

Confirmed on the reported record: managers/504's `roles` is
`{"fr":["path-editor","meditations-editor"]}` — no `en` key at all, so
`roles['en'] || []` is empty and `hasPermission` returns false.

- FrameEditor/hooks.ts — the locale joins the SWR key, so switching the
  admin locale refetches for free.
- ThumbnailCell — the loader is a module singleton, not a hook, so the
  locale threads through `load()` and the batch key becomes
  `relationTo:locale`. Two locales must not share a batch: the response
  is gated per locale, so merging them would answer one locale's cells
  from the other's request.
- EventSubmissionActions — both URLs carry it. DELETE is not
  locale-gated today, but consistency costs nothing.

Fixed on the client, not the server: the gates are deliberate and
documented, and Payload's own fetches already send the locale.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012noYdvt78W3aLKqJpDpEQY

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-668 — eae73ce5 Deployed Sep 1, 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

None yet

Development

Successfully merging this pull request may close these issues.

fix(access): resolve manager roles at every locale, not just English

3 participants