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
+7
View File
@@ -69,6 +69,13 @@ type Organization struct {
Avatar string `json:"avatar" gorm:"type:varchar(512)"`
// User ID of the organization owner
OwnerID string `json:"owner_id" gorm:"type:varchar(36);not null;index"`
// OwnerTenantID is the tenant the owner belonged to when the
// organization was created. Plan 3 (#1303) treats this tenant as
// the org's "owning tenant": its membership row in
// organization_tenant_members is undeletable / unchangeable so
// the org can never be orphaned even if the owner user later
// switches tenants or is soft-deleted. See migration 000046.
OwnerTenantID uint64 `json:"owner_tenant_id" gorm:"not null;index"`
// Unique invitation code for joining the organization
InviteCode string `json:"invite_code" gorm:"type:varchar(32);uniqueIndex"`
// When the current invite code expires; nil means no expiry