From caaafd903bfbbefcc3a149a54285d26b259428e3 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Tue, 4 Jun 2024 14:24:35 +0200 Subject: [PATCH] fix(browser): allow iframe to load even if there is a custom CSP header (#5841) --- packages/browser/src/node/index.ts | 13 +++++++++++++ test/browser/vitest.config.mts | 3 +++ 2 files changed, 16 insertions(+) diff --git a/packages/browser/src/node/index.ts b/packages/browser/src/node/index.ts index 105c9ba1b416..a32534284d3d 100644 --- a/packages/browser/src/node/index.ts +++ b/packages/browser/src/node/index.ts @@ -74,7 +74,13 @@ export default (project: WorkspaceProject, base = '/'): Plugin[] => { __VITEST_TYPE__: url.pathname === base ? '"orchestrator"' : '"tester"', }) + // remove custom iframe related headers to allow the iframe to load + res.removeHeader('X-Frame-Options') + if (url.pathname === base) { + // disable CSP for the orchestrator as we are the ones controlling it + res.removeHeader('Content-Security-Policy') + if (!indexScripts) indexScripts = await formatScripts(project.config.browser.indexScripts, server) @@ -105,6 +111,13 @@ export default (project: WorkspaceProject, base = '/'): Plugin[] => { return } + const csp = res.getHeader('Content-Security-Policy') + if (typeof csp === 'string') { + // add frame-ancestors to allow the iframe to be loaded by Vitest, + // but keep the rest of the CSP + res.setHeader('Content-Security-Policy', csp.replace(/frame-ancestors [^;]+/, 'frame-ancestors *')) + } + const decodedTestFile = decodeURIComponent(url.pathname.slice(testerPrefix.length)) const testFiles = await project.globTestFiles() // if decoded test file is "__vitest_all__" or not in the list of known files, run all tests diff --git a/test/browser/vitest.config.mts b/test/browser/vitest.config.mts index c3bd055bbe0b..a613cda53098 100644 --- a/test/browser/vitest.config.mts +++ b/test/browser/vitest.config.mts @@ -18,6 +18,9 @@ export default defineConfig({ server: { headers: { 'x-custom': 'hello', + // Vitest iframe should still be loaded + 'X-Frame-Options': 'DENY', + 'content-security-policy': 'frame-src https://example.com; frame-ancestors https://example.com', }, }, optimizeDeps: {