2FA setup required: an account without TOTP reaches only setup, within a 72 h window
twoFactor.requireSetup (on by default with 2FA): an account of the 2FA collection that has not set TOTP up is refused by ipal-kit's second-factor check on every collection, global and plugin endpoint; the setup screen and /api/setup-totp are all it reaches. It has 72 hours from its creation or from an admin's reset (field totpSetupFrom, stamped by a hook); after that setup is refused too until an admin reopens it. Accounts that existed before get their window at the first start after the upgrade (backfill in onInit), so nobody is blocked when a site upgrades. Admin side: status and reset / 'Reopen setup' button on the account page (TwoFactorStatusField), POST /api/ipal/two-factor/reset, a dashboard notice (TwoFactorAlert), a notice on the setup screen; texts in English and Polish. ipal-doctor reports blocked accounts and a switched-off mode. Overridable: requireSetup false, windowHours (false / 0 = none), exempt for a service account, resetAccess; the per-entity second-factor opt-out applies. API keys, seeds, bearer-token routes and sites with twoFactor false are not affected. HTTP tests (REST, GraphQL, first admin on an empty database) run on SQLite, Postgres and MongoDB; a browser test on the reference site covers the first admin, a new editor and the admin's reset. Docs, guide, skills, changelog. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
45d52c4690
commit
2aaaaa115a
@@ -283,14 +283,6 @@ describe('what must keep working', () => {
|
||||
expect((out.data?.SiteIntegration as { smtpPassword: string }).smtpPassword).toBe('S3CRET')
|
||||
})
|
||||
|
||||
test('an account that has not set TOTP up yet can still do so', async () => {
|
||||
// The package lets such an account through until TOTP is set up (the setup screen needs it).
|
||||
expect((await api('/users/me', sessions.newcomer)).status).toBe(200)
|
||||
const setup = await api('/setup-totp', sessions.newcomer, { body: JSON.stringify({ secret: TOTP_SECRET, token: totp(TOTP_SECRET) }), method: 'POST' })
|
||||
expect(setup.status).toBe(200)
|
||||
expect(((await setup.json()) as { ok: boolean }).ok).toBe(true)
|
||||
})
|
||||
|
||||
test('anonymous visitors still read the public globals and forms', async () => {
|
||||
for (const p of ['/globals/site-settings', '/globals/notifications', '/globals/cookie-settings', '/forms']) {
|
||||
expect([p, (await api(p, sessions.anonymous)).status]).toEqual([p, 200])
|
||||
@@ -475,6 +467,97 @@ describe('the code cannot be guessed: verify attempts are limited per account',
|
||||
})
|
||||
})
|
||||
|
||||
// Uses the account `[email protected]` (admin role, TOTP never set up). Order matters inside this block.
|
||||
describe('2FA setup required: an account without TOTP reaches nothing but setup', () => {
|
||||
const NEW_SECRET = 'MFRGGZDFMZTWQ2LK'
|
||||
const idOf = async (email: string) => (await payload.find({ collection: 'users' as never, where: { email: { equals: email } } })).docs[0].id
|
||||
const setup = (session: Session) => api('/setup-totp', session, { body: JSON.stringify({ secret: NEW_SECRET, token: totp(NEW_SECRET) }), method: 'POST' })
|
||||
|
||||
test('REST: every collection and global is refused, for reading and for writing', async () => {
|
||||
const open: string[] = []
|
||||
for (const [kind, slugs] of [['collection', [...pluginCollections, 'pages']], ['global', pluginGlobals]] as const) {
|
||||
for (const slug of slugs) {
|
||||
if ((await readStatus(kind, slug, sessions.newcomer)) !== 403) {open.push(`read ${kind} ${slug}`)}
|
||||
if ((await writeStatus(kind, slug, sessions.newcomer)) !== 403) {open.push(`write ${kind} ${slug}`)}
|
||||
}
|
||||
}
|
||||
expect(open).toEqual([])
|
||||
const integrations = await api('/globals/site-integrations', sessions.newcomer)
|
||||
expect(await integrations.text()).not.toContain('S3CRET')
|
||||
})
|
||||
|
||||
test('GraphQL and the staff endpoints refuse too', async () => {
|
||||
for (const query of ['{ SiteIntegration { smtpPassword } }', '{ FormSubmissions { totalDocs } }', '{ Users { totalDocs } }', 'mutation { updateSiteSetting(data: { siteName: "x" }) { siteName } }']) {
|
||||
const out = await gql(sessions.newcomer, query)
|
||||
expect(out.errors?.length, `${query} → ${JSON.stringify(out)}`).toBeGreaterThan(0)
|
||||
expect(JSON.stringify(out)).not.toContain('S3CRET')
|
||||
}
|
||||
expect((await api('/ipal/test-email', sessions.newcomer, { body: '{}', method: 'POST' })).status).toBe(403)
|
||||
expect((await api('/ipal/cookie-scan', sessions.newcomer)).status).toBe(403)
|
||||
expect((await api('/ipal/two-factor/reset', sessions.newcomer, { body: JSON.stringify({ userId: await idOf('[email protected]') }), method: 'POST' })).status).toBe(403)
|
||||
})
|
||||
|
||||
test('the window start is stamped at creation and cannot be written through the API', async () => {
|
||||
const id = await idOf('[email protected]')
|
||||
const doc = (await payload.findByID({ id, collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
|
||||
expect(Date.now() - new Date(doc.totpSetupFrom!).getTime()).toBeLessThan(120_000)
|
||||
const patch = await api(`/users/${id}`, sessions.verified, { body: JSON.stringify({ totpSetupFrom: '2030-01-01T00:00:00.000Z' }), method: 'PATCH' })
|
||||
expect(patch.status).toBe(200)
|
||||
const after = (await payload.findByID({ id, collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
|
||||
expect(after.totpSetupFrom).toBe(doc.totpSetupFrom)
|
||||
})
|
||||
|
||||
test('after the window the account is blocked: setup refused with a message, in the admin language', async () => {
|
||||
const id = await idOf('[email protected]')
|
||||
await payload.update({ id, collection: 'users' as never, data: { totpSetupFrom: new Date(Date.now() - 73 * 3_600_000).toISOString() } as never })
|
||||
const res = await setup(sessions.newcomer)
|
||||
expect(res.status).toBe(403)
|
||||
expect(((await res.json()) as { message: string }).message).toMatch(/time to set up two-step verification has passed/i)
|
||||
const pl = await api('/setup-totp', { headers: { ...sessions.newcomer.headers, 'accept-language': 'pl' } }, { body: JSON.stringify({ secret: NEW_SECRET, token: totp(NEW_SECRET) }), method: 'POST' })
|
||||
expect(((await pl.json()) as { message: string }).message).toMatch(/Czas na ustawienie weryfikacji dwuetapowej minął/)
|
||||
expect((await api('/globals/site-integrations', sessions.newcomer)).status).toBe(403)
|
||||
})
|
||||
|
||||
test('only a fully logged-in admin reopens setup', async () => {
|
||||
const userId = await idOf('[email protected]')
|
||||
const reset = (session: Session) => api('/ipal/two-factor/reset', session, { body: JSON.stringify({ userId }), method: 'POST' })
|
||||
for (const session of [sessions.anonymous, sessions.customer, sessions.member, sessions.passwordOnly, sessions.newcomer]) {
|
||||
expect((await reset(session)).status).toBe(403)
|
||||
}
|
||||
expect((await setup(sessions.newcomer)).status).toBe(403) // still blocked
|
||||
const ok = await reset(sessions.verified)
|
||||
expect(ok.status).toBe(200)
|
||||
const doc = (await payload.findByID({ id: userId, collection: 'users' as never })) as unknown as { totpSetupFrom: string }
|
||||
expect(Date.now() - new Date(doc.totpSetupFrom).getTime()).toBeLessThan(120_000)
|
||||
})
|
||||
|
||||
test('inside the window it sets TOTP up, and then everything its role allows opens', async () => {
|
||||
const res = await setup(sessions.newcomer)
|
||||
expect(res.status).toBe(200)
|
||||
expect(((await res.json()) as { ok: boolean }).ok).toBe(true)
|
||||
const full: Session = { headers: { ...sessions.newcomer.headers, cookie: cookiesOf(res).join('; ') } }
|
||||
expect((await api('/globals/site-integrations', full)).status).toBe(200)
|
||||
expect((await api('/form-submissions', full)).status).toBe(200)
|
||||
expect((await api('/users/me', full)).status).toBe(200)
|
||||
// without the 2FA cookie the same token is a password-only session again
|
||||
expect((await api('/globals/site-integrations', sessions.newcomer)).status).toBe(403)
|
||||
})
|
||||
|
||||
test('accounts from before the mode get their window when the site starts', async () => {
|
||||
const { backfillSetupFrom } = await import('../src/modules/security/totp/setupRequired.js')
|
||||
const legacy = await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
|
||||
await payload.db.updateOne({ id: legacy.id, collection: 'users' as never, data: { totpSetupFrom: null } as never })
|
||||
expect(await backfillSetupFrom(payload, 'users')).toBe(1)
|
||||
const doc = (await payload.findByID({ id: legacy.id, collection: 'users' as never })) as unknown as { totpSetupFrom: string }
|
||||
expect(Date.now() - new Date(doc.totpSetupFrom).getTime()).toBeLessThan(120_000)
|
||||
expect(await backfillSetupFrom(payload, 'users')).toBe(0)
|
||||
// accounts that have TOTP are left alone
|
||||
const admin = (await payload.findByID({ id: await idOf('[email protected]'), collection: 'users' as never })) as unknown as { totpSetupFrom?: string }
|
||||
expect(admin.totpSetupFrom).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
// Last: it replaces the running config.
|
||||
describe('dev hot reload', () => {
|
||||
test('a freshly built config is guarded again, also what a later plugin added', async () => {
|
||||
|
||||
Reference in New Issue
Block a user