Skip to content

chore(sentry): a rejected key on a custom endpoint is still invisible - #761

Merged
Ardnived merged 9 commits into
mainfrom
claude/chore-743-endpoint-guard-sentry
Sep 12, 2026
Merged

Ardnived merged 9 commits into
mainfrom
claude/chore-743-endpoint-guard-sentry

Conversation

@sydevs-bot

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

Copy link
Copy Markdown
Contributor

Summary

  • requireActiveClient now reports a presented-and-rejected API key itself, covering the fifteen custom endpoints whose returned 403 no error hook ever sees.
  • Both denial paths share one tag set, one fingerprint shape and one log message, so a rejected key is intended to group into one Sentry issue wherever it was denied. Unverified against Sentry itself — see Manual verification.
  • An anonymous denial, and an authenticated-but-unpublished client, stay silent. Only a refused credential is new signal.
  • Every rejection reports. An in-process dedupe window was added on review, then dropped on review: volume is routed by the Sentry-side rule on auth_outcome, which both paths already share.

Changes

  • src/plugins/sentry/credentialRejection.ts — new, 170 lines. Two exports: describeRejectedCredential builds the tags, fingerprint, IP and user agent for a rejected credential and writes the WARN mirror, and reportRejectedCredential sends the guard's own event.
  • src/plugins/sentry/sentryPlugin.ts — rewired onto that module. No behaviour change; chore(sentry): tell a rejected API key apart from an anonymous read #744's 25 assertions pass untouched.
  • src/lib/endpoints/requireActiveClient.ts — one call, before the 403 it already returned.

Preview

Railway builds it on each push.

Test results

  • Lean gate: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (1791 passed, 136 files), re-run after merging main
  • Targeted specs: 13 in tests/unit/endpoint-guard-credential-rejected.spec.ts; chore(sentry): tell a rejected API key apart from an anonymous read #744's sentry-credential-rejected (14) and sentry-auth-attempt (11) pass unchanged
  • Build: N/A — Railway builds the preview

Manual verification

Against a local dev server on this branch, from /api/atlas/seo — the endpoint the ticket names:

  1. curl -i -H "Authorization: clients API-Key 00000000-0000-0000-0000-000000000000" "http://localhost:3000/api/atlas/seo" → 403, and one WARN line API credential presented and rejected carrying source: 'requireActiveClient' and a 12-hex fingerprint.
  2. The same request with no Authorization header → 403 and no such line.
  3. Neither the line nor the captured payload contains any substring of the key sent.

I could not run these. This session has no dev server and no database, so the three are asserted in the unit lane instead — 1 and 2 through the real guard, 3 by stringifying every mock call and searching it for the key and two of its slices. A reviewer with a local server should still run them: the lane mocks @sentry/nextjs, so nothing here proves the SDK is reached in a real process.

Two checks need Sentry itself, both inherited from #744 and neither newly closed here: that a real rejected key on /api/atlas/seo groups with one denied on a Payload route, and that an explicit user.ip_address survives sendDefaultPii: false. docs/architecture.md states the first as intent rather than fact.

Notes for reviewer

One judgement call. The WARN message lost its sentryPlugin: prefix and gained a source field naming the path. One spelling means one Railway query finds every rejection; two prefixes would split it the way two fingerprints split a Sentry issue. This edits a line #744 has already approved — say the word and I will keep the prefix and drop source instead.

requireActiveManager is deliberately untouched. The ticket notes it sits beside the client guard with the same shape, but names only requireActiveClient in its criteria, and the admin surface's denials are a person's stale session far more often than a broken integration. It is a one-line call to the same helper whenever that changes. Recorded in docs/architecture.md rather than left for the next reader to wonder about.

The security review did not run. securityReview.triggerPattern matches neither src/lib/endpoints/ nor src/plugins/sentry/. Since the diff handles credentials anyway, I read it adversarially instead.

Detail

Why the shared module, rather than a second call site. The ticket's open question was where the reporting call belongs, given the guard is pure today and src/plugins/sentry/ owns every Sentry decision. Both stay true: the guard gains one call and no policy, and every Sentry decision — level, tags, fingerprint, message — still lives under src/plugins/sentry/. The alternative, calling classifyAuthAttempt from the guard and building the report there, satisfies the letter of "the classification is not duplicated" while duplicating everything around it. Two fingerprint arrays that agree today are two that can disagree after one edit, and the symptom is a Sentry issue silently split in half — the failure #734 exists to undo.

Why two exports and not five. detectRejectedCredential, rejectedCredentialTags, rejectedCredentialFingerprint and logRejectedCredential were always called together, in that order, by whichever path was reporting. They are one describeRejectedCredential(req, { status, source }) now, returning the context or null. It writes the WARN line itself rather than leaving that to the caller: one spelling of the message is what keeps one Railway query finding every rejection, and a caller that must remember to log is a caller that can forget.

Why no in-process dedupe. One was added for the amplification ceiling — these endpoints are public, and the edge allows 500 req/min per (client, IP) — and dropped again on review. It cost a Map, an expiry sweep, a wholesale clear against a caller-controlled key space, and a test-only reset, to do what a Sentry rule on auth_outcome does for both paths at once. The rule is external to this repo, so the ceiling is real; it is also the only mute that covers the throwing path, which never had a window.

Why captureMessage and not a synthetic Error. There is no exception. Throwing one to capture it would give Sentry a stack trace through our own guard, which names nothing about the caller, and the explicit fingerprint makes the grouping independent of it.

Why the guard is not DSN-gated. sentryPlugin returns the config untouched without NEXT_PUBLIC_SENTRY_DSN, so its WARN mirror vanishes with the DSN — a wart #744 recorded rather than fixed. The guard has no such wrapper, and Sentry.captureMessage is a no-op on an uninitialised SDK, so the log line survives a local run. That is what makes the ticket's verification checklist runnable at all.

Why reporting swallows its own failure, in two try blocks and not one. The caller is mid-denial. A throw would turn a correct 403 into a 500, and a logger that just failed cannot report its own failure. The WARN line keeps its own try inside describeRejectedCredential, so a broken transport does not take the Sentry event with it — the event is the half that survives a deploy nobody is tailing.

Every assertion was watched failing, against the real defect reintroduced at its own site:

Defect Red
The guard never calls the reporter (the ticket's own defect) 3
detectRejectedCredential returns facts for every outcome 4
The raw authorization header put in a Sentry extra 1
The IP in an extra instead of user.ip_address 1
The try/catch removed 1
The log sharing the capture's try 1
A per-caller log message instead of one string 1
The guard's own 403 changed to a 401 6
A dedupe window re-introduced in the reporter 5

Two assertions — "still denies the caller exactly as before" and the no-leak check — pass vacuously under the first defect, since nothing is written when nothing reports. Both are covered by a later round instead.

Fixture pre-mortem. buildRequest assumes req.user is read as { collection, _status }, req.headers is a Headers, and req.payload.collections is keyed by slug. Checked against src/lib/endpoints/requireActiveClient.ts (the only reader of the first), src/payload.config.ts, and src/plugins/openapi/specFilter.ts for the <slug> API-Key <key> format. The spec also drives the guard with { user: null } and no headers at all, which is the shape tests/unit/endpoint-helpers.spec.ts already passes it — that stub is why every read here is optional-chained.

Docs swept, not just the two obvious ones. docs/architecture.md and docs/rules/api-clients.md each carried a ⚠ pointing at #743, now replaced, and both record that there is no in-process dedupe and where the mute lives instead. docs/rules/endpoints.md gains the consequence its reader needs: hand-rolling the guard is now silent as well as inconsistent. tests/COVERAGE.md gains the new row. src/AGENTS.md's one-line mention of requireActiveClient needs nothing.

Closes #743

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

🤖 Generated with Claude Code

https://claude.ai/code/session_01BMVMoKUDAYRsh4unnz7H9K

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-761 September 10, 2026 05:23 Destroyed
@railway-app

railway-app Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

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

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

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 10, 2026
@sydevs-bot

sydevs-bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 16:53Z address-review · attempt 1 · session · done
  • 16:53Z address-review · attempt 1 · session
  • 16:36Z address-review · attempt 1 · session · done
  • 16:36Z address-review · attempt 1 · session
  • 16:22Z resolve-conflicts · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 10, 2026
@Ardnived
Ardnived added this pull request to stack #764 September 10, 2026 14:43
@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 10, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The session for this item did not finish after 3 attempts. I have stopped retrying. A comment, a verb, or a push from you starts me again.

🤖 sydevs dispatcher

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. awaiting and removed awaiting bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 10, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The session for this item did not finish after 3 attempts. I have stopped retrying. A comment, a verb, or a push from you starts me again.

🤖 sydevs dispatcher

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. awaiting and removed awaiting bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 10, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The session for this item did not finish after 3 attempts. I have stopped retrying. A comment, a verb, or a push from you starts me again.

🤖 sydevs dispatcher

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 11, 2026
`requireActiveClient` denies by RETURNING a 403 `Response`. Nothing throws,
so Payload's root `afterError` hook never runs and #734's rejected-credential
signal covered none of the fifteen handlers that short-circuit on this guard —
including `/api/atlas/seo` and `/api/atlas/sitemap`, the two third-party
integrations actually consume. A dead integration hammering them with a bad key
stayed exactly as invisible after #734 as before it.

The guard now reports its own denials, at the one seam all fifteen pass through.

`credentialRejection.ts` holds the facts both denial paths report, so the tag
names, the fingerprint shape and the log message have one definition. A second
copy would split one Sentry issue in two, which is the failure #734 exists to
undo. `sentryPlugin.ts` is rewired onto it with no behaviour change.

Two differences follow from denying rather than throwing. The guard captures a
message, since there is no exception to capture. And it is not gated on
`NEXT_PUBLIC_SENTRY_DSN` — `sentryPlugin` returns the config untouched without
one, so the hook's WARN mirror disappears with it, while the guard's line
survives a local run. Reporting never throws: a telemetry failure must not turn
a caller's 403 into a 500.

An anonymous denial and an authenticated-but-unpublished client stay silent.
Only a credential presented and refused is new signal.

Refs #743

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019a5Dg9YBnGht197YujmpPp
`docs/architecture.md` and `docs/rules/api-clients.md` each carried a ⚠ saying
the signal covered Payload's routes only and #743 tracked the rest. Both now
describe the guard's path instead, with the two differences that follow from
denying rather than throwing.

`docs/rules/endpoints.md` gains the consequence a new endpoint's author needs:
hand-rolling the guard is now silent as well as inconsistent.

The log line's shape changed — one message for both paths, plus a `source`
field. Two spellings would split the Railway query the way two fingerprints
split a Sentry issue.

Refs #743

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019a5Dg9YBnGht197YujmpPp
`reportRejectedCredential` took `{ status = 403 }` that no caller ever set:
the guard passes nothing, and `sentryPlugin` calls `logRejectedCredential`
directly with its own status. A knob with one value reads as though a second
status is coming.

Addresses a review thread on #761.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9CHn2zi6JiKNk9caJh8t9
The WARN mirror ran first inside the same `try` as the capture, so a
`logger.warn` that threw took the Sentry event with it — and the event is the
half that survives a deploy nobody is tailing. The log now has its own `try`,
which keeps the two independent.

The existing spec pinned only the 403 through that path, so the loss was
silent. The new assertion was watched failing against the shared `try`.

Addresses a review thread on #761.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9CHn2zi6JiKNk9caJh8t9
These endpoints are public and the edge allows 500 req/min per (client, IP),
so one stale integration could post ~720k `error` events a day. #734 accepted
that ceiling for a Payload route that throws; fifteen public endpoints is
wider, and the mute is a Sentry-side rule on `auth_outcome` that is external
to this repo and may not exist.

The capture is now deduped per key fingerprint, in a 60s per-process window,
which bounds the volume without dropping the level — the level is the signal.
The WARN line still goes out on every denial: it is cheap, needs no DSN, and
is the half a local run can see. The window's map is caller-controlled, so it
prunes expired entries at 1000 keys and clears wholesale if still full.

Four assertions, each watched failing against its own defect: the call
removed, the log deduped too, the window keyed on the collection, and a window
that never expires.

Addresses a review thread on #761.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9CHn2zi6JiKNk9caJh8t9
`architecture.md` asserted that both denial paths land in one Sentry issue.
Nobody has checked that against Sentry, and the paths capture differently —
`captureMessage` in the guard, `captureException` in the hook — so only the
explicit fingerprint is meant to make the difference irrelevant. Worded as the
intent it is, with what would confirm it.

Also records the capture dedupe in the three docs that describe the signal.

Addresses a review thread on #761.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M9CHn2zi6JiKNk9caJh8t9
@Ardnived
Ardnived force-pushed the claude/chore-743-endpoint-guard-sentry branch from 1fe3e2f to 0ebb108 Compare September 12, 2026 05:35
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-761 September 12, 2026 05:35 Destroyed
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 12, 2026
`main` moved five commits past this branch's base and `tests/COVERAGE.md`
conflicted: both sides appended a row to the same table. Kept both — the
`#743` guard row stays with the two Sentry rows above it, and #750's
translations-seed row follows.

Everything else merged clean. The overlap worth checking was
`src/lib/env/deploymentEnvironment.ts`, which `credentialRejection.ts`
imports: #763 only added `clientDeploymentEnvironment` beside it, so the
server-side read is untouched. `main` changed nothing under
`src/plugins/sentry/` or `src/lib/endpoints/`.

Lean gate green after the merge: lint, typecheck, typecheck:tests, and
1786 unit tests across 135 files.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WMc58cJat8rdZnpNWc4Fnp
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-761 September 12, 2026 16:26 Destroyed
@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 12, 2026
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 12, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

One thread, asked rather than guessed. Nothing pushed — no code changed.

  • The solution looks over-complicated — the reading is that we send an error we already have. We do not: requireActiveClient returns the 403, so nothing throws and no afterError hook ever sees it. The call itself is one line.

The new file is 95 code lines — 30 build the facts both denial paths share, 25 bound the event volume, 40 report. Two cuts are ready on your word: fold the four small exports into one, and drop the dedupe window if a Sentry-side mute on auth_outcome is preferred instead. The window was adopted last round, so I left the thread open rather than reverse it on a guess.

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


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. awaiting labels Sep 12, 2026
The review asked for a much simpler approach: report to Sentry with
context, and nothing else. So the per-fingerprint capture window goes —
with it the `Map`, the expiry sweep, the two constants and the test-only
reset — and every rejection reports again on both paths. The volume mute
is the Sentry-side rule on `auth_outcome` that #734 already named, which
is external to this repo but is also the one mute both paths share.

Five exported functions become two. `detectRejectedCredential`,
`rejectedCredentialTags`, `rejectedCredentialFingerprint` and
`logRejectedCredential` were always called together and in that order, so
they are one `describeRejectedCredential(req, { status, source })`
returning the tags, the fingerprint, the IP and the user agent — or null
when the credential is not what was wrong with the request. It writes the
WARN line itself, which is what keeps one spelling of the message across
both callers rather than trusting each to spell it. The guard still calls
`reportRejectedCredential`, unchanged at its call site.

The WARN line keeps its own `try`: a throwing logger must not cost the
Sentry event, and a spec pins that. The file drops from 257 lines to 170.

The dedupe spec block becomes one assertion that repeats are NOT
collapsed, watched failing against a re-introduced window — which also
turned four older assertions red, since a suppressed capture is invisible
to all of them.

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

Copy link
Copy Markdown
Contributor Author

One thread, adopted and resolved. Pushed b68d39d, with main merged in.

Every rejection reports again. Volume routes to the Sentry rule on auth_outcome, which both denial paths already share and which is the only mute the throwing path ever had. The four exports the error hook called in sequence are one describeRejectedCredential now, writing the WARN line itself so neither caller can spell the message differently. The guard's call site is unchanged.

Lean gate green after the merge: lint, both typechecks, 1791 unit tests. The one new assertion — repeats are not collapsed — was watched failing against a re-introduced window, which turned four older assertions red with it.

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


Generated by Claude Code

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

I could not merge 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

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-761 — b68d39df Deployed Sep 12, 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.

chore(sentry): a rejected key on a custom endpoint is still invisible

3 participants