Skip to content

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

Merged
sydevs-bot merged 4 commits into
mainfrom
claude/fix-admin-locale-fetches
Sep 6, 2026
Merged

sydevs-bot merged 4 commits into
mainfrom
claude/fix-admin-locale-fetches

Conversation

@sydevs-bot

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

Copy link
Copy Markdown
Contributor

Summary

  • Three admin components called /api/* with a hand-rolled fetch that sent no ?locale=. Payload resolves such a request at the default locale, so every per-locale role gate read the manager's English roles — and denied anyone whose roles live only elsewhere.
  • All three now send useLocale().code. The fix is on the client: the gates are deliberate and documented, and Payload's own requests already send the locale.
  • The suite was green through this for a structural reason, now closed: nothing drove Payload's real REST pipeline as a manager with roles in a non-default locale.

The ticket's stop-gate is confirmed, not assumed. #701 says to abandon the diagnosis if the reported manager has English roles. GET /api/managers/504?locale=all&depth=0 answers "roles":{"fr":["path-editor","meditations-editor"]} — no en key at all, so roles['en'] || [] is [] and hasPermission returns false. That is the reported 403.

Changes

File Change
FrameEditor/utils.ts framesByNarratorKey(narratorId, locale) — the SWR key, or null with no locale
FrameEditor/hooks.ts useLocale(), and the key comes from that builder — so switching the admin locale refetches for free
ThumbnailCell/relationshipDocLoader.ts The loader is a module singleton, not a hook, so the locale threads through load() / FetchRelationshipDocs, and the batch key becomes relationTo:locale
ThumbnailCell/RelationshipThumbnailCell.tsx Reads useLocale().code, passes it down, and it is in the effect deps
EventSubmissions/urls.ts New. eventSubmissionActionUrl(id, action, locale) — both URLs, or null with no locale
EventSubmissions/EventSubmissionActions.tsx Uses that builder, and reports a failure rather than sending ?locale=undefined
tests/utils/restRequest.ts createRestClientAs(env, manager) for any manager; the caller takes a method and a JSON body
tests/int/frames-by-narrator.int.spec.ts Three REST cases for a French-only meditations-editor
tests/int/event-submissions-review.int.spec.ts New. The same three for an atlas-manager on POST /:id/review
tests/unit/admin-locale-urls.spec.ts New. What the two client-side builders build, and their refusal to build without a locale
tests/unit/relationshipDocLoader.spec.ts Locale forwarding, per-locale batching, and the default fetcher's URL
docs/rules/access.md, docs/rules/admin-ui.md, tests/AGENTS.md, tests/COVERAGE.md The rule, and the coverage rows

Two locales must not share a batch. The thumbnail response is gated per locale, so a relationTo-only key would answer one locale's cells from the other's request. That is a second, quieter bug the fix would otherwise have introduced, and it has its own spec.

The rule names a condition, not every fetch. docs/rules/access.md is the artefact #701 chose instead of a shared helper, so it is a deliverable rather than a comment. It governs a hand-rolled fetch whose target runs a per-locale hasPermission, and tables all six call sites — the three fixed here, the two gated on requireActiveManager that then read with overrideAccess: true, and useEnglishTranslation's deliberate ?locale=en. Without that condition a reader who greps fetch('/api/ finds four counter-examples and concludes the rule is approximate.

Why the suite was green

The handler-level specs build req by hand and hardcode locale: 'en'; event-submissions.int.spec.ts exercises applyReview directly and never touches the /review endpoint; the loader spec's own header called the real fetcher "not worth a unit test" — and that is precisely where the defect was. None of them can observe how req.locale is derived, which is the whole mechanism. The new specs drive handleEndpoints as a real French-only manager instead.

Test results

  • Lean gate: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (125 files, 1601 tests)
  • Touched integration specs: ✓ frames-by-narrator (14) + event-submissions-review (3)
  • Every spec using the refactored REST helper: ✓ 4 files, 26 tests — error-disclosure and error-disclosure-debug included, so the refactor is proven against its existing consumers
  • Build: N/A — Railway builds the preview

Every new assertion was confirmed failing first, at the site that causes it:

Defect reintroduced Goes red
Fixture roles { fr: … } → { en: … } All 6 REST cases, in both specs
locale dropped from the loader's qs object — the real #701 bug puts the locale in the request URL
Batch key collapsed to relationTo keeps two locales in separate batches
locale dropped from framesByNarratorKey 4 of the 9 admin-locale-urls cases
The null guard dropped from eventSubmissionActionUrl refuses to build a URL with no locale

Fixture pre-mortem. testData.createManager writes a per-locale roles object one locale at a time, so { fr: [...] } genuinely leaves roles.en empty — verified in tests/utils/testData.ts, and against the live shape of managers/504 above. anchorRegion must be a city or venue, so the review fixture anchors on a city under the managed country (prepareSubmission.ts:101 rejects a country with region_level_invalid).

Manual verification

All three call sites are now asserted — the loader's URL and the two client builders in the unit lane, both gated endpoints in the integration lane. What a browser would still add is that the wiring between them holds: that useLocale() supplies a code, and the admin actually renders these surfaces for a French-only manager.

  1. Create a manager with roles in French only, _verified. Log in — the admin opens in French.
  2. Meditations list → thumbnails render. Network: GET /api/images?…&locale=fr → 200.
  3. Meditation → Video → Insert → the frames grid renders. Network: GET /api/frames/by-narrator/<id>?locale=fr → 200.
  4. A pending submission in their region → Accept succeeds. Network: POST …/review?locale=fr → 200.
  5. Give the manager a second locale's roles, switch the admin locale — new requests fire under it, both surfaces render.
  6. As an admin in English: all three unchanged, requests carry ?locale=en.

Notes for reviewer

  • A missing locale now fails visibly, at all three sites. useLocale()'s context default is {}, so code is string to the compiler but can be undefined at runtime, and ?locale=undefined is rewritten to the default locale by sanitizeLocales — the fix(admin): send the active locale on hand-rolled admin REST fetches #701 403 again, with nothing for the manager to see. Both builders return null instead, and each caller refuses to act. That replaces three different treatments of the same falsy value.
  • useEnglishTranslation.ts is deliberately untouched. It sends ?locale=en on purpose — English reference text for translators — and is admin-only today. Per the ticket: if a manager role ever gains a translations-global grant, that read needs a different design (the English text, not the English roles).
  • Open question 2 answered as the ticket's default: skip. No static guard against a new locale-less fetch('/api/…') in src/components. A grep heuristic is brittle, and the rule's call-site table carries it. Worth revisiting if a fourth instance appears.
  • No server file changed. byNarrator.ts, review.ts and src/plugins/access/* are correct and were left alone, so no changed path matches securityReview.triggerPattern — /security-review is gated off, as it was on fix(ci): restore Railway preview URLs, fail closed when none is found #703.
  • Rebased onto main after fix(ci): restore Railway preview URLs, fail closed when none is found #703 merged, so CI here runs against the restored smoke lane.
Review round

An adversarial review raised four threads, all applied.

should-fix, docs/rules/access.md — the rule said "on every request" while four hand-rolled fetches legitimately do not send a locale. Now stated as a condition with a call-site table, and admin-ui.md's duplicate of the old claim defers to it.

should-fix, the two unasserted call sites — the review offered either running the ticket's browser steps or pinning what each site builds. Took the second: this run had no dev server. Both URLs move into pure modules with a unit spec.

consider, three treatments of a falsy code — resolved by making the guard uniform, as above.

consider, comment debris — a dangling The in the spec docblock, the docblock arguing with the sentence it replaced, and relationshipDocLoader.ts:65's stale "a single request per relationTo" contradicting the batch-key comment three lines below it.

Closes #701

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

🤖 Generated with Claude Code

https://claude.ai/code/session_01Po2VWfKLXuT5TtZRysSDmk

@railway-app

railway-app Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

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

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

@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

Holistic assessment. The diff is the size of the bug: three one-parameter call-site fixes, the locale threaded through the one loader that is a singleton rather than a hook, and no server file touched — the ticket's "fix on the client" decision is honoured exactly, with no helper invented for appending a query parameter and no refactor smuggled alongside. The per-locale batch key is the right catch: a relationTo-only key would have answered one locale's cells from the other's gated response, and it has its own spec. Two things keep it from being a clean pass. The written rule in docs/rules/access.md — which this ticket chose instead of a shared helper, so it is the deliverable — is broader than the code it describes, and four hand-rolled admin fetches contradict it on day one. And of the three call sites, only the loader's URL is asserted; the other two rest on inspection, with the manual browser pass skipped, on a Critical bug that is live in production.

Findings

  • should-fix — docs/rules/access.md:70: the rule says "on every request"; four hand-rolled fetches don't, three of them legitimately. Name the condition or the exceptions.
  • should-fix — src/components/admin/FrameEditor/hooks.ts:97: this site and EventSubmissionActions.tsx:86 carry the user-visible fix and are asserted nowhere; manual verification was skipped.
  • consider — src/components/admin/EventSubmissions/EventSubmissionActions.tsx:86: a falsy useLocale().code is handled three different ways across the three sites; here it degrades silently back to the default locale.
  • consider — tests/unit/relationshipDocLoader.spec.ts:7: dangling The, and the docblock argues with the comment it replaced.

What was checked

  • Ticket vs diff. #701's Resolved-decisions list, item by item, against git diff origin/main...FETCH_HEAD (12 files, +351/−58). Every prescribed change is present and nothing beyond them is: FrameEditor/hooks.ts builds the null key on narratorId && code as specified, relationshipDocLoader keys batches relationTo:locale, EventSubmissionActions appends to both URLs, both doc rules and both COVERAGE rows landed. No server file, no src/plugins/access/* — the security-review gate is correctly not triggered.
  • The stop-gate. Verified the diagnosis is stated as confirmed against managers/504 (roles.fr only, no en key), which is the condition #701 says to abandon on.
  • Consumer sides. mediaField.ts:45 is the only registrar of RelationshipThumbnailCell; relationshipDocLoader.load has no other caller; by-narrator appears in no other client. createRestClient's four existing consumers still compile — tsc --noEmit -p tsconfig.test.json passes clean on the branch.
  • The write path, not just the read gate. ?locale= now also chooses the locale applyReview writes under (review.ts:63 forwards req into payload.create/update). Checked Events for localized fields — title, description, images, website are all explicitly non-localized (Events.ts:176, :629) — so accepting a submission in French writes the same row it did in English. No finding; it would have been one.
  • Payload internals, read rather than assumed. sanitizeLocales (payload/dist/utilities/addLocalesToRequest.js) rewrites an unrecognised ?locale= to defaultLocale when fallback is on, which is what makes the guard asymmetry above silent rather than loud. useLocale's context default is {}, so code is not runtime-guaranteed.
  • The other hand-rolled fetches. Grepped fetch('/api across src/: four besides the three fixed. Read requireActiveManager and both endpoint handlers (setProject.ts, verifyEmbed.ts) to confirm none runs a per-locale hasPermission — they are safe, which is why the finding is about the rule's wording, not about a missed bug.
  • Ran. vitest run --project unit tests/unit/relationshipDocLoader.spec.ts → 9/9 green, including the new fetcher-URL and per-locale-batch cases. The integration lane needs Postgres and was not run here; CI covers it.
  • Reviewer profile read and applied (workflow/skills/adversarial-review/reviewer-profile.md). No finding raised on style, naming, or coverage volume.

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


Generated by Claude Code

Comment thread docs/rules/access.md Resolved
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
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
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
…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
@sydevs-bot
sydevs-bot force-pushed the claude/fix-admin-locale-fetches branch from a073d32 to 2b23712 Compare September 5, 2026 18:11
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-711 September 5, 2026 18:11 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Revised. All four review threads applied and resolved, and the branch is rebased onto main now that #703 has merged.

The two call sites that carried the user-visible fix with no assertion now build their URLs in pure modules — framesByNarratorKey and eventSubmissionActionUrl — pinned by tests/unit/admin-locale-urls.spec.ts. Both return null without a locale, so the third finding settles with them: ?locale=undefined resolves to the default locale server-side, which reproduced the #701 403 silently.

docs/rules/access.md now names the condition it governs and tables all six hand-rolled fetches on each side of it, instead of claiming "every request".

Gate green: lint, typecheck, typecheck:tests, test:unit (125 files, 1601 tests). Each new assertion confirmed failing first at its own site.

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


Generated by Claude Code

@Ardnived Ardnived removed the awaiting label Sep 6, 2026
@sydevs-bot
sydevs-bot merged commit bc936db into main Sep 6, 2026
8 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in SYDevelopers Technical Roadmap Sep 6, 2026
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
…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

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-711 — 2b23712d Deployed Sep 5, 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(admin): send the active locale on hand-rolled admin REST fetches

3 participants