Files
ipal-kit/reference/e2e/two-factor-enrolment.spec.ts
T
Radosław SmolińskiandClaude Opus 5.5 c9d1f4b340 2FA: the first set-up is confirmed by e-mail (twoFactor.confirmByEmail, 1.18.0)
Security audit 2026-12, F0: inside an account's setup window its password alone
enrolled an authenticator of the caller's choosing; the owner was locked out.

- /setup-totp for an account without a factor: IAPL checks the code, keeps the
  secret pending (payload-kv), mails a single-use 30-min link to the account and
  ties it to the enrolling browser; the package's handler (and its -totp cookie)
  is never used for a first enrolment
- GET /api/iapl/two-factor/confirm = a page with one button; POST confirms
  (own origin, same browser), ends the account's sessions, signs nobody in
- notice mails on every enrolment, change, removal / reset (any path)
- mail not working: link to the server log, admin confirms on the account page
  (POST /api/iapl/two-factor/confirm-pending), doctor rule 2fa-enrolment-mail
- options and opt-out (confirmByEmail: false), building blocks exported
- tests: HTTP suite on SQLite, MongoDB, Postgres; built-site spec in e2e:built;
  closed doors and judged routes; docs, AGENT.md, skills, changelog

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 13:37:39 +01:00

124 lines
6.5 KiB
TypeScript

import { type APIRequestContext, expect, type Page, test } from '@playwright/test'
import { waitForEnrolmentLink } from './enrolment'
import { startSmtpSink } from './smtp-sink'
import { secondTestAdmin, totp } from './totp'
/**
* twoFactor.confirmByEmail on the BUILT site (pnpm e2e:built, webpack and Turbopack; security audit 2026-12, F0).
* Before 1.18.0 the password of an account inside its setup window was enough to enrol a factor of one's own — the
* owner was then locked out. Now the first set-up waits for a link sent to the account's e-mail (read here from the
* mail sink), opened in the browser that scanned the code.
*/
test.describe.configure({ mode: 'serial' })
const stamp = Date.now()
const VICTIM = { email: `e2e-enrol-${stamp}@example.com`, password: `enrol-${stamp}-Hk29dLq` }
const ATTACKER_SECRET = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
let sink: Awaited<ReturnType<typeof startSmtpSink>>
let victimId: string | undefined
type Ctx = { request: { newContext: (o: object) => Promise<APIRequestContext> } }
const ctx = (playwright: Ctx, baseURL: string) => playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL } })
async function adminApi(playwright: Ctx, baseURL: string) {
const api = await ctx(playwright, baseURL)
expect((await api.post('/api/users/login', { data: { email: secondTestAdmin(process.env.E2E_ADMIN_EMAIL!), password: process.env.E2E_ADMIN_PASSWORD } })).status()).toBe(200)
expect((await (await api.post('/api/verify-totp', { data: { token: totp(process.env.E2E_TOTP_SECRET!) } })).json()).ok).toBe(true)
return api
}
async function typeCode(page: Page, secret: string) {
await page.getByRole('textbox').first().click()
await page.keyboard.type(totp(secret))
}
test.beforeAll(async () => {
sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
})
test.afterAll(async ({ baseURL, playwright }) => {
await sink?.close()
if (victimId && process.env.E2E_ADMIN_EMAIL) {
const api = await adminApi(playwright, baseURL!)
await api.delete(`/api/users/${victimId}`)
await api.dispose()
}
})
test('2FA enrolment: the password alone no longer takes an account inside its setup window', async ({ baseURL, playwright }) => {
test.skip(!process.env.E2E_ADMIN_EMAIL || !process.env.E2E_ADMIN_PASSWORD || !process.env.E2E_TOTP_SECRET, 'E2E_* test admin not configured')
const admin = await adminApi(playwright, baseURL!)
const created = await admin.post('/api/users', { data: { ...VICTIM, roles: ['editor'] } })
expect(created.status()).toBe(201)
victimId = String((await created.json()).doc.id)
await admin.dispose()
const attacker = await ctx(playwright, baseURL!)
expect((await attacker.post('/api/users/login', { data: VICTIM })).status()).toBe(200)
const setup = await attacker.post('/api/setup-totp', { data: { secret: ATTACKER_SECRET, token: totp(ATTACKER_SECRET) } })
expect(setup.status()).toBe(202)
expect(await setup.json()).toMatchObject({ ok: false, pending: true })
// not signed in with a factor, nothing opens
expect(((await (await attacker.get('/api/users/me')).json()) as { user?: { _strategy?: string } }).user?._strategy).not.toBe('totp')
expect((await attacker.post('/api/globals/site-settings', { data: {} })).status()).toBe(403)
// the link went to the OWNER's mailbox; opened in the owner's own browser it is refused
const link = await waitForEnrolmentLink(sink.messages, VICTIM.email)
expect(link.origin).toBe(new URL(baseURL!).origin)
const owner = await ctx(playwright, baseURL!)
const page = await owner.get(link.pathname + link.search)
expect(page.status()).toBe(200)
expect(await page.text()).toContain('<form method="post"')
const refused = await owner.post('/api/iapl/two-factor/confirm', { form: { t: link.searchParams.get('t')!, u: link.searchParams.get('u')! } })
expect(refused.status()).toBe(403)
// the owner can still set up their own factor
expect((await owner.post('/api/users/login', { data: VICTIM })).status()).toBe(200)
const ownSetup = await owner.post('/api/setup-totp', { data: { secret: 'KRSXG5CTMVRXEZLUKRSXG5CTMVRXEZLU', token: totp('KRSXG5CTMVRXEZLUKRSXG5CTMVRXEZLU') } })
expect(ownSetup.status()).toBe(202)
await attacker.dispose()
await owner.dispose()
})
test('2FA enrolment in the panel: code, the notice on the setup screen, the e-mail link, sign in again, in', async ({ baseURL, browser, playwright }) => {
test.skip(!process.env.E2E_ADMIN_EMAIL, 'E2E_* test admin not configured')
const person = { email: `e2e-enrol-ui-${stamp}@example.com`, password: `enrolui-${stamp}-Pz71mWx` }
const admin = await adminApi(playwright, baseURL!)
const created = await admin.post('/api/users', { data: { ...person, roles: ['editor'] } })
expect(created.status()).toBe(201)
const id = String((await created.json()).doc.id)
const context = await browser.newContext({ baseURL })
const page = await context.newPage()
try {
await page.goto('/admin/login')
await page.fill('#field-email', person.email)
await page.fill('#field-password', person.password)
await page.click('.form-submit button')
await page.waitForURL(/setup-totp/)
const secret = await page.locator('input[name="secret"]').inputValue()
await typeCode(page, secret)
// the package's form shows the answer; the screen stays, and after a reload names where the link went
await expect(page.locator('[data-sonner-toast]').first()).toContainText(/e…@example\.com/, { timeout: 15_000 })
await page.reload()
await expect(page.locator('[data-iapl="two-factor-pending"]')).toContainText(/e…@example\.com/)
// the link, in this browser: a page with one button, then done
const link = await waitForEnrolmentLink(sink.messages, person.email)
await page.goto(link.toString())
await page.getByRole('button').click()
await expect(page.locator('body')).toContainText(/Two-step verification is on|Weryfikacja dwuetapowa jest włączona/)
// signed out: password, then the code
await page.goto('/admin/login')
await page.fill('#field-email', person.email)
await page.fill('#field-password', person.password)
await page.click('.form-submit button')
await page.waitForURL(/verify-totp/, { waitUntil: 'commit' })
await typeCode(page, secret)
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
// notices: the confirmation mail, then "turned on"
expect(sink.messages.filter((m) => m.to.some((to) => to.includes(person.email))).length).toBeGreaterThanOrEqual(2)
} finally {
await context.close()
await admin.delete(`/api/users/${id}`)
await admin.dispose()
}
})