Repository navigation
feat(web): security headers, and fix three confirmed vulnerabilities - #190
Merged
Merged
Conversation
The frontend had no response security headers at all — no CSP, HSTS,
X-Frame-Options, X-Content-Type-Options, Referrer-Policy or
Permissions-Policy, anywhere in next.config.ts, src/proxy.ts or infra/ —
for an internet-facing BFF holding sessions, org API keys, the operator
token and the Anthropic key. This adds them, and fixes three specific
vulnerabilities found while reading the surface they protect.
### Headers
The five uncontroversial ones are ENFORCED. The CSP ships REPORT-ONLY,
and the policy is the realistic one rather than the strict one on
purpose: a strict script-src needs a per-request nonce, and per Next 16's
own guide a nonce can only be injected into DYNAMICALLY rendered pages —
`/login` and `/reset` are prerendered. A nonce policy today would either
break them or force them dynamic. Starting report-only with
'unsafe-inline' for Next's own bootstrap means the reports are about
genuinely unexpected origins instead of drowning in our own inline tags.
Tightening script-src is the follow-up.
They go in next.config.ts rather than the proxy because `headers()`
applies to static responses too, and the proxy's matcher deliberately
excludes static assets.
/api/csp-report is the sink, because a report-only policy with nowhere
to report is just a header. It is unauthenticated and in PUBLIC_PATHS:
violations on the login page happen before a session exists, and those
are the ones most worth having. It is size-capped and never interpolates
the body anywhere.
### 1. Open redirect (confirmed exploitable)
`login/page.tsx` took `next` from the query string and passed it to
`router.push()`, checked only against `startsWith("/login")`. So
`/login?next=https://evil.example/phish` landed a freshly authenticated
user off-origin — the moment they are least likely to check the address
bar. This is not theoretical: reverting the fix makes the new Playwright
test fail, i.e. router.push really does navigate off-origin.
`safeNextPath` (src/lib/auth/redirect.ts) narrows the value to a
same-origin path, rejecting absolute URLs, protocol-relative `//host`,
the `/\host` backslash variant, non-http schemes and control characters,
with a resolved-origin comparison as the backstop.
### 2. CSV formula injection
Both download routes had their own copy of `csvCell`, each doing
RFC-4180 quoting and nothing else — so a golden-record value beginning
`=`, `+`, `-` or `@` was written through verbatim and a spreadsheet
evaluated it (`=HYPERLINK`, `=WEBSERVICE`, DDE on older Excel). Golden
records derive from tenant-uploaded source files, so the value is
reachable by anyone who can get a record into a corpus, and the person
opening the export is typically an admin on their own workstation.
Now one shared @/lib/bff/csv, so the next export route cannot
reintroduce it. Numeric literals are deliberately exempt from the
apostrophe prefix: blanket-prefixing `-` would corrupt every negative
number in every export for no security gain, and `Number()` still
rejects `-5+cmd|'…'`.
### 3. Unvalidated org slug
`org` was the one path parameter never encodeURIComponent-ed: ~46 tenant
routes and 4 admin routes interpolate it into `/v1/orgs/${org}/…`, and
`new URL()` collapses `..` segments, so a name containing them
re-points the upstream request with a privileged credential attached.
Membership lookup already made that unreachable for tenant users. The
gaps were requireOrgAccess's super-admin branch (which returns access
for ANY string) and the four admin routes, which authorize with
requireSuperAdmin and never call requireOrgAccess at all. A super admin
can already reach every org, so this is not privilege escalation — it
removes a traversal primitive behind the operator token and stops the
audit trail recording requests for orgs that cannot exist.
`requireOrgSlug` reuses the shape api/admin/orgs already enforces when
MINTING a name, and answers 404 so a malformed probe learns no more than
an unauthorized one. One guard, not 50 call sites.
### Tests
93 new unit cases (164 total, from 71) and 13 Playwright cases. The
functional ones assert at the HTTP boundary, since the thing worth
locking is the status the network actually returns: tenant isolation
answering 404 rather than 403, a viewer's writes refused 403 while their
reads still succeed, traversal-shaped org names refused, and both the
hostile and the legitimate `?next=` paths.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #187.
Why
The frontend had no response security headers at all — no CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy or Permissions-Policy, anywhere in
next.config.ts,src/proxy.tsorinfra/— for an internet-facing BFF holding sessions, org API keys, the operator token and the Anthropic key.This adds them, and fixes three specific vulnerabilities found while reading the surface they protect.
Headers
Five enforced. The CSP ships report-only, and the policy is the realistic one rather than the strict one deliberately: a strict
script-srcneeds a per-request nonce, and per Next 16's own guide (node_modules/next/dist/docs/01-app/02-guides/content-security-policy.md) a nonce can only be injected into dynamically rendered pages —/loginand/resetare prerendered. A nonce policy today would either break them or force them dynamic. Starting report-only with'unsafe-inline'for Next's own bootstrap means the reports are about genuinely unexpected origins instead of drowning in our own inline tags.They live in
next.config.tsrather than the proxy becauseheaders()applies to static responses too, and the proxy's matcher deliberately excludes static assets./api/csp-reportis the sink — a report-only policy with nowhere to report is just a header. Unauthenticated and inPUBLIC_PATHS, because violations on the login page happen before a session exists and those are the ones most worth having; size-capped, and the body is never interpolated anywhere.The three fixes
1. Open redirect — confirmed exploitable, not theoretical
login/page.tsx:38tooknextfrom the query string and passed it torouter.push(), checked only againststartsWith("/login"). So/login?next=https://evil.example/phishlanded a freshly authenticated user off-origin, at the moment they are least likely to check the address bar.I verified this is real rather than assuming: reverting the fix makes the new Playwright test fail, so
router.pushgenuinely does navigate off-origin in Next 16.safeNextPathrejects absolute URLs, protocol-relative//host, the/\hostbackslash variant, non-http schemes and control characters, with a resolved-origin comparison as the backstop.2. CSV formula injection
Both download routes had their own
csvCell, each doing RFC-4180 quoting and nothing else — so a golden-record value beginning=,+,-or@reached the file verbatim and a spreadsheet evaluated it (=HYPERLINK,=WEBSERVICE, DDE on older Excel). Golden records derive from tenant-uploaded source files, so the value is reachable by anyone who can get a record into a corpus, and the person opening the export is typically an admin on their own workstation.Now one shared
@/lib/bff/csv, so the next export route can't reintroduce it. Numeric literals are deliberately exempt from the apostrophe prefix — blanket-prefixing-would corrupt every negative number in every export for no security gain, andNumber()still rejects-5+cmd|'…'.3. Unvalidated org slug
orgwas the one path parameter neverencodeURIComponent-ed: ~46 tenant routes and 4 admin routes interpolate it into/v1/orgs/${org}/…, andnew URL()collapses..segments, so a name containing them re-points the upstream request with a privileged credential attached.Membership lookup already made that unreachable for tenant users. The gaps were
requireOrgAccess's super-admin branch, which returns access for any string, and the fourapi/admin/orgs/[org]/…routes, which authorize withrequireSuperAdminand never callrequireOrgAccessat all.A super admin can already reach every org, so this is not privilege escalation — it removes a traversal primitive behind the operator token and stops the audit trail recording requests for orgs that cannot exist.
requireOrgSlugreuses the shapeapi/admin/orgsalready enforces when minting a name, and answers 404 so a malformed probe learns no more than an unauthorized one.Tests
93 new unit cases (164 total, up from 71) and 13 Playwright cases.
The functional ones assert at the HTTP boundary, because what's worth locking is the status the network actually returns:
?next=paths, so the fix can't quietly break deep linksVerification
pnpm checkgreen: eslint, prettier, tsc, authz gate, 164 tests.next buildclean, with/loginand/resetstill static. All 13 new Playwright cases pass locally, and the CSP sink was observed receiving a real report.Three
grow.spec.tswizard specs fail on macOS, unchanged by this PR — they fail identically on pristine main and pass in CI's Linux container (#187 confirmed this).Follow-up
Tightening
script-srcto a nonce and promoting the CSP to enforcing, which needs/loginand/resetto become dynamic.🤖 Generated with Claude Code