Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
CREATE OR REPLACE FUNCTION "public"."verify_mfa"()
RETURNS boolean
LANGUAGE "plpgsql"
SECURITY DEFINER
SET "search_path" TO ''
AS $$
BEGIN
-- Email OTP and magic-link first-factor sessions can carry amr.method = 'otp'
-- while remaining aal1, so MFA authorization must use the authoritative aal
-- claim instead of accepting OTP method metadata.
RETURN (
array[(SELECT coalesce(auth.jwt()->>'aal', 'aal1'))] <@ (
SELECT
CASE
WHEN count(id) > 0 THEN array['aal2']
ELSE array['aal1', 'aal2']
END AS aal
FROM auth.mfa_factors
WHERE (SELECT auth.uid()) = user_id AND status = 'verified'
)
);
END;
$$;

ALTER FUNCTION "public"."verify_mfa"() OWNER TO "postgres";
REVOKE ALL ON FUNCTION "public"."verify_mfa"() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "public"."verify_mfa"() TO "anon";
GRANT EXECUTE ON FUNCTION "public"."verify_mfa"() TO "authenticated";
GRANT EXECUTE ON FUNCTION "public"."verify_mfa"() TO "service_role";

CREATE OR REPLACE FUNCTION "public"."is_platform_admin"()
RETURNS boolean
LANGUAGE "plpgsql"
SECURITY DEFINER
SET "search_path" TO ''
AS $$
BEGIN
-- Platform-admin actions are privileged even for admins without an enrolled
-- factor row, so require an MFA-verified session before checking the secret.
IF coalesce(auth.jwt()->>'aal', 'aal1') <> 'aal2' THEN
RETURN false;
END IF;

RETURN public.is_platform_admin((SELECT auth.uid()));
END;
$$;

ALTER FUNCTION "public"."is_platform_admin"() OWNER TO "postgres";
REVOKE ALL ON FUNCTION "public"."is_platform_admin"() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION "public"."is_platform_admin"() TO "authenticated";
GRANT EXECUTE ON FUNCTION "public"."is_platform_admin"() TO "service_role";
82 changes: 82 additions & 0 deletions tests/is-admin-functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,20 @@ describe('is_platform_admin SQL function', () => {
}
}

async function setAuthClaims(query: QueryFn, claims: Record<string, unknown>) {
const sub = typeof claims.sub === 'string' ? claims.sub : ''
const email = typeof claims.email === 'string' ? claims.email : ''

await query('SELECT set_config(\'role\', \'authenticated\', true)')
await query('SELECT set_config(\'request.jwt.claim.sub\', $1, true)', [sub])
await query('SELECT set_config(\'request.jwt.claim.email\', $1, true)', [email])
await query('SELECT set_config(\'request.jwt.claim.role\', \'authenticated\', true)')
await query('SELECT set_config(\'request.jwt.claims\', $1, true)', [JSON.stringify({
role: 'authenticated',
...claims,
})])
}

afterAll(async () => {
await pool.end()
})
Expand Down Expand Up @@ -145,4 +159,72 @@ describe('is_platform_admin SQL function', () => {
expect(regularUserResults.rows[0].is_platform_admin).toBe(false)
})
})

it.concurrent('does not treat email OTP sessions as platform-admin MFA', async () => {
await withTransaction(async (query) => {
const legacyAdmin = await getAdminUserId(query)

expect(legacyAdmin).toBeTruthy()

await query(`
INSERT INTO public.user_security (user_id, email_otp_verified_at, created_at, updated_at)
VALUES ($1::uuid, NOW(), NOW(), NOW())
ON CONFLICT (user_id) DO UPDATE
SET
email_otp_verified_at = EXCLUDED.email_otp_verified_at,
updated_at = NOW();
`, [legacyAdmin])

await query(`
INSERT INTO auth.mfa_factors (id, user_id, friendly_name, factor_type, status, created_at, updated_at)
VALUES (gen_random_uuid(), $1::uuid, 'Admin TOTP', 'totp'::auth.factor_type, 'verified'::auth.factor_status, NOW(), NOW());
`, [legacyAdmin])

await setAuthClaims(query, {
sub: legacyAdmin,
email: 'admin@example.test',
aal: 'aal1',
amr: [{ method: 'otp' }],
})

const otpOnly = await query('SELECT public.is_platform_admin() as is_platform_admin')

expect(otpOnly.rows[0].is_platform_admin).toBe(false)

await setAuthClaims(query, {
sub: legacyAdmin,
email: 'admin@example.test',
aal: 'aal2',
amr: [{ method: 'password' }, { method: 'totp' }],
})

const totpVerified = await query('SELECT public.is_platform_admin() as is_platform_admin')

expect(totpVerified.rows[0].is_platform_admin).toBe(true)
})
})

it.concurrent('requires aal2 for platform admins without enrolled factors', async () => {
await withTransaction(async (query) => {
const legacyAdmin = await getAdminUserId(query)

expect(legacyAdmin).toBeTruthy()

await query(`
DELETE FROM auth.mfa_factors
WHERE user_id = $1::uuid;
`, [legacyAdmin])

await setAuthClaims(query, {
sub: legacyAdmin,
email: 'admin@example.test',
aal: 'aal1',
amr: [{ method: 'password' }],
})

const aal1Admin = await query('SELECT public.is_platform_admin() as is_platform_admin')

expect(aal1Admin.rows[0].is_platform_admin).toBe(false)
})
})
})
Loading