Restrict organization management email updates
Summary
- Keep organization
management_emailchanges behind the dedicated email-change path. - Sync Stripe before persisting the management email and use the service-role client only for the approved final write.
- Block authenticated direct table updates to
orgs.management_emailwith a database trigger. - Route
organization set --emailthroughprivate/set_org_emailand document the super-admin requirement. - Add regressions for direct table writes and the public organization update path.
Motivation
The management email is used for billing-related communication and customer sync. Org admin update paths could change that field without the dedicated Stripe synchronization and rollback behavior.
Business Impact
This reduces billing-contact takeover risk, keeps Capgo's Stripe customer email aligned with the organization record, and preserves the existing public update endpoint while tightening the sensitive field boundary.
/claim #1667
Test Plan
- [x] GitHub CI passed on head
18cf36e. - [x]
bunx eslint "supabase/functions/_backend/public/organization/put.ts" "supabase/functions/_backend/private/set_org_email.ts" "tests/organization-api.test.ts" "tests/organization-put-stripe-sync.unit.test.ts" "cli/src/organization/set.ts" "cli/src/index.ts" - [x]
bunx vitest run tests/organization-put-stripe-sync.unit.test.ts - [x]
bun run typecheck - [x]
bun run lintincli/ - [x]
bun run buildincli/ - [x]
bun run test:mcpincli/ - [x]
bun run test:bundleincli/ - [x]
git diff --check - [ ] Supabase-backed focused organization API regression was attempted locally, but Docker Desktop/Supabase was unavailable.
This PR adds authorization control for Management Email Authorization 🎯 2 (Simple) | ⏱️ ~10 minutes 🐰 A bunny hops down authorization lane,
Guarding ✏️ Tip: You can configure your own custom pre-merge checks in the settings.📝 Walkthrough
Walkthrough
management_email updates. A new helper function restricts such updates to users with org.update_billing permission. The PUT endpoint conditionally invokes this check, and an integration test verifies that unauthorized users receive a 403 error.Changes
Layer / File(s)
Summary
Authorization Helper
supabase/functions/_backend/public/organization/put.tsNew
ensureManagementEmailAccess function checks org.update_billing permission and throws 403 not_authorized if access is denied.
Endpoint Integration
supabase/functions/_backend/public/organization/put.tsPUT endpoint conditionally calls the authorization helper when
management_email is present in the request body.
Authorization Test
tests/organization-api.test.tsIntegration test confirms org admin cannot update
management_email without org.update_billing permission, expects 403 not_authorized, and verifies the database value remains unchanged.Estimated code review effort
Possibly related PRs
supabase/functions/_backend/public/organization/put.ts with different authorization and validation logic.Suggested labels
codexPoem
management_email with RBAC's chain,
Org admins now get a friendly 403,
Only billing hearts may pass, you'll see! ✨🚥 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 accurately and concisely summarizes the main change—restricting management email updates to prevent unauthorized changes by regular org admins.
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.
Description check
✅ Passed
The PR description includes all required template sections with substantial detail, though Screenshots section can be skipped for backend changes.
✨ Finishing Touches
🧪 Generate unit tests (beta)
[!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.
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.
Merging this PR will not alter performance
✅ 43 untouched benchmarks
⏩ 2 skipped benchmarks[^skipped]
Comparing slashdevcorpse:codex/capgo-management-email-authz (18cf36e) with main (38e5856)[^unexpected-base]
[^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.
[^unexpected-base]: No successful run was found on main (3d184f8) during the generation of this report, so 38e5856 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.
CI note: the repository Run tests workflow reached setup, lint, typecheck, Supabase start/reset, DB tests, and many backend tests successfully, then the Run all backend and CLI tests step ended with The operation was canceled.
I tried to rerun the cancelled job, but GitHub returned 403 for this fork PR. Could a maintainer rerun the cancelled Run tests job when convenient?
Update: I corrected the regression test fixture so it uses an org admin caller without creator/super-admin authority.
Latest head b60021d is now green: backend tests, Playwright, SonarCloud, CodSpeed, Socket, dead-code, and benchmarks all pass.
Update:
- Addressed the Stripe sync bypass:
PUT /organizationstill acceptsmanagement_email, but now requires the same super-admin boundary as the dedicated email path and callsupdateCustomerEmail(...)with rollback if the DB update fails or a later name-sync rollback is needed. - Closed the direct table/CLI bypass: added a migration trigger that blocks non-super-admin direct updates to
orgs.management_email, and changedorganization set --emailto invokeprivate/set_org_emailinstead of writing the column directly. - Added regression coverage for admin-level API updates and direct Supabase table updates leaving
management_emailunchanged. - Verification: local targeted ESLint, root typecheck, CLI lint/build/MCP smoke/bundle tests passed. GitHub CI is green on
d61100fwith 25/25 checks passing.
Pushed 77170ba to tighten the remaining table-write invariant.
Changes:
- Direct user-context updates to
orgs.management_emailare now blocked for both admins and super admins. private/set_org_emailandPUT /organizationstill perform permission checks and Stripe sync first, then persist the final email through the service-role client.- Added a regression for direct super-admin table updates and a unit test that verifies the public organization update path writes through the service-role client after Stripe email sync.
Validation:
bunx vitest run tests/organization-put-stripe-sync.unit.test.tsbunx eslint supabase/functions/_backend/private/set_org_email.ts supabase/functions/_backend/public/organization/put.ts tests/organization-put-stripe-sync.unit.test.ts tests/organization-api.test.tsgit diff --check
I could not run the Supabase-backed tests/organization-api.test.ts slice locally because Docker Desktop is not running in this environment; the branch CI should cover that database-backed path.
Quality Gate passed
Issues
1 New issue
0 Accepted issues
Measures
0 Security Hotspots
0.0% Coverage on New Code
0.0% Duplication on New Code
Nice tightening of the management-email path. Two correctness concerns and a smaller defense-in-depth note before this lands.
1. Concurrent management_email updates can desync Stripe and the DB
In put.ts the update flow for management_email looks like:
updateCustomerEmail(c, currentOrg.customer_id, body.management_email)(Stripe first)updateOrg(writeSupabase, ...updateFields)(DB second)
There's an expectedCurrentName optimistic-concurrency guard for the name path, but no equivalent expectedCurrentManagementEmail for the email path. If two super-admins call PUT at the same time with different new emails on the same org:
- Both pass
ensureManagementEmailAccess. - Both run Stripe
updateCustomerEmail-- order is non-deterministic, last write wins on Stripe. - Both run
updateOrgwith the sameorgId-- last write wins on DB.
There's no guarantee the Stripe last-write matches the DB last-write. End state: orgs.management_email says A, Stripe customer.email says B.
Suggestion: extend buildExpectedCurrentFields / expectedCurrentName to include management_email when shouldSyncStripeEmail is true, and pass expectedCurrentManagementEmail: currentOrg.management_email so the DB write fails fast (and the existing Stripe rollback kicks in) if another caller raced ahead.
A regression test that fires two concurrent PUTs with different emails for the same org and asserts the final Stripe email and orgs.management_email agree would catch this.
2. Post-update Stripe sync failure: rollback ordering can leave Stripe with the new email
Around line 117-120 in the post-update Stripe-name-sync error handler, the rollback runs:
ts try { await updateOrg(writeSupabase, body.orgId, rollbackFields, { expectedCurrentName, expectedCurrentFields }) if (shouldSyncStripeEmail && currentOrg) { await rollbackStripeCustomerEmail(c, currentOrg, stripeError) } } catch (rollbackError) { throw simpleError('cannot_update_org', 'Cannot update org', { ... }) }
If updateOrg throws (e.g. expectedCurrentName mismatch from a racing update), the rollbackStripeCustomerEmail line is never reached. Stripe is left with the new email, DB is also still on the new email (since the bulk update fields succeeded earlier), and the caller sees cannot_update_org. The outer name-sync rollback intent fails open instead of restoring Stripe.
Suggestion: invert order, or wrap each in its own try so a DB-rollback failure doesn't prevent Stripe rollback. Something like:
ts const dbRollbackError = await tryUpdateOrg(...).catch(e => e) const stripeRollbackError = shouldSyncStripeEmail ? await rollbackStripeCustomerEmail(c, currentOrg, stripeError).catch(e => e) : null if (dbRollbackError || stripeRollbackError) { throw simpleError('cannot_update_org', 'Cannot update org', { error, dbRollbackError, stripeRollbackError, }) }
3. Minor: trigger doesn't cover SECURITY DEFINER bypass
The migration's prevent_org_management_email_direct_update trigger checks auth.role() = 'service_role'. Any existing PL/pgSQL SECURITY DEFINER function that does UPDATE orgs SET management_email = ... and is owned by a privileged role (postgres/service_role) will bypass this gate. Worth a quick audit:
sql SELECT n.nspname, p.proname FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE prosecdef = true AND prosrc ILIKE '%update%orgs%management_email%';
If any hits, route them through the email-sync helper or add an explicit caller-allowlist column to the trigger.
Happy to send a PR with the concurrent-update regression test and the rollback restructuring if (1) and (2) get acked.