test(supabase): GoTrue MFA behaviour proven on the sandbox (V1-2.5 A)
Ten cases on the pinned GoTrue: aal1 cannot enrol a second factor or remove a verified one (no STOP); removal downgrades only the sessions verified with that factor; password change and reset need aal2 once a factor is verified. Findings in IDENTITY.md §4.1.
This commit is contained in:
1 parent
a701b04210
commit
78791bfb6b
3 files changed
+289
-1
No files matched your search
@@ -99,6 +99,42 @@ into the policies of the first admin table) with pgTAP allowed/denied cases;
|
||||
enrolment + challenge screens in Mon compte; step-up at sign-in for accounts
|
||||
holding a platform role.
|
||||
|
||||
### 4.1 GoTrue v2.197.0 behaviour, measured on the sandbox (V1-2.5)
|
||||
|
||||
`packages/supabase/tests/sandbox/mfa-behaviour.sandbox.ts` (real GoTrue, run by
|
||||
`pnpm db:sandbox test`) asserts what the pinned image does; V1-2 contract §5.6,
|
||||
§5.7.1, §5.7.3, §5.7.4. None of it is assumed elsewhere.
|
||||
|
||||
- First factor: enrolled from `aal1`, stored `unverified`; until verified a new
|
||||
sign-in stays `aal1`.
|
||||
- Verify: challenge and verify upgrade the same session (same `session_id`) to
|
||||
`aal2`, `amr` password + totp, and delete the account's other `aal1`
|
||||
sessions. GoTrue refuses their tokens at once; PostgREST keeps accepting
|
||||
their access token until it expires.
|
||||
- Second factor from `aal1`: 403 `insufficient_aal`; from `aal2`: allowed.
|
||||
- Removing a verified factor from `aal1`: 422 `insufficient_aal`; an
|
||||
unverified one: allowed. The STOP condition of §5.6 did not fire.
|
||||
- Removing a verified factor from `aal2`: only the sessions last verified with
|
||||
that factor drop to `aal1`. Their access token keeps its `aal2` claim until it
|
||||
expires: `has_mfa()` stays true for it, `has_aal2_session()` turns false, so
|
||||
the role and rights RPCs refuse it at once. Their next refresh is `aal1`.
|
||||
- Dormant unverified factor: one left before any verification is deleted when
|
||||
another factor is verified. One enrolled from `aal2` after verification is
|
||||
kept and can later be verified from a password-only session, reaching
|
||||
`aal2`. Planting it needs an `aal2` session and its secret (shown once), so it
|
||||
stays within the stolen-session residual (§5.7.8). Factor lists show
|
||||
unverified factors.
|
||||
- Password change or reset with a verified factor: refused at `aal1` (401
|
||||
`insufficient_aal`), including from a recovery-link session (`amr` otp). From
|
||||
`aal2` it succeeds, keeps that session and deletes the account's others. The
|
||||
recovery screens and the §5.7.7 runbook must reach `aal2` first. Without a
|
||||
factor, `aal1` changes the password and stays `aal1`.
|
||||
- Refresh keeps `aal2`; a new password sign-in starts at `aal1`.
|
||||
- Email change: refused at `aal1`; from `aal2` the confirmation link opens a
|
||||
new `aal1` session. Identity linking: 404 `manual_linking_disabled`.
|
||||
- A TOTP code accepted twice within its 30 s window by two sessions of one
|
||||
factor (observed, not asserted).
|
||||
|
||||
## 5. Manual validation (local stack)
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* 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'
|
||||
|
||||
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) }
|
||||
}
|
||||
|
||||
/** 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(/&/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)
|
||||
})
|
||||
})
|
||||
@@ -17,7 +17,7 @@ export interface MfaResult {
|
||||
body: Record<string, unknown>
|
||||
}
|
||||
|
||||
async function authRequest(
|
||||
export async function authRequest(
|
||||
method: string,
|
||||
path: string,
|
||||
token: string,
|
||||
|
||||
Reference in new issue
Block a user