Accounts: Playwright on the real pages; interaction cookie path fix
The interaction address is now /api/v2/interaction/<uid> (redirecting to the sign-in page): oidc-provider scopes its cookie to that path, so every step's API call gets it. Before, a real browser never sent it and every sign-in 'expired'; the test browser now honours cookie paths too. 8 Playwright tests (deep link, wrong password, foreign return address, sign-up, reset mid-sign-in, 2FA set-up, account page, admin) on the real backend with an in-memory database, no Postgres needed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
test-results/
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"private": true,
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* The e2e backend (playwright.config.ts): Accounts on port 5210 with the in-memory database from the
|
||||
* backend tests (no Postgres needed), and a test product on 5211 that signs people in through it
|
||||
* with @crosscode/auth-client, as the Website will. The pages run with `next dev` on 3210 and send
|
||||
* /api here.
|
||||
*
|
||||
* Test helpers on the product: GET /test/code?to=<email or phone> (the last code sent),
|
||||
* GET /test/link?to=<email> (the last link sent), GET /test/totp?secret=… (the current app code).
|
||||
*/
|
||||
import http from 'node:http';
|
||||
import { accountsClient } from '@crosscode/auth-client';
|
||||
import { ed25519PublicToPem, generateEd25519, newLinkSecret } from '@crosscode/contracts/signing';
|
||||
import { createApp } from '../backend/src/app.js';
|
||||
import { createCtx } from '../backend/src/context.js';
|
||||
import { loadConfig } from '../backend/src/lib/config.js';
|
||||
import { MemoryMessenger } from '../backend/src/lib/messages.js';
|
||||
import { hashPassword } from '../backend/src/lib/passwords.js';
|
||||
import { codeAt } from '../backend/src/lib/totp.js';
|
||||
import { createProvider } from '../backend/src/oidc/provider.js';
|
||||
import { memoryDb } from '../backend/tests/support/memoryDb.js';
|
||||
|
||||
const WEB = 'http://localhost:3210';
|
||||
const PRODUCT = 'http://localhost:5211';
|
||||
const PRODUCT_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
|
||||
|
||||
const db = memoryDb();
|
||||
const messenger = new MemoryMessenger();
|
||||
// Behind Next's rewrite (as behind nginx in production): the public host comes in X-Forwarded-Host.
|
||||
const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger });
|
||||
await ctx.settings.setMany({
|
||||
hub_install_id: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
|
||||
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
|
||||
});
|
||||
const linkSecret = newLinkSecret();
|
||||
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
|
||||
const seed = (email: string, extra: Record<string, unknown> = {}) => hashPassword('Correct-horse-1').then((passwordHash) =>
|
||||
db.account.create({ data: { name: 'Thandi Test', email, emailVerified: true, noticeVersionAccepted: 1, newsAskedAt: new Date(), passwordHash, ...extra } }));
|
||||
await seed('thandi@hope.test');
|
||||
await seed('admin@hope.test', { name: 'Ada Admin', role: 'admin' });
|
||||
|
||||
const provider = await createProvider(ctx);
|
||||
http.createServer(createApp(ctx, provider)).listen(5210, '127.0.0.1', () => console.log('[e2e] Accounts on 5210'));
|
||||
|
||||
// ─── The test product ────────────────────────────────────────────────────────
|
||||
|
||||
// Made on the first sign-in: the pages (and so discovery through them) start after this server.
|
||||
let authP: ReturnType<typeof accountsClient> | null = null;
|
||||
const getAuth = () => (authP ??= accountsClient({ accountsUrl: WEB, productUrl: PRODUCT, clientId: PRODUCT_ID, linkSecret, allowInsecure: true }));
|
||||
const cookieOf = (req: http.IncomingMessage, name: string) => String(req.headers.cookie ?? '').split(';').map((c) => c.trim().split('=')).find(([k]) => k === name)?.[1];
|
||||
|
||||
http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url ?? '/', PRODUCT);
|
||||
const send = (status: number, body: string, type = 'text/html') => res.writeHead(status, { 'content-type': type }).end(body);
|
||||
try {
|
||||
if (url.pathname === '/start') {
|
||||
const { url: to, cookie } = await (await getAuth()).startSignIn(url.searchParams.get('returnTo') ?? '/', { requireTwoFactor: url.searchParams.get('mfa') === '1' });
|
||||
res.writeHead(302, { location: to, 'set-cookie': `signin=${cookie}; Path=/; HttpOnly; SameSite=Lax` }).end();
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/api/auth/callback') {
|
||||
const r = await (await getAuth()).finishSignIn(url, cookieOf(req, 'signin'));
|
||||
send(200, `<!doctype html><title>Product</title><h1>Signed in to the product</h1><p id="email">${r.claims.email}</p><p id="return">${r.returnTo}</p><p id="amr">${r.claims.amr.join(' ')}</p>`);
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/test/code') return send(200, messenger.lastCode(url.searchParams.get('to') ?? '') ?? '', 'text/plain');
|
||||
if (url.pathname === '/test/link') return send(200, messenger.lastLink(url.searchParams.get('to') ?? '') ?? '', 'text/plain');
|
||||
if (url.pathname === '/test/totp') return send(200, codeAt(url.searchParams.get('secret') ?? '', Math.floor(Date.now() / 30000)), 'text/plain');
|
||||
if (req.method === 'POST') return send(200, '{}', 'application/json');
|
||||
send(200, '<!doctype html><title>Product home</title><h1>Product home</h1>');
|
||||
} catch (e) {
|
||||
send(500, `<pre>${String((e as Error).message)}</pre>`);
|
||||
}
|
||||
}).listen(5211, '127.0.0.1', () => console.log('[e2e] Test product on 5211'));
|
||||
@@ -0,0 +1,103 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
|
||||
// The release checks (ROADMAP-v3 §9) on Accounts' real pages: signing in from a deep link lands
|
||||
// back on that page, through sign-up, a password reset and two-step sign-in set up on the way; a
|
||||
// foreign return address is refused. A test product (e2e/server.ts) starts and finishes sign-ins.
|
||||
const PRODUCT = "http://localhost:5211";
|
||||
const helper = async (page: Page, path: string) => (await (await page.request.get(`${PRODUCT}${path}`)).text()).trim();
|
||||
|
||||
async function signIn(page: Page, email: string, password = "Correct-horse-1") {
|
||||
await page.getByLabel("Email address").fill(email);
|
||||
await page.getByLabel("Password").fill(password);
|
||||
await page.getByRole("button", { name: "Sign in" }).click();
|
||||
}
|
||||
|
||||
test("signing in from a deep link returns to that exact page", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("/events/youth-camp/register?ticket=adult")}`);
|
||||
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
|
||||
await signIn(page, "thandi@hope.test");
|
||||
await expect(page.locator("#return")).toHaveText("/events/youth-camp/register?ticket=adult");
|
||||
await expect(page.locator("#email")).toHaveText("thandi@hope.test");
|
||||
});
|
||||
|
||||
test("a wrong password says so without saying whether the account exists", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=/`);
|
||||
await signIn(page, "thandi@hope.test", "not-the-password");
|
||||
await expect(page.locator("main").getByRole("alert")).toHaveText("That email address and password don't match.");
|
||||
await signIn(page, "nobody@hope.test", "not-the-password");
|
||||
await expect(page.locator("main").getByRole("alert")).toHaveText("That email address and password don't match.");
|
||||
});
|
||||
|
||||
test("a foreign return address ends on the product's home page", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("//evil.example/steal")}`);
|
||||
await signIn(page, "thandi@hope.test");
|
||||
await expect(page.locator("#return")).toHaveText("/");
|
||||
});
|
||||
|
||||
test("sign-up with an emailed code, back to the page", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("/give?fund=building")}`);
|
||||
await page.getByRole("button", { name: "Create an account" }).click();
|
||||
await page.getByLabel("Your name").fill("New Person");
|
||||
await page.getByLabel("Email address").fill("new@hope.test");
|
||||
await page.getByLabel("Password").fill("Correct-horse-2");
|
||||
await page.getByLabel(/privacy notice/).check();
|
||||
await page.getByRole("button", { name: "Create account" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Check your email" })).toBeVisible();
|
||||
await page.getByLabel("Code").fill(await helper(page, "/test/code?to=new@hope.test"));
|
||||
await page.getByRole("button", { name: "Continue" }).click();
|
||||
await expect(page.locator("#return")).toHaveText("/give?fund=building");
|
||||
await expect(page.locator("#email")).toHaveText("new@hope.test");
|
||||
});
|
||||
|
||||
test("forgot password in the middle of signing in still returns to the page", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=/my-tickets`);
|
||||
await page.getByRole("link", { name: "Forgot your password?" }).click();
|
||||
await page.getByLabel("Email address").fill("thandi@hope.test");
|
||||
await page.getByRole("button", { name: "Send the link" }).click();
|
||||
await expect(page.getByRole("status")).toContainText("a link is on its way");
|
||||
await page.goto(await helper(page, "/test/link?to=thandi@hope.test"));
|
||||
await page.getByLabel("New password").fill("Correct-horse-1");
|
||||
await page.getByRole("button", { name: "Save and sign in" }).click();
|
||||
await signIn(page, "thandi@hope.test");
|
||||
await expect(page.locator("#return")).toHaveText("/my-tickets");
|
||||
});
|
||||
|
||||
test("a product asking for two-step sign-in: set up with an app, recovery codes, then back", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?mfa=1&returnTo=/dashboard`);
|
||||
await signIn(page, "thandi@hope.test");
|
||||
await expect(page.getByRole("heading", { name: "Set up two-step sign-in" })).toBeVisible();
|
||||
await page.getByRole("button", { name: /An authenticator app/ }).click();
|
||||
const key = (await page.getByText(/Or type this key:/).innerText()).replace(/.*:\s*/, "").trim();
|
||||
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
|
||||
await page.getByRole("button", { name: "Turn on" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Save your recovery codes" })).toBeVisible();
|
||||
await page.getByRole("button", { name: "I've saved them" }).click();
|
||||
await expect(page.locator("#return")).toHaveText("/dashboard");
|
||||
await expect(page.locator("#amr")).toHaveText("pwd otp mfa");
|
||||
});
|
||||
|
||||
test("the account page: signs in first, then saves details", async ({ page }) => {
|
||||
await page.goto("/account");
|
||||
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
|
||||
await page.getByLabel("Email address").fill("new@hope.test");
|
||||
await page.getByLabel("Password").fill("Correct-horse-2");
|
||||
await page.getByRole("button", { name: "Sign in" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Your account" })).toBeVisible();
|
||||
await page.getByLabel("Name").fill("New Person-Smith");
|
||||
await page.getByRole("button", { name: "Save", exact: true }).click();
|
||||
await expect(page.getByRole("status")).toContainText("Your details are saved");
|
||||
});
|
||||
|
||||
test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
|
||||
await page.goto("/admin");
|
||||
await signIn(page, "admin@hope.test");
|
||||
await expect(page.getByRole("heading", { name: "Set up two-step sign-in" })).toBeVisible();
|
||||
await expect(page.getByText("Admins must use a second step")).toBeVisible();
|
||||
await page.getByRole("button", { name: /An authenticator app/ }).click();
|
||||
const key = (await page.getByText(/Or type this key:/).innerText()).replace(/.*:\s*/, "").trim();
|
||||
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
|
||||
await page.getByRole("button", { name: "Turn on" }).click();
|
||||
await page.getByRole("button", { name: "I've saved them" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Accounts admin" })).toBeVisible();
|
||||
await expect(page.getByText("thandi@hope.test")).toBeVisible();
|
||||
});
|
||||
Reference in New Issue
Block a user