fix(e2e): read the CSP off the response, not a second fetch

readCspString re-fetched the current URL through the Playwright API
request context and, when that failed, waited actionTimeout (30s) for a
<meta http-equiv="Content-Security-Policy"> that no template in this
repo emits. On a healthy runner that path works and costs one extra
request; when name resolution degrades it collapses, because the API
request context resolves DNS separately from the browser: the re-fetch
burns its 10s cap and the meta wait then drains whatever is left of the
caller's test budget.

That is what killed web-svc-logout's guest persona in run 32597248629,
job Pretix#0, whose swarm manager had a single resolver on 127.0.0.1
with dnsmasq no longer answering. Every guest test on that host inflated
to ~40s and the logout one, loading two external assets on top, died on
its 60s timeout having asserted nothing. The same role in Bluesky#0 and
YOURLS#0 of the same run, same role set, finished in 0.85s and 0.82s -
so this is a resilience fix, not a repair of a broken assertion.

gotoOnion now installs a page.on("response") recorder, so the header is
taken from the document the browser already received. That also covers
the surface reached through an SSO round trip, where no navigation
Response is in scope at the assertion - only guest.js holds one, biber,
admin and the suitecrm saml spec discard theirs. The re-fetch stays as
the fallback for a spec that navigates without gotoOnion; the meta
fallback is deleted.

The suite pins the header precedence (enforced over report-only) and
every guard in assertCspInjections: a disabled injector, a gate that
throws, an enabled injector without a base URL, a missing gate, a second
enabled injector, and the case-insensitive host match. Inverting the
precedence or dropping toLowerCase each trips exactly one test.

Verified against a headless Chromium and a local server counting
requests: the header survives a 302, no extra request is issued, a
missing injector host still fails the assertion, and a header-less page
falls back to exactly one re-fetch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
kevinveenbirkenbachandClaude Opus 5 committed 2026-08-23 04:31:55 +02:00
1 parent c9b45f5804
commit 43ec22ee20
3 files changed
+322 -20

No files matched your search

@@ -0,0 +1,271 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const path = require("node:path");
const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../../..");
const { assertCspInjections, installCspHeaderRecorder } = require(
path.join(
PROJECT_ROOT,
"roles/test-e2e-playwright/files/personas/utils/csp.js",
),
);
const CDN = "https://cdn.example.test";
const WITH_CDN = `default-src 'self' ${CDN}`;
const WITHOUT_CDN = "default-src 'self'";
/**
* Build a stub `page` that records its response listeners.
*
* @param {object|null} refetchHeaders - headers the page.request.get
* fallback returns, or null to make that fallback fail
* @returns {object} the stub page plus its inspection handles
*/
function stubPage(refetchHeaders = null) {
const listeners = [];
const mainFrame = { name: "main" };
let refetchCalls = 0;
const page = {
url: () => "https://app.example.test/",
mainFrame: () => mainFrame,
on: (event, handler) => {
if (event === "response") listeners.push(handler);
},
request: {
get: async () => {
refetchCalls += 1;
if (!refetchHeaders) throw new Error("apiRequestContext.get: Timeout 10000ms exceeded.");
return { headers: () => refetchHeaders };
},
},
};
return {
page,
mainFrame,
listenerCount: () => listeners.length,
refetchCalls: () => refetchCalls,
emit: (response) => listeners.forEach((handler) => handler(response)),
};
}
function response(frame, headers, resourceType = "document") {
return {
frame: () => frame,
request: () => ({ resourceType: () => resourceType }),
headers: () => headers,
};
}
/**
* Run `run` with the given env vars applied, then restore them.
*
* @param {object} vars - env var name to value, or undefined to unset
* @param {function} run - async callback
* @returns {Promise<*>} whatever `run` resolves to
*/
async function withEnv(vars, run) {
const previous = {};
for (const name of Object.keys(vars)) {
previous[name] = process.env[name];
if (vars[name] === undefined) delete process.env[name];
else process.env[name] = vars[name];
}
try {
return await run();
} finally {
for (const name of Object.keys(previous)) {
if (previous[name] === undefined) delete process.env[name];
else process.env[name] = previous[name];
}
}
}
const withCdnEnv = (run) => withEnv({ CDN_BASE_URL: CDN }, run);
const cdnEnabled = (service) => service === "cdn";
const assertCdn = (page) =>
withCdnEnv(() => assertCspInjections(page, { isEnabled: cdnEnabled }));
test("the recorded header is used without a second request", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(response(stub.mainFrame, { "content-security-policy": WITH_CDN }));
await assertCdn(stub.page);
assert.equal(
stub.refetchCalls(),
0,
"re-fetching resolves DNS separately from the browser and is the slow path",
);
});
test("a recorded header missing an enabled injector host fails the assertion", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(response(stub.mainFrame, { "content-security-policy": WITHOUT_CDN }));
await assert.rejects(() => assertCdn(stub.page), /cdn\.example\.test/);
});
test("report-only counts as a recorded policy", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(
response(stub.mainFrame, { "content-security-policy-report-only": WITHOUT_CDN }),
);
await assert.rejects(() => assertCdn(stub.page), /cdn\.example\.test/);
});
test("the last main-frame document wins over an earlier redirect", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(response(stub.mainFrame, { "content-security-policy": WITHOUT_CDN }));
stub.emit(response(stub.mainFrame, { "content-security-policy": WITH_CDN }));
await assertCdn(stub.page);
});
test("sub-frame and sub-resource responses are ignored", async () => {
const stub = stubPage({ "content-security-policy": WITH_CDN });
installCspHeaderRecorder(stub.page);
stub.emit(response({ name: "iframe" }, { "content-security-policy": WITHOUT_CDN }));
stub.emit(
response(stub.mainFrame, { "content-security-policy": WITHOUT_CDN }, "script"),
);
await assertCdn(stub.page);
assert.equal(stub.refetchCalls(), 1, "nothing was recorded, so the fallback runs");
});
test("a spec that never installed the recorder falls back to a re-fetch", async () => {
const stub = stubPage({ "content-security-policy": WITH_CDN });
await assertCdn(stub.page);
assert.equal(stub.refetchCalls(), 1);
});
test("no policy anywhere asserts nothing rather than throwing", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
await assertCdn(stub.page);
assert.equal(stub.refetchCalls(), 1);
});
test("installing the recorder twice keeps one listener", () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
installCspHeaderRecorder(stub.page);
assert.equal(stub.listenerCount(), 1);
});
test("an enforced policy wins over report-only on the same response", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(
response(stub.mainFrame, {
"content-security-policy": WITHOUT_CDN,
"content-security-policy-report-only": WITH_CDN,
}),
);
await assert.rejects(
() => assertCdn(stub.page),
/cdn\.example\.test/,
"the enforced header is the policy the browser applies; report-only must not mask it",
);
});
test("a disabled injector is not asserted", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(response(stub.mainFrame, { "content-security-policy": WITHOUT_CDN }));
await withCdnEnv(() => assertCspInjections(stub.page, { isEnabled: () => false }));
});
test("a gate that throws counts as disabled", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(response(stub.mainFrame, { "content-security-policy": WITHOUT_CDN }));
await withCdnEnv(() =>
assertCspInjections(stub.page, {
isEnabled: () => {
throw new Error("gate unavailable");
},
}),
);
});
test("an enabled injector without a base URL is not asserted", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(response(stub.mainFrame, { "content-security-policy": WITHOUT_CDN }));
await withEnv({ CDN_BASE_URL: undefined }, () =>
assertCspInjections(stub.page, { isEnabled: cdnEnabled }),
);
});
test("no gate function reads nothing and asserts nothing", async () => {
const stub = stubPage({ "content-security-policy": WITHOUT_CDN });
await assertCspInjections(stub.page, {});
assert.equal(stub.refetchCalls(), 0);
});
test("every enabled injector is checked, not just the first", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(response(stub.mainFrame, { "content-security-policy": WITH_CDN }));
await assert.rejects(
() =>
withEnv(
{ CDN_BASE_URL: CDN, MATOMO_BASE_URL: "https://matomo.example.test" },
() =>
assertCspInjections(stub.page, {
isEnabled: (s) => s === "cdn" || s === "matomo",
}),
),
/matomo\.example\.test/,
);
});
test("the host match ignores case", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(
response(stub.mainFrame, {
"content-security-policy": "default-src 'self' https://CDN.EXAMPLE.TEST",
}),
);
await assertCdn(stub.page);
});
test("a torn-down response does not break the recorder", async () => {
const stub = stubPage();
installCspHeaderRecorder(stub.page);
stub.emit(response(stub.mainFrame, { "content-security-policy": WITH_CDN }));
stub.emit({
frame: () => {
throw new Error("Target page, context or browser has been closed");
},
});
await assertCdn(stub.page);
assert.equal(stub.refetchCalls(), 0);
});