SPB Git

Repository Public

03-security.spec.ts 10.9 KB 194 lines typescript

1import { expect, test, type BrowserContext, type Page } from "@playwright/test";2import { addAuthenticator, signedIn, sql, type Authenticator, type Problems, newClient } from "../lib/harness";34type Ctx = { context: BrowserContext; page: Page; auth: Authenticator; problems: Problems };56test.describe.serial("step-up, passkeys, sessions, devices, language", () => {7  let owner: Ctx;89  test.beforeAll(async ({ browser }) => {10    owner = await signedIn(browser, "e2e-owner");11  });12  test.afterAll(async () => {13    // whatever happened above, the following specs expect the French profile again14    sql(`update users set locale = 'fr' where handle = 'e2e-owner'`);15    await owner.context.close();16  });1718  test("step-up: an aged session is asked for the passkey and the original request is replayed", async () => {19    const { page } = owner;20    await page.goto("/settings/invitations");21    await expect(page.getByTestId("screen-settings-invitations")).toBeVisible();22    // age the ceremony beyond the 5-minute step-up window, as time would23    sql(`update sessions set authenticated_at = now() - interval '10 minutes' where user_id = (select id from users where handle = 'e2e-owner')`);24    const calls: { url: string; status: number }[] = [];25    page.on("response", (r) => {26      if (r.request().method() === "POST" && /\/api\/v1\/(invitations|auth\/stepup\/)/.test(r.url())) calls.push({ url: new URL(r.url()).pathname.replace("/api/v1", ""), status: r.status() });27    });28    await page.getByTestId("invite-create").click();29    await page.getByTestId("invite-role").selectOption("viewer");30    await page.getByTestId("invite-submit").click();31    await expect(page.getByTestId("stepup-verify")).toBeVisible();32    await page.getByTestId("stepup-verify").click();33    await expect(page.getByTestId("invite-link")).toBeVisible();34    expect(calls).toEqual([35      { url: "/invitations", status: 403 },36      { url: "/auth/stepup/begin", status: 200 },37      { url: "/auth/stepup/finish", status: 200 },38      { url: "/invitations", status: 201 },39    ]);40    await page.getByTestId("invite-done").click();41  });4243  test("step-up cancelled: nothing is created and the refusal is explained", async () => {44    const { page } = owner;45    sql(`update sessions set authenticated_at = now() - interval '10 minutes' where user_id = (select id from users where handle = 'e2e-owner')`);46    const before = Number(sql(`select count(*) from invitations`));47    await page.getByTestId("invite-create").click();48    await page.getByTestId("invite-role").selectOption("viewer");49    await page.getByTestId("invite-submit").click();50    await expect(page.getByTestId("stepup-verify")).toBeVisible();51    await page.getByRole("dialog", { name: "Confirmez avec votre clé d'accès" }).getByRole("button", { name: "Annuler" }).click();52    await expect(page.getByTestId("invite-link")).toHaveCount(0);53    expect(Number(sql(`select count(*) from invitations`))).toBe(before);54    await page.keyboard.press("Escape");55  });5657  test("passkeys: add a second one, rename it, remove it; the last one is protected", async ({ browser }) => {58    // a second device of the same person: same session rights, but an authenticator that does not hold the first key59    const second = await signedIn(browser, "e2e-owner");60    await second.auth.cdp.send("WebAuthn.removeVirtualAuthenticator", { authenticatorId: second.auth.id });61    const fresh = await addAuthenticator(second.page);62    const { page } = second;63    await page.goto("/settings/security");64    await expect(page.getByTestId("screen-settings-security")).toBeVisible();65    await expect(page.getByTestId("passkey-row")).toHaveCount(1);66    await expect(page.getByTestId("passkey-row").first().getByTestId("passkey-remove")).toBeDisabled();6768    await page.getByTestId("passkey-add").click();69    const label = page.getByRole("dialog").getByRole("textbox").first();70    if (await label.isVisible().catch(() => false)) {71      await label.fill("E2E second key");72      await page.getByRole("dialog").getByRole("button", { name: /créer|ajouter|enregistrer/i }).last().click();73    }74    await expect(page.getByTestId("passkey-row")).toHaveCount(2);75    expect((await fresh.credentials()).length).toBe(1);7677    const added = page.getByTestId("passkey-row").filter({ hasText: "E2E second key" });78    await added.getByTestId("passkey-rename").click();79    await page.getByRole("dialog").getByRole("textbox").first().fill("E2E renamed key");80    await page.getByRole("dialog").getByRole("button", { name: /enregistrer|renommer/i }).last().click();81    const renamed = page.getByTestId("passkey-row").filter({ hasText: "E2E renamed key" });82    await expect(renamed).toHaveCount(1);8384    await renamed.getByTestId("passkey-remove").click();85    await page.getByRole("dialog").getByRole("button", { name: /retirer|supprimer/i }).last().click();86    await expect(page.getByTestId("passkey-row")).toHaveCount(1);87    await expect(page.getByTestId("passkey-row").first().getByTestId("passkey-remove")).toBeDisabled();88    // the server protects the last passkey too89    const status = await page.evaluate(async () => {90      const me = (await (await fetch("/api/v1/me")).json()) as { csrf_token: string };91      const keys = (await (await fetch("/api/v1/me/passkeys")).json()) as { items: { id: string }[] };92      return (await fetch(`/api/v1/me/passkeys/${keys.items[0]?.id}`, { method: "DELETE", headers: { "X-MCC-CSRF": me.csrf_token } })).status;93    });94    expect(status).toBe(409);95    second.problems.assertClean();96    await second.context.close();97  });9899  test("revoking a session signs that browser out on its next request", async ({ browser }) => {100    const other = await signedIn(browser, "e2e-owner");101    const otherSession = await other.page.evaluate(async () => ((await (await fetch("/api/v1/me")).json()) as { session: { id: string } }).session.id);102    const { page } = owner;103    await page.goto("/settings/security");104    const row = page.locator(`[data-testid="session-row"][data-session-id="${otherSession}"]`);105    await expect(row).toHaveAttribute("data-current", "false");106    await expect(page.locator('[data-testid="session-row"][data-current="true"]')).toHaveCount(1);107    await row.getByTestId("session-revoke").click();108    const confirm = page.getByRole("dialog").getByRole("button", { name: /révoquer/i }).last();109    if (await confirm.isVisible().catch(() => false)) await confirm.click();110    await expect(row).toHaveCount(0);111    // the revoked browser: its next API call is refused and the app returns to the sign-in page112    await other.page.goto("/nodes");113    await expect(other.page).toHaveURL(/\/signin/);114    expect(await other.page.evaluate(async () => (await fetch("/api/v1/me")).status)).toBe(401);115    other.problems.assertClean();116    await other.context.close();117  });118119  test("revoking a device signs that device out on its next request", async ({ browser }) => {120    const other = await signedIn(browser, "e2e-owner");121    const otherDevice = await other.page.evaluate(async () => ((await (await fetch("/api/v1/me")).json()) as { session: { device_id: string } }).session.device_id);122    const { page } = owner;123    await page.goto("/settings/security");124    const row = page.locator(`[data-testid="device-row"][data-device-id="${otherDevice}"]`);125    await expect(row).toHaveAttribute("data-current", "false");126    await row.getByTestId("device-revoke").click();127    const confirm = page.getByRole("dialog").getByRole("button", { name: /révoquer/i }).last();128    if (await confirm.isVisible().catch(() => false)) await confirm.click();129    await expect(page.locator(`[data-testid="device-row"][data-device-id="${otherDevice}"]:not([data-revoked="true"])`)).toHaveCount(0);130    // the revoked device keeps working only until its next request131    await other.page.getByRole("navigation", { name: "Navigation principale" }).getByRole("link", { name: "Nœuds" }).click();132    await expect(other.page).toHaveURL(/\/signin/);133    other.problems.assertClean();134    await other.context.close();135  });136137  test("language: switching to English persists across reloads and new sign-ins, then back to French", async ({ browser }) => {138    const { page } = owner;139    await page.goto("/settings");140    await page.getByTestId("settings-locale").selectOption("en");141    const save = page.getByTestId("settings-profile-save");142    if (await save.isVisible().catch(() => false)) await save.click();143    const nav = page.getByRole("navigation", { name: "Main navigation" });144    await expect(nav.getByRole("link", { name: "Overview" })).toBeVisible();145    await expect(page.locator("html")).toHaveAttribute("lang", "en");146    await page.reload();147    await expect(page.getByRole("navigation", { name: "Main navigation" }).getByRole("link", { name: "Maintenance" })).toBeVisible();148    expect(sql(`select locale from users where handle = 'e2e-owner'`)).toBe("en");149    // a browser that prefers French still gets English after sign-in: the profile wins150    const other = await signedIn(browser, "e2e-owner", { locale: "fr-CA" });151    await expect(other.page.getByRole("navigation", { name: "Main navigation" })).toBeVisible();152    await other.context.close();153154    await page.getByTestId("settings-locale").selectOption("fr");155    if (await save.isVisible().catch(() => false)) await save.click();156    await expect(page.getByRole("navigation", { name: "Navigation principale" }).getByRole("link", { name: "Vue d'ensemble" })).toBeVisible();157    await page.reload();158    await expect(page.locator("html")).toHaveAttribute("lang", "fr");159    expect(sql(`select locale from users where handle = 'e2e-owner'`)).toBe("fr");160  });161162  test("the sign-in page follows the browser language before sign-in and the switch is remembered", async ({ browser }) => {163    const en = await newClient(browser, { locale: "en-US", conditional: true });164    const p = await en.newPage();165    await p.goto("/signin");166    await expect(p.getByRole("heading", { name: "Sign in" })).toBeVisible();167    await p.getByTestId("public-locale").click();168    await expect(p.getByRole("heading", { name: "Connexion" })).toBeVisible();169    await p.reload();170    await expect(p.getByRole("heading", { name: "Connexion" })).toBeVisible();171    await en.close();172  });173174  test("rate limit on passkey ceremonies is enforced per client and explained on the sign-in page", async ({ browser }) => {175    const ctx = await newClient(browser); // its own client address: the other tests are not affected176    const p = await ctx.newPage();177    await p.goto("/signin");178    const statuses = await p.evaluate(async () => {179      const out: number[] = [];180      for (let i = 0; i < 40; i++) out.push((await fetch("/api/v1/auth/webauthn/authentication/begin", { method: "POST" })).status);181      return out;182    });183    expect(statuses[0]).toBe(200);184    expect(statuses).toContain(429);185    await p.getByTestId("signin-button").click();186    await expect(p.getByTestId("signin-error")).toContainText("Trop de tentatives");187    await ctx.close();188  });189190  test("no CSP violation and no console error", async () => {191    owner.problems.assertClean();192  });193});194
Files main
Menu

Theme