Files
faunosteo/packages/supabase/tests/sandbox/mfa-behaviour.sandbox.ts
T
bchanot dcb1a94ee4 docs(supabase): V1-2.5 checkpoint decisions, TOTP reuse measured, lost-factor review
IDENTITY 4.1 asserted reuse span (step N and N+1), 4.2 lost authenticator paths and gaps, production prerequisite; V1-2 contract 12.3, 13, 17.10, 17.11; design README accepted deviations; REVUE L15 and object_conflict EN; M7 header.
2026-11-02 22:57:22 +01:00

301 lines
17 KiB
TypeScript

/**
* V1-2.5 C1: what the pinned GoTrue v2.197.0 really does for TOTP MFA, proven
* on the throwaway stack (contract docs/development/V1-2_ANATOMICAL_SHEETS.md
* §5.6, §5.7.1, §5.7.3, §5.7.4, §15 "MFA on the sandbox stack"). Every
* expectation is the observed behaviour of the image, not the documented one;
* a gap with §5.7.3 is written up for the owner. Fictitious accounts created
* per test through the admin API and deleted afterwards; secrets and tokens
* stay in memory. Run through
* `pnpm db:sandbox test tests/sandbox/mfa-behaviour.sandbox.ts`.
*/
import { PASSWORD, confirmedAccount, rest, signIn, sql, stack, uniqueEmail, type Account } from './stack'
import { authRequest, claimsOf, enrolTotp, verifyTotp, type Factor, type MfaResult } from './mfa'
import { TOTP_STEP_SECONDS, totpCode } from './totp'
interface Session {
access: string
refresh: string
}
const created: string[] = []
const account = async (tag: string): Promise<Account> => {
const a = await confirmedAccount(tag)
created.push(a.id)
return a
}
const passwordSession = async (email: string, password = PASSWORD): Promise<Session> => {
const res = await signIn(email, password)
expect(res.status).toBe(200)
return { access: res.body.access_token as string, refresh: res.body.refresh_token as string }
}
const sessionOf = (result: MfaResult): Session =>
({ access: result.body.access_token as string, refresh: result.body.refresh_token as string })
const aal = (token: string) => claimsOf(token).aal
const amr = (token: string) =>
(claimsOf(token).amr as { method: string }[]).map((entry) => entry.method).sort()
/** Status and GoTrue error_code: the shape every refusal is asserted with. */
const outcome = (result: MfaResult) => [result.status, result.body.error_code ?? null]
const refresh = (session: Session) =>
authRequest('POST', '/token?grant_type=refresh_token', stack.anonKey, { refresh_token: session.refresh })
const unenrol = (token: string, factor: Factor) => authRequest('DELETE', `/factors/${factor.id}`, token)
const factorsOf = (id: string) =>
sql(`select friendly_name || ':' || status from auth.mfa_factors where user_id = '${id}' order by created_at`)
/** The aal of the auth.sessions row a token names ('' once the row is gone). */
const sessionAal = (token: string) =>
sql(`select aal from auth.sessions where id = '${claimsOf(token).session_id as string}'`)
const fragmentToken = (location: string | null) =>
new URLSearchParams((location ?? '').split('#')[1] ?? '').get('access_token')
/** An account with one verified factor `A`, its aal2 session and the factor. */
const withFactor = async (tag: string) => {
const a = await account(tag)
const aal1 = await passwordSession(a.email)
const factor = (await enrolTotp(aal1.access, 'A')).factor!
const verified = await verifyTotp(aal1.access, factor)
expect(verified.status).toBe(200)
return { account: a, factor, aal2: sessionOf(verified) }
}
/** Sleeps into the start of a TOTP step with at least `minLeftS` seconds left. */
const intoFreshStep = async (minLeftS: number) => {
const stepMs = TOTP_STEP_SECONDS * 1000
const leftMs = stepMs - (Date.now() % stepMs)
if (leftMs <= minLeftS * 1000) await new Promise((r) => setTimeout(r, leftMs + 500))
}
/** Sleeps over the next step boundary (the code of the new step is then current). */
const intoNextStep = async () => {
const stepMs = TOTP_STEP_SECONDS * 1000
await new Promise((r) => setTimeout(r, stepMs - (Date.now() % stepMs) + 500))
}
/** Challenge then verify with a code fixed by the caller (the secret is never read back). */
const verifyWith = async (token: string, factor: Factor, code: string) => {
const challenge = await authRequest('POST', `/factors/${factor.id}/challenge`, token, {})
if (challenge.status !== 200) return challenge
return authRequest('POST', `/factors/${factor.id}/verify`, token, { challenge_id: challenge.body.id, code })
}
/** has_mfa() and has_aal2_session() evaluated with `token`'s claims, as PostgREST sets them. */
const helpersFor = async (token: string) => {
const out = await sql(`begin;
select set_config('request.jwt.claims', $j$${JSON.stringify(claimsOf(token))}$j$, true);
select private.has_mfa() || ',' || private.has_aal2_session();
commit;`)
return out.split('\n').filter(Boolean).pop()
}
describe('GoTrue v2.197.0 TOTP behaviour (V1-2.5 C1)', () => {
afterAll(async () => {
if (created.length > 0)
await sql(`delete from auth.users where id in (${created.map((id) => `'${id}'`).join(', ')})`)
})
it('1. the first factor is enrolled from aal1 and counts only once verified', async () => {
const a = await account('mfa-first')
const session = await passwordSession(a.email)
expect(aal(session.access)).toBe('aal1')
expect((await enrolTotp(session.access, 'A')).status).toBe(200)
expect(await factorsOf(a.id)).toBe('A:unverified')
// An unverified factor counts for nothing: a new sign-in is aal1 and may still enrol.
const again = await passwordSession(a.email)
expect(aal(again.access)).toBe('aal1')
expect((await enrolTotp(again.access, 'B')).status).toBe(200)
})
it('2. challenge + verify upgrades the same session to aal2 (amr password + totp)', async () => {
const a = await account('mfa-verify')
const before = await passwordSession(a.email)
const session = await passwordSession(a.email)
const factor = (await enrolTotp(session.access, 'A')).factor!
const verified = await verifyTotp(session.access, factor)
expect(verified.status).toBe(200)
const aal2 = sessionOf(verified)
expect([aal(aal2.access), amr(aal2.access)]).toEqual(['aal2', ['password', 'totp']])
expect(claimsOf(aal2.access).session_id).toBe(claimsOf(session.access).session_id)
expect(await sessionAal(aal2.access)).toBe('aal2')
expect(await factorsOf(a.id)).toBe('A:verified')
// The verification deletes the account's other (aal1) sessions: GoTrue
// refuses their access and refresh tokens; PostgREST, which reads no
// session, still accepts the access token until it expires.
expect(await sessionAal(before.access)).toBe('')
expect(outcome(await authRequest('GET', '/user', before.access))).toEqual([403, 'session_not_found'])
expect(outcome(await refresh(before))).toEqual([400, 'refresh_token_not_found'])
expect((await rest('/profiles?select=id', before.access)).status).toBe(200)
})
it('3. with a verified factor, aal1 cannot enrol a second factor; aal2 can', async () => {
const { account: a, aal2 } = await withFactor('mfa-second')
const aal1 = await passwordSession(a.email)
expect(outcome(await enrolTotp(aal1.access, 'B'))).toEqual([403, 'insufficient_aal'])
expect((await enrolTotp(aal2.access, 'B')).status).toBe(200)
})
it('4. with a verified factor, aal1 cannot remove it; an unverified factor is removed from aal1', async () => {
const { account: a, factor, aal2 } = await withFactor('mfa-remove-aal1')
const pending = (await enrolTotp(aal2.access, 'B')).factor!
const aal1 = await passwordSession(a.email)
expect(outcome(await unenrol(aal1.access, factor))).toEqual([422, 'insufficient_aal'])
expect((await unenrol(aal1.access, pending)).status).toBe(200)
expect(await factorsOf(a.id)).toBe('A:verified')
})
it('5. removing a verified factor from aal2 downgrades only the sessions verified with it', async () => {
const { account: a, factor: A, aal2: s1 } = await withFactor('mfa-remove-aal2')
const B = (await enrolTotp(s1.access, 'B')).factor!
expect((await verifyTotp(s1.access, B)).status).toBe(200)
// S2 reaches aal2 with A, S3 with B (S1 now carries B, its last verification).
const s2 = sessionOf(await verifyTotp((await passwordSession(a.email)).access, A))
const s3 = sessionOf(await verifyTotp((await passwordSession(a.email)).access, B))
expect([aal(s2.access), aal(s3.access)]).toEqual(['aal2', 'aal2'])
expect((await unenrol(s1.access, A)).status).toBe(200)
expect(await factorsOf(a.id)).toBe('B:verified')
// The session row of S2 drops to aal1; S1 and S3 stay aal2.
expect([await sessionAal(s1.access), await sessionAal(s2.access), await sessionAal(s3.access)])
.toEqual(['aal2', 'aal1', 'aal2'])
// S2's issued access token keeps its aal2 claim and is still accepted by
// GoTrue and PostgREST until it expires: has_mfa() passes on it, the
// session check of the role and rights RPCs (has_aal2_session) refuses it.
expect(aal(s2.access)).toBe('aal2')
expect((await authRequest('GET', '/user', s2.access)).status).toBe(200)
expect((await rest('/profiles?select=id', s2.access)).status).toBe(200)
expect(await helpersFor(s2.access)).toBe('true,false')
expect(await helpersFor(s3.access)).toBe('true,true')
// Its refresh comes back aal1 (amr password only); S3's stays aal2.
const r2 = await refresh(s2)
expect(r2.status).toBe(200)
const downgraded = r2.body.access_token as string
expect([aal(downgraded), amr(downgraded)]).toEqual(['aal1', ['password']])
expect(aal((await refresh(s3)).body.access_token as string)).toBe('aal2')
})
it('6. dormant unverified factors: deleted by the first verification, verifiable from aal1 otherwise', async () => {
// Left before any factor is verified: verifying another factor deletes it.
const a = await account('mfa-dormant')
const first = await passwordSession(a.email)
const dormant = (await enrolTotp(first.access, 'dormant')).factor!
const A = (await enrolTotp(first.access, 'A')).factor!
const aal2 = sessionOf(await verifyTotp(first.access, A))
expect(await factorsOf(a.id)).toBe('A:verified')
const later = await passwordSession(a.email)
expect(outcome(await verifyTotp(later.access, dormant))).toEqual([404, 'mfa_factor_not_found'])
// Left from aal2 once a factor is verified: it survives, and whoever holds
// its secret (shown once to that aal2 session) verifies it later from a
// password-only aal1 session, which reaches aal2 (the §5.7.3 dormant path).
const late = (await enrolTotp(aal2.access, 'late')).factor!
const aal1 = await passwordSession(a.email)
const verified = await verifyTotp(aal1.access, late)
expect(verified.status).toBe(200)
expect(aal(verified.body.access_token as string)).toBe('aal2')
expect(await factorsOf(a.id)).toBe('A:verified\nlate:verified')
})
it('7. password change and reset never reach aal2; with a factor they need aal2', async () => {
const { account: a, aal2 } = await withFactor('mfa-password')
const aal1 = await passwordSession(a.email)
// From aal1 (a known password), GoTrue refuses the change outright.
const refused = await authRequest('PUT', '/user', aal1.access, { password: PASSWORD + 'a' })
expect(outcome(refused)).toEqual([401, 'insufficient_aal'])
// Reset: the admin recovery link (no mailbox needed) opens an aal1 session
// (amr otp), refused the same way.
const link = await authRequest('POST', '/admin/generate_link', stack.serviceKey, { type: 'recovery', email: a.email })
const landing = await fetch(link.body.action_link as string, { redirect: 'manual' })
const recovery = fragmentToken(landing.headers.get('location'))!
expect([aal(recovery), amr(recovery)]).toEqual(['aal1', ['otp']])
const reset = await authRequest('PUT', '/user', recovery, { password: PASSWORD + 'b' })
expect(outcome(reset)).toEqual([401, 'insufficient_aal'])
// From aal2 it passes: that session stays aal2, every other session of the
// account is ended, and a sign-in with the new password starts at aal1.
expect((await authRequest('PUT', '/user', aal2.access, { password: PASSWORD + 'c' })).status).toBe(200)
expect(await sessionAal(aal2.access)).toBe('aal2')
expect(await sql(`select count(*) from auth.sessions where user_id = '${a.id}'`)).toBe('1')
expect(aal((await passwordSession(a.email, PASSWORD + 'c')).access)).toBe('aal1')
// Without a factor, aal1 changes the password and stays aal1.
const plain = await account('mfa-password-plain')
const session = await passwordSession(plain.email)
expect((await authRequest('PUT', '/user', session.access, { password: PASSWORD + 'd' })).status).toBe(200)
expect(aal((await refresh(session)).body.access_token as string)).toBe('aal1')
})
it('8. a refresh of an aal2 session keeps aal2', async () => {
const { aal2 } = await withFactor('mfa-refresh')
const refreshed = await refresh(aal2)
expect(refreshed.status).toBe(200)
const token = refreshed.body.access_token as string
expect([aal(token), amr(token)]).toEqual(['aal2', ['password', 'totp']])
expect(claimsOf(token).session_id).toBe(claimsOf(aal2.access).session_id)
})
it('9. a new password sign-in of an account with a verified factor starts at aal1', async () => {
const { account: a } = await withFactor('mfa-signin')
const session = await passwordSession(a.email)
expect([aal(session.access), amr(session.access)]).toEqual(['aal1', ['password']])
expect(await sessionAal(session.access)).toBe('aal1')
})
it('10. email change and identity linking never raise a session to aal2', async () => {
const { account: a, aal2 } = await withFactor('mfa-email')
const aal1 = await passwordSession(a.email)
const newEmail = uniqueEmail('mfa-email-new')
// From aal1: refused like the password change.
const fromAal1 = await authRequest('PUT', '/user', aal1.access, { email: newEmail })
expect(outcome(fromAal1)).toEqual([401, 'insufficient_aal'])
// Identity linking is disabled (enable_manual_linking = false): refused, nothing to raise.
const linking = await authRequest('GET', '/user/identities/authorize?provider=google&skip_http_redirect=true', aal1.access)
expect(outcome(linking)).toEqual([404, 'manual_linking_disabled'])
// From aal2: accepted; the secure change mails both addresses, and the
// second confirmation opens a new session at aal1 (amr otp).
expect((await authRequest('PUT', '/user', aal2.access, { email: newEmail })).status).toBe(200)
const tokens: string[] = []
for (const address of [a.email, newEmail]) {
const search = (await (
await fetch(`${stack.mailUrl}/api/v1/search?query=${encodeURIComponent('to:' + address)}`)
).json()) as { messages: { ID: string }[] }
expect(search.messages).toHaveLength(1)
const message = (await (
await fetch(`${stack.mailUrl}/api/v1/message/${search.messages[0].ID}`)
).json()) as { Text: string }
const url = message.Text.match(/http:\/\/127\.0\.0\.1:\d+\/verify\?[^\s)\]]+/)?.[0]
expect(url).toBeTruthy()
const res = await fetch(url!.replace(/&amp;/g, '&'), { redirect: 'manual' })
expect(res.status).toBe(303)
const token = fragmentToken(res.headers.get('location'))
if (token) tokens.push(token)
}
expect(tokens).toHaveLength(1)
expect([aal(tokens[0]), amr(tokens[0])]).toEqual(['aal1', ['otp']])
expect(await sql(`select email from auth.users where id = '${a.id}'`)).toBe(newEmail)
})
it('11. a TOTP code is accepted again within its window: same step, next step, not the one after', async () => {
// Measured, not documented (IDENTITY.md §4.1): GoTrue keeps no used-code
// record in this image. The code C of step N is verified by session A,
// then by a second aal1 session B signed in after A's verify, then by A
// again; C is still accepted one step later and refused two steps later.
const { account: a, factor } = await withFactor('mfa-reuse')
await intoNextStep()
await intoFreshStep(8)
const code = totpCode(factor.secret)
const A = await passwordSession(a.email)
const first = await verifyWith(A.access, factor, code)
expect(outcome(first)).toEqual([200, null])
const B = await passwordSession(a.email)
// B is alive before the code is sent: the refusal below cannot be a dead session.
expect([outcome(await authRequest('GET', '/user', B.access)), aal(B.access)]).toEqual([[200, null], 'aal1'])
const reused = await verifyWith(B.access, factor, code)
expect(outcome(reused)).toEqual([200, null])
expect(aal(reused.body.access_token as string)).toBe('aal2')
expect(outcome(await verifyWith(sessionOf(first).access, factor, code))).toEqual([200, null])
// Step N+1 (one step of skew): still accepted.
await intoNextStep()
const D = await passwordSession(a.email)
expect(outcome(await verifyWith(D.access, factor, code))).toEqual([200, null])
// Step N+2: refused. The span of C is its step and the next one (30 to 60 s).
await intoNextStep()
const E = await passwordSession(a.email)
expect(outcome(await verifyWith(E.access, factor, code))).toEqual([422, 'mfa_verification_failed'])
}, 180_000)
})