f3d1210577
Tighten correctness, security and observability of the tenant RBAC foundation introduced in 3c4cdd70 in response to internal review. Bugfixes - custom_agents.runnable_by_viewer: drop the GORM `default:true` tag. GORM treats a plain bool's zero value as "unspecified" and silently rewrites it to the column default on insert, which would prevent admins from ever creating an agent with viewer-runtime disabled. The column-level DEFAULT TRUE on the database side still backstops rows inserted by raw SQL / migrations. - TenantMemberRepository.HasAnyMembers: replace `Limit(1).Count(&n)` with `Take(&probe)`. GORM's Count ignores Limit and scans the whole table, which matters because this runs on the auth middleware's hot path for users without a cached membership. - service/user.LoginWithOIDC: include User, Tenant and Memberships in the OIDCCallbackResponse so the OIDC flow returns the same shape as password login (previously User and friends were left nil). Security - middleware/auth.resolveTenantRole: restrict orphan-tenant auto-promotion to the caller's home tenant. Cross-tenant superuser visits and JWTs minted for foreign tenants no longer trigger silent Owner grants. Two regression tests pin the new behaviour. - service/user.synthFallbackMembership: default the synthesised role to Viewer instead of Owner. The login response only feeds UI; the backend re-derives the real role from tenant_members on every request, so showing a Viewer UI is preferable to a misleading Owner UI that would surface admin controls the backend will then 403. - migrations/versioned/000043_tenant_rbac.down.sql: gate the destructive drop behind a `weknora.allow_destructive_migration` GUC so an accidental `migrate down` cannot wipe role data in production. - frontend/src/stores/auth.ts: comment currentTenantRole as rendering-only so future PRs cannot mistake the localStorage-backed value for an authorisation signal. API contract - Memberships in LoginResponse and OIDCCallbackResponse now serialises without omitempty, and buildMembershipsForUser / synthFallbackMembership always return a non-nil slice — frontend can rely on JSON `[]`. - handler/auth.GetCurrentUser includes memberships so /auth/me refreshes recover currentTenantRole after a page reload. Performance - Add TenantService.GetTenantsByIDs (with the matching repo method) and use it inside buildMembershipsForUser to batch tenant-name lookups instead of issuing one query per membership. Observability - Replace the remaining `log.Printf` calls in middleware/auth with contextual logger.Warnf / logger.Infof so role resolution events ride the standard request-id / Langfuse trace plumbing. The successful auto-promote line is tagged `[audit]` for log mining. Tests - internal/application/service/tenant_member_test.go: hand-rolled fakeTenantMemberRepo plus 11 cases covering AddMember validation, EnsureOwner idempotence, "cannot demote/remove the last Owner", same-role no-op, ErrInvalidTenantRole / ErrMembershipNotFound, and the TenantRole.HasPermission lattice. - internal/middleware/auth_role_test.go: fakeMemberService plus 8 cases pinning every branch of resolveTenantRole, including the two H1 regressions (cross-tenant superuser must not auto-promote; orphan auto-promote requires the home tenant).
33 lines
1.5 KiB
SQL
33 lines
1.5 KiB
SQL
-- Migration 000043 down: revert tenant RBAC schema additions.
|
|
--
|
|
-- DANGER: This drops the tenant_members table and the creator_id /
|
|
-- runnable_by_viewer columns. All role assignments, KB ownership
|
|
-- metadata, and viewer-runtime flags are lost UNRECOVERABLY.
|
|
-- Only intended for development rollbacks, never for production.
|
|
--
|
|
-- Operators who really need to run this in a non-dev environment must set
|
|
-- the session-level GUC `weknora.allow_destructive_migration` to 'true'
|
|
-- first (e.g. `SET weknora.allow_destructive_migration = 'true';`).
|
|
-- Otherwise the migration aborts before touching any data.
|
|
DO $$
|
|
BEGIN
|
|
IF coalesce(current_setting('weknora.allow_destructive_migration', true), 'false') <> 'true' THEN
|
|
RAISE EXCEPTION
|
|
'[Migration 000043 down] BLOCKED: refuse to drop tenant_members / creator_id / runnable_by_viewer. '
|
|
'Set weknora.allow_destructive_migration = ''true'' in this session to override.';
|
|
END IF;
|
|
RAISE WARNING '[Migration 000043 down] Reverting tenant RBAC — role data will be lost';
|
|
END $$;
|
|
|
|
ALTER TABLE custom_agents DROP COLUMN IF EXISTS runnable_by_viewer;
|
|
|
|
DROP INDEX IF EXISTS idx_knowledge_bases_tenant_creator;
|
|
ALTER TABLE knowledge_bases DROP COLUMN IF EXISTS creator_id;
|
|
|
|
DROP INDEX IF EXISTS idx_tenant_members_user;
|
|
DROP INDEX IF EXISTS idx_tenant_members_tenant_role;
|
|
DROP INDEX IF EXISTS idx_tenant_members_user_tenant_unique;
|
|
DROP TABLE IF EXISTS tenant_members;
|
|
|
|
DO $$ BEGIN RAISE NOTICE '[Migration 000043 down] tenant RBAC reverted'; END $$;
|