🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(rbac): reshape role assignment storage (#18490)
Mark Salpeteref42ef7d2ec1
diff --git a/packages/shared/prisma/migrations/20261008120000_reshape_role_assignments/migration.sql b/packages/shared/prisma/migrations/20261008120000_reshape_role_assignments/migration.sqlnew file mode 100644index 0000000000..41c9f06b86--- /dev/null+++ b/packages/shared/prisma/migrations/20261008120000_reshape_role_assignments/migration.sql@@ -0,0 +1,143 @@+BEGIN;++LOCK TABLE "role_assignments" IN ACCESS EXCLUSIVE MODE;++DO $$+BEGIN+ IF EXISTS (+ SELECT 1 FROM "role_assignments"+ WHERE "owner_org_id" IS NOT NULL AND "owner_org_id" <> "org_id"+ ) THEN+ RAISE EXCEPTION 'Cannot reshape role assignments whose organization owner differs from their tenant';+ END IF;+END $$;++ALTER TABLE "role_assignments"+ ADD COLUMN "project_id" TEXT,+ ADD COLUMN "user_id" TEXT,+ ADD COLUMN "api_key_id" TEXT,+ ADD COLUMN "owner_id" TEXT,+ ADD COLUMN "principal_id" TEXT,+ ADD COLUMN "role_id" TEXT;++UPDATE "role_assignments"+SET "project_id" = "owner_project_id",+ "user_id" = "principal_user_id",+ "api_key_id" = "principal_api_key_id",+ "owner_id" = CASE+ WHEN "owner_project_id" IS NOT NULL THEN 'project/' || "owner_project_id"+ ELSE 'organization/' || "owner_org_id"+ END,+ "principal_id" = CASE+ WHEN "principal_user_id" IS NOT NULL THEN 'user/' || "principal_user_id"+ ELSE 'apiKey/' || "principal_api_key_id"+ END,+ "role_id" = 'system/' || "system_role"::text;++CREATE FUNCTION "role_assignments_fill_legacy_insert"() RETURNS trigger+LANGUAGE plpgsql AS $$+BEGIN+ NEW."project_id" := COALESCE(NEW."project_id", NEW."owner_project_id");+ NEW."owner_project_id" := COALESCE(NEW."owner_project_id", NEW."project_id");+ NEW."user_id" := COALESCE(NEW."user_id", NEW."principal_user_id");+ NEW."principal_user_id" := COALESCE(NEW."principal_user_id", NEW."user_id");+ NEW."api_key_id" := COALESCE(NEW."api_key_id", NEW."principal_api_key_id");+ NEW."principal_api_key_id" := COALESCE(NEW."principal_api_key_id", NEW."api_key_id");++ IF NEW."owner_id" IS NULL THEN+ NEW."owner_id" := CASE+ WHEN NEW."owner_project_id" IS NOT NULL THEN 'project/' || NEW."owner_project_id"+ ELSE 'organization/' || NEW."owner_org_id"+ END;+ ELSIF NEW."owner_project_id" IS NULL+ AND NEW."owner_org_id" IS NULL+ AND NEW."owner_id" = 'organization/' || NEW."org_id" THEN+ NEW."owner_org_id" := NEW."org_id";+ END IF;++ IF NEW."principal_id" IS NULL THEN+ NEW."principal_id" := CASE+ WHEN NEW."principal_user_id" IS NOT NULL THEN 'user/' || NEW."principal_user_id"+ ELSE 'apiKey/' || NEW."principal_api_key_id"+ END;+ END IF;++ IF NEW."role_id" IS NULL THEN+ NEW."role_id" := 'system/' || NEW."system_role"::text;+ END IF;++ RETURN NEW;+END $$;++CREATE TRIGGER "role_assignments_fill_legacy_insert"+BEFORE INSERT ON "role_assignments"+FOR EACH ROW EXECUTE FUNCTION "role_assignments_fill_legacy_insert"();++ALTER TABLE "role_assignments"+ ALTER COLUMN "owner_id" SET NOT NULL,+ ALTER COLUMN "principal_id" SET NOT NULL,+ ALTER COLUMN "role_id" SET NOT NULL;++CREATE FUNCTION "role_assignments_validate_legacy_update"() RETURNS trigger+LANGUAGE plpgsql AS $$+BEGIN+ IF NEW."project_id" IS DISTINCT FROM NEW."owner_project_id"+ OR NEW."user_id" IS DISTINCT FROM NEW."principal_user_id"+ OR NEW."api_key_id" IS DISTINCT FROM NEW."principal_api_key_id"+ OR NEW."owner_org_id" IS DISTINCT FROM (CASE WHEN NEW."project_id" IS NULL THEN NEW."org_id" END) THEN+ RAISE EXCEPTION 'Role assignment legacy fields must match the active fields'+ USING ERRCODE = '23514', CONSTRAINT = 'role_assignments_legacy_fields_check';+ END IF;+ RETURN NEW;+END $$;++CREATE FUNCTION "role_assignments_sync_legacy_update"() RETURNS trigger+LANGUAGE plpgsql AS $$+BEGIN+ NEW."owner_project_id" := NEW."project_id";+ NEW."principal_user_id" := NEW."user_id";+ NEW."principal_api_key_id" := NEW."api_key_id";+ NEW."owner_org_id" := CASE WHEN NEW."project_id" IS NULL THEN NEW."org_id" END;+ RETURN NEW;+END $$;++CREATE TRIGGER "role_assignments_10_validate_legacy_update"+BEFORE UPDATE OF "owner_project_id", "principal_user_id", "principal_api_key_id", "owner_org_id" ON "role_assignments"+FOR EACH ROW EXECUTE FUNCTION "role_assignments_validate_legacy_update"();++CREATE TRIGGER "role_assignments_20_sync_legacy_update"+BEFORE UPDATE OF "project_id", "user_id", "api_key_id", "org_id" ON "role_assignments"+FOR EACH ROW EXECUTE FUNCTION "role_assignments_sync_legacy_update"();++ALTER TABLE "role_assignments"+ ADD CONSTRAINT "role_assignments_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ ADD CONSTRAINT "role_assignments_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ ADD CONSTRAINT "role_assignments_api_key_id_fkey" FOREIGN KEY ("api_key_id") REFERENCES "api_keys"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ ADD CONSTRAINT "role_assignments_owner_check" CHECK (+ "owner_id" = CASE+ WHEN "project_id" IS NOT NULL THEN 'project/' || "project_id"+ ELSE 'organization/' || "org_id"+ END+ ),+ ADD CONSTRAINT "role_assignments_principal_check" CHECK (+ ("user_id" IS NOT NULL AND "api_key_id" IS NULL AND "principal_id" = 'user/' || "user_id")+ OR+ ("user_id" IS NULL AND "api_key_id" IS NOT NULL AND "principal_id" = 'apiKey/' || "api_key_id")+ ),+ ADD CONSTRAINT "role_assignments_role_check" CHECK (+ "role_id" = 'system/' || "system_role"::text+ ),+ ADD CONSTRAINT "role_assignments_legacy_fields_check" CHECK (+ "project_id" IS NOT DISTINCT FROM "owner_project_id"+ AND "user_id" IS NOT DISTINCT FROM "principal_user_id"+ AND "api_key_id" IS NOT DISTINCT FROM "principal_api_key_id"+ AND "owner_org_id" IS NOT DISTINCT FROM CASE WHEN "project_id" IS NULL THEN "org_id" END+ );++CREATE UNIQUE INDEX "role_assignments_owner_id_principal_id_role_id_key" ON "role_assignments"("owner_id", "principal_id", "role_id");+CREATE INDEX "role_assignments_project_id_idx" ON "role_assignments"("project_id");+CREATE INDEX "role_assignments_principal_id_idx" ON "role_assignments"("principal_id");+CREATE INDEX "role_assignments_user_id_idx" ON "role_assignments"("user_id");+CREATE INDEX "role_assignments_api_key_id_idx" ON "role_assignments"("api_key_id");++COMMIT;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 822440ce32..0b72c47cbe 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -90,6 +90,8 @@ model User {evaluatorVersionsCreated EvaluatorVersion[] @relation("EvaluatorVersionCreatedByUser")evaluationRulesCreated EvaluationRule[] @relation("EvaluationRuleCreatedByUser")+ deprecatedRoleAssignments RoleAssignment[] @relation("DeprecatedRoleAssignmentUser") @ignore+@@map("users")}@@ -131,7 +133,8 @@ model Organization {gatewayConfig GatewayConfig?gatewayAiConnections GatewayAiConnection[]roleAssignments RoleAssignment[] @relation("RoleAssignmentTenant")- ownedRoleAssignments RoleAssignment[] @relation("RoleAssignmentOwnerOrganization")++ deprecatedRoleAssignments RoleAssignment[] @relation("DeprecatedRoleAssignmentOrganization") @ignore@@map("organizations")}@@ -208,6 +211,8 @@ model Project {topicClusteringRuns TopicClusteringRun[]gatewayConfigs GatewayConfig[] @relation("GatewayDefaultIngestionProject")+ deprecatedRoleAssignments RoleAssignment[] @relation("DeprecatedRoleAssignmentProject") @ignore+@@index([orgId])@@map("projects")}@@ -242,6 +247,8 @@ model ApiKey {gatewayAssociation GatewayApiKeyAssociation?roleAssignments RoleAssignment[]+ deprecatedRoleAssignments RoleAssignment[] @relation("DeprecatedRoleAssignmentApiKey") @ignore+@@index(orgId)@@index(projectId)@@index(createdByApiKeyId)@@ -265,28 +272,43 @@ enum SystemRole {}model RoleAssignment {- id String @id @default(cuid())- orgId String @map("org_id")- organization Organization @relation("RoleAssignmentTenant", fields: [orgId], references: [id], onDelete: Cascade)- principalUserId String? @map("principal_user_id")- principalUser User? @relation(fields: [principalUserId], references: [id], onDelete: Cascade)- principalApiKeyId String? @map("principal_api_key_id")- principalApiKey ApiKey? @relation(fields: [principalApiKeyId], references: [id], onDelete: Cascade)- systemRole SystemRole @map("system_role")- ownerOrgId String? @map("owner_org_id")- ownerOrg Organization? @relation("RoleAssignmentOwnerOrganization", fields: [ownerOrgId], references: [id], onDelete: Cascade)- ownerProjectId String? @map("owner_project_id")- ownerProject Project? @relation(fields: [ownerProjectId], references: [id], onDelete: Cascade)- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")-- @@unique([principalUserId, ownerOrgId, systemRole], map: "role_assignments_user_org_role_key")- @@unique([principalUserId, ownerProjectId, systemRole], map: "role_assignments_user_project_role_key")- @@unique([principalApiKeyId, ownerOrgId, systemRole], map: "role_assignments_api_key_org_role_key")- @@unique([principalApiKeyId, ownerProjectId, systemRole], map: "role_assignments_api_key_project_role_key")+ id String @id @default(cuid())+ ownerId String @map("owner_id")+ projectId String? @map("project_id")+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)+ orgId String @map("org_id")+ organization Organization @relation("RoleAssignmentTenant", fields: [orgId], references: [id], onDelete: Cascade)+ principalId String @map("principal_id")+ userId String? @map("user_id")+ user User? @relation(fields: [userId], references: [id], onDelete: Cascade)+ apiKeyId String? @map("api_key_id")+ apiKey ApiKey? @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)+ roleId String @map("role_id")+ systemRole SystemRole @map("system_role")+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ deprecatedOwnerOrgId String? @map("owner_org_id") @ignore+ deprecatedOwnerOrg Organization? @relation("DeprecatedRoleAssignmentOrganization", fields: [deprecatedOwnerOrgId], references: [id], onDelete: Cascade) @ignore+ deprecatedOwnerProjectId String? @map("owner_project_id") @ignore+ deprecatedOwnerProject Project? @relation("DeprecatedRoleAssignmentProject", fields: [deprecatedOwnerProjectId], references: [id], onDelete: Cascade) @ignore+ deprecatedPrincipalUserId String? @map("principal_user_id") @ignore+ deprecatedPrincipalUser User? @relation("DeprecatedRoleAssignmentUser", fields: [deprecatedPrincipalUserId], references: [id], onDelete: Cascade) @ignore+ deprecatedPrincipalApiKeyId String? @map("principal_api_key_id") @ignore+ deprecatedPrincipalApiKey ApiKey? @relation("DeprecatedRoleAssignmentApiKey", fields: [deprecatedPrincipalApiKeyId], references: [id], onDelete: Cascade) @ignore++ @@unique([deprecatedPrincipalUserId, deprecatedOwnerOrgId, systemRole], map: "role_assignments_user_org_role_key")+ @@unique([deprecatedPrincipalUserId, deprecatedOwnerProjectId, systemRole], map: "role_assignments_user_project_role_key")+ @@unique([deprecatedPrincipalApiKeyId, deprecatedOwnerOrgId, systemRole], map: "role_assignments_api_key_org_role_key")+ @@unique([deprecatedPrincipalApiKeyId, deprecatedOwnerProjectId, systemRole], map: "role_assignments_api_key_project_role_key")+ @@unique([ownerId, principalId, roleId])+ @@index([deprecatedOwnerOrgId], map: "role_assignments_owner_org_id_idx")+ @@index([deprecatedOwnerProjectId], map: "role_assignments_owner_project_id_idx")@@index([orgId])- @@index([ownerOrgId])- @@index([ownerProjectId])+ @@index([projectId])+ @@index([principalId])+ @@index([userId])+ @@index([apiKeyId])@@map("role_assignments")}diff --git a/packages/shared/scripts/seeder/load-seed-clickhouse.ts b/packages/shared/scripts/seeder/load-seed-clickhouse.tsindex 6c93d784d3..52fc204f11 100644--- a/packages/shared/scripts/seeder/load-seed-clickhouse.ts+++ b/packages/shared/scripts/seeder/load-seed-clickhouse.ts@@ -5,7 +5,7 @@ import {getDisplaySecretKey,logger,} from "../../src/server";-import { assignRole } from "../../src/features/rbac/roleAssignmentRepository";+import { assignRole } from "../../src/features/rbac/roleAssignmentService";import {ApiKeyId,OrganizationId,diff --git a/packages/shared/src/features/rbac/roleAssignmentRepository.ts b/packages/shared/src/features/rbac/roleAssignmentRepository.tsdeleted file mode 100644index af72d5e7f9..0000000000--- a/packages/shared/src/features/rbac/roleAssignmentRepository.ts+++ /dev/null@@ -1,78 +0,0 @@-import {- type PrismaClient,- type Prisma,- type RoleAssignment as StoredRoleAssignment,-} from "@prisma/client";-import { NotImplementedError } from "../../errors";-import { withTransaction } from "../../server/utils/withTransaction";-import {- hasApiKeyKind,- hasProjectKind,- hasSystemRoleKind,- toSystemRole,- untag,- type OwnerId,- type PrincipalId,- type RoleAssignment,-} from "./types";--type Tx = PrismaClient | Prisma.TransactionClient;--/** getRoleAssignmentsForPrincipal loads a principal's stored assignments. */-export async function getRoleAssignmentsForPrincipal(- tx: Tx,- principalId: PrincipalId,-): Promise<StoredRoleAssignment[]> {- return await tx.roleAssignment.findMany({- where: principalFields(principalId),- });-}--/** assignRole persists a system-role assignment in the supplied tenant. */-export async function assignRole(- tx: Tx,- ra: Omit<RoleAssignment, "id" | "createdAt" | "updatedAt">,-): Promise<void> {- if (!hasSystemRoleKind(ra.roleId)) {- throw new NotImplementedError("custom roles not yet supported");- }- await tx.roleAssignment.create({- data: {- orgId: untag(ra.tenantId),- ...principalFields(ra.principalId),- ...ownerFields(ra.ownerId),- systemRole: toSystemRole(ra.roleId),- },- });-}--/** transferRoleAssignments moves a transferred project's api-key assignments to the destination organization and drops its user assignments, mirroring the membership wipe. */-export async function transferRoleAssignments(- prisma: Tx,- projectId: string,- targetOrgId: string,-): Promise<void> {- await withTransaction(prisma, async (tx) => {- await tx.roleAssignment.updateMany({- where: { ownerProjectId: projectId, principalApiKeyId: { not: null } },- data: { orgId: targetOrgId },- });- await tx.roleAssignment.deleteMany({- where: { ownerProjectId: projectId, principalUserId: { not: null } },- });- });-}--/** principalFields selects the foreign key for a tagged principal. */-function principalFields(principalId: PrincipalId) {- return hasApiKeyKind(principalId)- ? { principalApiKeyId: untag(principalId) }- : { principalUserId: untag(principalId) };-}--/** ownerFields selects the foreign key for a tagged owner. */-function ownerFields(ownerId: OwnerId) {- return hasProjectKind(ownerId)- ? { ownerProjectId: untag(ownerId) }- : { ownerOrgId: untag(ownerId) };-}diff --git a/packages/shared/src/features/rbac/roleAssignmentService.ts b/packages/shared/src/features/rbac/roleAssignmentService.tsnew file mode 100644index 0000000000..a3d6e6d28f--- /dev/null+++ b/packages/shared/src/features/rbac/roleAssignmentService.ts@@ -0,0 +1,118 @@+import {+ SystemRole,+ type Prisma,+ type RoleAssignment as StoredRoleAssignment,+} from "@prisma/client";++import { InvalidRequestError, NotImplementedError } from "../../errors";+import { withTransaction } from "../../server/utils/withTransaction";+import {+ hasApiKeyKind,+ hasOrganizationKind,+ hasSystemRoleKind,+ untag,+ type PrincipalId,+ type OwnerId,+ type RoleAssignment,+ type RoleId,+ type TenantId,+} from "./types";++/** getRoleAssignmentsForPrincipal loads a principal's stored assignments. */+export async function getRoleAssignmentsForPrincipal(+ tx: Prisma.TransactionClient,+ principalId: PrincipalId,+): Promise<StoredRoleAssignment[]> {+ return await tx.roleAssignment.findMany({+ where: { principalId },+ });+}++/** assignRole persists a system-role assignment in the supplied tenant. */+export async function assignRole(+ prisma: Prisma.TransactionClient,+ ra: Omit<RoleAssignment, "id" | "createdAt" | "updatedAt">,+): Promise<void> {+ const roleFields = validateRole(ra.roleId);+ await withTransaction(prisma, async (tx) => {+ const ownerAndTenantFields = await validateTenancy(+ tx,+ ra.tenantId,+ ra.ownerId,+ );+ await tx.roleAssignment.create({+ data: {+ ...ownerAndTenantFields,+ ...principalFields(ra.principalId),+ ...roleFields,+ },+ });+ });+}++/** transferRoleAssignments moves a transferred project's api-key assignments to the destination organization and drops its user assignments, mirroring the membership wipe. */+export async function transferRoleAssignments(+ prisma: Prisma.TransactionClient,+ projectId: string,+ targetOrgId: string,+): Promise<void> {+ await withTransaction(prisma, async (tx) => {+ await tx.roleAssignment.updateMany({+ where: { projectId, apiKeyId: { not: null } },+ data: { orgId: targetOrgId },+ });+ await tx.roleAssignment.deleteMany({+ where: { projectId, userId: { not: null } },+ });+ });+}++/** validateTenancy holds project ownership stable until the transaction ends. */+async function validateTenancy(+ tx: Prisma.TransactionClient,+ tenantId: TenantId,+ ownerId: OwnerId,+) {+ const orgId = untag(tenantId);+ if (hasOrganizationKind(ownerId)) {+ if (ownerId !== tenantId) {+ throw new InvalidRequestError(+ "Role assignment owner must belong to its tenant",+ );+ }+ return { orgId, ownerId, projectId: null };+ }+ const projectId = untag(ownerId);+ const projects = await tx.$queryRaw<{ id: string }[]>`+ SELECT id FROM projects+ WHERE id = ${projectId} AND org_id = ${orgId}+ FOR SHARE+ `;+ if (projects.length === 0) {+ throw new InvalidRequestError(+ "Role assignment owner must belong to its tenant",+ );+ }+ return { orgId, ownerId, projectId };+}++/** principalFields pairs a tagged principal with its foreign key. */+function principalFields(principalId: PrincipalId) {+ return hasApiKeyKind(principalId)+ ? { principalId, apiKeyId: untag(principalId) }+ : { principalId, userId: untag(principalId) };+}++/** validateRole rejects unsupported roles and returns their storage fields. */+function validateRole(roleId: RoleId) {+ if (!hasSystemRoleKind(roleId)) {+ throw new NotImplementedError("custom roles not yet supported");+ }+ const systemRole = Object.values(SystemRole).find(+ (role) => role === untag(roleId),+ );+ if (systemRole === undefined) {+ throw new InvalidRequestError("Unknown system role");+ }+ return { roleId, systemRole };+}diff --git a/packages/shared/src/features/rbac/server.ts b/packages/shared/src/features/rbac/server.tsindex 178729cf8f..b52d33e703 100644--- a/packages/shared/src/features/rbac/server.ts+++ b/packages/shared/src/features/rbac/server.ts@@ -1 +1 @@-export * from "./roleAssignmentRepository";+export * from "./roleAssignmentService";diff --git a/packages/shared/src/server/auth/apiKeys.test.ts b/packages/shared/src/server/auth/apiKeys.test.tsindex fd7a5b20dc..cc9b84d29e 100644--- a/packages/shared/src/server/auth/apiKeys.test.ts+++ b/packages/shared/src/server/auth/apiKeys.test.ts@@ -102,13 +102,16 @@ describe("createApiKey assignment rows", () => {function makeTx() {const assignments: Array<{orgId: string;- principalApiKeyId: string;- ownerOrgId?: string;- ownerProjectId?: string;+ apiKeyId: string;+ principalId: string;+ ownerId: string;+ roleId: string;+ projectId: string | null;systemRole: string;}> = [];let apiKeyData: Record<string, unknown> = {};const tx = {+ $queryRaw: vi.fn(async () => [{ id: "proj_1" }]),apiKey: {create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {apiKeyData = data;@@ -152,8 +155,11 @@ describe("createApiKey assignment rows", () => {expect(assignments).toEqual([{orgId: ORG_ID,- principalApiKeyId: KEY_ID,- ownerProjectId: "proj_1",+ apiKeyId: KEY_ID,+ principalId: ApiKeyId(KEY_ID),+ ownerId: ProjectId("proj_1"),+ roleId: SystemRoleId("VIEWER"),+ projectId: "proj_1",systemRole: "VIEWER",},]);@@ -178,8 +184,11 @@ describe("createApiKey assignment rows", () => {expect(assignments).toEqual([{orgId: ORG_ID,- principalApiKeyId: KEY_ID,- ownerOrgId: ORG_ID,+ apiKeyId: KEY_ID,+ principalId: ApiKeyId(KEY_ID),+ ownerId: OrganizationId(ORG_ID),+ roleId: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),+ projectId: null,systemRole: "LEGACY_ORGANIZATION_API_KEY",},]);diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.tsindex ba30a99c27..be365c232a 100644--- a/packages/shared/src/server/auth/apiKeys.ts+++ b/packages/shared/src/server/auth/apiKeys.ts@@ -23,7 +23,7 @@ import {roleHasProjectPolicy,} from "../../features/rbac/systemRoleAccessRights";import { logger } from "../logger";-import { assignRole } from "../../features/rbac/roleAssignmentRepository";+import { assignRole } from "../../features/rbac/roleAssignmentService";import { invalidateCachedApiKeys } from "./invalidateApiKeys";import { withTransaction } from "../utils/withTransaction";diff --git a/packages/shared/src/server/test-utils/org-factory.ts b/packages/shared/src/server/test-utils/org-factory.tsindex b30b2f13db..8748c62c48 100644--- a/packages/shared/src/server/test-utils/org-factory.ts+++ b/packages/shared/src/server/test-utils/org-factory.ts@@ -8,7 +8,7 @@ import {SystemRoleId,} from "../../features/rbac/types";import { CloudConfigSchema } from "../../interfaces/cloudConfigSchema";-import { assignRole } from "../../features/rbac/roleAssignmentRepository";+import { assignRole } from "../../features/rbac/roleAssignmentService";import { createShaHash, getDisplaySecretKey } from "../auth/apiKeys";export function createBasicAuthHeader(diff --git a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.tsindex f67362da0b..cb0dab3c77 100644--- a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts+++ b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts@@ -281,9 +281,12 @@ describe("API-key cache invalidation on project/org lifecycle", () => {const assignment = await prisma.roleAssignment.create({data: {orgId,- principalUserId: user.id,- ownerProjectId: projectId,+ userId: user.id,+ principalId: `user/${user.id}`,+ projectId,+ ownerId: `project/${projectId}`,systemRole: "VIEWER",+ roleId: "system/VIEWER",},});diff --git a/web/src/__tests__/server/getRolesForPrincipal.servertest.ts b/web/src/__tests__/server/getRolesForPrincipal.servertest.tsindex 203ef4e300..6aeaab5f21 100644--- a/web/src/__tests__/server/getRolesForPrincipal.servertest.ts+++ b/web/src/__tests__/server/getRolesForPrincipal.servertest.ts@@ -52,7 +52,7 @@ describe("getRolesForPrincipal decision-equivalence", () => {tags: [],});- const roles = await getRolesForPrincipal(principalId);+ const roles = await getRolesForPrincipal(prisma, principalId);expect(roles).toHaveLength(1);for (const policy of roles[0].policies) {expect(policy.resources.length).toBeGreaterThan(0);@@ -101,7 +101,7 @@ describe("getRolesForPrincipal decision-equivalence", () => {tags: [],});- const roles = await getRolesForPrincipal(principalId);+ const roles = await getRolesForPrincipal(prisma, principalId);expect(roles).toHaveLength(2);const organizationRole = roles.find((role) => role.tenantId === OrganizationId(organization.orgId),@@ -147,9 +147,9 @@ describe("getRolesForPrincipal decision-equivalence", () => {createdBy: UserId(creator.id),});- const policies = (await getRolesForPrincipal(ApiKeyId(key.id))).flatMap(- (role) => role.policies,- );+ const policies = (+ await getRolesForPrincipal(prisma, ApiKeyId(key.id))+ ).flatMap((role) => role.policies);expect(policies).toEqual(systemRoleAccessRights.LEGACY_PROJECT_API_KEY.policies.map((p) => ({@@ -174,9 +174,9 @@ describe("getRolesForPrincipal decision-equivalence", () => {createdBy: UserId(creator.id),});- const policies = (await getRolesForPrincipal(ApiKeyId(key.id))).flatMap(- (role) => role.policies,- );+ const policies = (+ await getRolesForPrincipal(prisma, ApiKeyId(key.id))+ ).flatMap((role) => role.policies);expect(policies).toEqual(systemRoleAccessRights.LEGACY_ORGANIZATION_API_KEY.policies.map((p) => ({diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.tsindex f99e34e342..50c8ca90a3 100644--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts@@ -45,13 +45,16 @@ afterEach(() => {});describe("organization API keys trpc", () => {- const organizationId = "seed-org-id";+ const organizationId = randomUUID();// The session user is persisted as the API key creator, so it must exist// in the database (CI does not run the seeder that creates user-1).// createMany + skipDuplicates is atomic, so concurrently running test// files can ensure the user without racing each other.beforeAll(async () => {+ await prisma.organization.create({+ data: { id: organizationId, name: "Test Organization" },+ });await prisma.user.createMany({data: [{@@ -615,7 +618,9 @@ describe("organization API keys trpc", () => {role: "ADMIN",});- const projectResources = (await getRolesForPrincipal(ApiKeyId(key.id)))+ const projectResources = (+ await getRolesForPrincipal(prisma, ApiKeyId(key.id))+ ).flatMap((role) => role.policies).filter((policy) => policy.id.endsWith(":project")).flatMap((policy) => policy.resources);@@ -643,9 +648,14 @@ describe("organization API keys trpc", () => {});expect(await prisma.roleAssignment.findFirstOrThrow({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },}),- ).toMatchObject({ systemRole: role, ownerOrgId: orgId });+ ).toMatchObject({+ systemRole: role,+ orgId,+ ownerId: `organization/${orgId}`,+ projectId: null,+ });},);@@ -679,11 +689,13 @@ describe("organization API keys trpc", () => {).organizationApiKeys.create({ orgId, ...input });expect(await prisma.roleAssignment.findFirstOrThrow({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },}),).toMatchObject({systemRole: "LEGACY_ORGANIZATION_API_KEY",- ownerOrgId: orgId,+ orgId,+ ownerId: `organization/${orgId}`,+ projectId: null,});},);diff --git a/web/src/__tests__/server/project-api-key-trpc.servertest.ts b/web/src/__tests__/server/project-api-key-trpc.servertest.tsindex d25ba570c6..393c881ae4 100644--- a/web/src/__tests__/server/project-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/project-api-key-trpc.servertest.ts@@ -147,7 +147,7 @@ describe("project API keys trpc", () => {expect(dbKey.createdByApiKeyId).toBeNull();expect(await prisma.roleAssignment.findFirstOrThrow({- where: { principalApiKeyId: apiKeyResult.id },+ where: { apiKeyId: apiKeyResult.id },}),).toMatchObject({ systemRole: "LEGACY_PROJECT_API_KEY" });expect(dbKey.scope).toBe("PROJECT");@@ -217,10 +217,10 @@ describe("project API keys trpc", () => {const { caller, projectId } = await createProjectCaller();const key = await caller.projectApiKeys.create({ projectId, role });const assignment = await prisma.roleAssignment.findFirstOrThrow({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },});expect(assignment.systemRole).toBe(role);- expect(assignment.ownerProjectId).toBe(projectId);+ expect(assignment.projectId).toBe(projectId);},);@@ -252,11 +252,11 @@ describe("project API keys trpc", () => {});expect(await prisma.roleAssignment.findFirstOrThrow({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },}),).toMatchObject({systemRole: "LEGACY_PROJECT_API_KEY",- ownerProjectId: projectId,+ projectId: projectId,});},);@@ -342,10 +342,10 @@ describe("project API keys trpc", () => {});const assignment = await prisma.roleAssignment.findFirstOrThrow({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },});expect(assignment.systemRole).toBe("LEGACY_PROJECT_API_KEY");- expect(assignment.ownerProjectId).toBe(projectId);+ expect(assignment.projectId).toBe(projectId);expect(assignment.orgId).toBe(project.orgId);await expect(@@ -354,7 +354,7 @@ describe("project API keys trpc", () => {await expect(prisma.roleAssignment.count({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },}),).resolves.toBe(0);});diff --git a/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts b/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.tsindex 6f31cf2f56..3ddec3ea25 100644--- a/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts+++ b/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts@@ -194,16 +194,19 @@ describe("projectsRouter system role assignments", () => {await expect(prisma.roleAssignment.count({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },}),).resolves.toBe(1);const assignment = await prisma.roleAssignment.create({data: {orgId,- principalUserId: user.id,- ownerProjectId: projectId,+ userId: user.id,+ principalId: `user/${user.id}`,+ projectId,+ ownerId: `project/${projectId}`,systemRole: "VIEWER",+ roleId: "system/VIEWER",},});@@ -211,7 +214,7 @@ describe("projectsRouter system role assignments", () => {await expect(prisma.roleAssignment.count({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },}),).resolves.toBe(0);await expect(@@ -230,7 +233,7 @@ describe("projectsRouter system role assignments", () => {).resolves.toEqual([expect.objectContaining({id: assignment.id,- ownerProjectId: projectId,+ projectId: projectId,systemRole: "VIEWER",}),]);@@ -254,16 +257,16 @@ describe("projectsRouter system role assignments", () => {});const before = await prisma.roleAssignment.findFirstOrThrow({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },});expect(before.orgId).toBe(sourceOrgId);await caller.projects.transfer({ projectId, targetOrgId });const after = await prisma.roleAssignment.findFirstOrThrow({- where: { principalApiKeyId: key.id },+ where: { apiKeyId: key.id },});expect(after.orgId).toBe(targetOrgId);- expect(after.ownerProjectId).toBe(projectId);+ expect(after.projectId).toBe(projectId);});});diff --git a/web/src/__tests__/server/roleAssignmentRepository.servertest.ts b/web/src/__tests__/server/roleAssignmentRepository.servertest.tsdeleted file mode 100644index bdcf36a282..0000000000--- a/web/src/__tests__/server/roleAssignmentRepository.servertest.ts+++ /dev/null@@ -1,352 +0,0 @@-import { v4 } from "uuid";-import { describe, expect, it } from "vitest";--import { InternalServerError } from "@langfuse/shared";-import { prisma } from "@langfuse/shared/src/db";-import {- createApiKey,- createOrgProjectAndApiKey,-} from "@langfuse/shared/src/server";-import {- assignRole,- getRoleAssignmentsForPrincipal,- transferRoleAssignments,-} from "@langfuse/shared/rbac/server";-import {- ApiKeyId,- OrganizationId,- ProjectId,- SystemRoleId,- UserId,-} from "@langfuse/shared/rbac";--describe("role assignment integrity", () => {- it("rejects assignments for a user that does not exist", async () => {- const project = await prisma.project.create({- data: {- name: v4(),- organization: { create: { name: v4() } },- },- });-- await expect(- assignRole(prisma, {- tenantId: OrganizationId(project.orgId),- principalId: UserId(v4()),- ownerId: ProjectId(project.id),- roleId: SystemRoleId("VIEWER"),- tags: [],- }),- ).rejects.toMatchObject({ code: "P2003" });- });-});--async function addUserAssignment(orgId: string, projectId: string) {- const user = await prisma.user.create({- data: { email: `${v4()}@example.com` },- });- const assignment = await prisma.roleAssignment.create({- data: {- orgId,- principalUserId: user.id,- ownerProjectId: projectId,- systemRole: "VIEWER",- },- });- return { ...assignment, principalUserId: user.id };-}--async function assignmentsFor(projectId: string, prefix: string) {- return prisma.roleAssignment.findMany({- where: {- ownerProjectId: projectId,- ...(prefix === "apiKey/"- ? { principalApiKeyId: { not: null } }- : { principalUserId: { not: null } }),- },- });-}--describe("transferRoleAssignments", () => {- it("rolls back a root client's transfer when deleting user assignments fails", async () => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- await addUserAssignment(orgId, projectId);- const targetOrg = await prisma.organization.create({- data: { id: v4(), name: v4() },- });- const failingPrisma = prisma.$extends({- query: {- roleAssignment: {- deleteMany({ args, query }) {- if (args.where?.ownerProjectId === projectId) {- throw new InternalServerError("assignment deletion failed");- }- return query(args);- },- },- },- });-- await expect(- transferRoleAssignments(- failingPrisma as typeof prisma,- projectId,- targetOrg.id,- ),- ).rejects.toThrow("assignment deletion failed");-- const apiKeyAssignments = await assignmentsFor(projectId, "apiKey/");- expect(apiKeyAssignments[0].orgId).toBe(orgId);- expect(await assignmentsFor(projectId, "user/")).toHaveLength(1);- });-- it("joins the caller's transaction and rolls back with its project update", async () => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- await addUserAssignment(orgId, projectId);- const targetOrg = await prisma.organization.create({- data: { id: v4(), name: v4() },- });-- await expect(- prisma.$transaction(async (tx) => {- await tx.project.update({- where: { id: projectId },- data: { orgId: targetOrg.id },- });- await transferRoleAssignments(tx, projectId, targetOrg.id);-- const assignments = await tx.roleAssignment.findMany({- where: { ownerProjectId: projectId },- });- expect(assignments).toHaveLength(1);- expect(assignments[0].orgId).toBe(targetOrg.id);- expect(assignments[0].principalApiKeyId).not.toBeNull();- throw new InternalServerError("outer transaction failed");- }),- ).rejects.toThrow("outer transaction failed");-- const project = await prisma.project.findUniqueOrThrow({- where: { id: projectId },- });- expect(project.orgId).toBe(orgId);- const apiKeyAssignments = await assignmentsFor(projectId, "apiKey/");- expect(apiKeyAssignments[0].orgId).toBe(orgId);- expect(await assignmentsFor(projectId, "user/")).toHaveLength(1);- });-- it("moves api-key assignments to the destination org and drops user assignments", async () => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- await addUserAssignment(orgId, projectId);- const targetOrg = await prisma.organization.create({- data: { id: v4(), name: v4() },- });-- await transferRoleAssignments(prisma, projectId, targetOrg.id);-- const apiKeyAssignments = await assignmentsFor(projectId, "apiKey/");- expect(apiKeyAssignments).toHaveLength(1);- expect(apiKeyAssignments[0].orgId).toBe(targetOrg.id);- expect(await assignmentsFor(projectId, "user/")).toHaveLength(0);- });-});--describe("API-key deletion", () => {- it("cascades bulk key deletion while preserving user and other-project assignments", async () => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- await addUserAssignment(orgId, projectId);-- const otherProject = await prisma.project.create({- data: { id: v4(), name: v4(), orgId },- });- const keyCreator = await prisma.user.create({- data: { email: `apikey-creator-${v4()}@example.com` },- });- await createApiKey(prisma, {- owner: ProjectId(otherProject.id),- role: SystemRoleId("LEGACY_PROJECT_API_KEY"),- createdBy: UserId(keyCreator.id),- });-- await prisma.apiKey.deleteMany({- where: { projectId, scope: "PROJECT" },- });-- expect(await assignmentsFor(projectId, "apiKey/")).toHaveLength(0);- expect(await assignmentsFor(projectId, "user/")).toHaveLength(1);- expect(await assignmentsFor(otherProject.id, "apiKey/")).toHaveLength(1);- });-});--describe("role assignment foreign keys", () => {- it.each([- ["user", "organization"],- ["user", "project"],- ["api key", "organization"],- ["api key", "project"],- ] as const)(- "rejects duplicate %s assignments on an %s owner",- async (principal, owner) => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- const key = await prisma.apiKey.findFirstOrThrow({- where: { projectId },- });- const user = await prisma.user.create({- data: { email: `${v4()}@example.com` },- });- const assignment = {- tenantId: OrganizationId(orgId),- principalId: principal === "user" ? UserId(user.id) : ApiKeyId(key.id),- ownerId:- owner === "organization"- ? OrganizationId(orgId)- : ProjectId(projectId),- roleId: SystemRoleId("VIEWER"),- tags: [],- };- await assignRole(prisma, assignment);-- await expect(assignRole(prisma, assignment)).rejects.toMatchObject({- code: "P2002",- });- },- );-- it.each([- "principalUserId",- "principalApiKeyId",- "ownerOrgId",- "ownerProjectId",- ] as const)("rejects a missing %s", async (field) => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- const user = await prisma.user.create({- data: { email: `${v4()}@example.com` },- });- const data = {- orgId,- principalUserId: field === "principalApiKeyId" ? null : user.id,- ownerProjectId: field === "ownerOrgId" ? null : projectId,- systemRole: "VIEWER" as const,- [field]: v4(),- };-- await expect(prisma.roleAssignment.create({ data })).rejects.toMatchObject({- code: "P2003",- });- });-- it.each([- "both principals",- "neither principal",- "both owners",- "neither owner",- ] as const)("rejects assignments with %s", async (invalidShape) => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- const key = await prisma.apiKey.findFirstOrThrow({ where: { projectId } });- const user = await prisma.user.create({- data: { email: `${v4()}@example.com` },- });- const data = {- orgId,- principalUserId: invalidShape === "neither principal" ? null : user.id,- principalApiKeyId: invalidShape === "both principals" ? key.id : null,- ownerProjectId: invalidShape === "neither owner" ? null : projectId,- ownerOrgId: invalidShape === "both owners" ? orgId : null,- systemRole: "VIEWER" as const,- };-- await expect(prisma.roleAssignment.create({ data })).rejects.toThrow(- /check constraint/,- );- });-- it.each(["user", "api key", "project", "organization"] as const)(- "cascades assignments when deleting their %s",- async (deletedEntity) => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- const key = await prisma.apiKey.findFirstOrThrow({- where: { projectId },- });- const userAssignment = await addUserAssignment(orgId, projectId);- await assignRole(prisma, {- tenantId: OrganizationId(orgId),- ownerId: OrganizationId(orgId),- principalId: UserId(userAssignment.principalUserId),- roleId: SystemRoleId("VIEWER"),- tags: [],- });-- const affectedAssignments = await prisma.roleAssignment.findMany({- where: {- user: { principalUserId: userAssignment.principalUserId },- "api key": { principalApiKeyId: key.id },- project: { ownerProjectId: projectId },- organization: { orgId },- }[deletedEntity],- });- expect(affectedAssignments.length).toBeGreaterThan(0);-- if (deletedEntity === "user")- await prisma.user.delete({- where: { id: userAssignment.principalUserId },- });- if (deletedEntity === "api key")- await prisma.apiKey.delete({ where: { id: key.id } });- if (deletedEntity === "project")- await prisma.project.delete({ where: { id: projectId } });- if (deletedEntity === "organization")- await prisma.organization.delete({ where: { id: orgId } });-- expect(- await prisma.roleAssignment.count({- where: { id: { in: affectedAssignments.map(({ id }) => id) } },- }),- ).toBe(0);- },- );-- it("loads stored assignments with the caller-supplied tenant for both principal kinds", async () => {- const { projectId, orgId } = await createOrgProjectAndApiKey();- const key = await prisma.apiKey.findFirstOrThrow({ where: { projectId } });- const assignment = await addUserAssignment(orgId, projectId);- const principalId = UserId(assignment.principalUserId);- await assignRole(prisma, {- tenantId: OrganizationId(orgId),- ownerId: OrganizationId(orgId),- principalId,- roleId: SystemRoleId("ADMIN"),- tags: [],- });-- expect(await getRoleAssignmentsForPrincipal(prisma, principalId)).toEqual(- expect.arrayContaining([- assignment,- {- id: expect.any(String),- orgId,- principalUserId: assignment.principalUserId,- principalApiKeyId: null,- ownerOrgId: orgId,- ownerProjectId: null,- systemRole: "ADMIN",- createdAt: expect.any(Date),- updatedAt: expect.any(Date),- },- ]),- );- expect(- await getRoleAssignmentsForPrincipal(prisma, ApiKeyId(key.id)),- ).toEqual([- {- id: expect.any(String),- orgId,- principalApiKeyId: key.id,- principalUserId: null,- ownerProjectId: projectId,- ownerOrgId: null,- systemRole: "LEGACY_PROJECT_API_KEY",- createdAt: expect.any(Date),- updatedAt: expect.any(Date),- },- ]);- });-});diff --git a/web/src/__tests__/server/roleAssignmentService.servertest.ts b/web/src/__tests__/server/roleAssignmentService.servertest.tsnew file mode 100644index 0000000000..c5c7d5709e--- /dev/null+++ b/web/src/__tests__/server/roleAssignmentService.servertest.ts@@ -0,0 +1,656 @@+import { v4 } from "uuid";+import { describe, expect, it, vi } from "vitest";++import { InternalServerError, InvalidRequestError } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import {+ createApiKey,+ createOrgProjectAndApiKey,+} from "@langfuse/shared/src/server";+import {+ assignRole,+ getRoleAssignmentsForPrincipal,+ transferRoleAssignments,+} from "@langfuse/shared/rbac/server";+import {+ ApiKeyId,+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+ type RoleId,+} from "@langfuse/shared/rbac";++describe("role assignment integrity", () => {+ it.each(["system/UNKNOWN", "system/", "system/toString"])(+ "rejects invalid role %s before opening a transaction",+ async (roleId) => {+ const transaction = vi.fn();+ const client = { $transaction: transaction } as unknown as typeof prisma;+ await expect(+ assignRole(client, {+ tenantId: OrganizationId("org"),+ ownerId: OrganizationId("org"),+ principalId: UserId("user"),+ roleId: roleId as RoleId,+ tags: [],+ }),+ ).rejects.toBeInstanceOf(InvalidRequestError);+ expect(transaction).not.toHaveBeenCalled();+ },+ );++ it.each(["organization", "project"])(+ "rejects a %s owner outside the assignment tenant",+ async (kind) => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const tenant = await prisma.organization.create({ data: { name: v4() } });+ const user = await prisma.user.create({ data: { name: v4() } });++ await expect(+ assignRole(prisma, {+ tenantId: OrganizationId(tenant.id),+ ownerId:+ kind === "project" ? ProjectId(projectId) : OrganizationId(orgId),+ principalId: UserId(user.id),+ roleId: SystemRoleId("VIEWER"),+ tags: [],+ }),+ ).rejects.toBeInstanceOf(InvalidRequestError);+ expect(+ await prisma.roleAssignment.count({ where: { userId: user.id } }),+ ).toBe(0);+ },+ );++ it("holds project tenancy stable until assignment commit during a transfer", async () => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const target = await prisma.organization.create({ data: { name: v4() } });+ const user = await prisma.user.create({ data: { name: v4() } });+ let releaseAssignment!: () => void;+ const commitAllowed = new Promise<void>((resolve) => {+ releaseAssignment = resolve;+ });+ let signalAssigned!: () => void;+ const assigned = new Promise<void>((resolve) => {+ signalAssigned = resolve;+ });+ let transferPid: number | undefined;+ let assignmentPid: number | undefined;+ const assignment = prisma.$transaction(+ async (tx) => {+ const [backend] = await tx.$queryRaw<+ { pid: number }[]+ >`SELECT pg_backend_pid() AS pid`;+ assignmentPid = backend.pid;+ await assignRole(tx, {+ tenantId: OrganizationId(orgId),+ ownerId: ProjectId(projectId),+ principalId: UserId(user.id),+ roleId: SystemRoleId("VIEWER"),+ tags: [],+ });+ signalAssigned();+ await commitAllowed;+ },+ { timeout: 15000 },+ );+ await Promise.race([assigned, assignment]);+ const transfer = prisma.$transaction(+ async (tx) => {+ const [backend] = await tx.$queryRaw<+ { pid: number }[]+ >`SELECT pg_backend_pid() AS pid`;+ transferPid = backend.pid;+ await tx.project.update({+ where: { id: projectId },+ data: { orgId: target.id },+ });+ await transferRoleAssignments(tx, projectId, target.id);+ },+ { timeout: 15000 },+ );+ try {+ await vi.waitFor(+ async () => {+ expect(transferPid).toBeDefined();+ const [locks] = await prisma.$queryRaw<{ blockers: number[] }[]>`+ SELECT pg_blocking_pids(${transferPid}::int) AS blockers+ `;+ expect(locks.blockers).toContain(assignmentPid);+ },+ { timeout: 2000, interval: 25 },+ );+ } finally {+ releaseAssignment();+ await Promise.all([assignment, transfer]);+ }+ expect(+ await prisma.roleAssignment.count({ where: { userId: user.id } }),+ ).toBe(0);+ });++ it("rejects assignments for a user that does not exist", async () => {+ const project = await prisma.project.create({+ data: {+ name: v4(),+ organization: { create: { name: v4() } },+ },+ });++ await expect(+ assignRole(prisma, {+ tenantId: OrganizationId(project.orgId),+ principalId: UserId(v4()),+ ownerId: ProjectId(project.id),+ roleId: SystemRoleId("VIEWER"),+ tags: [],+ }),+ ).rejects.toMatchObject({ code: "P2003" });+ });+});++async function addUserAssignment(orgId: string, projectId: string) {+ const user = await prisma.user.create({+ data: { email: `${v4()}@example.com` },+ });+ const assignment = await prisma.roleAssignment.create({+ data: {+ orgId,+ userId: user.id,+ principalId: UserId(user.id),+ projectId,+ ownerId: ProjectId(projectId),+ systemRole: "VIEWER",+ roleId: SystemRoleId("VIEWER"),+ },+ });+ return { ...assignment, userId: user.id };+}++async function assignmentsFor(projectId: string, prefix: string) {+ return prisma.roleAssignment.findMany({+ where: {+ projectId: projectId,+ ...(prefix === "apiKey/"+ ? { apiKeyId: { not: null } }+ : { userId: { not: null } }),+ },+ });+}++describe("transferRoleAssignments", () => {+ it("rolls back a root client's transfer when deleting user assignments fails", async () => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ await addUserAssignment(orgId, projectId);+ const targetOrg = await prisma.organization.create({+ data: { id: v4(), name: v4() },+ });+ const failingPrisma = prisma.$extends({+ query: {+ roleAssignment: {+ deleteMany({ args, query }) {+ if (args.where?.projectId === projectId) {+ throw new InternalServerError("assignment deletion failed");+ }+ return query(args);+ },+ },+ },+ });++ await expect(+ transferRoleAssignments(+ failingPrisma as typeof prisma,+ projectId,+ targetOrg.id,+ ),+ ).rejects.toThrow("assignment deletion failed");++ const apiKeyAssignments = await assignmentsFor(projectId, "apiKey/");+ expect(apiKeyAssignments[0].orgId).toBe(orgId);+ expect(await assignmentsFor(projectId, "user/")).toHaveLength(1);+ });++ it("joins the caller's transaction and rolls back with its project update", async () => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ await addUserAssignment(orgId, projectId);+ const targetOrg = await prisma.organization.create({+ data: { id: v4(), name: v4() },+ });++ await expect(+ prisma.$transaction(async (tx) => {+ await tx.project.update({+ where: { id: projectId },+ data: { orgId: targetOrg.id },+ });+ await transferRoleAssignments(tx, projectId, targetOrg.id);++ const assignments = await tx.roleAssignment.findMany({+ where: { projectId: projectId },+ });+ expect(assignments).toHaveLength(1);+ expect(assignments[0].orgId).toBe(targetOrg.id);+ expect(assignments[0].apiKeyId).not.toBeNull();+ throw new InternalServerError("outer transaction failed");+ }),+ ).rejects.toThrow("outer transaction failed");++ const project = await prisma.project.findUniqueOrThrow({+ where: { id: projectId },+ });+ expect(project.orgId).toBe(orgId);+ const apiKeyAssignments = await assignmentsFor(projectId, "apiKey/");+ expect(apiKeyAssignments[0].orgId).toBe(orgId);+ expect(await assignmentsFor(projectId, "user/")).toHaveLength(1);+ });++ it("moves api-key assignments to the destination org and drops user assignments", async () => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ await addUserAssignment(orgId, projectId);+ const targetOrg = await prisma.organization.create({+ data: { id: v4(), name: v4() },+ });++ await transferRoleAssignments(prisma, projectId, targetOrg.id);++ const apiKeyAssignments = await assignmentsFor(projectId, "apiKey/");+ expect(apiKeyAssignments).toHaveLength(1);+ expect(apiKeyAssignments[0].orgId).toBe(targetOrg.id);+ expect(await assignmentsFor(projectId, "user/")).toHaveLength(0);+ });+});++describe("API-key deletion", () => {+ it("cascades bulk key deletion while preserving user and other-project assignments", async () => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ await addUserAssignment(orgId, projectId);++ const otherProject = await prisma.project.create({+ data: { id: v4(), name: v4(), orgId },+ });+ const keyCreator = await prisma.user.create({+ data: { email: `apikey-creator-${v4()}@example.com` },+ });+ await createApiKey(prisma, {+ owner: ProjectId(otherProject.id),+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),+ createdBy: UserId(keyCreator.id),+ });++ await prisma.apiKey.deleteMany({+ where: { projectId, scope: "PROJECT" },+ });++ expect(await assignmentsFor(projectId, "apiKey/")).toHaveLength(0);+ expect(await assignmentsFor(projectId, "user/")).toHaveLength(1);+ expect(await assignmentsFor(otherProject.id, "apiKey/")).toHaveLength(1);+ });+});++describe("role assignment rolling compatibility", () => {+ it.each([+ ["user", "organization"],+ ["user", "project"],+ ["api key", "organization"],+ ["api key", "project"],+ ] as const)(+ "supports old and new writers for a %s on a %s",+ async (principal, owner) => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const key = await prisma.apiKey.findFirstOrThrow({+ where: { projectId },+ });+ const user = await prisma.user.create({ data: { name: v4() } });+ const id = v4();+ const userId = principal === "user" ? user.id : null;+ const apiKeyId = principal === "api key" ? key.id : null;+ const ownerProjectId = owner === "project" ? projectId : null;+ const ownerOrgId = owner === "organization" ? orgId : null;+ const principalId = userId ? UserId(userId) : ApiKeyId(key.id);+ const ownerId = ownerProjectId+ ? ProjectId(ownerProjectId)+ : OrganizationId(orgId);++ await prisma.$executeRaw`+ INSERT INTO role_assignments+ (id, org_id, principal_user_id, principal_api_key_id, owner_project_id, owner_org_id, system_role)+ VALUES (${id}, ${orgId}, ${userId}, ${apiKeyId}, ${ownerProjectId}, ${ownerOrgId}, 'VIEWER')+ `;+ expect(+ await prisma.roleAssignment.findUniqueOrThrow({ where: { id } }),+ ).toMatchObject({+ principalId,+ ownerId,+ roleId: SystemRoleId("VIEWER"),+ userId,+ apiKeyId,+ projectId: ownerProjectId,+ orgId,+ });++ await assignRole(prisma, {+ tenantId: OrganizationId(orgId),+ principalId,+ ownerId,+ roleId: SystemRoleId("ADMIN"),+ tags: [],+ });+ const legacyRows = await prisma.$queryRaw`+ SELECT principal_user_id, principal_api_key_id, owner_project_id, owner_org_id,+ user_id, api_key_id, project_id+ FROM role_assignments+ WHERE principal_id = ${principalId} AND owner_id = ${ownerId} AND system_role = 'ADMIN'+ `;+ expect(legacyRows).toEqual([+ {+ principal_user_id: userId,+ principal_api_key_id: apiKeyId,+ owner_project_id: ownerProjectId,+ owner_org_id: ownerOrgId,+ user_id: userId,+ api_key_id: apiKeyId,+ project_id: ownerProjectId,+ },+ ]);++ const nextPrincipalId = userId ? ApiKeyId(key.id) : UserId(user.id);+ const nextProjectId = ownerProjectId ? null : projectId;+ const nextOwnerId = nextProjectId+ ? ProjectId(nextProjectId)+ : OrganizationId(orgId);+ const updated = await prisma.roleAssignment.update({+ where: {+ ownerId_principalId_roleId: {+ roleId: SystemRoleId("ADMIN"),+ principalId,+ ownerId,+ },+ },+ data: {+ principalId: nextPrincipalId,+ userId: userId ? null : user.id,+ apiKeyId: userId ? key.id : null,+ projectId: nextProjectId,+ ownerId: nextOwnerId,+ },+ });+ const updatedLegacyRows = await prisma.$queryRaw`+ SELECT principal_user_id, principal_api_key_id, owner_project_id, owner_org_id,+ user_id, api_key_id, project_id+ FROM role_assignments WHERE id = ${updated.id}+ `;+ expect(updatedLegacyRows).toEqual([+ {+ principal_user_id: userId ? null : user.id,+ principal_api_key_id: userId ? key.id : null,+ owner_project_id: nextProjectId,+ owner_org_id: nextProjectId ? null : orgId,+ user_id: userId ? null : user.id,+ api_key_id: userId ? key.id : null,+ project_id: nextProjectId,+ },+ ]);+ },+ );+});++describe("role assignment foreign keys", () => {+ it.each([+ ["user", "organization"],+ ["user", "project"],+ ["api key", "organization"],+ ["api key", "project"],+ ] as const)(+ "rejects duplicate %s assignments on an %s owner while allowing distinct roles",+ async (principal, owner) => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const key = await prisma.apiKey.findFirstOrThrow({+ where: { projectId },+ });+ const user = await prisma.user.create({+ data: { email: `${v4()}@example.com` },+ });+ const assignment = {+ tenantId: OrganizationId(orgId),+ principalId: principal === "user" ? UserId(user.id) : ApiKeyId(key.id),+ ownerId:+ owner === "organization"+ ? OrganizationId(orgId)+ : ProjectId(projectId),+ roleId: SystemRoleId("VIEWER"),+ tags: [],+ };+ await assignRole(prisma, assignment);++ await expect(assignRole(prisma, assignment)).rejects.toMatchObject({+ code: "P2002",+ });+ await assignRole(prisma, {+ ...assignment,+ roleId: SystemRoleId("ADMIN"),+ });+ const stored = await prisma.roleAssignment.findUniqueOrThrow({+ where: {+ ownerId_principalId_roleId: {+ roleId: assignment.roleId,+ principalId: assignment.principalId,+ ownerId: assignment.ownerId,+ },+ },+ include: {+ user: true,+ apiKey: true,+ project: true,+ organization: true,+ },+ });+ expect(stored).toMatchObject({+ principalId: assignment.principalId,+ ownerId: assignment.ownerId,+ roleId: assignment.roleId,+ user: principal === "user" ? { id: user.id } : null,+ apiKey: principal === "api key" ? { id: key.id } : null,+ project: owner === "project" ? { id: projectId } : null,+ organization: { id: orgId },+ });+ },+ );++ it.each(["userId", "apiKeyId", "orgId", "projectId"] as const)(+ "rejects a missing %s",+ async (field) => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const user = await prisma.user.create({+ data: { email: `${v4()}@example.com` },+ });+ const missingId = v4();+ const userId = field === "userId" ? missingId : user.id;+ const ownerProjectId = field === "projectId" ? missingId : projectId;+ const data = {+ orgId: field === "orgId" ? missingId : orgId,+ userId: field === "apiKeyId" ? null : userId,+ apiKeyId: field === "apiKeyId" ? missingId : null,+ principalId:+ field === "apiKeyId" ? ApiKeyId(missingId) : UserId(userId),+ projectId: field === "orgId" ? null : ownerProjectId,+ ownerId:+ field === "orgId"+ ? OrganizationId(missingId)+ : ProjectId(ownerProjectId),+ roleId: SystemRoleId("VIEWER"),+ systemRole: "VIEWER" as const,+ };++ await expect(+ prisma.roleAssignment.create({ data }),+ ).rejects.toMatchObject({+ code: "P2003",+ });+ },+ );++ it.each([+ "both principals",+ "neither principal",+ "mismatched user",+ "mismatched api key",+ "unknown principal kind",+ "mismatched project",+ "mismatched organization",+ "organization owner with project",+ "project owner without project",+ "unknown owner kind",+ "mismatched system role",+ "custom role",+ ] as const)("rejects creates and updates with %s", async (invalidShape) => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const key = await prisma.apiKey.findFirstOrThrow({ where: { projectId } });+ const user = await prisma.user.create({+ data: { email: `${v4()}@example.com` },+ });+ const validData = {+ orgId,+ userId: user.id,+ apiKeyId: null,+ principalId: UserId(user.id),+ projectId,+ ownerId: ProjectId(projectId),+ systemRole: "VIEWER" as const,+ roleId: SystemRoleId("VIEWER"),+ };+ const invalidFields = {+ "both principals": { apiKeyId: key.id },+ "neither principal": { userId: null },+ "mismatched user": { principalId: UserId(v4()) },+ "mismatched api key": {+ userId: null,+ apiKeyId: key.id,+ principalId: ApiKeyId(v4()),+ },+ "unknown principal kind": { principalId: `service/${user.id}` },+ "mismatched project": { ownerId: ProjectId(v4()) },+ "mismatched organization": {+ projectId: null,+ ownerId: OrganizationId(v4()),+ },+ "organization owner with project": { ownerId: OrganizationId(orgId) },+ "project owner without project": { projectId: null },+ "unknown owner kind": { ownerId: `workspace/${orgId}` },+ "mismatched system role": { roleId: SystemRoleId("ADMIN") },+ "custom role": { roleId: `custom/${v4()}` },+ }[invalidShape];++ await expect(+ prisma.roleAssignment.create({+ data: { ...validData, ...invalidFields },+ }),+ ).rejects.toThrow(/check constraint/);+ const assignment = await prisma.roleAssignment.create({ data: validData });+ await expect(+ prisma.roleAssignment.update({+ where: { id: assignment.id },+ data: invalidFields,+ }),+ ).rejects.toThrow(/check constraint/);+ expect(+ await prisma.roleAssignment.findUnique({ where: { id: assignment.id } }),+ ).toEqual(assignment);+ });++ it.each(["user", "api key", "project", "organization"] as const)(+ "cascades assignments when deleting their %s",+ async (deletedEntity) => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const key = await prisma.apiKey.findFirstOrThrow({+ where: { projectId },+ });+ const userAssignment = await addUserAssignment(orgId, projectId);+ await assignRole(prisma, {+ tenantId: OrganizationId(orgId),+ ownerId: OrganizationId(orgId),+ principalId: UserId(userAssignment.userId),+ roleId: SystemRoleId("VIEWER"),+ tags: [],+ });++ const affectedAssignments = await prisma.roleAssignment.findMany({+ where: {+ user: { userId: userAssignment.userId },+ "api key": { apiKeyId: key.id },+ project: { projectId: projectId },+ organization: { orgId },+ }[deletedEntity],+ });+ expect(affectedAssignments.length).toBeGreaterThan(0);++ if (deletedEntity === "user")+ await prisma.user.delete({+ where: { id: userAssignment.userId },+ });+ if (deletedEntity === "api key")+ await prisma.apiKey.delete({ where: { id: key.id } });+ if (deletedEntity === "project")+ await prisma.project.delete({ where: { id: projectId } });+ if (deletedEntity === "organization")+ await prisma.organization.delete({ where: { id: orgId } });++ expect(+ await prisma.roleAssignment.count({+ where: { id: { in: affectedAssignments.map(({ id }) => id) } },+ }),+ ).toBe(0);+ },+ );++ it("loads stored assignments with the caller-supplied tenant for both principal kinds", async () => {+ const { projectId, orgId } = await createOrgProjectAndApiKey();+ const key = await prisma.apiKey.findFirstOrThrow({ where: { projectId } });+ const assignment = await addUserAssignment(orgId, projectId);+ const principalId = UserId(assignment.userId);+ await assignRole(prisma, {+ tenantId: OrganizationId(orgId),+ ownerId: OrganizationId(orgId),+ principalId,+ roleId: SystemRoleId("ADMIN"),+ tags: [],+ });++ expect(await getRoleAssignmentsForPrincipal(prisma, principalId)).toEqual(+ expect.arrayContaining([+ assignment,+ {+ id: expect.any(String),+ orgId,+ userId: assignment.userId,+ apiKeyId: null,+ principalId,+ ownerId: OrganizationId(orgId),+ projectId: null,+ systemRole: "ADMIN",+ roleId: SystemRoleId("ADMIN"),+ createdAt: expect.any(Date),+ updatedAt: expect.any(Date),+ },+ ]),+ );+ expect(+ await getRoleAssignmentsForPrincipal(prisma, ApiKeyId(key.id)),+ ).toEqual([+ {+ id: expect.any(String),+ orgId,+ apiKeyId: key.id,+ userId: null,+ principalId: ApiKeyId(key.id),+ projectId: projectId,+ ownerId: ProjectId(projectId),+ systemRole: "LEGACY_PROJECT_API_KEY",+ roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),+ createdAt: expect.any(Date),+ updatedAt: expect.any(Date),+ },+ ]);+ });+});diff --git a/web/src/__tests__/server/shadowAuth.servertest.ts b/web/src/__tests__/server/shadowAuth.servertest.tsindex b117b979b4..7b93a0ee1f 100644--- a/web/src/__tests__/server/shadowAuth.servertest.ts+++ b/web/src/__tests__/server/shadowAuth.servertest.ts@@ -149,9 +149,11 @@ const createOrgApiKey = async (targetOrgId: string) => {await prisma.roleAssignment.create({data: {orgId: targetOrgId,- principalApiKeyId: apiKeyRowId,+ apiKeyId: apiKeyRowId,+ principalId: `apiKey/${apiKeyRowId}`,systemRole: "LEGACY_ORGANIZATION_API_KEY",- ownerOrgId: targetOrgId,+ roleId: "system/LEGACY_ORGANIZATION_API_KEY",+ ownerId: `organization/${targetOrgId}`,},});return createBasicAuthHeader(publicKey, secretKey);@@ -179,6 +181,23 @@ const ownedProjectIds = (context: AuthorizationContext): string[] =>? context.principal.organizations.flatMap((o) => o.projectIds): [];+const createUnassignedApiKey = async (scope: "PROJECT" | "ORGANIZATION") => {+ const publicKey = `pk-lf-${randomUUID()}`;+ const secretKey = `sk-lf-${randomUUID()}`;+ const apiKey = await prisma.apiKey.create({+ data: {+ scope,+ projectId: scope === "PROJECT" ? projectId : null,+ orgId: scope === "ORGANIZATION" ? orgId : null,+ publicKey,+ hashedSecretKey: `unused-fast-hash-${randomUUID()}`,+ fastHashedSecretKey: createShaHash(secretKey, env.SALT),+ displaySecretKey: getDisplaySecretKey(secretKey),+ },+ });+ return { apiKey, authorization: createBasicAuthHeader(publicKey, secretKey) };+};+describe("shadowAuth maps principals to legacy-identical scopes", () => {beforeAll(async () => {originalMigration = (env as any).API_AUTH_MIGRATION;@@ -213,6 +232,180 @@ describe("shadowAuth maps principals to legacy-identical scopes", () => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;});+ describe("backfills verified keys without role assignments", () => {+ it.each(["PROJECT", "ORGANIZATION"] as const)(+ "repairs a %s key on first use and authorizes that request",+ async (scope) => {+ const { apiKey, authorization } = await createUnassignedApiKey(scope);+ setMode("enforce");+ const result = await shadowAuth({+ req: reqWith({ authorization }),+ action: scope === "PROJECT" ? "project:read" : "projects:read",+ allowedAccessLevels: [+ scope === "PROJECT" ? "project" : "organization",+ ],+ });+ expect(result.success).toBe(true);+ expect(+ await prisma.roleAssignment.findMany({+ where: { apiKeyId: apiKey.id },+ }),+ ).toMatchObject([+ {+ orgId,+ ownerId:+ scope === "PROJECT"+ ? `project/${projectId}`+ : `organization/${orgId}`,+ systemRole:+ scope === "PROJECT"+ ? "LEGACY_PROJECT_API_KEY"+ : "LEGACY_ORGANIZATION_API_KEY",+ },+ ]);+ },+ );++ it("preserves a narrow assignment instead of restoring a legacy grant", async () => {+ const { apiKey, authorization } = await createUnassignedApiKey("PROJECT");+ const assignment = await prisma.roleAssignment.create({+ data: {+ orgId,+ projectId,+ apiKeyId: apiKey.id,+ ownerId: `project/${projectId}`,+ principalId: `apiKey/${apiKey.id}`,+ roleId: "system/INGEST",+ systemRole: "INGEST",+ },+ });+ setMode("enforce");+ const result = await shadowAuth({+ req: reqWith({ authorization }),+ action: "project:read",+ allowedAccessLevels: ["project"],+ });+ expect(result).toMatchObject({+ success: false,+ error: { httpCode: 403 },+ });+ expect(+ await prisma.roleAssignment.findMany({+ where: { apiKeyId: apiKey.id },+ }),+ ).toEqual([assignment]);+ });++ it.each(["invalid", "expired"] as const)(+ "does not repair an %s credential",+ async (kind) => {+ const { apiKey, authorization } =+ await createUnassignedApiKey("PROJECT");+ if (kind === "expired") {+ await prisma.apiKey.update({+ where: { id: apiKey.id },+ data: { expiresAt: new Date(0) },+ });+ }+ setMode("enforce");+ const result = await shadowAuth({+ req: reqWith({+ authorization:+ kind === "invalid"+ ? createBasicAuthHeader(+ apiKey.publicKey,+ `sk-lf-${randomUUID()}`,+ )+ : authorization,+ }),+ action: "project:read",+ allowedAccessLevels: ["project"],+ });+ expect(result).toMatchObject({+ success: false,+ error: { httpCode: 401 },+ });+ expect(+ await prisma.roleAssignment.count({ where: { apiKeyId: apiKey.id } }),+ ).toBe(0);+ },+ );++ it("repairs a transferred project's key in its current tenant", async () => {+ const fixture = await createOrgProjectAndApiKey();+ const key = await prisma.apiKey.findUniqueOrThrow({+ where: { publicKey: fixture.publicKey },+ });+ await prisma.roleAssignment.deleteMany({ where: { apiKeyId: key.id } });+ await prisma.project.update({+ where: { id: fixture.projectId },+ data: { orgId: foreignOrgId },+ });+ const context = await contextFor(fixture.auth);+ expect(+ authorize(+ context,+ OrganizationId(foreignOrgId),+ "project:read",+ ProjectId(fixture.projectId),+ ).success,+ ).toBe(true);+ expect(+ authorize(+ context,+ OrganizationId(fixture.orgId),+ "project:read",+ ProjectId(fixture.projectId),+ ).success,+ ).toBe(false);+ expect(+ await prisma.roleAssignment.findMany({ where: { apiKeyId: key.id } }),+ ).toMatchObject([{ orgId: foreignOrgId }]);+ });++ it("creates one assignment across concurrent first-use repairs", async () => {+ const { apiKey, authorization } = await createUnassignedApiKey("PROJECT");+ setMode("enforce");+ const results = await Promise.all(+ Array.from({ length: 5 }, () =>+ shadowAuth({+ req: reqWith({ authorization }),+ action: "project:read",+ allowedAccessLevels: ["project"],+ }),+ ),+ );+ expect(results.every((result) => result.success)).toBe(true);+ expect(+ await prisma.roleAssignment.count({ where: { apiKeyId: apiKey.id } }),+ ).toBe(1);+ });++ it("keeps a repaired public bearer restricted to scores", async () => {+ const { apiKey } = await createUnassignedApiKey("PROJECT");+ const context = await contextFor(`Bearer ${apiKey.publicKey}`);+ expect(+ authorize(+ context,+ OrganizationId(orgId),+ "scores:save",+ ProjectId(projectId),+ ).success,+ ).toBe(true);+ expect(+ authorize(+ context,+ OrganizationId(orgId),+ "project:read",+ ProjectId(projectId),+ ).success,+ ).toBe(false);+ expect(+ await prisma.roleAssignment.count({ where: { apiKeyId: apiKey.id } }),+ ).toBe(1);+ });+ });+it("an organization key on an org route yields a legacy-identical org scope", async () => {const { legacy, enforce } = await orgResultUnderModes(orgAuth);expect(scopeOf(enforce).accessLevel).toBe("organization");diff --git a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.tsindex afa2ff7fa6..b643812a17 100644--- a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts+++ b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts@@ -85,11 +85,13 @@ const resolver = new ContextResolver({id: "assignment_1",orgId: ORG,- principalApiKeyId: "key_p",- principalUserId: null,- ownerProjectId: PRJ,- ownerOrgId: null,+ apiKeyId: "key_p",+ principalId: "apiKey/key_p",+ userId: null,+ projectId: PRJ,+ ownerId: `project/${PRJ}`,systemRole: "ADMIN",+ roleId: "system/ADMIN",createdAt: new Date(0),updatedAt: new Date(0),},diff --git a/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts b/web/src/__tests__/server/unit/policy/contextResolver.servertest.tsindex 9fbc5bd5b9..4ceef2cfac 100644--- a/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts+++ b/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts@@ -1,6 +1,10 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import { type ApiKey, type PrismaClient } from "@langfuse/shared/src/db";+import {+ Prisma,+ type ApiKey,+ type PrismaClient,+} from "@langfuse/shared/src/db";import { InternalServerError } from "@langfuse/shared";import { OrganizationId, ProjectId, SystemRoleId } from "@langfuse/shared/rbac";@@ -35,35 +39,42 @@ const orgRow = (}) as unknown as OrganizationWithProjects;// Backfilled keys receive their legacy role, owned by their project or organization.-const assignmentsFor = (principalApiKeyId: string) => {- const principal = { principalApiKeyId, principalUserId: null };- if (principalApiKeyId === "key_o")+const assignmentsFor = (principalId: string) => {+ const principal = {+ principalId,+ apiKeyId: principalId.slice(7),+ userId: null,+ };+ if (principalId === "apiKey/key_o")return [{systemRole: "LEGACY_ORGANIZATION_API_KEY",+ roleId: "system/LEGACY_ORGANIZATION_API_KEY",...principal,- ownerOrgId: ORG,- ownerProjectId: null,+ ownerId: `organization/${ORG}`,+ projectId: null,orgId: ORG,},];- if (principalApiKeyId === "key_p")+ if (principalId === "apiKey/key_p")return [{systemRole: "LEGACY_PROJECT_API_KEY",+ roleId: "system/LEGACY_PROJECT_API_KEY",...principal,- ownerOrgId: null,- ownerProjectId: PRJ,+ ownerId: `project/${PRJ}`,+ projectId: PRJ,orgId: ORG,},];- if (principalApiKeyId === "key_v")+ if (principalId === "apiKey/key_v")return [{...principal,systemRole: "VIEWER",- ownerOrgId: null,- ownerProjectId: PRJ,+ roleId: "system/VIEWER",+ ownerId: `project/${PRJ}`,+ projectId: PRJ,orgId: ORG,},];@@ -77,8 +88,8 @@ const mockPrisma = (row: OrganizationWithProjects | null): PrismaClient =>findFirst: async () => row,},roleAssignment: {- findMany: async ({ where }: { where: { principalApiKeyId: string } }) =>- assignmentsFor(where.principalApiKeyId),+ findMany: async ({ where }: { where: { principalId: string } }) =>+ assignmentsFor(where.principalId),},project: {findMany: async () => (row?.projects ?? []).map((p) => ({ id: p.id })),@@ -339,3 +350,93 @@ describe("a verified key with no org is a 500 invariant break", () => {}});});++describe("role lookup", () => {+ it("throws an internal server error when backfill leaves no roles", async () => {+ const prisma = mockPrisma(orgRow());+ prisma.roleAssignment.findMany = vi.fn().mockResolvedValue([]);+ prisma.$transaction = vi.fn().mockResolvedValue(undefined);+ const resolver = new ContextResolver(+ new OrganizationRepository(prisma),+ prisma,+ );+ await expect(+ resolver.resolve({ authorization: "privateKey", apiKey: apiKey() }),+ ).rejects.toThrow(InternalServerError);+ expect(prisma.roleAssignment.findMany).toHaveBeenCalledTimes(2);+ });++ it("allows a stored role that grants no actions", async () => {+ const prisma = mockPrisma(orgRow());+ prisma.roleAssignment.findMany = vi.fn().mockResolvedValue([+ {+ ...assignmentsFor("apiKey/key_p")[0],+ systemRole: "NONE",+ roleId: "system/NONE",+ },+ ]);+ prisma.$transaction = vi.fn();+ const resolver = new ContextResolver(+ new OrganizationRepository(prisma),+ prisma,+ );+ const resolved = await resolver.resolve({+ authorization: "privateKey",+ apiKey: apiKey(),+ });+ expect(resolved).toMatchObject({+ success: true,+ context: { policies: [{ roleId: SystemRoleId("NONE"), actions: [] }] },+ });+ expect(prisma.$transaction).not.toHaveBeenCalled();+ });++ it.each(["P2002", "P2003"])(+ "handles a backfill %s error without swallowing other failures",+ async (code) => {+ const prisma = mockPrisma(orgRow());+ const failure = new Prisma.PrismaClientKnownRequestError("write failed", {+ code,+ clientVersion: Prisma.prismaVersion.client,+ });+ prisma.roleAssignment.findMany = vi+ .fn()+ .mockResolvedValueOnce([])+ .mockResolvedValue(assignmentsFor("apiKey/key_p"));+ prisma.$transaction = vi.fn().mockRejectedValue(failure);+ const resolver = new ContextResolver(+ new OrganizationRepository(prisma),+ prisma,+ );+ const result = resolver.resolve({+ authorization: "privateKey",+ apiKey: apiKey(),+ });+ if (code !== "P2002") {+ await expect(result).rejects.toThrow(failure);+ return;+ }+ const resolved = await result;+ if (!resolved.success) throw resolved.error;+ expect(+ authorize(resolved.context, TENANT, "project:read", ProjectId(PRJ))+ .success,+ ).toBe(true);+ },+ );++ it("does not backfill after a database error", async () => {+ const prisma = mockPrisma(orgRow());+ const failure = new Error("role lookup unavailable");+ prisma.roleAssignment.findMany = vi.fn().mockRejectedValue(failure);+ prisma.$transaction = vi.fn();+ const resolver = new ContextResolver(+ new OrganizationRepository(prisma),+ prisma,+ );+ await expect(+ resolver.resolve({ authorization: "privateKey", apiKey: apiKey() }),+ ).rejects.toThrow(failure);+ expect(prisma.$transaction).not.toHaveBeenCalled();+ });+});diff --git a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.tsindex acff4009fc..9bc236e6e2 100644--- a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts+++ b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts@@ -113,23 +113,32 @@ describe.each(["x-langfuse-project-id", "langfuse-project-id"])(),).toEqual({ success: true, projectId: PRJ });});- it("403s a header disagreeing with the bound project", () => {+ it("ignores a header disagreeing with the bound project", () => {expect(getProjectId(projectKey(), req({}, { [projectIdHeader]: "prj_2" })),- ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ ).toEqual({ success: true, projectId: PRJ });});- it("403s a URL disagreeing with the bound project", () => {+ it("ignores a URL disagreeing with the bound project", () => {+ expect(getProjectId(projectKey(), req({ projectId: "prj_2" }))).toEqual({+ success: true,+ projectId: PRJ,+ });+ });+ it("ignores conflicting URL and header projects when bound", () => {expect(- getProjectId(projectKey(), req({ projectId: "prj_2" })),- ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ getProjectId(+ projectKey(),+ req({ projectId: "prj_2" }, { [projectIdHeader]: "prj_3" }),+ ),+ ).toEqual({ success: true, projectId: PRJ });});- it("403s a URL disagreeing with the header", () => {+ it("prefers the URL project over a conflicting header", () => {expect(getProjectId(orgKey(),req({ projectId: PRJ }, { [projectIdHeader]: "prj_2" }),),- ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ ).toEqual({ success: true, projectId: PRJ });});it("prefers the X-prefixed header when both are provided", () => {expect(diff --git a/web/src/features/apiKey/verifier.ts b/web/src/features/apiKey/verifier.tsindex a47fb42ce6..f8c73fbf35 100644--- a/web/src/features/apiKey/verifier.ts+++ b/web/src/features/apiKey/verifier.ts@@ -52,6 +52,7 @@ export class Verifier {const byPrivateKey = await this.verifyPrivateKey(secretKey);if (byPrivateKey) return rejectExpired(byPrivateKey);+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Compatibility until the next major version.const bySlowHash = await this.backfillSlowHash(publicKey, secretKey);if (bySlowHash) return rejectExpired(bySlowHash);@@ -63,6 +64,7 @@ export class Verifier {const admin = this.verifyAdminKey(token);if (admin) return admin;+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Compatibility until the next major version.const byPublicKey = await this.verifyPublicKey(token);if (byPublicKey) return rejectExpired(byPublicKey);@@ -84,7 +86,10 @@ export class Verifier {return null;}- /** backfillSlowHash bcrypt-verifies keys without a fast hash and backfills matching secrets. */+ /**+ * backfillSlowHash bcrypt-verifies keys without a fast hash and backfills matching secrets.+ * @deprecated Slow-hash backfill will be removed in the next major version.+ */private async backfillSlowHash(publicKey: string,secretKey: string,@@ -115,7 +120,10 @@ export class Verifier {: null;}- /** verifyPublicKey resolves a public-key token to its scores-only presentation, or null when it is not a public key or is unknown. */+ /**+ * verifyPublicKey resolves a public-key token to its scores-only presentation, or null when it is not a public key or is unknown.+ * @deprecated Public bearer authentication will be removed in the next major version.+ */private async verifyPublicKey(token: string,): Promise<VerifyApiKeyResult | null> {diff --git a/web/src/features/auth/policy/contextResolver.ts b/web/src/features/auth/policy/contextResolver.tsindex a03f23e4bc..a883379fe6 100644--- a/web/src/features/auth/policy/contextResolver.ts+++ b/web/src/features/auth/policy/contextResolver.ts@@ -1,9 +1,10 @@import {+ Prisma,type ApiKey,type PrismaClient,prisma as defaultPrisma,} from "@langfuse/shared/src/db";-import { CloudConfigSchema, type InternalServerError } from "@langfuse/shared";+import { CloudConfigSchema, InternalServerError } from "@langfuse/shared";import {ApiKeyId,OrganizationId,@@ -12,6 +13,8 @@ import {systemRoleAccessRights,} from "@langfuse/shared/rbac";+import { assignRole } from "@langfuse/shared/rbac/server";+import { getRolesForPrincipal } from "@/src/features/rbac/getRolesForPrincipal";import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server";import {@@ -20,7 +23,7 @@ import {type OrganizationWithProjects,} from "./organizationRepository";import { authorize } from "@/src/features/rbac/authorize";-import { type Policy } from "@/src/features/rbac/types";+import { type Policy, type Role } from "@/src/features/rbac/types";import {internalServerError,type AuthorizationContext,@@ -40,6 +43,7 @@ export class ContextResolver {/** resolve turns a verified credential into its context, collapsing a missing org to a 500 invariant break. */async resolve(params: ResolveContextParams): Promise<Resolved> {+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Compatibility until the next major version.if (params.authorization === "admin") {return { success: true, context: adminContext() };}@@ -49,6 +53,7 @@ export class ContextResolver {success: true,context: await materialize(params.apiKey,+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Compatibility until the next major version.params.authorization,org.organization,this.prisma,@@ -112,18 +117,71 @@ async function materialize(boundResource: boundResourceFor(apiKey, org),};- const roles = await getRolesForPrincipal(ApiKeyId(apiKey.id), prisma);+ const roles = await getRolesForApiKey(apiKey.id);const context = {principal,policies: roles.flatMap((role) => role.policies),};if (authorization === "publicKey") {+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Compatibility until the next major version.return { principal, policies: publicBearerPolicies(context, apiKey, org) };}return context;++ /** getRolesForApiKey restores missing assignments and rejects an empty result after repair. */+ async function getRolesForApiKey(apiKeyId: string): Promise<Role[]> {+ let roles = await getRolesForPrincipal(prisma, ApiKeyId(apiKeyId));+ if (roles.length === 0) {+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Compatibility until the next major version.+ await backfillApiKeyRoleAssignment(prisma, apiKey, org);+ roles = await getRolesForPrincipal(prisma, ApiKeyId(apiKeyId));+ }+ if (roles.length === 0) {+ throw new InternalServerError(+ `API key ${apiKeyId} has no role assignments after backfill`,+ );+ }+ return roles;+ }+}++/**+ * backfillApiKeyRoleAssignment restores a verified key's legacy role.+ * @deprecated RoleAssignment backfill will be removed in the next major version.+ */+async function backfillApiKeyRoleAssignment(+ prisma: PrismaClient,+ apiKey: ApiKey,+ org: PrincipalOrganization,+): Promise<void> {+ const isProject = apiKey.scope === "PROJECT";+ await assignRole(prisma, {+ tenantId: OrganizationId(org.orgId),+ principalId: ApiKeyId(apiKey.id),+ ownerId: isProject+ ? ProjectId(apiKey.projectId!)+ : OrganizationId(apiKey.orgId!),+ roleId: SystemRoleId(+ isProject ? "LEGACY_PROJECT_API_KEY" : "LEGACY_ORGANIZATION_API_KEY",+ ),+ tags: [],+ }).catch((error: unknown) => {+ if (!isUniqueConstraintFailedError(error)) throw error;+ });+}++/** isUniqueConstraintFailedError identifies Prisma's P2002 uniqueness violation. */+function isUniqueConstraintFailedError(error: unknown): boolean {+ return (+ error instanceof Prisma.PrismaClientKnownRequestError &&+ error.code === "P2002"+ );}-/** publicBearerPolicies narrows a public-key bearer to scores:save on its own project, granted only when the key's stored roles allow it there. */+/**+ * publicBearerPolicies narrows a public-key bearer to scores:save on its own project, granted only when the key's stored roles allow it there.+ * @deprecated Public bearer authentication will be removed in the next major version.+ */function publicBearerPolicies(roleContext: AuthorizationContext,apiKey: ApiKey,@@ -146,9 +204,7 @@ function publicBearerPolicies(}));}-/** adminContext is the self-host superuser: an evaluated OWNER on every tenant. It binds the OWNER catalog to the org- and project-kind wildcards under the organization/* tenant, so the PDP grants it exactly what OWNER grants, on every tenant.- *- * The organization/* tenant is minted only here; a future custom-role loader must reject a wildcard tenant on a stored role. */+/** adminContext grants the admin principal OWNER permissions across all tenants. */function adminContext(): AuthorizationContext {const principal: Principal = { kind: "admin", userId: null };const roleId = SystemRoleId("OWNER");@@ -204,6 +260,7 @@ function getCloudConfig(/** ResolveContextParams is a verified credential: an api key with how it was presented, or the admin key. */export type ResolveContextParams =| {+ /** @deprecated Remove in the next major version when all API-key authentication is private. */authorization: "publicKey" | "privateKey";apiKey: ApiKey;}diff --git a/web/src/features/public-api/server/enforceAuth.ts b/web/src/features/public-api/server/enforceAuth.tsindex 4ec39d40db..af389a362a 100644--- a/web/src/features/public-api/server/enforceAuth.ts+++ b/web/src/features/public-api/server/enforceAuth.ts@@ -163,19 +163,16 @@ function getOrgId(return { success: true, orgId };}-/** getProjectId resolves the target project the key's bound project, the URL param, and the header agree on. */+/** getProjectId prioritizes the bound project, then the query parameter, then the header. */function getProjectId(context: AuthorizationContext,req: NextApiRequest,): ResolvedProject | ErrorResult<ForbiddenError> {- const requested = [- getBoundProjectId(context),- getUrlProjectId(req),- getHeaderProjectId(req),- ];-- const projectId = first(requested);- if (!equal(requested) || !projectId) {+ const projectId =+ getBoundProjectId(context) ??+ getUrlProjectId(req) ??+ getHeaderProjectId(req);+ if (!projectId) {return forbiddenError();}diff --git a/web/src/features/rbac/getRolesForPrincipal.ts b/web/src/features/rbac/getRolesForPrincipal.tsindex f68656ff4a..5c7fb42965 100644--- a/web/src/features/rbac/getRolesForPrincipal.ts+++ b/web/src/features/rbac/getRolesForPrincipal.ts@@ -1,4 +1,3 @@-import { InternalServerError } from "@langfuse/shared";import {hasOrganizationKind,hasProjectKind,@@ -14,17 +13,13 @@ import {type TenantId,} from "@langfuse/shared/rbac";import { getRoleAssignmentsForPrincipal } from "@langfuse/shared/rbac/server";-import {- prisma as defaultPrisma,- type PrismaClient,- type RoleAssignment,-} from "@langfuse/shared/src/db";+import { type Prisma, type RoleAssignment } from "@langfuse/shared/src/db";import { type Policy, type Role } from "./types";/** getRolesForPrincipal loads a principal's roles with policies bound to each assignment. */export async function getRolesForPrincipal(+ prisma: Prisma.TransactionClient,principalId: PrincipalId,- prisma: PrismaClient = defaultPrisma,): Promise<Role[]> {const assignments = await getRoleAssignmentsForPrincipal(prisma, principalId);return assignments.map(toRole);@@ -53,11 +48,8 @@ function toRole(assignment: RoleAssignment): Role {/** toOwnerId tags the populated owner foreign key. */function toOwnerId(assignment: RoleAssignment): OwnerId {- if (assignment.ownerProjectId !== null)- return ProjectId(assignment.ownerProjectId);- if (assignment.ownerOrgId !== null)- return OrganizationId(assignment.ownerOrgId);- throw new InternalServerError("role assignment requires an owner");+ if (assignment.projectId !== null) return ProjectId(assignment.projectId);+ return OrganizationId(assignment.orgId);}/** toPolicy binds a catalog policy to resources of its kind. */