fix(rbac): pin organization owner tenant in DB instead of deriving at runtime

Plan 3's isOwnerTenant resolved "is this tenant the owner tenant?"
by looking up the owner user's CURRENT tenant via userRepo. That
breaks silently the moment the owner user is moved to another
tenant: the formerly-protected owning tenant becomes removable
(can be kicked from OTM, role-downgraded), and the new tenant the
owner moved to is treated as untouchable even though it isn't even
in OTM.

Promote owner-tenant to a first-class column on `organizations`:

- New migration 000046 adds owner_tenant_id BIGINT NOT NULL with
  index. Backfill: (1) owner user's current tenant when known,
  (2) earliest Admin tenant in OTM as fallback for orphans, then
  (3) RAISE EXCEPTION on anything still NULL — refuse to silently
  ship a bogus value. SQLite init schema mirrors the column.

- CreateOrganization now sets OwnerTenantID at create time so the
  pinned value is correct for all new orgs.

- isOwnerTenant becomes a pure equality check on the persisted
  column — no userRepo lookup, no error tuple. Fail-closed on a
  zero column value (legacy data not yet backfilled or unit tests
  bypassing the migration) so the worst case is "membership table
  frozen for that org" rather than "owner tenant is removable",
  matching the prior fail-closed-on-error semantics.

- RemoveTenantMember / UpdateTenantMemberRole simplify to a single
  bool check.
This commit is contained in:
wizardchen
2026-05-15 22:53:02 +08:00
committed by lyingbug
parent 7720db39fa
commit a16fe83034
5 changed files with 134 additions and 39 deletions
+3
View File
@@ -377,6 +377,8 @@ CREATE TABLE IF NOT EXISTS organizations (
name VARCHAR(255) NOT NULL,
description TEXT,
owner_id VARCHAR(36) NOT NULL,
-- Plan 3 (#1303): owning tenant pinned at create time; see migration 000046.
owner_tenant_id INTEGER NOT NULL DEFAULT 0,
invite_code VARCHAR(32),
require_approval BOOLEAN DEFAULT 0,
invite_code_expires_at DATETIME,
@@ -390,6 +392,7 @@ CREATE TABLE IF NOT EXISTS organizations (
);
CREATE INDEX IF NOT EXISTS idx_organizations_owner_id ON organizations(owner_id);
CREATE INDEX IF NOT EXISTS idx_organizations_owner_tenant ON organizations(owner_tenant_id);
CREATE INDEX IF NOT EXISTS idx_organizations_deleted_at ON organizations(deleted_at);
CREATE TABLE IF NOT EXISTS organization_tenant_members (