test(e2e): add Playwright suite for auth + CSRF + visibility fixes

Covers the security fixes that landed across both repos:

- auth.spec.ts: login persists nz-jwt cookie and getProfile succeeds;
  password change bumps TokenVersion + revokes the old cookie so the
  pre-change JWT can no longer auth (regression guard for the
  keyId+session backend rewrite).
- cron-csrf.spec.ts: POST /api/v1/cron/:id/manual succeeds while GET
  is no longer routable (regression guard for the cron CSRF fix).
- fm-csrf.spec.ts: POST /api/v1/file is reachable while GET is no
  longer routable (regression guard for the FM CSRF fix).
- visibility.spec.ts: an anonymous caller cannot see a server-group
  that contains zero guest-visible servers (regression guard for the
  server-group leak fix).

Fixtures wrap the noisy login + cleanup boilerplate. tsconfig is
scoped to tests/e2e so the suite stays out of the production tsc
project graph.

Playwright config starts the Vite dev server (npm run dev) and
expects a backend reachable at the URL Vite proxies to. CI workflow
follow-up commit wires the backend up.

Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
This commit is contained in:
naiba
2026-05-26 04:34:43 +00:00
co-authored by cloudcode
parent 266cd7d150
commit 22da4d74b8
10 changed files with 345 additions and 1 deletions
+57
View File
@@ -0,0 +1,57 @@
import { expect } from "@playwright/test"
import { defaultAdmin, expectAuthenticated, expectUnauthenticated, loginAs, test } from "./fixtures"
test("login persists session via cookie and getProfile succeeds", async ({ page }) => {
await loginAs(page, defaultAdmin)
await expectAuthenticated(page)
})
test("password change rotates TokenVersion and revokes existing session", async ({ page }) => {
await loginAs(page, defaultAdmin)
const originalCookies = await page.context().cookies()
const originalJWT = originalCookies.find((c) => c.name === "nz-jwt")?.value
expect(originalJWT, "login must set nz-jwt cookie").toBeTruthy()
const newPassword = `e2e-${Date.now().toString(36)}`
let isOnNewPassword = false
try {
const resp = await page.request.post("/api/v1/profile", {
data: {
original_password: defaultAdmin.password,
new_password: newPassword,
new_username: defaultAdmin.username,
reject_password: false,
},
})
expect(resp.ok(), "profile update must succeed").toBeTruthy()
isOnNewPassword = true
await page.context().clearCookies()
if (originalJWT) {
await page.context().addCookies([
{
name: "nz-jwt",
value: originalJWT,
url: page.url() || "http://localhost:5173",
},
])
}
await expectUnauthenticated(page)
} finally {
if (isOnNewPassword) {
await page.context().clearCookies()
await loginAs(page, { username: defaultAdmin.username, password: newPassword })
const restoreResp = await page.request.post("/api/v1/profile", {
data: {
original_password: newPassword,
new_password: defaultAdmin.password,
new_username: defaultAdmin.username,
reject_password: false,
},
})
expect(restoreResp.ok(), "password restore must succeed so other suites can still log in").toBeTruthy()
}
}
})
+38
View File
@@ -0,0 +1,38 @@
import { expect } from "@playwright/test"
import { test } from "./fixtures"
test("manual cron trigger goes through POST, not GET", async ({ adminPage: page }) => {
const created = await page.request.post("/api/v1/cron", {
data: {
name: "e2e-cron-csrf",
task_type: 0,
scheduler: "@every 1h",
command: "true",
servers: [],
cover: 0,
push_successful: false,
notification_group_id: 0,
},
})
expect(created.ok(), "create cron via POST must succeed").toBeTruthy()
const { data: cronID } = (await created.json()) as { data: number }
expect(typeof cronID).toBe("number")
try {
const getResp = await page.request.get(`/api/v1/cron/${cronID}/manual`, {
failOnStatusCode: false,
})
expect(
getResp.status() === 404 || getResp.status() === 405,
`GET must no longer be routable (got ${getResp.status()})`,
).toBeTruthy()
const postResp = await page.request.post(`/api/v1/cron/${cronID}/manual`)
expect(postResp.ok(), `POST must succeed (got ${postResp.status()})`).toBeTruthy()
const body = await postResp.json()
expect(body.success).toBe(true)
} finally {
await page.request.post("/api/v1/batch-delete/cron", { data: [cronID] })
}
})
+56
View File
@@ -0,0 +1,56 @@
import { Page, Request, expect, test as base } from "@playwright/test"
export type LoginContext = {
username: string
password: string
}
export const defaultAdmin: LoginContext = {
username: process.env.E2E_ADMIN_USER || "admin",
password: process.env.E2E_ADMIN_PASS || "admin",
}
export async function loginAs(page: Page, creds: LoginContext) {
await page.goto("/dashboard/login")
await page.locator('input[autocomplete="username"]').fill(creds.username)
await page.locator('input[autocomplete="current-password"]').fill(creds.password)
await page.locator('button[type="submit"]').click()
await page.waitForURL(/\/dashboard\/?(?:$|\?|#)/, { timeout: 10_000 })
}
export async function logout(page: Page) {
await page.context().clearCookies()
}
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)
const body = await resp.json()
expect(body.success, "profile.success must be true").toBe(true)
expect(body.data?.id, "profile.data.id must be present").toBeTruthy()
}
export async function expectUnauthenticated(page: Page) {
const resp = await page.request.get("/api/v1/profile")
const body = await resp.json()
expect(body.success, "profile must NOT be authorized after revoke").not.toBe(true)
expect(body.error, "profile must surface an error after revoke").toBeTruthy()
}
export async function findRequest(
page: Page,
matcher: (req: Request) => boolean,
trigger: () => Promise<void>,
timeoutMs = 5000,
): Promise<Request> {
const waiter = page.waitForRequest(matcher, { timeout: timeoutMs })
await trigger()
return await waiter
}
export const test = base.extend<{ adminPage: Page }>({
adminPage: async ({ page }, use) => {
await loginAs(page, defaultAdmin)
await use(page)
},
})
+21
View File
@@ -0,0 +1,21 @@
import { expect } from "@playwright/test"
import { test } from "./fixtures"
test("file manager creation only accepts POST", async ({ adminPage: page }) => {
const getResp = await page.request.get("/api/v1/file?id=1", {
failOnStatusCode: false,
})
expect(
getResp.status() === 404 || getResp.status() === 405,
`GET /api/v1/file must no longer be routable (got ${getResp.status()})`,
).toBeTruthy()
const postResp = await page.request.post("/api/v1/file?id=1", {
failOnStatusCode: false,
})
expect(postResp.status()).toBe(200)
const body = await postResp.json()
expect(body.success, "without a connected agent server the POST surfaces a Service error, but the route is reachable").not.toBe(true)
expect(body.error).toBeTruthy()
})
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023", "DOM"],
"module": "ESNext",
"moduleResolution": "Bundler",
"isolatedModules": true,
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"types": ["@playwright/test"]
},
"include": ["**/*.ts"]
}
+53
View File
@@ -0,0 +1,53 @@
import { expect } from "@playwright/test"
import { test } from "./fixtures"
test("server-group hides guest-empty groups from anonymous callers", async ({ adminPage: page, browser }) => {
const tag = Date.now().toString(36)
const visibleName = `e2e-visible-${tag}`
const hiddenName = `e2e-hidden-${tag}`
// Admin creates one group with no servers (will be guest-empty) and one with a public server.
// First make sure there's at least one public server visible to guests; if not, this whole
// scenario boils down to "no group is guest-visible", which the assertion below still covers.
const serversResp = await page.request.get("/api/v1/server")
expect(serversResp.ok()).toBeTruthy()
const serversBody = (await serversResp.json()) as { data: Array<{ id: number; hide_for_guest?: boolean }> }
const publicServer = serversBody.data?.find((s) => !s.hide_for_guest)
const createdGroupIDs: number[] = []
if (publicServer) {
const visibleResp = await page.request.post("/api/v1/server-group", {
data: { name: visibleName, servers: [publicServer.id] },
})
expect(visibleResp.ok()).toBeTruthy()
createdGroupIDs.push(((await visibleResp.json()) as { data: number }).data)
}
const hiddenResp = await page.request.post("/api/v1/server-group", {
data: { name: hiddenName, servers: [] },
})
expect(hiddenResp.ok()).toBeTruthy()
createdGroupIDs.push(((await hiddenResp.json()) as { data: number }).data)
try {
const guestCtx = await browser.newContext()
try {
const guestResp = await guestCtx.request.get("/api/v1/server-group")
expect(guestResp.ok()).toBeTruthy()
const guestBody = (await guestResp.json()) as {
data: Array<{ group: { name: string }; servers: number[] }>
}
const names = (guestBody.data || []).map((it) => it.group.name)
expect(names, "guest must NOT see groups with zero visible servers").not.toContain(hiddenName)
if (publicServer) {
expect(names, "guest still sees groups that contain a guest-visible server").toContain(visibleName)
}
} finally {
await guestCtx.close()
}
} finally {
if (createdGroupIDs.length > 0) {
await page.request.post("/api/v1/batch-delete/server-group", { data: createdGroupIDs })
}
}
})