Skip to content

Commit 1cd4618

Browse files
authored
Tests for CSP and route handlers pulled from Nexus (#3403)
While doing #3400, I realized I wanted a way to test the CSP from Nexus against our actual production bundle. I decide that because CSP is enforced in the browser, we don't need Nexus for this at all, we just need the CSP string. So all we have to do is use regex to extract that from the pinned Omicron commit, and then we can test the CSP with `vite preview` and a Playwright test. I was able to confirm the test fails when it's supposed to: on the #3400 branch, if I comment out the step that moves React Router's inline bootstrap scripts into separate files, the app never renders and the test fails with the browser's CSP errors: ``` Error: expect(received).toEqual(expected) // deep equality - Array [] + Array [ + "Executing inline script violates the following Content Security Policy directive 'default-src 'self''. [...] The action has been blocked.", + [3 more of those] + "CSP violation: script-src-elem inline", + "CSP violation: script-src-elem inline", ``` Once I had that in place, I thought about what else we might want to test about the contract with Nexus, and I remembered that I have sometimes forgotten to add a new route handler on the Nexus side when we added a new top-level route prefix in the console. So I added a test that similarly extracts the console routes from Nexus and makes sure all the client-side routes are covered by those handlers. That immediately turned up a bug (go to https://oxide.sys.r3.oxide-preview.com/images, click an image, and then refresh — 404), which is fixed in oxidecomputer/omicron#11467. So the test will fail until that is merged and omicron is bumped. This is nice and neat because #3402 pulls out the setup.
1 parent f468410 commit 1cd4618

12 files changed

Lines changed: 348 additions & 34 deletions

File tree

‎.github/workflows/lintBuildTest.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ jobs:
9696
run: npm run test:browser -- run --browser.name=${{ matrix.vitest }}
9797
- name: Run Playwright browser tests
9898
run: npx playwright test --project=${{ matrix.playwright }}
99+
- name: Run Playwright tests against production build
100+
run: npm run e2e:preview -- --project=${{ matrix.playwright }}
99101
- uses: actions/upload-artifact@v7
100102
if: always()
101103
with:

‎OMICRON_VERSION‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
7e18e523687767bb8c75070945ac398a5b89d9fd
1+
6d241a7d21d11cb7979122bde9a906d8d4837d09

‎app/api/__generated__/OMICRON_VERSION‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

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

Lines changed: 30 additions & 0 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: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ import path from 'path'
1111

1212
import { expect, it } from 'vitest'
1313

14+
import vercelConfig from '../../../vercel.json'
1415
import viteConfigFn from '../../../vite.config'
16+
import { nexusCsp } from '../__generated__/nexus-console'
1517

1618
it('Generated API client version matches API version specified for deployment', () => {
1719
const generatedVersion = fs
@@ -57,6 +59,15 @@ it('vite build target matches tsconfig target', () => {
5759
expect(viteConfig.build?.target).toEqual(tsconfig.compilerOptions.target)
5860
})
5961

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)
69+
})
70+
6071
const grepFiles = (s: string) =>
6172
execSync(`git grep -l "${s}"`)
6273
.toString()
@@ -110,9 +121,9 @@ const listFiles = (s: string) =>
110121
execSync(`git ls-files | grep "${s}"`).toString().trim().split('\n')
111122

112123
// avoid accidentally making an e2e file in the wrong place
113-
it('e2e tests are only in test/e2e or test/visual', () => {
124+
it('e2e tests are only in test/e2e, test/preview, or test/visual', () => {
114125
for (const file of listFiles('\\.e2e\\.')) {
115-
expect(file).toMatch(/^test\/(e2e|visual)/)
126+
expect(file).toMatch(/^test\/(e2e|preview|visual)/)
116127
}
117128
})
118129

‎app/util/path-builder.spec.ts‎

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
*
66
* Copyright Oxide Computer Company
77
*/
8-
import { matchRoutes } from 'react-router'
8+
import { matchRoutes, type RouteObject } from 'react-router'
99
import * as R from 'remeda'
1010
import { expect, test } from 'vitest'
1111

12+
import { nexusConsoleRoutes } from '~/api/__generated__/nexus-console'
1213
import { matchesToCrumbs } from '~/hooks/use-crumbs'
1314
import { routes } from '~/routes'
1415

@@ -224,3 +225,96 @@ test('every page reachable by breadcrumb should have a self-referential breadcru
224225
expect(dropFinalSlash(path)).toEqual(dropFinalSlash(last.path))
225226
}
226227
})
228+
229+
// Full path of every leaf route, with optional segments expanded both ways.
230+
// Only leaves are pages: a route with children renders at its own path only
231+
// through an index child, which is itself a leaf.
232+
function routePaths(routes: RouteObject[], parent = ''): string[] {
233+
return routes.flatMap((route) => {
234+
const full = route.path?.startsWith('/')
235+
? route.path
236+
: [parent, route.path].filter(Boolean).join('/')
237+
if (route.children) return routePaths(route.children, full)
238+
return expandOptional(full.split('/').filter(Boolean)).map((s) => '/' + s.join('/'))
239+
})
240+
}
241+
242+
const expandOptional = (segments: string[]): string[][] =>
243+
segments.reduce<string[][]>(
244+
(acc, seg) =>
245+
seg.endsWith('?')
246+
? [...acc, ...acc.map((prefix) => [...prefix, seg.slice(0, -1)])]
247+
: acc.map((prefix) => [...prefix, seg]),
248+
[[]]
249+
)
250+
251+
// Port of dropshot's lookup_route for a single template. Dropshot splits paths
252+
// on `/` and drops empty segments, then walks a trie: `{name}` matches one
253+
// segment and `{name:.*}` matches the rest, including nothing, so
254+
// /projects/{path:.*} serves /projects. Checking templates one at a time gives
255+
// the same answer as the trie because dropshot refuses to register a node with
256+
// both literal and variable children, so a path matches at most one route.
257+
// https://github.com/oxidecomputer/dropshot/blob/4ff9cb3/dropshot/src/router.rs#L438-L503
258+
// https://github.com/oxidecomputer/dropshot/blob/4ff9cb3/dropshot/src/router.rs#L254-L270
259+
function nexusServes(template: string, pathname: string) {
260+
const want = template.split('/').filter(Boolean)
261+
const have = pathname.split('/').filter(Boolean)
262+
for (const [i, seg] of want.entries()) {
263+
if (/^\{\w+:\.\*\}$/.test(seg)) return true
264+
if (i >= have.length) return false
265+
// a route param like :project only matches a Nexus param, not a literal
266+
if (!/^\{\w+\}$/.test(seg) && seg !== have[i]) return false
267+
}
268+
return want.length === have.length
269+
}
270+
271+
// The Nexus test below is only as good as nexusServes, so check that it matches
272+
// paths the same way dropshot does. These are the cases from dropshot's router
273+
// tests, plus the empty wildcard match, which dropshot doesn't test but the
274+
// console relies on for paths like /projects.
275+
// https://github.com/oxidecomputer/dropshot/blob/4ff9cb3/dropshot/src/router.rs#L1242-L1643
276+
test.each([
277+
['/', '/', true],
278+
['/', '//', true],
279+
['/foo', '/foo', true],
280+
['/foo', '/foo/', true],
281+
['/foo', '//foo//', true],
282+
['/foo', '/', false],
283+
['/not{a}variable', '/not{a}variable', true],
284+
['/not{a}variable', '/not{b}variable', false],
285+
['/projects/{project_id}', '/projects', false],
286+
['/projects/{project_id}', '/projects/', false],
287+
['/projects/{project_id}', '/projects/p12345', true],
288+
['/projects/{project_id}', '/projects/p12345/', true],
289+
['/projects/{project_id}', '/projects///p12345//', true],
290+
['/projects/{project_id}', '/projects/p12345/child', false],
291+
[
292+
'/projects/{project_id}/instances/{instance_id}/fwrules/{fwrule_id}/info',
293+
'/projects/p1/instances/i2/fwrules/fw3/info',
294+
true,
295+
],
296+
['/projects/{project_id}/instances', '/projects/instances', false],
297+
['/projects/{project_id}/instances', '/projects//instances', false],
298+
['/projects/{project_id}/instances', '/projects/foo/instances', true],
299+
['/console/{path:.*}', '/console/missiles/launch', true],
300+
['/console/{path:.*}', '/console', true],
301+
['/console/{path:.*}', '/', false],
302+
// console route params only match Nexus params, not literals
303+
['/projects/{project_id}', '/projects/:project', true],
304+
['/projects/new', '/projects/:project', false],
305+
])('nexusServes(%s, %s) is %s', (template, pathname, expected) => {
306+
expect(nexusServes(template, pathname)).toBe(expected)
307+
})
308+
309+
// Nexus only serves index.html on paths it knows about, so a console route
310+
// outside them works on client-side navigation but 404s on reload or direct
311+
// link. If this fails, add an endpoint for the new path in omicron next to the
312+
// existing ones, then bump OMICRON_VERSION once it merges.
313+
// https://github.com/oxidecomputer/omicron/blob/7e18e52/nexus/external-api/src/lib.rs#L9206
314+
test('Nexus serves the console on every route', () => {
315+
const unserved = R.unique(routePaths(routes))
316+
// the catch-all is for unknown paths, which Nexus is right to 404
317+
.filter((p) => !p.split('/').includes('*'))
318+
.filter((p) => !nexusConsoleRoutes.some((t) => nexusServes(t, p)))
319+
expect(unserved).toEqual([])
320+
})

‎docs/update-pinned-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
## Instructions
44

55
1. Update [`OMICRON_VERSION`](/OMICRON_VERSION) with new Omicron commit hash
6-
1. Update the generated API client by running `npm run gen-api`. This will automatically check out the omicron commit specified in `OMICRON_VERSION`. It also snapshots timeseries descriptions and units from omicron's oximeter schema files, which the API doesn't return. If you forget this step, a safety test in `app/api` will fail.
6+
1. Update the generated API client by running `npm run gen-api`. This will automatically check out the omicron commit specified in `OMICRON_VERSION`. It also snapshots timeseries descriptions and units from omicron's oximeter schema files, which the API doesn't return, and the paths Nexus serves the console on, which a test checks against the console's routes, and the Content-Security-Policy Nexus serves the console with, which the dev and preview servers use. If you forget this step, a safety test in `app/api` will fail.
77
1. Run `npm run tsc` and fix any type errors introduced by changes to the generated code. New endpoints must be added to the handler map in `mock-api/msw/handlers.ts`; use `NotImplemented` unless the UI needs them.
88
1. Commit and push to a branch
99

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
"update-snapshots": "npm test run -- -u",
3131
"e2e": "playwright test",
3232
"e2ec": "playwright test --project=chrome",
33+
"e2e:preview": "playwright test --config playwright.preview.config.ts",
3334
"visual:baseline": "./tools/generate-visual-baseline.sh",
3435
"visual:compare": "playwright test -c playwright.visual.config.ts",
3536
"lint": "oxlint --type-aware",

‎playwright.preview.config.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
5+
*
6+
* Copyright Oxide Computer Company
7+
*/
8+
import type { PlaywrightTestConfig } from '@playwright/test'
9+
10+
import baseConfig from './playwright.config'
11+
12+
/**
13+
* Run test/preview against the production build served under the Nexus CSP.
14+
* The main e2e suite runs against the dev server, which allows inline scripts
15+
* by nonce, so it can't catch scripts the build leaves inline.
16+
*/
17+
export default {
18+
...baseConfig,
19+
testDir: './test/preview',
20+
use: { ...baseConfig.use, baseURL: 'http://localhost:4010' },
21+
webServer: {
22+
command: 'npm run preview -- --port 4010 --strictPort',
23+
port: 4010,
24+
// includes a production build
25+
timeout: 180_000,
26+
},
27+
} satisfies PlaywrightTestConfig

‎test/preview/csp.e2e.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
5+
*
6+
* Copyright Oxide Computer Company
7+
*/
8+
import { expect, test, type Page } from '@playwright/test'
9+
10+
import { nexusCsp } from '../../app/api/__generated__/nexus-console'
11+
12+
/** Collect page errors, console errors, and CSP violations */
13+
async function trackErrors(page: Page) {
14+
const errors: string[] = []
15+
page.on('pageerror', (error) => errors.push(error.message))
16+
page.on('console', (message) => {
17+
if (message.type() === 'error') errors.push(message.text())
18+
})
19+
// not every browser logs violations to the console
20+
await page.addInitScript(() => {
21+
document.addEventListener('securitypolicyviolation', (event) => {
22+
console.error(`CSP violation: ${event.violatedDirective} ${event.blockedURI}`)
23+
})
24+
})
25+
return errors
26+
}
27+
28+
test('Production build runs under the Nexus CSP', async ({ page }) => {
29+
const errors = await trackErrors(page)
30+
try {
31+
const response = await page.goto('/projects/mock-project/instances')
32+
// make sure the test isn't passing because the server dropped the CSP
33+
expect(response?.headers()['content-security-policy']).toBe(nexusCsp)
34+
35+
await expect(page.getByRole('heading', { name: 'Instances' })).toBeVisible()
36+
// client-side navigation only works if the app hydrated
37+
await page.getByRole('link', { name: 'db1' }).click()
38+
await expect(page.getByRole('heading', { name: 'db1' })).toBeVisible()
39+
await expect(page.getByRole('cell', { name: 'disk-1' })).toBeVisible()
40+
} finally {
41+
// a CSP violation usually means the page never renders, so report the
42+
// errors instead of a missing heading
43+
expect(errors).toEqual([])
44+
}
45+
})

0 commit comments

Comments
 (0)