Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions frontend/src/__tests__/lib/security/csp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* @jest-environment node
*/
import { buildCsp, createNonce } from '@/lib/security/csp';

const directive = (csp: string, name: string) =>
csp.split('; ').find((d) => d.startsWith(`${name} `)) ?? '';

describe('buildCsp', () => {
it('trusts scripts by nonce and strict-dynamic, with no inline or eval in production', () => {
const scripts = directive(buildCsp('abc123'), 'script-src');
expect(scripts).toContain("'nonce-abc123'");
expect(scripts).toContain("'strict-dynamic'");
expect(scripts).not.toContain("'unsafe-inline'");
expect(scripts).not.toContain("'unsafe-eval'");
});

it("adds 'unsafe-eval' and the local API only in development", () => {
const csp = buildCsp('abc123', { isDev: true });
expect(directive(csp, 'script-src')).toContain("'unsafe-eval'");
expect(directive(csp, 'connect-src')).toContain('http://localhost:4000');
expect(directive(buildCsp('abc123'), 'connect-src')).not.toContain('localhost');
});

it('keeps the protections and third parties the nginx policy had', () => {
const csp = buildCsp('abc123');
for (const rule of [
"default-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
'frame-src https://challenges.cloudflare.com',
]) {
expect(csp).toContain(rule);
}
expect(directive(csp, 'connect-src')).toContain('https://o4510868467417088.ingest.us.sentry.io');
expect(directive(csp, 'connect-src')).toContain('https://places.googleapis.com');
});
});

describe('createNonce', () => {
it('is base64 and different every time', () => {
const a = createNonce();
expect(a).toMatch(/^[A-Za-z0-9+/]+=*$/);
expect(createNonce()).not.toBe(a);
});
});
50 changes: 47 additions & 3 deletions frontend/src/__tests__/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/**
* @jest-environment node
*/
// Types for mock responses
interface MockResponse {
status: number;
Expand All @@ -11,15 +14,18 @@ const mockRedirect = jest.fn<MockResponse, [URL, number?]>((url: URL, status = 3
headers: { get: (key: string) => key === 'location' ? url.toString() : null },
}));

const mockNext = jest.fn<MockResponse, []>(() => ({
type NextInit = { request?: { headers?: Headers } };

// Mirrors NextResponse.next: a 200 whose headers the proxy can set.
const mockNext = jest.fn<MockResponse & { headers: Headers }, [NextInit?]>(() => ({
status: 200,
headers: { get: () => null },
headers: new Headers(),
}));

jest.mock('next/server', () => ({
NextResponse: {
redirect: (url: URL, status?: number) => mockRedirect(url, status),
next: () => mockNext(),
next: (init?: NextInit) => mockNext(init),
},
}));

Expand All @@ -35,6 +41,7 @@ function createMockRequest(pathname: string, token?: string): Parameters<typeof
pathname,
},
url: url.toString(),
headers: new Headers(),
cookies: {
get: (name: string) => {
if (name === 'token' && token) {
Expand Down Expand Up @@ -328,3 +335,40 @@ describe('Middleware - Admin Route Protection', () => {
});
});
});

describe('Proxy - Content-Security-Policy (#479)', () => {
const scriptSrc = (csp: string) => csp.split('; ').find((d) => d.startsWith('script-src ')) ?? '';

beforeEach(() => mockNext.mockClear());

it('sends a nonce CSP on every page, and hands the same nonce to the render', () => {
const response = proxy(createMockRequest('/about'));
const csp = response.headers.get('Content-Security-Policy') ?? '';

const nonce = /'nonce-([^']+)'/.exec(csp)?.[1];
expect(nonce).toBeTruthy();
expect(scriptSrc(csp)).toContain("'strict-dynamic'");

const forwarded = mockNext.mock.calls[0][0]?.request?.headers;
expect(forwarded?.get('x-nonce')).toBe(nonce);
expect(forwarded?.get('Content-Security-Policy')).toBe(csp);
});

it('makes a new nonce for each request', () => {
const first = proxy(createMockRequest('/')).headers.get('Content-Security-Policy');
const second = proxy(createMockRequest('/')).headers.get('Content-Security-Policy');
expect(first).not.toBe(second);
});

it('allows no inline or eval scripts outside development', () => {
const csp = proxy(createMockRequest('/')).headers.get('Content-Security-Policy') ?? '';
expect(scriptSrc(csp)).not.toContain("'unsafe-inline'");
expect(scriptSrc(csp)).not.toContain("'unsafe-eval'");
});

it('also sets the CSP on protected pages that pass the auth check', () => {
const token = createMockToken({ id: '1', email: 'a@example.com', role: 'ADMIN', exp: Math.floor(Date.now() / 1000) + 3600 });
const response = proxy(createMockRequest('/admin', token));
expect(response.headers.get('Content-Security-Policy')).toMatch(/'nonce-/);
});
});
11 changes: 9 additions & 2 deletions frontend/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import "./globals.css";
import { ApolloProvider } from "@/lib/apollo/ApolloProvider";
import { ThemeProvider } from "@/components/theme-provider";
Expand All @@ -9,16 +10,21 @@ import GoogleAnalytics from "@/components/GoogleAnalytics";
import { defaultMetadata } from "./metadata";
import { StripeFab } from "@/components/stripe/StripeFab";
import { FabStack } from "@/components/layouts/FabStack";
import { NONCE_HEADER } from "@/lib/security/csp";

export const metadata: Metadata = {
...defaultMetadata,
};

export default function RootLayout({
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
// proxy.ts sets a nonce per request (#479). Reading it makes every page
// dynamic, which nonces require.
const nonce = (await headers()).get(NONCE_HEADER) ?? undefined;

return (
<html lang="en" suppressHydrationWarning>
<body className="font-sans antialiased">
Expand All @@ -27,10 +33,11 @@ export default function RootLayout({
defaultTheme="system"
enableSystem
disableTransitionOnChange
nonce={nonce}
>
<ApolloProvider>
<AuthProvider>
<GoogleAnalytics />
<GoogleAnalytics nonce={nonce} />
{children}
<Toaster />
<SonnerToaster />
Expand Down
6 changes: 5 additions & 1 deletion frontend/src/components/GoogleAnalytics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@

import Script from 'next/script'

const GoogleAnalytics = () => {
// The inline gtag snippet needs the request's nonce (#479); the external script is
// trusted through 'strict-dynamic' but takes it too.
const GoogleAnalytics = ({ nonce }: { nonce?: string }) => {
return (
<>
<Script
nonce={nonce}
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=G-RZW38XNT3N`}
/>
<Script
id="google-analytics"
nonce={nonce}
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
Expand Down
64 changes: 64 additions & 0 deletions frontend/src/lib/security/csp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* The Content-Security-Policy for every page (#479).
*
* proxy.ts makes a fresh nonce per request and sends this policy; Next.js reads
* the nonce from it and stamps its own scripts. 'strict-dynamic' then trusts
* whatever those scripts load (Google Maps, Turnstile, Sentry), so script-src
* needs neither 'unsafe-inline' nor 'unsafe-eval'. The host list after it is a
* fallback for browsers without 'strict-dynamic', which ignore the nonce rules.
*
* nginx sends its own CSP only for backend routes (nginx/conf/default.conf).
*/

export const NONCE_HEADER = 'x-nonce';

const SENTRY_INGEST = 'https://o4510868467417088.ingest.us.sentry.io';

export const createNonce = (): string => Buffer.from(crypto.randomUUID()).toString('base64');

export function buildCsp(nonce: string, { isDev = false }: { isDev?: boolean } = {}): string {
const directives: Record<string, string[]> = {
'default-src': ["'self'"],
'script-src': [
"'self'",
`'nonce-${nonce}'`,
"'strict-dynamic'",
// React rebuilds server error stacks with eval in development only.
...(isDev ? ["'unsafe-eval'"] : []),
'https://challenges.cloudflare.com',
'https://maps.googleapis.com',
'https://maps.gstatic.com',
'https://www.googletagmanager.com',
],
// Styles stay as before: Google Maps and Next.js set inline styles without a nonce.
'style-src': ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
'img-src': ["'self'", 'data:', 'https:'],
'font-src': ["'self'", 'data:', 'https://fonts.gstatic.com', 'https://maps.gstatic.com'],
'connect-src': [
"'self'",
'data:',
'https://luisfaria.dev',
'https://challenges.cloudflare.com',
'https://maps.googleapis.com',
'https://places.googleapis.com',
'https://maps.gstatic.com',
'https://www.gstatic.com',
'https://www.google-analytics.com',
'https://analytics.google.com',
'https://region1.google-analytics.com',
SENTRY_INGEST,
// The dev server's GraphQL API and hot reload.
...(isDev ? ['http://localhost:4000', 'ws:'] : []),
],
'worker-src': ["'self'", 'blob:'],
'frame-src': ['https://challenges.cloudflare.com'],
'frame-ancestors': ["'none'"],
'object-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
};

return Object.entries(directives)
.map(([name, values]) => `${name} ${values.join(' ')}`)
.join('; ');
}
25 changes: 22 additions & 3 deletions frontend/src/proxy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
import { jwtDecode } from 'jwt-decode';
import { logger } from '@/lib/logger';
import { NONCE_HEADER, buildCsp, createNonce } from '@/lib/security/csp';

interface DecodedToken {
id: string;
Expand All @@ -18,6 +19,21 @@ const LEGACY_PLACES_PATHS = ['/relationship', '/admin/relationship'];
const isLegacyPlacesPath = (pathname: string) =>
LEGACY_PLACES_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`));

// Every page gets a fresh nonce and the CSP that names it (#479). Next.js reads
// the nonce from the request's CSP header and stamps its own scripts with it.
function nextWithCsp(request: NextRequest) {
const nonce = createNonce();
const csp = buildCsp(nonce, { isDev: process.env.NODE_ENV === 'development' });

const requestHeaders = new Headers(request.headers);
requestHeaders.set(NONCE_HEADER, nonce);
requestHeaders.set('Content-Security-Policy', csp);

const response = NextResponse.next({ request: { headers: requestHeaders } });
response.headers.set('Content-Security-Policy', csp);
return response;
}

export function proxy(request: NextRequest) {
if (isLegacyPlacesPath(request.nextUrl.pathname)) {
return NextResponse.redirect(new URL('/places', request.url), 308);
Expand Down Expand Up @@ -74,10 +90,13 @@ export function proxy(request: NextRequest) {
}
}

return NextResponse.next();
return nextWithCsp(request);
}

// Configure which paths this proxy applies to
// Every page, for the CSP. Skips route handlers (/api), build assets, image
// optimisation and files served from /public or generated (icons, robots, sitemap).
export const config = {
matcher: ['/admin/:path*', '/notes/:path*', '/places/:path*', '/relationship/:path*'],
matcher: [
'/((?!api/|_next/static|_next/image|favicon\\.ico|.*\\.(?:png|jpe?g|gif|svg|webp|avif|ico|txt|xml|webmanifest|js|css|map)$).*)',
],
};
10 changes: 9 additions & 1 deletion nginx/conf/default.conf
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ map $http_user_agent $has_user_agent {
default 1;
}

# Pages get their CSP from Next.js (frontend/src/proxy.ts): a fresh nonce per
# request, which nginx can't make. nginx sends this policy only for the backend
# routes. An empty value means nginx adds no header, so each response has one CSP.
map $uri $nginx_csp {
~^/(health(/|$)|webhooks/|graphql) "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://challenges.cloudflare.com https://maps.googleapis.com https://maps.gstatic.com https://www.googletagmanager.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: https:; font-src 'self' data: https://fonts.gstatic.com https://maps.gstatic.com; connect-src 'self' data: https://luisfaria.dev https://challenges.cloudflare.com https://maps.googleapis.com https://places.googleapis.com https://maps.gstatic.com https://www.gstatic.com https://www.google-analytics.com https://analytics.google.com https://region1.google-analytics.com https://o4510868467417088.ingest.us.sentry.io; worker-src 'self' blob:; frame-src https://challenges.cloudflare.com; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self';";
default "";
}

# ---------------------------------------------------------------------------
# Catch-all: bare-IP and unknown-host requests get nothing
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -124,7 +132,7 @@ server {
# Features the site never uses. Fullscreen, wake lock and clipboard (EMOM) stay allowed.
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://challenges.cloudflare.com https://maps.googleapis.com https://maps.gstatic.com https://www.googletagmanager.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: https:; font-src 'self' data: https://fonts.gstatic.com https://maps.gstatic.com; connect-src 'self' data: https://luisfaria.dev https://challenges.cloudflare.com https://maps.googleapis.com https://places.googleapis.com https://maps.gstatic.com https://www.gstatic.com https://www.google-analytics.com https://analytics.google.com https://region1.google-analytics.com https://o4510868467417088.ingest.us.sentry.io; worker-src 'self' blob:; frame-src https://challenges.cloudflare.com; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self';" always;
add_header Content-Security-Policy $nginx_csp always;

# CORS is Express's job (cors() in backend/src/index.ts), preflight included.
# Setting it here too sent two Access-Control-Allow-Origin headers (#456).
Expand Down
6 changes: 5 additions & 1 deletion ops/nginx/test-config.sh
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,11 @@ expect "Referrer-Policy keeps the origin cross-site" "strict-origin-when-cross-o
expect "X-XSS-Protection is off (CSP replaces it)" "0" "$(header X-XSS-Protection luisfaria.dev /)"
expect "Permissions-Policy denies unused features" "camera=(), microphone=(), geolocation=(), payment=(), usb=()" \
"$(header Permissions-Policy luisfaria.dev /)"
csp="$(header Content-Security-Policy luisfaria.dev /)"
# Pages: Next.js sends the nonce CSP (frontend/src/proxy.ts); nginx must add none,
# or the browser would enforce both and block the nonce'd scripts.
expect "no CSP from nginx on pages (Next.js sends it)" "" "$(header Content-Security-Policy luisfaria.dev /)"
expect "CSP on /graphql" "1" "$(header Content-Security-Policy luisfaria.dev /graphql | grep -c "default-src 'self'")"
csp="$(header Content-Security-Policy luisfaria.dev /health)"
for d in "object-src 'none'" "base-uri 'self'" "form-action 'self'" "frame-ancestors 'none'" "https://o4510868467417088.ingest.us.sentry.io"; do
expect "CSP has $d" "1" "$(grep -cF -- "$d" <<< "$csp")"
done
Expand Down
Loading