fix(rbac): dedup pending join/upgrade requests per (org, tenant, type)

Plan 3 of #1303 changed the join-request lookup key from per-user
to per-tenant (GetPendingRequestByTenantAndType), but didn't touch
existing data or add a structural constraint. Result: any (org,
tenant) that had multiple pending rows under the old per-user model
now has ambiguous "which one wins" semantics — the LIMIT 1 query
returns one row, the others stay pending and resurface in admin
lists after the first is approved/rejected.

Two fixes:

1. Migration 000045 up.sql now collapses pre-existing pending rows
   to one per (org, tenant, type), keeping the earliest by
   created_at. The losers are flagged status='rejected' with a
   '[Plan 3] superseded' review_message so the audit trail shows
   it was a system cleanup, not a human reject. down.sql drops
   the new index but leaves the data mutation in place — we don't
   have enough information to safely re-promote the discarded rows.

2. Add a partial unique index on
   (organization_id, tenant_id, request_type) WHERE status='pending'
   to both the PG migration and the SQLite init schema. This makes
   the invariant structural so SubmitJoinRequest /
   RequestRoleUpgrade cannot regress.

Approved/rejected history is intentionally unconstrained so the
audit trail remains complete.
This commit is contained in:
wizardchen
2026-05-15 22:52:45 +08:00
committed by lyingbug
parent f6684f226b
commit 7720db39fa
3 changed files with 50 additions and 0 deletions
@@ -24,4 +24,12 @@ ALTER INDEX IF EXISTS idx_org_members_role_pre_plan3 RENAME TO idx_org_
-- Drop the new table. The unique/secondary indexes go with it.
DROP TABLE IF EXISTS organization_tenant_members;
-- Drop the partial unique index added in step 5 of up.sql. The data
-- mutation (pending → rejected) is intentionally NOT reverted: those
-- duplicates were already wrong under Plan 3 semantics, and we don't
-- have enough information to safely re-promote which one should win.
-- The `[Plan 3] superseded` review_message tag makes the affected
-- rows easy to audit if a manual fix is later needed.
DROP INDEX IF EXISTS uq_org_join_requests_pending_per_tenant;
DO $$ BEGIN RAISE NOTICE '[Migration 000045] Plan 3 reverted'; END $$;