capgo icon indicating copy to clipboard operation
capgo copied to clipboard

fix(webhooks): align RLS API key scope with org webhook policy

Open teixr12 opened this issue 6 months ago โ€ข 7 comments

Summary

  • Adds a webhook-specific API-key identity helper so direct webhook RLS resolution rejects app-scoped API keys for org-level webhook resources.
  • Applies the same org required-expiration API-key policy at the webhook RLS layer that webhook route handlers already enforce.
  • Adds regressions covering direct REST webhook visibility for app-scoped keys and legacy keys after an org requires expiring API keys.

Why

Webhook handlers already enforce these API-key constraints before managing org-level webhook resources. Direct table access through RLS should fail closed with the same constraints while leaving the shared org API-key helper compatible for non-webhook callers.

Test plan

  • git diff --check origin/main...HEAD
  • bash scripts/check-supabase-migration-order.sh
  • Regression coverage added in tests/webhooks.test.ts and tests/webhooks-apikey-policy.test.ts.
  • I could not run the targeted Vitest files locally in this checkout because the local environment does not have bun or installed project dependencies. CI is expected to exercise the added regression tests.

Screenshots

N/A. This is a backend SQL/RLS 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. Local lint could not be run in this checkout because bun and installed dependencies are unavailable; GitHub CI is expected to run the project checks.
  • [ ] My change requires a change to the documentation. N/A: this is a backend SQL/RLS authorization hardening change with no user-facing behavior or docs surface.
  • [ ] I have updated the documentation accordingly. N/A: no documentation change is required.
  • [ ] My change has adequate E2E test coverage. Backend regression coverage was added in tests/webhooks.test.ts and tests/webhooks-apikey-policy.test.ts; no frontend E2E path is involved.
  • [ ] I have tested my code manually, and I have provided steps how to reproduce my tests. Manual DB-backed testing could not be run locally without bun/dependencies; reproducible validation steps are listed in the Test plan.

Refs #1667 /claim #1667

Summary by CodeRabbit

  • Security

    • Stricter validation of webhook API key scopes (read, write, upload, all)
    • Enforced organization and app-level restrictions for webhook API keys
    • API key expiration requirements honored when configured
    • Access control policies tightened for webhook and delivery operations
  • Tests

    • New REST tests verifying legacy non-expiring keys are denied and compliant expiring subkeys can read webhooks and deliveries
    • Added test confirming app-scoped keys cannot read specific webhook rows

Review Change Stack

teixr12 avatar May 11 '26 09:05 teixr12

[!WARNING]

Rate limit exceeded

@teixr12 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 46 minutes and 55 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: b617fe99-7177-4b06-8d41-5dff79f06b4b

๐Ÿ“ฅ Commits

Reviewing files that changed from the base of the PR and between dd5648b4d0f09e27906e7ba3c930c363752e97bd and a622f0b1e3ba844e4354156bd96fc61b543dcf19.

๐Ÿ“’ Files selected for processing (1)
  • supabase/migrations/20260511061700_harden_webhook_rls_apikey_scope.sql
๐Ÿ“ Walkthrough

Walkthrough

Adds a SECURITY DEFINER SQL helper public.webhook_allowed_org_ids to resolve/validate API-key identity for webhook RLS, updates RLS policies on webhooks and webhook_deliveries to call it, and extends tests to exercise REST access with legacy, expiring, and app-scoped API keys.

Changes

API Key Webhook RLS Hardening

Layer / File(s) Summary
DB helper: webhook_allowed_org_ids
supabase/migrations/20260511061700_harden_webhook_rls_apikey_scope.sql
Adds public.webhook_allowed_org_ids(min_right public.user_min_right, keymode public.key_mode[]) RETURNS uuid[] (SECURITY DEFINER) that resolves identity from auth or API-key header, validates mode/app-scoping/expiration, gathers candidate org IDs, filters by apikey/org constraints, and delegates to public.check_min_rights.
RLS: public.webhooks
supabase/migrations/20260511061700_harden_webhook_rls_apikey_scope.sql
Drops and recreates SELECT/INSERT/UPDATE/DELETE policies for authenticated, anon, using org_id = ANY(webhook_allowed_org_ids('admin', '{all,write,upload}'::public.key_mode[])) in USING and WITH CHECK.
RLS: public.webhook_deliveries
supabase/migrations/20260511061700_harden_webhook_rls_apikey_scope.sql
Drops and recreates policies: SELECT uses webhook_allowed_org_ids('read', '{read,write,upload,all}'::public.key_mode[]); INSERT/UPDATE use webhook_allowed_org_ids('admin', '{all,write,upload}'::public.key_mode[]) for authenticated, anon.
Test imports
tests/webhooks-apikey-policy.test.ts, tests/webhooks.test.ts
Adds SUPABASE_ANON_KEY and SUPABASE_BASE_URL imports for REST requests.
Test fixture: org policy
tests/webhooks-apikey-policy.test.ts
Seeded org policy set to require_apikey_expiration = true and max_apikey_expiration_days = NULL.
Tests: REST GET webhook access cases
tests/webhooks-apikey-policy.test.ts, tests/webhooks.test.ts
Adds REST GET tests against /rest/v1/webhooks and /rest/v1/webhook_deliveries using legacy non-expiring org keys, expiring org subkeys, and app-scoped keys; asserts HTTP 200 with empty or expected rows.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant PostgREST
  participant Database
  Client->>PostgREST: REST GET /rest/v1/webhooks (headers: apikey / Authorization / capgkey)
  PostgREST->>Database: SQL SELECT triggers RLS on public.webhooks
  Database->>Database: call public.webhook_allowed_org_ids(min_right, keymode[])
  Database-->>Database: resolve apikey header, validate mode, limited_to_apps/orgs, expiration
  Database->>Database: call public.check_min_rights(...) to enforce min-rights
  Database-->>PostgREST: filtered rows (empty if no eligible org_ids)
  PostgREST-->>Client: HTTP 200 JSON array

Estimated code review effort

๐ŸŽฏ 4 (Complex) | โฑ๏ธ ~45 minutes

Possibly related PRs

  • Cap-go/capgo#1948: Modifies API-key lookup/validation (find_apikey_by_value) which the new helper calls.
  • Cap-go/capgo#2080: Changes to public.check_min_rights that the helper invokes.
  • Cap-go/capgo#1966: Hardening of SECURITY DEFINER/EXECUTE grants for API-key helper functions referenced by this change.

Suggested labels

codex

Poem

๐Ÿ‡
I hop the headers, sniff each key,
I guard the webhooks silently.
Expired ones bounce, app keys deter,
Only rightful orgs may stir.
Rabbit done โ€” safe webhook tree.

๐Ÿšฅ Pre-merge checks | โœ… 5
โœ… Passed checks (5 passed)
Check name Status Explanation
Title check โœ… Passed The title accurately summarizes the main change: aligning RLS API key scope with org webhook policy through a new webhook-specific helper.
Description check โœ… Passed The PR description covers all required sections with detailed explanations of changes, test plan, and checklist responses; only non-applicable sections (screenshots, docs) are marked N/A.
Docstring Coverage โœ… Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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

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 11 '26 09:05 coderabbitai[bot]

Merging this PR will not alter performance

โœ… 43 untouched benchmarks
โฉ 2 skipped benchmarks[^skipped]


Comparing teixr12:bounty/webhook-rls-apikey-scope (a622f0b) with main (30cedef)

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 11 '26 09:05 codspeed[bot]

Runtime/performance note for reviewers:

  • Execution model: the new webhook-specific helper is used only by webhook and webhook delivery RLS policies when a request carries an API key header. It is not on the shared non-webhook helper path.
  • Per-row work: one API-key lookup via the existing find_apikey_by_value() path, simple array/expiration checks, and one primary-key lookup against orgs for the target org policy.
  • Cardinality: the target org lookup is one row; API-key resolution is the same bounded lookup pattern already used by the existing RLS/API-key helpers.
  • CI evidence: CodSpeed reports that merging this PR does not alter performance.
  • Local EXPLAIN: I cannot produce truthful EXPLAIN (ANALYZE, BUFFERS) output from this checkout because there is no local psql, supabase, bun, or running test DB available. I do not want to invent timings. A maintainer can run the helper under a local reset DB with a representative API key/org pair if project policy requires DB-backed timings before merge.

teixr12 avatar May 11 '26 09:05 teixr12

Addressed the consistency point in ac03fb5: the webhook-specific RLS helper now matches the route-level webhook guard by enforcing the required-expiration policy only, without adding a direct-REST-only max_apikey_expiration_days denial. I also adjusted the regression setup so it no longer implies max-days route coverage.

teixr12 avatar May 11 '26 13:05 teixr12

The new RLS helper appears to drop valid RBAC-only access at the final filter. webhook_allowed_org_ids() builds candidate_orgs from legacy org_users, user RBAC bindings, API-key RBAC bindings, and group RBAC bindings, but then every candidate is filtered with public.check_min_rights(...). That helper only checks org_users.user_right; it does not evaluate rbac_has_permission() / rbac_check_permission_direct().

So an org that relies on new RBAC for webhook administration can have a valid org-scoped role binding in candidate_orgs, then lose the row because the user/key does not also have a legacy org_users.user_right >= admin/read row. The tests cover legacy org keys, but not an RBAC-only org/key path through direct REST.

I would make the final filter call the same RBAC-aware permission path used by route handlers (or explicitly map webhook read/admin to RBAC permission keys), and add a regression where use_new_rbac = true, the principal has only an org-scoped RBAC role binding, and direct REST can still read/manage the webhook rows.

digzrow-coder avatar May 13 '26 19:05 digzrow-coder

Quick safety check on the expiration guard here: what does public.is_apikey_expired() return when expires_at IS NULL?

The PR's stated goal is to enforce the org's expiration policy at the RLS layer, but if is_apikey_expired(NULL) returns false (i.e. "a key with no expiration is not expired"), legacy non-expiring keys against an org that has require_apikey_expiration = true would still pass this guard and reach the table โ€” which would contradict the route-level enforcement added in #2130.

Could you either link the is_apikey_expired definition for quick confirmation, or add a test case for expires_at IS NULL on an org with require_apikey_expiration = true (expected: deny + a WEBHOOK_ALLOWED_ORGS_EXPIRED log entry, or a new dedicated code for the null case)?

Related minor: the limited_to_apps check uses COALESCE(array_length(..., 1), 0) > 0. array_length returns NULL for both NULL columns and empty arrays '{}' โ€” the COALESCE handles both consistently, but cardinality() would be more explicit if the column is non-null in practice.

austin33133-maker avatar May 14 '26 05:05 austin33133-maker