Skip to content

Commit df32a01

Browse files
authored
Snapshot all Nexus security headers (#3405)
Followup to #3403 — there are other security headers besides CSP, we might as well get em all. We could change the Rust to make these regexes less gnarly, but it really doesn't matter.
1 parent 1cd4618 commit df32a01

6 files changed

Lines changed: 61 additions & 40 deletions

File tree

‎app/api/__generated__/nexus-console.ts‎

Lines changed: 7 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎app/api/__tests__/safety.spec.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { expect, it } from 'vitest'
1313

1414
import vercelConfig from '../../../vercel.json'
1515
import viteConfigFn from '../../../vite.config'
16-
import { nexusCsp } from '../__generated__/nexus-console'
16+
import { nexusSecurityHeaders } from '../__generated__/nexus-console'
1717

1818
it('Generated API client version matches API version specified for deployment', () => {
1919
const generatedVersion = fs
@@ -59,13 +59,13 @@ it('vite build target matches tsconfig target', () => {
5959
expect(viteConfig.build?.target).toEqual(tsconfig.compilerOptions.target)
6060
})
6161

62-
// Vercel preview deploys should run under the same CSP as Nexus. If this fails
63-
// after a pin bump, copy the generated policy into vercel.json.
64-
it('vercel.json CSP matches Nexus', () => {
65-
const vercelCsp = vercelConfig.headers[0].headers.find(
66-
(h) => h.key === 'content-security-policy'
67-
)?.value
68-
expect(vercelCsp).toEqual(nexusCsp)
62+
// Vercel preview deploys should run under the same security headers as Nexus.
63+
// If this fails after a pin bump, copy the generated headers into vercel.json.
64+
it('vercel.json security headers match Nexus', () => {
65+
const vercelHeaders = vercelConfig.headers[0].headers
66+
expect(Object.fromEntries(vercelHeaders.map((h) => [h.key, h.value]))).toEqual(
67+
nexusSecurityHeaders
68+
)
6969
})
7070

7171
const grepFiles = (s: string) =>

‎docs/csp-headers.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ Production CSP headers are set server-side in Nexus, so why should we set the he
66

77
## What
88

9-
The base headers are defined in `vercel.json` and imported into `vite.config.ts` to avoid repeating them.
9+
The headers are defined in Nexus. `npm run gen-api` snapshots them from the pinned omicron commit into `app/api/__generated__/nexus-console.ts`, which the Vite dev and preview servers serve. Vercel can only read headers from `vercel.json`, so they are copied there, and a test in `app/api/__tests__/safety.spec.ts` checks that the copy matches.
1010

1111
The `content-security-policy` is based on the recommendation by the [OWASP Secure Headers Project](https://owasp.org/www-project-secure-headers/index.html) (click the "Best Practices" tab). The directives:
1212

‎test/preview/csp.e2e.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88
import { expect, test, type Page } from '@playwright/test'
99

10-
import { nexusCsp } from '../../app/api/__generated__/nexus-console'
10+
import { nexusSecurityHeaders } from '../../app/api/__generated__/nexus-console'
1111

1212
/** Collect page errors, console errors, and CSP violations */
1313
async function trackErrors(page: Page) {
@@ -30,7 +30,9 @@ test('Production build runs under the Nexus CSP', async ({ page }) => {
3030
try {
3131
const response = await page.goto('/projects/mock-project/instances')
3232
// make sure the test isn't passing because the server dropped the CSP
33-
expect(response?.headers()['content-security-policy']).toBe(nexusCsp)
33+
expect(response?.headers()['content-security-policy']).toBe(
34+
nexusSecurityHeaders['content-security-policy']
35+
)
3436

3537
await expect(page.getByRole('heading', { name: 'Instances' })).toBeVisible()
3638
// client-side navigation only works if the app hydrated

‎tools/gen_api.ts‎

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -243,8 +243,8 @@ const ENDPOINTS_PATH = 'nexus/external-api/src/lib.rs'
243243
/**
244244
* Snapshot from the Rust source:
245245
*
246-
* - The Content-Security-Policy header Nexus serves the console with, so dev
247-
* and preview servers can serve the console under the same policy.
246+
* - The security headers Nexus serves the console with, including the CSP, so
247+
* dev and preview servers can serve the console under the same policy.
248248
* - The paths Nexus serves the console's index.html on. These endpoints are
249249
* unpublished, so they aren't in the OpenAPI spec. A test checks that every
250250
* console route is covered, so a new top-level route can't ship without
@@ -258,15 +258,35 @@ async function generateNexusConsole() {
258258
])
259259

260260
// https://github.com/oxidecomputer/omicron/blob/7e18e52/nexus/src/external_api/console_api.rs#L323-L334
261-
const cspLiteral = consoleApi.match(
262-
/CONTENT_SECURITY_POLICY,\s*HeaderValue::from_static\(\s*"([^"]*)"/
263-
)?.[1]
264-
if (!cspLiteral) throw new Error(`Could not find CSP in ${CONSOLE_API_PATH}`)
265-
266-
// A Rust string continuation (backslash-newline) also skips the next line's
267-
// leading whitespace. Any other escape means the source changed shape.
268-
const csp = cspLiteral.replace(/\\\n\s*/g, '')
269-
if (csp.includes('\\')) throw new Error(`Unexpected escape in CSP: ${csp}`)
261+
const headersBlock = consoleApi.match(
262+
/WEB_SECURITY_HEADERS: \[\(HeaderName, HeaderValue\); (\d+)\] = \[([\s\S]*?)\n\];/
263+
)
264+
if (!headersBlock)
265+
throw new Error(`Could not find security headers in ${CONSOLE_API_PATH}`)
266+
const securityHeaders = Array.from(
267+
headersBlock[2].matchAll(
268+
/http::header::(\w+),\s*HeaderValue::from_static\(\s*"([^"]*)"/g
269+
),
270+
([, name, literal]) => {
271+
// A Rust string continuation (backslash-newline) also skips the next
272+
// line's leading whitespace. Any other escape means the source changed shape.
273+
const value = literal.replace(/\\\n\s*/g, '')
274+
if (value.includes('\\')) throw new Error(`Unexpected escape in ${name}: ${value}`)
275+
// the http crate names header constants by uppercasing the header name
276+
return [name.toLowerCase().replaceAll('_', '-'), value] as const
277+
}
278+
)
279+
// guard against a source change that makes the extraction silently miss things
280+
if (securityHeaders.length !== Number(headersBlock[1])) {
281+
throw new Error(
282+
`Expected ${headersBlock[1]} security headers, found ${securityHeaders.length}`
283+
)
284+
}
285+
if (!securityHeaders.some(([name]) => name === 'content-security-policy')) {
286+
throw new Error(
287+
`Expected a CSP among ${securityHeaders.map(([name]) => name).join(', ')}`
288+
)
289+
}
270290

271291
// The handler impls are where we can tell which endpoints serve the console:
272292
// they call one of these two functions.
@@ -303,15 +323,16 @@ async function generateNexusConsole() {
303323
`// generated by tools/gen_api.ts from the Nexus source in omicron.
304324
// do not update manually. see docs/update-pinned-api.md
305325
306-
export const nexusCsp = ${JSON.stringify(csp)}
326+
/** Security headers Nexus serves the console with, including the CSP */
327+
export const nexusSecurityHeaders = ${JSON.stringify(Object.fromEntries(securityHeaders))}
307328
308329
/** Dropshot path templates that Nexus serves the console's index.html on */
309330
export const nexusConsoleRoutes = ${JSON.stringify(routes)}
310331
`
311332
)
312333

313334
console.info(
314-
`wrote Nexus CSP and ${routes.length} console routes to ${NEXUS_CONSOLE_FILE}`
335+
`wrote Nexus security headers and ${routes.length} console routes to ${NEXUS_CONSOLE_FILE}`
315336
)
316337
}
317338

‎vite.config.ts‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@ import { defineConfig } from 'vite'
1616
import { configDefaults } from 'vitest/config'
1717
import { z } from 'zod/v4'
1818

19-
import { nexusCsp } from './app/api/__generated__/nexus-console'
20-
import vercelConfig from './vercel.json'
19+
import { nexusSecurityHeaders } from './app/api/__generated__/nexus-console'
2120

2221
const ApiMode = z.enum(['msw', 'remote', 'nexus'])
2322

@@ -79,22 +78,16 @@ const previewTags = [
7978
},
8079
]
8180

82-
// Serve the CSP Nexus serves, snapshotted at the pinned omicron commit, so dev
83-
// and preview catch CSP violations. Other headers come from the vercel config.
84-
const vercelHeaders = vercelConfig.headers[0].headers
85-
const headers = {
86-
...Object.fromEntries(vercelHeaders.map((h) => [h.key, h.value])),
87-
'content-security-policy': nexusCsp,
88-
}
89-
90-
// This is only needed for local dev to avoid breaking Vite's script injection.
81+
// Serve the headers Nexus serves, snapshotted at the pinned omicron commit, so
82+
// dev and preview catch CSP violations. The nonce is only needed for local dev
83+
// to avoid breaking Vite's script injection.
9184
// Rather than use unsafe-inline all the time, the nonce approach is much more
9285
// narrowly scoped and lets us make sure everything *else* works fine without
9386
// unsafe-inline.
9487
const cspNonce = randomBytes(8).toString('hex')
9588
const devHeaders = {
96-
...headers,
97-
'content-security-policy': `${nexusCsp}; script-src 'nonce-${cspNonce}' 'self'`,
89+
...nexusSecurityHeaders,
90+
'content-security-policy': `${nexusSecurityHeaders['content-security-policy']}; script-src 'nonce-${cspNonce}' 'self'`,
9891
}
9992

10093
// see https://vitejs.dev/config/
@@ -189,7 +182,7 @@ export default defineConfig(({ mode }) => ({
189182
},
190183
},
191184
resolve: { tsconfigPaths: true },
192-
preview: { headers },
185+
preview: { headers: nexusSecurityHeaders },
193186
test: {
194187
name: 'unit',
195188
fsModuleCache: true,

0 commit comments

Comments
 (0)