Require AAL2 for platform admin MFA
Summary
- Require
public.verify_mfa()to rely on the Supabaseaalclaim instead of accepting anyamr.method = "otp"session as MFA. - Add regression coverage for an email OTP / magic-link style
aal1session for a platform admin with a verified TOTP factor. - Preserve access for a real
aal2session while making the platform-admin wrapper requireaal2before checking the admin secret.
Root Cause
is_platform_admin() delegates to verify_mfa() before allowing platform-admin-only actions such as impersonation, admin credits, admin stats, and replication status.
verify_mfa() correctly required aal2 when the user had a verified MFA factor, but it also returned true when the JWT amr array contained method = "otp". Supabase email OTP / magic-link authentication can produce an OTP first-factor session while still staying at aal1, so mailbox access could satisfy the platform-admin MFA gate without the admin's TOTP factor.
Security Impact
For users listed in admin_users, platform-admin endpoints should require an MFA-verified aal2 session. This change prevents email OTP / magic-link sessions and zero-factor aal1 sessions from being treated as platform-admin MFA.
Test plan
git diff --check- Regression coverage added in
tests/is-admin-functions.test.tsandsupabase/tests/07_auth_functions.sql. - I could not run the DB-backed Vitest test locally because this fresh environment does not have project dependencies installed and does not have
bun,supabase, orpsqlavailable. CI is expected to exercise the added regression tests.
Screenshots
N/A. This is a backend SQL authorization change with regression test coverage and no frontend/CLI UI changes.
Checklist
- [ ] My code follows the code style of this project and passes
bun run lint:backend && bun run lint. - [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] My change has adequate E2E test coverage.
- [ ] I have tested my code manually, and I have provided steps how to reproduce my tests.
Refs #1667 /claim #1667
Summary by CodeRabbit
New Features
- TOTP (Time-based One-Time Password) multi-factor authentication is now available for users to enroll and verify
- Platform admin accounts now require additional authentication verification before access
Tests
- Added comprehensive test coverage for multi-factor authentication workflows
- Updated admin authentication helpers and test suites to support new authentication requirements
[!WARNING]
Rate limit exceeded
@teixr12has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 35 seconds before requesting another review.Youβve run out of usage credits. Purchase more in the billing tab.
β How to resolve this issue?
After the wait time has elapsed, a review can be triggered using the
@coderabbitai reviewcommand as a PR comment. Alternatively, push new commits to this PR.We recommend that you space out your commits to avoid hitting the rate limit.
π¦ How do rate limits work?
CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.
βΉοΈ Review info
βοΈ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
dd0c2937-3913-4dc3-9434-e5a55f9ab788π₯ Commits
Reviewing files that changed from the base of the PR and between d51af96a399190b0c8758e6b54ba9236bfa06313 and 14f42428702e5982e5b720b237c03a5dda183540.
π Files selected for processing (2)
supabase/migrations/20260512003000_require_aal2_for_platform_admin_mfa.sqltests/test-utils.ts
π Walkthrough
Walkthrough
The pull request implements AAL2 (multi-factor authentication) authorization for platform admin access. It adds two PostgreSQL functions (verify_mfa() and public.is_platform_admin()) that enforce JWT AAL claims, enables TOTP in Supabase config, provides test utilities for TOTP-based AAL2 authentication, and updates admin and audit test suites to use the new authentication flow.
Changes
AAL2 and MFA Authorization for Platform Admin
| Layer / File(s) | Summary |
|---|---|
MFA Authorization Database Functions supabase/migrations/20260511001500_require_aal2_for_platform_admin_mfa.sql |
public.verify_mfa() authorizes based on JWT aal claim and verified MFA factors (AAL1 for users without factors, AAL2 for users with factors). public.is_platform_admin() rejects non-AAL2 sessions before delegating to the UUID overload. Both use SECURITY DEFINER with explicit execution grants. |
TOTP Configuration supabase/config.toml |
auth.mfa.totp enrollment and verification are enabled by setting enroll_enabled and verify_enabled to true. |
TOTP and AAL2 Test Utilities tests/test-utils.ts |
Added Node crypto imports, decodeBase32 helper for TOTP secret decoding, generateTotp helper for RFC6238 TOTP code generation, and getAal2AuthHeadersForCredentials function that performs Supabase sign-in, marks email verification, enrolls and verifies a TOTP factor via MFA API, and returns AAL2-authorized headers with test factor cleanup in a finally block. |
Database Function Privilege Tests supabase/tests/07_auth_functions.sql |
Test assertion count increased to 18; aal claim added to test admin JWT context; new assertions verify service_role cannot execute public.is_platform_admin() (user-context wrapper) but can execute public.is_platform_admin(uuid) (private overload). |
Admin Authorization MFA Tests tests/is-admin-functions.test.ts |
Helper setAuthClaims populates Postgres set_config with JWT context. First test verifies is_platform_admin() is false for OTP-only amr, then true when password and TOTP are in amr. Second test verifies function is false when admin has no MFA factors and aal1 claim. |
Admin Endpoint Tests Using AAL2 Auth tests/admin-credits.test.ts, tests/admin-stats.test.ts |
Admin endpoint tests updated to import and use getAal2AuthHeadersForCredentials instead of previous auth helpers, ensuring requests are authenticated with AAL2 sessions. |
Audit Log Test Updates tests/audit-logs.test.ts |
Audit test suite now tracks created app-version both ID and name; INSERT assertion refactored to use waitForAuditLog filtered by record ID and validates new_record.name; soft-delete test updated to use stored version name in DELETE payload. |
π― 3 (Moderate) | β±οΈ ~20 minutes
π° The admin gates now stand tall and true,
With MFA factors keeping hackers at bayβ
AAL2 claims and TOTP codes in view,
Platform guardians secure every day! β¨π
π₯ Pre-merge checks | β 4 | β 1
β Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | β οΈ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
β Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | β Passed | The title 'Require AAL2 for platform admin MFA' clearly and concisely summarizes the main security-focused change: enforcing AAL2 authentication for platform admin MFA checks instead of accepting OTP-only sessions. |
| Description check | β Passed | The PR description covers all required sections: a clear summary explaining the change and root cause, a detailed test plan with regression test references, acknowledgment that screenshots are not applicable (backend SQL change), and a completed checklist acknowledging unchecked items where applicable. |
| Linked Issues check | β Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | β Passed | Check skipped because no linked issues were found for this pull request. |
βοΈ Tip: You can configure your own custom pre-merge checks in the settings.
β¨ Finishing Touches
π§ͺ Generate unit tests (beta)
- [ ] Create PR with unit tests
[!TIP]
π¬ Introducing Slack Agent: The best way for teams to turn conversations into code.
Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
- Generate code and open pull requests
- Plan features and break down work
- Investigate incidents and troubleshoot customer tickets together
- Automate recurring tasks and respond to alerts with triggers
- Summarize progress and report instantly
Built for teams:
- Shared memory across your entire orgβno repeating context
- Per-thread sandboxes to safely plan and execute work
- Governance built-inβscoped access, auditability, and budget controls
One agent for your entire SDLC. Right inside Slack.
π Get started
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Fixed the test setup issue by seeding a recent public.user_security.email_otp_verified_at row for the platform admin before inserting the verified MFA factor, so the existing MFA enrollment trigger can pass on reset test DBs.
Thanks, this addresses the test setup issue I flagged. The added public.user_security upsert should allow the existing MFA enrollment trigger to pass before inserting the verified factor.
Merging this PR will not alter performance
β
43 untouched benchmarks
β© 2 skipped benchmarks[^skipped]
Comparing teixr12:bounty/platform-admin-mfa-aal2 (14f4242) with main (a4f7c93)
[^skipped]: 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
I think there is still a zero-factor platform-admin gap in this version. verify_mfa() returns true for aal1 whenever the caller has no verified rows in auth.mfa_factors, so a user listed in the admin_users secret with no verified MFA factor can still pass public.is_platform_admin() under a plain aal1 session.
The new regression test covers an admin who already has a verified TOTP factor, but it does not cover the no-factor platform-admin case. If the intended invariant is "platform admin access requires MFA", this should either require aal2 on the platform-admin path regardless of factor count or add a stricter helper for is_platform_admin(), plus a regression test where the admin has zero verified factors.
If no-factor platform admins are intentionally grandfathered, I would make that explicit in the PR description and function comment, because the current is_platform_admin comment says it requires MFA.
Nice catch on the amr.method vs aal distinction β easy to miss unless you understand Supabase's JWT claim model. Left a full review above (approved). One minor suggestion: add a comment in the migration SQL explaining why the amr.method = 'otp' fallback was removed, for future readers.
/claim #1667
Good catch, thank you. Fixed in 1176f2a by keeping public.verify_mfa() compatible with ordinary non-MFA users, but making the no-argument public.is_platform_admin() wrapper require an aal2 session before checking the admin_users secret. I also added a regression test for the zero-factor platform-admin aal1 case and added an inline SQL comment explaining why amr.method = 'otp' is not accepted for this gate.
Review note: getAal2AuthHeadersForCredentials() deletes every row in auth.mfa_factors for the signed-in user before enrolling its test TOTP factor. Because the admin stats/credits suites reuse shared admin credentials and Vitest can run files concurrently, this helper can race with another suite that is using the same admin account or remove MFA fixtures that were not created by this helper. It also leaves the newly verified factor behind, so repeated runs can accumulate state unless the next call happens to delete it first.
Could we scope this cleanup to factors created by this helper, for example by using a deterministic friendlyName prefix and deleting only that prefix, or create a dedicated per-suite admin user/factor and clean it up in afterAll? That keeps the new AAL2 coverage while avoiding cross-test interference around a security-sensitive table.
Quality Gate passed
Issues
0 New issues
0 Accepted issues
Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code