capgo icon indicating copy to clipboard operation
capgo copied to clipboard

Require AAL2 for platform admin MFA

Open teixr12 opened this issue 6 months ago β€’ 9 comments

Summary

  • Require public.verify_mfa() to rely on the Supabase aal claim instead of accepting any amr.method = "otp" session as MFA.
  • Add regression coverage for an email OTP / magic-link style aal1 session for a platform admin with a verified TOTP factor.
  • Preserve access for a real aal2 session while making the platform-admin wrapper require aal2 before 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.ts and supabase/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, or psql available. 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

Review Change Stack

teixr12 avatar May 10 '26 21:05 teixr12

[!WARNING]

Rate limit exceeded

@teixr12 has 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 review command 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.sql
  • tests/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.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 10 '26 21:05 coderabbitai[bot]

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.

teixr12 avatar May 10 '26 21:05 teixr12

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.

ShravanthReddy avatar May 10 '26 21:05 ShravanthReddy

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)

Open in CodSpeed

[^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.

codspeed[bot] avatar May 10 '26 21:05 codspeed[bot]

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.

mySebbe avatar May 10 '26 22:05 mySebbe

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

zinc-builds avatar May 10 '26 23:05 zinc-builds

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.

teixr12 avatar May 11 '26 00:05 teixr12

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.

Abergelnathan avatar May 11 '26 15:05 Abergelnathan