Repository navigation
chore(sentry): a handler's own 5xx reaches no one - #1183
Conversation
A handler that answers a failure by returning a 5xx Response never throws, so neither Payload's root afterError hook nor Next's onRequestError sees it — and those two are the whole path a routed failure takes to Sentry. Nine such branches left nothing but a Railway log line: the Atlas event feed's own 500, the embed-report write, the project switcher, and every failure branch of the Cloudflare Stream webhook. #743 closed this seam for a returned 403; this is the 5xx half it named and never filed. Each branch replaces its logger.error with one capture() carrying the same fields, so the line Railway gets is unchanged and no site gains a second one. Two tags identify them: capture_source=handler, and handler naming which. Every 4xx is left alone — a caller's mistake is not an incident (#670). The two "not configured" 503s follow the rule the jobs already use: warning outside production, error in production. Closes #1182 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjVAPknru64YdYduxD3
`readFailureResponse` (`src/lib/endpoints/errorResponse.ts`) already was the one definition of "a read threw: log it, answer 500", and its six branches across the four /api/atlas/* endpoints reported nothing — the same defect #1182 names, in the shared helper rather than a handler. The capture goes inside it, so every caller gets the signal and a new one is covered by construction. `requireIntegerClientId` beside it the same way: its 500 means a client is about to be told it owns nothing. `handlerTags` now owns the tag pair, beside `capture`. geojson answers through the shared helper instead of re-spelling the log-and-500 itself, which moves its cast-error mapping ahead of the APIError arm — no APIError the query gates throw carries a `cause`, so neither arm can take the other's. setProject keeps its own call: it is a write, and surfacing an APIError's own status would change what the caller is told. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjVAPknru64YdYduxD3
|
🚅 Deployed to the SahajCloud-pr-1183 environment in sahajcloud
1 service not affected by this PR
|
sydevs-bot
left a comment
There was a problem hiding this comment.
1 question for the reviewer, one per thread.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The shape is right, and the joined finding was correct: readFailureResponse already owned "a read threw: log it, answer 500", so the capture belongs there and covers six branches with no edit of their own. capture mirrors to the same logger and never throws.
What the diff does not do is finish the sweep. Six more branches answer a 5xx and report nothing, four inside the ticket's own scope — including a production Turnstile test key and a hand-rolled copy of readFailureResponse. The new AGENTS.md section states the population as closed, which is the argument this PR used to justify joining the helper.
No contract surface moves.
Findings
- should-fix — six returned-5xx branches still silent; the new doc claims otherwise (
src/plugins/sentry/AGENTS.md:29) - consider —
capture_source's value set now lives in two files, bound only by prose (src/plugins/sentry/captureFailure.ts:33) - consider — each site names itself twice, and
handlertrails an object literal (src/lib/endpoints/errorResponse.ts:34)
What was checked
Read whole on the branch: errorResponse.ts, capture.ts, captureFailure.ts, cloudflareStreamWebhook.ts, geojson.ts, plus the four files behind the finding.
Ladder: handlerTags has four callers and no existing owner — held. configGap returns an error class, not a CaptureLevel, so not sharing it holds.
geojson.ts's reorder is safe: findPostgresError walks only cause and needs a string code, and every gate throw in src/plugins/usage/hooks.ts is a bare new APIError(msg, 4xx).
All ten ticket branches are covered, every 4xx stays silent, and the new spec has a case per branch plus "capture throws, status unchanged". Both preview links are ON_HOST, pages/1014001 is contentIds.welcome, and every path the body names exists.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
`readFailureResponse` took `handler` as a fifth positional argument, trailing an object literal, so each call site spelled its own identity twice in two vocabularies — `msg: 'atlasSeo: read failed'` beside `'atlas/seo'` — and a wrong slot was easy to pass. It rides in the bag that already carries the context instead. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW7yRyB4yPfTbWZbtF
The tag's values lived in two files — `CaptureSource` in the classifier and a bare `'handler'` literal in `handlerTags` — bound by prose alone, so a typo in either would split one Sentry issue in two. `CaptureSourceTag` declares the set where the tag is written, and `CaptureSource` is now the subset the classifier accepts. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW7yRyB4yPfTbWZbtF
The sweep stopped at the branches the ticket enumerated, and the new AGENTS.md section then claimed the population closed while six more answered a 5xx and reported nothing — four of them inside the ticket's own scope, including a production Turnstile test key and a hand-rolled copy of `readFailureResponse`. `users/block`, the three `atlas/challenge` 503s, `transcripts/request` and the R2 static handler now report under their own `handler` tag. All of them at `error`: `.env` is tracked and carries Cloudflare's test pair, so a missing `TURNSTILE_SITE_KEY` is an incident anywhere, unlike the Stream webhook's secret that dev deliberately leaves unset. Two keep their own answer, and the section says why: the transcript request needs its `ValidationError` arm ahead of the `APIError` one and can carry `Retry-After`, and the R2 handler holds no `req`, so it keeps its `storageLogger` line and passes `capture` no mirror. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW7yRyB4yPfTbWZbtF
|
All three adversarial-review findings built, on a clean merge of
#1182 gained a criterion for the six. Lean gate green on 3745 unit tests; Still open: the 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
A failure answers its caller, writes a log line and sends a Sentry event. The log line and the event now have one owner between them: `reportHandlerFailure` (`src/plugins/sentry/handlerFailure.ts`), the sibling of `captureFailure` for a failure a handler answers by **returning** a response. All twelve sites call it; none reaches `capture` directly any more. What that buys is the policy. "A 5xx is an incident, a 4xx is a caller's mistake" (#670) was a paragraph each of the twelve restated, and each was free to get it wrong. It is now one comparison the seam runs on the status the site is about to answer with — so the rule is executable instead of prose, and a site that starts routing a 4xx through here reports nothing without anyone remembering to say so. `tests/unit/handler-5xx-capture.spec.ts` pins that directly. Two consequences worth naming. A 5xx carrying no exception is reported at `error`, where `capture` alone calls such a report a `warning` — which is why eight sites were spelling `level: 'error'` by hand. And an `APIError` that carries a 500 of its own is now reported: `readFailureResponse` matched on the error class and let it through. The response stays the caller's, because the four shapes answer four different consumers — the JSON envelope an API client parses, the HTML document the Atlas widget's frame renders, the plain text R2 delivery serves, and the `{ status, body }` Cloudflare decides whether to retry on. `readFailureResponse` fuses report and answer for the one composition that recurs, and `atlas/challenge`'s three 503s fold into one local `unavailable` so the page reads as three one-line refusals. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjVPfyUFfSdkzCwdVHB
Two tightenings the branch-level security sweep turned up, neither a finding against the seam itself. `readFailureResponse` surfaced an `APIError`'s message whatever its status. Payload marks a 500 `APIError` `isPublic: false` and its own `routeError` withholds the message for exactly that reason, so the helper was the one door handing an API client a driver's text that nothing else in the app discloses. A 4xx still speaks for itself — a gate refusing a caller's query is what that arm is for — and a 5xx now answers `failure`, whatever threw it. Found because the seam made the 5xx arm reachable at all: it used to return before the report, so nothing looked at what it answered with. `HandlerFailure.report` is `true` rather than `boolean`. It exists so a 2xx hiding an upstream failure can report anyway; written the other way round, `report: false` would silence a real 500, and the type is what stops anyone writing one. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjVPfyUFfSdkzCwdVHB
|
Pushed 9a97e63. Four threads answered — all four left open for you to settle.
The security sweep found nothing and raised two things, both built: a 5xx #1182 gained two criteria. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
Approved, but this thread still waits on you, and the ruleset will not merge until it is resolved: #1183 (comment). Reply there, or resolve it. 🤖 sydevs dispatcher |
|
One thread settled. No new commits.
Every other thread is resolved, and neither of your last two reviews carried a body. That leaves no open thread on this PR. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
afterErrornoronRequestErrorever runs.readFailureResponseis the repo's shared "a read threw: log it, answer 500", and it was silent too — six more branches across the four/api/atlas/*endpoints. The capture went inside it, so the ticket's premise undercounted its own population.reportHandlerFailure, which owns the log line and the Sentry event together and decides from the status whether there is an incident at all. The rule "a 5xx reports, a 4xx does not" was a paragraph twelve sites each restated.Change outline
The seam — three streams, and one owner for two of them
reportHandlerFailure(src/plugins/sentry/handlerFailure.ts) is the one report behind every failure a handler returns, the sibling ofcaptureFailurefor one that was thrown. The status the site is about to answer with is the policy, not a label on the report:Each site then answers in its own shape, and there are four, for four consumers — which is where one handler stops being honest:
{ errors: [{ message }] }/api/atlas/*branch, geojson,clients/report,managers/set-project,users/block,transcripts/requestatlas/challenger2/static{ status, body }Folding those in would have each site hand the seam a body builder plus the status it had already given. So a site reports in one statement and answers in the next, and
readFailureResponsefuses the two for the one composition that recurs.Flow — how a returned 5xx reaches Sentry
The ticket's three endpoint sites, each one
logger.errorreplaced by one report:The seam the joined finding moves, which covers geojson and the six atlas branches at once:
readFailureResponse(req, error, failure, { handler, msg, ...extra }) src/lib/endpoints/errorResponse.ts - error instanceof APIError → errorResponse(error.message, error.status) # any status, silent + APIError, status < 500 → errorResponse(error.message, error.status) # the caller's own + anything else → errorResponse(failure, 500) # a 5xx keeps its words - logger.error({ ...log, error: error.message }) + reportHandlerFailure({ error, message: msg, extra, handler, logger, status }) # the status decides callers now naming themselves atlasSeo 'atlas/seo' atlasSitemap 'atlas/sitemap' # + requireIntegerClientId atlasWixRoute 'atlas/wix/route' atlasWixSitemap 'atlas/wix/sitemap' # + requireIntegerClientId + eventsGeoJson 'events/geojson' # was its own log-and-500The webhook, where seven branches share one handler name and answer
{ status, body }:handleStreamWebhook({ rawBody, secret, accountId, apiKey, logger, onReady }) !secret → 503 configGapLevel() # warning off-prod, error in prod verifySignature fails → 400 / 401 # silent: the caller's mistake payload fails the schema → 400 # silent status.state === 'error' → 200 error # the upload is unplayable !accountId || !apiKey → 503 configGapLevel() downloads success: false → 500 error onReady rejected → 200 error # ready, and never transcribed ZodError / threw → 500 errorThe six the adversarial review added, each one
logger.errorreplaced by one report:Behaviour — what decides the level
Preview
The reporting itself is invisible from a browser: every branch here needs a failed read, a missing credential or a signed webhook, and the
/api/atlas/*and geojson routes need a client API key. What a reviewer can exercise is the one success path the refactor touched, through the admin's own UI:POST /api/managers/set-project, whose catch block this PR rewrote. Switching project still works, and still answers{ ok: true, currentProject }.ProjectContext).Both links open on data: every preview loads
src/fixture/into itself at boot, and1014001is that fixture's pinned Welcome page (src/fixture/content-ids.ts). This session holds neitherPREVIEW_ACCESS_CLIENT_IDnorPREVIEW_ACCESS_CLIENT_SECRET, so it could not open them through Cloudflare Access to confirm.The failure branches are covered by
tests/unit/handler-5xx-capture.spec.ts, which drives each one through its own handler and asserts exactly one Sentry event per branch and none for any 4xx.Test results
mainmerged in (test(openapi): check OpenAPI coverage of root endpoints, globals and route handlers #1175, and chore(seeds): retire the one-shot importers and the atlas sync #1171 earlier, which deleted the retired seed lane's specs)atlas-challenge,block-user,events-geojson,set-project-endpoint,meditation-transcription,file-transcripts— 121 passed;atlas-seo,atlas-sitemap,atlas-wix— 104 passed, for thereadFailureResponsechangetests/unit/handler-5xx-capture.spec.ts, now 39 cases. Every "reports X" case was watched failing against the unfixed source first. The four new policy cases were watched failing with the status comparison forced open (the 4xx and 2xx silence cases went red) and with theerrordefault dropped (eight went red); the non-disclosure case was watched failing with thestatus < 500guard removedManual verification
handlergroup. No branch here is reachable from a preview, and chore(sentry): a rejected key on a custom endpoint is still invisible #743's own note says the same thing about its 403 path: the fingerprint and tag shape are unverified against Sentry itself. The cheapest check isatlas/sitemap— point a client key at/api/atlas/sitemapon an environment where the region read can be made to fail.Notes for reviewer
The adversarial review's should-fix is built, and it is the second reason this PR outgrew the ticket. Six answered a 5xx and reported nothing after the first pass, four inside the ticket's own scope — so the
AGENTS.mdsection was asserting a closed population that was not closed. #1182 gained a criterion naming them.The joined finding is why this PR is larger than the ticket. Two of the four review lenses found it independently: the ticket enumerated nine hand-rolled branches and missed the shared helper six more sit behind. Leaving it would have made the new
AGENTS.mdsection assert a blind spot was closed while/api/atlas/seostill reported nothing — harder to find later, not easier.One deliberate change to a log line.
captureputs the error onerr(the object, so the line keeps its stack) where these sites hand-wroteerror: error.message. Every other field is unchanged, and no site gains a second line — pinned by the "and only one" cases.The
setProjectquestion is answered, and the answer is neither letter. The seam splits the two halves the question was weighing: the report is one spelling for all twelve sites, and the answer stays this write's own, becausepayload.updatethrows aValidationErrorwhose message carries localised field labels and the helper would surface that as the caller's 400.One pre-existing disclosure closed on the way.
readFailureResponsesurfaced anAPIError's own message whatever its status. Payload marks a 500APIErrorisPublic: falseand its ownrouteErrorwithholds the message for that reason, so this helper was the one door handing an API client a driver's text. A 4xx still speaks for itself; a 5xx answersfailure. It was invisible until the seam made that arm reachable — it used to return before the report, so nothing looked at what it answered with.What is left for you on three threads. The consolidation stops at the response, and the open threads say why in each place: the challenge page's body is an HTML document the widget's frame renders, not an envelope an API client parses. If you want the answer folded in behind a body builder too, say so on the thread and it is one commit.
One reordering, settled.
geojson's cast-error mapping now runs before theAPIErrorarm, because the helper owns that arm. Checked every gate throw site (src/plugins/usage/hooks.ts): each is a freshnew APIError(msg, 4xx)with nocause, andfindPostgresErrorwalks only thecausechain, so neither arm can take the other's.Detail
Dismissed review findings, with reasons.
captureFailureand give it a fifthCaptureSource(the ticket's own Approach). Declined, and the altitude lens agreed.captureFailurederives level, user, ip, fingerprint and extras from aPayloadRequestand a source; these sites bring a literal message, extras, level and logger, and the webhook's seven hold no request at all. It would have neededmessage,extraandloggeroptions — four of its six inputs pass-through — and the classifier would stop classifying. The one thing it adds that these sites want is itsmapPostgresCastErrorexclusion, and the only branch where a caller's value reaches a Postgres cast is the geojson feed, which calls that mapper itself and answers 400 before reaching the report.CaptureSource's JSDoc now names the fifth tag value and points atreportHandlerFailure.credentialRejection.ts-shaped seam. Declined. That module exists because two paths must produce one identical fingerprint or Sentry splits the issue. There is no second path here and no shared fingerprint — these sites deliberately differ in message, extras and level, so the seam would be acapturecall with indirection.buildConfigtime and report any returned 5xx automatically. Declined; the lens that raised it did not recommend it either. A generic wrapper sees only aResponse, so its issue is titled by the client-facing message, with no exception, no stack and no extras — which is the deficiency thehandlertag exists to fix. It also cannot reach the Next route the webhook lives behind.configGapLevel()withTranscribeRecording'sconfigGap(). Declined. One policy, two mechanisms: the job picks an error class (ExpectedJobFailure, whichjobCapturemaps), the webhook aCaptureLevel. A shareddeploymentGapLevel()would serve one of them. Both citeisProductionDeployment(), which is the single definition that matters.tests/unit/constant-time-equal.spec.tsstops loading the Sentry SDK. Declined. Measured at +350–450 ms on a 35-line spec, inside a 12 s Tier-1 budget and a 66 s lane, against a new file for three functions.vi.resetModules()+ dynamic import tobeforeAll. Declined as unrelated churn. Measured at ~0.5 s; no case there varies the environment, so it is a real win, butafterEachrestoresprocess.envand the refactor is fiddlier than the gain.Applied from the adversarial review. All three findings built. The should-fix is above.
CaptureSourceTag(src/plugins/sentry/capture.ts) now declares thecapture_sourcevocabulary where the tag is written, andCaptureSourceisExclude<CaptureSourceTag, 'handler'>— one declaration, so a typo cannot split a Sentry issue.readFailureResponselost its fifth positional argument:handlerrides in the bag that already carriesmsg, so each site names itself once.Applied from the pre-PR review. The tag pair was folded out of four hand-spelled copies, and now lives inside the seam.
level: 'error'dropped where an exception is passed —capturealready defaults to it, and no pre-existing site spells it. The four repeated "why" comments cut to one line each, with the story insrc/plugins/sentry/AGENTS.md.errorResponseused in place of three hand-built refusal envelopes. The shared signature fixture moved tonode:crypto's one-liner and became synchronous, andtests/utils/streamWebhook.tsnow holds the secret, the frozen clock, the ready payload and the fetch stub both specs were spelling twice — the fetch stub builds a freshResponseper call, because a captured one reads empty on the second test to reach it.vi.resetAllMocksin place ofclearAllMocks, which kept the throwing implementations for every later case.Security review on this review round's commits: no findings. The trigger paths matched again (
src/collections/(Clients|Managers|Users)/endpoints/,src/plugins/storage/,webhook), so the sweep ran over the conversion. It enumerated every converted site with the status it passes and confirmed none passes a status under 500 withoutreport: true— so nothing that used to report is silenced, and no 4xx reports. It confirmed every response body, status and header is byte-identical, that noextra, message or tag gained a credential or a site key, and that the challenge page's gate order is unchanged with both 403 refusals still silent. The two things it raised are built, above and in the type:reportistruerather thanboolean, so the escape hatch cannot run backwards, and the 5xxAPIErrormessage is withheld.Security review on the review's own six: no findings. The trigger paths matched again (
src/collections/Users/endpoints/,src/plugins/storage/), so the sweep ran over the three newextrapayloads.users/blocksends{ userId }, an integer — not the acting admin's address, which the log line never carried either;transcripts/requestsends{ source }, arelationTo/id pair;atlas/challengesends no extras, and neither 503 message carries the site key. The R2 handler sends{ key }, which is the same value itsstorageLoggerline already carried, and R2 delivery is public and unsigned — so the key is a path to a public media object, andimports(the one R2-gated collection carrying PII) stores no object at all (disableLocalStorage). No gate moved, and all four response envelopes are byte-identical.Security review of the first pass: no findings. The trigger paths matched (
src/collections/(Clients|Managers)/,src/plugins/storage/,webhook), so the branch-level sweep ran. It ruled out credential leakage through the new reports —captureforwards onlyerror,message,extra,tags,fingerprint,level,user/ip, and no newextracarries a secret; the webhook captures neither itssecret, itsapiKeynor the signature, andsendDefaultPii: falsekeepsAuthorizationout of the HTTP integration. It confirmed the three response envelopes are byte-identical and that no auth gate moved.Fixture pre-mortem. The new spec's request stubs assume:
req.userread as{ collection, enabled }/{ collection, type }(checked againstsrc/lib/endpoints/requireActiveClient.tsandrequireActiveManager.ts);getPgPoolreadingreq.payload.db.pool(checked againstsrc/plugins/usage/db.ts); the origin check comparingOrigintositeHosts(site.domain)(checked againstsrc/plugins/usage/hooks.tsandsrc/lib/clients/site.ts);parseBodyreadingreq.json()(checked againstsrc/lib/endpoints/parseBody.ts); and the cast-error fixture carrying SQLSTATE22P02oncause, wherefindPostgresErrorreads it (checked againstsrc/lib/databaseErrors/index.ts— the first version of that fixture answered 500 because it had nomessageon the cause).Fixture pre-mortem, the review's six.
blockUserbuilds its system request withcreateLocalReq, which readsconfig.i18n.fallbackLanguageandconfig.i18n.supportedLanguages[lang]and thenconfig.localization(checked againstpayload/dist/utilities/createLocalReq.jsand@payloadcms/translations'sinitI18n), so the stub config carries a minimalen. The challenge cases re-import the endpoint aftervi.stubEnv, becauseserverEnvparses once at import — the lane sets noTURNSTILE_SITE_KEY, which is why the missing-key case needs no stub at all.requestTranscript's stub letsfindanswer no rows anddeleteanswer no errors, socreateis the throw (checked againstsrc/lib/transcripts/read.tsandsync.ts). The R2 case drives the real adapter with anS3Clientwhosesendrejects, astests/unit/r2-adapter-keys.spec.tsdoes.Docs.
src/plugins/sentry/AGENTS.mdgets the seam, beside the #743 paragraph that explains the mechanism, and says which helper covers what, where the status policy lives, and why the response stayed out.src/AGENTS.md's "every server report goes through one body" paragraph now names both layers above that body rather than one.docs/rules/endpoints.mdgets the rule a new endpoint owes.docs/rules/routes.md's worked example no longer calls the webhook processor "pure helpers", since it now reports for itself.Closes #1182
Generated by Claude Code