Repository navigation
fix(admin): send the active locale on hand-rolled admin REST fetches - #711
Conversation
|
🚅 Deployed to the SahajCloud-pr-711 environment in sahajcloud
1 service not affected by this PR
|
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 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 andEventSubmissionActions.tsx:86carry the user-visible fix and are asserted nowhere; manual verification was skipped. - consider —
src/components/admin/EventSubmissions/EventSubmissionActions.tsx:86: a falsyuseLocale().codeis handled three different ways across the three sites; here it degrades silently back to the default locale. - consider —
tests/unit/relationshipDocLoader.spec.ts:7: danglingThe, 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.tsbuilds the null key onnarratorId && codeas specified,relationshipDocLoaderkeys batchesrelationTo:locale,EventSubmissionActionsappends to both URLs, both doc rules and both COVERAGE rows landed. No server file, nosrc/plugins/access/*— the security-review gate is correctly not triggered. - The stop-gate. Verified the diagnosis is stated as confirmed against
managers/504(roles.fronly, noenkey), which is the condition #701 says to abandon on. - Consumer sides.
mediaField.ts:45is the only registrar ofRelationshipThumbnailCell;relationshipDocLoader.loadhas no other caller;by-narratorappears in no other client.createRestClient's four existing consumers still compile —tsc --noEmit -p tsconfig.test.jsonpasses clean on the branch. - The write path, not just the read gate.
?locale=now also chooses the localeapplyReviewwrites under (review.ts:63forwardsreqintopayload.create/update). Checked Events for localized fields —title,description,images,websiteare 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=todefaultLocalewhenfallbackis on, which is what makes the guard asymmetry above silent rather than loud.useLocale's context default is{}, socodeis not runtime-guaranteed. - The other hand-rolled fetches. Grepped
fetch('/apiacrosssrc/: four besides the three fixed. ReadrequireActiveManagerand both endpoint handlers (setProject.ts,verifyEmbed.ts) to confirm none runs a per-localehasPermission— 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
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
a073d32 to
2b23712
Compare
|
Revised. All four review threads applied and resolved, and the branch is rebased onto The two call sites that carried the user-visible fix with no assertion now build their URLs in pure modules —
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 |
…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
Summary
/api/*with a hand-rolledfetchthat 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.useLocale().code. The fix is on the client: the gates are deliberate and documented, and Payload's own requests already send the 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=0answers"roles":{"fr":["path-editor","meditations-editor"]}— noenkey at all, soroles['en'] || []is[]andhasPermissionreturns false. That is the reported 403.Changes
FrameEditor/utils.tsframesByNarratorKey(narratorId, locale)— the SWR key, ornullwith no localeFrameEditor/hooks.tsuseLocale(), and the key comes from that builder — so switching the admin locale refetches for freeThumbnailCell/relationshipDocLoader.tsload()/FetchRelationshipDocs, and the batch key becomesrelationTo:localeThumbnailCell/RelationshipThumbnailCell.tsxuseLocale().code, passes it down, and it is in the effect depsEventSubmissions/urls.tseventSubmissionActionUrl(id, action, locale)— both URLs, ornullwith no localeEventSubmissions/EventSubmissionActions.tsx?locale=undefinedtests/utils/restRequest.tscreateRestClientAs(env, manager)for any manager; the caller takes a method and a JSON bodytests/int/frames-by-narrator.int.spec.tsmeditations-editortests/int/event-submissions-review.int.spec.tsatlas-manageronPOST /:id/reviewtests/unit/admin-locale-urls.spec.tstests/unit/relationshipDocLoader.spec.tsdocs/rules/access.md,docs/rules/admin-ui.md,tests/AGENTS.md,tests/COVERAGE.mdTwo 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.mdis 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-localehasPermission, and tables all six call sites — the three fixed here, the two gated onrequireActiveManagerthat then read withoverrideAccess: true, anduseEnglishTranslation's deliberate?locale=en. Without that condition a reader who grepsfetch('/api/finds four counter-examples and concludes the rule is approximate.Why the suite was green
The handler-level specs build
reqby hand and hardcodelocale: 'en';event-submissions.int.spec.tsexercisesapplyReviewdirectly and never touches the/reviewendpoint; 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 howreq.localeis derived, which is the whole mechanism. The new specs drivehandleEndpointsas a real French-only manager instead.Test results
pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(125 files, 1601 tests)frames-by-narrator(14) +event-submissions-review(3)error-disclosureanderror-disclosure-debugincluded, so the refactor is proven against its existing consumersEvery new assertion was confirmed failing first, at the site that causes it:
{ fr: … }→{ en: … }localedropped from the loader'sqsobject — the real #701 bugputs the locale in the request URLrelationTokeeps two locales in separate batcheslocaledropped fromframesByNarratorKeyadmin-locale-urlscasesnullguard dropped fromeventSubmissionActionUrlrefuses to build a URL with no localeFixture pre-mortem.
testData.createManagerwrites a per-locale roles object one locale at a time, so{ fr: [...] }genuinely leavesroles.enempty — verified intests/utils/testData.ts, and against the live shape ofmanagers/504above.anchorRegionmust be a city or venue, so the review fixture anchors on a city under the managed country (prepareSubmission.ts:101rejects a country withregion_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.rolesin French only,_verified. Log in — the admin opens in French.GET /api/images?…&locale=fr→ 200.GET /api/frames/by-narrator/<id>?locale=fr→ 200.POST …/review?locale=fr→ 200.?locale=en.Notes for reviewer
useLocale()'s context default is{}, socodeisstringto the compiler but can beundefinedat runtime, and?locale=undefinedis rewritten to the default locale bysanitizeLocales— 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 returnnullinstead, and each caller refuses to act. That replaces three different treatments of the same falsy value.useEnglishTranslation.tsis deliberately untouched. It sends?locale=enon 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).fetch('/api/…')insrc/components. A grep heuristic is brittle, and the rule's call-site table carries it. Worth revisiting if a fourth instance appears.byNarrator.ts,review.tsandsrc/plugins/access/*are correct and were left alone, so no changed path matchessecurityReview.triggerPattern—/security-reviewis gated off, as it was on fix(ci): restore Railway preview URLs, fail closed when none is found #703.mainafter 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, andadmin-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
Thein the spec docblock, the docblock arguing with the sentence it replaced, andrelationshipDocLoader.ts:65's stale "a single request perrelationTo" 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