Repository navigation
chore(sentry): tell a rejected API key apart from an anonymous read - #744
Conversation
The failure this prevents: a dead production integration reported for three months as background noise. A Firebase function in sydevs/WeMeditateApp presented a key matching no `clients` row on every consent decision, and SahajCloud captured all 3,855 denials at `warning` level, in the same Sentry group as ordinary anonymous 403s. Nothing in the report said a credential had been presented at all, so nobody could see there was an integration to fix. (#734) `authAttempt.ts` splits a failed request's `Authorization` header into the three cases the old report collapsed into one: no header anonymous ordinary traffic header + `req.user` set authenticated denied on access control header + no `req.user` rejected a broken integration, always Only the third changes behaviour. It captures at `error` rather than `warning`, and sets a Sentry fingerprint so it groups on its own. An anonymous 403 keeps today's level and default grouping, and a 500 keeps both too — the credential is not what is wrong with a server error, and re-grouping one under `credential-rejected` would bury a real incident. Attribution is a truncated SHA-256 of the key, the auth scheme, the collection slug, the User-Agent and `cf-connecting-ip` — never the key or any substring of it. The scheme comes from an allowlist rather than "the first word of the header", because a malformed header's first word can BE the credential. Grouping uses the collection, not the key fingerprint, so a spraying caller cannot open one Sentry issue per key it tries; the fingerprint is a tag, which segments within the group and stays searchable. No `clients` lookup: that would be a database read inside `afterError`, on every rejected 403. The same denial is mirrored to the application log at WARN, the shape `assertClientOriginAllowed` already uses, so it stays diagnosable from Railway without opening Sentry. `SentryContext` gained a `fingerprint` field and `withScope` now calls `setFingerprint`; without both, separate grouping cannot happen. Two specs, because a pure one is not enough here. `sentry-auth-attempt` covers the three outcomes and the leak rules. `sentry-credential-rejected` drives the plugin's own `afterError` hook, since nothing pure can see whether `setFingerprint` is ever reached — and it pins that the custom `context` function `payload.config.ts` passes does not drop the new field on its way through. Each assertion was watched failing against the real defect reintroduced at its own site: the unwired `setFingerprint`, the un-escalated level, the missing log mirror, the raw key in place of its hash, and the echoed scheme word. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BDJi6dsRTkPP1T9RGN2VL3
Review pass over the branch, in one commit because the two halves touch
the same lines.
The finding worth its own note: `authCollection` came straight out of
the request header, and reached the Sentry **fingerprint**. Unbounded,
`Authorization: <anything> API-Key x` would open one Sentry issue per
invented word — exactly the failure grouping-by-collection rather than
by key fingerprint exists to prevent. `classifyAuthAttempt` now takes an
`isKnownCollection` predicate, the hook answers it from
`req.payload.collections` (via `Object.hasOwn`, so a header naming
`toString` does not read as a collection), and an unrecognised word is
reported as no collection at all.
The rest is shape. Nothing auth-related is computed at all above 500 —
the classify call, both header reads and, on a 500 carrying a bad
header, a discarded SHA-256 were all running to be thrown away, on the
branch that arrives in bursts. The four `...(cond ? {} : {})` spreads
collapse into the single `if` the log mirror already needed, so the
whole rejection behaviour reads in one place. The log body spreads
`...rejected` instead of restating its three fields under new names.
Also: `parseAuthorization` guards the empty header once rather than
filtering the split array, and `KNOWN_SCHEMES` drops an `as const` whose
only purpose was to satisfy a cast in the one function whose job is
distrusting its input.
The two new assertions were watched failing with the validation removed.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BDJi6dsRTkPP1T9RGN2VL3
Found by the branch security review. The IP was going into a Sentry `extra`, which contradicts a control this repo states twice. `sentry.server.config.ts` sets `sendDefaultPii: false` under a comment that says the deployment never attaches PII to events, and `docs/rules/email.md` says copying personal data into a third-party error tracker widens where that data lives. An `extra` is opaque free-form context: neither that flag, nor the project's "Prevent Storing of IP Addresses" setting, nor any built-in scrubber can see it. It would have been retained for the full window with no way to turn it off but a redeploy — a durable IP log of identifiable third parties, from a service whose own config asserts it keeps none. Sentry's `user.ip_address` is the field all of those controls act on, so the IP goes there instead. The ticket's criterion — that the event carry the request IP — still holds, and the org keeps a kill switch it can use without shipping code. With no authenticated user the `user` object carries the IP alone, so an absent `id` still says nobody authenticated; the `auth_outcome` tag says it outright either way. Also records what the header is worth: a request reaching the Railway origin directly can set `cf-connecting-ip` to anything, so it is a lead, never identification. The key fingerprint is what names an integration. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BDJi6dsRTkPP1T9RGN2VL3
Three surfaces describe what changed, each for a different reader. `docs/architecture.md` gains a section beside the two existing `afterError` ones (#670, #684), since this is the third thing that hook now decides. It states the three outcomes, why only one of them moves, where the IP lands and why, and what the header is actually worth. `docs/rules/api-clients.md` gains the operator-facing half, under the authentication flow: what the log line looks like, and that searching Sentry by `key_fingerprint` finds every request from one credential. `tests/COVERAGE.md` gains the two new unit rows. All three carry the same warning, because it is the thing a reader will otherwise assume away: this sees only what Payload's error handler sees. A custom endpoint behind `requireActiveClient` returns its 403 rather than throwing, so fifteen handlers — the atlas SEO and sitemap endpoints among them — never reach the hook at all. Filed as #743. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BDJi6dsRTkPP1T9RGN2VL3
|
🚅 Deployed to the SahajCloud-pr-744 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 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
This matches #734: two source files, one pure helper, every criterion met by code I can point at. Nothing smuggled in. The blind spot it cannot cover is named in the PR and #743.
Two changes I would make: the new code is roughly half comment, and user/ip_address nests two conditionals where one does. On the IP — keep it, see inline.
Findings
- should-fix — comment volume ·
authAttempt.ts:12 - should-fix —
usernests two conditionals ·sentryPlugin.ts:223 - consider —
anonymous/authenticatedunused ·authAttempt.ts:19 - consider — any caller can force
error·sentryPlugin.ts:172 - consider — the IP path is unobserved ·
sentryPlugin.ts:236 - consider — a spec copies the config callback ·
…rejected.spec.ts:190
What was checked
Read #734, both specs and both source files whole at 330158e, against each criterion. payload.config.ts:281 spreads defaultContext, so the fingerprint survives. bypassPermissions.ts:45: a draft client authenticates first, so authenticated is right.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
| : undefined | ||
|
|
||
| const defaultContext: SentryContext = { | ||
| user: user && clientIp ? { ...user, ip_address: clientIp } : user, |
There was a problem hiding this comment.
Answering the question in your PR body: user.ip_address is the right home, for the reason you give — it is the one field sendDefaultPii: false and the org setting both act on. Keep it. But nothing covers it end to end. The manual run had ip: null, and the spec asserts our setUser call, not what the SDK does with an explicit ip_address under sendDefaultPii: false. One preview request through Cloudflare would close that.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Right on both halves, and I cannot close the second from here. This session has no Sentry access, so I cannot read back what the SDK did with an explicit ip_address under sendDefaultPii: false. Left open, and named in the PR body as a check only a reviewer with Sentry can make.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The #734 history now lives in docs/architecture.md and docs/rules/api-clients.md, both added by this PR. Three copies of the same reasoning drift apart. The imperative rules stay at the call site — never the key, allowlist the scheme, bound the slug, keep the IP on user.ip_address — and the narrative is one pointer away. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DxQ5LjMmKFh86tVYSHgVz2
clientIp is set only inside the rejected branch, which requires no req.user,
so the `{ ...user, ip_address }` arm could only ever spread `{}`. One
conditional says the same thing and does not invite the reader to work out
that the two are exclusive.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DxQ5LjMmKFh86tVYSHgVz2
A cookie-authenticated manager's 403 sends no Authorization header, so the old order filed it under `anonymous` — the one outcome it is not. Asking `hasUser` first makes the label match the caller. `rejected` is unchanged: it still needs a header and no user, so nothing production reads moves. The type doc now names who reads the other two, which the review asked for: only `rejected` changes the report, and the pair exists because telling them apart is the whole of #734. The new spec case was watched failing with the old order in place. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DxQ5LjMmKFh86tVYSHgVz2
…gerable A junk Authorization header raises any captured 400/403/404 to `error`. Grouping stays bounded, so this is quota and alert noise, not issue sprawl — but nothing said so, and the next reader hitting the quota would have dropped the level, which is the signal. Names the Sentry-side mute instead. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DxQ5LjMmKFh86tVYSHgVz2
It asserts against a hand-copied replica, not payload.config.ts's own inline callback, so dropping the spread there leaves this green. Importing the real file boots the whole config, which the unit lane will not do — so the fix is the honest claim, plus a pointer to the one line that stays hand-checked. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DxQ5LjMmKFh86tVYSHgVz2
|
5 of 6 review threads adopted, pushed as 67ce84c. Lean gate green: lint, both typechecks, 1694 unit tests. The Adopted
Left open — the IP path is unobserved. No Sentry access here, so nothing reads back what the SDK does with an explicit 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
No CI failure to fix. The red that dispatched this run was the dispatcher's own All 65 check runs on this head are I changed no code. Three 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
This draft has had no CI activity for hours and no session holds it. Comment or push to wake me. 🤖 sydevs dispatcher |
|
I could not mark ready here — the dispatch token is not allowed to. Everything else on this item is done, so this is the one step left for you. 🤖 sydevs dispatcher |
Review asked whether the file was over-engineered. It was: 126 lines and four functions for one decision. `parseAuthorization` returned a nullable intermediate shape that `classifyAuthAttempt` then re-mapped, and `namedScheme` was a one-line helper with one caller. Both are gone. `classifyAuthAttempt` now reads the header once and returns the outcome directly, in two branches — the `<slug> API-Key <key>` format, and everything else. 126 lines to 92, four functions to two. Behaviour is unchanged, and the 25 existing cases are the proof: the allowlisted scheme, the bounded slug, the lone-token header, the malformed `clients API-Key`, and the never-echo-the-key assertions all pass untouched. The three-outcome union stays. #734's acceptance criteria name all three and require unit coverage of each, so collapsing it to a nullable "rejected" would drop a criterion rather than simplify. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01L9VV3We4RLpQuk1SvzqnH3
|
Adopted the one thread:
Behaviour is unchanged, and the 25 existing cases passing untouched are the proof — the allowlisted scheme, the bounded slug, the lone-token header, and never echoing the key. Not taken: collapsing the three-outcome union. #734's criteria name all three and require unit coverage of each.
The 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
One conflict, in `tests/COVERAGE.md`: both sides appended a row to the same coverage table. Kept both — #744's two Sentry rows and this branch's Atlas seed row. `src/payload-types.ts` and `src/globals/AGENTS.md` auto-merged and were verified rather than trusted: `pnpm generate:types` reproduces the merged types byte for byte, and both sides' AGENTS.md paragraphs survive (#705's `stringsSchema` rename beside #706's Atlas tab list). No semantic conflict. `main` brought #756's `jsonField` helper, which rewrites `src/fields/translationsField.ts` — a file this branch never touched — and added no migration, so the branch's migration stays last in `src/migrations/index.ts`. Gate: lint, typecheck, typecheck:tests, 1757 unit tests in 132 files. Targeted: translations-globals, available-locales and the Atlas seed spec, 43 tests, against a real Payload and Postgres. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DEd12ZA8W99LeMM2ukWup1
Summary
Authorizationheader failed to authenticate is now captured aterror, in a Sentry group of its own, with the caller attributed.warninglevel and default grouping. A 500 keeps both too.Changes
src/plugins/sentry/authAttempt.ts— new. One function splits the header into the three outcomes, hashes the credential, and bounds what is safe to report.src/plugins/sentry/sentryPlugin.ts— classifies, escalates, fingerprints, mirrors to the log.SentryContextgainedfingerprint, andwithScopenow callssetFingerprint— without both, separate grouping cannot happen.Preview
https://sahajcloud-sahajcloud-pr-744.up.railway.app
Test results
pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(1696 passed)Manual verification
Ran against a local dev server on this branch, with a non-routable DSN so no events left the machine. Both requests to
/api/pages/1?depth=1&select[title]=true:credential presented and rejectedline.Authorization: clients API-Key <uuid>→ 403, and:4149fc018766issha256(<uuid>).slice(0,12), and grepping the whole server log for the key and each of its segments returned 0 hits. (ip: nullis correct locally — no Cloudflare edge.)Three checks need Sentry itself, and no automated check covers any of them:
key_fingerprinttag is searchable there.user.ip_addresssurvivessendDefaultPii: false. The spec asserts oursetUsercall, not what the SDK does with it, and the local run hadip: null. One request through the Cloudflare-fronted origin closes it. This is the one review thread left open.Notes for reviewer
One judgement call to check. The ticket's criterion 2 says the event carries the request IP.
sentry.server.config.tssetssendDefaultPii: falseanddocs/rules/email.mdsays not to widen where personal data lives — so the IP goes on Sentry'suser.ip_addressrather than anextra, which satisfies the criterion while leaving the org's Prevent Storing of IP Addresses setting able to turn it off without a redeploy. If you would rather ship no IP at all, say so and I will drop it — the key fingerprint is what actually names an integration, andcf-connecting-ipis spoofable on a request that skips Cloudflare anyway.Filed on the way: #743. This hook only sees what Payload's error handler sees. A custom endpoint behind
requireActiveClientreturns its 403 rather than throwing, so fifteen handlers — including/api/atlas/seoand/api/atlas/sitemap, the ones third-party integrations actually consume — never reach it. A rejected key there is as invisible as before. #734's own scope is this hook and stays correct; #743 is the other half.#734 stops no 403 and repairs no empty snapshot. Both remain in WeMeditateApp#401, which the loop cannot reach.
Review round 2 — the file was over-engineered (1 thread, adopted)
authAttempt.tsis one classify function (6a1483a).parseAuthorizationreturned a nullable intermediate shape thatclassifyAuthAttemptthen re-mapped, andnamedSchemewas a one-liner with a single caller. Both are gone: the header is read once and the outcome returned directly, in two branches — the<slug> API-Key <key>format, and everything else. 126 lines to 92, four functions to two.clients API-Key, and the never-echo-the-key assertions.main(8483cb7) is merged in.Review round 1 (5 of 6 threads adopted)
One behaviour change, one bug the review's own finding uncovered, three clean-ups:
hasUseris asked before the header (18e94e7). Reviewing "are theanonymous/authenticatedlabels load-bearing?" turned up that they were also wrong: a cookie-authenticated manager's 403 sends noAuthorizationheader, so it reported asanonymous.rejectedis unchanged — it still needs a header and no user — so nothing production reads moves. New spec case, watched failing.docs/architecture.md: a junk header raises any captured 400/403/404 toerror. Grouping stays bounded, so the cost is quota and alert noise. Mute it with a Sentry rule onauth_outcome, never by dropping the level.user/ip_addressis one conditional (25c7fcf). The old{ ...user, ip_address }arm could only ever spread{}.payload.config.ts:281dropping its spread stays hand-checked, and the ⚠ says so.Detail
Why the fingerprint groups by collection, not by key. Grouping on
key_fingerprintwould give each broken integration its own issue — but also one issue per key a spraying caller invents. Collection is bounded; the fingerprint rides along as a tag, which segments within the group and stays searchable. The collection is checked againstreq.payload.collectionswithObject.hasOwnfor the same reason: unchecked, it is a word out of the header reaching a grouping key.Why the scheme comes from an allowlist. A malformed header's first word can be the credential, so "report the first word as the scheme" is a leak. Anything outside
api-key/bearer/basic/digest/jwtreports asunknown, and a single-token header reports no scheme at all.Why two specs.
sentry-auth-attemptcovers the pure classification and the leak rules.sentry-credential-rejecteddrives the plugin's ownafterErrorhook, because nothing pure can see whethersetFingerprintis ever reached. It also pins that acontextcallback shaped like the real config's does not drop the new field — a replica, not the callback itself, since importingpayload.config.tsboots the whole config.payload.config.ts:281dropping its spread would leave that spec green, and its ⚠ says so.Every assertion was watched failing against the real defect reintroduced at its own site: the unwired
setFingerprint, the un-escalated level, the missing log mirror, the raw key in place of its hash, the echoed scheme word, the unvalidated collection slug, and the header-before-hasUserorder.Fixture pre-mortem.
buildRequestassumesreq.headersis aHeaders,req.payload.collectionsis keyed by slug, andcaptureErrorsis[400, 403, 404]. Checked againstsrc/payload.config.ts:279(the codes and thecontextcallback's shape),src/plugins/openapi/specFilter.ts(the<slug> API-Key <key>format) andsrc/lib/antiSpam/antiSpamGuard.ts:63(how the IP is read). The live dev-server run above confirms all three against a real request.Review findings not taken, each with its reason:
userAgent/ipunconditional on every captured error. That is a PII-posture change for the whole error stream, not this ticket's call.NEXT_PUBLIC_SENTRY_DSN, so a deployment without one gets neither the event nor the line. Every deployed environment sets it, the ticket prescribes this file, and moving it is a second behaviour. Recorded in a⚠at the call site instead.contextcallback inpayload.config.ts. The ticket namessentryPlugin.tsand the log mirror must survive a reshapingcontext.requestIp(req)helper. Now a second consumer alongsideantiSpamGuard, so it clears thesrc/lib/bar — but it means editing a file this ticket does not otherwise touch.auth_outcometag as a constant. It is constant on purpose:auth_outcome:rejectedis the one Sentry query that finds every such event across collections and statuses.rejectedlabels (18e94e7); round 2 removed the machinery around them instead (6a1483a).Closes #734
🤖 Generated with Claude Code
https://claude.ai/code/session_01L9VV3We4RLpQuk1SvzqnH3