test(e2e): send CSRF token on mutating requests and fix PAT UI selectors

The backend CSRF double-submit gate rejects unsafe methods unless
X-CSRF-Token mirrors the signed nz-csrf cookie. page.request bypasses the
SPA JS that does this, so every mutating E2E call got 403, failing the suite.

- Add csrfHeaders(page) helper that mirrors the nz-csrf cookie into the
  header, polling until the cookie is readable to avoid the post-login race.
- Apply it to all cookie-authenticated POST/PATCH/DELETE calls (the /mcp
  Bearer calls stay header-free since PAT requests are CSRF-exempt).
- loginAs waits for the nz-csrf cookie before returning.
- Fix the create-token dialog submit selector: the button is labelled
  'Create API token' (t('CreateApiToken')), not 'Create'.

Verified 8/8 passing across repeated CI-mode runs against a real backend.

Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
This commit is contained in:
naiba
2026-05-31 08:17:15 +00:00
co-authored by cloudcode
parent c9bed85a91
commit 76b9eb6a54
6 changed files with 59 additions and 11 deletions
+26
View File
@@ -16,12 +16,38 @@ export async function loginAs(page: Page, creds: LoginContext) {
await page.locator('input[autocomplete="current-password"]').fill(creds.password)
await page.locator('button[type="submit"]').click()
await page.waitForURL(/\/dashboard\/?(?:$|\?|#)/, { timeout: 10_000 })
// Block until the signed nz-csrf cookie is readable. csrfHeaders() reads it
// synchronously; without this wait a mutating request fired right after
// login can race the Set-Cookie and send no token, getting a 403.
await expect
.poll(async () => (await page.context().cookies()).some((c) => c.name === "nz-csrf"), {
timeout: 10_000,
})
.toBe(true)
}
export async function logout(page: Page) {
await page.context().clearCookies()
}
// csrfHeaders mirrors the signed nz-csrf cookie into the X-CSRF-Token header.
// The backend's double-submit CSRF gate rejects unsafe methods unless the two
// match; the SPA does this in api.ts, but page.request bypasses that JS, so
// E2E mutating calls must replicate it or every POST/PATCH/DELETE gets 403.
export async function csrfHeaders(page: Page): Promise<Record<string, string>> {
let value = ""
await expect
.poll(
async () => {
value = (await page.context().cookies()).find((c) => c.name === "nz-csrf")?.value ?? ""
return value
},
{ timeout: 10_000 },
)
.not.toBe("")
return { "X-CSRF-Token": value }
}
export async function expectAuthenticated(page: Page) {
const resp = await page.request.get("/api/v1/profile")
expect(resp.status(), "profile must respond 2xx while authenticated").toBeLessThan(400)