Skip to content

fix(db): enforce API key expiry in get_user_org_ids#1745

Open
NlDev-hub wants to merge 1 commit intoCap-go:mainfrom
NlDev-hub:fix/get-user-org-ids-expired-key
Open

fix(db): enforce API key expiry in get_user_org_ids#1745
NlDev-hub wants to merge 1 commit intoCap-go:mainfrom
NlDev-hub:fix/get-user-org-ids-expired-key

Conversation

@NlDev-hub
Copy link

@NlDev-hub NlDev-hub commented Mar 5, 2026

Summary

Fixes an API-key-expiration bypass in get_user_org_ids().

get_user_org_ids() currently loads API keys from apikeys but does not reject expired keys before returning org IDs. This allows expired keys to continue resolving org memberships via RPC.

Changes

  • Use find_apikey_by_value(api_key_text) in get_user_org_ids()
  • Add is_apikey_expired(api_key.expires_at) guard
  • Raise API key has expired (same behavior style used in get_orgs_v6 / identity functions)
  • Add pgTAP regression tests in supabase/tests/42_test_apikey_expiration.sql
  • Keep migration/schema parity by updating both:
    • supabase/migrations/20251222140030_rbac_system.sql
    • supabase/schemas/prod.sql

Why

Maintains consistent expiration enforcement across RPC auth paths and prevents stale-key use for org-id enumeration.

Test notes

  • Updated test plan count from 22 -> 24
  • Added tests that:
    1. assert expired key is rejected in get_user_org_ids()
    2. assert valid key still returns org IDs

Summary by CodeRabbit

Release Notes

  • Security

    • Implemented API key expiration validation across all request flows. Expired API keys are now rejected with clear error messaging to enhance security and prevent unauthorized access.
  • Tests

    • Added comprehensive test coverage for API key expiration validation and error handling.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 5, 2026

📝 Walkthrough

Walkthrough

This pull request enhances API key security by replacing direct database lookups with a dedicated function call and adding expiration validation checks across authentication flows. Updates include migration schema changes and corresponding test coverage for the new expiration logic.

Changes

Cohort / File(s) Summary
API Key Lookup & Expiration Validation
supabase/migrations/20251222140030_rbac_system.sql, supabase/schemas/prod.sql
Modified get_orgs_v6 and get_user_org_ids functions to replace direct apikeys table queries with public.find_apikey_by_value() function calls; added explicit expiration checks via is_apikey_expired() with error logging for expired keys.
Expiration Test Coverage
supabase/tests/42_test_apikey_expiration.sql
Added two new test cases for get_user_org_ids: validation of expired API key rejection (test 23) and acceptance of valid non-expired API keys (test 24); test plan increased from 22 to 24.

Sequence Diagram

sequenceDiagram
    participant Client
    participant AuthFunc as Auth Function<br/>(get_orgs_v6 / get_user_org_ids)
    participant Lookup as find_apikey_by_value()
    participant Check as is_apikey_expired()
    participant DB as Database Result
    
    Client->>AuthFunc: Request with API key
    AuthFunc->>Lookup: Retrieve API key by value
    Lookup->>DB: Query apikeys table
    DB-->>Lookup: Return API key record
    Lookup-->>AuthFunc: API key data
    
    AuthFunc->>Check: Validate expiration
    alt Key Expired
        Check-->>AuthFunc: Expired (true)
        AuthFunc-->>Client: Error: API_KEY_EXPIRED
    else Key Valid
        Check-->>AuthFunc: Not expired (false)
        AuthFunc->>DB: Proceed with org lookup
        DB-->>AuthFunc: Organization data
        AuthFunc-->>Client: Success: Return orgs
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A hop and a skip through the API tunnel,
Keys once free now check their expiration funnel,
No more sneaking past with dates long since gone,
The database guards keep weary vigil on—
Security strengthened, one validation at a time!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: enforcing API key expiry validation in the get_user_org_ids function, which is the primary objective of this PR.
Description check ✅ Passed The description covers the summary, changes, rationale, and test notes comprehensively. However, the Test plan section (required template field) lacks specific reproduction steps beyond test count updates.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@supabase/migrations/20251222140030_rbac_system.sql`:
- Around line 2024-2035: Revert the edits made inside the committed migration
supabase/migrations/20251222140030_rbac_system.sql (remove the added SELECT/IF
blocks) and instead create a new migration using supabase migration new
<feature_slug>; in that new migration file apply the intended change to the
function public.get_user_org_ids() (add the SELECT
public.find_apikey_by_value(...) into api_key and the expiry check using
public.is_apikey_expired(api_key.expires_at) with the corresponding pg_log and
RAISE EXCEPTION statements) so the fix is introduced via a fresh migration
rather than editing a committed one.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 156e321f-7621-41d3-86ed-8096c6818ec7

📥 Commits

Reviewing files that changed from the base of the PR and between 02068b1 and 55a592e.

📒 Files selected for processing (3)
  • supabase/migrations/20251222140030_rbac_system.sql
  • supabase/schemas/prod.sql
  • supabase/tests/42_test_apikey_expiration.sql

Comment on lines +2024 to +2035
SELECT * FROM public.find_apikey_by_value(api_key_text) into api_key;

IF api_key IS NULL THEN
PERFORM public.pg_log('deny: INVALID_API_KEY', jsonb_build_object('source', 'header'));
RAISE EXCEPTION 'Invalid API key provided';
END IF;

-- Reject expired API keys (parity with get_orgs_v6/get_identity_*)
IF public.is_apikey_expired(api_key.expires_at) THEN
PERFORM public.pg_log('deny: API_KEY_EXPIRED', jsonb_build_object('key_id', api_key.id));
RAISE EXCEPTION 'API key has expired';
END IF;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Move this fix to a new migration file instead of editing a committed migration.

The logic at Line 2024 and Line 2031-Line 2035 is good, but applying it inside supabase/migrations/20251222140030_rbac_system.sql violates the migration workflow and can cause migration drift across environments. Revert these edits here and apply the same CREATE OR REPLACE FUNCTION public.get_user_org_ids() change in a new migration file.

As per coding guidelines, “Never edit committed migrations in supabase/migrations/; create new migrations with supabase migration new <feature_slug> and edit a single migration file until feature ships.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@supabase/migrations/20251222140030_rbac_system.sql` around lines 2024 - 2035,
Revert the edits made inside the committed migration
supabase/migrations/20251222140030_rbac_system.sql (remove the added SELECT/IF
blocks) and instead create a new migration using supabase migration new
<feature_slug>; in that new migration file apply the intended change to the
function public.get_user_org_ids() (add the SELECT
public.find_apikey_by_value(...) into api_key and the expiry check using
public.is_apikey_expired(api_key.expires_at) with the corresponding pg_log and
RAISE EXCEPTION statements) so the fix is introduced via a fresh migration
rather than editing a committed one.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Mar 5, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant