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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
84717804ae
commit
c9d1f4b340
@@ -79,6 +79,8 @@ export const DOORS: Door[] = [
|
||||
{ closedFor: ALL, method: 'POST', name: 'the mail service cannot be disconnected', path: '/api/iapl/mail-relay/disconnect' },
|
||||
{ closedFor: ALL, method: 'POST', name: 'the confirm route answers 404 without a nonce of this site', path: '/api/iapl/mail-relay/confirm', body: { nonce: 'n'.repeat(40), state: 'active', token: `ims_${'a'.repeat(43)}` }, closed: notFound },
|
||||
{ body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be reset', path: '/api/ipal/two-factor/reset' },
|
||||
{ body: { userId: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s waiting 2FA set-up cannot be confirmed (1.18.0)', path: '/api/iapl/two-factor/confirm-pending' },
|
||||
{ body: 'u=1&t=' + 'x'.repeat(43), closedFor: ['anonymous'], headers: { 'content-type': 'application/x-www-form-urlencoded' }, method: 'POST', name: 'a made-up 2FA confirmation link turns nothing on (1.18.0)', path: '/api/iapl/two-factor/confirm', closed: ({ status }) => status === 400 || status === 403 },
|
||||
// payload-2fa refuses with HTTP 200 and `{ ok: false }` (its own convention), so the body is what is judged
|
||||
{ body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be removed (payload-2fa)', path: '/api/admin/remove-user-totp', closed: refusedOrNotOk },
|
||||
{ body: { id: NO_ID }, closedFor: ALL, method: 'POST', name: 'another account\'s 2FA cannot be reset (payload-2fa)', path: '/api/admin/reset-user-totp', closed: refusedOrNotOk },
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { SinkMessage } from './smtp-sink'
|
||||
|
||||
/**
|
||||
* twoFactor.confirmByEmail (IAPL 1.18.0, on by default): the first set-up of two-step verification waits for a link
|
||||
* sent to the account's e-mail. The specs read that link from the mail sink (e2e/smtp-sink.ts; create-test-admin.ts
|
||||
* points the site's SMTP at it).
|
||||
*/
|
||||
|
||||
/** A raw message body as text: quoted-printable soft breaks and escapes undone. */
|
||||
export const decodeMail = (raw: string): string =>
|
||||
raw.replace(/=\r?\n/g, '').replace(/=([0-9A-F]{2})/g, (_, hex: string) => String.fromCharCode(parseInt(hex, 16)))
|
||||
|
||||
/** The confirmation link of the latest message to `email`, or null. */
|
||||
export function enrolmentLink(messages: SinkMessage[], email: string): null | URL {
|
||||
for (const message of [...messages].reverse()) {
|
||||
if (!message.to.some((to) => to.toLowerCase().includes(email.toLowerCase()))) {continue}
|
||||
const found = decodeMail(message.data).match(/https?:\/\/[^\s"<>]+\/two-factor\/confirm\?u=[^\s"<>&]+&(?:amp;)?t=[\w-]+/)
|
||||
if (found) {return new URL(found[0].replace('&', '&'))}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Waits until a message with the confirmation link for `email` arrives (mail goes out right after the request). */
|
||||
export async function waitForEnrolmentLink(messages: SinkMessage[], email: string, timeoutMs = 10_000): Promise<URL> {
|
||||
const until = Date.now() + timeoutMs
|
||||
for (;;) {
|
||||
const link = enrolmentLink(messages, email)
|
||||
if (link) {return link}
|
||||
if (Date.now() > until) {throw new Error(`no confirmation e-mail for ${email} in the mail sink`)}
|
||||
await new Promise((r) => setTimeout(r, 200))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
import { waitForEnrolmentLink } from './enrolment'
|
||||
import { startSmtpSink } from './smtp-sink'
|
||||
import { totp } from './totp'
|
||||
|
||||
/**
|
||||
@@ -28,7 +30,16 @@ test('own account: a new e-mail needs the current password, in the panel', async
|
||||
await admin.dispose()
|
||||
const own = await playwright.request.newContext({ baseURL, extraHTTPHeaders: { origin: baseURL! } })
|
||||
expect((await own.post('/api/users/login', { data: { email, password } })).status()).toBe(200)
|
||||
expect((await (await own.post('/api/setup-totp', { data: { secret: SECRET, token: totp(SECRET) } })).json()).ok).toBe(true)
|
||||
// the first set-up waits for its e-mail link (twoFactor.confirmByEmail): read it from the mail sink, confirm it here
|
||||
const sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
|
||||
try {
|
||||
expect((await (await own.post('/api/setup-totp', { data: { secret: SECRET, token: totp(SECRET) } })).json()).pending).toBe(true)
|
||||
const link = await waitForEnrolmentLink(sink.messages, email)
|
||||
const done = await own.post('/api/iapl/two-factor/confirm', { form: { t: link.searchParams.get('t')!, u: link.searchParams.get('u')! } })
|
||||
expect(done.status()).toBe(200)
|
||||
} finally {
|
||||
await sink.close()
|
||||
}
|
||||
await own.dispose()
|
||||
|
||||
const context = await browser.newContext({ baseURL })
|
||||
|
||||
@@ -77,6 +77,7 @@
|
||||
"GET /api/globals/site-settings/versions": "versions: readVersions = read (anyone (brand, homepage, construction mode)); no version history kept here",
|
||||
"GET /api/globals/site-settings/versions/:id": "versionByID: readVersions = read (anyone (brand, homepage, construction mode)); no version history kept here",
|
||||
"GET /api/iapl/mail-relay/status": "mail service status in the panel: admin",
|
||||
"GET /api/iapl/two-factor/confirm": "public by design: the e-mailed 2FA confirmation link's page (twoFactor.confirmByEmail); shows one button, changes nothing; 400 without a valid waiting set-up",
|
||||
"GET /api/ipal/admin-icon": "public by design: the panel's favicon (white-label)",
|
||||
"GET /api/ipal/admin-language": "public by design: the sign-in panel's language links (whiteLabel.signIn); writes Payload's payload-lng cookie for a supported language and 303s to a path inside the admin route; 400 otherwise",
|
||||
"GET /api/ipal/admin-og": "public by design: the panel's link-preview image",
|
||||
@@ -197,6 +198,8 @@
|
||||
"POST /api/iapl/mail-relay/confirm": "public by design: the mail service's call-back; 404 unless it carries a nonce this site made in the last 5 min (single use)",
|
||||
"POST /api/iapl/mail-relay/connect": "mail service, connect with a pasted token: admin",
|
||||
"POST /api/iapl/mail-relay/disconnect": "mail service, disconnect: admin",
|
||||
"POST /api/iapl/two-factor/confirm": "public by design: the link's button; own origin, the single-use 30-min token AND the enrolling browser's cookie; turns the factor on, ends the account's sessions, signs nobody in",
|
||||
"POST /api/iapl/two-factor/confirm-pending": "2FA: an admin signed in with the second factor confirms another account's waiting set-up (mail not working); own origin",
|
||||
"POST /api/ipal/consent": "public by design: a visitor's own banner choice (random id, no personal data), body capped at 4 KiB",
|
||||
"POST /api/ipal/cookie-approval": "approve cookies: editor+ with the second factor",
|
||||
"POST /api/ipal/cookie-crawl": "start a crawl: editor+, or Bearer IAPL_COOKIE_SCAN_TOKEN (the schedule); only of the configured site URL",
|
||||
|
||||
@@ -74,17 +74,15 @@ test('2FA screens: a prepared back link ends on the admin root', async ({ baseUR
|
||||
await third.goto(`/admin/setup-totp?back=${encodeURIComponent(SCRIPT)}`)
|
||||
const newSecret = await third.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v)))
|
||||
expect(newSecret).toBeTruthy()
|
||||
// twoFactor.confirmByEmail (1.18.0): a FIRST set-up waits for its e-mail link, so the setup screen does not
|
||||
// navigate at all — the script in `back` cannot run, the screen stays. (`back` after setup matters only with
|
||||
// confirmByEmail: false; test/safeBack.test.ts covers the check itself.)
|
||||
await enterCode(third, totp(newSecret!))
|
||||
await expectAdminRoot(third, baseURL!)
|
||||
await expect(third.locator('[data-sonner-toast]').first()).toBeVisible({ timeout: 15_000 })
|
||||
await expect(third).toHaveURL(/\/admin\/setup-totp/)
|
||||
expect(await third.title()).not.toContain('XSS-')
|
||||
await third.context().close()
|
||||
|
||||
// setup screen, an ordinary link back into the panel is still followed
|
||||
const fourth = await passwordOnly(browser, baseURL!, fresh[1])
|
||||
await fourth.goto(`/admin/setup-totp?back=${encodeURIComponent('/admin/collections/pages?limit=5')}`)
|
||||
const fourthSecret = await fourth.locator('input[type="hidden"]').evaluateAll((inputs) => inputs.map((i) => (i as HTMLInputElement).value).find((v) => /^[A-Z2-7]{16,}$/.test(v)))
|
||||
await enterCode(fourth, totp(fourthSecret!))
|
||||
await expect(fourth).toHaveURL(/\/admin\/collections\/pages\?limit=5$/, { timeout: 20_000 })
|
||||
await fourth.context().close()
|
||||
void fresh[1]
|
||||
} finally {
|
||||
for (const id of ids) {await first.request.delete(`/api/users/${id}`, { headers: { origin: baseURL! } })}
|
||||
await first.context().close()
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
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()
|
||||
}
|
||||
})
|
||||
@@ -1,10 +1,12 @@
|
||||
import { type APIRequestContext, expect, type Page, test } from '@playwright/test'
|
||||
|
||||
import { waitForEnrolmentLink } from './enrolment'
|
||||
import { startSmtpSink } from './smtp-sink'
|
||||
import { secondTestAdmin, totp } from './totp'
|
||||
|
||||
/**
|
||||
* "2FA setup required" in a real browser: an account that has not set two-step verification up sees only the setup
|
||||
* screen and gets nothing from the API; after the code it is in. Covers the first admin of a fresh site (only when
|
||||
* screen and gets nothing from the API; after the code and the e-mailed link (twoFactor.confirmByEmail) it is in. Covers the first admin of a fresh site (only when
|
||||
* the database has no users yet — run this file before e2e/create-test-admin.ts for that), a new editor, and the
|
||||
* administrator's reset on the account page.
|
||||
* E2E_BASE_URL=http://localhost:3217 pnpm exec playwright test e2e/two-factor-setup.spec.ts
|
||||
@@ -43,7 +45,7 @@ async function adminApi(playwright: { request: { newContext: (o: object) => Prom
|
||||
return api
|
||||
}
|
||||
|
||||
test('first admin of a fresh site: created, sent to 2FA setup, in after the code', async ({ baseURL, page }) => {
|
||||
test('first admin of a fresh site: created, sent to 2FA setup; with no mail yet the set-up waits for the link in the server log', async ({ baseURL, page }) => {
|
||||
// With users in the database this address leads to the login screen instead.
|
||||
await page.goto('/admin/create-first-user')
|
||||
const firstUserForm = await page.locator('#field-confirm-password').waitFor({ timeout: 10_000 }).then(() => true, () => false)
|
||||
@@ -65,9 +67,10 @@ test('first admin of a fresh site: created, sent to 2FA setup, in after the code
|
||||
}
|
||||
const secret = await page.locator('input[name="secret"]').inputValue()
|
||||
await typeCode(page, secret)
|
||||
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
|
||||
expect((await page.request.get('/api/globals/site-integrations', { headers: { origin: baseURL! } })).status()).toBe(200)
|
||||
admin = { ...OWNER, secret }
|
||||
// twoFactor.confirmByEmail: a fresh site has no mail yet, so the set-up waits and its link is in the server log
|
||||
// (the person who set the site up opens it there); nothing opens before that
|
||||
await expect(page.locator('[data-sonner-toast]').first()).toContainText(/administrator|log/i, { timeout: 15_000 })
|
||||
expect((await page.request.get('/api/globals/site-integrations', { headers: { origin: baseURL! } })).status()).toBe(403)
|
||||
})
|
||||
|
||||
test('a new editor: setup screen with the deadline, nothing else, in after the code', async ({ baseURL, page, playwright }) => {
|
||||
@@ -95,9 +98,22 @@ test('a new editor: setup screen with the deadline, nothing else, in after the c
|
||||
await page.waitForURL(/setup-totp/)
|
||||
|
||||
const secret = await page.locator('input[name="secret"]').inputValue()
|
||||
// twoFactor.confirmByEmail: the code starts the set-up, the e-mailed link (opened in this browser) finishes it
|
||||
const sink = await startSmtpSink(Number(process.env.E2E_SMTP_PORT ?? 2526))
|
||||
try {
|
||||
await typeCode(page, secret)
|
||||
const link = await waitForEnrolmentLink(sink.messages, EDITOR.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/)
|
||||
} finally {
|
||||
await sink.close()
|
||||
}
|
||||
// signed out by the confirmation: password and code, then the data opens
|
||||
await signIn(page, EDITOR)
|
||||
await page.waitForURL(/verify-totp/, { waitUntil: 'commit' })
|
||||
await typeCode(page, secret)
|
||||
// back where it wanted to go, and the data opens
|
||||
await page.waitForURL(/\/admin\/collections\/pages/, { timeout: 20_000 })
|
||||
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
|
||||
expect((await page.request.get('/api/pages', { headers: { origin: baseURL! } })).status()).toBe(200)
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user