Files
supabase/apps/www/lib/security-headers.test.ts
Etienne StalmansandClaude Opus 5.5 08388eecd6 feat: update headers on www (#43442)
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## Problem

www sends no `Content-Security-Policy`, `X-Frame-Options`,
`X-Content-Type-Options`, or `Referrer-Policy` headers on its pages.
Only HSTS is set.

The first version of this PR added these headers on `/(.*)`. That turned
out to be unsafe, because www is the zone router: `lib/rewrites.js`
proxies Studio (`/dashboard`), docs, the UI library, the design system,
the knowledge base, and other apps, and the header rules in
`next.config.mjs` also apply to those proxied responses. A CSP there
would add a second enforced policy on top of each app's own headers, and
`X-Frame-Options: DENY` would break the UI library previews, which
iframe `/library/example/*`.

## Solution

The headers are built in `apps/www/lib/security-headers.js` and spread
into `headers()` in `next.config.mjs`.

**Scope**
- The rules apply only to paths that www serves itself. The proxied path
prefixes come from `lib/rewrites.js`, so a new zone rewrite is excluded
automatically.
- On those paths: `X-Frame-Options: SAMEORIGIN`,
`X-Content-Type-Options: nosniff`, `Referrer-Policy:
strict-origin-when-cross-origin`, and an enforced CSP.

**CSP (script-focused)**
- `script-src` allows `'self'`, `'unsafe-inline'`, and an explicit list
of the third-party script hosts that www pages load: GTM through Stape,
PostHog, Usercentrics, tweet embeds, HubSpot, hCaptcha, Default.com, Buy
with AWS, and a path-scoped jsDelivr entry for unicornstudio. Each entry
has a comment that names its user.
- `'unsafe-inline'` stays, because the Next.js inline scripts need a
nonce otherwise, and a nonce needs dynamic rendering.
- `object-src 'none'`, `base-uri 'self'`, `form-action 'self'`,
`frame-ancestors 'self'`.
- Removed from the earlier version: `unpkg.com` (only used inside a blog
code block, and anyone can publish scripts there), `*.vercel.app` (any
Vercel app), `frontend-assets.supabase.com` (www serves its assets from
the same origin), and the duplicate `script-src-elem`.

**`'unsafe-eval'`**
- Off by default.
- Allowed only on the pages that evaluate MDX on the client with
`next-mdx-remote-client`: `/changelog`, `/customers/[slug]`,
`/events/[slug]`, `/alternatives/[slug]`, and
`/partners/catalog/[slug]`. Removing it there would break those pages.
- Allowed in development, because Next.js needs it there.

**Preview and staging**
- Detection matches Studio's CSP: `NEXT_PUBLIC_VERCEL_ENV === 'preview'`
or `NEXT_PUBLIC_ENVIRONMENT` of `local` or `staging`. It no longer
depends on `NEXT_PUBLIC_IS_PLATFORM`.
- On preview and staging, the Vercel toolbar and the staging PostHog
host are added.
- The PostHog origin also comes from `NEXT_PUBLIC_POSTHOG_HOST`, the
same value the client uses.

**Tests**
`lib/security-headers.test.ts` covers the policy for each environment,
the proxied prefixes from the real rewrites, and the header sources. The
sources are compiled with the same path-to-regexp build and options that
Next.js uses.

## Review instructions

1. Open the preview and accept cookie consent so GTM and PostHog load.
2. Open DevTools → Console and filter on `Content-Security-Policy`.
3. Visit these pages and confirm there are no violations:
   - home
- a blog post with a tweet embed (`/blog/launch-week-5-community-day`)
   - `/changelog`
   - a `/customers/...` page
   - `/state-of-startups`
   - `/contact/sales`
   - `/aws-marketplace`
   - a `/go` page with a HubSpot form
4. Run `curl -sI <preview>/` and check the four headers. Run `curl -sI
<preview>/changelog` and check that the CSP includes `'unsafe-eval'`.
5. Run `curl -sI <preview>/dashboard` and `curl -sI <preview>/library`
and check that they have no www CSP or `X-Frame-Options`.
6. Confirm `/dashboard` and `/library` still load.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 11:19:07 +01:00

321 lines
9.1 KiB
TypeScript

import { buildCustomRoute } from 'next/dist/lib/build-custom-route'
import { describe, expect, it } from 'vitest'
import rewrites from './rewrites'
import {
buildCsp,
getProxiedPathPatterns,
getSecurityHeaderRules,
getWwwOwnedSource,
} from './security-headers'
const PRODUCTION_ENV = {
NODE_ENV: 'production',
NEXT_PUBLIC_VERCEL_ENV: 'production',
NEXT_PUBLIC_POSTHOG_HOST: 'https://ph.supabase.com',
}
const PREVIEW_ENV = {
NODE_ENV: 'production',
NEXT_PUBLIC_VERCEL_ENV: 'preview',
NEXT_PUBLIC_POSTHOG_HOST: 'https://ph.supabase.green',
}
// The docs zone is only rewritten in production
const REWRITES = [
...rewrites,
{ source: '/docs/:path*', destination: 'https://docs.example.com/:path*' },
]
// Next.js's full custom-route matcher, including its optional trailing slash
const toRegExp = (regex: string) => new RegExp(regex, 'i')
const rewriteMatches = (source: string, path: string) =>
toRegExp(
buildCustomRoute('rewrite', { source, destination: 'https://other.example.com' }).regex
).test(path)
const headerMatches = (source: string, path: string) =>
toRegExp(buildCustomRoute('header', { source, headers: [] }).regex).test(path)
const scriptSrc = (csp: string) =>
csp
.split('; ')
.find((directive) => directive.startsWith('script-src '))!
.split(' ')
.slice(1)
describe('buildCsp', () => {
it('builds the production policy', () => {
const csp = buildCsp({ env: PRODUCTION_ENV })
expect(csp).toContain("object-src 'none'")
expect(csp).toContain("base-uri 'self'")
expect(csp).toContain("form-action 'self'")
expect(csp).toContain("frame-ancestors 'self'")
const sources = scriptSrc(csp)
expect(sources).toEqual(
expect.arrayContaining([
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
'https://ss.supabase.com',
'https://ph.supabase.com',
])
)
expect(sources).not.toContain('https://vercel.live')
expect(sources).not.toContain('https://ph.supabase.green')
expect(sources.some((source) => source.includes('unpkg.com'))).toBe(false)
expect(sources.some((source) => source.includes('vercel.app'))).toBe(false)
expect(sources.some((source) => source === 'https://cdn.jsdelivr.net')).toBe(false)
})
it.each([
['production', PRODUCTION_ENV],
['preview', PREVIEW_ENV],
['development', { NODE_ENV: 'development' }],
])('allows eval in %s, where MDX pages evaluate on the client', (_, env) => {
expect(scriptSrc(buildCsp({ env }))).toContain("'unsafe-eval'")
})
it('allows the preview hosts on preview and staging', () => {
for (const env of [
PREVIEW_ENV,
{ NODE_ENV: 'production', NEXT_PUBLIC_ENVIRONMENT: 'staging' },
]) {
const sources = scriptSrc(buildCsp({ env }))
expect(sources).toContain('https://vercel.live')
expect(sources).toContain('https://ph.supabase.green')
}
})
it('uses the configured PostHog host', () => {
const sources = scriptSrc(
buildCsp({
env: { ...PRODUCTION_ENV, NEXT_PUBLIC_POSTHOG_HOST: 'https://ph.example.com/path' },
})
)
expect(sources).toContain('https://ph.example.com')
})
})
describe('getProxiedPathPatterns', () => {
it('ignores internal rewrites', () => {
expect(
getProxiedPathPatterns([
{ source: '/feed.xml', destination: '/rss.xml' },
{ source: '/:path*', destination: '/:path*' },
])
).toEqual([])
})
it('includes rewrites to unset env vars', () => {
expect(
getProxiedPathPatterns([{ source: '/kb/:path*', destination: 'undefined/:path*' }])
).toHaveLength(1)
})
})
describe('getWwwOwnedSource', () => {
it.each(['/', '/pricing', '/blog/some-post'])(
'matches every path when nothing is proxied: %s',
(path) => {
expect(headerMatches(getWwwOwnedSource([]), path)).toBe(true)
}
)
// Paths that the www source must skip, because the rewrite proxies them
const proxiedBy = (source: string, path: string) => {
const wwwSource = getWwwOwnedSource(
getProxiedPathPatterns([{ source, destination: 'https://other.example.com' }])
)
return !headerMatches(wwwSource, path)
}
it.each([
['/:path*', '/pricing'],
['/:path*', '/blog/some-post'],
['/:slug?', '/pricing'],
['/:slug?', '/'],
['/:path*', '/'],
['/:lang?{/guides/:page}', '/guides/intro'],
['/:lang?{/guides/:page}', '/en/guides/intro'],
['/kb/:path*', '/kb/'],
['/asset.:ext?', '/asset'],
['/asset.:ext?', '/asset.json'],
['/files/:slug(foo\\(bar\\))', '/files/foo(bar)'],
['/kb/:path*', '/kb'],
['/kb/:path*', '/kb/a/b'],
])('excludes what %s proxies: %s', (source, path) => {
expect(rewriteMatches(source, path)).toBe(true)
expect(proxiedBy(source, path)).toBe(true)
})
it.each([
['/:slug?', '/blog/some-post'],
['/asset.:ext?', '/assets'],
['/files/:slug(foo\\(bar\\))', '/files/foobar'],
['/kb/:path*', '/kbx'],
])('keeps what %s does not proxy: %s', (source, path) => {
expect(rewriteMatches(source, path)).toBe(false)
expect(proxiedBy(source, path)).toBe(false)
})
const SOURCES = [
'/:path*',
'/:slug?',
'/:slug+',
'/:lang?/guides/:page',
'/:lang?{/guides/:page}',
'/asset.:ext?',
'/files/:slug(foo\\(bar\\))',
'/kb/:path*',
'/docs/:slug+',
'/library\\.segments/:segment(.*)\\.segment\\.rsc',
]
const PATHS = [
'/',
'/pricing',
'/pricing/',
'/blog/some-post',
'/a/b/c',
'/asset',
'/asset.json',
'/asset.json/',
'/assets',
'/files/foo(bar)',
'/files/foobar',
'/guides/intro',
'/en/guides/intro',
'/kb',
'/kb/',
'/kb/a/b',
'/kbx',
'/docs',
'/docs/a',
'/library.segments/a.segment.rsc',
'/library.segments/example',
]
it.each(SOURCES.flatMap((source) => PATHS.map((path) => [source, path])))(
'agrees with the Next.js matcher for %s on %s',
(source, path) => {
expect(proxiedBy(source, path)).toBe(rewriteMatches(source, path))
}
)
})
describe('getSecurityHeaderRules', () => {
const rules = getSecurityHeaderRules(REWRITES, PRODUCTION_ENV)
const [wwwRule] = rules
it.each([
'/',
'/pricing',
'/blog/some-post',
'/customers',
'/customers/maergo',
'/changelog',
'/openapi',
'/openapi-guide',
'/library.json',
'/libraryx',
'/library.segments/example',
'/migrate',
'/migrate/other',
'/humans',
'/.well-known/ard.json',
'/dashboarding-guide',
'/docsearch',
])('applies to the www path %s', (path) => {
expect(headerMatches(wwwRule.source, path)).toBe(true)
})
it.each([
'/.well-known/security.txt',
'/openapi.json',
'/humans.txt',
'/dashboard',
'/dashboard/project/abc',
'/docs',
'/docs/guides/auth',
'/library',
'/library.rsc',
'/library.segments/a.segment.rsc',
'/library/example/x.segments/y.segment.rsc',
'/library/example/password-based-auth',
'/design-system/docs',
'/migrate/instantdb',
'/migrate/instantdb/step',
'/new-docs/',
'/kb/some-article',
])('does not apply to the proxied path %s', (path) => {
expect(headerMatches(wwwRule.source, path)).toBe(false)
})
// Every path must get the www headers exactly when no external rewrite proxies it
const externalSources = REWRITES.filter((rewrite) => !rewrite.destination.startsWith('/')).map(
(rewrite) => rewrite.source
)
const SAMPLE_PATHS = [
'/',
'/pricing',
'/customers/maergo',
'/dashboard',
'/dashboard/project/abc',
'/dashboarding-guide',
'/docs',
'/docs/guides/auth',
'/docs.segments/a.segment.rsc',
'/docsearch',
'/library',
'/library.rsc',
'/library.json',
'/library.segments/a.segment.rsc',
'/library.segments/example',
'/library/example/x.segments/y.segment.rsc',
'/library/example/password-based-auth',
'/libraryx',
'/design-system.segments/a.segment.rsc',
'/design-system.segments/example',
'/kb',
'/kb/a/b',
'/evals/run',
'/migrate',
'/migrate/instantdb',
'/migrate/instantdb/step',
'/migrate/other',
'/new-docs',
'/new-docs/',
'/new-docs/guides',
'/humans.txt',
'/humans',
'/lawyers.txt',
'/.well-known/security.txt',
'/.well-known/ard.json',
'/openapi.json',
'/openapi',
'/feed.xml',
]
it.each(SAMPLE_PATHS)('agrees with the rewrite sources for %s', (path) => {
const isProxied = externalSources.some((source) => rewriteMatches(source, path))
expect(headerMatches(wwwRule.source, path)).toBe(!isProxied)
})
it('sets the framing, sniffing and referrer headers', () => {
expect(wwwRule.headers).toEqual(
expect.arrayContaining([
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
])
)
})
it('uses one CSP for every www page, so client-side navigation keeps a working policy', () => {
const cspRules = rules.filter((rule) =>
rule.headers.some((header) => header.key === 'Content-Security-Policy')
)
expect(cspRules).toHaveLength(1)
})
})