Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(rbac): resolve API-key authorization from SystemRoleAssignments (#17952)

Mark Salpeter5cebf7ed3fb8
diff --git a/fern/apis/organizations/definition/organizations.yml b/fern/apis/organizations/definition/organizations.yml
index 5ca96bd5a2..f7c53daf86 100644
--- a/fern/apis/organizations/definition/organizations.yml
+++ b/fern/apis/organizations/definition/organizations.yml
@@ -100,9 +100,18 @@ service:
name: CreateApiKeyRequest
body:
properties:
+ name:
+ type: optional<string>
+ docs: Optional name for the API key. Cannot be provided together with note, even if either value is an empty string.
note:
type: optional<string>
- docs: Optional note for the API key
+ availability:
+ status: deprecated
+ message: Use name instead.
+ docs: Deprecated alias for name. Cannot be provided together with name, even if either value is an empty string.
+ expiresAt:
+ type: optional<nullable<datetime>>
+ docs: Optional expiration timestamp in ISO 8601 format. Must be in the future. Omit or set to null for a key that does not expire.
response: ApiKeyResponse
errors:
- commons.Error
@@ -165,9 +174,19 @@ types:
properties:
id: string
createdAt: datetime
- expiresAt: optional<datetime>
+ expiresAt:
+ type: optional<datetime>
+ docs: Expiration timestamp. Null if the key does not expire.
lastUsedAt: optional<datetime>
- note: optional<string>
+ name:
+ type: optional<nullable<string>>
+ docs: Name of the API key. Contains the same value as note; null if no name was provided.
+ note:
+ type: optional<string>
+ availability:
+ status: deprecated
+ message: Use name instead.
+ docs: Deprecated alias for name. Contains the same value as name.
publicKey: string
displaySecretKey: string
@@ -176,7 +195,18 @@ types:
properties:
id: string
createdAt: datetime
+ expiresAt:
+ type: optional<nullable<datetime>>
+ docs: Expiration timestamp. Null if the key does not expire.
publicKey: string
secretKey: string
displaySecretKey: string
- note: optional<string>
+ name:
+ type: optional<nullable<string>>
+ docs: Name of the API key. Contains the same value as note; null if no name was provided.
+ note:
+ type: optional<string>
+ availability:
+ status: deprecated
+ message: Use name instead.
+ docs: Deprecated alias for name. Contains the same value as name.
diff --git a/fern/apis/server/definition/organizations.yml b/fern/apis/server/definition/organizations.yml
index abd54ae307..c5b67c2887 100644
--- a/fern/apis/server/definition/organizations.yml
+++ b/fern/apis/server/definition/organizations.yml
@@ -114,9 +114,19 @@ types:
properties:
id: string
createdAt: datetime
- expiresAt: optional<datetime>
+ expiresAt:
+ type: optional<datetime>
+ docs: Expiration timestamp. Null if the key does not expire.
lastUsedAt: optional<datetime>
- note: optional<string>
+ name:
+ type: optional<nullable<string>>
+ docs: Name of the API key. Contains the same value as note; null if no name was provided.
+ note:
+ type: optional<string>
+ availability:
+ status: deprecated
+ message: Use name instead.
+ docs: Deprecated alias for name. Contains the same value as name.
publicKey: string
displaySecretKey: string
diff --git a/fern/apis/server/definition/projects.yml b/fern/apis/server/definition/projects.yml
index 26809c571c..89e548841b 100644
--- a/fern/apis/server/definition/projects.yml
+++ b/fern/apis/server/definition/projects.yml
@@ -81,9 +81,18 @@ service:
name: CreateApiKeyRequest
body:
properties:
+ name:
+ type: optional<string>
+ docs: Optional name for the API key. Cannot be provided together with note, even if either value is an empty string.
note:
type: optional<string>
- docs: Optional note for the API key
+ availability:
+ status: deprecated
+ message: Use name instead.
+ docs: Deprecated alias for name. Cannot be provided together with name, even if either value is an empty string.
+ expiresAt:
+ type: optional<nullable<datetime>>
+ docs: Optional expiration timestamp in ISO 8601 format. Must be in the future. Omit or set to null for a key that does not expire.
publicKey:
type: optional<string>
docs: Optional predefined public key. Must start with 'pk-lf-'. If provided, secretKey must also be provided.
@@ -144,9 +153,19 @@ types:
properties:
id: string
createdAt: datetime
- expiresAt: optional<datetime>
+ expiresAt:
+ type: optional<datetime>
+ docs: Expiration timestamp. Null if the key does not expire.
lastUsedAt: optional<datetime>
- note: optional<string>
+ name:
+ type: optional<nullable<string>>
+ docs: Name of the API key. Contains the same value as note; null if no name was provided.
+ note:
+ type: optional<string>
+ availability:
+ status: deprecated
+ message: Use name instead.
+ docs: Deprecated alias for name. Contains the same value as name.
publicKey: string
displaySecretKey: string
@@ -155,10 +174,21 @@ types:
properties:
id: string
createdAt: datetime
+ expiresAt:
+ type: optional<nullable<datetime>>
+ docs: Expiration timestamp. Null if the key does not expire.
publicKey: string
secretKey: string
displaySecretKey: string
- note: optional<string>
+ name:
+ type: optional<nullable<string>>
+ docs: Name of the API key. Contains the same value as note; null if no name was provided.
+ note:
+ type: optional<string>
+ availability:
+ status: deprecated
+ message: Use name instead.
+ docs: Deprecated alias for name. Contains the same value as name.
ApiKeyDeletionResponse:
docs: Response for API key deletion
diff --git a/package.json b/package.json
index 64eb0eae28..dadb196a28 100644
--- a/package.json
+++ b/package.json
@@ -47,7 +47,7 @@
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,css}\" --experimental-cli",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,css}\" --experimental-cli",
"playwright:install": "pnpm --filter web exec playwright install chromium",
- "openapi:export": "pnpm dlx [email protected] export --api server web/public/generated/api/openapi.yml && pnpm --filter web exec tsx scripts/openapi/postprocess-openapi.ts && pnpm dlx [email protected] export --api client web/public/generated/api-client/openapi.yml && pnpm dlx [email protected] export --api organizations web/public/generated/organizations-api/openapi.yml",
+ "openapi:export": "pnpm dlx [email protected] export --api server web/public/generated/api/openapi.yml && pnpm --filter web exec tsx scripts/openapi/postprocess-openapi.ts && pnpm dlx [email protected] export --api client web/public/generated/api-client/openapi.yml && pnpm dlx [email protected] export --api organizations web/public/generated/organizations-api/openapi.yml && pnpm --filter web exec tsx scripts/openapi/postprocess-openapi.ts organizations",
"openapi:check": "pnpm run openapi:export && bash scripts/openapi/assert-generated-current.sh",
"storybook": "pnpm --filter web run storybook",
"test": "turbo run test",
diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.md
index e0d93045c8..554bec2c5f 100644
--- a/packages/shared/AGENTS.md
+++ b/packages/shared/AGENTS.md
@@ -137,6 +137,10 @@
- `@langfuse/shared/encryption` via `src/encryption/index.ts`: encryption and
signature helpers for secrets and signed payloads.
- `@langfuse/shared/query` via `src/features/query/index.ts`: dashboard query feature.
+- `@langfuse/shared/rbac` via `src/features/rbac/index.ts`: client-safe tagged IDs,
+ role assignments, role catalog, and permission vocabulary.
+- `@langfuse/shared/rbac/server` via `src/features/rbac/server.ts`: server-only
+ role-assignment reads and writes, mapping database foreign keys to tagged IDs.
- `@langfuse/shared/instrumentation/bootstrap` via
`src/server/instrumentation/bootstrap/index.ts`: instrumentation initializers loaded before sdk.start(); must not import the server barrel or any instrumented library.
- `@langfuse/shared/in-app-agent` via `src/in-app-agent/index.ts`:
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 662d3fc6b2..6c52d0935f 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -95,6 +95,14 @@
"import": "./dist/src/features/query/index.js",
"require": "./dist/src/features/query/index.js"
},
+ "./rbac": {
+ "import": "./dist/src/features/rbac/index.js",
+ "require": "./dist/src/features/rbac/index.js"
+ },
+ "./rbac/server": {
+ "import": "./dist/src/features/rbac/server.js",
+ "require": "./dist/src/features/rbac/server.js"
+ },
"./query/server": {
"import": "./dist/src/features/query/server/index.js",
"require": "./dist/src/features/query/server/index.js"
diff --git a/packages/shared/prisma/migrations/20260924213305_add_role_assignments/migration.sql b/packages/shared/prisma/migrations/20260924213305_add_role_assignments/migration.sql
new file mode 100644
index 0000000000..abd7b03a25
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260924213305_add_role_assignments/migration.sql
@@ -0,0 +1,31 @@
+CREATE TYPE "SystemRole" AS ENUM ('OWNER', 'ADMIN', 'MEMBER', 'VIEWER', 'NONE', 'LEGACY_PROJECT_API_KEY', 'LEGACY_ORGANIZATION_API_KEY', 'SCORES_INGEST', 'INGEST', 'AI_GATEWAY');
+
+CREATE TABLE "role_assignments" (
+ "id" TEXT NOT NULL,
+ "org_id" TEXT NOT NULL,
+ "principal_user_id" TEXT,
+ "principal_api_key_id" TEXT,
+ "system_role" "SystemRole" NOT NULL,
+ "owner_org_id" TEXT,
+ "owner_project_id" TEXT,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "role_assignments_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "role_assignments_exactly_one_principal" CHECK (("principal_user_id" IS NOT NULL) <> ("principal_api_key_id" IS NOT NULL)),
+ CONSTRAINT "role_assignments_exactly_one_owner" CHECK (("owner_org_id" IS NOT NULL) <> ("owner_project_id" IS NOT NULL))
+);
+
+CREATE UNIQUE INDEX "role_assignments_user_org_role_key" ON "role_assignments"("principal_user_id", "owner_org_id", "system_role");
+CREATE UNIQUE INDEX "role_assignments_user_project_role_key" ON "role_assignments"("principal_user_id", "owner_project_id", "system_role");
+CREATE UNIQUE INDEX "role_assignments_api_key_org_role_key" ON "role_assignments"("principal_api_key_id", "owner_org_id", "system_role");
+CREATE UNIQUE INDEX "role_assignments_api_key_project_role_key" ON "role_assignments"("principal_api_key_id", "owner_project_id", "system_role");
+CREATE INDEX "role_assignments_org_id_idx" ON "role_assignments"("org_id");
+CREATE INDEX "role_assignments_owner_org_id_idx" ON "role_assignments"("owner_org_id");
+CREATE INDEX "role_assignments_owner_project_id_idx" ON "role_assignments"("owner_project_id");
+
+ALTER TABLE "role_assignments" ADD CONSTRAINT "role_assignments_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+ALTER TABLE "role_assignments" ADD CONSTRAINT "role_assignments_principal_user_id_fkey" FOREIGN KEY ("principal_user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+ALTER TABLE "role_assignments" ADD CONSTRAINT "role_assignments_principal_api_key_id_fkey" FOREIGN KEY ("principal_api_key_id") REFERENCES "api_keys"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+ALTER TABLE "role_assignments" ADD CONSTRAINT "role_assignments_owner_org_id_fkey" FOREIGN KEY ("owner_org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+ALTER TABLE "role_assignments" ADD CONSTRAINT "role_assignments_owner_project_id_fkey" FOREIGN KEY ("owner_project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/migrations/20260924213400_backfill_role_assignments/migration.sql b/packages/shared/prisma/migrations/20260924213400_backfill_role_assignments/migration.sql
new file mode 100644
index 0000000000..b2cca40fdd
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260924213400_backfill_role_assignments/migration.sql
@@ -0,0 +1,16 @@
+INSERT INTO "role_assignments" ("id", "org_id", "principal_api_key_id", "system_role", "owner_org_id", "owner_project_id", "created_at", "updated_at")
+SELECT gen_random_uuid()::text,
+ CASE WHEN ak.scope = 'ORGANIZATION' THEN ak.organization_id ELSE p.org_id END,
+ ak.id,
+ CASE ak.scope
+ WHEN 'PROJECT' THEN 'LEGACY_PROJECT_API_KEY'::"SystemRole"
+ WHEN 'ORGANIZATION' THEN 'LEGACY_ORGANIZATION_API_KEY'::"SystemRole"
+ END,
+ CASE WHEN ak.scope = 'ORGANIZATION' THEN ak.organization_id END,
+ CASE WHEN ak.scope = 'PROJECT' THEN ak.project_id END,
+ now(), now()
+FROM api_keys ak
+LEFT JOIN projects p ON p.id = ak.project_id
+WHERE (ak.scope = 'ORGANIZATION' AND ak.organization_id IS NOT NULL)
+ OR (ak.scope = 'PROJECT' AND ak.project_id IS NOT NULL AND p.org_id IS NOT NULL)
+ON CONFLICT DO NOTHING;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 61fe8d0cc7..1998c8164c 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -85,6 +85,7 @@ model User {
inAppAgentConversations InAppAgentConversation[] @relation("InAppAgentConversationCreatedByUser")
inAppAgentRuns InAppAgentRun[] @relation("InAppAgentRunTriggeredByUser")
apiKeysCreated ApiKey[] @relation("ApiKeyCreatedByUser")
+ roleAssignments RoleAssignment[]
evaluatorsCreated Evaluator[] @relation("EvaluatorCreatedByUser")
evaluatorVersionsCreated EvaluatorVersion[] @relation("EvaluatorVersionCreatedByUser")
evaluationRulesCreated EvaluationRule[] @relation("EvaluationRuleCreatedByUser")
@@ -129,6 +130,8 @@ model Organization {
verifiedDomains VerifiedDomain[]
gatewayConfig GatewayConfig?
gatewayAiConnections GatewayAiConnection[]
+ roleAssignments RoleAssignment[] @relation("RoleAssignmentTenant")
+ ownedRoleAssignments RoleAssignment[] @relation("RoleAssignmentOwnerOrganization")
@@map("organizations")
}
@@ -150,6 +153,7 @@ model Project {
projectMembers ProjectMembership[]
organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
apiKeys ApiKey[]
+ roleAssignments RoleAssignment[]
dataset Dataset[]
invitations MembershipInvitation[]
sessions TraceSession[]
@@ -235,6 +239,7 @@ model ApiKey {
createdByApiKey ApiKey? @relation("ApiKeyCreatedByApiKey", fields: [createdByApiKeyId], references: [id], onDelete: SetNull)
apiKeysCreated ApiKey[] @relation("ApiKeyCreatedByApiKey")
gatewayAssociation GatewayApiKeyAssociation?
+ roleAssignments RoleAssignment[]
@@index(orgId)
@@index(projectId)
@@ -245,6 +250,45 @@ model ApiKey {
@@map("api_keys")
}
+enum SystemRole {
+ OWNER
+ ADMIN
+ MEMBER
+ VIEWER
+ NONE
+ LEGACY_PROJECT_API_KEY
+ LEGACY_ORGANIZATION_API_KEY
+ SCORES_INGEST
+ INGEST
+ AI_GATEWAY
+}
+
+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")
+ @@index([orgId])
+ @@index([ownerOrgId])
+ @@index([ownerProjectId])
+ @@map("role_assignments")
+}
+
enum GatewayIngestionMode {
USAGE @map("usage")
FULL @map("full")
diff --git a/packages/shared/scripts/seeder/load-seed-clickhouse.ts b/packages/shared/scripts/seeder/load-seed-clickhouse.ts
index ad50be03f0..15e86a7b05 100644
--- a/packages/shared/scripts/seeder/load-seed-clickhouse.ts
+++ b/packages/shared/scripts/seeder/load-seed-clickhouse.ts
@@ -1,6 +1,13 @@
import { randomUUID } from "crypto";
import { prisma } from "../../src/db";
import { getDisplaySecretKey, hashSecretKey, logger } from "../../src/server";
+import { assignRole } from "../../src/features/rbac/roleAssignmentRepository";
+import {
+ ApiKeyId,
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+} from "../../src/features/rbac/types";
import { prepareClickhouse } from "./prepare-clickhouse";
import { redis } from "../../src/server";
@@ -33,7 +40,7 @@ const prepareProjectsAndApiKeys = async (
},
});
- await prisma.project.upsert({
+ const project = await prisma.project.upsert({
where: { id: projectId },
update: {},
create: {
@@ -51,20 +58,29 @@ const prepareProjectsAndApiKeys = async (
const sk = await hashSecretKey(
`sk-${Math.random().toString(36).slice(2, 11)}`,
);
- await prisma.apiKey.create({
- data: {
- id: apiKeyId,
- note: `API Key for ${projectId}`,
- publicKey: `pk-${Math.random().toString(36).slice(2, 11)}`,
- hashedSecretKey: sk,
- displaySecretKey: getDisplaySecretKey(sk),
- scope: "PROJECT",
- project: {
- connect: {
- id: projectId,
+ await prisma.$transaction(async (tx) => {
+ await tx.apiKey.create({
+ data: {
+ id: apiKeyId,
+ note: `API Key for ${projectId}`,
+ publicKey: `pk-${Math.random().toString(36).slice(2, 11)}`,
+ hashedSecretKey: sk,
+ displaySecretKey: getDisplaySecretKey(sk),
+ scope: "PROJECT",
+ project: {
+ connect: {
+ id: projectId,
+ },
},
},
- },
+ });
+ await assignRole(tx, {
+ tenantId: OrganizationId(project.orgId),
+ principalId: ApiKeyId(apiKeyId),
+ roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ ownerId: ProjectId(projectId),
+ tags: [],
+ });
});
}
});
diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.ts
index f09e28dadb..c90f90266e 100644
--- a/packages/shared/scripts/seeder/seed-postgres.ts
+++ b/packages/shared/scripts/seeder/seed-postgres.ts
@@ -16,12 +16,13 @@ import {
ScoreDataTypeEnum,
type ScoreDataTypeType,
} from "../../src/index";
+import { createApiKey, getDisplaySecretKey, logger } from "../../src/server";
import {
- createAndAddApiKeysToDb,
- getDisplaySecretKey,
- hashSecretKey,
- logger,
-} from "../../src/server";
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "../../src/features/rbac/types";
import { redis } from "../../src/server/redis/redis";
import {
DEFAULT_SEED_API_KEY,
@@ -228,20 +229,19 @@ async function main() {
secret: process.env.SEED_SECRET_KEY ?? DEFAULT_SEED_API_KEY.secret, // eslint-disable-line turbo/no-undeclared-env-vars
};
- if (!(await prisma.apiKey.findUnique({ where: { id: seedApiKey.id } }))) {
- await prisma.apiKey.create({
- data: {
- note: seedApiKey.note,
- id: seedApiKey.id,
+ if (
+ !(await prisma.apiKey.findUnique({
+ where: { publicKey: seedApiKey.public },
+ }))
+ ) {
+ await createApiKey(prisma, {
+ owner: ProjectId(project1.id),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ name: seedApiKey.note,
+ predefinedKeys: {
publicKey: seedApiKey.public,
- hashedSecretKey: await hashSecretKey(seedApiKey.secret),
- displaySecretKey: getDisplaySecretKey(seedApiKey.secret),
- scope: "PROJECT",
- project: {
- connect: {
- id: project1.id,
- },
- },
+ secretKey: seedApiKey.secret,
},
});
}
@@ -286,25 +286,23 @@ async function main() {
await upsertInAppAgentSystemPrompt(project2.id);
const secondKey = {
- id: "seed-api-key-2",
secret: process.env.SEED_SECRET_KEY ?? "sk-lf-asdfghjkl", // eslint-disable-line turbo/no-undeclared-env-vars
public: "pk-lf-asdfghjkl",
note: "seeded key 2",
};
- if (!(await prisma.apiKey.findUnique({ where: { id: secondKey.id } }))) {
- await prisma.apiKey.create({
- data: {
- note: secondKey.note,
- id: secondKey.id,
+ if (
+ !(await prisma.apiKey.findUnique({
+ where: { publicKey: secondKey.public },
+ }))
+ ) {
+ await createApiKey(prisma, {
+ owner: ProjectId(project2.id),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ name: secondKey.note,
+ predefinedKeys: {
publicKey: secondKey.public,
- hashedSecretKey: await hashSecretKey(secondKey.secret),
- displaySecretKey: getDisplaySecretKey(secondKey.secret),
- scope: "PROJECT",
- project: {
- connect: {
- id: project2.id,
- },
- },
+ secretKey: secondKey.secret,
},
});
}
@@ -612,12 +610,11 @@ async function seedAiGateway(params: {
});
const key =
existingKey ??
- (await createAndAddApiKeysToDb({
- prisma,
- entityId: params.organizationId,
- scope: "ORGANIZATION",
- note: "Seeded gateway key",
- createdByUserId: params.userId,
+ (await createApiKey(prisma, {
+ owner: OrganizationId(params.organizationId),
+ role: SystemRoleId("AI_GATEWAY"),
+ createdBy: UserId(params.userId),
+ name: "Seeded gateway key",
predefinedKeys: {
publicKey,
secretKey: "sk-lf-gateway-seed",
diff --git a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts b/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts
index 4409ad7644..598e16025e 100644
--- a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts
+++ b/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts
@@ -1,5 +1,4 @@
export const DEFAULT_SEED_API_KEY = {
- id: "seed-api-key",
public: "pk-lf-1234567890",
secret: "sk-lf-1234567890",
note: "seeded key",
diff --git a/packages/shared/src/features/rbac/index.ts b/packages/shared/src/features/rbac/index.ts
new file mode 100644
index 0000000000..ee59e01e41
--- /dev/null
+++ b/packages/shared/src/features/rbac/index.ts
@@ -0,0 +1,3 @@
+export * from "./types";
+export * from "./organizationAccessRights";
+export * from "./systemRoleAccessRights";
diff --git a/web/src/features/rbac/constants/organizationAccessRights.ts b/packages/shared/src/features/rbac/organizationAccessRights.ts
similarity index 87%
rename from web/src/features/rbac/constants/organizationAccessRights.ts
rename to packages/shared/src/features/rbac/organizationAccessRights.ts
index e46ee651e6..97786ea4dd 100644
--- a/web/src/features/rbac/constants/organizationAccessRights.ts
+++ b/packages/shared/src/features/rbac/organizationAccessRights.ts
@@ -1,4 +1,4 @@
-import { type Role } from "@langfuse/shared/src/db";
+import { type Role } from "../../db";
export const organizationScopes = [
"projects:read",
@@ -11,6 +11,7 @@ export const organizationScopes = [
"gateway:invoke",
"organizationMembers:read",
"organizationMembers:CUD",
+ "organizationMembers:manageOwnership",
"langfuseCloudBilling:CRUD",
"organizationUsage:read",
"orgAuditLogs:read",
@@ -29,10 +30,13 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {
"gateway:manage",
"gateway:invoke",
"organizationMembers:CUD",
+ "organizationMembers:manageOwnership",
"organizationMembers:read",
"langfuseCloudBilling:CRUD",
"organizationUsage:read",
"orgAuditLogs:read",
+ // used for api keys
+ "projects:read",
],
ADMIN: [
"projects:create",
@@ -44,6 +48,8 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {
"organizationMembers:read",
"organizationUsage:read",
"orgAuditLogs:read",
+ // used for api keys
+ "projects:read",
],
MEMBER: ["gateway:invoke", "organizationMembers:read"],
VIEWER: [],
diff --git a/packages/shared/src/features/rbac/projectAccessRights.ts b/packages/shared/src/features/rbac/projectAccessRights.ts
index bc5b94adb4..264ac01b5d 100644
--- a/packages/shared/src/features/rbac/projectAccessRights.ts
+++ b/packages/shared/src/features/rbac/projectAccessRights.ts
@@ -1,66 +1,54 @@
import { type Role } from "../../db";
export const projectScopes = [
- "projectMembers:read",
- "projectMembers:CUD",
-
- "apiKeys:read",
- "apiKeys:CUD",
+ "alerts:CUD",
+ "alerts:read",
- "objects:publish",
- "objects:bookmark",
- "objects:tag",
+ "annotationQueueAssignments:CUD",
+ "annotationQueueAssignments:read",
- "traces:delete",
+ "annotationQueues:CUD",
+ "annotationQueues:read",
- "scores:CUD",
+ "apiKeys:CUD",
+ "apiKeys:read",
- "scoreConfigs:CUD",
- "scoreConfigs:read",
+ "automations:CUD",
+ "automations:read",
- "annotationQueues:read",
- "annotationQueues:CUD",
- "annotationQueueAssignments:read",
- "annotationQueueAssignments:CUD",
+ "batchExports:create",
+ "batchExports:read",
- "project:read",
- "project:update",
- "project:delete",
+ "comments:CUD",
+ "comments:read",
- "integrations:CRUD",
+ "dashboards:CUD",
+ "dashboards:read",
- "datasets:read",
"datasets:CUD",
+ "datasets:read",
- "prompts:CUD",
- "prompts:read",
- "promptProtectedLabels:CUD",
-
- "skills:CUD",
- "skills:read",
-
- "dashboards:read",
- "dashboards:CUD",
+ "evalDefaultModel:CUD",
+ "evalDefaultModel:read",
- "models:CUD",
+ "evalJobExecution:read",
- "batchExports:create",
- "batchExports:read",
+ "evaluationRule:CUD",
+ "evaluationRule:read",
"evaluator:CUD",
- "topics:CUD",
"evaluator:read",
- "topics:read",
- "evaluationRule:read",
- "evaluationRule:CUD",
- "evalJobExecution:read",
- "evalDefaultModel:read",
- "evalDefaultModel:CUD",
- "llmApiKeys:read",
+ "experiments:read",
+
+ "feedback:create",
+
+ "integrations:CRUD",
+
"llmApiKeys:create",
- "llmApiKeys:update",
"llmApiKeys:delete",
+ "llmApiKeys:read",
+ "llmApiKeys:update",
"llmSchemas:CUD",
"llmSchemas:read",
@@ -68,37 +56,59 @@ export const projectScopes = [
"llmTools:CUD",
"llmTools:read",
+ "media:create",
+ "media:read",
+
+ "metrics:read",
+
+ "models:CUD",
+ "models:read",
+
+ "objects:bookmark",
+ "objects:publish",
+ "objects:tag",
+
"playground:execute",
- "comments:CUD",
- "comments:read",
+ "project:delete",
+ "project:read",
+ "project:update",
+
+ "projectAuditLogs:read",
+
+ "projectMembers:CUD",
+ "projectMembers:manageOwnership",
+ "projectMembers:read",
"promptExperiments:CUD",
"promptExperiments:read",
- "projectAuditLogs:read",
+ "promptProtectedLabels:CUD",
+
+ "prompts:CUD",
+ "prompts:read",
+
+ "scoreConfigs:CUD",
+ "scoreConfigs:read",
+
+ "scores:delete",
+ "scores:read",
+ "scores:save",
+
+ "sessions:read",
+
+ "skills:CUD",
+ "skills:read",
"TableViewPresets:CUD",
"TableViewPresets:read",
- "automations:CUD",
- "automations:read",
-
- "alerts:read",
- "alerts:CUD",
+ "topics:CUD",
+ "topics:read",
- // Public-API action tokens; not granted to any UI role.
- "traces:read",
"traces:create",
- "scores:read",
- "scores:create",
- "media:read",
- "media:create",
- "sessions:read",
- "metrics:read",
- "models:read",
- "experiments:read",
- "feedback:create",
+ "traces:delete",
+ "traces:read",
] as const;
// type string of all Resource:Action, e.g. "members:read"
@@ -106,197 +116,228 @@ export type ProjectScope = (typeof projectScopes)[number];
export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
OWNER: [
- "project:read",
- "project:update",
- "project:delete",
- "projectMembers:read",
- "projectMembers:CUD",
- "apiKeys:read",
+ "alerts:CUD",
+ "alerts:read",
+ "annotationQueueAssignments:CUD",
+ "annotationQueueAssignments:read",
+ "annotationQueues:CUD",
+ "annotationQueues:read",
"apiKeys:CUD",
- "integrations:CRUD",
- "objects:publish",
- "objects:bookmark",
- "objects:tag",
- "traces:delete",
- "scores:CUD",
- "scoreConfigs:CUD",
- "scoreConfigs:read",
- "datasets:read",
+ "apiKeys:read",
+ "automations:CUD",
+ "automations:read",
+ "batchExports:create",
+ "batchExports:read",
+ "comments:CUD",
+ "comments:read",
+ "dashboards:CUD",
+ "dashboards:read",
"datasets:CUD",
- "prompts:CUD",
- "prompts:read",
- "promptProtectedLabels:CUD",
- "skills:CUD",
- "skills:read",
- "models:CUD",
- "evaluator:CUD",
- "topics:CUD",
- "evaluator:read",
- "topics:read",
- "evaluationRule:CUD",
- "evaluationRule:read",
- "evalJobExecution:read",
+ "datasets:read",
"evalDefaultModel:CUD",
"evalDefaultModel:read",
- "llmApiKeys:read",
+ "evalJobExecution:read",
+ "evaluationRule:CUD",
+ "evaluationRule:read",
+ "evaluator:CUD",
+ "evaluator:read",
+ "experiments:read",
+ "feedback:create",
+ "integrations:CRUD",
"llmApiKeys:create",
- "llmApiKeys:update",
"llmApiKeys:delete",
+ "llmApiKeys:read",
+ "llmApiKeys:update",
"llmSchemas:CUD",
"llmSchemas:read",
"llmTools:CUD",
"llmTools:read",
+ "media:create",
+ "media:read",
+ "metrics:read",
+ "models:CUD",
+ "models:read",
+ "objects:bookmark",
+ "objects:publish",
+ "objects:tag",
"playground:execute",
- "batchExports:create",
- "batchExports:read",
- "comments:CUD",
- "comments:read",
- "annotationQueues:read",
- "annotationQueues:CUD",
- "annotationQueueAssignments:read",
- "annotationQueueAssignments:CUD",
- "promptExperiments:CUD",
- "promptExperiments:read",
- "projectAuditLogs:read",
- "dashboards:read",
- "dashboards:CUD",
- "TableViewPresets:CUD",
- "TableViewPresets:read",
- "automations:CUD",
- "automations:read",
- "alerts:read",
- "alerts:CUD",
- ],
- ADMIN: [
+ "project:delete",
"project:read",
"project:update",
- "projectMembers:read",
+ "projectAuditLogs:read",
"projectMembers:CUD",
- "apiKeys:read",
- "apiKeys:CUD",
- "integrations:CRUD",
- "objects:publish",
- "objects:bookmark",
- "objects:tag",
- "traces:delete",
- "scores:CUD",
- "scoreConfigs:CUD",
- "scoreConfigs:read",
- "datasets:read",
- "datasets:CUD",
+ "projectMembers:manageOwnership",
+ "projectMembers:read",
+ "promptExperiments:CUD",
+ "promptExperiments:read",
+ "promptProtectedLabels:CUD",
"prompts:CUD",
"prompts:read",
- "promptProtectedLabels:CUD",
+ "scoreConfigs:CUD",
+ "scoreConfigs:read",
+ "scores:delete",
+ "scores:read",
+ "scores:save",
+ "sessions:read",
"skills:CUD",
"skills:read",
- "models:CUD",
- "evaluator:CUD",
+ "TableViewPresets:CUD",
+ "TableViewPresets:read",
"topics:CUD",
- "evaluator:read",
"topics:read",
- "evaluationRule:CUD",
- "evaluationRule:read",
- "evalJobExecution:read",
+ "traces:create",
+ "traces:delete",
+ "traces:read",
+ ],
+ ADMIN: [
+ "alerts:CUD",
+ "alerts:read",
+ "annotationQueueAssignments:CUD",
+ "annotationQueueAssignments:read",
+ "annotationQueues:CUD",
+ "annotationQueues:read",
+ "apiKeys:CUD",
+ "apiKeys:read",
+ "automations:CUD",
+ "automations:read",
+ "batchExports:create",
+ "batchExports:read",
+ "comments:CUD",
+ "comments:read",
+ "dashboards:CUD",
+ "dashboards:read",
+ "datasets:CUD",
+ "datasets:read",
"evalDefaultModel:CUD",
"evalDefaultModel:read",
- "llmApiKeys:read",
+ "evalJobExecution:read",
+ "evaluationRule:CUD",
+ "evaluationRule:read",
+ "evaluator:CUD",
+ "evaluator:read",
+ "experiments:read",
+ "feedback:create",
+ "integrations:CRUD",
"llmApiKeys:create",
- "llmApiKeys:update",
"llmApiKeys:delete",
+ "llmApiKeys:read",
+ "llmApiKeys:update",
"llmSchemas:CUD",
"llmSchemas:read",
"llmTools:CUD",
"llmTools:read",
+ "media:create",
+ "media:read",
+ "metrics:read",
+ "models:CUD",
+ "models:read",
+ "objects:bookmark",
+ "objects:publish",
+ "objects:tag",
"playground:execute",
- "batchExports:create",
- "batchExports:read",
- "comments:CUD",
- "comments:read",
- "annotationQueues:read",
- "annotationQueues:CUD",
- "annotationQueueAssignments:read",
- "annotationQueueAssignments:CUD",
+ "project:read",
+ "project:update",
+ "projectAuditLogs:read",
+ "projectMembers:CUD",
+ "projectMembers:read",
"promptExperiments:CUD",
"promptExperiments:read",
- "projectAuditLogs:read",
- "dashboards:read",
- "dashboards:CUD",
+ "promptProtectedLabels:CUD",
+ "prompts:CUD",
+ "prompts:read",
+ "scoreConfigs:CUD",
+ "scoreConfigs:read",
+ "scores:delete",
+ "scores:read",
+ "scores:save",
+ "sessions:read",
+ "skills:CUD",
+ "skills:read",
"TableViewPresets:CUD",
"TableViewPresets:read",
- "automations:CUD",
- "automations:read",
- "alerts:read",
- "alerts:CUD",
+ "topics:CUD",
+ "topics:read",
+ "traces:create",
+ "traces:delete",
+ "traces:read",
],
MEMBER: [
- "project:read",
- "projectMembers:read",
+ "alerts:CUD",
+ "alerts:read",
+ "annotationQueueAssignments:read",
+ "annotationQueues:CUD",
+ "annotationQueues:read",
"apiKeys:read",
- "objects:publish",
- "objects:bookmark",
- "objects:tag",
- "scores:CUD",
- "scoreConfigs:CUD",
- "scoreConfigs:read",
- "datasets:read",
+ "automations:read",
+ "batchExports:create",
+ "batchExports:read",
+ "comments:CUD",
+ "comments:read",
+ "dashboards:CUD",
+ "dashboards:read",
"datasets:CUD",
- "prompts:CUD",
- "prompts:read",
- "skills:CUD",
- "skills:read",
+ "datasets:read",
+ "evalDefaultModel:CUD",
+ "evalDefaultModel:read",
+ "evalJobExecution:read",
+ "evaluationRule:CUD",
+ "evaluationRule:read",
"evaluator:CUD",
- "topics:CUD",
"evaluator:read",
- "topics:read",
- "evaluationRule:read",
- "evaluationRule:CUD",
- "evalJobExecution:read",
- "evalDefaultModel:read",
- "evalDefaultModel:CUD",
"llmApiKeys:read",
- "llmSchemas:read",
"llmSchemas:CUD",
+ "llmSchemas:read",
"llmTools:CUD",
"llmTools:read",
+ "objects:bookmark",
+ "objects:publish",
+ "objects:tag",
"playground:execute",
- "batchExports:create",
- "batchExports:read",
- "comments:CUD",
- "comments:read",
- "annotationQueues:read",
- "annotationQueues:CUD",
- "annotationQueueAssignments:read",
+ "project:read",
+ "projectMembers:read",
"promptExperiments:CUD",
"promptExperiments:read",
- "dashboards:read",
- "dashboards:CUD",
+ "prompts:CUD",
+ "prompts:read",
+ "scoreConfigs:CUD",
+ "scoreConfigs:read",
+ "scores:delete",
+ "scores:save",
+ "skills:CUD",
+ "skills:read",
"TableViewPresets:CUD",
"TableViewPresets:read",
- "automations:read",
- "alerts:read",
- "alerts:CUD",
+ "topics:CUD",
+ "topics:read",
],
VIEWER: [
- "project:read",
- "prompts:read",
- "skills:read",
- "evaluator:read",
- "topics:read",
- "scoreConfigs:read",
- "evaluationRule:read",
- "evalJobExecution:read",
- "evalDefaultModel:read",
+ "alerts:read",
+ "annotationQueues:read",
+ "automations:read",
+ "comments:read",
+ "dashboards:read",
"datasets:read",
+ "evalDefaultModel:read",
+ "evalJobExecution:read",
+ "evaluationRule:read",
+ "evaluator:read",
+ "experiments:read",
"llmApiKeys:read",
"llmSchemas:read",
"llmTools:read",
- "comments:read",
- "annotationQueues:read",
+ "media:read",
+ "metrics:read",
+ "models:read",
+ "project:read",
"promptExperiments:read",
- "dashboards:read",
+ "prompts:read",
+ "scoreConfigs:read",
+ "scores:read",
+ "sessions:read",
+ "skills:read",
"TableViewPresets:read",
- "automations:read",
- "alerts:read",
+ "topics:read",
+ "traces:read",
],
NONE: [],
};
diff --git a/packages/shared/src/features/rbac/roleAssignmentRepository.ts b/packages/shared/src/features/rbac/roleAssignmentRepository.ts
new file mode 100644
index 0000000000..af72d5e7f9
--- /dev/null
+++ b/packages/shared/src/features/rbac/roleAssignmentRepository.ts
@@ -0,0 +1,78 @@
+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/server.ts b/packages/shared/src/features/rbac/server.ts
new file mode 100644
index 0000000000..178729cf8f
--- /dev/null
+++ b/packages/shared/src/features/rbac/server.ts
@@ -0,0 +1 @@
+export * from "./roleAssignmentRepository";
diff --git a/packages/shared/src/features/rbac/systemRoleAccessRights.ts b/packages/shared/src/features/rbac/systemRoleAccessRights.ts
new file mode 100644
index 0000000000..45117bf944
--- /dev/null
+++ b/packages/shared/src/features/rbac/systemRoleAccessRights.ts
@@ -0,0 +1,214 @@
+import { type Role, type SystemRole } from "../../db";
+import {
+ organizationRoleAccessRights,
+ organizationScopes,
+ type OrganizationScope,
+} from "./organizationAccessRights";
+import {
+ projectRoleAccessRights,
+ projectScopes,
+ type ProjectScope,
+} from "./projectAccessRights";
+
+/** allProjectActions is the full project action vocabulary. */
+export const allProjectActions: ProjectAction[] = [...projectScopes];
+
+/** allOrganizationActions is the full organization action vocabulary. */
+export const allOrganizationActions: OrganizationAction[] = [
+ ...organizationScopes,
+];
+
+/** organizationActionSet is allOrganizationActions indexed for membership tests. */
+const organizationActionSet: ReadonlySet<string> = new Set(organizationScopes);
+
+/** isOrgAction reports whether an action belongs to the disjoint org vocabulary. */
+export const isOrgAction = (action: Action): action is OrganizationAction =>
+ organizationActionSet.has(action);
+
+/** Effect is whether a policy grants or denies its actions. */
+export type Effect = "ALLOW" | "DENY";
+
+/** ProjectAction is an action assignable to a project policy. */
+export type ProjectAction = ProjectScope;
+
+/** OrganizationAction is an action assignable to an organization policy. */
+export type OrganizationAction = OrganizationScope;
+
+/** Action is any checkable action. */
+export type Action = ProjectAction | OrganizationAction;
+
+/** SystemRolePolicy is a catalog policy before its resource is bound. */
+export type SystemRolePolicy =
+ | {
+ resourceKind: "organization";
+ actions: OrganizationAction[];
+ effect: Effect;
+ }
+ | { resourceKind: "project"; actions: ProjectAction[]; effect: Effect };
+
+/** SystemRoleTag marks a role's intended principal kind, or `"legacy"` for a role still valid on existing keys but no longer offered for new ones. */
+export type SystemRoleTag = "principal:apiKey" | "principal:user" | "legacy";
+
+/** SystemRoleDefinition is an in-code system role's catalog entry: metadata plus its resource-less policies. */
+export type SystemRoleDefinition = {
+ id: SystemRole;
+ name: string;
+ description: string;
+ policies: SystemRolePolicy[];
+ tags: SystemRoleTag[];
+};
+
+/** allow builds a resource-less `SystemRolePolicy`, correlating its action vocabulary to the resource kind. */
+const allow = <K extends SystemRolePolicy["resourceKind"]>(
+ resourceKind: K,
+ actions: Extract<SystemRolePolicy, { resourceKind: K }>["actions"],
+ effect: SystemRolePolicy["effect"] = "ALLOW",
+): SystemRolePolicy => ({ resourceKind, actions, effect }) as SystemRolePolicy;
+
+/** userRoleAccessRights builds a user role's org- and project-kind policies from the per-role access-right tables. */
+const userRoleAccessRights = (role: Role): SystemRolePolicy[] => [
+ allow("organization", organizationRoleAccessRights[role]),
+ allow("project", projectRoleAccessRights[role]),
+];
+
+/** orgKeyProjectActions are the project-kind actions an ORGANIZATION key holds against its own projects. */
+const orgKeyProjectActions: ProjectAction[] = [
+ "project:read",
+ "apiKeys:read",
+ "apiKeys:CUD",
+ "projectMembers:read",
+ "projectMembers:CUD",
+ "projectMembers:manageOwnership",
+ "project:update",
+ "project:delete",
+];
+
+/** projectKeyActions is the project vocabulary a PROJECT key holds, less the project-administration actions reserved for ORGANIZATION keys and the session user. */
+const projectKeyActions: ProjectAction[] = allProjectActions.filter(
+ (action) =>
+ action === "project:read" || !orgKeyProjectActions.includes(action),
+);
+
+/** systemRoleAccessRights maps each `SystemRole` to its rich definition; the resolver binds each policy to concrete org/project resources. */
+export const systemRoleAccessRights: Record<SystemRole, SystemRoleDefinition> =
+ {
+ OWNER: {
+ id: "OWNER",
+ name: "Owner",
+ description: "Full access, plus billing and account deletion.",
+ policies: userRoleAccessRights("OWNER"),
+ tags: ["principal:user"],
+ },
+ ADMIN: {
+ id: "ADMIN",
+ name: "Admin",
+ description: "All read and write privileges.",
+ policies: userRoleAccessRights("ADMIN"),
+ tags: ["principal:user", "principal:apiKey"],
+ },
+ MEMBER: {
+ id: "MEMBER",
+ name: "Member",
+ description: "Work within the organization and its projects.",
+ policies: userRoleAccessRights("MEMBER"),
+ tags: ["principal:user"],
+ },
+ VIEWER: {
+ id: "VIEWER",
+ name: "Viewer",
+ description: "Read-only privileges.",
+ policies: userRoleAccessRights("VIEWER"),
+ tags: ["principal:user", "principal:apiKey"],
+ },
+ NONE: {
+ id: "NONE",
+ name: "None",
+ description: "No organization or project access.",
+ policies: userRoleAccessRights("NONE"),
+ tags: ["principal:user"],
+ },
+ LEGACY_PROJECT_API_KEY: {
+ id: "LEGACY_PROJECT_API_KEY",
+ name: "Project API key",
+ description: "Read and write within a single project.",
+ policies: [allow("project", projectKeyActions)],
+ tags: ["principal:apiKey", "legacy"],
+ },
+ LEGACY_ORGANIZATION_API_KEY: {
+ id: "LEGACY_ORGANIZATION_API_KEY",
+ name: "Organization API key",
+ description: "Administer the organization and all of its projects.",
+ policies: [
+ allow("organization", allOrganizationActions),
+ allow("project", orgKeyProjectActions),
+ ],
+ tags: ["principal:apiKey", "legacy"],
+ },
+ INGEST: {
+ id: "INGEST",
+ name: "Ingestion",
+ description: "Create scores and traces from application telemetry.",
+ policies: [
+ allow("project", ["traces:create", "scores:save", "media:create"]),
+ ],
+ tags: ["principal:apiKey"],
+ },
+ SCORES_INGEST: {
+ id: "SCORES_INGEST",
+ name: "Scores ingestion",
+ description: "Submit scores from a web application.",
+ policies: [allow("project", ["scores:save"])],
+ tags: ["principal:apiKey"],
+ },
+ AI_GATEWAY: {
+ id: "AI_GATEWAY",
+ name: "AI Gateway",
+ description: "Route model requests through the AI Gateway.",
+ policies: [allow("organization", ["gateway:invoke"])],
+ tags: ["principal:apiKey"],
+ },
+ };
+
+/** roleHasProjectPolicy reports whether a role grants any project-kind policy. */
+export const roleHasProjectPolicy = (role: SystemRole): boolean =>
+ systemRoleAccessRights[role].policies.some(
+ (policy) => policy.resourceKind === "project",
+ );
+
+/** isApiKeyRole reports whether a role may back an api key at all, including legacy roles still valid on existing keys. */
+export const isApiKeyRole = (role: SystemRole): boolean =>
+ systemRoleAccessRights[role].tags.includes("principal:apiKey");
+
+/** isAssignableAtCreate reports whether a role is offered when creating a new api key: an api-key role that is not retired as legacy. */
+export const isAssignableAtCreate = (role: SystemRole): boolean =>
+ isApiKeyRole(role) && !systemRoleAccessRights[role].tags.includes("legacy");
+
+/** isLegacyApiKeyRole reports whether a role is a retired legacy api-key role. */
+export const isLegacyApiKeyRole = (role: SystemRole): boolean =>
+ isApiKeyRole(role) && systemRoleAccessRights[role].tags.includes("legacy");
+
+/** legacyApiKeyRoleForScope is the full-access role a scope's keys carried before per-key roles. */
+export const legacyApiKeyRoleForScope = (
+ scope: "project" | "organization",
+): SystemRole =>
+ scope === "project"
+ ? "LEGACY_PROJECT_API_KEY"
+ : "LEGACY_ORGANIZATION_API_KEY";
+
+/** apiKeyRolesAcceptedForScope is the roles a scope's create input accepts: the UI roles plus the scope's legacy role. */
+export const apiKeyRolesAcceptedForScope = (
+ scope: "project" | "organization",
+): SystemRole[] => [
+ ...apiKeyRolesForScope(scope),
+ legacyApiKeyRoleForScope(scope),
+];
+
+/** apiKeyRolesForScope lists, in catalog order, the roles offered when creating an api key at the given scope: project-capable roles for a project key, every creatable api-key role for an organization key. */
+export const apiKeyRolesForScope = (
+ scope: "project" | "organization",
+): SystemRole[] =>
+ (Object.keys(systemRoleAccessRights) as SystemRole[]).filter((role) =>
+ scope === "project"
+ ? isAssignableAtCreate(role) && roleHasProjectPolicy(role)
+ : isAssignableAtCreate(role),
+ );
diff --git a/packages/shared/src/features/rbac/types.ts b/packages/shared/src/features/rbac/types.ts
new file mode 100644
index 0000000000..eb2e8b0984
--- /dev/null
+++ b/packages/shared/src/features/rbac/types.ts
@@ -0,0 +1,83 @@
+import { type SystemRole } from "../../db";
+
+/** UserId is a user principal, tagged for disjoint principal ids. */
+export type UserId = `user/${string}`;
+export const UserId = (id: string): UserId => `user/${id}`;
+
+/** ApiKeyId is an api-key principal, tagged for disjoint principal ids. */
+export type ApiKeyId = `apiKey/${string}`;
+export const ApiKeyId = (id: string): ApiKeyId => `apiKey/${id}`;
+
+/** OrganizationId is an organization resource/owner/tenant, tagged. */
+export type OrganizationId = `organization/${string}`;
+export const OrganizationId = (id: string): OrganizationId =>
+ `organization/${id}`;
+
+/** ProjectId is a project resource/owner, tagged. */
+export type ProjectId = `project/${string}`;
+export const ProjectId = (id: string): ProjectId => `project/${id}`;
+
+/** SystemRoleId is an in-code role, tagged by its `SystemRole` enum member. */
+export type SystemRoleId = `system/${SystemRole}`;
+export const SystemRoleId = (role: SystemRole): SystemRoleId =>
+ `system/${role}`;
+
+/** CustomRoleId is a DB-stored role, tagged; custom-role storage is a later ticket. */
+export type CustomRoleId = `custom/${string}`;
+export const CustomRoleId = (id: string): CustomRoleId => `custom/${id}`;
+
+/** PrincipalId is who a role is assigned to. */
+export type PrincipalId = UserId | ApiKeyId;
+
+/** ResourceId is a thing access is checked against. */
+export type ResourceId = OrganizationId | ProjectId;
+
+/** OwnerId is the node a role assignment hangs off. */
+export type OwnerId = OrganizationId | ProjectId;
+
+/** TenantId scopes roles and assignments to one organization. */
+export type TenantId = OrganizationId;
+
+/** RoleId is either an in-code system role or a DB-stored custom role. */
+export type RoleId = SystemRoleId | CustomRoleId;
+
+/** untag strips the leading `kind/` prefix from a tagged id. */
+export const untag = (tagged: `${string}/${string}`): string =>
+ tagged.slice(tagged.indexOf("/") + 1);
+
+/** hasProjectKind narrows an owner/resource id to a project. */
+export const hasProjectKind = (id: OwnerId | ResourceId): id is ProjectId =>
+ id.startsWith("project/");
+
+/** hasApiKeyKind narrows a principal id to an api key. */
+export const hasApiKeyKind = (id: PrincipalId): id is ApiKeyId =>
+ id.startsWith("apiKey/");
+
+/** hasUserKind narrows a principal id to a user. */
+export const hasUserKind = (id: PrincipalId): id is UserId =>
+ id.startsWith("user/");
+
+/** hasOrganizationKind narrows an owner/resource id to an organization. */
+export const hasOrganizationKind = (
+ id: OwnerId | ResourceId,
+): id is OrganizationId => id.startsWith("organization/");
+
+/** hasSystemRoleKind narrows a role id to an in-code system role. */
+export const hasSystemRoleKind = (id: RoleId): id is SystemRoleId =>
+ id.startsWith("system/");
+
+/** toSystemRole maps a system role id to its `SystemRole` enum member. */
+export const toSystemRole = (id: SystemRoleId): SystemRole =>
+ untag(id) as SystemRole;
+
+/** RoleAssignment binds a role to a principal on an owner within a tenant. */
+export type RoleAssignment = {
+ id: string;
+ tenantId: TenantId;
+ ownerId: OwnerId;
+ roleId: RoleId;
+ principalId: PrincipalId;
+ tags: string[];
+ createdAt: Date;
+ updatedAt: Date;
+};
diff --git a/packages/shared/src/in-app-agent/server/mcpPolicy.ts b/packages/shared/src/in-app-agent/server/mcpPolicy.ts
index 946d86e444..204ffb507f 100644
--- a/packages/shared/src/in-app-agent/server/mcpPolicy.ts
+++ b/packages/shared/src/in-app-agent/server/mcpPolicy.ts
@@ -314,7 +314,7 @@ export const IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES = {
},
createScore: {
approval: "approval",
- availability: { scope: "scores:CUD" },
+ availability: { scope: "scores:save" },
},
listScoreConfigs: {
approval: "auto",
diff --git a/packages/shared/src/server/auth/apiKeyCache.ts b/packages/shared/src/server/auth/apiKeyCache.ts
index d5651e90dc..e5f69b2659 100644
--- a/packages/shared/src/server/auth/apiKeyCache.ts
+++ b/packages/shared/src/server/auth/apiKeyCache.ts
@@ -8,7 +8,10 @@ export const API_KEY_CACHE_PATTERN = createApiKeyCacheKey("*");
/** AUTHZ_CONTEXT_CACHE_KEY_PREFIX namespaces the policy-core context cache, disjoint from the legacy `api-key:` cache so both coexist in shadow mode. */
export const AUTHZ_CONTEXT_CACHE_KEY_PREFIX = "authz:context:";
-export const createAuthzContextCacheKey = (hash: string) =>
- `${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${hash}`;
+/** createAuthzContextCacheKey isolates credential presentations by schema version. */
+export const createAuthzContextCacheKey = (
+ kind: "basic" | "bearer",
+ hash: string,
+) => `${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}v2:${kind}:${hash}`;
-export const AUTHZ_CONTEXT_CACHE_PATTERN = createAuthzContextCacheKey("*");
+export const AUTHZ_CONTEXT_CACHE_PATTERN = `${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}*`;
diff --git a/packages/shared/src/server/auth/apiKeys.test.ts b/packages/shared/src/server/auth/apiKeys.test.ts
index d03c9150fa..c514182e52 100644
--- a/packages/shared/src/server/auth/apiKeys.test.ts
+++ b/packages/shared/src/server/auth/apiKeys.test.ts
@@ -1,8 +1,22 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+import { type Prisma } from "@prisma/client";
+import { InvalidRequestError } from "../../errors";
+
+// Give createApiKey a SALT without depending on the ambient env.
+vi.mock("../../env", () => ({ env: { SALT: "test-salt" } }));
+
import {
+ createApiKey,
formatSubmittedPublicKeyForLog,
redactLangfuseSecretKeys,
} from "./apiKeys";
+import {
+ ApiKeyId,
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "../../features/rbac/types";
const SECRET_KEY = "sk-lf-0f2a4c6e-8b1d-4e3f-9a7c-5d6e7f8a9b0c";
const PUBLIC_KEY = "pk-lf-1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d";
@@ -73,3 +87,177 @@ describe("formatSubmittedPublicKeyForLog", () => {
expect(formatSubmittedPublicKeyForLog(long)).toBe(`"${long.slice(0, 64)}"`);
});
});
+
+describe("createApiKey assignment rows", () => {
+ const KEY_ID = "key_abc";
+ const ORG_ID = "org_1";
+
+ // A transaction-client double that records the api-key create input and the
+ // assignment rows written and resolves a project's tenant, so the row-writing
+ // contract can be asserted without a live database. Lacking `$transaction`, it
+ // is treated as a joined transaction client, so createApiKey runs directly
+ // against it.
+ function makeTx() {
+ const assignments: Array<{
+ orgId: string;
+ principalApiKeyId: string;
+ ownerOrgId?: string;
+ ownerProjectId?: string;
+ systemRole: string;
+ }> = [];
+ let apiKeyData: Record<string, unknown> = {};
+ const tx = {
+ apiKey: {
+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
+ apiKeyData = data;
+ return {
+ id: KEY_ID,
+ createdAt: new Date(),
+ note: (data.note as string | null) ?? null,
+ publicKey: data.publicKey,
+ displaySecretKey: data.displaySecretKey,
+ };
+ }),
+ },
+ roleAssignment: {
+ create: vi.fn(
+ async ({ data }: { data: (typeof assignments)[number] }) => {
+ assignments.push(data);
+ return data;
+ },
+ ),
+ },
+ project: {
+ findFirstOrThrow: vi.fn(async () => ({ orgId: ORG_ID })),
+ },
+ };
+ return { tx, assignments, getApiKeyData: () => apiKeyData };
+ }
+
+ const asTx = (tx: ReturnType<typeof makeTx>["tx"]) =>
+ tx as unknown as Prisma.TransactionClient;
+
+ it("writes exactly one role@project row for a PROJECT-owner key", async () => {
+ const { tx, assignments, getApiKeyData } = makeTx();
+
+ await createApiKey(asTx(tx), {
+ owner: ProjectId("proj_1"),
+ role: SystemRoleId("VIEWER"),
+ createdBy: UserId("user_1"),
+ name: "project key",
+ });
+
+ expect(assignments).toEqual([
+ {
+ orgId: ORG_ID,
+ principalApiKeyId: KEY_ID,
+ ownerProjectId: "proj_1",
+ systemRole: "VIEWER",
+ },
+ ]);
+ const data = getApiKeyData();
+ expect(data.projectId).toBe("proj_1");
+ expect(data.orgId).toBeUndefined();
+ expect(data.note).toBe("project key");
+ expect(data.createdByUserId).toBe("user_1");
+ expect(data.createdByApiKeyId).toBeUndefined();
+ });
+
+ it("writes exactly one role@organization row for an ORGANIZATION-owner key", async () => {
+ const { tx, assignments, getApiKeyData } = makeTx();
+
+ await createApiKey(asTx(tx), {
+ owner: OrganizationId(ORG_ID),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: ApiKeyId("key_creator"),
+ name: "org key",
+ });
+
+ expect(assignments).toEqual([
+ {
+ orgId: ORG_ID,
+ principalApiKeyId: KEY_ID,
+ ownerOrgId: ORG_ID,
+ systemRole: "LEGACY_ORGANIZATION_API_KEY",
+ },
+ ]);
+ const data = getApiKeyData();
+ expect(data.orgId).toBe(ORG_ID);
+ expect(data.projectId).toBeUndefined();
+ expect(data.createdByApiKeyId).toBe("key_creator");
+ expect(data.createdByUserId).toBeUndefined();
+ // An organization owner resolves to itself; no project lookup is needed.
+ expect(tx.project.findFirstOrThrow).not.toHaveBeenCalled();
+ });
+
+ it.each(["legacy name", ""])(
+ "accepts the deprecated note alias %j",
+ async (note) => {
+ const { tx, getApiKeyData } = makeTx();
+
+ const result = await createApiKey(asTx(tx), {
+ owner: OrganizationId(ORG_ID),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: "system",
+ note,
+ });
+
+ expect(getApiKeyData().note).toBe(note);
+ expect(result.note).toBe(note);
+ },
+ );
+
+ it.each([
+ { name: "same", note: "same" },
+ { name: "", note: "" },
+ { name: "", note: "alias" },
+ { name: "name", note: "" },
+ ])(
+ "rejects conflicting name and note inputs %j before writing",
+ async (input) => {
+ const { tx } = makeTx();
+
+ await expect(
+ createApiKey(asTx(tx), {
+ owner: OrganizationId(ORG_ID),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: "system",
+ ...input,
+ }),
+ ).rejects.toThrow(InvalidRequestError);
+ expect(tx.apiKey.create).not.toHaveBeenCalled();
+ expect(tx.roleAssignment.create).not.toHaveBeenCalled();
+ },
+ );
+
+ // createApiKey always enforces that the role can back a key: a user-only
+ // role is rejected outright, and a project owner needs a project-capable
+ // role. Legacy api-key roles remain valid.
+ describe("role validation", () => {
+ it("rejects a user-only role that cannot back an api key", async () => {
+ const { tx, assignments } = makeTx();
+
+ await expect(
+ createApiKey(asTx(tx), {
+ owner: OrganizationId(ORG_ID),
+ role: SystemRoleId("OWNER"),
+ createdBy: UserId("user_1"),
+ }),
+ ).rejects.toThrow(/cannot back an organization API key/);
+ expect(assignments).toEqual([]);
+ });
+
+ it("rejects an org-only role on a project owner", async () => {
+ const { tx, assignments } = makeTx();
+
+ await expect(
+ createApiKey(asTx(tx), {
+ owner: ProjectId("proj_1"),
+ role: SystemRoleId("AI_GATEWAY"),
+ createdBy: UserId("user_1"),
+ }),
+ ).rejects.toThrow(/cannot back a project API key/);
+ expect(assignments).toEqual([]);
+ });
+ });
+});
diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.ts
index f0489d9a71..8f027c4e77 100644
--- a/packages/shared/src/server/auth/apiKeys.ts
+++ b/packages/shared/src/server/auth/apiKeys.ts
@@ -4,8 +4,28 @@ import { randomUUID } from "crypto";
import * as crypto from "crypto";
import type { Cluster, Redis } from "ioredis";
import { env } from "../../env";
+import { InvalidRequestError } from "../../errors";
+import {
+ ApiKeyId,
+ OrganizationId,
+ hasApiKeyKind,
+ hasOrganizationKind,
+ hasProjectKind,
+ hasSystemRoleKind,
+ toSystemRole,
+ untag,
+ type OwnerId,
+ type RoleId,
+ type UserId,
+} from "../../features/rbac/types";
+import {
+ isApiKeyRole,
+ roleHasProjectPolicy,
+} from "../../features/rbac/systemRoleAccessRights";
import { logger } from "../logger";
+import { assignRole } from "../../features/rbac/roleAssignmentRepository";
import { invalidateCachedApiKeys } from "./invalidateApiKeys";
+import { withTransaction } from "../utils/withTransaction";
export function getDisplaySecretKey(secretKey: string) {
return secretKey.slice(0, 6) + "..." + secretKey.slice(-4);
@@ -26,24 +46,7 @@ export function redactLangfuseSecretKeys(value: string): string {
const MAX_LOGGED_PUBLIC_KEY_LENGTH = 64;
-/**
- * Formats a client-submitted public key for logging. Only a value that is
- * actually a Langfuse public key is echoed; anything else is masked to its
- * display form because it may be a secret placed in the wrong slot.
- *
- * The value reaches us straight from a client-controlled Authorization header,
- * and the callers that log it are the ones where the key was not found, so it
- * may be arbitrary bytes of arbitrary length. Log formatters interpolate a
- * message verbatim, so echoing the value as-is would let a caller forge log
- * lines with a newline, or drive an operator's terminal with an escape
- * sequence (CWE-117).
- *
- * A real public key is printable ASCII (`pk-lf-` plus a UUID), so allow-list
- * that range rather than enumerating the dangerous one: a single rule covers C0
- * controls, DEL and the C1 range, which `JSON.stringify` leaves unescaped.
- * `JSON.stringify` then quotes the result, delimiting it within the log line
- * and escaping any embedded quote or backslash.
- */
+/** formatSubmittedPublicKeyForLog masks values without a pk-lf- prefix and sanitizes untrusted input for logging. */
export function formatSubmittedPublicKeyForLog(value: string): string {
let formatted: string;
if (value.startsWith("pk-lf-")) formatted = value;
@@ -85,62 +88,126 @@ export function createShaHash(privateKey: string, salt: string): string {
return hash;
}
-export async function createAndAddApiKeysToDb(p: {
- // Accepts a transaction client so callers can commit key creation
- // atomically with linking the key to its owner (e.g. an agent run row).
- prisma: PrismaClient | Prisma.TransactionClient;
- entityId: string;
- scope: ApiKeyScope;
- note?: string;
- isInAppAgentKey?: boolean;
- /** User who created the key, e.g. via the UI. */
- createdByUserId?: string;
- /** API key that created the key, e.g. an org-scoped key using the public API. */
- createdByApiKeyId?: string;
- predefinedKeys?: {
- secretKey: string;
- publicKey: string;
- };
-}) {
+/** createApiKey inserts an api-key row and its single system-role assignment, keyed on the owner. */
+export async function createApiKey(
+ prisma: PrismaClient | Prisma.TransactionClient,
+ {
+ name,
+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Accept the legacy alias at the compatibility boundary.
+ note,
+ ...opts
+ }: {
+ owner: OwnerId;
+ role: RoleId;
+ createdBy: ApiKeyId | UserId | "system";
+ name?: string;
+ /** @deprecated Use name instead; name and note are mutually exclusive. */
+ note?: string;
+ expiresAt?: Date | null;
+ isInAppAgentKey?: boolean;
+ predefinedKeys?: { secretKey: string; publicKey: string };
+ },
+): Promise<{
+ id: string;
+ createdAt: Date;
+ note: string | null;
+ publicKey: string;
+ displaySecretKey: string;
+ secretKey: string;
+}> {
+ if (name !== undefined && note !== undefined) {
+ throw new InvalidRequestError("Provide either name or note, not both");
+ }
+
const salt = env.SALT;
if (!salt) {
throw new Error("SALT is not set");
}
- const { pk, sk } = p.predefinedKeys
- ? { pk: p.predefinedKeys.publicKey, sk: p.predefinedKeys.secretKey }
+ if (hasSystemRoleKind(opts.role)) {
+ const role = toSystemRole(opts.role);
+ const isProjectOwner = hasProjectKind(opts.owner);
+ // A key can only carry a role tagged for api keys; a project owner also
+ // needs a project-kind policy, or the key grants nothing on its project.
+ if (
+ !isApiKeyRole(role) ||
+ (isProjectOwner && !roleHasProjectPolicy(role))
+ ) {
+ throw new InvalidRequestError(
+ `Role ${role} cannot back ${
+ isProjectOwner ? "a project" : "an organization"
+ } API key`,
+ );
+ }
+ }
+
+ const { pk, sk } = opts.predefinedKeys
+ ? { pk: opts.predefinedKeys.publicKey, sk: opts.predefinedKeys.secretKey }
: await generateKeySet();
- const hashedSk = await hashSecretKey(sk);
- const displaySk = getDisplaySecretKey(sk);
+ const scope = hasOrganizationKind(opts.owner) ? "ORGANIZATION" : "PROJECT";
+ const data: Prisma.ApiKeyUncheckedCreateInput = {
+ ...(scope === "ORGANIZATION"
+ ? { orgId: untag(opts.owner) }
+ : { projectId: untag(opts.owner) }),
+ publicKey: pk,
+ hashedSecretKey: await hashSecretKey(sk),
+ displaySecretKey: getDisplaySecretKey(sk),
+ fastHashedSecretKey: createShaHash(sk, salt),
+ note: name ?? note,
+ scope,
+ expiresAt: opts.expiresAt ?? null,
+ isInAppAgentKey: opts.isInAppAgentKey ?? false,
+ ...creatorColumns(opts.createdBy),
+ };
- const hashFromProvidedKey = createShaHash(sk, salt);
+ const created = await withTransaction(prisma, (tx) =>
+ insertApiKey(tx, data, opts),
+ );
+ return { ...created, secretKey: sk };
+}
- const entity =
- p.scope === "PROJECT" ? { projectId: p.entityId } : { orgId: p.entityId };
+/** creatorColumns maps a key's creator to its api-key columns; "system" records none. */
+function creatorColumns(
+ createdBy: ApiKeyId | UserId | "system",
+): Pick<
+ Prisma.ApiKeyUncheckedCreateInput,
+ "createdByApiKeyId" | "createdByUserId"
+> {
+ if (createdBy === "system") return {};
+ return hasApiKeyKind(createdBy)
+ ? { createdByApiKeyId: untag(createdBy) }
+ : { createdByUserId: untag(createdBy) };
+}
- const apiKey = await p.prisma.apiKey.create({
- data: {
- ...entity,
- publicKey: pk,
- hashedSecretKey: hashedSk,
- displaySecretKey: displaySk,
- fastHashedSecretKey: hashFromProvidedKey,
- note: p.note,
- scope: p.scope,
- isInAppAgentKey: p.isInAppAgentKey ?? false,
- createdByUserId: p.createdByUserId,
- createdByApiKeyId: p.createdByApiKeyId,
- },
+/** insertApiKey writes the api-key row and its one owner-keyed role assignment on a single transaction client. */
+async function insertApiKey(
+ tx: Prisma.TransactionClient,
+ data: Prisma.ApiKeyUncheckedCreateInput,
+ opts: { owner: OwnerId; role: RoleId },
+) {
+ const apiKey = await tx.apiKey.create({ data });
+ const orgId = hasOrganizationKind(opts.owner)
+ ? untag(opts.owner)
+ : (
+ await tx.project.findFirstOrThrow({
+ where: { id: untag(opts.owner) },
+ select: { orgId: true },
+ })
+ ).orgId;
+ await assignRole(tx, {
+ tenantId: OrganizationId(orgId),
+ principalId: ApiKeyId(apiKey.id),
+ roleId: opts.role,
+ ownerId: opts.owner,
+ tags: [],
});
-
return {
id: apiKey.id,
createdAt: apiKey.createdAt,
note: apiKey.note,
publicKey: apiKey.publicKey,
- secretKey: sk,
- displaySecretKey: displaySk,
+ displaySecretKey: apiKey.displaySecretKey,
};
}
diff --git a/packages/shared/src/server/auth/invalidateApiKeys.ts b/packages/shared/src/server/auth/invalidateApiKeys.ts
index 592a6c8cff..3f40fcb7c3 100644
--- a/packages/shared/src/server/auth/invalidateApiKeys.ts
+++ b/packages/shared/src/server/auth/invalidateApiKeys.ts
@@ -8,47 +8,33 @@ import { type ApiKey } from "../../db";
import {
API_KEY_CACHE_PATTERN,
AUTHZ_CONTEXT_CACHE_PATTERN,
+ AUTHZ_CONTEXT_CACHE_KEY_PREFIX,
createApiKeyCacheKey,
createAuthzContextCacheKey,
} from "./apiKeyCache";
import { createShaHash } from "./apiKeys";
-/**
- * Redis keys to delete per API key row, across both cache namespaces:
- * legacy `api-key:<fastHash>` plus the policy-core `authz:context:` keys for
- * every presentation of the key — `sha(secret+salt)` (== fastHash) and
- * `sha(publicKey+salt)`. Public-key rows are covered even without a fast hash.
- */
+/** cacheKeysForRows includes legacy and versioned credential entries. */
function cacheKeysForRows(apiKeys: ApiKey[]): string[] {
const salt = env.SALT;
const keys: string[] = [];
for (const key of apiKeys) {
if (key.fastHashedSecretKey) {
keys.push(createApiKeyCacheKey(key.fastHashedSecretKey));
- keys.push(createAuthzContextCacheKey(key.fastHashedSecretKey));
+ keys.push(`${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${key.fastHashedSecretKey}`);
+ keys.push(createAuthzContextCacheKey("basic", key.fastHashedSecretKey));
+ keys.push(createAuthzContextCacheKey("bearer", key.fastHashedSecretKey));
}
if (salt && key.publicKey) {
- keys.push(createAuthzContextCacheKey(createShaHash(key.publicKey, salt)));
+ const publicHash = createShaHash(key.publicKey, salt);
+ keys.push(`${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${publicHash}`);
+ keys.push(createAuthzContextCacheKey("bearer", publicHash));
}
}
return keys;
}
-/**
- * Invalidate cached API keys from Redis cache
- *
- * Utility used by higher-level helpers to remove individual API keys from the cache,
- * e.g. after key rotation, revocation, or entitlement/plan changes.
- *
- * Note: This only invalidates the Redis cache, not the API keys themselves in the database.
- *
- * Behavior:
- * - Skips keys without a `fastHashedSecretKey`
- * - No-ops when Redis is not configured
- *
- * @param apiKeys - List of API key records to invalidate from cache
- * @param identifier - Context string for logging (e.g., org or project identifier)
- */
+/** invalidateCachedApiKeys removes every cached credential presentation. */
export async function invalidateCachedApiKeys(
apiKeys: ApiKey[],
identifier: string,
diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.ts
index ce03f967fb..e5d81fb530 100644
--- a/packages/shared/src/server/ingestion/processEventBatch.ts
+++ b/packages/shared/src/server/ingestion/processEventBatch.ts
@@ -8,7 +8,7 @@ import {
LangfuseNotFoundError,
UnauthorizedError,
} from "../../errors";
-import { AuthHeaderValidVerificationResultIngestion } from "../auth/types";
+import { type AuthHeaderValidVerificationResultIngestion } from "../auth/types";
import {
getClickhouseEntityType,
type IngestionEntityTypes,
@@ -97,12 +97,7 @@ type ProcessEventBatchOptions = {
attribution: IngestionAttribution;
};
-/**
- * Processes a batch of events.
- * @param input - Batch of IngestionEventType. Will validate the types first thing and return errors if they are invalid.
- * @param authCheck - AuthHeaderValidVerificationResultIngestion
- * @param options - (Optional) Options for the event batch processing.
- */
+/** processEventBatch validates and queues authorized ingestion events, returning per-event results. */
export const processEventBatch = async (
input: unknown[],
authCheck: AuthHeaderValidVerificationResultIngestion,
@@ -152,7 +147,6 @@ export const processEventBatch = async (
}
const validationErrors: { id: string; error: unknown }[] = [];
- const authenticationErrors: { id: string; error: unknown }[] = [];
const ingestionSchema = createIngestionEventSchema(isLangfuseInternal);
const batch: z.infer<typeof ingestionSchema>[] = input
@@ -170,13 +164,6 @@ export const processEventBatch = async (
});
return [];
}
- if (!isAuthorized(parsed.data, authCheck)) {
- authenticationErrors.push({
- id: parsed.data.id,
- error: new UnauthorizedError("Access Scope Denied"),
- });
- return [];
- }
return [parsed.data];
})
.flatMap((event) => {
@@ -401,30 +388,12 @@ export const processEventBatch = async (
);
return aggregateBatchResult(
- [...validationErrors, ...authenticationErrors],
+ validationErrors,
sortedBatch.map((event) => ({ id: event.id, result: event })),
authCheck.scope.projectId,
);
};
-const isAuthorized = (
- event: IngestionEventType,
- authScope: AuthHeaderValidVerificationResultIngestion,
-): boolean => {
- if (event.type === eventTypes.SDK_LOG) {
- return true;
- }
-
- if (event.type === eventTypes.SCORE_CREATE) {
- return (
- authScope.scope.accessLevel === "scores" ||
- authScope.scope.accessLevel === "project"
- );
- }
-
- return authScope.scope.accessLevel === "project";
-};
-
/**
* Sorts a batch of ingestion events. Orders by: updating events last, sorted by timestamp asc.
*/
diff --git a/packages/shared/src/server/test-utils/org-factory.ts b/packages/shared/src/server/test-utils/org-factory.ts
index cc1e1ac0b3..b30b2f13db 100644
--- a/packages/shared/src/server/test-utils/org-factory.ts
+++ b/packages/shared/src/server/test-utils/org-factory.ts
@@ -1,7 +1,14 @@
import { v4 } from "uuid";
import { prisma } from "../../db";
import { env } from "../../env";
+import {
+ ApiKeyId,
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+} from "../../features/rbac/types";
import { CloudConfigSchema } from "../../interfaces/cloudConfigSchema";
+import { assignRole } from "../../features/rbac/roleAssignmentRepository";
import { createShaHash, getDisplaySecretKey } from "../auth/apiKeys";
export function createBasicAuthHeader(
@@ -47,19 +54,31 @@ export const createOrgProjectAndApiKey = async (
}
const auth = createBasicAuthHeader(publicKey, secretKey);
- await prisma.apiKey.create({
- data: {
- id: v4(),
- projectId: projectId,
- publicKey: publicKey,
- // Test fixtures use the modern fast-hash auth path. Avoid bcrypt here as
- // cost-11 hashing adds ~100ms per fixture; keep the legacy hash unique to
- // satisfy the database constraint without affecting authentication.
- hashedSecretKey: `test-hashed-secret-key-${v4()}`,
- fastHashedSecretKey: createShaHash(secretKey, salt),
- displaySecretKey: getDisplaySecretKey(secretKey),
- scope: "PROJECT",
- },
+ const apiKeyRowId = v4();
+ await prisma.$transaction(async (tx) => {
+ await tx.apiKey.create({
+ data: {
+ id: apiKeyRowId,
+ projectId: projectId,
+ publicKey: publicKey,
+ // Test fixtures use the modern fast-hash auth path. Avoid bcrypt here as
+ // cost-11 hashing adds ~100ms per fixture; keep the legacy hash unique to
+ // satisfy the database constraint without affecting authentication.
+ hashedSecretKey: `test-hashed-secret-key-${v4()}`,
+ fastHashedSecretKey: createShaHash(secretKey, salt),
+ displaySecretKey: getDisplaySecretKey(secretKey),
+ scope: "PROJECT",
+ },
+ });
+
+ // Give the fixture key its legacy project permissions.
+ await assignRole(tx, {
+ tenantId: OrganizationId(org.id),
+ principalId: ApiKeyId(apiKeyRowId),
+ roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ ownerId: ProjectId(projectId),
+ tags: [],
+ });
});
return { projectId, orgId: org.id, publicKey, secretKey, auth, org, project };
diff --git a/packages/shared/src/server/utils/withTransaction.ts b/packages/shared/src/server/utils/withTransaction.ts
new file mode 100644
index 0000000000..e7b73c65a5
--- /dev/null
+++ b/packages/shared/src/server/utils/withTransaction.ts
@@ -0,0 +1,9 @@
+import { type Prisma, type PrismaClient } from "@prisma/client";
+
+/** withTransaction joins an existing transaction or opens one. */
+export async function withTransaction<T>(
+ client: PrismaClient | Prisma.TransactionClient,
+ fn: (tx: Prisma.TransactionClient) => Promise<T>,
+): Promise<T> {
+ return "$transaction" in client ? client.$transaction(fn) : fn(client);
+}
diff --git a/web/.storybook/main.ts b/web/.storybook/main.ts
index 81be8aa3e6..f9eeb5c48a 100644
--- a/web/.storybook/main.ts
+++ b/web/.storybook/main.ts
@@ -179,6 +179,13 @@ const config: StorybookConfig = {
find: /^@langfuse\/shared\/query$/,
replacement: `${sharedSrc}/features/query`,
},
+ // Client-safe role catalog, imported by the RBAC role-select UI and its
+ // stories. No `/rbac/server` rule: a story pulling server-only code
+ // should fail the build, not silently resolve.
+ {
+ find: /^@langfuse\/shared\/rbac$/,
+ replacement: `${sharedSrc}/features/rbac`,
+ },
// Client-safe entry of the in-app-agent module (imported by the agent
// window components and their stories). Deliberately no rule for the
// `/server` subpaths: a story that pulls server code should fail the
diff --git a/web/AGENTS.md b/web/AGENTS.md
index 547be27ca6..feebcac26c 100644
--- a/web/AGENTS.md
+++ b/web/AGENTS.md
@@ -128,9 +128,11 @@ Sentry instrumentation skill first and decide whether it should capture at all
components under `src/components/*`.
- We use tRPC for full-stack web features; register routers in
`src/server/api/root.ts`.
-- RBAC lives in `src/features/rbac`: role definitions in
- `src/features/rbac/constants`, access checks in
- `src/features/rbac/utils/checkProjectAccess.ts` and
+- RBAC lives in `src/features/rbac`: the role catalog (definitions, policies,
+ tags, access-right tables, and helpers) lives in `@langfuse/shared/rbac`;
+ assignment reads and writes live in `@langfuse/shared/rbac/server`;
+ web owns policy resolution/evaluation (`getRolesForPrincipal`, `authorize`)
+ and the access checks in `src/features/rbac/utils/checkProjectAccess.ts` and
`src/features/rbac/utils/checkOrganizationAccess.ts`.
- Entitlements guidance lives in `src/features/entitlements/README.md`.
- Prefer Shadcn/ui primitives from `src/components/ui`; if a missing component
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 8a4835c3c9..e92700f20c 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -5546,10 +5546,27 @@ paths:
schema:
type: object
properties:
+ name:
+ type: string
+ nullable: true
+ description: >-
+ Optional name for the API key. Cannot be provided together
+ with note, even if either value is an empty string.
note:
type: string
nullable: true
- description: Optional note for the API key
+ description: >-
+ Deprecated alias for name. Cannot be provided together with
+ name, even if either value is an empty string.
+ deprecated: true
+ expiresAt:
+ type: string
+ format: date-time
+ nullable: true
+ description: >-
+ Optional expiration timestamp in ISO 8601 format. Must be in
+ the future. Omit or set to null for a key that does not
+ expire.
publicKey:
type: string
nullable: true
@@ -6282,6 +6299,7 @@ paths:
disabled). No credential is created for the user;
provisioned users authenticate via SSO or set a password
themselves through the password reset flow.
+ deprecated: true
required:
- userName
- name
@@ -15647,13 +15665,22 @@ components:
type: string
format: date-time
nullable: true
+ description: Expiration timestamp. Null if the key does not expire.
lastUsedAt:
type: string
format: date-time
nullable: true
+ name:
+ type: string
+ nullable: true
+ description: >-
+ Name of the API key. Contains the same value as note; null if no
+ name was provided.
note:
type: string
nullable: true
+ description: Deprecated alias for name. Contains the same value as name.
+ deprecated: true
publicKey:
type: string
displaySecretKey:
@@ -15758,13 +15785,22 @@ components:
type: string
format: date-time
nullable: true
+ description: Expiration timestamp. Null if the key does not expire.
lastUsedAt:
type: string
format: date-time
nullable: true
+ name:
+ type: string
+ nullable: true
+ description: >-
+ Name of the API key. Contains the same value as note; null if no
+ name was provided.
note:
type: string
nullable: true
+ description: Deprecated alias for name. Contains the same value as name.
+ deprecated: true
publicKey:
type: string
displaySecretKey:
@@ -15784,15 +15820,28 @@ components:
createdAt:
type: string
format: date-time
+ expiresAt:
+ type: string
+ format: date-time
+ nullable: true
+ description: Expiration timestamp. Null if the key does not expire.
publicKey:
type: string
secretKey:
type: string
displaySecretKey:
type: string
+ name:
+ type: string
+ nullable: true
+ description: >-
+ Name of the API key. Contains the same value as note; null if no
+ name was provided.
note:
type: string
nullable: true
+ description: Deprecated alias for name. Contains the same value as name.
+ deprecated: true
required:
- id
- createdAt
diff --git a/web/public/generated/organizations-api/openapi.yml b/web/public/generated/organizations-api/openapi.yml
index b4d12af939..f166f48d79 100644
--- a/web/public/generated/organizations-api/openapi.yml
+++ b/web/public/generated/organizations-api/openapi.yml
@@ -370,10 +370,27 @@ paths:
schema:
type: object
properties:
+ name:
+ type: string
+ nullable: true
+ description: >-
+ Optional name for the API key. Cannot be provided together
+ with note, even if either value is an empty string.
note:
type: string
nullable: true
- description: Optional note for the API key
+ description: >-
+ Deprecated alias for name. Cannot be provided together with
+ name, even if either value is an empty string.
+ deprecated: true
+ expiresAt:
+ type: string
+ format: date-time
+ nullable: true
+ description: >-
+ Optional expiration timestamp in ISO 8601 format. Must be in
+ the future. Omit or set to null for a key that does not
+ expire.
/api/admin/organizations/{organizationId}/apiKeys/{apiKeyId}:
delete:
description: Delete an API key for an organization
@@ -521,13 +538,22 @@ components:
type: string
format: date-time
nullable: true
+ description: Expiration timestamp. Null if the key does not expire.
lastUsedAt:
type: string
format: date-time
nullable: true
+ name:
+ type: string
+ nullable: true
+ description: >-
+ Name of the API key. Contains the same value as note; null if no
+ name was provided.
note:
type: string
nullable: true
+ description: Deprecated alias for name. Contains the same value as name.
+ deprecated: true
publicKey:
type: string
displaySecretKey:
@@ -547,15 +573,28 @@ components:
createdAt:
type: string
format: date-time
+ expiresAt:
+ type: string
+ format: date-time
+ nullable: true
+ description: Expiration timestamp. Null if the key does not expire.
publicKey:
type: string
secretKey:
type: string
displaySecretKey:
type: string
+ name:
+ type: string
+ nullable: true
+ description: >-
+ Name of the API key. Contains the same value as note; null if no
+ name was provided.
note:
type: string
nullable: true
+ description: Deprecated alias for name. Contains the same value as name.
+ deprecated: true
required:
- id
- createdAt
diff --git a/web/scripts/openapi/fern-deprecations.ts b/web/scripts/openapi/fern-deprecations.ts
index fb6cb59a2d..36192ca3c0 100644
--- a/web/scripts/openapi/fern-deprecations.ts
+++ b/web/scripts/openapi/fern-deprecations.ts
@@ -11,6 +11,7 @@ type FernAvailability =
type FernDefinition = {
"base-path"?: string;
+ types?: Record<string, string | { properties?: FernProperties }>;
service?: {
"base-path"?: string;
endpoints?: Record<
@@ -20,6 +21,7 @@ type FernDefinition = {
"base-path"?: string;
method?: string;
path?: string;
+ request?: string | { body?: string | { properties?: FernProperties } };
}
>;
};
@@ -113,3 +115,65 @@ export function getFernDeprecatedOperations(
});
});
}
+
+/** getFernDeprecatedProperties locates named-type and inline-request properties in the exported schema. */
+export function getFernDeprecatedProperties(
+ definitionDirectory: string,
+): string[][] {
+ const apiDefinition = parse(
+ fs.readFileSync(path.join(definitionDirectory, "api.yml"), "utf8"),
+ ) as FernDefinition;
+
+ return listYamlFiles(definitionDirectory).flatMap((definitionPath) => {
+ const definition = parse(
+ fs.readFileSync(definitionPath, "utf8"),
+ ) as FernDefinition;
+ const typeProperties = Object.entries(definition.types ?? {}).flatMap(
+ ([name, type]) =>
+ deprecatedPropertyPaths(
+ typeof type === "string" ? undefined : type.properties,
+ ["components", "schemas", name, "properties"],
+ ),
+ );
+ const service = definition.service;
+ const requestProperties = Object.values(service?.endpoints ?? {}).flatMap(
+ (endpoint) => {
+ const request = endpoint.request;
+ const body = typeof request === "object" ? request.body : undefined;
+ if (typeof body !== "object" || !endpoint.method) return [];
+ return deprecatedPropertyPaths(body.properties, [
+ "paths",
+ joinApiPath(
+ apiDefinition["base-path"],
+ service?.["base-path"],
+ endpoint["base-path"],
+ endpoint.path,
+ ),
+ endpoint.method.toLowerCase(),
+ "requestBody",
+ "content",
+ "application/json",
+ "schema",
+ "properties",
+ ]);
+ },
+ );
+ return [...typeProperties, ...requestProperties];
+ });
+}
+
+function deprecatedPropertyPaths(
+ properties: FernProperties | undefined,
+ prefix: string[],
+): string[][] {
+ return Object.entries(properties ?? {}).flatMap(([name, property]) =>
+ typeof property === "object" && isDeprecated(property.availability)
+ ? [[...prefix, name]]
+ : [],
+ );
+}
+
+type FernProperties = Record<
+ string,
+ string | { availability?: FernAvailability }
+>;
diff --git a/web/scripts/openapi/postprocess-openapi.ts b/web/scripts/openapi/postprocess-openapi.ts
index f98a420b91..56fb5d5b39 100644
--- a/web/scripts/openapi/postprocess-openapi.ts
+++ b/web/scripts/openapi/postprocess-openapi.ts
@@ -1,23 +1,35 @@
import fs from "node:fs";
import path from "node:path";
-import { getFernDeprecatedOperations } from "./fern-deprecations";
+import {
+ getFernDeprecatedOperations,
+ getFernDeprecatedProperties,
+} from "./fern-deprecations";
import { stampDeprecations } from "./stamp-deprecations";
import { stampUnionVariantTitles } from "./stamp-union-variant-titles";
const webDirectory = process.cwd();
+const api = process.argv[2] ?? "server";
+if (api !== "server" && api !== "organizations") {
+ throw new Error(`Unsupported API: ${api}`);
+}
const definitionDirectory = path.resolve(
webDirectory,
- "../fern/apis/server/definition",
+ `../fern/apis/${api}/definition`,
);
const openApiPath = path.resolve(
webDirectory,
- "public/generated/api/openapi.yml",
+ `public/generated/${api === "server" ? "api" : "organizations-api"}/openapi.yml`,
);
const deprecatedOperations = getFernDeprecatedOperations(definitionDirectory);
+const deprecatedProperties = getFernDeprecatedProperties(definitionDirectory);
const openApiSource = fs.readFileSync(openApiPath, "utf8");
-const deprecatedSource = stampDeprecations(openApiSource, deprecatedOperations);
+const deprecatedSource = stampDeprecations(
+ openApiSource,
+ deprecatedOperations,
+ deprecatedProperties,
+);
const { source: syncedSource, stamped } =
stampUnionVariantTitles(deprecatedSource);
@@ -26,4 +38,7 @@ if (syncedSource !== openApiSource) fs.writeFileSync(openApiPath, syncedSource);
console.log(
`Synced ${deprecatedOperations.length} deprecated OpenAPI operations from Fern definitions.`,
);
+console.log(
+ `Synced ${deprecatedProperties.length} deprecated OpenAPI properties from Fern definitions.`,
+);
console.log(`Titled ${stamped} anonymous OpenAPI union variants for Scalar.`);
diff --git a/web/scripts/openapi/stamp-deprecations.ts b/web/scripts/openapi/stamp-deprecations.ts
index fc8b8fb138..0f017f9555 100644
--- a/web/scripts/openapi/stamp-deprecations.ts
+++ b/web/scripts/openapi/stamp-deprecations.ts
@@ -53,17 +53,11 @@ function descriptionScalar(
return scalar;
}
-/**
- * Writes the standard OpenAPI `deprecated` flag and a `**Deprecated:** …`
- * notice onto every operation Fern marks deprecated.
- *
- * Printing the parsed document reflows a handful of long descriptions the
- * exporter had folded differently, which is why the result is checked against
- * the expected document: formatting may move, meaning may not.
- */
+/** stampDeprecations marks deprecated operations and properties, adding notices to operations. */
export function stampDeprecations(
source: string,
operations: DeprecatedOperation[],
+ properties: string[][] = [],
): string {
const document = parseDocument(source);
if (document.errors.length > 0) {
@@ -112,8 +106,23 @@ export function stampDeprecations(
target.description = description;
}
+ for (const propertyPath of properties) {
+ const property = document.getIn(propertyPath, true);
+ if (!isMap(property)) {
+ throw new Error(
+ `OpenAPI schema does not contain property ${propertyPath.join("/")}`,
+ );
+ }
+ property.set("deprecated", true);
+ const expectedProperty = propertyPath.reduce<Record<string, unknown>>(
+ (node, key) => node[key] as Record<string, unknown>,
+ expected as unknown as Record<string, unknown>,
+ );
+ expectedProperty.deprecated = true;
+ }
+
const text = document.toString({ lineWidth: LINE_WIDTH });
- // Nothing may change beyond the two fields on the operations we touched.
+ // Only targeted deprecation metadata may change.
assert.deepStrictEqual(parse(text, RESOLVE_OPTIONS), expected);
return text;
diff --git a/web/scripts/typescript-sdk/patch-generated-deprecations.ts b/web/scripts/typescript-sdk/patch-generated-deprecations.ts
index 0c5f837320..3a8be8d09b 100644
--- a/web/scripts/typescript-sdk/patch-generated-deprecations.ts
+++ b/web/scripts/typescript-sdk/patch-generated-deprecations.ts
@@ -26,6 +26,10 @@ type FernEndpoint = {
};
type FernDefinition = {
+ types?: Record<
+ string,
+ string | { properties?: Record<string, FernProperty> }
+ >;
service?: {
endpoints?: Record<string, FernEndpoint>;
};
@@ -161,6 +165,7 @@ function propertyGeneratedPath(resourceRoot: string, typeName: string): string {
return path.join(resourceRoot, "client", "requests", `${typeName}.ts`);
}
+/** getFernTypeScriptDeprecations maps Fern metadata to generated SDK declarations. */
export function getFernTypeScriptDeprecations(
definitionDirectory: string,
): FernTypeScriptDeprecation[] {
@@ -241,6 +246,37 @@ export function getFernTypeScriptDeprecations(
}
}
+ for (const [typeName, definitionType] of Object.entries(
+ definition.types ?? {},
+ )) {
+ if (typeof definitionType === "string") continue;
+ for (const [propertyName, property] of Object.entries(
+ definitionType.properties ?? {},
+ )) {
+ if (!isDeprecated(property.availability)) continue;
+ handledAvailabilityPaths.add(
+ availabilityPathKey([
+ "types",
+ typeName,
+ "properties",
+ propertyName,
+ "availability",
+ ]),
+ );
+ deprecations.push({
+ kind: "property",
+ definitionPath,
+ generatedPath: path.join(resourceRoot, "types", `${typeName}.ts`),
+ typeName,
+ propertyName: toLowerCamelCase(propertyName),
+ message: readDeprecationMessage(
+ property.availability,
+ `Deprecated property "${propertyName}" on type "${typeName}" in ${definitionPath}`,
+ ),
+ });
+ }
+ }
+
const unsupported = deprecatedAvailabilityPaths(definition).filter(
(segments) =>
!handledAvailabilityPaths.has(availabilityPathKey(segments)),
diff --git a/web/src/__e2e__/ai-gateway.gatewaye2e.ts b/web/src/__e2e__/ai-gateway.gatewaye2e.ts
index dad59829fc..43950ef48c 100644
--- a/web/src/__e2e__/ai-gateway.gatewaye2e.ts
+++ b/web/src/__e2e__/ai-gateway.gatewaye2e.ts
@@ -389,7 +389,7 @@ async function withGatewayApiKey(
const gatewayKey = await admin.caller.aiGateway.createApiKey({
orgId: ORGANIZATION_ID,
- note: `Gateway E2E ${input.provider} ${input.apiFormat}`,
+ name: `Gateway E2E ${input.provider} ${input.apiFormat}`,
metadata: {
test: true,
provider: input.provider,
diff --git a/web/src/__e2e__/api.servertest.ts b/web/src/__e2e__/api.servertest.ts
index 4e17bec062..f7513a5cb0 100644
--- a/web/src/__e2e__/api.servertest.ts
+++ b/web/src/__e2e__/api.servertest.ts
@@ -1,6 +1,8 @@
import { v4 } from "uuid";
import { JobExecutionStatus, Prisma, prisma } from "@langfuse/shared/src/db";
import {
+ API_KEY_CACHE_PATTERN,
+ AUTHZ_CONTEXT_CACHE_PATTERN,
getObservationById,
getTraceById,
OrgEnrichedApiKey,
@@ -8,6 +10,8 @@ import {
} from "@langfuse/shared/src/server";
import waitForExpect from "wait-for-expect";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+
const generateAuth = (username: string, password: string) => {
const auth = Buffer.from(`${username}:${password}`).toString("base64");
return `Basic ${auth}`;
@@ -96,9 +100,6 @@ describe("Ingestion Pipeline", () => {
await waitForExpect(
async () => {
- // we need a second call to the public API with the API key, so that it is stored in redis
- // first call (ingestion above) generates the new, fast API hash
- // second call (below) stores the API key in redis
const traceUrl = `http://localhost:3000/api/public/traces/${traceId}`;
const traceResponse = await fetch(traceUrl, {
@@ -126,26 +127,10 @@ describe("Ingestion Pipeline", () => {
expect(redis).not.toBeNull();
- const redisKeys = await redis?.keys(`api-key:*`);
- expect(redisKeys?.length ?? 0).toBeGreaterThanOrEqual(1);
// Concurrent e2e tests may cache additional API keys — find the seed
- // project's key by projectId rather than assuming it is the only one.
- let redisValue: string | null | undefined = null;
- for (const k of redisKeys ?? []) {
- const v = await redis?.get(k);
- if (!v) continue;
- try {
- if (JSON.parse(v).projectId === projectId) {
- redisValue = v;
- break;
- }
- } catch {}
- }
- expect(redisValue).not.toBeNull();
-
- const llmApiKey = OrgEnrichedApiKey.parse(JSON.parse(redisValue!));
- expect(llmApiKey.projectId).toBe(
- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ // project's key rather than assuming it is the only one.
+ expect(await findCachedPublicKeys(projectId)).toContain(
+ "pk-lf-1234567890",
);
},
40000,
@@ -329,3 +314,41 @@ describe("Prompts endpoint", () => {
});
});
});
+
+/** findCachedPublicKeys returns the public keys cached for a project by the legacy api-key cache or the authz context cache, whichever the auth migration mode writes. */
+async function findCachedPublicKeys(projectId: string): Promise<string[]> {
+ const [legacyKeys, contextKeys] = await Promise.all([
+ redis?.keys(API_KEY_CACHE_PATTERN) ?? [],
+ redis?.keys(AUTHZ_CONTEXT_CACHE_PATTERN) ?? [],
+ ]);
+ const [legacyValues, contextValues] = await Promise.all([
+ readCacheValues(legacyKeys),
+ readCacheValues(contextKeys),
+ ]);
+ return [
+ ...legacyValues.flatMap((v) => legacyPublicKey(v, projectId)),
+ ...contextValues.flatMap((v) => contextPublicKey(v, projectId)),
+ ];
+}
+
+async function readCacheValues(keys: string[]): Promise<unknown[]> {
+ const values = await Promise.all(keys.map((k) => redis?.get(k)));
+ return values.flatMap((v) => (v ? [JSON.parse(v)] : []));
+}
+
+function legacyPublicKey(value: unknown, projectId: string): string[] {
+ const apiKey = OrgEnrichedApiKey.safeParse(value);
+ return apiKey.success && apiKey.data.projectId === projectId
+ ? [apiKey.data.publicKey]
+ : [];
+}
+
+function contextPublicKey(value: unknown, projectId: string): string[] {
+ const principal = (value as CachedContext | null)?.context?.principal;
+ return principal?.kind === "apiKey" &&
+ principal.boundResource.projectId === projectId
+ ? [principal.publicKey]
+ : [];
+}
+
+type CachedContext = { context?: AuthorizationContext };
diff --git a/web/src/__tests__/server/admin-api-key-auth.servertest.ts b/web/src/__tests__/server/admin-api-key-auth.servertest.ts
index 354c74e75c..354c7aa42d 100644
--- a/web/src/__tests__/server/admin-api-key-auth.servertest.ts
+++ b/web/src/__tests__/server/admin-api-key-auth.servertest.ts
@@ -104,24 +104,27 @@ describe("Admin API Key Authentication", () => {
});
describe("Admin API Key Auth (isAdminApiKeyAuthAllowed = true)", () => {
- it("should successfully authenticate with valid admin API key", async () => {
- const mockReq = {
- headers: {
- authorization: `Bearer ${ADMIN_API_KEY}`,
- "x-langfuse-admin-api-key": ADMIN_API_KEY,
- "x-langfuse-project-id": projectId,
- },
- } as unknown as NextApiRequest;
+ it.each(["x-langfuse-project-id", "langfuse-project-id"])(
+ "should authenticate an admin API key with %s",
+ async (projectIdHeader) => {
+ const mockReq = {
+ headers: {
+ authorization: `Bearer ${ADMIN_API_KEY}`,
+ "x-langfuse-admin-api-key": ADMIN_API_KEY,
+ [projectIdHeader]: projectId,
+ },
+ } as unknown as NextApiRequest;
- const result = await verifyAuth(mockReq, true);
+ const result = await verifyAuth(mockReq, true);
- expect(result.validKey).toBe(true);
- expect(result.scope.projectId).toBe(projectId);
- expect(result.scope.orgId).toBe(orgId);
- expect(result.scope.apiKeyId).toBe("ADMIN_API_KEY");
- expect(result.scope.publicKey).toBe("ADMIN_API_KEY");
- expect(result.scope.accessLevel).toBe("project");
- });
+ expect(result.validKey).toBe(true);
+ expect(result.scope.projectId).toBe(projectId);
+ expect(result.scope.orgId).toBe(orgId);
+ expect(result.scope.apiKeyId).toBe("ADMIN_API_KEY");
+ expect(result.scope.publicKey).toBe("ADMIN_API_KEY");
+ expect(result.scope.accessLevel).toBe("project");
+ },
+ );
it("should fall back to basic auth when no Bearer header", async () => {
const mockReq = {
@@ -233,7 +236,7 @@ describe("Admin API Key Authentication", () => {
});
});
- it("should fail without x-langfuse-project-id header", async () => {
+ it("should fail without either project ID header", async () => {
const mockReq = {
headers: {
authorization: `Bearer ${ADMIN_API_KEY}`,
@@ -244,7 +247,7 @@ describe("Admin API Key Authentication", () => {
await expect(verifyAuth(mockReq, true)).rejects.toEqual({
status: 400,
message:
- "x-langfuse-project-id header is required for admin API key authentication",
+ "langfuse-project-id header is required for admin API key authentication",
});
});
diff --git a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
index b4409e8b89..650beb080d 100644
--- a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
+++ b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
@@ -336,7 +336,7 @@ describe("AI gateway control plane", () => {
const { caller, org } = await prepare();
const created = await caller.aiGateway.createApiKey({
orgId: org.id,
- note: "Production gateway",
+ name: "Production gateway",
metadata: { environment: "production", costCenter: 42 },
});
expect(created.secretKey).toMatch(/^sk-lf-/);
@@ -479,10 +479,10 @@ describe("AI gateway control plane", () => {
it("cursor-paginates gateway keys", async () => {
const { caller, org } = await prepare();
- for (const note of ["First", "Second", "Third"]) {
+ for (const name of ["First", "Second", "Third"]) {
await caller.aiGateway.createApiKey({
orgId: org.id,
- note,
+ name,
metadata: {},
});
}
diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.ts
index 0bbe828aac..9ee952aae5 100644
--- a/web/src/__tests__/server/api-auth.servertest.ts
+++ b/web/src/__tests__/server/api-auth.servertest.ts
@@ -1,7 +1,7 @@
import { vi } from "vitest";
import {
OrgEnrichedApiKey,
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
createOrgProjectAndApiKey,
createShaHash,
@@ -14,6 +14,7 @@ import { Prisma, type PrismaClient, prisma } from "@langfuse/shared/src/db";
import { env } from "@/src/env.mjs";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { v4 } from "uuid";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import {
clearRedisKeysByPatternSafely,
createRedisTestClient,
@@ -291,10 +292,13 @@ describe("Authenticate API calls", () => {
});
it("rejects in-app agent API keys by default", async () => {
- const apiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testApiKey.projectId,
- scope: "PROJECT",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${v4()}@example.com` },
+ });
+ const apiKey = await createApiKey(prisma, {
+ owner: ProjectId(testApiKey.projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
isInAppAgentKey: true,
});
@@ -313,10 +317,13 @@ describe("Authenticate API calls", () => {
});
it("allows in-app agent API keys when explicitly enabled", async () => {
- const apiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testApiKey.projectId,
- scope: "PROJECT",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${v4()}@example.com` },
+ });
+ const apiKey = await createApiKey(prisma, {
+ owner: ProjectId(testApiKey.projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
isInAppAgentKey: true,
});
@@ -420,6 +427,56 @@ describe("Authenticate API calls", () => {
warnSpy.mockRestore();
});
+
+ it("accepts a key that has not expired yet", async () => {
+ await prisma.apiKey.update({
+ where: { id: testApiKey.id },
+ data: { expiresAt: new Date(Date.now() + 60 * 60_000) },
+ });
+
+ const auth = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());
+
+ expect(auth.validKey).toBe(true);
+ });
+
+ it("rejects an expired key over basic auth like an unknown key", async () => {
+ await prisma.apiKey.update({
+ where: { id: testApiKey.id },
+ data: { expiresAt: new Date(Date.now() - 60_000) },
+ });
+
+ const auth = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());
+
+ expect(auth).toEqual({
+ validKey: false,
+ error:
+ "Invalid credentials. Confirm that you've configured the correct host.",
+ });
+ });
+
+ it("rejects an expired key over public-key bearer auth like an unknown key", async () => {
+ await prisma.apiKey.update({
+ where: { id: testApiKey.id },
+ data: { expiresAt: new Date(Date.now() - 60_000) },
+ });
+
+ const auth = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(`Bearer ${testApiKey.publicKey}`);
+
+ expect(auth).toEqual({
+ validKey: false,
+ error:
+ "Invalid public key. Confirm that you've configured the correct host.",
+ });
+ });
});
describe("validates with redis", () => {
@@ -864,6 +921,39 @@ describe("Authenticate API calls", () => {
expect(ttl2).toBeLessThanOrEqual(10);
});
+ it("rejects a cached key once it has expired", async () => {
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ getValidAuthHeader(),
+ );
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ getValidAuthHeader(),
+ );
+ const apiKey = await prisma.apiKey.findUniqueOrThrow({
+ where: { publicKey: testApiKey.publicKey },
+ });
+ const redisKey = `api-key:${apiKey.fastHashedSecretKey}`;
+ const cached = JSON.parse((await getRedisValue(redis, redisKey))!);
+ await setRedisValue(
+ redis,
+ redisKey,
+ JSON.stringify({
+ ...cached,
+ expiresAt: new Date(Date.now() - 60_000).toISOString(),
+ }),
+ );
+
+ const auth = await new ApiAuthService(
+ { apiKey: { findUnique: vi.fn() } } as unknown as PrismaClient,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());
+
+ expect(auth).toEqual({
+ validKey: false,
+ error:
+ "Invalid credentials. Confirm that you've configured the correct host.",
+ });
+ });
+
it("should delete API keys from cache and db", async () => {
// first auth will generate the fast hashed api key
await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
diff --git a/web/src/__tests__/server/api-key-list-filter.servertest.ts b/web/src/__tests__/server/api-key-list-filter.servertest.ts
index e57edd6bfe..9b41279815 100644
--- a/web/src/__tests__/server/api-key-list-filter.servertest.ts
+++ b/web/src/__tests__/server/api-key-list-filter.servertest.ts
@@ -1,8 +1,15 @@
+import { randomUUID } from "crypto";
import { prisma } from "@langfuse/shared/src/db";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
import { handleGetApiKeys as handleGetProjectApiKeys } from "@/src/ee/features/admin-api/server/projects/projectById/apiKeys";
import { handleDeleteApiKey as handleDeleteProjectApiKey } from "@/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById";
import { handleGetApiKeys as handleGetOrganizationApiKeys } from "@/src/ee/features/admin-api/server/organizations/apiKeys";
@@ -36,18 +43,21 @@ describe("public API key list filters", () => {
it("filters in-app agent keys from project API key responses", async () => {
const { projectId } = await createOrgProjectAndApiKey();
- const visibleKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "Visible project key",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const visibleKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Visible project key",
});
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "Hidden project in-app agent key",
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Hidden project in-app agent key",
isInAppAgentKey: true,
});
@@ -67,18 +77,21 @@ describe("public API key list filters", () => {
it("filters in-app agent keys from organization API key responses", async () => {
const { orgId } = await createOrgProjectAndApiKey();
- const visibleKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: orgId,
- scope: "ORGANIZATION",
- note: "Visible org key",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const visibleKey = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Visible org key",
});
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: orgId,
- scope: "ORGANIZATION",
- note: "Hidden org in-app agent key",
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Hidden org in-app agent key",
isInAppAgentKey: true,
});
@@ -97,10 +110,18 @@ describe("public API key list filters", () => {
it("does not delete project in-app agent keys via admin API handler", async () => {
const { projectId, orgId } = await createOrgProjectAndApiKey();
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const callerKey = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ });
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
isInAppAgentKey: true,
});
@@ -111,6 +132,7 @@ describe("public API key list filters", () => {
projectId,
inAppAgentKey.id,
orgId,
+ callerKey.id,
);
expect(response.statusCode).toBe(404);
@@ -121,10 +143,13 @@ describe("public API key list filters", () => {
it("does not delete organization in-app agent keys via admin API handler", async () => {
const { orgId } = await createOrgProjectAndApiKey();
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: orgId,
- scope: "ORGANIZATION",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
isInAppAgentKey: true,
});
diff --git a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
index c1f47a5f02..f67362da0b 100644
--- a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
+++ b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
@@ -3,6 +3,7 @@ import { type Plan, Role } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
createApiKeyCacheKey,
+ AUTHZ_CONTEXT_CACHE_KEY_PREFIX,
createAuthzContextCacheKey,
createShaHash,
} from "@langfuse/shared/src/server";
@@ -80,8 +81,11 @@ function cacheKeysFor({
}) {
return [
createApiKeyCacheKey(fastHash),
- createAuthzContextCacheKey(fastHash),
- createAuthzContextCacheKey(createShaHash(publicKey, env.SALT!)),
+ `${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${fastHash}`,
+ `${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${createShaHash(publicKey, env.SALT!)}`,
+ createAuthzContextCacheKey("basic", fastHash),
+ createAuthzContextCacheKey("bearer", fastHash),
+ createAuthzContextCacheKey("bearer", createShaHash(publicKey, env.SALT!)),
];
}
@@ -268,11 +272,21 @@ describe("API-key cache invalidation on project/org lifecycle", () => {
).resolves.toMatchObject({ deletedAt: null });
});
- it("admin handleDeleteProject evicts the org's cached keys", async () => {
+ it("admin project soft deletion preserves user permissions and evicts cached keys", async () => {
const orgId = await createOrg();
const projectId = await createProject(orgId);
const keys = await seedOrgScopedKey(orgId);
+ const user = await createUserInOrgs([orgId]);
+ const assignment = await prisma.roleAssignment.create({
+ data: {
+ orgId,
+ principalUserId: user.id,
+ ownerProjectId: projectId,
+ systemRole: "VIEWER",
+ },
+ });
+
const res = makeRes();
await handleDeleteProject({} as any, res, projectId, {
orgId,
@@ -281,6 +295,12 @@ describe("API-key cache invalidation on project/org lifecycle", () => {
expect(res.statusCode).toBe(202);
expect(await survivingKeys(keys)).toEqual([]);
+ await expect(
+ prisma.roleAssignment.findUnique({ where: { id: assignment.id } }),
+ ).resolves.toEqual(assignment);
+ await expect(
+ prisma.project.findUnique({ where: { id: projectId } }),
+ ).resolves.toMatchObject({ deletedAt: expect.any(Date) });
});
it("admin handleDeleteOrganization evicts cached keys before the cascade removes the rows", async () => {
diff --git a/web/src/__tests__/server/audit-log-in-app-agent.servertest.ts b/web/src/__tests__/server/audit-log-in-app-agent.servertest.ts
index 1ec2ded8fe..7144ccca74 100644
--- a/web/src/__tests__/server/audit-log-in-app-agent.servertest.ts
+++ b/web/src/__tests__/server/audit-log-in-app-agent.servertest.ts
@@ -2,8 +2,9 @@ import { randomUUID } from "crypto";
import { afterEach, describe, expect, it, vi } from "vitest";
import { auditLog } from "@/src/features/audit-logs/server";
import { prisma, AuditLogRecordType } from "@langfuse/shared/src/db";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
describe("in-app agent audit logging", () => {
afterEach(() => {
@@ -19,13 +20,12 @@ describe("in-app agent audit logging", () => {
},
});
- const mcpApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "In-app agent MCP session",
+ const mcpApiKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ name: "In-app agent MCP session",
isInAppAgentKey: true,
- createdByUserId: user.id,
});
const persistedApiKey = await prisma.apiKey.findUniqueOrThrow({
@@ -51,13 +51,12 @@ describe("in-app agent audit logging", () => {
},
});
- const mcpApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "In-app agent MCP session",
+ const mcpApiKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ name: "In-app agent MCP session",
isInAppAgentKey: true,
- createdByUserId: user.id,
});
const resourceId = randomUUID();
diff --git a/web/src/__tests__/server/audit-log-license-gate.servertest.ts b/web/src/__tests__/server/audit-log-license-gate.servertest.ts
index fba4bb63f5..00dcacbe9b 100644
--- a/web/src/__tests__/server/audit-log-license-gate.servertest.ts
+++ b/web/src/__tests__/server/audit-log-license-gate.servertest.ts
@@ -26,8 +26,9 @@ vi.mock("@/src/env.mjs", async (importOriginal) => {
import { auditLog } from "@/src/features/audit-logs/server";
import { prisma } from "@langfuse/shared/src/db";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
import { createOrgProjectAndApiKey, logger } from "@langfuse/shared/src/server";
+import { ProjectId, SystemRoleId } from "@langfuse/shared/rbac";
/**
* Audit log records are an enterprise feature, so they are only persisted when
@@ -48,11 +49,11 @@ describe("audit log license gate", () => {
orgId = org.orgId;
projectId = org.projectId;
apiKeyId = (
- await createAndAddApiKeysToDb({
- prisma,
- entityId: org.projectId,
- scope: "PROJECT",
- note: "License gate test key",
+ await createApiKey(prisma, {
+ owner: ProjectId(org.projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: "system",
+ name: "License gate test key",
})
).id;
});
diff --git a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts b/web/src/__tests__/server/blob-storage-integration-api.servertest.ts
index e3f1e1ae32..5b8bf38ef2 100644
--- a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts
+++ b/web/src/__tests__/server/blob-storage-integration-api.servertest.ts
@@ -6,9 +6,15 @@ import { prisma } from "@langfuse/shared/src/db";
import { z } from "zod";
import { randomUUID } from "crypto";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
} from "@langfuse/shared/src/server";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
import {
OBSERVATION_FIELD_GROUPS_FULL,
LEGACY_EXPORT_PROJECT_CUTOFF,
@@ -124,11 +130,14 @@ describe("Blob Storage Integrations API", () => {
testProject2Id = testProject2.id;
// Create organization API key
- const orgApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testOrgId,
- scope: "ORGANIZATION",
- note: "Test API Key for Blob Storage API",
+ const orgKeyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const orgApiKey = await createApiKey(prisma, {
+ owner: OrganizationId(testOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(orgKeyCreator.id),
+ name: "Test API Key for Blob Storage API",
predefinedKeys: {
publicKey: `pk-lf-blob-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-blob-${randomUUID().substring(0, 8)}`,
@@ -235,11 +244,14 @@ describe("Blob Storage Integrations API", () => {
it("should return 403 with project-scoped API key", async () => {
// Create project API key
- const projectApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testProject1Id,
- scope: "PROJECT",
- note: "Project API Key",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const projectApiKey = await createApiKey(prisma, {
+ owner: ProjectId(testProject1Id),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Project API Key",
predefinedKeys: {
publicKey: `pk-lf-proj-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-proj-${randomUUID().substring(0, 8)}`,
@@ -1459,11 +1471,14 @@ describe("Blob Storage Integrations API", () => {
});
it("should return 403 with project-scoped API key", async () => {
- const projectApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testProject1Id,
- scope: "PROJECT",
- note: "Project API Key",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const projectApiKey = await createApiKey(prisma, {
+ owner: ProjectId(testProject1Id),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Project API Key",
predefinedKeys: {
publicKey: `pk-lf-proj-del-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-proj-del-${randomUUID().substring(0, 8)}`,
diff --git a/web/src/__tests__/server/blob-storage-integration-status-api.servertest.ts b/web/src/__tests__/server/blob-storage-integration-status-api.servertest.ts
index c475081c65..a6df3bbeeb 100644
--- a/web/src/__tests__/server/blob-storage-integration-status-api.servertest.ts
+++ b/web/src/__tests__/server/blob-storage-integration-status-api.servertest.ts
@@ -6,9 +6,15 @@ import { prisma } from "@langfuse/shared/src/db";
import { z } from "zod";
import { randomUUID } from "crypto";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
} from "@langfuse/shared/src/server";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
const BlobStorageIntegrationStatusResponseSchema = z
.object({
@@ -64,11 +70,14 @@ describe("Blob Storage Integration Status API - GET /api/public/integrations/blo
});
testProjectId = testProject.id;
- const orgApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testOrgId,
- scope: "ORGANIZATION",
- note: "Test API Key for Blob Status API",
+ const orgKeyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const orgApiKey = await createApiKey(prisma, {
+ owner: OrganizationId(testOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(orgKeyCreator.id),
+ name: "Test API Key for Blob Status API",
predefinedKeys: {
publicKey: `pk-lf-bstat-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-bstat-${randomUUID().substring(0, 8)}`,
@@ -118,11 +127,14 @@ describe("Blob Storage Integration Status API - GET /api/public/integrations/blo
});
it("should return 403 with project-scoped API key", async () => {
- const projectApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testProjectId,
- scope: "PROJECT",
- note: "Project API Key for status test",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const projectApiKey = await createApiKey(prisma, {
+ owner: ProjectId(testProjectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Project API Key for status test",
predefinedKeys: {
publicKey: `pk-lf-pstat-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-pstat-${randomUUID().substring(0, 8)}`,
diff --git a/web/src/__tests__/server/getRolesForPrincipal.servertest.ts b/web/src/__tests__/server/getRolesForPrincipal.servertest.ts
new file mode 100644
index 0000000000..203ef4e300
--- /dev/null
+++ b/web/src/__tests__/server/getRolesForPrincipal.servertest.ts
@@ -0,0 +1,195 @@
+import { describe, expect, it } from "vitest";
+
+import { randomUUID } from "crypto";
+
+import { prisma } from "@langfuse/shared/src/db";
+import { assignRole } from "@langfuse/shared/rbac/server";
+import {
+ createApiKey,
+ createOrgProjectAndApiKey,
+} from "@langfuse/shared/src/server";
+
+import {
+ allOrganizationActions,
+ allProjectActions,
+ ApiKeyId,
+ OrganizationId,
+ ProjectId,
+ systemRoleAccessRights,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
+
+import { getRolesForPrincipal } from "@/src/features/rbac/getRolesForPrincipal";
+
+// Decision-equivalence: resolving policies from system-role assignments must
+// yield the catalog grants bound to the same tenant and resources the key
+// covered before the resolver read from assignments.
+describe("getRolesForPrincipal decision-equivalence", () => {
+ it.each(
+ Object.values(systemRoleAccessRights).flatMap(({ id }) =>
+ (["organization", "project"] as const).map((ownerKind) => ({
+ systemRole: id,
+ ownerKind,
+ })),
+ ),
+ )(
+ "$systemRole on a $ownerKind returns policies with matching action and resource kinds",
+ async ({ systemRole, ownerKind }) => {
+ const { orgId, projectId } = await createOrgProjectAndApiKey();
+ const user = await prisma.user.create({
+ data: { email: `policy-kinds-${randomUUID()}@example.com` },
+ });
+ const principalId = UserId(user.id);
+ await assignRole(prisma, {
+ principalId,
+ roleId: SystemRoleId(systemRole),
+ tenantId: OrganizationId(orgId),
+ ownerId:
+ ownerKind === "organization"
+ ? OrganizationId(orgId)
+ : ProjectId(projectId),
+ tags: [],
+ });
+
+ const roles = await getRolesForPrincipal(principalId);
+ expect(roles).toHaveLength(1);
+ for (const policy of roles[0].policies) {
+ expect(policy.resources.length).toBeGreaterThan(0);
+ const resourceKind = policy.resources[0].split("/")[0];
+ expect(["organization", "project"]).toContain(resourceKind);
+ expect(
+ policy.resources.every((resource) =>
+ resource.startsWith(`${resourceKind}/`),
+ ),
+ ).toBe(true);
+
+ const allowedActions = new Set<string>(
+ resourceKind === "organization"
+ ? allOrganizationActions
+ : allProjectActions,
+ );
+ for (const action of policy.actions) {
+ expect(allowedActions.has(action), `${policy.id}: ${action}`).toBe(
+ true,
+ );
+ }
+ }
+ },
+ );
+
+ it("keeps the same role scoped to each assignment's owner and tenant", async () => {
+ const organization = await createOrgProjectAndApiKey();
+ const project = await createOrgProjectAndApiKey();
+ const user = await prisma.user.create({
+ data: { email: `role-scope-${randomUUID()}@example.com` },
+ });
+ const principalId = UserId(user.id);
+ const roleId = SystemRoleId("VIEWER");
+ await assignRole(prisma, {
+ principalId,
+ roleId,
+ tenantId: OrganizationId(organization.orgId),
+ ownerId: OrganizationId(organization.orgId),
+ tags: [],
+ });
+ await assignRole(prisma, {
+ principalId,
+ roleId,
+ tenantId: OrganizationId(project.orgId),
+ ownerId: ProjectId(project.projectId),
+ tags: [],
+ });
+
+ const roles = await getRolesForPrincipal(principalId);
+ expect(roles).toHaveLength(2);
+ const organizationRole = roles.find(
+ (role) => role.tenantId === OrganizationId(organization.orgId),
+ );
+ const projectRole = roles.find(
+ (role) => role.tenantId === OrganizationId(project.orgId),
+ );
+ expect(organizationRole?.policies).toEqual(
+ systemRoleAccessRights.VIEWER.policies.map((policy) => ({
+ id: `${roleId}:${policy.resourceKind}`,
+ roleId,
+ tenantId: OrganizationId(organization.orgId),
+ effect: policy.effect,
+ actions: policy.actions,
+ resources:
+ policy.resourceKind === "organization"
+ ? [OrganizationId(organization.orgId)]
+ : [ProjectId("*")],
+ })),
+ );
+ expect(projectRole?.policies).toEqual(
+ systemRoleAccessRights.VIEWER.policies
+ .filter((policy) => policy.resourceKind === "project")
+ .map((policy) => ({
+ id: `${roleId}:${policy.resourceKind}`,
+ roleId,
+ tenantId: OrganizationId(project.orgId),
+ effect: policy.effect,
+ actions: policy.actions,
+ resources: [ProjectId(project.projectId)],
+ })),
+ );
+ });
+
+ it("a legacy project API key resolves to the project policy bound to its project", async () => {
+ const { projectId, orgId } = await createOrgProjectAndApiKey();
+ const creator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const key = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(creator.id),
+ });
+
+ const policies = (await getRolesForPrincipal(ApiKeyId(key.id))).flatMap(
+ (role) => role.policies,
+ );
+
+ expect(policies).toEqual(
+ systemRoleAccessRights.LEGACY_PROJECT_API_KEY.policies.map((p) => ({
+ id: `${SystemRoleId("LEGACY_PROJECT_API_KEY")}:${p.resourceKind}`,
+ roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ tenantId: OrganizationId(orgId),
+ effect: p.effect,
+ actions: p.actions,
+ resources: [ProjectId(projectId)],
+ })),
+ );
+ });
+
+ it("a legacy organization API key resolves to the org policy plus its project policy over the org's project wildcard", async () => {
+ const { orgId } = await createOrgProjectAndApiKey();
+ const creator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const key = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(creator.id),
+ });
+
+ const policies = (await getRolesForPrincipal(ApiKeyId(key.id))).flatMap(
+ (role) => role.policies,
+ );
+
+ expect(policies).toEqual(
+ systemRoleAccessRights.LEGACY_ORGANIZATION_API_KEY.policies.map((p) => ({
+ id: `${SystemRoleId("LEGACY_ORGANIZATION_API_KEY")}:${p.resourceKind}`,
+ roleId: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ tenantId: OrganizationId(orgId),
+ effect: p.effect,
+ actions: p.actions,
+ resources:
+ p.resourceKind === "organization"
+ ? [OrganizationId(orgId)]
+ : [ProjectId("*")],
+ })),
+ );
+ });
+});
diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
index 07402a0fa1..eea50eb073 100644
--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
@@ -13,10 +13,11 @@ import {
} from "@langfuse/shared/in-app-agent/server/mcpPolicy";
import { prisma } from "@langfuse/shared/src/db";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
const authMocks = vi.hoisted(() => ({
getServerAuthSessionForRequest: vi.fn(),
@@ -46,10 +47,13 @@ describe("in-app agent public API route auth", () => {
async function createInAppAgentAuthHeader() {
const { projectId } = await createOrgProjectAndApiKey();
- const apiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const apiKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
isInAppAgentKey: true,
});
diff --git a/web/src/__tests__/server/mcp-auth-parity.servertest.ts b/web/src/__tests__/server/mcp-auth-parity.servertest.ts
index 2123ab5ebd..f7d5dff57d 100644
--- a/web/src/__tests__/server/mcp-auth-parity.servertest.ts
+++ b/web/src/__tests__/server/mcp-auth-parity.servertest.ts
@@ -1,13 +1,20 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
+import { randomUUID } from "crypto";
import { env } from "@/src/env.mjs";
import { prisma } from "@langfuse/shared/src/db";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
import mcpHandler from "@/src/pages/api/public/mcp";
@@ -140,17 +147,23 @@ describe("MCP connection auth parity", () => {
fixtureProjectId = base.projectId;
keys.project = { publicKey: base.publicKey, secretKey: base.secretKey };
- const org = await createAndAddApiKeysToDb({
- prisma,
- entityId: base.orgId,
- scope: "ORGANIZATION",
+ const orgKeyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const org = await createApiKey(prisma, {
+ owner: OrganizationId(base.orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(orgKeyCreator.id),
});
keys.org = { publicKey: org.publicKey, secretKey: org.secretKey };
- const agent = await createAndAddApiKeysToDb({
- prisma,
- entityId: base.projectId,
- scope: "PROJECT",
+ const agentKeyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const agent = await createApiKey(prisma, {
+ owner: ProjectId(base.projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(agentKeyCreator.id),
isInAppAgentKey: true,
});
keys.agent = { publicKey: agent.publicKey, secretKey: agent.secretKey };
diff --git a/web/src/__tests__/server/mcp-auth.servertest.ts b/web/src/__tests__/server/mcp-auth.servertest.ts
index 0da95b9d5f..dddf393a08 100644
--- a/web/src/__tests__/server/mcp-auth.servertest.ts
+++ b/web/src/__tests__/server/mcp-auth.servertest.ts
@@ -43,8 +43,10 @@ describe("MCP Authentication", () => {
});
expect(response.status).toBe(401);
+ // The exact wording differs by auth-migration mode; only the 401 and the
+ // presence of an error message are a stable contract.
const body = await response.json();
- expect(body.error).toContain("Invalid credentials");
+ expect(body.error).toEqual(expect.any(String));
});
it("should return 401 for missing authorization header", async () => {
diff --git a/web/src/__tests__/server/mcp-helpers.ts b/web/src/__tests__/server/mcp-helpers.ts
index aadd1a624a..e06ce9f8c4 100644
--- a/web/src/__tests__/server/mcp-helpers.ts
+++ b/web/src/__tests__/server/mcp-helpers.ts
@@ -8,8 +8,10 @@
import { randomUUID } from "crypto";
import { prisma, type Role } from "@langfuse/shared/src/db";
import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import type { ServerContext } from "@/src/features/mcp/types";
+import { authenticator } from "@/src/features/apiKey/server";
/**
* Creates a complete MCP test setup including:
@@ -38,6 +40,11 @@ export async function createMcpTestSetup(): Promise<{
throw new Error("Failed to create API key for test setup");
}
+ const authenticated = await authenticator.authenticate({
+ headers: { authorization: auth },
+ });
+ if (!authenticated.success) throw authenticated.error;
+
const context: ServerContext = {
projectId,
orgId,
@@ -46,6 +53,7 @@ export async function createMcpTestSetup(): Promise<{
publicKey: result.publicKey,
plan: "oss",
rateLimitOverrides: [],
+ auth: authenticated.context,
};
return {
@@ -92,14 +100,27 @@ export async function createInAppAgentMcpContext(params: {
orgId: string;
createdByUserId?: string;
}): Promise<{ apiKeyId: string; context: ServerContext }> {
- const apiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: params.projectId,
- scope: "PROJECT",
- note: "In-app agent MCP session",
+ const creatorUserId =
+ params.createdByUserId ??
+ (
+ await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ })
+ ).id;
+ const apiKey = await createApiKey(prisma, {
+ owner: ProjectId(params.projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(creatorUserId),
+ name: "In-app agent MCP session",
isInAppAgentKey: true,
- createdByUserId: params.createdByUserId,
});
+ const authenticated = await authenticator.authenticate({
+ headers: {
+ authorization: `Basic ${Buffer.from(`${apiKey.publicKey}:${apiKey.secretKey}`).toString("base64")}`,
+ },
+ allowInAppAgentKey: true,
+ });
+ if (!authenticated.success) throw authenticated.error;
return {
apiKeyId: apiKey.id,
@@ -111,6 +132,7 @@ export async function createInAppAgentMcpContext(params: {
publicKey: apiKey.publicKey,
plan: "oss",
rateLimitOverrides: [],
+ auth: authenticated.context,
},
};
}
diff --git a/web/src/__tests__/server/memberships-api.servertest.ts b/web/src/__tests__/server/memberships-api.servertest.ts
index fffb7c8a9d..f169c256c0 100644
--- a/web/src/__tests__/server/memberships-api.servertest.ts
+++ b/web/src/__tests__/server/memberships-api.servertest.ts
@@ -6,10 +6,37 @@ import { prisma } from "@langfuse/shared/src/db";
import { z } from "zod";
import { randomUUID } from "crypto";
import { Role } from "@langfuse/shared";
+import projectMembershipRoute from "@/src/pages/api/public/projects/[projectId]/memberships";
+import { env } from "@/src/env.mjs";
+import { createMocks } from "node-mocks-http";
+import { type NextApiRequest, type NextApiResponse } from "next";
+import * as auditLogs from "@/src/features/audit-logs/server";
+import { authenticator } from "@/src/features/apiKey/server";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+import * as sfdc from "@/src/ee/features/sfdc-sync/server";
import {
- createAndAddApiKeysToDb,
+ handleUpdateMembership,
+ handleDeleteMembership,
+} from "@/src/ee/features/admin-api/server/memberships";
+import {
+ handleUpdateMembership as handleUpdateProjectMembership,
+ handleDeleteMembership as handleDeleteProjectMembership,
+} from "@/src/ee/features/admin-api/server/projects/projectById/memberships";
+import {
+ createApiKey,
createBasicAuthHeader,
} from "@langfuse/shared/src/server";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
+
+vi.mock("@/src/env.mjs", async (importOriginal) => {
+ const actual = await importOriginal<{ env: typeof env }>();
+ return { ...actual, env: { ...actual.env } };
+});
// Schema for membership response
const MembershipResponseSchema = z.object({
@@ -61,11 +88,11 @@ describe("Memberships APIs", () => {
testUserId = user.id;
// Create an organization API key
- const apiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testOrgId,
- scope: "ORGANIZATION",
- note: "Test API Key for Memberships API",
+ const apiKey = await createApiKey(prisma, {
+ owner: OrganizationId(testOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(testUserId),
+ name: "Test API Key for Memberships API",
predefinedKeys: {
publicKey: `pk-lf-org-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-org-${randomUUID().substring(0, 8)}`,
@@ -77,6 +104,7 @@ describe("Memberships APIs", () => {
afterAll(async () => {
// Clean up test data
+ await prisma.auditLog.deleteMany({ where: { orgId: testOrgId } });
await prisma.user.delete({
where: {
id: testUserId,
@@ -137,11 +165,11 @@ describe("Memberships APIs", () => {
it("should return 403 when using a non-organization API key", async () => {
// Create a project API key
- const projectApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testProjectId,
- scope: "PROJECT",
- note: "Test API Key for Memberships API",
+ const projectApiKey = await createApiKey(prisma, {
+ owner: ProjectId(testProjectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(testUserId),
+ name: "Test API Key for Memberships API",
predefinedKeys: {
publicKey: `pk-lf-project-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-project-${randomUUID().substring(0, 8)}`,
@@ -488,7 +516,7 @@ describe("Memberships APIs", () => {
orgId: testOrgId,
},
},
- update: {},
+ update: { role: Role.MEMBER },
create: {
userId: testUserId,
orgId: testOrgId,
@@ -537,3 +565,602 @@ describe("Memberships APIs", () => {
});
});
});
+
+describe("Organization membership safeguards", () => {
+ let orgId: string;
+ let ownerId: string;
+ let memberId: string;
+ let apiKeyId: string;
+ let adminKeyId: string;
+ let ownerContext: AuthorizationContext;
+ let adminContext: AuthorizationContext;
+ let ownerAuth: string;
+ let adminAuth: string;
+ let legacyAuth: string;
+
+ beforeEach(async () => {
+ const org = await prisma.organization.create({
+ data: { name: randomUUID(), cloudConfig: { plan: "Team" } },
+ });
+ orgId = org.id;
+ const [owner, member] = await Promise.all(
+ [Role.OWNER, Role.MEMBER].map((role) =>
+ prisma.user.create({
+ data: {
+ email: `${randomUUID()}@example.com`,
+ organizationMemberships: { create: { orgId, role } },
+ },
+ }),
+ ),
+ );
+ ownerId = owner!.id;
+ memberId = member!.id;
+ const [ownerKey, adminKey] = await Promise.all(
+ (["LEGACY_ORGANIZATION_API_KEY", "ADMIN"] as const).map((role) =>
+ createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId(role),
+ createdBy: UserId(ownerId),
+ }),
+ ),
+ );
+ apiKeyId = ownerKey!.id;
+ adminKeyId = adminKey!.id;
+ ownerAuth = createBasicAuthHeader(ownerKey!.publicKey, ownerKey!.secretKey);
+ adminAuth = createBasicAuthHeader(adminKey!.publicKey, adminKey!.secretKey);
+ legacyAuth = ownerAuth;
+ const ownerAuthentication = await authenticator.authenticate({
+ headers: { authorization: ownerAuth },
+ });
+ const adminAuthentication = await authenticator.authenticate({
+ headers: { authorization: adminAuth },
+ });
+ if (!ownerAuthentication.success) throw ownerAuthentication.error;
+ if (!adminAuthentication.success) throw adminAuthentication.error;
+ ownerContext = ownerAuthentication.context;
+ adminContext = adminAuthentication.context;
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await prisma.auditLog.deleteMany({ where: { orgId } });
+ await prisma.organization.delete({ where: { id: orgId } });
+ await prisma.user.deleteMany({
+ where: { id: { in: [ownerId, memberId] } },
+ });
+ });
+
+ const membership = (userId: string) =>
+ prisma.organizationMembership.findUnique({
+ where: { orgId_userId: { orgId, userId } },
+ });
+ const logs = () =>
+ prisma.auditLog.findMany({
+ where: { orgId, resourceType: "orgMembership" },
+ orderBy: { createdAt: "asc" },
+ });
+ const request = (
+ method: "PUT" | "DELETE",
+ userId: string,
+ role?: Role,
+ auth = ownerAuth,
+ ) =>
+ makeAPICall(
+ method,
+ "/api/public/organizations/memberships",
+ { userId, role },
+ auth,
+ );
+
+ it.each(["PUT", "DELETE"] as const)(
+ "rejects last-owner %s without changing state or auditing success",
+ async (method) => {
+ const before = await membership(ownerId);
+ expect((await request(method, ownerId, Role.ADMIN)).status).toBe(403);
+ expect(await membership(ownerId)).toEqual(before);
+ expect(await logs()).toEqual([]);
+ },
+ );
+
+ it.each([
+ ["PUT", "member", Role.OWNER],
+ ["PUT", "owner", Role.ADMIN],
+ ["DELETE", "owner", undefined],
+ ] as const)("rejects ADMIN %s of %s to %s", async (method, target, role) => {
+ if (target === "owner") {
+ await prisma.organizationMembership.update({
+ where: { orgId_userId: { orgId, userId: memberId } },
+ data: { role: Role.OWNER },
+ });
+ }
+ const userId = target === "owner" ? ownerId : memberId;
+ const before = await membership(userId);
+ expect((await request(method, userId, role, adminAuth)).status).toBe(403);
+ expect(await membership(userId)).toEqual(before);
+ expect(await logs()).toEqual([]);
+ });
+
+ it("lets ADMIN manage ordinary members and remove the last ADMIN", async () => {
+ expect((await request("PUT", memberId, Role.ADMIN, adminAuth)).status).toBe(
+ 200,
+ );
+ expect(
+ (await request("DELETE", memberId, undefined, adminAuth)).status,
+ ).toBe(200);
+ expect(await membership(memberId)).toBeNull();
+ expect((await membership(ownerId))?.role).toBe(Role.OWNER);
+ });
+
+ it("combines membership and ownership policy grants across roles", async () => {
+ await prisma.organizationMembership.update({
+ where: { orgId_userId: { orgId, userId: memberId } },
+ data: { role: Role.OWNER },
+ });
+ const context: AuthorizationContext = {
+ ...adminContext,
+ policies: (
+ [
+ ["VIEWER", "organizationMembers:CUD"],
+ ["INGEST", "organizationMembers:manageOwnership"],
+ ] as const
+ ).map(([role, action]) => ({
+ id: action,
+ roleId: SystemRoleId(role),
+ tenantId: OrganizationId(orgId),
+ effect: "ALLOW",
+ actions: [action],
+ resources: [OrganizationId(orgId)],
+ })),
+ };
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "PUT",
+ body: { userId: ownerId, role: Role.MEMBER },
+ });
+ await handleUpdateMembership(req, res, orgId, adminKeyId, context);
+ expect(res.statusCode).toBe(200);
+ expect((await membership(ownerId))?.role).toBe(Role.MEMBER);
+ expect(await logs()).toHaveLength(1);
+ });
+
+ it("denies membership changes without policy grants", async () => {
+ const context = { ...ownerContext, policies: [] };
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "DELETE",
+ body: { userId: memberId },
+ });
+ const before = await membership(memberId);
+ await expect(
+ handleDeleteMembership(req, res, orgId, apiKeyId, context),
+ ).rejects.toMatchObject({ httpCode: 403 });
+ expect(await membership(memberId)).toEqual(before);
+ expect(await logs()).toEqual([]);
+ });
+
+ it("rejects a VIEWER key without membership write grants", async () => {
+ const key = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("VIEWER"),
+ createdBy: UserId(ownerId),
+ });
+ const before = await membership(memberId);
+ expect(
+ (
+ await request(
+ "DELETE",
+ memberId,
+ undefined,
+ createBasicAuthHeader(key.publicKey, key.secretKey),
+ )
+ ).status,
+ ).toBe(403);
+ expect(await membership(memberId)).toEqual(before);
+ expect(await logs()).toEqual([]);
+ });
+
+ it("keeps legacy organization keys' owner authority", async () => {
+ expect(
+ (await request("PUT", memberId, Role.OWNER, legacyAuth)).status,
+ ).toBe(200);
+ expect(
+ (await request("DELETE", ownerId, undefined, legacyAuth)).status,
+ ).toBe(200);
+ expect(
+ (await request("DELETE", memberId, undefined, legacyAuth)).status,
+ ).toBe(403);
+ });
+
+ it("audits create, update, no-op PUT, and actual deletion with the verified key", async () => {
+ await prisma.organizationMembership.deleteMany({
+ where: { orgId, userId: memberId },
+ });
+ expect((await request("PUT", memberId, Role.VIEWER)).status).toBe(200);
+ const created = await membership(memberId);
+ expect((await request("PUT", memberId, Role.ADMIN)).status).toBe(200);
+ const updated = await membership(memberId);
+ expect((await request("PUT", ownerId, Role.OWNER)).status).toBe(200);
+ expect((await request("DELETE", memberId)).status).toBe(200);
+ expect((await request("DELETE", memberId)).status).toBe(200);
+ const records = await logs();
+ expect(records.map((record) => record.action)).toEqual([
+ "create",
+ "update",
+ "update",
+ "delete",
+ ]);
+ for (const record of records) {
+ expect(record).toMatchObject({
+ orgId,
+ apiKeyId,
+ type: "API_KEY",
+ userId: null,
+ projectId: null,
+ });
+ }
+ const serialized = (value: unknown) => JSON.parse(JSON.stringify(value));
+ expect(records[0]).toMatchObject({ resourceId: created!.id, before: null });
+ expect(JSON.parse(records[0]!.after!)).toEqual(serialized(created));
+ expect(records[1]).toMatchObject({ resourceId: created!.id });
+ expect(JSON.parse(records[1]!.before!)).toEqual(serialized(created));
+ expect(JSON.parse(records[1]!.after!)).toEqual(serialized(updated));
+ expect(records[3]).toMatchObject({ resourceId: created!.id, after: null });
+ expect(JSON.parse(records[3]!.before!)).toEqual(serialized(updated));
+ });
+
+ it("does not audit invalid requests or missing users", async () => {
+ expect((await request("PUT", randomUUID(), Role.MEMBER)).status).toBe(404);
+ expect(
+ (
+ await makeAPICall(
+ "PUT",
+ "/api/public/organizations/memberships",
+ { userId: memberId, role: "INVALID" },
+ ownerAuth,
+ )
+ ).status,
+ ).toBe(400);
+ expect(
+ (
+ await makeAPICall(
+ "DELETE",
+ "/api/public/organizations/memberships",
+ {},
+ ownerAuth,
+ )
+ ).status,
+ ).toBe(400);
+ expect(await logs()).toEqual([]);
+ });
+
+ it.each(["PUT", "DELETE"] as const)(
+ "serializes concurrent owner %s operations",
+ async (method) => {
+ await prisma.organizationMembership.update({
+ where: { orgId_userId: { orgId, userId: memberId } },
+ data: { role: Role.OWNER },
+ });
+ const responses = await Promise.all([
+ request(method, ownerId, Role.ADMIN),
+ request("DELETE", memberId),
+ ]);
+ expect(responses.map((response) => response.status).sort()).toEqual([
+ 200, 403,
+ ]);
+ expect(
+ await prisma.organizationMembership.count({
+ where: { orgId, role: Role.OWNER },
+ }),
+ ).toBe(1);
+ expect(await logs()).toHaveLength(1);
+ },
+ );
+
+ it.each(["create", "update", "delete"] as const)(
+ "rolls back %s when audit persistence fails",
+ async (operation) => {
+ const method = operation === "delete" ? "DELETE" : "PUT";
+ if (operation === "create") {
+ await prisma.organizationMembership.deleteMany({
+ where: { orgId, userId: memberId },
+ });
+ }
+ const before = await membership(memberId);
+ vi.spyOn(auditLogs, "auditLog").mockRejectedValueOnce(
+ new Error("audit unavailable"),
+ );
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method,
+ body: { userId: memberId, role: Role.ADMIN },
+ });
+ const handler =
+ method === "PUT" ? handleUpdateMembership : handleDeleteMembership;
+ await expect(
+ handler(req, res, orgId, apiKeyId, ownerContext),
+ ).rejects.toThrow("audit unavailable");
+ expect(await membership(memberId)).toEqual(before);
+ expect(await logs()).toEqual([]);
+ },
+ );
+
+ it("retains the committed mutation and audit when SFDC fails", async () => {
+ vi.spyOn(sfdc, "getSfdcService").mockImplementation(() => {
+ throw new Error("SFDC unavailable");
+ });
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "PUT",
+ body: { userId: memberId, role: Role.ADMIN },
+ });
+ await expect(
+ handleUpdateMembership(req, res, orgId, apiKeyId, ownerContext),
+ ).rejects.toThrow("SFDC unavailable");
+ expect((await membership(memberId))?.role).toBe(Role.ADMIN);
+ expect(await logs()).toHaveLength(1);
+ });
+});
+
+describe("Project membership safeguards", () => {
+ let orgId: string;
+ let projectId: string;
+ let userId: string;
+ let adminAuth: string;
+ let projectAdminAuth: string;
+ let legacyAuth: string;
+ let legacyKeyId: string;
+ let projectAdminKeyId: string;
+ let adminContext: AuthorizationContext;
+ const mutableEnv = env as {
+ API_AUTH_MIGRATION: typeof env.API_AUTH_MIGRATION;
+ };
+ const originalMode = env.API_AUTH_MIGRATION;
+
+ beforeEach(async () => {
+ mutableEnv.API_AUTH_MIGRATION = "enforce";
+ const org = await prisma.organization.create({
+ data: { name: randomUUID(), cloudConfig: { plan: "Team" } },
+ });
+ orgId = org.id;
+ const project = await prisma.project.create({
+ data: { name: randomUUID(), orgId },
+ });
+ projectId = project.id;
+ const user = await prisma.user.create({
+ data: {
+ email: `${randomUUID()}@example.com`,
+ organizationMemberships: { create: { orgId, role: Role.MEMBER } },
+ },
+ });
+ userId = user.id;
+ const key = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("ADMIN"),
+ createdBy: UserId(userId),
+ });
+ adminAuth = createBasicAuthHeader(key.publicKey, key.secretKey);
+ const authentication = await authenticator.authenticate({
+ headers: { authorization: adminAuth },
+ });
+ if (!authentication.success) throw authentication.error;
+ adminContext = authentication.context;
+ const projectKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("ADMIN"),
+ createdBy: UserId(userId),
+ });
+ projectAdminKeyId = projectKey.id;
+ projectAdminAuth = createBasicAuthHeader(
+ projectKey.publicKey,
+ projectKey.secretKey,
+ );
+ const legacyKey = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(userId),
+ });
+ legacyKeyId = legacyKey.id;
+ legacyAuth = createBasicAuthHeader(
+ legacyKey.publicKey,
+ legacyKey.secretKey,
+ );
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ mutableEnv.API_AUTH_MIGRATION = originalMode;
+ await prisma.auditLog.deleteMany({ where: { orgId } });
+ await prisma.organization.delete({ where: { id: orgId } });
+ await prisma.user.delete({ where: { id: userId } });
+ });
+
+ const membership = () =>
+ prisma.projectMembership.findUnique({
+ where: { projectId_userId: { projectId, userId } },
+ });
+ const logs = () =>
+ prisma.auditLog.findMany({
+ where: { projectId, resourceType: "projectMembership" },
+ orderBy: { createdAt: "asc" },
+ });
+ const request = async (
+ method: "PUT" | "DELETE",
+ role?: Role,
+ auth = adminAuth,
+ ) => {
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method,
+ query: { projectId },
+ headers: { authorization: auth },
+ body: { userId, role },
+ });
+ await projectMembershipRoute(req, res);
+ return res;
+ };
+ const createMembership = async (role: Role) => {
+ const orgMembership = await prisma.organizationMembership.findUniqueOrThrow(
+ {
+ where: { orgId_userId: { orgId, userId } },
+ },
+ );
+ return prisma.projectMembership.create({
+ data: { projectId, userId, orgMembershipId: orgMembership.id, role },
+ });
+ };
+
+ it("rejects ADMIN promotion to project OWNER", async () => {
+ expect((await request("PUT", Role.OWNER)).statusCode).toBe(403);
+ expect(await membership()).toBeNull();
+ expect(await logs()).toEqual([]);
+ });
+
+ it.each([
+ ["organization", "PUT", Role.ADMIN],
+ ["organization", "PUT", Role.OWNER],
+ ["organization", "DELETE", undefined],
+ ["project", "PUT", Role.ADMIN],
+ ["project", "PUT", Role.OWNER],
+ ["project", "DELETE", undefined],
+ ] as const)(
+ "rejects %s ADMIN owner %s to %s",
+ async (scope, method, role) => {
+ const before = await createMembership(Role.OWNER);
+ const auth = scope === "project" ? projectAdminAuth : adminAuth;
+ expect((await request(method, role, auth)).statusCode).toBe(403);
+ expect(await membership()).toEqual(before);
+ expect(await logs()).toEqual([]);
+ },
+ );
+
+ it.each(["legacy", "shadow"] as const)(
+ "enforces ownership and write grants in %s mode",
+ async (mode) => {
+ mutableEnv.API_AUTH_MIGRATION = mode;
+ expect((await request("PUT", Role.OWNER)).statusCode).toBe(403);
+ const viewer = await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("VIEWER"),
+ createdBy: UserId(userId),
+ });
+ const auth = createBasicAuthHeader(viewer.publicKey, viewer.secretKey);
+ expect((await request("PUT", Role.MEMBER, auth)).statusCode).toBe(403);
+ expect(await membership()).toBeNull();
+ expect(await logs()).toEqual([]);
+ },
+ );
+
+ it("allows ordinary project ADMIN mutations and attributes every audit to its caller", async () => {
+ expect(
+ (await request("PUT", Role.VIEWER, projectAdminAuth)).statusCode,
+ ).toBe(200);
+ const created = await membership();
+ expect(
+ (await request("PUT", Role.ADMIN, projectAdminAuth)).statusCode,
+ ).toBe(200);
+ const updated = await membership();
+ expect(
+ (await request("DELETE", undefined, projectAdminAuth)).statusCode,
+ ).toBe(200);
+ expect(await membership()).toBeNull();
+ const records = await logs();
+ expect(records.map(({ action }) => action)).toEqual([
+ "create",
+ "update",
+ "delete",
+ ]);
+ for (const record of records) {
+ expect(record).toMatchObject({
+ orgId,
+ projectId,
+ type: "API_KEY",
+ apiKeyId: projectAdminKeyId,
+ resourceId: `${projectId}--${userId}`,
+ });
+ }
+ const serialized = (value: unknown) => JSON.parse(JSON.stringify(value));
+ expect(JSON.parse(records[0]!.after!)).toEqual(serialized(created));
+ expect(JSON.parse(records[1]!.before!)).toEqual(serialized(created));
+ expect(JSON.parse(records[1]!.after!)).toEqual(serialized(updated));
+ expect(JSON.parse(records[2]!.before!)).toEqual(serialized(updated));
+ });
+
+ it.each(["legacy", "shadow", "enforce"] as const)(
+ "keeps legacy organization owner authority and permits zero direct project owners in %s mode",
+ async (mode) => {
+ mutableEnv.API_AUTH_MIGRATION = mode;
+ expect((await request("PUT", Role.OWNER, legacyAuth)).statusCode).toBe(
+ 200,
+ );
+ expect((await request("PUT", Role.OWNER, legacyAuth)).statusCode).toBe(
+ 200,
+ );
+ expect((await request("PUT", Role.MEMBER, legacyAuth)).statusCode).toBe(
+ 200,
+ );
+ expect((await request("PUT", Role.OWNER, legacyAuth)).statusCode).toBe(
+ 200,
+ );
+ expect((await request("DELETE", undefined, legacyAuth)).statusCode).toBe(
+ 200,
+ );
+ expect(await membership()).toBeNull();
+ expect(
+ (await logs()).every(({ apiKeyId }) => apiKeyId === legacyKeyId),
+ ).toBe(true);
+ },
+ );
+
+ it("combines membership and ownership policy grants across roles", async () => {
+ const context: AuthorizationContext = {
+ ...adminContext,
+ policies: (
+ [
+ ["VIEWER", "projectMembers:CUD"],
+ ["INGEST", "projectMembers:manageOwnership"],
+ ] as const
+ ).map(([role, action]) => ({
+ id: action,
+ roleId: SystemRoleId(role),
+ tenantId: OrganizationId(orgId),
+ effect: "ALLOW",
+ actions: [action],
+ resources: [ProjectId(projectId)],
+ })),
+ };
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "PUT",
+ body: { userId, role: Role.OWNER },
+ });
+ await handleUpdateProjectMembership(
+ req,
+ res,
+ projectId,
+ orgId,
+ projectAdminKeyId,
+ context,
+ );
+ expect(res.statusCode).toBe(200);
+ expect((await membership())?.role).toBe(Role.OWNER);
+ expect(await logs()).toHaveLength(1);
+ });
+
+ it.each(["create", "update", "delete"] as const)(
+ "rolls back project membership %s when audit persistence fails",
+ async (operation) => {
+ if (operation !== "create") await createMembership(Role.MEMBER);
+ const before = await membership();
+ vi.spyOn(auditLogs, "auditLog").mockRejectedValueOnce(
+ new Error("audit unavailable"),
+ );
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: operation === "delete" ? "DELETE" : "PUT",
+ body: { userId, role: Role.ADMIN },
+ });
+ const handler =
+ operation === "delete"
+ ? handleDeleteProjectMembership
+ : handleUpdateProjectMembership;
+ await expect(
+ handler(req, res, projectId, orgId, projectAdminKeyId, adminContext),
+ ).rejects.toThrow("audit unavailable");
+ expect(await membership()).toEqual(before);
+ expect(await logs()).toEqual([]);
+ },
+ );
+});
diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts
index 7fcc15fadf..950849fac8 100644
--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts
+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts
@@ -9,9 +9,26 @@ import { prisma } from "@langfuse/shared/src/db";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import { TRPCError } from "@trpc/server";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server";
+import { createApiKey } from "@langfuse/shared/src/server";
+import {
+ ApiKeyId,
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
+import { getRolesForPrincipal } from "@/src/features/rbac/getRolesForPrincipal";
+import { env } from "@/src/env.mjs";
import { randomUUID } from "crypto";
+vi.mock("@/src/env.mjs", async (importOriginal) => {
+ const actual = await importOriginal<{ env: typeof env }>();
+ return {
+ ...actual,
+ env: { ...actual.env, API_AUTH_MIGRATION: "enforce" },
+ };
+});
+
describe("organization API keys trpc", () => {
const organizationId = "seed-org-id";
@@ -169,7 +186,7 @@ describe("organization API keys trpc", () => {
// Create a test API key first
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Test API Key",
+ name: "Test API Key",
});
expect(apiKeyResult).toBeDefined();
@@ -189,11 +206,11 @@ describe("organization API keys trpc", () => {
});
it("filters in-app agent API keys", async () => {
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: organizationId,
- scope: "ORGANIZATION",
- note: "In-app agent key hidden from org UI",
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: OrganizationId(organizationId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId("user-1"),
+ name: "In-app agent key hidden from org UI",
isInAppAgentKey: true,
});
@@ -236,7 +253,7 @@ describe("organization API keys trpc", () => {
it("owner can create organization API keys", async () => {
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Test API Key",
+ name: "Test API Key",
});
expect(apiKeyResult).toBeDefined();
@@ -248,7 +265,7 @@ describe("organization API keys trpc", () => {
it("stores the creating user and returns it in the list", async () => {
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Key for creator attribution test",
+ name: "Key for creator attribution test",
});
const dbKey = await prisma.apiKey.findUniqueOrThrow({
@@ -265,11 +282,20 @@ describe("organization API keys trpc", () => {
expect(listedKey?.createdByApiKey).toBeNull();
});
+ it("rejects an expiration date in the past", async () => {
+ await expect(
+ ownerCaller.organizationApiKeys.create({
+ orgId: organizationId,
+ expiresAt: new Date(Date.now() - 60_000),
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ });
+
it("regular member cannot create organization API keys", async () => {
await expect(
memberCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Test API Key",
+ name: "Test API Key",
}),
).rejects.toThrow(TRPCError);
});
@@ -278,7 +304,7 @@ describe("organization API keys trpc", () => {
await expect(
adminCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Test API Key",
+ name: "Test API Key",
}),
).rejects.toThrow(TRPCError);
});
@@ -287,7 +313,7 @@ describe("organization API keys trpc", () => {
await expect(
unAuthedCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Test API Key",
+ name: "Test API Key",
}),
).rejects.toThrow(TRPCError);
});
@@ -295,12 +321,12 @@ describe("organization API keys trpc", () => {
it("owner on a plan without admin-api cannot create organization API keys", async () => {
// Unique note so the persistence assertion stays independent of other
// tests and of keys left behind by earlier runs.
- const note = `unentitled-create-${randomUUID()}`;
+ const name = `unentitled-create-${randomUUID()}`;
await expect(
unentitledOwnerCaller.organizationApiKeys.create({
orgId: organizationId,
- note,
+ name,
}),
).rejects.toThrow(
expect.objectContaining({
@@ -312,7 +338,9 @@ describe("organization API keys trpc", () => {
// The rejection must happen before the key is persisted, otherwise the
// plan gate would only hide a key that already works.
await expect(
- prisma.apiKey.findFirst({ where: { orgId: organizationId, note } }),
+ prisma.apiKey.findFirst({
+ where: { orgId: organizationId, note: name },
+ }),
).resolves.toBeNull();
});
@@ -320,7 +348,7 @@ describe("organization API keys trpc", () => {
const apiKeyResult = await entitledOwnerCaller.organizationApiKeys.create(
{
orgId: organizationId,
- note: "Entitled plan key",
+ name: "Entitled plan key",
},
);
@@ -329,19 +357,19 @@ describe("organization API keys trpc", () => {
});
});
- describe("organizationApiKeys.updateNote", () => {
+ describe("organizationApiKeys.updateName", () => {
it("owner can update API key note", async () => {
// Create a key first
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Original Note",
+ name: "Original Note",
});
// Update the note
- await ownerCaller.organizationApiKeys.updateNote({
+ await ownerCaller.organizationApiKeys.updateName({
orgId: organizationId,
keyId: apiKeyResult.id,
- note: "Updated Note",
+ name: "Updated Note",
});
// Fetch to verify
@@ -356,28 +384,28 @@ describe("organization API keys trpc", () => {
it("returns NOT_FOUND for a missing API key", async () => {
await expect(
- ownerCaller.organizationApiKeys.updateNote({
+ ownerCaller.organizationApiKeys.updateName({
orgId: organizationId,
keyId: randomUUID(),
- note: "Updated Note",
+ name: "Updated Note",
}),
).rejects.toMatchObject({ code: "NOT_FOUND" });
});
it("does not update in-app agent API keys", async () => {
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: organizationId,
- scope: "ORGANIZATION",
- note: "Original in-app agent note",
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: OrganizationId(organizationId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId("user-1"),
+ name: "Original in-app agent note",
isInAppAgentKey: true,
});
await expect(
- ownerCaller.organizationApiKeys.updateNote({
+ ownerCaller.organizationApiKeys.updateName({
orgId: organizationId,
keyId: inAppAgentKey.id,
- note: "Updated in-app agent note",
+ name: "Updated in-app agent note",
}),
).rejects.toThrow();
@@ -391,15 +419,15 @@ describe("organization API keys trpc", () => {
// Create a key as owner
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Original Note",
+ name: "Original Note",
});
// Try to update as member
await expect(
- memberCaller.organizationApiKeys.updateNote({
+ memberCaller.organizationApiKeys.updateName({
orgId: organizationId,
keyId: apiKeyResult.id,
- note: "Updated Note",
+ name: "Updated Note",
}),
).rejects.toThrow(TRPCError);
});
@@ -408,15 +436,15 @@ describe("organization API keys trpc", () => {
// Create a key as owner
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "Original Note",
+ name: "Original Note",
});
// Try to update as admin
await expect(
- adminCaller.organizationApiKeys.updateNote({
+ adminCaller.organizationApiKeys.updateName({
orgId: organizationId,
keyId: apiKeyResult.id,
- note: "Updated Note",
+ name: "Updated Note",
}),
).rejects.toThrow(TRPCError);
});
@@ -427,7 +455,7 @@ describe("organization API keys trpc", () => {
// Create a key first
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "To Be Deleted",
+ name: "To Be Deleted",
});
// Delete the key
@@ -455,10 +483,10 @@ describe("organization API keys trpc", () => {
});
it("does not delete in-app agent API keys", async () => {
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: organizationId,
- scope: "ORGANIZATION",
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: OrganizationId(organizationId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId("user-1"),
isInAppAgentKey: true,
});
@@ -478,7 +506,7 @@ describe("organization API keys trpc", () => {
// Create a key as owner
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "To Be Deleted",
+ name: "To Be Deleted",
});
// Try to delete as member
@@ -494,7 +522,7 @@ describe("organization API keys trpc", () => {
// Create a key as owner
const apiKeyResult = await ownerCaller.organizationApiKeys.create({
orgId: organizationId,
- note: "To Be Deleted",
+ name: "To Be Deleted",
});
// Try to delete as admin
@@ -510,11 +538,11 @@ describe("organization API keys trpc", () => {
// Only creation is plan-gated. A downgraded organization must keep the
// ability to see and revoke keys that were issued while entitled,
// otherwise a downgrade would strand live credentials.
- const existingKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: organizationId,
- scope: "ORGANIZATION",
- note: "Issued before downgrade",
+ const existingKey = await createApiKey(prisma, {
+ owner: OrganizationId(organizationId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId("user-1"),
+ name: "Issued before downgrade",
});
const apiKeys =
@@ -533,4 +561,93 @@ describe("organization API keys trpc", () => {
).resolves.toBeNull();
});
});
+
+ describe("organizationApiKeys.create role scoping", () => {
+ const ownerCallerForOrg = (orgId: string) =>
+ callerForSession({
+ expires: "1",
+ user: {
+ id: "user-1",
+ canCreateOrganizations: true,
+ name: "Demo User",
+ organizations: [
+ {
+ id: orgId,
+ name: "Scoped Org",
+ role: "OWNER",
+ plan: "cloud:team",
+ cloudConfig: undefined,
+ metadata: {},
+ projects: [] as SessionOrg["projects"],
+ } as SessionOrg,
+ ],
+ featureFlags: testFeatureFlags(),
+ admin: false,
+ },
+ environment: {} as any,
+ });
+
+ // An org key owns a single assignment on the organization, and the resolver
+ // expands that owner to the project-kind wildcard, so a project-capable role
+ // reaches every project of the org rather than a chosen subset.
+ it("creates an org key that reaches every project via the project wildcard", async () => {
+ const orgId = `org-${randomUUID()}`;
+ await prisma.organization.create({ data: { id: orgId, name: "Scoped" } });
+
+ const key = await ownerCallerForOrg(orgId).organizationApiKeys.create({
+ orgId,
+ role: "ADMIN",
+ });
+
+ const projectResources = (await getRolesForPrincipal(ApiKeyId(key.id)))
+ .flatMap((role) => role.policies)
+ .filter((policy) => policy.id.endsWith(":project"))
+ .flatMap((policy) => policy.resources);
+
+ expect(projectResources).toContain(ProjectId("*"));
+ });
+
+ it("rejects a legacy role under enforce", async () => {
+ const orgId = `org-${randomUUID()}`;
+ await prisma.organization.create({ data: { id: orgId, name: "Scoped" } });
+
+ await expect(
+ ownerCallerForOrg(orgId).organizationApiKeys.create({
+ orgId,
+ role: "LEGACY_ORGANIZATION_API_KEY",
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+
+ await expect(prisma.apiKey.count({ where: { orgId } })).resolves.toBe(0);
+ });
+
+ it("accepts only the LEGACY_ORGANIZATION_API_KEY role when enforce is off", async () => {
+ const orgId = `org-${randomUUID()}`;
+ await prisma.organization.create({ data: { id: orgId, name: "Scoped" } });
+
+ const originalMigration = (env as { API_AUTH_MIGRATION: string })
+ .API_AUTH_MIGRATION;
+ (env as { API_AUTH_MIGRATION: string }).API_AUTH_MIGRATION = "legacy";
+ try {
+ await expect(
+ ownerCallerForOrg(orgId).organizationApiKeys.create({
+ orgId,
+ role: "ADMIN",
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+
+ const key = await ownerCallerForOrg(orgId).organizationApiKeys.create({
+ orgId,
+ role: "LEGACY_ORGANIZATION_API_KEY",
+ });
+ const roleIds = (await getRolesForPrincipal(ApiKeyId(key.id))).map(
+ (role) => role.id,
+ );
+ expect(roleIds).toContain(SystemRoleId("LEGACY_ORGANIZATION_API_KEY"));
+ } finally {
+ (env as { API_AUTH_MIGRATION: string }).API_AUTH_MIGRATION =
+ originalMigration;
+ }
+ });
+ });
});
diff --git a/web/src/__tests__/server/organizations-api.servertest.ts b/web/src/__tests__/server/organizations-api.servertest.ts
index 9ffb0945e4..09529ac46a 100644
--- a/web/src/__tests__/server/organizations-api.servertest.ts
+++ b/web/src/__tests__/server/organizations-api.servertest.ts
@@ -6,9 +6,17 @@ import { prisma, type Prisma } from "@langfuse/shared/src/db";
import { z } from "zod";
import { randomUUID } from "crypto";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
} from "@langfuse/shared/src/server";
+import { assignRole } from "@langfuse/shared/rbac/server";
+import {
+ ApiKeyId,
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
// Schema for organization project response
const OrganizationProjectSchema = z.object({
@@ -45,7 +53,10 @@ const ApiKeyResponseSchema = z.object({
publicKey: z.string(),
secretKey: z.string(),
displaySecretKey: z.string(),
- note: z.string().optional().nullable(),
+ name: z.string().nullable(),
+ note: z.string().nullable(),
+ expiresAt: z.iso.datetime().nullable(),
+ role: z.string(),
});
// Schema for API key list response
@@ -56,7 +67,9 @@ const ApiKeyListSchema = z.object({
createdAt: z.iso.datetime(),
expiresAt: z.iso.datetime().nullable(),
lastUsedAt: z.iso.datetime().nullable(),
+ name: z.string().nullable(),
note: z.string().nullable(),
+ role: z.string().nullable(),
publicKey: z.string(),
displaySecretKey: z.string(),
}),
@@ -607,7 +620,11 @@ describe("Admin Organizations API", () => {
expect(response.status).toBe(200);
expect(Array.isArray(response.body.apiKeys)).toBe(true);
expect(response.body.apiKeys.length).toBeGreaterThan(0);
- expect(response.body.apiKeys[0].note).toBe("Test API Key");
+ expect(response.body.apiKeys[0]).toMatchObject({
+ name: "Test API Key",
+ note: "Test API Key",
+ role: null,
+ });
});
it("should return 404 when getting API keys for a non-existent organization", async () => {
@@ -628,7 +645,6 @@ describe("Admin Organizations API", () => {
let testOrgId: string;
beforeEach(async () => {
- // Create a test organization
const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;
const org = await prisma.organization.create({
data: { name: uniqueOrgName, metadata: { tier: "testing", users: 5 } },
@@ -650,6 +666,112 @@ describe("Admin Organizations API", () => {
});
});
+ it.each([
+ {
+ label: "omitted",
+ role: undefined,
+ expiresAt: undefined,
+ name: "Named key",
+ },
+ { label: "null", role: null, expiresAt: null, name: "Named key" },
+ { label: "empty", role: "", expiresAt: undefined, name: "" },
+ {
+ label: "explicit legacy",
+ name: undefined,
+ role: "LEGACY_ORGANIZATION_API_KEY",
+ expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
+ },
+ ])(
+ "provisions a key with $label role and lists its expiration",
+ async ({ role, expiresAt, name }) => {
+ const response = await makeAPICall<
+ z.infer<typeof ApiKeyResponseSchema>
+ >(
+ "POST",
+ `/api/admin/organizations/${testOrgId}/apiKeys`,
+ { name, role, expiresAt },
+ `Bearer ${ADMIN_API_KEY}`,
+ );
+ expect(response.status).toBe(201);
+ expect(response.body).toMatchObject({
+ name: name ?? null,
+ note: name ?? null,
+ expiresAt: expiresAt ?? null,
+ role: "LEGACY_ORGANIZATION_API_KEY",
+ });
+
+ const stored = await prisma.apiKey.findUniqueOrThrow({
+ where: { id: response.body.id },
+ include: { roleAssignments: true },
+ });
+ expect(stored.note).toBe(name ?? null);
+ expect(stored.expiresAt?.toISOString() ?? null).toBe(expiresAt ?? null);
+ expect(stored.roleAssignments).toMatchObject([
+ { systemRole: "LEGACY_ORGANIZATION_API_KEY" },
+ ]);
+
+ const listed = await makeAPICall<z.infer<typeof ApiKeyListSchema>>(
+ "GET",
+ `/api/admin/organizations/${testOrgId}/apiKeys`,
+ undefined,
+ `Bearer ${ADMIN_API_KEY}`,
+ );
+ expect(listed.status).toBe(200);
+ ApiKeyListSchema.parse(listed.body);
+ const listedKey = listed.body.apiKeys.find(
+ (key) => key.id === stored.id,
+ );
+ expect(listedKey).toMatchObject({
+ name: name ?? null,
+ note: name ?? null,
+ expiresAt: expiresAt ?? null,
+ role: "LEGACY_ORGANIZATION_API_KEY",
+ });
+ for (const field of [
+ "secretKey",
+ "hashedSecretKey",
+ "fastHashedSecretKey",
+ "roleAssignments",
+ ]) {
+ expect(listedKey).not.toHaveProperty(field);
+ }
+ },
+ );
+
+ it.each([
+ { label: "both name and note", body: { name: "same", note: "same" } },
+ { label: "empty name and note", body: { name: "", note: "" } },
+ { label: "empty name with note", body: { name: "", note: "alias" } },
+ { label: "name with empty note", body: { name: "name", note: "" } },
+ { label: "null name", body: { name: null } },
+ { label: "past expiration", body: { expiresAt: "2000-01-01T00:00:00Z" } },
+ { label: "invalid expiration", body: { expiresAt: "not-a-date" } },
+ { label: "numeric expiration", body: { expiresAt: 4_102_444_800_000 } },
+ {
+ label: "wrong-scope legacy role",
+ body: { role: "LEGACY_PROJECT_API_KEY" },
+ },
+ { label: "admin role", body: { role: "ADMIN" } },
+ { label: "viewer role", body: { role: "VIEWER" } },
+ { label: "ingest role", body: { role: "INGEST" } },
+ { label: "scores ingest role", body: { role: "SCORES_INGEST" } },
+ { label: "gateway role", body: { role: "AI_GATEWAY" } },
+ { label: "role array", body: { role: [] } },
+ ])("rejects $label without creating a key", async ({ body }) => {
+ const before = await prisma.apiKey.count({ where: { orgId: testOrgId } });
+ const result = await makeAPICall<{ error: string }>(
+ "POST",
+ `/api/admin/organizations/${testOrgId}/apiKeys`,
+ body,
+ `Bearer ${ADMIN_API_KEY}`,
+ );
+ expect(result.status).toBe(400);
+ expect(result.body.error).toEqual(expect.any(String));
+ expect(await prisma.apiKey.count({ where: { orgId: testOrgId } })).toBe(
+ before,
+ );
+ });
+
it("should create a new API key for an organization with valid admin authentication", async () => {
const response = await makeZodVerifiedAPICall(
ApiKeyResponseSchema,
@@ -666,6 +788,9 @@ describe("Admin Organizations API", () => {
expect(response.body.publicKey).toMatch(/^pk-lf-/);
expect(response.body.secretKey).toMatch(/^sk-lf-/);
expect(response.body.note).toBe("Test API Key");
+ expect(response.body.name).toBe("Test API Key");
+ expect(response.body.expiresAt).toBeNull();
+ expect(response.body.role).toBe("LEGACY_ORGANIZATION_API_KEY");
// Verify the API key was actually created in the database
const apiKey = await prisma.apiKey.findUnique({
@@ -674,6 +799,8 @@ describe("Admin Organizations API", () => {
expect(apiKey).not.toBeNull();
expect(apiKey?.orgId).toBe(testOrgId);
expect(apiKey?.scope).toBe("ORGANIZATION");
+ expect(apiKey?.createdByUserId).toBeNull();
+ expect(apiKey?.createdByApiKeyId).toBeNull();
});
it("should return 404 when creating an API key for a non-existent organization", async () => {
@@ -859,11 +986,14 @@ describe("Public Organizations API", () => {
testProject2Id = project2.id;
// Create an organization API key
- const apiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testOrgId,
- scope: "ORGANIZATION",
- note: "Test API Key for Organizations API",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const apiKey = await createApiKey(prisma, {
+ owner: OrganizationId(testOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Test API Key for Organizations API",
predefinedKeys: {
publicKey: `pk-lf-org-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-org-${randomUUID().substring(0, 8)}`,
@@ -928,11 +1058,14 @@ describe("Public Organizations API", () => {
it("should return 403 when using a project-scoped API key", async () => {
// Create a project API key
- const projectApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testProject1Id,
- scope: "PROJECT",
- note: "Test Project API Key",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const projectApiKey = await createApiKey(prisma, {
+ owner: ProjectId(testProject1Id),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Test Project API Key",
predefinedKeys: {
publicKey: `pk-lf-project-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-project-${randomUUID().substring(0, 8)}`,
@@ -1032,11 +1165,14 @@ describe("Public Organizations API", () => {
});
// Create API key for empty organization
- const emptyOrgApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: emptyOrg.id,
- scope: "ORGANIZATION",
- note: "Test API Key for Empty Org",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const emptyOrgApiKey = await createApiKey(prisma, {
+ owner: OrganizationId(emptyOrg.id),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Test API Key for Empty Org",
predefinedKeys: {
publicKey: `pk-lf-empty-${randomUUID().substring(0, 8)}`,
secretKey: `sk-lf-empty-${randomUUID().substring(0, 8)}`,
@@ -1117,29 +1253,47 @@ describe("Public Organizations API", () => {
});
testOrgId = org.id;
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+
// Create an organization API key for authentication
- const orgApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: testOrgId,
- note: "Org API Key for testing",
- scope: "ORGANIZATION",
+ const orgApiKey = await createApiKey(prisma, {
+ owner: OrganizationId(testOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Org API Key for testing",
});
testApiKey = orgApiKey.publicKey;
testApiSecretKey = orgApiKey.secretKey;
// Create additional organization API keys to list
- await createAndAddApiKeysToDb({
- prisma,
- entityId: testOrgId,
- note: "First test key",
- scope: "ORGANIZATION",
+ await createApiKey(prisma, {
+ owner: OrganizationId(testOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "First test key",
+ });
+
+ await createApiKey(prisma, {
+ owner: OrganizationId(testOrgId),
+ role: SystemRoleId("VIEWER"),
+ createdBy: UserId(keyCreator.id),
+ name: "Second test key",
});
- await createAndAddApiKeysToDb({
- prisma,
- entityId: testOrgId,
- note: "Second test key",
- scope: "ORGANIZATION",
+ const multiRoleKey = await createApiKey(prisma, {
+ owner: OrganizationId(testOrgId),
+ role: SystemRoleId("INGEST"),
+ createdBy: UserId(keyCreator.id),
+ name: "Multiple roles key",
+ });
+ await assignRole(prisma, {
+ tenantId: OrganizationId(testOrgId),
+ principalId: ApiKeyId(multiRoleKey.id),
+ roleId: SystemRoleId("VIEWER"),
+ ownerId: OrganizationId(testOrgId),
+ tags: [],
});
// Create second organization with its own API keys (for isolation test)
@@ -1152,11 +1306,11 @@ describe("Public Organizations API", () => {
});
secondOrgId = secondOrg.id;
- const secondOrgKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: secondOrgId,
- note: "Second org API key",
- scope: "ORGANIZATION",
+ const secondOrgKey = await createApiKey(prisma, {
+ owner: OrganizationId(secondOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Second org API key",
});
secondOrgApiKey = secondOrgKey.publicKey;
secondOrgApiSecretKey = secondOrgKey.secretKey;
@@ -1189,18 +1343,17 @@ describe("Public Organizations API", () => {
});
it("should successfully list organization API keys with valid org API key", async () => {
- const response = await makeZodVerifiedAPICall(
- ApiKeyListSchema,
+ const response = await makeAPICall<z.infer<typeof ApiKeyListSchema>>(
"GET",
`/api/public/organizations/apiKeys`,
undefined,
createBasicAuthHeader(testApiKey, testApiSecretKey),
- 200,
);
expect(response.status).toBe(200);
+ ApiKeyListSchema.parse(response.body);
expect(Array.isArray(response.body.apiKeys)).toBe(true);
- expect(response.body.apiKeys.length).toBe(3); // Auth key + 2 test keys
+ expect(response.body.apiKeys.length).toBe(4);
// Verify the structure of returned API keys
const apiKeys = response.body.apiKeys;
@@ -1213,6 +1366,31 @@ describe("Public Organizations API", () => {
expect(apiKeys[0]).toHaveProperty("displaySecretKey");
// Verify note values
+ for (const key of apiKeys) {
+ expect(key.name).toBe(key.note);
+ for (const field of [
+ "secretKey",
+ "hashedSecretKey",
+ "fastHashedSecretKey",
+ "roleAssignments",
+ ]) {
+ expect(key).not.toHaveProperty(field);
+ }
+ }
+ expect(apiKeys).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: "Org API Key for testing",
+ role: "LEGACY_ORGANIZATION_API_KEY",
+ }),
+ expect.objectContaining({
+ name: "First test key",
+ role: "LEGACY_ORGANIZATION_API_KEY",
+ }),
+ expect.objectContaining({ name: "Second test key", role: "VIEWER" }),
+ expect.objectContaining({ name: "Multiple roles key", role: null }),
+ ]),
+ );
const notes = apiKeys.map((key) => key.note);
expect(notes).toContain("Org API Key for testing");
expect(notes).toContain("First test key");
@@ -1250,11 +1428,14 @@ describe("Public Organizations API", () => {
},
});
- const projectApiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: project.id,
- note: "Project API key",
- scope: "PROJECT",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const projectApiKey = await createApiKey(prisma, {
+ owner: ProjectId(project.id),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: "Project API key",
});
const response = await makeAPICall<{ error: string }>(
diff --git a/web/src/__tests__/server/policy-auth.servertest.ts b/web/src/__tests__/server/policy-auth.servertest.ts
index 1536ea3f9a..69cd5ff540 100644
--- a/web/src/__tests__/server/policy-auth.servertest.ts
+++ b/web/src/__tests__/server/policy-auth.servertest.ts
@@ -4,9 +4,10 @@ import {
hashSecretKey,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
+import { OrganizationId, ProjectId } from "@langfuse/shared/rbac";
import { Authenticator } from "@/src/features/apiKey/server";
-import { authorize } from "@/src/features/auth/policy/authorize";
+import { authorize } from "@/src/features/rbac/authorize";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
describe("policy authenticate() composition", () => {
@@ -34,9 +35,12 @@ describe("policy authenticate() composition", () => {
if (!result.success) return;
expect(result.context.principal.kind).toBe("apiKey");
expect(
- authorize(result.context, "traces:read", {
- projectId: fixture.projectId,
- }).success,
+ authorize(
+ result.context,
+ OrganizationId(fixture.orgId),
+ "traces:read",
+ ProjectId(fixture.projectId),
+ ).success,
).toBe(true);
});
@@ -46,9 +50,12 @@ describe("policy authenticate() composition", () => {
expect(result.success).toBe(true);
if (!result.success) return;
expect(
- authorize(result.context, "traces:read", {
- projectId: fixture.projectId,
- }).success,
+ authorize(
+ result.context,
+ OrganizationId(fixture.orgId),
+ "traces:read",
+ ProjectId(fixture.projectId),
+ ).success,
).toBe(true);
});
@@ -57,14 +64,20 @@ describe("policy authenticate() composition", () => {
expect(result.success).toBe(true);
if (!result.success) return;
expect(
- authorize(result.context, "scores:create", {
- projectId: fixture.projectId,
- }).success,
+ authorize(
+ result.context,
+ OrganizationId(fixture.orgId),
+ "scores:save",
+ ProjectId(fixture.projectId),
+ ).success,
).toBe(true);
expect(
- authorize(result.context, "traces:read", {
- projectId: fixture.projectId,
- }).success,
+ authorize(
+ result.context,
+ OrganizationId(fixture.orgId),
+ "traces:read",
+ ProjectId(fixture.projectId),
+ ).success,
).toBe(false);
});
diff --git a/web/src/__tests__/server/project-api-key-trpc.servertest.ts b/web/src/__tests__/server/project-api-key-trpc.servertest.ts
index 663d734053..6f8f2c3c13 100644
--- a/web/src/__tests__/server/project-api-key-trpc.servertest.ts
+++ b/web/src/__tests__/server/project-api-key-trpc.servertest.ts
@@ -4,11 +4,21 @@ import { prisma } from "@langfuse/shared/src/db";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
+import { env } from "@/src/env.mjs";
import { randomUUID } from "crypto";
+vi.mock("@/src/env.mjs", async (importOriginal) => {
+ const actual = await importOriginal<{ env: typeof env }>();
+ return {
+ ...actual,
+ env: { ...actual.env, API_AUTH_MIGRATION: "enforce" },
+ };
+});
+
describe("project API keys trpc", () => {
// 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).
@@ -78,11 +88,11 @@ describe("project API keys trpc", () => {
it("filters in-app agent API keys", async () => {
const { caller, projectId } = await createProjectCaller();
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "In-app agent key hidden from project UI",
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId("user-1"),
+ name: "In-app agent key hidden from project UI",
isInAppAgentKey: true,
});
@@ -112,7 +122,7 @@ describe("project API keys trpc", () => {
const apiKeyResult = await caller.projectApiKeys.create({
projectId,
- note: "Key for creator attribution test",
+ name: "Key for creator attribution test",
});
const dbKey = await prisma.apiKey.findUniqueOrThrow({
@@ -130,13 +140,24 @@ describe("project API keys trpc", () => {
expect(listedKey?.createdByApiKey).toBeNull();
});
+ it("rejects an expiration date in the past", async () => {
+ const { caller, projectId } = await createProjectCaller();
+
+ await expect(
+ caller.projectApiKeys.create({
+ projectId,
+ expiresAt: new Date(Date.now() - 60_000),
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ });
+
it("rejects users without apiKeys:CUD access", async () => {
const { caller, projectId } = await createProjectCaller("MEMBER");
await expect(
caller.projectApiKeys.create({
projectId,
- note: "Unauthorized migration key",
+ name: "Unauthorized migration key",
}),
).rejects.toMatchObject({ code: "FORBIDDEN" });
@@ -146,36 +167,103 @@ describe("project API keys trpc", () => {
}),
).resolves.toBe(0);
});
+
+ // A project key whose role grants no project-kind actions (e.g. the
+ // org-only AI Gateway role) would grant nothing on the project it is
+ // scoped to, so it is not among the roles the create input accepts.
+ it("rejects an organization-only role on a project key", async () => {
+ const { caller, projectId } = await createProjectCaller();
+
+ await expect(
+ caller.projectApiKeys.create({
+ projectId,
+ name: "org-only role on project key",
+ role: "AI_GATEWAY",
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+
+ await expect(
+ prisma.apiKey.count({
+ where: { projectId, note: "org-only role on project key" },
+ }),
+ ).resolves.toBe(0);
+ });
+
+ it("creates a project key with a project-capable role", async () => {
+ const { caller, projectId } = await createProjectCaller();
+
+ const key = await caller.projectApiKeys.create({
+ projectId,
+ name: "viewer project key",
+ role: "VIEWER",
+ });
+
+ const assignment = await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: key.id },
+ });
+ expect(assignment.systemRole).toBe("VIEWER");
+ expect(assignment.ownerProjectId).toBe(projectId);
+ });
+
+ it("accepts only the LEGACY_PROJECT_API_KEY role when enforce is off", async () => {
+ const { caller, projectId } = await createProjectCaller();
+
+ const originalMigration = (env as { API_AUTH_MIGRATION: string })
+ .API_AUTH_MIGRATION;
+ (env as { API_AUTH_MIGRATION: string }).API_AUTH_MIGRATION = "legacy";
+ try {
+ await expect(
+ caller.projectApiKeys.create({
+ projectId,
+ name: "normal role off enforce",
+ role: "VIEWER",
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+
+ const key = await caller.projectApiKeys.create({
+ projectId,
+ name: "legacy role off enforce",
+ role: "LEGACY_PROJECT_API_KEY",
+ });
+ const assignment = await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: key.id },
+ });
+ expect(assignment.systemRole).toBe("LEGACY_PROJECT_API_KEY");
+ } finally {
+ (env as { API_AUTH_MIGRATION: string }).API_AUTH_MIGRATION =
+ originalMigration;
+ }
+ });
});
- describe("projectApiKeys.updateNote", () => {
+ describe("projectApiKeys.updateName", () => {
it("returns NOT_FOUND for a missing API key", async () => {
const { caller, projectId } = await createProjectCaller();
await expect(
- caller.projectApiKeys.updateNote({
+ caller.projectApiKeys.updateName({
projectId,
keyId: randomUUID(),
- note: "Updated Note",
+ name: "Updated Note",
}),
).rejects.toMatchObject({ code: "NOT_FOUND" });
});
it("does not update in-app agent API keys", async () => {
const { caller, projectId } = await createProjectCaller();
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "Original in-app agent note",
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId("user-1"),
+ name: "Original in-app agent note",
isInAppAgentKey: true,
});
await expect(
- caller.projectApiKeys.updateNote({
+ caller.projectApiKeys.updateName({
projectId,
keyId: inAppAgentKey.id,
- note: "Updated in-app agent note",
+ name: "Updated in-app agent note",
}),
).rejects.toThrow();
@@ -186,6 +274,41 @@ describe("project API keys trpc", () => {
});
});
+ describe("system role assignments", () => {
+ it("writes a LEGACY_PROJECT_API_KEY assignment on create and revokes it on delete", async () => {
+ const { caller, projectId } = await createProjectCaller();
+
+ const key = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId("user-1"),
+ name: "Key for role assignment test",
+ });
+
+ const project = await prisma.project.findUniqueOrThrow({
+ where: { id: projectId },
+ select: { orgId: true },
+ });
+
+ const assignment = await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: key.id },
+ });
+ expect(assignment.systemRole).toBe("LEGACY_PROJECT_API_KEY");
+ expect(assignment.ownerProjectId).toBe(projectId);
+ expect(assignment.orgId).toBe(project.orgId);
+
+ await expect(
+ caller.projectApiKeys.delete({ projectId, id: key.id }),
+ ).resolves.toBe(true);
+
+ await expect(
+ prisma.roleAssignment.count({
+ where: { principalApiKeyId: key.id },
+ }),
+ ).resolves.toBe(0);
+ });
+ });
+
describe("projectApiKeys.delete", () => {
it("returns NOT_FOUND for a missing API key", async () => {
const { caller, projectId } = await createProjectCaller();
@@ -200,10 +323,10 @@ describe("project API keys trpc", () => {
it("does not delete in-app agent API keys", async () => {
const { caller, projectId } = await createProjectCaller();
- const inAppAgentKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
+ const inAppAgentKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId("user-1"),
isInAppAgentKey: true,
});
diff --git a/web/src/__tests__/server/projects-api.servertest.ts b/web/src/__tests__/server/projects-api.servertest.ts
index e7f7b8d77e..840560c964 100644
--- a/web/src/__tests__/server/projects-api.servertest.ts
+++ b/web/src/__tests__/server/projects-api.servertest.ts
@@ -4,11 +4,22 @@ import {
} from "@/src/__tests__/test-utils";
import { z } from "zod";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
+ invalidateCachedOrgApiKeys,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
import { randomUUID } from "crypto";
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { createMocks } from "node-mocks-http";
+import projectApiKeysHandler from "@/src/pages/api/public/projects/[projectId]/apiKeys";
+import projectApiKeyHandler from "@/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId]";
// Schema for project response
const ProjectResponseSchema = z.object({
@@ -56,7 +67,9 @@ const ApiKeysResponseSchema = z.object({
createdAt: z.string().or(z.date()),
expiresAt: z.string().or(z.date()).nullable(),
lastUsedAt: z.string().or(z.date()).nullable(),
+ name: z.string().nullable(),
note: z.string().nullable(),
+ role: z.string().nullable(),
publicKey: z.string(),
displaySecretKey: z.string().nullable(),
}),
@@ -69,9 +82,11 @@ const ApiKeyCreationResponseSchema = z.object({
publicKey: z.string(),
secretKey: z.string(),
displaySecretKey: z.string(),
+ name: z.string().nullable(),
note: z.string().nullable(),
+ role: z.string(),
createdAt: z.string().or(z.date()),
- expiresAt: z.string().or(z.date()).optional(),
+ expiresAt: z.iso.datetime().nullable(),
});
// Schema for API key deletion response
@@ -90,16 +105,22 @@ describe("Projects API", () => {
const orgApiKey = `pk-lf-org-${randomUUID().substring(0, 8)}`;
const orgSecretKey = `sk-lf-org-${randomUUID().substring(0, 8)}`;
+ let orgApiKeyId: string;
+
beforeAll(async () => {
- await createAndAddApiKeysToDb({
- prisma,
- entityId: "seed-org-id",
- scope: "ORGANIZATION",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const orgKey = await createApiKey(prisma, {
+ owner: OrganizationId("seed-org-id"),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
predefinedKeys: {
publicKey: orgApiKey,
secretKey: orgSecretKey,
},
});
+ orgApiKeyId = orgKey.id;
});
describe("GET /api/public/projects", () => {
@@ -147,26 +168,6 @@ describe("Projects API", () => {
expect(result.status).toBe(405);
expect(result.body.message).toContain("Method not allowed");
});
-
- it("should handle different authentication formats", async () => {
- // Test with Bearer token format
- const bearerResult = await makeAPICall<{ message: string }>(
- "GET",
- "/api/public/projects",
- undefined,
- `Bearer ${projectSecretKey}`,
- );
- expect(bearerResult.status).toBe(401);
-
- // Test with just the secret key (no Bearer prefix)
- const secretKeyResult = await makeAPICall<{ message: string }>(
- "GET",
- "/api/public/projects",
- undefined,
- projectSecretKey,
- );
- expect(secretKeyResult.status).toBe(401);
- });
});
describe("POST /api/public/projects", () => {
@@ -444,6 +445,9 @@ describe("Projects API", () => {
},
});
testProjectId = project.id;
+ // The raw create bypasses the invalidation real create paths run, so the
+ // org key's cached context would keep a projectIds snapshot without it.
+ await invalidateCachedOrgApiKeys("seed-org-id");
});
afterEach(async () => {
@@ -693,6 +697,9 @@ describe("Projects API", () => {
},
});
testProjectId = project.id;
+ // The raw create bypasses the invalidation real create paths run, so the
+ // org key's cached context would keep a projectIds snapshot without it.
+ await invalidateCachedOrgApiKeys("seed-org-id");
});
afterEach(async () => {
@@ -843,6 +850,137 @@ describe("Projects API", () => {
}
});
+ it("attributes project-key creation to the authenticating API key", async () => {
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ query: { projectId },
+ headers: {
+ authorization: createBasicAuthHeader(orgApiKey, orgSecretKey),
+ },
+ body: { note: "Audit attribution" },
+ });
+
+ await projectApiKeysHandler(req, res);
+ expect(res._getStatusCode()).toBe(201);
+ createdApiKeyId = res._getJSONData().id;
+
+ const audit = await prisma.auditLog.findFirstOrThrow({
+ where: { projectId, resourceId: createdApiKeyId, action: "create" },
+ });
+ expect(audit).toMatchObject({
+ apiKeyId: orgApiKeyId,
+ orgId: "seed-org-id",
+ projectId,
+ resourceType: "apiKey",
+ resourceId: createdApiKeyId,
+ });
+ });
+
+ it.each([
+ {
+ label: "omitted",
+ role: undefined,
+ expiresAt: undefined,
+ name: "Named key",
+ },
+ { label: "null", role: null, expiresAt: null, name: "Named key" },
+ { label: "empty", role: "", expiresAt: undefined, name: "" },
+ {
+ label: "explicit legacy",
+ name: undefined,
+ role: "LEGACY_PROJECT_API_KEY",
+ expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
+ },
+ ])(
+ "provisions a key with $label role and lists its expiration",
+ async ({ role, expiresAt, name }) => {
+ const response = await makeAPICall<
+ z.infer<typeof ApiKeyCreationResponseSchema>
+ >(
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ { name, role, expiresAt },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ createdApiKeyId = response.body.id;
+ expect(response.status).toBe(201);
+ expect(response.body).toMatchObject({
+ name: name ?? null,
+ note: name ?? null,
+ expiresAt: expiresAt ?? null,
+ role: "LEGACY_PROJECT_API_KEY",
+ });
+
+ const stored = await prisma.apiKey.findUniqueOrThrow({
+ where: { id: response.body.id },
+ include: { roleAssignments: true },
+ });
+ expect(stored.note).toBe(name ?? null);
+ expect(stored.expiresAt?.toISOString() ?? null).toBe(expiresAt ?? null);
+ expect(stored.roleAssignments).toMatchObject([
+ { systemRole: "LEGACY_PROJECT_API_KEY" },
+ ]);
+
+ const listed = await makeAPICall<z.infer<typeof ApiKeysResponseSchema>>(
+ "GET",
+ `/api/public/projects/${projectId}/apiKeys`,
+ undefined,
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(listed.status).toBe(200);
+ ApiKeysResponseSchema.parse(listed.body);
+ const listedKey = listed.body.apiKeys.find(
+ (key) => key.id === stored.id,
+ );
+ expect(listedKey).toMatchObject({
+ name: name ?? null,
+ note: name ?? null,
+ expiresAt: expiresAt ?? null,
+ role: "LEGACY_PROJECT_API_KEY",
+ });
+ for (const field of [
+ "secretKey",
+ "hashedSecretKey",
+ "fastHashedSecretKey",
+ "roleAssignments",
+ ]) {
+ expect(listedKey).not.toHaveProperty(field);
+ }
+ },
+ );
+
+ it.each([
+ { label: "both name and note", body: { name: "same", note: "same" } },
+ { label: "empty name and note", body: { name: "", note: "" } },
+ { label: "empty name with note", body: { name: "", note: "alias" } },
+ { label: "name with empty note", body: { name: "name", note: "" } },
+ { label: "null name", body: { name: null } },
+ { label: "past expiration", body: { expiresAt: "2000-01-01T00:00:00Z" } },
+ { label: "invalid expiration", body: { expiresAt: "not-a-date" } },
+ { label: "numeric expiration", body: { expiresAt: 4_102_444_800_000 } },
+ {
+ label: "wrong-scope legacy role",
+ body: { role: "LEGACY_ORGANIZATION_API_KEY" },
+ },
+ { label: "admin role", body: { role: "ADMIN" } },
+ { label: "viewer role", body: { role: "VIEWER" } },
+ { label: "ingest role", body: { role: "INGEST" } },
+ { label: "scores ingest role", body: { role: "SCORES_INGEST" } },
+ { label: "gateway role", body: { role: "AI_GATEWAY" } },
+ { label: "role array", body: { role: [] } },
+ ])("rejects $label without creating a key", async ({ body }) => {
+ const before = await prisma.apiKey.count({ where: { projectId } });
+ const result = await makeAPICall<{ message: string }>(
+ "POST",
+ `/api/public/projects/${projectId}/apiKeys`,
+ body,
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(result.status).toBe(400);
+ expect(result.body.message).toEqual(expect.any(String));
+ expect(await prisma.apiKey.count({ where: { projectId } })).toBe(before);
+ });
+
it("should create a new API key with valid organization API key", async () => {
const note = `Test API Key ${randomUUID().substring(0, 8)}`;
@@ -862,6 +1000,9 @@ describe("Projects API", () => {
expect(response.body).toHaveProperty("publicKey");
expect(response.body).toHaveProperty("secretKey");
expect(response.body.note).toBe(note);
+ expect(response.body.name).toBe(note);
+ expect(response.body.expiresAt).toBeNull();
+ expect(response.body.role).toBe("LEGACY_PROJECT_API_KEY");
// Store the created API key ID for cleanup
createdApiKeyId = response.body.id;
@@ -1088,11 +1229,14 @@ describe("Projects API", () => {
beforeEach(async () => {
// Create a test API key to delete
- const apiKeyMeta = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: `Delete Test API Key ${randomUUID().substring(0, 8)}`,
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const apiKeyMeta = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(keyCreator.id),
+ name: `Delete Test API Key ${randomUUID().substring(0, 8)}`,
});
deleteTestApiKeyId = apiKeyMeta.id;
});
@@ -1110,6 +1254,33 @@ describe("Projects API", () => {
}
});
+ it("attributes project-key deletion to the authenticating API key", async () => {
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "DELETE",
+ query: { projectId, apiKeyId: deleteTestApiKeyId },
+ headers: {
+ authorization: createBasicAuthHeader(orgApiKey, orgSecretKey),
+ },
+ });
+
+ await projectApiKeyHandler(req, res);
+ expect(res._getStatusCode()).toBe(200);
+ expect(
+ await prisma.apiKey.findUnique({ where: { id: deleteTestApiKeyId } }),
+ ).toBeNull();
+
+ const audit = await prisma.auditLog.findFirstOrThrow({
+ where: { projectId, resourceId: deleteTestApiKeyId, action: "delete" },
+ });
+ expect(audit).toMatchObject({
+ apiKeyId: orgApiKeyId,
+ orgId: "seed-org-id",
+ projectId,
+ resourceType: "apiKey",
+ resourceId: deleteTestApiKeyId,
+ });
+ });
+
it("should delete an API key with valid organization API key", async () => {
const response = await makeZodVerifiedAPICall(
ApiKeyDeletionResponseSchema,
diff --git a/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts b/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts
index 420ff528d5..6f31cf2f56 100644
--- a/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts
+++ b/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts
@@ -13,6 +13,9 @@ vi.mock("@/src/ee/features/billing/server/chb/chbProjectEvents", () => ({
emitChbProjectEvent: mocks.emit,
}));
+import { createApiKey } from "@langfuse/shared/src/server";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
+import { getRoleAssignmentsForPrincipal } from "@langfuse/shared/rbac/server";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
@@ -175,3 +178,92 @@ describe("projectsRouter CHB project lifecycle events", () => {
});
});
});
+
+describe("projectsRouter system role assignments", () => {
+ it("preserves user permissions while deleting project keys on soft deletion", async () => {
+ const orgId = await createOrg("Assignment Delete Org");
+ const projectId = await createProject(orgId);
+ const user = await createUserInOrgs([orgId]);
+ const caller = makeCaller({ userId: user.id, orgIds: [orgId], projectId });
+
+ const key = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ });
+
+ await expect(
+ prisma.roleAssignment.count({
+ where: { principalApiKeyId: key.id },
+ }),
+ ).resolves.toBe(1);
+
+ const assignment = await prisma.roleAssignment.create({
+ data: {
+ orgId,
+ principalUserId: user.id,
+ ownerProjectId: projectId,
+ systemRole: "VIEWER",
+ },
+ });
+
+ await caller.projects.delete({ projectId });
+
+ await expect(
+ prisma.roleAssignment.count({
+ where: { principalApiKeyId: key.id },
+ }),
+ ).resolves.toBe(0);
+ await expect(
+ prisma.roleAssignment.findUnique({ where: { id: assignment.id } }),
+ ).resolves.toEqual(assignment);
+ await expect(
+ prisma.project.findUnique({ where: { id: projectId } }),
+ ).resolves.toMatchObject({ deletedAt: expect.any(Date) });
+
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { deletedAt: null },
+ });
+ await expect(
+ getRoleAssignmentsForPrincipal(prisma, UserId(user.id)),
+ ).resolves.toEqual([
+ expect.objectContaining({
+ id: assignment.id,
+ ownerProjectId: projectId,
+ systemRole: "VIEWER",
+ }),
+ ]);
+ });
+
+ it("re-tags a project key's assignment orgId on transfer", async () => {
+ const sourceOrgId = await createOrg("Assignment Source Org");
+ const targetOrgId = await createOrg("Assignment Target Org");
+ const projectId = await createProject(sourceOrgId);
+ const user = await createUserInOrgs([sourceOrgId, targetOrgId]);
+ const caller = makeCaller({
+ userId: user.id,
+ orgIds: [sourceOrgId, targetOrgId],
+ projectId,
+ });
+
+ const key = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ });
+
+ const before = await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: key.id },
+ });
+ expect(before.orgId).toBe(sourceOrgId);
+
+ await caller.projects.transfer({ projectId, targetOrgId });
+
+ const after = await prisma.roleAssignment.findFirstOrThrow({
+ where: { principalApiKeyId: key.id },
+ });
+ expect(after.orgId).toBe(targetOrgId);
+ expect(after.ownerProjectId).toBe(projectId);
+ });
+});
diff --git a/web/src/__tests__/server/prompts.v2.servertest.ts b/web/src/__tests__/server/prompts.v2.servertest.ts
index a7ccfc8a53..075224c335 100644
--- a/web/src/__tests__/server/prompts.v2.servertest.ts
+++ b/web/src/__tests__/server/prompts.v2.servertest.ts
@@ -15,7 +15,7 @@ import { nanoid } from "nanoid";
import { type PromptsMetaResponse } from "@/src/features/prompts/server/actions/getPromptsMeta";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
createOrgProjectAndApiKey,
getObservationById,
@@ -24,6 +24,7 @@ import {
PromptService,
redis,
} from "@langfuse/shared/src/server";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import {
createUserWithOrgRole,
protectPromptLabel,
@@ -3353,12 +3354,11 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {
orgId,
role: Role.MEMBER,
});
- const apiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
+ const apiKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(userId),
isInAppAgentKey: true,
- createdByUserId: userId,
});
const name = "deleteProtectedAgent" + uuidv4();
await prisma.prompt.create({
@@ -3440,12 +3440,11 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {
orgId,
role: Role.MEMBER,
});
- const apiKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
+ const apiKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(userId),
isInAppAgentKey: true,
- createdByUserId: userId,
});
const name = "deleteUnlabeledSibling" + uuidv4();
await prisma.prompt.createMany({
diff --git a/web/src/__tests__/server/public-api-auth-parity.servertest.ts b/web/src/__tests__/server/public-api-auth-parity.servertest.ts
index 2c6fb4b798..a733cfd128 100644
--- a/web/src/__tests__/server/public-api-auth-parity.servertest.ts
+++ b/web/src/__tests__/server/public-api-auth-parity.servertest.ts
@@ -1,5 +1,6 @@
import { readdirSync } from "node:fs";
import path from "node:path";
+import { randomUUID } from "node:crypto";
import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
@@ -7,10 +8,16 @@ import { createMocks } from "node-mocks-http";
import { env } from "@/src/env.mjs";
import { prisma } from "@langfuse/shared/src/db";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
// Pins the public-API authorization seam to legacy: sweeps every route across
// migration modes and key kinds, recording each cell's status. Shadow and
@@ -346,17 +353,23 @@ describe("public-api auth parity", () => {
fixtureProjectId = base.projectId;
keys.project = { publicKey: base.publicKey, secretKey: base.secretKey };
- const org = await createAndAddApiKeysToDb({
- prisma,
- entityId: base.orgId,
- scope: "ORGANIZATION",
+ const orgKeyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const org = await createApiKey(prisma, {
+ owner: OrganizationId(base.orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(orgKeyCreator.id),
});
keys.org = { publicKey: org.publicKey, secretKey: org.secretKey };
- const agent = await createAndAddApiKeysToDb({
- prisma,
- entityId: base.projectId,
- scope: "PROJECT",
+ const agentKeyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ const agent = await createApiKey(prisma, {
+ owner: ProjectId(base.projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(agentKeyCreator.id),
isInAppAgentKey: true,
});
keys.agent = { publicKey: agent.publicKey, secretKey: agent.secretKey };
diff --git a/web/src/__tests__/server/roleAssignmentRepository.servertest.ts b/web/src/__tests__/server/roleAssignmentRepository.servertest.ts
new file mode 100644
index 0000000000..bdcf36a282
--- /dev/null
+++ b/web/src/__tests__/server/roleAssignmentRepository.servertest.ts
@@ -0,0 +1,352 @@
+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/scim-api.servertest.ts b/web/src/__tests__/server/scim-api.servertest.ts
index 389e012696..a3cbf84b99 100644
--- a/web/src/__tests__/server/scim-api.servertest.ts
+++ b/web/src/__tests__/server/scim-api.servertest.ts
@@ -4,10 +4,11 @@ import {
} from "@/src/__tests__/test-utils";
import { z } from "zod";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
createBasicAuthHeader,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
+import { OrganizationId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import { randomUUID } from "crypto";
// Schema for SCIM User response
@@ -141,10 +142,13 @@ describe("SCIM API", () => {
let testUserId: string;
beforeAll(async () => {
- await createAndAddApiKeysToDb({
- prisma,
- entityId: orgId,
- scope: "ORGANIZATION",
+ const keyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ await createApiKey(prisma, {
+ owner: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(keyCreator.id),
predefinedKeys: {
publicKey: orgApiKey,
secretKey: orgSecretKey,
@@ -1307,10 +1311,10 @@ describe("SCIM API", () => {
scopedOrgPublicKey = `pk-lf-org-${randomUUID().substring(0, 8)}`;
scopedOrgSecretKey = `sk-lf-org-${randomUUID().substring(0, 8)}`;
- await createAndAddApiKeysToDb({
- prisma,
- entityId: scopedOrgId,
- scope: "ORGANIZATION",
+ await createApiKey(prisma, {
+ owner: OrganizationId(scopedOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(owner.id),
predefinedKeys: {
publicKey: scopedOrgPublicKey,
secretKey: scopedOrgSecretKey,
@@ -1648,10 +1652,13 @@ describe("SCIM API", () => {
hobbyOrgId = hobbyOrg.id;
hobbyPublicKey = `pk-lf-org-${randomUUID().substring(0, 8)}`;
hobbySecretKey = `sk-lf-org-${randomUUID().substring(0, 8)}`;
- await createAndAddApiKeysToDb({
- prisma,
- entityId: hobbyOrgId,
- scope: "ORGANIZATION",
+ const hobbyKeyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ await createApiKey(prisma, {
+ owner: OrganizationId(hobbyOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(hobbyKeyCreator.id),
predefinedKeys: {
publicKey: hobbyPublicKey,
secretKey: hobbySecretKey,
@@ -1669,10 +1676,13 @@ describe("SCIM API", () => {
teamOrgId = teamOrg.id;
teamPublicKey = `pk-lf-org-${randomUUID().substring(0, 8)}`;
teamSecretKey = `sk-lf-org-${randomUUID().substring(0, 8)}`;
- await createAndAddApiKeysToDb({
- prisma,
- entityId: teamOrgId,
- scope: "ORGANIZATION",
+ const teamKeyCreator = await prisma.user.create({
+ data: { email: `apikey-creator-${randomUUID()}@example.com` },
+ });
+ await createApiKey(prisma, {
+ owner: OrganizationId(teamOrgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: UserId(teamKeyCreator.id),
predefinedKeys: {
publicKey: teamPublicKey,
secretKey: teamSecretKey,
diff --git a/web/src/__tests__/server/shadowAuth.servertest.ts b/web/src/__tests__/server/shadowAuth.servertest.ts
index 1435f30b75..b117b979b4 100644
--- a/web/src/__tests__/server/shadowAuth.servertest.ts
+++ b/web/src/__tests__/server/shadowAuth.servertest.ts
@@ -9,15 +9,17 @@ import {
createShaHash,
getDisplaySecretKey,
} from "@langfuse/shared/src/server";
-
-import { env } from "@/src/env.mjs";
-import { authorize } from "@/src/features/auth/policy/authorize";
-import { type ShadowAuthParams } from "@/src/features/public-api/server";
import {
- type AuthorizationContext,
+ OrganizationId,
+ ProjectId,
type OrganizationAction,
type ProjectAction,
-} from "@/src/features/auth/policy/types";
+} from "@langfuse/shared/rbac";
+
+import { env } from "@/src/env.mjs";
+import { authorize } from "@/src/features/rbac/authorize";
+import { type ShadowAuthParams } from "@/src/features/public-api/server";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
// The seam is imported dynamically so the authenticator singleton captures
// the admin key set in beforeAll.
@@ -43,6 +45,7 @@ let authenticator: Authenticator;
let orgId = "";
let projectId = "";
let foreignProjectId = "";
+let foreignOrgId = "";
let orgAuth = "";
let projectAuth = "";
let projectPublicKey = "";
@@ -131,9 +134,10 @@ const scopeOf = (result: ShadowResult): Record<string, unknown> => {
const createOrgApiKey = async (targetOrgId: string) => {
const publicKey = `pk-lf-${randomUUID()}`;
const secretKey = `sk-lf-${randomUUID()}`;
+ const apiKeyRowId = randomUUID();
await prisma.apiKey.create({
data: {
- id: randomUUID(),
+ id: apiKeyRowId,
orgId: targetOrgId,
publicKey,
hashedSecretKey: `test-hashed-secret-key-${randomUUID()}`,
@@ -142,6 +146,14 @@ const createOrgApiKey = async (targetOrgId: string) => {
scope: "ORGANIZATION",
},
});
+ await prisma.roleAssignment.create({
+ data: {
+ orgId: targetOrgId,
+ principalApiKeyId: apiKeyRowId,
+ systemRole: "LEGACY_ORGANIZATION_API_KEY",
+ ownerOrgId: targetOrgId,
+ },
+ });
return createBasicAuthHeader(publicKey, secretKey);
};
@@ -192,6 +204,7 @@ describe("shadowAuth maps principals to legacy-identical scopes", () => {
const foreign = await createOrgProjectAndApiKey();
foreignProjectId = foreign.projectId;
+ foreignOrgId = foreign.orgId;
});
afterAll(() => {
@@ -316,16 +329,25 @@ describe("shadowAuth maps principals to legacy-identical scopes", () => {
it("an organization key is granted project:read on a project it owns", async () => {
const context = await contextFor(orgAuth);
expect(ownedProjectIds(context)).toContain(projectId);
- expect(authorize(context, "project:read", { projectId }).success).toBe(
- true,
- );
+ expect(
+ authorize(
+ context,
+ OrganizationId(orgId),
+ "project:read",
+ ProjectId(projectId),
+ ).success,
+ ).toBe(true);
});
- it("an organization key is denied project:read on a project it does not own", async () => {
+ it("an organization key is denied project:read on a project in another tenant", async () => {
const context = await contextFor(orgAuth);
expect(
- authorize(context, "project:read", { projectId: foreignProjectId })
- .success,
+ authorize(
+ context,
+ OrganizationId(foreignOrgId),
+ "project:read",
+ ProjectId(foreignProjectId),
+ ).success,
).toBe(false);
});
@@ -334,6 +356,54 @@ describe("shadowAuth maps principals to legacy-identical scopes", () => {
expect(ownedProjectIds(await contextFor(auth))).toEqual([]);
});
+ it("an organization key's project wildcard covers live projects and excludes soft-deleted projects", async () => {
+ const org = await prisma.organization.create({
+ data: { id: randomUUID(), name: randomUUID() },
+ });
+ const live1 = await prisma.project.create({
+ data: { id: randomUUID(), name: randomUUID(), orgId: org.id },
+ });
+ const live2 = await prisma.project.create({
+ data: { id: randomUUID(), name: randomUUID(), orgId: org.id },
+ });
+ const deleted = await prisma.project.create({
+ data: {
+ id: randomUUID(),
+ name: randomUUID(),
+ orgId: org.id,
+ deletedAt: new Date(),
+ },
+ });
+ const auth = await createOrgApiKey(org.id);
+ const context = await contextFor(auth);
+
+ expect([...ownedProjectIds(context)].sort()).toEqual(
+ [live1.id, live2.id].sort(),
+ );
+
+ for (const projectId of [live1.id, live2.id]) {
+ const { enforce } = await projectNestedUnderModes(auth, projectId);
+ expect(scopeOf(enforce).projectId).toBe(projectId);
+ }
+ const { enforce: deletedEnforce } = await projectNestedUnderModes(
+ auth,
+ deleted.id,
+ );
+ expect(deletedEnforce).toMatchObject({
+ success: false,
+ error: { httpCode: 404 },
+ });
+
+ expect(
+ authorize(
+ context,
+ OrganizationId(org.id),
+ "project:read",
+ ProjectId(live2.id),
+ ).success,
+ ).toBe(true);
+ });
+
it("the admin key is refused on both dispatch families in both modes", async () => {
const admin = `Bearer ${adminApiKey}`;
const org = await orgResultUnderModes(admin);
@@ -359,7 +429,7 @@ describe("shadowAuth maps principals to legacy-identical scopes", () => {
it("a public-key bearer on a score-ingest route yields the scores access level", async () => {
const { legacy, enforce } = await resultsUnderModes({
req: reqWith({ authorization: `Bearer ${projectPublicKey}` }),
- action: "scores:create",
+ action: "scores:save",
allowedAccessLevels: ["project", "scores"],
});
expect(scopeOf(enforce).accessLevel).toBe("scores");
diff --git a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts
index 149174a6f5..afa2ff7fa6 100644
--- a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts
+++ b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts
@@ -11,6 +11,7 @@ import {
AUTHZ_CONTEXT_CACHE_KEY_PREFIX,
API_KEY_CACHE_KEY_PREFIX,
createShaHash,
+ hashSecretKey,
} from "@langfuse/shared/src/server";
import { Authenticator } from "@/src/features/apiKey/server";
@@ -78,6 +79,23 @@ const resolver = new ContextResolver(
findFirst: async () => orgRow,
},
} as unknown as PrismaClient),
+ {
+ roleAssignment: {
+ findMany: async () => [
+ {
+ id: "assignment_1",
+ orgId: ORG,
+ principalApiKeyId: "key_p",
+ principalUserId: null,
+ ownerProjectId: PRJ,
+ ownerOrgId: null,
+ systemRole: "ADMIN",
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ },
+ ],
+ },
+ } as unknown as PrismaClient,
);
/** fakeRedis is an in-memory get/set store; overrides let a test make either op throw. */
@@ -134,7 +152,7 @@ describe("Authenticator consolidated context cache", () => {
const first = await auth.authenticate(bearer(KNOWN_SECRET));
expect(first.success).toBe(true);
expect([...redis.map.keys()]).toEqual([
- `${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${knownHash}`,
+ `${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}v2:bearer:${knownHash}`,
]);
const verifySpy = vi.spyOn(verifier, "verify");
@@ -159,31 +177,208 @@ describe("Authenticator consolidated context cache", () => {
expect(key.startsWith(API_KEY_CACHE_KEY_PREFIX)).toBe(false);
});
- it("negative caching: an unknown credential's 401 is stored and replayed without verifying", async () => {
+ it("does not cache a 401: unknown credentials are verified on every request", async () => {
const redis = fakeRedis();
const auth = new Authenticator(
verifier,
resolver,
new AuthenticatorCache(redis, SALT),
);
+ const verifySpy = vi.spyOn(verifier, "verify");
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const result = await auth.authenticate(bearer(UNKNOWN_SECRET));
+ expect(result.success).toBe(false);
+ expect(result.error).toBeInstanceOf(UnauthorizedError);
+ }
+ expect(verifySpy).toHaveBeenCalledTimes(2);
+ expect(redis.map.size).toBe(0);
+ });
- const first = await auth.authenticate(bearer(UNKNOWN_SECRET));
- expect(first.success).toBe(false);
- expect(first.error).toBeInstanceOf(UnauthorizedError);
- const stored = redis.map.get(
- `${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${createShaHash(UNKNOWN_SECRET, SALT)}`,
+ it("does not let a Basic failure poison a public Bearer credential", async () => {
+ const key = apiKey();
+ const repository = store(key);
+ repository.findByPublicKey = async (publicKey) => ({
+ success: true,
+ apiKey: publicKey === key.publicKey ? key : null,
+ });
+ const auth = new Authenticator(
+ new Verifier(repository, SALT),
+ resolver,
+ new AuthenticatorCache(fakeRedis(), SALT),
);
- expect(stored).toBeDefined();
- const verifySpy = vi.spyOn(verifier, "verify");
- const second = await auth.authenticate(bearer(UNKNOWN_SECRET));
- expect(verifySpy).not.toHaveBeenCalled();
- expect(second.success).toBe(false);
- if (!first.success && !second.success) {
- expect(second.error.message).toBe(first.error.message);
+ const poisoned = await auth.authenticate({
+ headers: {
+ authorization: `Basic ${btoa(`unknown:${key.publicKey}`)}`,
+ },
+ });
+ expect(poisoned.success).toBe(false);
+ const legitimate = await auth.authenticate(bearer(key.publicKey));
+ expect(legitimate.success).toBe(true);
+ if (legitimate.success) {
+ expect(legitimate.context.principal).toMatchObject({
+ presentation: "publicKey",
+ });
}
});
+ it("does not reuse a public Bearer success for Basic authentication", async () => {
+ const key = apiKey();
+ const repository = store(key);
+ repository.findByPublicKey = async (publicKey) => ({
+ success: true,
+ apiKey: publicKey === key.publicKey ? key : null,
+ });
+ const auth = new Authenticator(
+ new Verifier(repository, SALT),
+ resolver,
+ new AuthenticatorCache(fakeRedis(), SALT),
+ );
+ expect((await auth.authenticate(bearer(key.publicKey))).success).toBe(true);
+ expect(
+ (
+ await auth.authenticate({
+ headers: {
+ authorization: `Basic ${btoa(`unknown:${key.publicKey}`)}`,
+ },
+ })
+ ).success,
+ ).toBe(false);
+ });
+
+ it("allows slow-hash migration after a failure with a different Basic username", async () => {
+ const key = apiKey({
+ fastHashedSecretKey: null,
+ hashedSecretKey: await hashSecretKey(KNOWN_SECRET),
+ });
+ const repository = store(key);
+ repository.findByPublicKey = async (publicKey) => ({
+ success: true,
+ apiKey: publicKey === key.publicKey ? key : null,
+ });
+ const auth = new Authenticator(
+ new Verifier(repository, SALT),
+ resolver,
+ new AuthenticatorCache(fakeRedis(), SALT),
+ );
+ const basic = (publicKey: string) => ({
+ headers: {
+ authorization: `Basic ${btoa(`${publicKey}:${KNOWN_SECRET}`)}`,
+ },
+ });
+ expect((await auth.authenticate(basic("unknown"))).success).toBe(false);
+ expect((await auth.authenticate(basic(key.publicKey))).success).toBe(true);
+ });
+
+ it("allows private Bearer authentication after Basic fast-hash migration", async () => {
+ const key = apiKey({
+ fastHashedSecretKey: null,
+ hashedSecretKey: await hashSecretKey(KNOWN_SECRET),
+ });
+ const repository = store(key);
+ repository.findByPublicKey = async (publicKey) => ({
+ success: true,
+ apiKey: publicKey === key.publicKey ? { ...key } : null,
+ });
+ repository.backfillFastHash = async (_id, hash) => {
+ key.fastHashedSecretKey = hash;
+ };
+ const auth = new Authenticator(
+ new Verifier(repository, SALT),
+ resolver,
+ new AuthenticatorCache(fakeRedis(), SALT),
+ );
+
+ expect((await auth.authenticate(bearer(KNOWN_SECRET))).success).toBe(false);
+ expect(
+ (
+ await auth.authenticate({
+ headers: {
+ authorization: `Basic ${btoa(`${key.publicKey}:${KNOWN_SECRET}`)}`,
+ },
+ })
+ ).success,
+ ).toBe(true);
+ expect((await auth.authenticate(bearer(KNOWN_SECRET))).success).toBe(true);
+ });
+
+ it("does not cache a private success when fast-hash backfill failed", async () => {
+ const key = apiKey({
+ fastHashedSecretKey: null,
+ hashedSecretKey: await hashSecretKey(KNOWN_SECRET),
+ });
+ const repository = store(key);
+ const findByPublicKey = vi.fn(async () => ({
+ success: true as const,
+ apiKey: key as ApiKey | null,
+ }));
+ repository.findByPublicKey = findByPublicKey;
+ const redis = fakeRedis();
+ const auth = new Authenticator(
+ new Verifier(repository, SALT),
+ resolver,
+ new AuthenticatorCache(redis, SALT),
+ );
+ const request = {
+ headers: {
+ authorization: `Basic ${btoa(`${key.publicKey}:${KNOWN_SECRET}`)}`,
+ },
+ };
+
+ expect((await auth.authenticate(request)).success).toBe(true);
+ findByPublicKey.mockResolvedValue({ success: true, apiKey: null });
+ expect((await auth.authenticate(request)).success).toBe(false);
+ });
+
+ it("preserves arbitrary Basic usernames for fast-hash secrets in both cache states", async () => {
+ const auth = new Authenticator(
+ verifier,
+ resolver,
+ new AuthenticatorCache(fakeRedis(), SALT),
+ );
+ for (const publicKey of ["unmatched-cold", "unmatched-warm"]) {
+ expect(
+ (
+ await auth.authenticate({
+ headers: {
+ authorization: `Basic ${btoa(`${publicKey}:${KNOWN_SECRET}`)}`,
+ },
+ })
+ ).success,
+ ).toBe(true);
+ }
+ expect((await auth.authenticate(bearer(KNOWN_SECRET))).success).toBe(true);
+ });
+
+ it.each(["null", "{}", '{"unauthorized":"Invalid credentials"}', "{"])(
+ "ignores cache entries without a readable context: %s",
+ async (raw) => {
+ const redis = fakeRedis({
+ get: (async () => raw) as Redis["get"],
+ });
+ const cache = new AuthenticatorCache(redis, SALT);
+ expect(
+ await cache.get({ kind: "bearer", token: KNOWN_SECRET }),
+ ).toBeNull();
+ },
+ );
+
+ it("ignores contexts from an earlier cache namespace", async () => {
+ const redis = fakeRedis();
+ redis.map.set(
+ `authz:context:${knownHash}`,
+ JSON.stringify({
+ context: { principal: { kind: "admin", userId: null }, policies: [] },
+ }),
+ );
+ const auth = new Authenticator(
+ verifier,
+ resolver,
+ new AuthenticatorCache(redis, SALT),
+ );
+ expect((await auth.authenticate(bearer(KNOWN_SECRET))).success).toBe(true);
+ });
+
it("fails open on a read error: falls through to verify and still authenticates", async () => {
const redis = fakeRedis({
get: (async () => {
@@ -240,13 +435,13 @@ describe("Authenticator consolidated context cache", () => {
}
});
- it("admin key, route disallows: gated off a cache hit", async () => {
+ it("does not cache environment admin authentication and still enforces route opt-in", async () => {
const redis = fakeRedis();
const adminVerifier = new Verifier(store(apiKey()), SALT, KNOWN_SECRET);
const auth = new Authenticator(
adminVerifier,
resolver,
- new AuthenticatorCache(redis, SALT),
+ new AuthenticatorCache(redis, SALT, ""),
);
const allowed = await auth.authenticate({
@@ -254,17 +449,93 @@ describe("Authenticator consolidated context cache", () => {
isAdminApiKeyAuthAllowed: true,
});
expect(allowed.success).toBe(true);
- expect(redis.map.size).toBe(1);
+ expect(redis.map.size).toBe(0);
const verifySpy = vi.spyOn(adminVerifier, "verify");
const gated = await auth.authenticate(bearer(KNOWN_SECRET));
- expect(verifySpy).not.toHaveBeenCalled();
+ expect(verifySpy).toHaveBeenCalledOnce();
expect(gated.success).toBe(false);
if (!gated.success) {
expect(gated.error).toBeInstanceOf(UnauthorizedError);
}
});
+ it.each(["rotated-admin-secret", ""])(
+ "rejects the old environment admin credential after configuration changes to %j",
+ async (adminApiKey) => {
+ const redis = fakeRedis();
+ const oldAdminKey = "old-admin-secret";
+ const request = {
+ ...bearer(oldAdminKey),
+ isAdminApiKeyAuthAllowed: true,
+ };
+ const oldAuth = new Authenticator(
+ new Verifier(store(apiKey()), SALT, oldAdminKey),
+ resolver,
+ new AuthenticatorCache(redis, SALT, oldAdminKey),
+ );
+ expect((await oldAuth.authenticate(request)).success).toBe(true);
+
+ const newAuth = new Authenticator(
+ new Verifier(store(apiKey()), SALT, adminApiKey),
+ resolver,
+ new AuthenticatorCache(redis, SALT, adminApiKey),
+ );
+ const result = await newAuth.authenticate(request);
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBeInstanceOf(UnauthorizedError);
+ }
+ },
+ );
+
+ it("recognizes a cached database credential as the newly configured environment admin", async () => {
+ const redis = fakeRedis();
+ const auth = new Authenticator(
+ new Verifier(store(apiKey()), SALT, ""),
+ resolver,
+ new AuthenticatorCache(redis, SALT, ""),
+ );
+ const request = {
+ ...bearer(KNOWN_SECRET),
+ isAdminApiKeyAuthAllowed: true,
+ };
+ expect(await auth.authenticate(request)).toMatchObject({
+ success: true,
+ context: { principal: { kind: "apiKey" } },
+ });
+ expect(redis.map.size).toBe(1);
+
+ const adminApiKey = ` ${KNOWN_SECRET} `;
+ const adminVerifier = new Verifier(store(apiKey()), SALT, adminApiKey);
+ const promotedAuth = new Authenticator(
+ adminVerifier,
+ resolver,
+ new AuthenticatorCache(redis, SALT, adminApiKey),
+ );
+ const getSpy = vi.spyOn(redis, "get");
+ const setSpy = vi.spyOn(redis, "set");
+ expect(await promotedAuth.authenticate(request)).toMatchObject({
+ success: true,
+ context: { principal: { kind: "admin" } },
+ });
+ expect(getSpy).not.toHaveBeenCalled();
+ expect(setSpy).not.toHaveBeenCalled();
+
+ const basic = {
+ headers: {
+ authorization: `Basic ${btoa(`unknown:${KNOWN_SECRET}`)}`,
+ },
+ };
+ expect(await promotedAuth.authenticate(basic)).toMatchObject({
+ success: true,
+ context: { principal: { kind: "apiKey" } },
+ });
+ const verifySpy = vi.spyOn(adminVerifier, "verify");
+ expect((await promotedAuth.authenticate(basic)).success).toBe(true);
+ expect(verifySpy).not.toHaveBeenCalled();
+ });
+
it("admin key on a cloud region: 403s even when the route allows it", async () => {
(
env as { NEXT_PUBLIC_LANGFUSE_CLOUD_REGION?: string }
@@ -339,21 +610,25 @@ describe("Authenticator consolidated context cache", () => {
expect(setSpy).toHaveBeenCalledTimes(1);
});
- it("get returns null on a miss, distinct from a replayed 401", async () => {
+ it("caps a context's TTL at the key's remaining lifetime", async () => {
+ const expiringVerifier = new Verifier(
+ store(apiKey({ expiresAt: new Date(Date.now() + 10_000) })),
+ SALT,
+ );
const redis = fakeRedis();
- const cache = new AuthenticatorCache(redis, SALT);
- const credential = { kind: "bearer", token: UNKNOWN_SECRET } as const;
+ const setSpy = vi.spyOn(redis, "set");
+ const auth = new Authenticator(
+ expiringVerifier,
+ resolver,
+ new AuthenticatorCache(redis, SALT),
+ );
- expect(await cache.get(credential)).toBeNull();
+ const result = await auth.authenticate(bearer(KNOWN_SECRET));
- await cache.set(credential, {
- success: false,
- error: new UnauthorizedError("nope"),
- });
- const hit = await cache.get(credential);
- expect(hit?.success).toBe(false);
- if (hit && !hit.success) {
- expect(hit.error).toBeInstanceOf(UnauthorizedError);
- }
+ expect(result.success).toBe(true);
+ expect(setSpy).toHaveBeenCalledOnce();
+ const ttl = setSpy.mock.calls[0][3] as unknown as number;
+ expect(ttl).toBeGreaterThan(0);
+ expect(ttl).toBeLessThanOrEqual(10);
});
});
diff --git a/web/src/__tests__/server/unit/apiKey/invalidateApiKeys.servertest.ts b/web/src/__tests__/server/unit/apiKey/invalidateApiKeys.servertest.ts
index 5f63e977ad..e9cd9af7c1 100644
--- a/web/src/__tests__/server/unit/apiKey/invalidateApiKeys.servertest.ts
+++ b/web/src/__tests__/server/unit/apiKey/invalidateApiKeys.servertest.ts
@@ -6,6 +6,7 @@ import {
API_KEY_CACHE_KEY_PREFIX,
AUTHZ_CONTEXT_CACHE_KEY_PREFIX,
createShaHash,
+ createAuthzContextCacheKey,
invalidateCachedApiKeys,
} from "@langfuse/shared/src/server";
@@ -48,6 +49,11 @@ describe("invalidateCachedApiKeys clears both cache namespaces", () => {
const keys = deletedKeys();
expect(keys).toContain(`${API_KEY_CACHE_KEY_PREFIX}fh1`);
expect(keys).toContain(`${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}fh1`);
+ expect(keys).toContain(createAuthzContextCacheKey("basic", "fh1"));
+ expect(keys).toContain(createAuthzContextCacheKey("bearer", "fh1"));
+ expect(keys).toContain(
+ createAuthzContextCacheKey("bearer", createShaHash("pk-lf-1", env.SALT!)),
+ );
expect(keys).toContain(
`${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${createShaHash("pk-lf-1", env.SALT!)}`,
);
@@ -62,6 +68,7 @@ describe("invalidateCachedApiKeys clears both cache namespaces", () => {
const keys = deletedKeys();
expect(keys).toEqual([
`${AUTHZ_CONTEXT_CACHE_KEY_PREFIX}${createShaHash("pk-lf-2", env.SALT!)}`,
+ createAuthzContextCacheKey("bearer", createShaHash("pk-lf-2", env.SALT!)),
]);
expect(keys.some((k) => k.startsWith(API_KEY_CACHE_KEY_PREFIX))).toBe(
false,
diff --git a/web/src/__tests__/server/unit/assertToolAuthorized.servertest.ts b/web/src/__tests__/server/unit/assertToolAuthorized.servertest.ts
index 94365ce486..172006ad7b 100644
--- a/web/src/__tests__/server/unit/assertToolAuthorized.servertest.ts
+++ b/web/src/__tests__/server/unit/assertToolAuthorized.servertest.ts
@@ -2,6 +2,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";
import { ForbiddenError } from "@langfuse/shared";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ type ProjectAction,
+} from "@langfuse/shared/rbac";
const { env } = vi.hoisted(() => ({
env: { API_AUTH_MIGRATION: "enforce" as string },
@@ -22,22 +28,20 @@ import {
type ApiAction,
} from "@/src/features/public-api/server";
import type { ServerContext } from "@/src/features/mcp/types";
-import {
- type AuthorizationContext,
- type Policy,
- type ProjectAction,
-} from "@/src/features/auth/policy/types";
+import { type Policy } from "@/src/features/rbac/types";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
const { assertToolAuthorized } = __test;
const PRJ = "prj_1";
const allowPrompts: Policy = {
- kind: "project",
- source: { kind: "role", id: "PROJECT" },
+ id: "system/LEGACY_PROJECT_API_KEY:project",
+ tenantId: OrganizationId("org_1"),
+ roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),
actions: ["prompts:read"] as ProjectAction[] as never,
- resources: [PRJ],
- effect: "allow",
+ resources: [ProjectId(PRJ)],
+ effect: "ALLOW",
};
const authContext = (policies: Policy[]): AuthorizationContext => ({
@@ -108,12 +112,21 @@ describe("assertToolAuthorized", () => {
).not.toThrow();
});
- it("passes when no context resolved (legacy)", () => {
+ it("passes when no context resolved in legacy", () => {
+ env.API_AUTH_MIGRATION = "legacy";
expect(() =>
assertToolAuthorized(tool("prompts:CUD"), serverContext(undefined)),
).not.toThrow();
});
+ it("rejects a gated tool without context in enforce", () => {
+ expect(() =>
+ assertToolAuthorized(tool("prompts:CUD"), serverContext()),
+ ).toThrow(
+ expect.objectContaining({ code: ErrorCode.InvalidRequest }) as Error,
+ );
+ });
+
describe("shadow mode", () => {
beforeEach(() => {
env.API_AUTH_MIGRATION = "shadow";
diff --git a/web/src/__tests__/server/unit/feedback-api.servertest.ts b/web/src/__tests__/server/unit/feedback-api.servertest.ts
index dc2fcdc891..f084bd10a3 100644
--- a/web/src/__tests__/server/unit/feedback-api.servertest.ts
+++ b/web/src/__tests__/server/unit/feedback-api.servertest.ts
@@ -7,11 +7,11 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const { mockRateLimitRequest, mockSubmitFeedback, mockVerifyAuth } = vi.hoisted(
+const { mockRateLimitRequest, mockSubmitFeedback, mockShadowAuth } = vi.hoisted(
() => ({
mockRateLimitRequest: vi.fn(),
mockSubmitFeedback: vi.fn(),
- mockVerifyAuth: vi.fn(),
+ mockShadowAuth: vi.fn(),
}),
);
@@ -19,15 +19,12 @@ vi.mock("@/src/features/feedback/server/FeedbackService", () => ({
submitFeedback: mockSubmitFeedback,
}));
-vi.mock("@/src/features/public-api/server/apiAuth", () => {
- function ApiAuthService() {
- return {
- verifyAuthHeaderAndReturnScope: mockVerifyAuth,
- };
- }
-
- return { ApiAuthService };
-});
+// Stub the auth seam the route actually uses so the test is independent of the
+// active API_AUTH_MIGRATION mode.
+vi.mock("@/src/features/public-api/server/shadowAuth", async () => ({
+ ...(await vi.importActual("@/src/features/public-api/server/shadowAuth")),
+ shadowAuth: mockShadowAuth,
+}));
vi.mock("@/src/features/public-api/server/RateLimitService", () => ({
RateLimitService: {
@@ -78,14 +75,14 @@ describe("POST /api/public/feedback", () => {
beforeEach(() => {
mockRateLimitRequest.mockReset();
mockSubmitFeedback.mockReset();
- mockVerifyAuth.mockReset();
+ mockShadowAuth.mockReset();
mockRateLimitRequest.mockResolvedValue(undefined);
mockSubmitFeedback.mockResolvedValue({
id: "11111111-1111-4111-8111-111111111111",
});
- mockVerifyAuth.mockResolvedValue({
- validKey: true,
+ mockShadowAuth.mockResolvedValue({
+ success: true,
scope: validScope,
});
});
diff --git a/web/src/__tests__/server/unit/ingestion-write-mode.servertest.ts b/web/src/__tests__/server/unit/ingestion-write-mode.servertest.ts
index 0749ec8996..c63d7891df 100644
--- a/web/src/__tests__/server/unit/ingestion-write-mode.servertest.ts
+++ b/web/src/__tests__/server/unit/ingestion-write-mode.servertest.ts
@@ -1,4 +1,55 @@
-import { filterBatchForEventsOnly } from "@/src/pages/api/public/ingestion";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { createMocks } from "node-mocks-http";
+
+import { OrganizationId, ProjectId, SystemRoleId } from "@langfuse/shared/rbac";
+import { processEventBatch } from "@langfuse/shared/src/server";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+import handler, {
+ filterBatchForEventsOnly,
+} from "@/src/pages/api/public/ingestion";
+
+const { migration, shadowAuth, recordIncrement } = vi.hoisted(() => ({
+ migration: { mode: "shadow" as "legacy" | "shadow" | "enforce" },
+ shadowAuth: vi.fn(),
+ recordIncrement: vi.fn(),
+}));
+
+vi.mock(import("@/src/env.mjs"), async (importOriginal) => {
+ const original = await importOriginal();
+ return {
+ env: new Proxy(original.env, {
+ get(target, property, receiver) {
+ if (property === "API_AUTH_MIGRATION") return migration.mode;
+ if (property === "LANGFUSE_MIGRATION_V4_WRITE_MODE") return "dual";
+ return Reflect.get(target, property, receiver);
+ },
+ }),
+ };
+});
+
+vi.mock(import("@/src/features/public-api/server"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ shadowAuth,
+}));
+
+vi.mock(import("@langfuse/shared/src/server"), async (importOriginal) => {
+ const original = await importOriginal();
+ return {
+ ...original,
+ processEventBatch: vi.fn(original.processEventBatch),
+ recordIncrement,
+ };
+});
+
+vi.mock("@/src/features/telemetry", () => ({ telemetry: vi.fn() }));
+vi.mock("@/src/features/public-api/server/RateLimitService", () => ({
+ RateLimitService: {
+ getInstance: () => ({
+ rateLimitRequest: vi.fn().mockResolvedValue(undefined),
+ }),
+ },
+}));
describe("legacy ingestion write-mode filter", () => {
const scoreEvent = { id: "score", type: "score-create" };
@@ -25,3 +76,114 @@ describe("legacy ingestion write-mode filter", () => {
});
});
});
+
+describe("ingestion per-event shadow comparison", () => {
+ beforeEach(() => {
+ migration.mode = "shadow";
+ shadowAuth.mockReset();
+ recordIncrement.mockClear();
+ vi.mocked(processEventBatch).mockClear();
+ });
+
+ it.each([
+ ["legacy", false, undefined],
+ ["shadow", false, "match"],
+ ["shadow", true, "new_allows"],
+ ["enforce", false, undefined],
+ ] as const)(
+ "%s keeps public-key trace rejection when new authorization allows=%s",
+ async (mode, allowTrace, parity) => {
+ migration.mode = mode;
+ const ctx: AuthorizationContext = {
+ principal: {
+ kind: "apiKey",
+ apiKeyId: "key",
+ userId: null,
+ isInAppAgentKey: false,
+ publicKey: "pk-lf-test",
+ scope: "PROJECT",
+ presentation: "publicKey",
+ organizations: [],
+ boundResource: { orgId: "org", projectId: "project" },
+ },
+ policies: allowTrace
+ ? [
+ {
+ id: "trace-policy",
+ tenantId: OrganizationId("org"),
+ roleId: SystemRoleId("ADMIN"),
+ actions: ["traces:create"],
+ resources: [ProjectId("project")],
+ effect: "ALLOW",
+ },
+ ]
+ : [],
+ };
+ shadowAuth.mockResolvedValue({
+ success: true,
+ scope: {
+ accessLevel: "scores",
+ projectId: "project",
+ orgId: "org",
+ apiKeyId: "key",
+ publicKey: "pk-lf-test",
+ plan: "cloud:hobby",
+ rateLimitOverrides: [],
+ },
+ ctx: mode === "legacy" ? undefined : ctx,
+ });
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ headers: { authorization: "Bearer pk-lf-test" },
+ body: {
+ batch: [
+ { id: "invalid-event", type: "trace-create" },
+ {
+ id: "trace-event",
+ timestamp: new Date().toISOString(),
+ type: "trace-create",
+ body: { id: "trace-id" },
+ },
+ {
+ id: "log-event",
+ timestamp: new Date().toISOString(),
+ type: "sdk-log",
+ body: { log: "test" },
+ },
+ ],
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(207);
+ expect(res._getJSONData()).toMatchObject({
+ successes: [],
+ errors: [
+ { id: "invalid-event", status: 401, error: "Access Scope Denied" },
+ { id: "trace-event", status: 401, error: "Access Scope Denied" },
+ ],
+ });
+ expect(vi.mocked(processEventBatch).mock.calls[0][0]).not.toContainEqual(
+ expect.objectContaining({ id: "trace-event" }),
+ );
+ if (parity) {
+ expect(recordIncrement).toHaveBeenCalledWith(
+ "langfuse.authz.parity",
+ 1,
+ expect.objectContaining({
+ action: "traces:create",
+ result: parity,
+ legacy_code: 401,
+ }),
+ );
+ } else {
+ expect(recordIncrement).not.toHaveBeenCalledWith(
+ "langfuse.authz.parity",
+ expect.anything(),
+ expect.anything(),
+ );
+ }
+ },
+ );
+});
diff --git a/web/src/__tests__/server/unit/openapi-deprecations.servertest.ts b/web/src/__tests__/server/unit/openapi-deprecations.servertest.ts
index 45813129c0..97ea3daceb 100644
--- a/web/src/__tests__/server/unit/openapi-deprecations.servertest.ts
+++ b/web/src/__tests__/server/unit/openapi-deprecations.servertest.ts
@@ -5,6 +5,7 @@ import { parse } from "yaml";
import {
getFernDeprecatedOperations,
+ getFernDeprecatedProperties,
type DeprecatedOperation,
} from "../../../../scripts/openapi/fern-deprecations";
import {
@@ -109,6 +110,70 @@ function withDefinition(
}
describe("OpenAPI deprecations", () => {
+ it("finds deprecated named-type and inline-request properties", () => {
+ withDefinition(
+ {
+ "api.yml": "base-path: /api\n",
+ "keys.yml": `types:
+ Key:
+ properties:
+ oldLabel:
+ type: optional<string>
+ availability: deprecated
+ label: optional<string>
+service:
+ base-path: /admin
+ endpoints:
+ create:
+ method: POST
+ path: /keys
+ request:
+ name: CreateKeyRequest
+ body:
+ properties:
+ oldLabel:
+ type: optional<string>
+ availability:
+ status: deprecated
+ label: optional<string>
+`,
+ },
+ (directory) => {
+ expect(getFernDeprecatedProperties(directory)).toEqual([
+ ["components", "schemas", "Key", "properties", "oldLabel"],
+ [
+ "paths",
+ "/api/admin/keys",
+ "post",
+ "requestBody",
+ "content",
+ "application/json",
+ "schema",
+ "properties",
+ "oldLabel",
+ ],
+ ]);
+ },
+ );
+ });
+
+ it("stamps property deprecations without changing their descriptions", () => {
+ const source = `${SPEC}components:\n schemas:\n Key:\n properties:\n oldLabel:\n type: string\n description: Use label instead.\n label:\n type: string\n`;
+ const properties = [
+ ["components", "schemas", "Key", "properties", "oldLabel"],
+ ];
+ const stamped = stampDeprecations(source, [], properties);
+ const schemas = parse(stamped).components.schemas;
+
+ expect(schemas.Key.properties.oldLabel).toEqual({
+ type: "string",
+ description: "Use label instead.",
+ deprecated: true,
+ });
+ expect(schemas.Key.properties.label).toEqual({ type: "string" });
+ expect(stampDeprecations(stamped, [], properties)).toBe(stamped);
+ });
+
it("matches the deprecated endpoints in the Fern definitions", () => {
const openApi = parseSpec(fs.readFileSync(openApiPath, "utf8"));
const openApiDeprecatedOperations = Object.entries(openApi.paths).flatMap(
diff --git a/web/src/__tests__/server/unit/policy/authorize.servertest.ts b/web/src/__tests__/server/unit/policy/authorize.servertest.ts
index d678317969..90d98bc3a2 100644
--- a/web/src/__tests__/server/unit/policy/authorize.servertest.ts
+++ b/web/src/__tests__/server/unit/policy/authorize.servertest.ts
@@ -1,50 +1,38 @@
import { describe, expect, it } from "vitest";
import { ForbiddenError } from "@langfuse/shared";
-
-import { authorize } from "@/src/features/auth/policy/authorize";
import {
- allOrganizationActions,
- allProjectActions,
- wildcard,
- type AuthorizationContext,
- type Policy,
-} from "@/src/features/auth/policy/types";
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ type ResourceId,
+ type TenantId,
+} from "@langfuse/shared/rbac";
-const ORG = "org_1";
-const PRJ = "prj_1";
-const OTHER_PRJ = "prj_2";
+import { authorize } from "@/src/features/rbac/authorize";
+import { type Policy } from "@/src/features/rbac/types";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
-const allowProject = (
- actions: readonly string[],
- resources: Policy["resources"],
-): Policy => ({
- kind: "project",
- source: { kind: "role", id: "OWNER" },
- actions: actions as never,
- resources,
- effect: "allow",
-});
-const allowOrg = (
- actions: readonly string[],
- resources: Policy["resources"],
-): Policy => ({
- kind: "organization",
- source: { kind: "role", id: "OWNER" },
- actions: actions as never,
- resources,
- effect: "allow",
-});
-const denyProject = (
- actions: readonly string[],
- resources: Policy["resources"],
-): Policy => ({
- kind: "project",
- source: { kind: "grant" },
- actions: actions as never,
- resources,
- effect: "deny",
+const TENANT: TenantId = OrganizationId("org_1");
+const OTHER_TENANT: TenantId = OrganizationId("org_2");
+const WILDCARD_TENANT: TenantId = OrganizationId("*");
+const PRJ: ResourceId = ProjectId("prj_1");
+const OTHER_PRJ: ResourceId = ProjectId("prj_2");
+const WILDCARD: ResourceId = ProjectId("*");
+const ORG: ResourceId = OrganizationId("org_1");
+const OTHER_ORG: ResourceId = OrganizationId("org_2");
+const WILDCARD_ORG: ResourceId = OrganizationId("*");
+
+const policy = (over: Partial<Policy> = {}): Policy => ({
+ id: "system/OWNER:project",
+ tenantId: TENANT,
+ roleId: SystemRoleId("OWNER"),
+ effect: "ALLOW",
+ actions: ["prompts:read"],
+ resources: [PRJ],
+ ...over,
});
+
const ctx = (policies: Policy[]): AuthorizationContext => ({
principal: {
kind: "apiKey",
@@ -60,110 +48,176 @@ const ctx = (policies: Policy[]): AuthorizationContext => ({
policies,
});
-describe("authorize — project coverage", () => {
- const grant = ctx([allowProject(["prompts:read"], [PRJ])]);
- it.each([
- ["a grant covers its project", { projectId: PRJ }, true],
- ["a grant does not cover another project", { projectId: OTHER_PRJ }, false],
- ] as const)("%s", (_name, resource, expected) => {
- expect(authorize(grant, "prompts:read", resource).success).toBe(expected);
- });
- it("no project ref grants nothing", () => {
- const empty = ctx([allowProject(["prompts:read"], [])]);
- expect(authorize(empty, "prompts:read", { projectId: PRJ }).success).toBe(
+describe("authorize — tenant scoping", () => {
+ const grant = ctx([policy()]);
+ it("authorizes within the resource's tenant", () => {
+ expect(authorize(grant, TENANT, "prompts:read", PRJ).success).toBe(true);
+ });
+ it("denies the same resource under a different tenant", () => {
+ expect(authorize(grant, OTHER_TENANT, "prompts:read", PRJ).success).toBe(
+ false,
+ );
+ });
+});
+
+describe("authorize — exact project coverage", () => {
+ const grant = ctx([policy({ resources: [PRJ] })]);
+ it("covers its exact project", () => {
+ expect(authorize(grant, TENANT, "prompts:read", PRJ).success).toBe(true);
+ });
+ it("does not cover another project without a wildcard", () => {
+ expect(authorize(grant, TENANT, "prompts:read", OTHER_PRJ).success).toBe(
false,
);
});
});
-describe("authorize — org-level actions", () => {
- const orgAdmin = ctx([allowOrg(["projects:create"], [ORG])]);
- it("an org ref covers org-level actions", () => {
- expect(authorize(orgAdmin, "projects:create", { orgId: ORG }).success).toBe(
+describe("authorize — project wildcard within a tenant", () => {
+ const wildcardGrant = ctx([policy({ resources: [WILDCARD] })]);
+ it("grants any project of the tenant", () => {
+ expect(authorize(wildcardGrant, TENANT, "prompts:read", PRJ).success).toBe(
true,
);
+ expect(
+ authorize(wildcardGrant, TENANT, "prompts:read", OTHER_PRJ).success,
+ ).toBe(true);
});
- it("org grant does not leak to another org", () => {
+ it("does not leak the wildcard to another tenant", () => {
expect(
- authorize(orgAdmin, "projects:create", { orgId: "org_x" }).success,
+ authorize(wildcardGrant, OTHER_TENANT, "prompts:read", PRJ).success,
).toBe(false);
});
});
-describe("authorize — kind-gating", () => {
- it("a project wildcard never satisfies an org action", () => {
- const projectWildcard = ctx([allowProject(["prompts:read"], wildcard)]);
- expect(
- authorize(projectWildcard, "project:read", { orgId: ORG }).success,
- ).toBe(false);
+describe("authorize — exact project overrides the wildcard", () => {
+ const c = ctx([
+ policy({ id: "wildcard", resources: [WILDCARD], effect: "ALLOW" }),
+ policy({ id: "exact-deny", resources: [PRJ], effect: "DENY" }),
+ ]);
+ it("the exact deny wins on its project, ignoring the allowing wildcard", () => {
+ expect(authorize(c, TENANT, "prompts:read", PRJ).success).toBe(false);
});
- it("an org wildcard never satisfies a project action", () => {
- const orgWildcard = ctx([allowOrg(["project:read"], wildcard)]);
- expect(
- authorize(orgWildcard, "prompts:read", { projectId: PRJ }).success,
- ).toBe(false);
+ it("the wildcard still allows a project with no exact policy", () => {
+ expect(authorize(c, TENANT, "prompts:read", OTHER_PRJ).success).toBe(true);
});
- it("a project audit grant does not satisfy an org-level audit check", () => {
- const projectAudit = ctx([allowProject(["projectAuditLogs:read"], [PRJ])]);
+});
+
+describe("authorize — org resources need an exact match", () => {
+ const ORG_RESOURCE: ResourceId = OrganizationId("org_1");
+ it("an org policy covers the org resource", () => {
+ const orgGrant = ctx([
+ policy({
+ resources: [ORG_RESOURCE],
+ actions: ["projects:create"],
+ }),
+ ]);
expect(
- authorize(projectAudit, "projectAuditLogs:read", { projectId: PRJ })
- .success,
+ authorize(orgGrant, TENANT, "projects:create", ORG_RESOURCE).success,
).toBe(true);
+ });
+ it("a project wildcard never satisfies an org resource", () => {
+ const wildcardGrant = ctx([
+ policy({ resources: [WILDCARD], actions: ["projects:create"] }),
+ ]);
expect(
- authorize(projectAudit, "projectAuditLogs:read", { orgId: ORG }).success,
+ authorize(wildcardGrant, TENANT, "projects:create", ORG_RESOURCE).success,
).toBe(false);
});
});
-describe("authorize — admin wildcard", () => {
- const admin = ctx([
- allowOrg(allOrganizationActions, wildcard),
- allowProject(allProjectActions, wildcard),
- ]);
- it("admin allows any project action", () => {
- expect(authorize(admin, "prompts:read", { projectId: "y" }).success).toBe(
- true,
+describe("authorize — deny-overrides and deny-by-default", () => {
+ it("denies by default when nothing matches", () => {
+ expect(authorize(ctx([]), TENANT, "prompts:read", PRJ).success).toBe(false);
+ });
+ it("a matching deny beats a matching allow on the same resource", () => {
+ const suspended = ctx([
+ policy({ id: "allow", actions: ["traces:create"], effect: "ALLOW" }),
+ policy({ id: "deny", actions: ["traces:create"], effect: "DENY" }),
+ ]);
+ expect(authorize(suspended, TENANT, "traces:create", PRJ).success).toBe(
+ false,
);
});
- it("admin allows any org action", () => {
- expect(authorize(admin, "projects:create", { orgId: "x" }).success).toBe(
- true,
+ it("a deny carries the generic Forbidden message", () => {
+ const decision = authorize(
+ ctx([policy({ actions: ["traces:create"], effect: "DENY" })]),
+ TENANT,
+ "traces:create",
+ PRJ,
);
+ expect(decision.error?.message).toBe(new ForbiddenError().message);
});
});
-describe("authorize — deny-overrides and deny-by-default", () => {
- it("denies by default when nothing matches", () => {
- expect(authorize(ctx([]), "prompts:read", { projectId: PRJ }).success).toBe(
- false,
- );
+describe("authorize — kind wildcards are never a target", () => {
+ it("denies an authorization check against project/*", () => {
+ const wildcardGrant = ctx([policy({ resources: [WILDCARD] })]);
+ expect(
+ authorize(wildcardGrant, TENANT, "prompts:read", WILDCARD).success,
+ ).toBe(false);
});
- it("a matching deny beats a matching allow", () => {
- const suspended = ctx([
- allowProject(["traces:create"], [PRJ]),
- denyProject(["traces:create"], [PRJ]),
+ it("denies an authorization check against organization/*", () => {
+ const wildcardGrant = ctx([
+ policy({
+ tenantId: WILDCARD_TENANT,
+ resources: [WILDCARD_ORG],
+ actions: ["projects:create"],
+ }),
]);
expect(
- authorize(suspended, "traces:create", { projectId: PRJ }).success,
+ authorize(wildcardGrant, TENANT, "projects:create", WILDCARD_ORG).success,
).toBe(false);
});
- it("a deny of the checked project beats an allow that also covers others", () => {
+});
+
+describe("authorize — organization/* tenant spans every tenant", () => {
+ const grant = ctx([
+ policy({ tenantId: WILDCARD_TENANT, resources: [WILDCARD] }),
+ ]);
+ it("grants a project of one tenant", () => {
+ expect(authorize(grant, TENANT, "prompts:read", PRJ).success).toBe(true);
+ });
+ it("grants a project of another tenant with the same policy", () => {
+ expect(
+ authorize(grant, OTHER_TENANT, "prompts:read", OTHER_PRJ).success,
+ ).toBe(true);
+ });
+});
+
+describe("authorize — organization/* resource wildcard covers org targets", () => {
+ const grant = ctx([
+ policy({
+ tenantId: WILDCARD_TENANT,
+ resources: [WILDCARD_ORG],
+ actions: ["projects:create"],
+ }),
+ ]);
+ it("grants an org target under any tenant", () => {
+ expect(authorize(grant, TENANT, "projects:create", ORG).success).toBe(true);
+ expect(
+ authorize(grant, OTHER_TENANT, "projects:create", OTHER_ORG).success,
+ ).toBe(true);
+ });
+ it("an exact org resource still overrides the org wildcard", () => {
const c = ctx([
- allowProject(["prompts:read"], [PRJ, OTHER_PRJ]),
- denyProject(["prompts:read"], [PRJ]),
+ policy({
+ id: "org-wildcard",
+ tenantId: WILDCARD_TENANT,
+ resources: [WILDCARD_ORG],
+ actions: ["projects:create"],
+ effect: "ALLOW",
+ }),
+ policy({
+ id: "org-exact-deny",
+ tenantId: WILDCARD_TENANT,
+ resources: [ORG],
+ actions: ["projects:create"],
+ effect: "DENY",
+ }),
]);
- expect(authorize(c, "prompts:read", { projectId: PRJ }).success).toBe(
- false,
- );
- expect(authorize(c, "prompts:read", { projectId: OTHER_PRJ }).success).toBe(
- true,
- );
- });
- it("a deny carries the generic Forbidden message", () => {
- const roleDeny = denyProject(["traces:create"], [PRJ]);
- const decision = authorize(ctx([roleDeny]), "traces:create", {
- projectId: PRJ,
- });
- expect(decision.error?.message).toBe(new ForbiddenError().message);
+ expect(authorize(c, TENANT, "projects:create", ORG).success).toBe(false);
+ expect(
+ authorize(c, OTHER_TENANT, "projects:create", OTHER_ORG).success,
+ ).toBe(true);
});
});
diff --git a/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts b/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts
index 17698d45fa..9fbc5bd5b9 100644
--- a/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts
+++ b/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts
@@ -2,8 +2,9 @@ import { describe, expect, it } from "vitest";
import { type ApiKey, type PrismaClient } from "@langfuse/shared/src/db";
import { InternalServerError } from "@langfuse/shared";
+import { OrganizationId, ProjectId, SystemRoleId } from "@langfuse/shared/rbac";
-import { authorize } from "@/src/features/auth/policy/authorize";
+import { authorize } from "@/src/features/rbac/authorize";
import {
OrganizationRepository,
type OrganizationWithProjects,
@@ -18,6 +19,7 @@ const ORG = "org_1";
const PRJ = "prj_1";
const OTHER_PRJ = "prj_2";
const USER = "user_1";
+const TENANT = OrganizationId(ORG);
const ORGANIZATION_CREATED_AT = new Date("2026-09-16T00:00:00.000Z");
const orgRow = (
@@ -32,14 +34,61 @@ const orgRow = (
...over,
}) 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")
+ return [
+ {
+ systemRole: "LEGACY_ORGANIZATION_API_KEY",
+ ...principal,
+ ownerOrgId: ORG,
+ ownerProjectId: null,
+ orgId: ORG,
+ },
+ ];
+ if (principalApiKeyId === "key_p")
+ return [
+ {
+ systemRole: "LEGACY_PROJECT_API_KEY",
+ ...principal,
+ ownerOrgId: null,
+ ownerProjectId: PRJ,
+ orgId: ORG,
+ },
+ ];
+ if (principalApiKeyId === "key_v")
+ return [
+ {
+ ...principal,
+ systemRole: "VIEWER",
+ ownerOrgId: null,
+ ownerProjectId: PRJ,
+ orgId: ORG,
+ },
+ ];
+ return [];
+};
+
+const mockPrisma = (row: OrganizationWithProjects | null): PrismaClient =>
+ ({
+ organization: {
+ findUnique: async () => row,
+ findFirst: async () => row,
+ },
+ roleAssignment: {
+ findMany: async ({ where }: { where: { principalApiKeyId: string } }) =>
+ assignmentsFor(where.principalApiKeyId),
+ },
+ project: {
+ findMany: async () => (row?.projects ?? []).map((p) => ({ id: p.id })),
+ },
+ }) as unknown as PrismaClient;
+
const resolverFor = (row: OrganizationWithProjects | null): ContextResolver =>
new ContextResolver(
- new OrganizationRepository({
- organization: {
- findUnique: async () => row,
- findFirst: async () => row,
- },
- } as unknown as PrismaClient),
+ new OrganizationRepository(mockPrisma(row)),
+ mockPrisma(row),
);
const contextFor = async (
@@ -76,12 +125,37 @@ describe("resolves the admin key", () => {
it("grants admin over any project and org", async () => {
const ctx = await contextFor({ authorization: "admin" });
expect(ctx.principal.kind).toBe("admin");
- expect(authorize(ctx, "prompts:read", { projectId: "any" }).success).toBe(
+ expect(
+ authorize(ctx, OrganizationId("any"), "prompts:read", ProjectId("any"))
+ .success,
+ ).toBe(true);
+ expect(
+ authorize(
+ ctx,
+ OrganizationId("any"),
+ "projects:create",
+ OrganizationId("any"),
+ ).success,
+ ).toBe(true);
+ });
+
+ it("carries OWNER policies bound to the wildcard tenant and resources", async () => {
+ const ctx = await contextFor({ authorization: "admin" });
+ expect(ctx.policies.length).toBeGreaterThan(0);
+ expect(ctx.policies.every((p) => p.tenantId === OrganizationId("*"))).toBe(
true,
);
- expect(authorize(ctx, "projects:create", { orgId: "any" }).success).toBe(
+ expect(ctx.policies.every((p) => p.roleId === SystemRoleId("OWNER"))).toBe(
true,
);
+ const org = ctx.policies.find((p) => p.id === "system/OWNER:organization");
+ const project = ctx.policies.find((p) => p.id === "system/OWNER:project");
+ expect(org?.resources).toEqual([OrganizationId("*")]);
+ expect(project?.resources).toEqual([ProjectId("*")]);
+ // The org wildcard carries an org action and the project wildcard a
+ // project action, i.e. each kind's policy bound to its own resource.
+ expect(org?.actions).toContain("projects:create");
+ expect(project?.actions).toContain("prompts:read");
});
});
@@ -95,13 +169,25 @@ describe("presentation rides in the input", () => {
authorization: "publicKey",
apiKey: apiKey(),
});
- expect(authorize(priv, "traces:read", { projectId: PRJ }).success).toBe(
+ expect(authorize(priv, TENANT, "traces:read", ProjectId(PRJ)).success).toBe(
true,
);
- expect(authorize(pub, "scores:create", { projectId: PRJ }).success).toBe(
+ expect(authorize(pub, TENANT, "scores:save", ProjectId(PRJ)).success).toBe(
true,
);
- expect(authorize(pub, "traces:read", { projectId: PRJ }).success).toBe(
+ expect(authorize(pub, TENANT, "traces:read", ProjectId(PRJ)).success).toBe(
+ false,
+ );
+ });
+});
+
+describe("publicKey is capped by the key's stored role", () => {
+ it("grants no scores:save to a key whose role lacks it", async () => {
+ const ctx = await contextFor({
+ authorization: "publicKey",
+ apiKey: apiKey({ id: "key_v" }),
+ });
+ expect(authorize(ctx, TENANT, "scores:save", ProjectId(PRJ)).success).toBe(
false,
);
});
@@ -113,20 +199,20 @@ describe("expansion table: scope PROJECT, privateKey", () => {
authorization: "privateKey",
apiKey: apiKey(),
});
- expect(authorize(ctx, "prompts:read", { projectId: PRJ }).success).toBe(
+ expect(authorize(ctx, TENANT, "prompts:read", ProjectId(PRJ)).success).toBe(
true,
);
- expect(authorize(ctx, "project:read", { projectId: PRJ }).success).toBe(
+ expect(authorize(ctx, TENANT, "project:read", ProjectId(PRJ)).success).toBe(
true,
);
- expect(authorize(ctx, "apiKeys:CUD", { projectId: PRJ }).success).toBe(
- false,
- );
- expect(authorize(ctx, "project:update", { projectId: PRJ }).success).toBe(
+ expect(authorize(ctx, TENANT, "apiKeys:CUD", ProjectId(PRJ)).success).toBe(
false,
);
expect(
- authorize(ctx, "prompts:read", { projectId: OTHER_PRJ }).success,
+ authorize(ctx, TENANT, "project:update", ProjectId(PRJ)).success,
+ ).toBe(false);
+ expect(
+ authorize(ctx, TENANT, "prompts:read", ProjectId(OTHER_PRJ)).success,
).toBe(false);
});
it("does not satisfy org-level actions", async () => {
@@ -134,27 +220,39 @@ describe("expansion table: scope PROJECT, privateKey", () => {
authorization: "privateKey",
apiKey: apiKey(),
});
- expect(authorize(ctx, "project:read", { orgId: ORG }).success).toBe(false);
+ expect(
+ authorize(ctx, TENANT, "project:read", OrganizationId(ORG)).success,
+ ).toBe(false);
});
});
describe("expansion table: scope ORGANIZATION, privateKey", () => {
- it("grants the org vocabulary plus project administration over its own projects only", async () => {
+ it("grants the org vocabulary plus project administration over any project of its own tenant", async () => {
const ctx = await contextFor({
authorization: "privateKey",
apiKey: orgKey(),
});
- expect(authorize(ctx, "projects:read", { orgId: ORG }).success).toBe(true);
- expect(authorize(ctx, "project:read", { projectId: PRJ }).success).toBe(
- true,
- );
- expect(authorize(ctx, "apiKeys:CUD", { projectId: PRJ }).success).toBe(
+ expect(
+ authorize(ctx, TENANT, "projects:read", OrganizationId(ORG)).success,
+ ).toBe(true);
+ expect(authorize(ctx, TENANT, "project:read", ProjectId(PRJ)).success).toBe(
true,
);
+ // The org key binds project actions to the project-kind wildcard, so any
+ // project of its own tenant is covered, not only the seeded ones.
+ expect(
+ authorize(ctx, TENANT, "apiKeys:CUD", ProjectId(OTHER_PRJ)).success,
+ ).toBe(true);
+ // The wildcard is tenant-scoped: a project of another org is not covered.
expect(
- authorize(ctx, "project:read", { projectId: "prj_foreign" }).success,
+ authorize(
+ ctx,
+ OrganizationId("org_foreign"),
+ "project:read",
+ ProjectId("prj_foreign"),
+ ).success,
).toBe(false);
- expect(authorize(ctx, "traces:read", { projectId: PRJ }).success).toBe(
+ expect(authorize(ctx, TENANT, "traces:read", ProjectId(PRJ)).success).toBe(
false,
);
});
@@ -201,9 +299,9 @@ describe("org suspension rides as a boolean, not a policy", () => {
const org =
ctx.principal.kind === "apiKey" ? ctx.principal.organizations[0] : null;
expect(org?.isIngestionSuspended).toBe(true);
- expect(authorize(ctx, "traces:create", { projectId: PRJ }).success).toBe(
- true,
- );
+ expect(
+ authorize(ctx, TENANT, "traces:create", ProjectId(PRJ)).success,
+ ).toBe(true);
});
});
diff --git a/web/src/__tests__/server/unit/policy/verifier.servertest.ts b/web/src/__tests__/server/unit/policy/verifier.servertest.ts
index 09ad7837b4..175da66dc7 100644
--- a/web/src/__tests__/server/unit/policy/verifier.servertest.ts
+++ b/web/src/__tests__/server/unit/policy/verifier.servertest.ts
@@ -2,15 +2,20 @@ import { describe, expect, it, vi } from "vitest";
import { InternalServerError } from "@langfuse/shared";
import { type ApiKey } from "@langfuse/shared/src/db";
-import { hashSecretKey } from "@langfuse/shared/src/server";
+import { hashSecretKey, verifySecretKey } from "@langfuse/shared/src/server";
-import { Verifier } from "@/src/features/apiKey/verifier";
+import { Verifier, invalidCredentials } from "@/src/features/apiKey/verifier";
import {
type FindApiKeyResult,
type ApiKeyRepository,
} from "@/src/features/apiKey/apiKeyRepository";
import { parseAuthorizationHeader } from "@/src/features/apiKey/helpers/parseAuthorizationHeader";
+vi.mock(import("@langfuse/shared/src/server"), async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, verifySecretKey: vi.fn(actual.verifySecretKey) };
+});
+
const SALT = "salt";
const ADMIN = "admin-secret";
@@ -104,6 +109,24 @@ describe("Basic authenticates the secret as privateKey", () => {
);
expect(result.success).toBe(false);
});
+ it("rejects a fast-hash mismatch without bcrypt or backfill", async () => {
+ const key = apiKey();
+ const store = stubStore({
+ findByPublicKey: vi.fn(async () => lookup(key)),
+ });
+ vi.mocked(verifySecretKey).mockClear();
+
+ const result = await verifier(store).verify(
+ parseAuthorizationHeader(basicHeader("pk-lf-1", "wrong-secret")),
+ );
+
+ expect(result).toMatchObject({
+ success: false,
+ error: { message: invalidCredentials },
+ });
+ expect(verifySecretKey).not.toHaveBeenCalled();
+ expect(store.backfillFastHash).not.toHaveBeenCalled();
+ });
});
describe("Bearer chains admin then private then public", () => {
@@ -166,6 +189,46 @@ describe("Bearer chains admin then private then public", () => {
});
});
+describe("an expired key is rejected like an unknown key", () => {
+ const expired = () => apiKey({ expiresAt: new Date(Date.now() - 60_000) });
+
+ it("401s an expired secret over Basic", async () => {
+ const store = stubStore({
+ findByFastHash: vi.fn(async () => lookup(expired())),
+ });
+ const result = await verifier(store).verify(
+ parseAuthorizationHeader(basicHeader("pk-lf-1", "sk")),
+ );
+ expect(result).toMatchObject({
+ success: false,
+ error: { message: invalidCredentials },
+ });
+ });
+ it("401s an expired public-key bearer", async () => {
+ const store = stubStore({
+ findByPublicKey: vi.fn(async () => lookup(expired())),
+ });
+ const result = await verifier(store).verify(
+ parseAuthorizationHeader("Bearer pk-lf-1"),
+ );
+ expect(result).toMatchObject({
+ success: false,
+ error: { message: invalidCredentials },
+ });
+ });
+ it("accepts a key expiring in the future", async () => {
+ const store = stubStore({
+ findByFastHash: vi.fn(async () =>
+ lookup(apiKey({ expiresAt: new Date(Date.now() + 60_000) })),
+ ),
+ });
+ const result = await verifier(store).verify(
+ parseAuthorizationHeader(basicHeader("pk-lf-1", "sk")),
+ );
+ expect(result.success).toBe(true);
+ });
+});
+
describe("admin key needs a set, non-empty configured key", () => {
it("is ignored when the configured key is unset", async () => {
const noKey = new Verifier(stubStore(), SALT, undefined);
diff --git a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
index 4f3e2ea228..acff4009fc 100644
--- a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
+++ b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
@@ -11,9 +11,6 @@ import {
const { getOrgId, getProjectId } = __test;
-const orgIdHeader = "x-langfuse-organization-id";
-const projectIdHeader = "x-langfuse-project-id";
-
const ORG = "org_1";
const PRJ = "prj_1";
@@ -56,10 +53,27 @@ describe("getOrgId", () => {
orgId: ORG,
});
});
- it("403s a header disagreeing with the bound org", () => {
+ it.each(["x-langfuse-organization-id", "langfuse-organization-id"])(
+ "403s %s disagreeing with the bound org",
+ (orgIdHeader) => {
+ expect(
+ getOrgId(orgKey(), req({}, { [orgIdHeader]: "org_2" })),
+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });
+ },
+ );
+ it("prefers the X-prefixed organization header when both are provided", () => {
expect(
- getOrgId(orgKey(), req({}, { [orgIdHeader]: "org_2" })),
- ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });
+ getOrgId(
+ orgKey(),
+ req(
+ {},
+ {
+ "x-langfuse-organization-id": ORG,
+ "langfuse-organization-id": "org_2",
+ },
+ ),
+ ),
+ ).toEqual({ success: true, orgId: ORG });
});
it("403s a principal carrying no binding", () => {
expect(getOrgId(adminKey(), req())).toMatchObject({
@@ -69,56 +83,73 @@ describe("getOrgId", () => {
});
});
-describe("getProjectId", () => {
- it("resolves the bound project without a header", () => {
- expect(getProjectId(projectKey(), req())).toEqual({
- success: true,
- projectId: PRJ,
+describe.each(["x-langfuse-project-id", "langfuse-project-id"])(
+ "getProjectId with %s",
+ (projectIdHeader) => {
+ it("resolves the bound project without a header", () => {
+ expect(getProjectId(projectKey(), req())).toEqual({
+ success: true,
+ projectId: PRJ,
+ });
});
- });
- it("resolves the bound project when the header is blank", () => {
- expect(
- getProjectId(projectKey(), req({}, { [projectIdHeader]: "" })),
- ).toEqual({ success: true, projectId: PRJ });
- });
- it("resolves an unbound principal from the header", () => {
- expect(getProjectId(orgKey(), req({}, { [projectIdHeader]: PRJ }))).toEqual(
- {
+ it("resolves the bound project when the header is blank", () => {
+ expect(
+ getProjectId(projectKey(), req({}, { [projectIdHeader]: "" })),
+ ).toEqual({ success: true, projectId: PRJ });
+ });
+ it("resolves an unbound principal from the header", () => {
+ expect(
+ getProjectId(orgKey(), req({}, { [projectIdHeader]: PRJ })),
+ ).toEqual({
success: true,
projectId: PRJ,
- },
- );
- });
- it("resolves when URL, header, and bound project agree", () => {
- expect(
- getProjectId(
- projectKey(),
- req({ projectId: PRJ }, { [projectIdHeader]: PRJ }),
- ),
- ).toEqual({ success: true, projectId: PRJ });
- });
- it("403s a header disagreeing with the bound project", () => {
- expect(
- getProjectId(projectKey(), req({}, { [projectIdHeader]: "prj_2" })),
- ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });
- });
- it("403s a URL disagreeing with the bound project", () => {
- expect(
- getProjectId(projectKey(), req({ projectId: "prj_2" })),
- ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });
- });
- it("403s a URL disagreeing with the header", () => {
- expect(
- getProjectId(
- orgKey(),
- req({ projectId: PRJ }, { [projectIdHeader]: "prj_2" }),
- ),
- ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });
- });
- it("403s when neither URL, header, nor bound project exists", () => {
- expect(getProjectId(orgKey(), req())).toMatchObject({
- success: false,
- error: expect.any(ForbiddenError),
+ });
});
- });
-});
+ it("resolves when URL, header, and bound project agree", () => {
+ expect(
+ getProjectId(
+ projectKey(),
+ req({ projectId: PRJ }, { [projectIdHeader]: PRJ }),
+ ),
+ ).toEqual({ success: true, projectId: PRJ });
+ });
+ it("403s a header disagreeing with the bound project", () => {
+ expect(
+ getProjectId(projectKey(), req({}, { [projectIdHeader]: "prj_2" })),
+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });
+ });
+ it("403s a URL disagreeing with the bound project", () => {
+ expect(
+ getProjectId(projectKey(), req({ projectId: "prj_2" })),
+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });
+ });
+ it("403s a URL disagreeing with the header", () => {
+ expect(
+ getProjectId(
+ orgKey(),
+ req({ projectId: PRJ }, { [projectIdHeader]: "prj_2" }),
+ ),
+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });
+ });
+ it("prefers the X-prefixed header when both are provided", () => {
+ expect(
+ getProjectId(
+ orgKey(),
+ req(
+ {},
+ {
+ "x-langfuse-project-id": PRJ,
+ "langfuse-project-id": "prj_2",
+ },
+ ),
+ ),
+ ).toEqual({ success: true, projectId: PRJ });
+ });
+ it("403s when neither URL, header, nor bound project exists", () => {
+ expect(getProjectId(orgKey(), req())).toMatchObject({
+ success: false,
+ error: expect.any(ForbiddenError),
+ });
+ });
+ },
+);
diff --git a/web/src/__tests__/server/unit/public-api/shadowAuth.servertest.ts b/web/src/__tests__/server/unit/public-api/shadowAuth.servertest.ts
index b380d38d78..1e8784d1f9 100644
--- a/web/src/__tests__/server/unit/public-api/shadowAuth.servertest.ts
+++ b/web/src/__tests__/server/unit/public-api/shadowAuth.servertest.ts
@@ -2,13 +2,16 @@ import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import { type NextApiRequest } from "next";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
ForbiddenError,
InternalServerError,
InvalidRequestError,
+ ServiceUnavailableError,
} from "@langfuse/shared";
+import { logger } from "@langfuse/shared/src/server";
+import { Prisma } from "@langfuse/shared/src/db";
const {
env,
@@ -155,6 +158,10 @@ describe("org-family dispatch (allowedAccessLevels ['organization'])", () => {
env.API_AUTH_MIGRATION = "enforce";
});
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it("returns the scope the new pipeline built, without calling legacy", async () => {
authzAllows();
expect(await call()).toEqual({
@@ -178,15 +185,78 @@ describe("org-family dispatch (allowedAccessLevels ['organization'])", () => {
});
});
- it("renders a new-pipeline 500 as a 500 denial", async () => {
- mockEnforceAuth.mockResolvedValue({
- success: false,
- error: new InternalServerError("unmappable principal"),
- });
+ it.each([
+ { name: "500", ErrorClass: InternalServerError },
+ { name: "503", ErrorClass: ServiceUnavailableError },
+ ])(
+ "sanitizes returned $name details while preserving its status and class",
+ async ({ ErrorClass }) => {
+ const diagnostic = "database host private-db:5432 rejected lookup";
+ const error = new ErrorClass(diagnostic);
+ const log = vi.spyOn(logger, "error").mockImplementation(() => logger);
+ mockEnforceAuth.mockResolvedValue({ success: false, error });
+
+ const result = await call();
+
+ expect(result).toMatchObject({
+ success: false,
+ error: {
+ httpCode: error.httpCode,
+ message: new ErrorClass().message,
+ },
+ });
+ if (result.success) throw new Error("Expected authentication failure");
+ expect(result.error).toBeInstanceOf(ErrorClass);
+ expect(error.message).toBe(diagnostic);
+ expect(JSON.stringify(log.mock.calls)).toContain(diagnostic);
+ },
+ );
+
+ it("sanitizes unexpected throws and redacts secrets from diagnostics", async () => {
+ const secret = "sk-lf-test-secret-12345678";
+ const log = vi.spyOn(logger, "error").mockImplementation(() => logger);
+ mockEnforceAuth.mockRejectedValue(new Error(`lookup failed ${secret}`));
+
expect(await call()).toMatchObject({
success: false,
- error: { httpCode: 500 },
+ error: { httpCode: 500, message: new InternalServerError().message },
});
+ const logged = JSON.stringify(log.mock.calls);
+ expect(logged).toContain("lookup failed");
+ expect(logged).not.toContain(secret);
+ });
+
+ it.each([
+ {
+ name: "typed",
+ error: new ServiceUnavailableError("database connection refused"),
+ },
+ {
+ name: "Prisma",
+ error: new Prisma.PrismaClientInitializationError(
+ "database connection refused",
+ "test",
+ "P1001",
+ ),
+ },
+ ])(
+ "returns a generic 503 for thrown $name infrastructure errors",
+ async ({ error }) => {
+ mockEnforceAuth.mockRejectedValue(error);
+ expect(await call()).toMatchObject({
+ success: false,
+ error: {
+ httpCode: 503,
+ message: new ServiceUnavailableError().message,
+ },
+ });
+ },
+ );
+
+ it("preserves thrown user errors", async () => {
+ const error = new InvalidRequestError("no target");
+ mockEnforceAuth.mockRejectedValue(error);
+ await expect(call()).rejects.toBe(error);
});
it("403s when the new pipeline denies, leaving the body to the route", async () => {
@@ -261,6 +331,42 @@ describe("project-family dispatch (allowedAccessLevels ['project'])", () => {
env.API_AUTH_MIGRATION = "legacy";
});
+ it.each(["legacy", "shadow"])(
+ "%s preserves legacy success and custom failure with a new-pipeline infrastructure failure",
+ async (mode) => {
+ env.API_AUTH_MIGRATION = mode;
+ const newFailure = {
+ success: false,
+ error: new InternalServerError("private database detail"),
+ };
+ mockEnforceAuth.mockResolvedValue(newFailure);
+ legacyAllows();
+ expect(await call()).toEqual({ success: true, scope: legacyScope.scope });
+
+ mockLegacyProjectAuth.mockRejectedValue({
+ status: 502,
+ message: "custom legacy infrastructure message",
+ });
+ const result = await call();
+ expect(result).toMatchObject({
+ success: false,
+ error: {
+ httpCode: 502,
+ message: "custom legacy infrastructure message",
+ },
+ });
+ if (mode === "shadow") {
+ expect(mockShadowAuthDiff).toHaveBeenLastCalledWith(
+ newFailure,
+ expect.objectContaining({ success: false }),
+ "traces:read",
+ );
+ } else {
+ expect(mockEnforceAuth).not.toHaveBeenCalled();
+ }
+ },
+ );
+
describe("legacy mode never runs the new pipeline", () => {
it("returns the legacy scope and skips enforceAuth", async () => {
legacyAllows();
diff --git a/web/src/__tests__/server/unit/public-api/shadowAuthorize.servertest.ts b/web/src/__tests__/server/unit/public-api/shadowAuthorize.servertest.ts
index 194780858e..78ef6aa29e 100644
--- a/web/src/__tests__/server/unit/public-api/shadowAuthorize.servertest.ts
+++ b/web/src/__tests__/server/unit/public-api/shadowAuthorize.servertest.ts
@@ -1,6 +1,12 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { ForbiddenError } from "@langfuse/shared";
+import { ForbiddenError, UnauthorizedError } from "@langfuse/shared";
+import {
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ type ProjectAction,
+} from "@langfuse/shared/rbac";
const { env } = vi.hoisted(() => ({
env: { API_AUTH_MIGRATION: "enforce" as string },
@@ -19,20 +25,21 @@ import {
__dangerouslySkipAuthz,
type ApiAction,
} from "@/src/features/public-api/server";
-import {
- type AuthorizationContext,
- type Policy,
- type ProjectAction,
-} from "@/src/features/auth/policy/types";
+import { type Prisma } from "@langfuse/shared/src/db";
+import { authorizeProtectedLabelMutation } from "@/src/features/prompts/server/utils/authorizeProtectedLabelMutation";
+import { type Policy } from "@/src/features/rbac/types";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
const PRJ = "prj_1";
+const ORG = "org_1";
const allowPrompts: Policy = {
- kind: "project",
- source: { kind: "role", id: "PROJECT" },
+ id: "system/LEGACY_PROJECT_API_KEY:project",
+ tenantId: OrganizationId(ORG),
+ roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),
actions: ["prompts:read"] as ProjectAction[] as never,
- resources: [PRJ],
- effect: "allow",
+ resources: [ProjectId(PRJ)],
+ effect: "ALLOW",
};
const authContext = (policies: Policy[]): AuthorizationContext => ({
@@ -54,7 +61,10 @@ const params = (action: ApiAction, ctx: AuthorizationContext | undefined) => ({
ctx,
action,
resource: { projectId: PRJ },
- accessLevel: "project" as const,
+ legacyDecision: {
+ success: true as const,
+ scope: { accessLevel: "project" as const },
+ },
});
describe("shadowAuthorize", () => {
@@ -87,9 +97,42 @@ describe("shadowAuthorize", () => {
});
});
- it("passes when no context resolved (legacy)", () => {
+ it.each(["legacy", "shadow"])("passes without context in %s", (mode) => {
+ env.API_AUTH_MIGRATION = mode;
expect(shadowAuthorize(params("prompts:CUD", undefined))).toEqual({
success: true,
+ scope: { accessLevel: "project" },
+ });
+ });
+
+ it.each([
+ ["legacy", undefined],
+ ["shadow", undefined],
+ ["shadow", authContext([allowPrompts])],
+ ] as const)(
+ "preserves a legacy denial in %s with context %j",
+ (mode, ctx) => {
+ env.API_AUTH_MIGRATION = mode;
+ const legacyDecision = {
+ success: false as const,
+ error: new UnauthorizedError("Access Scope Denied"),
+ };
+ expect(
+ shadowAuthorize({ ...params("prompts:read", ctx), legacyDecision }),
+ ).toEqual(legacyDecision);
+ },
+ );
+
+ it("denies a gated item without context in enforce", () => {
+ expect(shadowAuthorize(params("prompts:CUD", undefined))).toMatchObject({
+ success: false,
+ error: expect.any(UnauthorizedError),
+ });
+ });
+
+ it("allows an explicit opt-out without context in enforce", () => {
+ expect(shadowAuthorize(params(__dangerouslySkipAuthz, undefined))).toEqual({
+ success: true,
});
});
@@ -102,7 +145,10 @@ describe("shadowAuthorize", () => {
const decision = shadowAuthorize(
params("prompts:CUD", authContext([allowPrompts])),
);
- expect(decision).toEqual({ success: true });
+ expect(decision).toEqual({
+ success: true,
+ scope: { accessLevel: "project" },
+ });
expect(shadowAuthDiff).toHaveBeenCalledWith(
{ success: false, error: expect.any(ForbiddenError) },
{ success: true, scope: { accessLevel: "project" } },
@@ -110,6 +156,29 @@ describe("shadowAuthorize", () => {
);
});
+ it.each(["prompts:read", "prompts:CUD"] as const)(
+ "compares %s against an actual legacy denial without changing the outcome",
+ (action) => {
+ const legacyDecision = {
+ success: false as const,
+ error: new ForbiddenError("Creator cannot mutate protected labels"),
+ };
+ expect(
+ shadowAuthorize({
+ ...params(action, authContext([allowPrompts])),
+ legacyDecision,
+ }),
+ ).toEqual(legacyDecision);
+ expect(shadowAuthDiff).toHaveBeenCalledWith(
+ action === "prompts:read"
+ ? { success: true }
+ : { success: false, error: expect.any(ForbiddenError) },
+ legacyDecision,
+ action,
+ );
+ },
+ );
+
it("diffs an allowed item", () => {
shadowAuthorize(params("prompts:read", authContext([allowPrompts])));
expect(shadowAuthDiff).toHaveBeenCalledWith(
@@ -120,3 +189,106 @@ describe("shadowAuthorize", () => {
});
});
});
+
+describe("protected-label legacy comparisons", () => {
+ beforeEach(() => {
+ env.API_AUTH_MIGRATION = "shadow";
+ shadowAuthDiff.mockClear();
+ });
+
+ const setup = () => {
+ const findApiKey = vi.fn().mockResolvedValue({
+ isInAppAgentKey: true,
+ createdByUserId: "missing-user",
+ });
+ return {
+ findApiKey,
+ params: {
+ prisma: {
+ promptProtectedLabels: {
+ findMany: vi.fn().mockResolvedValue([{ label: "production" }]),
+ },
+ apiKey: { findUnique: findApiKey },
+ user: { findUnique: vi.fn().mockResolvedValue(null) },
+ } as unknown as Prisma.TransactionClient,
+ context: {
+ projectId: PRJ,
+ orgId: ORG,
+ apiKeyId: "key_1",
+ accessLevel: "project" as const,
+ },
+ ctx: authContext([
+ { ...allowPrompts, actions: ["promptProtectedLabels:CUD"] },
+ ]),
+ labelsToCheck: ["production"],
+ forbiddenErrorMessage: "Cannot change protected labels",
+ },
+ };
+ };
+
+ it.each(["legacy", "shadow"])(
+ "preserves creator denial in %s and compares the real shadow baseline",
+ async (mode) => {
+ env.API_AUTH_MIGRATION = mode;
+ const { params } = setup();
+ await expect(
+ authorizeProtectedLabelMutation(params),
+ ).rejects.toMatchObject({
+ httpCode: 403,
+ message:
+ "Cannot change protected labels\n\n Protected labels are: production",
+ });
+ if (mode === "shadow") {
+ expect(shadowAuthDiff).toHaveBeenCalledWith(
+ { success: true },
+ { success: false, error: expect.any(ForbiddenError) },
+ "promptProtectedLabels:CUD",
+ );
+ } else {
+ expect(shadowAuthDiff).not.toHaveBeenCalled();
+ }
+ },
+ );
+
+ it("preserves a shadow creator denial without a resolved context", async () => {
+ const { params } = setup();
+ await expect(
+ authorizeProtectedLabelMutation({ ...params, ctx: undefined }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ expect(shadowAuthDiff).not.toHaveBeenCalled();
+ });
+
+ it("compares an ordinary key's allow without repeating the lookup", async () => {
+ const { params, findApiKey } = setup();
+ findApiKey.mockResolvedValueOnce({ isInAppAgentKey: false });
+ await expect(
+ authorizeProtectedLabelMutation(params),
+ ).resolves.toBeUndefined();
+ expect(findApiKey).toHaveBeenCalledTimes(1);
+ expect(shadowAuthDiff).toHaveBeenCalledWith(
+ { success: true },
+ { success: true, scope: { accessLevel: "project" } },
+ "promptProtectedLabels:CUD",
+ );
+ });
+
+ it("keeps the enforce decision ahead of creator lookups", async () => {
+ env.API_AUTH_MIGRATION = "enforce";
+ const { params, findApiKey } = setup();
+ await expect(
+ authorizeProtectedLabelMutation({
+ ...params,
+ ctx: authContext([]),
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ expect(findApiKey).not.toHaveBeenCalled();
+ });
+
+ it("propagates creator lookup failures without reporting an auth denial", async () => {
+ const { params, findApiKey } = setup();
+ const error = new Error("database unavailable");
+ findApiKey.mockRejectedValueOnce(error);
+ await expect(authorizeProtectedLabelMutation(params)).rejects.toBe(error);
+ expect(shadowAuthDiff).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
index 9ad19e282d..ab78cbd87b 100644
--- a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
+++ b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
@@ -45,6 +45,7 @@ const { envMock, prismaMock, loggerMock, fetchMock } = vi.hoisted(() => {
},
organizationMembership: {
findFirst: vi.fn(async (): Promise<unknown> => null),
+ findUnique: vi.fn(async (): Promise<unknown> => null),
findMany: vi.fn(async (): Promise<unknown[]> => []),
count: vi.fn(async () => 1),
create: vi.fn(async (): Promise<unknown> => ({})),
@@ -63,6 +64,9 @@ const { envMock, prismaMock, loggerMock, fetchMock } = vi.hoisted(() => {
auditLog: {
create: vi.fn(async () => ({})),
},
+ apiKey: {
+ findUnique: vi.fn(async (): Promise<unknown> => null),
+ },
// Starter-org provisioning serializes on SELECT ... FOR UPDATE.
$queryRaw: vi.fn(async (): Promise<unknown> => []),
// tRPC organizations.create wraps its writes in a callback transaction;
@@ -126,7 +130,9 @@ import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/create
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import { handleUpdateMembership } from "@/src/ee/features/admin-api/server/memberships";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
import { CloudConfigSchema, Role } from "@langfuse/shared";
+import { OrganizationId, SystemRoleId } from "@langfuse/shared/rbac";
import { type PrismaClient } from "@langfuse/shared/src/db";
import type { Session } from "next-auth";
import { type NextApiRequest, type NextApiResponse } from "next";
@@ -784,6 +790,38 @@ describe("call site: tRPC members.updateOrgMembership", () => {
describe("call site: admin API handleUpdateMembership", () => {
const member = { id: "member-1", email: "[email protected]", name: "Member" };
+ const context: AuthorizationContext = {
+ principal: {
+ kind: "apiKey",
+ apiKeyId: "key-1",
+ userId: null,
+ isInAppAgentKey: false,
+ publicKey: "pk-lf-test",
+ scope: "ORGANIZATION",
+ presentation: "privateKey",
+ organizations: [
+ {
+ orgId: "org-1",
+ organizationCreatedAt: ORG_CREATED_AT.toISOString(),
+ plan: "cloud:team",
+ rateLimitOverrides: [],
+ projectIds: [],
+ isIngestionSuspended: false,
+ },
+ ],
+ boundResource: { orgId: "org-1" },
+ },
+ policies: [
+ {
+ id: "membership-admin",
+ roleId: SystemRoleId("ADMIN"),
+ tenantId: OrganizationId("org-1"),
+ effect: "ALLOW",
+ actions: ["organizationMembers:CUD"],
+ resources: [OrganizationId("org-1")],
+ },
+ ],
+ };
it("syncs a downgrade to NONE as removeUser", async () => {
prismaMock.user.findUnique.mockResolvedValueOnce(member);
@@ -798,7 +836,7 @@ describe("call site: admin API handleUpdateMembership", () => {
body: { userId: "member-1", role: "NONE" },
} as NextApiRequest;
const res = createMockRes();
- await handleUpdateMembership(req, res, "org-1");
+ await handleUpdateMembership(req, res, "org-1", "key-1", context);
expect(res.statusCode).toBe(200);
expect(fetchMock).toHaveBeenCalledOnce();
@@ -825,7 +863,7 @@ describe("call site: admin API handleUpdateMembership", () => {
body: { userId: "member-1", role: "MEMBER" },
} as NextApiRequest;
const res = createMockRes();
- await handleUpdateMembership(req, res, "org-1");
+ await handleUpdateMembership(req, res, "org-1", "key-1", context);
expect(res.statusCode).toBe(200);
expect(fetchMock).toHaveBeenCalledOnce();
diff --git a/web/src/__tests__/server/unit/skill-service.servertest.ts b/web/src/__tests__/server/unit/skill-service.servertest.ts
index c0f9feb9aa..d4c1bb31be 100644
--- a/web/src/__tests__/server/unit/skill-service.servertest.ts
+++ b/web/src/__tests__/server/unit/skill-service.servertest.ts
@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ProjectAuthedContext } from "@/src/server/api/trpc";
import type { PrismaClient } from "@langfuse/shared/src/db";
+import { OrganizationId, ProjectId, SystemRoleId } from "@langfuse/shared/rbac";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
import { SkillService } from "@/src/features/skills/server/skill-service";
import { auditLog } from "@/src/features/audit-logs/server";
@@ -131,6 +133,29 @@ describe("SkillService versions", () => {
orgId: "org",
apiKeyId: "api-key",
accessLevel: "project" as const,
+ ctx: {
+ principal: {
+ kind: "apiKey",
+ apiKeyId: "api-key",
+ userId: "user",
+ isInAppAgentKey: false,
+ publicKey: "pk-lf-test",
+ scope: "PROJECT",
+ presentation: "privateKey",
+ organizations: [],
+ boundResource: { orgId: "org", projectId: "project" },
+ },
+ policies: [
+ {
+ id: "system/LEGACY_PROJECT_API_KEY:project",
+ roleId: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ tenantId: OrganizationId("org"),
+ effect: "ALLOW",
+ actions: ["promptProtectedLabels:CUD"],
+ resources: [ProjectId("project")],
+ },
+ ],
+ } satisfies AuthorizationContext,
},
};
return {
diff --git a/web/src/__tests__/server/unit/systemRoleAccessRights.servertest.ts b/web/src/__tests__/server/unit/systemRoleAccessRights.servertest.ts
new file mode 100644
index 0000000000..9974a0ded8
--- /dev/null
+++ b/web/src/__tests__/server/unit/systemRoleAccessRights.servertest.ts
@@ -0,0 +1,165 @@
+import { projectRoleAccessRights } from "@langfuse/shared";
+import {
+ allOrganizationActions,
+ allProjectActions,
+ organizationRoleAccessRights,
+ systemRoleAccessRights,
+ type ProjectAction,
+} from "@langfuse/shared/rbac";
+import { describe, expect, it } from "vitest";
+
+// The project-administration actions a legacy organization API key reserves and a
+// legacy project API key does not hold.
+const orgReservedProjectActions: ProjectAction[] = [
+ "apiKeys:read",
+ "apiKeys:CUD",
+ "projectMembers:read",
+ "projectMembers:CUD",
+ "projectMembers:manageOwnership",
+ "project:update",
+ "project:delete",
+];
+
+describe("systemRoleAccessRights", () => {
+ it.each([
+ ["OWNER", true],
+ ["LEGACY_ORGANIZATION_API_KEY", true],
+ ["ADMIN", false],
+ ["VIEWER", false],
+ ] as const)(
+ "grants protected ownership management to %s: %s",
+ (role, expected) => {
+ const actions = systemRoleAccessRights[role].policies
+ .filter((policy) => policy.resourceKind === "organization")
+ .flatMap((policy) => policy.actions);
+ expect(actions.includes("organizationMembers:manageOwnership")).toBe(
+ expected,
+ );
+ },
+ );
+
+ // Decision-equivalence guard: these api-key policies pin the exact action
+ // sets a later ticket depends on staying equal.
+ it("grants a legacy project API key every project action except the org-reserved admin actions", () => {
+ expect(systemRoleAccessRights.LEGACY_PROJECT_API_KEY.policies).toEqual([
+ {
+ resourceKind: "project",
+ effect: "ALLOW",
+ actions: allProjectActions.filter(
+ (action) => !orgReservedProjectActions.includes(action),
+ ),
+ },
+ ]);
+ });
+
+ it("grants a legacy organization API key the full org vocab plus project administration", () => {
+ expect(systemRoleAccessRights.LEGACY_ORGANIZATION_API_KEY.policies).toEqual(
+ [
+ {
+ resourceKind: "organization",
+ effect: "ALLOW",
+ actions: allOrganizationActions,
+ },
+ {
+ resourceKind: "project",
+ effect: "ALLOW",
+ actions: [
+ "project:read",
+ "apiKeys:read",
+ "apiKeys:CUD",
+ "projectMembers:read",
+ "projectMembers:CUD",
+ "projectMembers:manageOwnership",
+ "project:update",
+ "project:delete",
+ ],
+ },
+ ],
+ );
+ });
+
+ it("grants SCORES_INGEST exactly scores:save at project scope", () => {
+ expect(systemRoleAccessRights.SCORES_INGEST.policies).toEqual([
+ {
+ resourceKind: "project",
+ effect: "ALLOW",
+ actions: ["scores:save"],
+ },
+ ]);
+ });
+
+ it("grants INGEST exactly the ingestion project actions", () => {
+ expect(systemRoleAccessRights.INGEST.policies).toEqual([
+ {
+ resourceKind: "project",
+ effect: "ALLOW",
+ actions: ["traces:create", "scores:save", "media:create"],
+ },
+ ]);
+ });
+
+ it("grants AI_GATEWAY exactly gateway:invoke at org scope", () => {
+ expect(systemRoleAccessRights.AI_GATEWAY.policies).toEqual([
+ {
+ resourceKind: "organization",
+ effect: "ALLOW",
+ actions: ["gateway:invoke"],
+ },
+ ]);
+ });
+
+ it.each(["OWNER", "ADMIN", "MEMBER", "VIEWER", "NONE"] as const)(
+ "derives %s policies from the org and project access-right tables",
+ (role) => {
+ expect(systemRoleAccessRights[role].policies).toEqual([
+ {
+ resourceKind: "organization",
+ effect: "ALLOW",
+ actions: organizationRoleAccessRights[role],
+ },
+ {
+ resourceKind: "project",
+ effect: "ALLOW",
+ actions: projectRoleAccessRights[role],
+ },
+ ]);
+ },
+ );
+
+ it("grants VIEWER public-API reads without write actions", () => {
+ const viewerProjectActions = systemRoleAccessRights.VIEWER.policies
+ .filter((policy) => policy.resourceKind === "project")
+ .flatMap((policy) => policy.actions);
+ expect(viewerProjectActions).toContain("traces:read");
+ expect(viewerProjectActions).not.toContain("scores:save");
+ });
+
+ it("keys every definition by its own id", () => {
+ for (const [key, definition] of Object.entries(systemRoleAccessRights)) {
+ expect(definition.id).toBe(key);
+ }
+ });
+
+ it("tags api-key roles and user roles disjointly", () => {
+ const tagsFor = (role: keyof typeof systemRoleAccessRights) =>
+ systemRoleAccessRights[role].tags;
+ for (const role of ["SCORES_INGEST", "INGEST", "AI_GATEWAY"] as const) {
+ expect(tagsFor(role)).toEqual(["principal:apiKey"]);
+ }
+ for (const role of [
+ "LEGACY_PROJECT_API_KEY",
+ "LEGACY_ORGANIZATION_API_KEY",
+ ] as const) {
+ expect(tagsFor(role)).toEqual(["principal:apiKey", "legacy"]);
+ }
+ for (const role of [
+ "OWNER",
+ "ADMIN",
+ "MEMBER",
+ "VIEWER",
+ "NONE",
+ ] as const) {
+ expect(tagsFor(role)).toContain("principal:user");
+ }
+ });
+});
diff --git a/web/src/__tests__/server/unit/typescript-sdk-deprecations.servertest.ts b/web/src/__tests__/server/unit/typescript-sdk-deprecations.servertest.ts
index 9ee7ac7ca1..6bde5d7858 100644
--- a/web/src/__tests__/server/unit/typescript-sdk-deprecations.servertest.ts
+++ b/web/src/__tests__/server/unit/typescript-sdk-deprecations.servertest.ts
@@ -31,6 +31,14 @@ const DEFINITION = `service:
message: Use listNewThings() instead.
method: GET
path: /widgets
+types:
+ Widget:
+ properties:
+ oldValue:
+ type: optional<string>
+ availability:
+ status: deprecated
+ message: Use value instead.
`;
const GENERATED_CLIENT = `export class GeneratedClient {
@@ -79,6 +87,7 @@ type Fixture = {
apiRoot: string;
clientPath: string;
requestPath: string;
+ responsePath: string;
};
function withFixture(
@@ -96,11 +105,13 @@ function withFixture(
resourceRoot,
"client/requests/GetThingRequest.ts",
);
+ const responsePath = path.join(resourceRoot, "types/Widget.ts");
try {
fs.mkdirSync(definitionDirectory, { recursive: true });
fs.mkdirSync(path.dirname(clientPath), { recursive: true });
fs.mkdirSync(path.dirname(requestPath), { recursive: true });
+ fs.mkdirSync(path.dirname(responsePath), { recursive: true });
fs.writeFileSync(path.join(definitionDirectory, "api.yml"), "name: api\n");
fs.writeFileSync(
path.join(definitionDirectory, "widget-service.yml"),
@@ -108,8 +119,18 @@ function withFixture(
);
fs.writeFileSync(clientPath, GENERATED_CLIENT);
fs.writeFileSync(requestPath, GENERATED_REQUEST);
+ fs.writeFileSync(
+ responsePath,
+ "export interface Widget {\n /** Existing field docs. */\n oldValue?: string;\n}\n",
+ );
- assertions({ definitionDirectory, apiRoot, clientPath, requestPath });
+ assertions({
+ definitionDirectory,
+ apiRoot,
+ clientPath,
+ requestPath,
+ responsePath,
+ });
} finally {
fs.rmSync(root, { recursive: true });
}
@@ -155,6 +176,10 @@ describe("TypeScript SDK deprecations", () => {
`${generatedPath.replaceAll(path.sep, "/")}:${typeName}.${propertyName}`,
),
).toEqual([
+ "api/resources/organizations/types/OrganizationApiKey.ts:OrganizationApiKey.note",
+ "api/resources/projects/client/requests/CreateApiKeyRequest.ts:CreateApiKeyRequest.note",
+ "api/resources/projects/types/ApiKeySummary.ts:ApiKeySummary.note",
+ "api/resources/projects/types/ApiKeyResponse.ts:ApiKeyResponse.note",
"api/resources/scim/client/requests/CreateUserRequest.ts:CreateUserRequest.password",
]);
});
@@ -162,16 +187,25 @@ describe("TypeScript SDK deprecations", () => {
it("patches exact messages across one shared client and is byte-idempotent", () => {
withFixture(
DEFINITION,
- ({ definitionDirectory, apiRoot, clientPath, requestPath }) => {
+ ({
+ definitionDirectory,
+ apiRoot,
+ clientPath,
+ requestPath,
+ responsePath,
+ }) => {
expect(
patchGeneratedTypeScriptDeprecations({
definitionDirectory,
apiRoot,
}),
- ).toEqual({ changedFiles: 2, decoratedSymbols: 3 });
+ ).toEqual({ changedFiles: 3, decoratedSymbols: 4 });
const client = fs.readFileSync(clientPath, "utf8");
const request = fs.readFileSync(requestPath, "utf8");
+ const response = fs.readFileSync(responsePath, "utf8");
+ expect(response).toContain("@deprecated Use value instead.");
+ expect(response).toContain("Existing field docs.");
expect(client.match(/@deprecated/g)).toHaveLength(2);
expect(client).toContain("@deprecated Use getNewThing() instead.");
expect(client).toContain("@deprecated Use listNewThings() instead.");
@@ -194,6 +228,7 @@ describe("TypeScript SDK deprecations", () => {
).toEqual({ changedFiles: 0, decoratedSymbols: 0 });
expect(fs.readFileSync(clientPath, "utf8")).toBe(client);
expect(fs.readFileSync(requestPath, "utf8")).toBe(request);
+ expect(fs.readFileSync(responsePath, "utf8")).toBe(response);
},
);
});
@@ -228,7 +263,7 @@ describe("TypeScript SDK deprecations", () => {
);
withFixture(
- `${DEFINITION}\ntypes:\n Widget:\n properties:\n oldValue:\n type: optional<string>\n availability:\n status: deprecated\n message: Use the current value.\n`,
+ `${DEFINITION}\n OldWidget:\n type: string\n availability:\n status: deprecated\n message: Use Widget instead.\n`,
({ definitionDirectory }) => {
expect(() =>
getFernTypeScriptDeprecations(definitionDirectory),
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index 059f6a3897..a7d7729c39 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -142,7 +142,8 @@ export async function makeAPICall<T = IngestionAPIResponse>(
auth?: string,
customHeaders?: Record<string, string>,
): Promise<{ body: T; status: number }> {
- const finalUrl = `http://localhost:3000${url.startsWith("/") ? url : `/${url}`}`;
+ const baseUrl = process.env.TEST_BASE_URL ?? "http://localhost:3000";
+ const finalUrl = `${baseUrl}${url.startsWith("/") ? url : `/${url}`}`;
const authorization =
auth || createBasicAuthHeader("pk-lf-1234567890", "sk-lf-1234567890");
const options = {
diff --git a/web/src/components/design-system/table/Table.tsx b/web/src/components/design-system/table/Table.tsx
index b24184f0d1..349b8372e9 100644
--- a/web/src/components/design-system/table/Table.tsx
+++ b/web/src/components/design-system/table/Table.tsx
@@ -318,7 +318,7 @@ export function Table<TData extends object>({
<tr
key={row.id}
className={cn(
- "hover:bg-accent h-12 transition-colors",
+ "group/row hover:bg-accent h-12 transition-colors",
rowHeight === "m" && "h-24",
rowHeight === "l" && "h-64",
onRowClick ? "cursor-pointer" : "cursor-default",
diff --git a/web/src/components/design-system/table/columns/createTextTableColumn.stories.tsx b/web/src/components/design-system/table/columns/createTextTableColumn.stories.tsx
index d1db35eb3c..fa4597091c 100644
--- a/web/src/components/design-system/table/columns/createTextTableColumn.stories.tsx
+++ b/web/src/components/design-system/table/columns/createTextTableColumn.stories.tsx
@@ -4,9 +4,9 @@ import { fn } from "storybook/test";
import preview from "../../../../../.storybook/preview";
import {
- DataTable,
+ Table,
type AsyncTableData,
-} from "@/src/components/table/data-table";
+} from "@/src/components/design-system/table/Table";
import { createTextTableColumn } from "./createTextTableColumn";
type Row = {
@@ -49,15 +49,7 @@ const columns = [
];
function TextTableColumnStory({ data }: { data: AsyncTableData<Row[]> }) {
- return (
- <DataTable
- tableName="text-column-story"
- columns={columns}
- data={data}
- hidePagination
- cellPadding="comfortable"
- />
- );
+ return <Table tableName="text-column-story" columns={columns} data={data} />;
}
const meta = preview.meta({
@@ -70,8 +62,7 @@ const meta = preview.meta({
export const Default = meta.story({
args: {
data: {
- isLoading: false,
- isError: false,
+ status: "success",
data: [{ name: "Production generation", count: 1200 }],
},
},
@@ -81,8 +72,7 @@ export const EmptyValue = meta.story({
name: "Empty Value",
args: {
data: {
- isLoading: false,
- isError: false,
+ status: "success",
data: [{ name: null, count: null }],
},
},
@@ -92,8 +82,7 @@ export const MappedValueLoading = meta.story({
name: "Mapped Value Loading",
args: {
data: {
- isLoading: false,
- isError: false,
+ status: "success",
data: [
{ name: "Production generation", count: null, isCountLoading: true },
],
@@ -104,8 +93,7 @@ export const MappedValueLoading = meta.story({
export const Loading = meta.story({
args: {
data: {
- isLoading: true,
- isError: false,
+ status: "loading",
},
},
});
diff --git a/web/src/components/design-system/table/columns/createTextTableColumn.tsx b/web/src/components/design-system/table/columns/createTextTableColumn.tsx
index 3ecaef9dec..f4e730299b 100644
--- a/web/src/components/design-system/table/columns/createTextTableColumn.tsx
+++ b/web/src/components/design-system/table/columns/createTextTableColumn.tsx
@@ -140,12 +140,14 @@ function TextWithTrailingAction<TData extends RowData, TValue>({
<TextWithAction
value={value}
action={
- <IconButton
- icon={action.icon}
- label={action.label}
- size="xs"
- onClick={() => action.onClick(context)}
- />
+ <span className="opacity-0 transition-opacity group-hover/row:opacity-100 focus-within:opacity-100">
+ <IconButton
+ icon={action.icon}
+ label={action.label}
+ size="xs"
+ onClick={() => action.onClick(context)}
+ />
+ </span>
}
/>
);
diff --git a/web/src/ee/features/admin-api/server/apiKeys.ts b/web/src/ee/features/admin-api/server/apiKeys.ts
new file mode 100644
index 0000000000..bed50299de
--- /dev/null
+++ b/web/src/ee/features/admin-api/server/apiKeys.ts
@@ -0,0 +1,50 @@
+import { z } from "zod/v4";
+
+import { type SystemRole } from "@langfuse/shared/src/db";
+
+const apiKeyCreationFields = {
+ name: z.string().optional(),
+ note: z.string().optional(),
+ expiresAt: z.iso
+ .datetime({ offset: true })
+ .transform((value) => new Date(value))
+ .refine((value) => value.getTime() > Date.now(), {
+ message: "expiresAt must be in the future",
+ })
+ .nullish(),
+};
+
+export const organizationApiKeyCreationSchema = z.object({
+ ...apiKeyCreationFields,
+ role: z
+ .enum(["LEGACY_ORGANIZATION_API_KEY", ""])
+ .nullish()
+ .transform((role) => role || "LEGACY_ORGANIZATION_API_KEY"),
+});
+
+export const projectApiKeyCreationSchema = z.object({
+ ...apiKeyCreationFields,
+ role: z
+ .enum(["LEGACY_PROJECT_API_KEY", ""])
+ .nullish()
+ .transform((role) => role || "LEGACY_PROJECT_API_KEY"),
+ publicKey: z.string().optional(),
+ secretKey: z.string().optional(),
+});
+
+/** apiKeyToResponse exposes the name alias and a role when exactly one is assigned. */
+export function apiKeyToResponse<
+ T extends {
+ note: string | null;
+ roleAssignments: { systemRole: SystemRole }[];
+ },
+>({ roleAssignments, ...apiKey }: T) {
+ return {
+ ...apiKey,
+ name: apiKey.note,
+ role:
+ roleAssignments.length === 1
+ ? (roleAssignments[0]?.systemRole ?? null)
+ : null,
+ };
+}
diff --git a/web/src/ee/features/admin-api/server/memberships.ts b/web/src/ee/features/admin-api/server/memberships.ts
index 2e45684a49..96c6c22b4e 100644
--- a/web/src/ee/features/admin-api/server/memberships.ts
+++ b/web/src/ee/features/admin-api/server/memberships.ts
@@ -1,8 +1,13 @@
import { type NextApiRequest, type NextApiResponse } from "next";
-import { prisma } from "@langfuse/shared/src/db";
-import { Role } from "@langfuse/shared";
import { z } from "zod";
+
import { getSfdcService } from "@/src/ee/features/sfdc-sync/server";
+import { auditLog } from "@/src/features/audit-logs/server";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+import { authorize } from "@/src/features/rbac/authorize";
+import { ForbiddenError, Role } from "@langfuse/shared";
+import { OrganizationId } from "@langfuse/shared/rbac";
+import { prisma, type Prisma } from "@langfuse/shared/src/db";
// Schema for request body validation
const MembershipSchema = z.object({
@@ -46,11 +51,13 @@ export async function handleGetMemberships(
});
}
-// PUT - Update or create an organization membership
+/** handleUpdateMembership upserts and audits an authorized organization membership. */
export async function handleUpdateMembership(
req: NextApiRequest,
res: NextApiResponse,
orgId: string,
+ apiKeyId: string,
+ context: AuthorizationContext,
) {
const validatedBody = MembershipSchema.safeParse(req.body);
if (!validatedBody.success) {
@@ -73,22 +80,41 @@ export async function handleUpdateMembership(
});
}
- // Upsert the membership
- const membership = await prisma.organizationMembership.upsert({
- where: {
- orgId_userId: {
+ const membership = await prisma.$transaction(async (tx) => {
+ await lockOrganization(tx, orgId);
+ const before = await tx.organizationMembership.findUnique({
+ where: { orgId_userId: { orgId, userId: validatedBody.data.userId } },
+ });
+ assertAuthorizeMembershipChange(context, orgId);
+ await assertValidOwnershipChange({
+ tx,
+ context,
+ orgId,
+ from: before?.role,
+ to: validatedBody.data.role,
+ });
+ const after = await tx.organizationMembership.upsert({
+ where: { orgId_userId: { orgId, userId: validatedBody.data.userId } },
+ update: { role: validatedBody.data.role },
+ create: {
orgId,
userId: validatedBody.data.userId,
+ role: validatedBody.data.role,
},
- },
- update: {
- role: validatedBody.data.role,
- },
- create: {
- orgId,
- userId: validatedBody.data.userId,
- role: validatedBody.data.role,
- },
+ });
+ await auditLog(
+ {
+ orgId,
+ apiKeyId,
+ resourceType: "orgMembership",
+ resourceId: after.id,
+ action: before ? "update" : "create",
+ before: before ?? undefined,
+ after,
+ },
+ tx,
+ );
+ return after;
});
await getSfdcService()?.setUserRole({
@@ -106,11 +132,13 @@ export async function handleUpdateMembership(
});
}
-// DELETE - Remove an organization membership
+/** handleDeleteMembership removes and audits an authorized organization membership. */
export async function handleDeleteMembership(
req: NextApiRequest,
res: NextApiResponse,
orgId: string,
+ apiKeyId: string,
+ context: AuthorizationContext,
) {
const validatedBody = DeleteMembershipSchema.safeParse(req.body);
if (!validatedBody.success) {
@@ -120,16 +148,37 @@ export async function handleDeleteMembership(
});
}
- // Delete the membership (using deleteMany to avoid errors on not found)
- const { count } = await prisma.organizationMembership.deleteMany({
- where: {
+ const deleted = await prisma.$transaction(async (tx) => {
+ await lockOrganization(tx, orgId);
+ const before = await tx.organizationMembership.findUnique({
+ where: { orgId_userId: { orgId, userId: validatedBody.data.userId } },
+ });
+ assertAuthorizeMembershipChange(context, orgId);
+ if (!before) return false;
+ await assertValidOwnershipChange({
+ tx,
+ context,
orgId,
- userId: validatedBody.data.userId,
- },
+ from: before.role,
+ });
+ await tx.organizationMembership.delete({
+ where: { id: before.id, orgId },
+ });
+ await auditLog(
+ {
+ orgId,
+ apiKeyId,
+ resourceType: "orgMembership",
+ resourceId: before.id,
+ action: "delete",
+ before,
+ },
+ tx,
+ );
+ return true;
});
- // SFDC: remove the org-member bridge if a membership actually existed
- if (count > 0) {
+ if (deleted) {
const user = await prisma.user.findUnique({
where: { id: validatedBody.data.userId },
select: { email: true },
@@ -146,3 +195,73 @@ export async function handleDeleteMembership(
userId: validatedBody.data.userId,
});
}
+
+/** lockOrganization serializes membership API mutations before reading owner state. */
+async function lockOrganization(tx: Prisma.TransactionClient, orgId: string) {
+ await tx.$queryRaw`SELECT id FROM organizations WHERE id = ${orgId} FOR UPDATE`;
+}
+
+function assertAuthorizeMembershipChange(
+ context: AuthorizationContext,
+ orgId: string,
+) {
+ const organization = OrganizationId(orgId);
+ const membershipAccess = authorize(
+ context,
+ organization,
+ "organizationMembers:CUD",
+ organization,
+ );
+ if (!membershipAccess.success) throw membershipAccess.error;
+}
+
+/** assertValidOwnershipChange checks ownership permission and preserves an owner under the organization lock. */
+async function assertValidOwnershipChange({
+ tx,
+ context,
+ orgId,
+ from,
+ to,
+}: {
+ tx: Prisma.TransactionClient;
+ context: AuthorizationContext;
+ orgId: string;
+ from: Role | undefined;
+ to?: Role;
+}) {
+ if (from === Role.OWNER || to === Role.OWNER) {
+ assertAuthorizeOwnershipChange(context, orgId);
+ }
+ if (from === Role.OWNER && to !== Role.OWNER) {
+ await assertOtherOwners(tx, orgId);
+ }
+}
+
+function assertAuthorizeOwnershipChange(
+ context: AuthorizationContext,
+ orgId: string,
+) {
+ const organization = OrganizationId(orgId);
+ const ownershipAccess = authorize(
+ context,
+ organization,
+ "organizationMembers:manageOwnership",
+ organization,
+ );
+ if (!ownershipAccess.success) throw ownershipAccess.error;
+}
+
+/** assertOtherOwners requires another owner before removing ownership under the organization lock. */
+async function assertOtherOwners(tx: Prisma.TransactionClient, orgId: string) {
+ const ownerCount = await tx.organizationMembership.count({
+ where: {
+ orgId,
+ role: Role.OWNER,
+ },
+ });
+ if (ownerCount < 2) {
+ throw new ForbiddenError(
+ "Cannot remove the last owner of an organization. Assign new owner or delete organization.",
+ );
+ }
+}
diff --git a/web/src/ee/features/admin-api/server/organizations/apiKeys/index.ts b/web/src/ee/features/admin-api/server/organizations/apiKeys/index.ts
index 27fc012377..82feb47528 100644
--- a/web/src/ee/features/admin-api/server/organizations/apiKeys/index.ts
+++ b/web/src/ee/features/admin-api/server/organizations/apiKeys/index.ts
@@ -3,7 +3,12 @@ import { prisma } from "@langfuse/shared/src/db";
import { logger } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/server";
import { z } from "zod";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
+import { OrganizationId, SystemRoleId } from "@langfuse/shared/rbac";
+import {
+ organizationApiKeyCreationSchema,
+ apiKeyToResponse,
+} from "@/src/ee/features/admin-api/server/apiKeys";
export const validateQueryAndExtractId = (query: unknown): string | null => {
const inputQuerySchema = z.object({
@@ -35,26 +40,23 @@ export async function handleGetApiKeys(
note: true,
publicKey: true,
displaySecretKey: true,
+ roleAssignments: { select: { systemRole: true } },
},
orderBy: {
createdAt: "asc",
},
});
- return res.status(200).json({ apiKeys });
+ return res.status(200).json({ apiKeys: apiKeys.map(apiKeyToResponse) });
}
+/** handleCreateApiKey provisions an organization key and records its audit event. */
export async function handleCreateApiKey(
req: NextApiRequest,
res: NextApiResponse,
organizationId: string,
) {
- // Validate the request body
- const createApiKeySchema = z.object({
- note: z.string().optional(),
- });
-
- const validationResult = createApiKeySchema.safeParse(req.body);
+ const validationResult = organizationApiKeyCreationSchema.safeParse(req.body);
if (!validationResult.success) {
return res.status(400).json({
@@ -63,14 +65,15 @@ export async function handleCreateApiKey(
});
}
- const { note } = validationResult.data;
+ const { name, note, expiresAt, role } = validationResult.data;
- // Create the API key
- const apiKeyMeta = await createAndAddApiKeysToDb({
- prisma,
- entityId: organizationId,
+ const apiKeyMeta = await createApiKey(prisma, {
+ owner: OrganizationId(organizationId),
+ role: SystemRoleId(role),
+ createdBy: "system",
+ name,
note,
- scope: "ORGANIZATION",
+ expiresAt,
});
// Log the API key creation
@@ -87,5 +90,10 @@ export async function handleCreateApiKey(
`Created API key ${apiKeyMeta.id} for organization ${organizationId} via admin API`,
);
- return res.status(201).json(apiKeyMeta);
+ return res.status(201).json({
+ ...apiKeyMeta,
+ name: apiKeyMeta.note,
+ expiresAt: expiresAt ?? null,
+ role,
+ });
}
diff --git a/web/src/ee/features/admin-api/server/projects.ts b/web/src/ee/features/admin-api/server/projects.ts
index d96f14a901..5b59bc2b50 100644
--- a/web/src/ee/features/admin-api/server/projects.ts
+++ b/web/src/ee/features/admin-api/server/projects.ts
@@ -1,11 +1,14 @@
import { type NextApiRequest, type NextApiResponse } from "next";
import { prisma } from "@langfuse/shared/src/db";
-
-import { authorize } from "@/src/features/auth/policy/authorize";
import {
+ OrganizationId,
+ ProjectId,
type Action,
- type AuthorizationContext,
-} from "@/src/features/auth/policy/types";
+ type TenantId,
+} from "@langfuse/shared/rbac";
+
+import { authorize } from "@/src/features/rbac/authorize";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
// GET - Retrieve all projects in an organization
export async function handleGetProjects(
@@ -30,7 +33,7 @@ export async function handleGetProjects(
return res.status(200).json({
projects: projects
- .filter(hasPermission(ctx, "project:read"))
+ .filter(hasPermission(ctx, OrganizationId(orgId), "project:read"))
.map((project) => ({
id: project.id,
name: project.name,
@@ -41,8 +44,8 @@ export async function handleGetProjects(
});
}
-/** hasPermission tests whether ctx permits action on a project, allowing all when ctx is absent. */
+/** hasPermission tests whether ctx permits action on a project in the tenant, allowing all when ctx is absent. */
const hasPermission =
- (ctx: AuthorizationContext | undefined, action: Action) =>
+ (ctx: AuthorizationContext | undefined, tenant: TenantId, action: Action) =>
(project: { id: string }) =>
- !ctx || authorize(ctx, action, { projectId: project.id }).success;
+ !ctx || authorize(ctx, tenant, action, ProjectId(project.id)).success;
diff --git a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById.ts b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById.ts
index 5daf720eb3..61a7314ab0 100644
--- a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById.ts
+++ b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById.ts
@@ -19,14 +19,15 @@ export const validateQueryParams = (
return validation.data;
};
+/** handleDeleteApiKey revokes a project key and records the authenticating actor. */
export async function handleDeleteApiKey(
req: NextApiRequest,
res: NextApiResponse,
projectId: string,
apiKeyId: string,
orgId: string,
+ authenticatingApiKeyId: string,
) {
- // Check if API key exists and belongs to the project
const apiKey = await prisma.apiKey.findFirst({
where: {
id: apiKeyId,
@@ -40,7 +41,6 @@ export async function handleDeleteApiKey(
return res.status(404).json({ message: "API key not found" });
}
- // Delete the API key
const deleted = await new ApiAuthService(prisma, redis).deleteApiKey(
apiKeyId,
projectId,
@@ -51,7 +51,6 @@ export async function handleDeleteApiKey(
return res.status(500).json({ message: "Failed to delete API key" });
}
- // Log the API key deletion
await auditLog({
resourceType: "apiKey",
resourceId: apiKeyId,
@@ -59,7 +58,7 @@ export async function handleDeleteApiKey(
orgId: orgId,
projectId: projectId,
orgRole: "ADMIN",
- apiKeyId: "ORG_KEY",
+ apiKeyId: authenticatingApiKeyId,
});
logger.info(
diff --git a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts
index 44e636f267..39f32b1a9d 100644
--- a/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts
+++ b/web/src/ee/features/admin-api/server/projects/projectById/apiKeys/index.ts
@@ -3,7 +3,12 @@ import { prisma } from "@langfuse/shared/src/db";
import { logger } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/server";
import { z } from "zod";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
+import { ApiKeyId, ProjectId, SystemRoleId } from "@langfuse/shared/rbac";
+import {
+ projectApiKeyCreationSchema,
+ apiKeyToResponse,
+} from "@/src/ee/features/admin-api/server/apiKeys";
export const validateQueryAndExtractId = (query: unknown): string | null => {
const inputQuerySchema = z.object({
@@ -35,15 +40,17 @@ export async function handleGetApiKeys(
note: true,
publicKey: true,
displaySecretKey: true,
+ roleAssignments: { select: { systemRole: true } },
},
orderBy: {
createdAt: "asc",
},
});
- return res.status(200).json({ apiKeys });
+ return res.status(200).json({ apiKeys: apiKeys.map(apiKeyToResponse) });
}
+/** handleCreateApiKey provisions a project key and records its audit event. */
export async function handleCreateApiKey(
req: NextApiRequest,
res: NextApiResponse,
@@ -51,14 +58,7 @@ export async function handleCreateApiKey(
orgId: string,
createdByApiKeyId?: string,
) {
- // Validate the request body
- const createApiKeySchema = z.object({
- note: z.string().optional(),
- publicKey: z.string().optional(),
- secretKey: z.string().optional(),
- });
-
- const validationResult = createApiKeySchema.safeParse(req.body);
+ const validationResult = projectApiKeyCreationSchema.safeParse(req.body);
if (!validationResult.success) {
return res.status(400).json({
@@ -67,11 +67,10 @@ export async function handleCreateApiKey(
});
}
- const { note, publicKey, secretKey } = validationResult.data;
+ const { name, note, expiresAt, role, publicKey, secretKey } =
+ validationResult.data;
- // Validate predefined keys if provided
if (publicKey || secretKey) {
- // Both keys must be provided together
if (!publicKey || !secretKey) {
return res.status(400).json({
message:
@@ -79,7 +78,6 @@ export async function handleCreateApiKey(
});
}
- // Validate key format
if (!publicKey.startsWith("pk-lf-")) {
return res.status(400).json({
message: "publicKey must start with 'pk-lf-'",
@@ -93,19 +91,24 @@ export async function handleCreateApiKey(
}
}
+ if (!createdByApiKeyId) {
+ return res.status(400).json({
+ message: "Missing authenticating API key",
+ });
+ }
+
try {
- // Create the API key
- const apiKeyMeta = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
+ const apiKeyMeta = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId(role),
+ createdBy: ApiKeyId(createdByApiKeyId),
+ name,
note,
- scope: "PROJECT",
- createdByApiKeyId,
+ expiresAt,
predefinedKeys:
publicKey && secretKey ? { publicKey, secretKey } : undefined,
});
- // Log the API key creation
await auditLog({
resourceType: "apiKey",
resourceId: apiKeyMeta.id,
@@ -113,16 +116,20 @@ export async function handleCreateApiKey(
orgId: orgId,
projectId: projectId,
orgRole: "ADMIN",
- apiKeyId: "ORG_KEY",
+ apiKeyId: createdByApiKeyId,
});
logger.info(
`Created API key ${apiKeyMeta.id} for project ${projectId} via public API`,
);
- return res.status(201).json(apiKeyMeta);
+ return res.status(201).json({
+ ...apiKeyMeta,
+ name: apiKeyMeta.note,
+ expiresAt: expiresAt ?? null,
+ role,
+ });
} catch (error) {
- // Handle database unique constraint violations
if (
error instanceof Error &&
(error.message.includes("Unique constraint") ||
diff --git a/web/src/ee/features/admin-api/server/projects/projectById/memberships/index.ts b/web/src/ee/features/admin-api/server/projects/projectById/memberships/index.ts
index 8824259cb3..aa29528f15 100644
--- a/web/src/ee/features/admin-api/server/projects/projectById/memberships/index.ts
+++ b/web/src/ee/features/admin-api/server/projects/projectById/memberships/index.ts
@@ -1,8 +1,17 @@
import { type NextApiRequest, type NextApiResponse } from "next";
-import { prisma } from "@langfuse/shared/src/db";
-import { Role } from "@langfuse/shared";
import { z } from "zod";
+import { auditLog } from "@/src/features/audit-logs/server";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+import { authorize } from "@/src/features/rbac/authorize";
+import { ForbiddenError, Role } from "@langfuse/shared";
+import { OrganizationId, ProjectId } from "@langfuse/shared/rbac";
+import {
+ prisma,
+ type Prisma,
+ type ProjectMembership,
+} from "@langfuse/shared/src/db";
+
// Schema for request body validation
const MembershipSchema = z.object({
userId: z.string(),
@@ -49,12 +58,14 @@ export async function handleGetMemberships(
});
}
-// PUT - Update or create a project membership
+/** handleUpdateMembership upserts and audits an authorized project membership. */
export async function handleUpdateMembership(
req: NextApiRequest,
res: NextApiResponse,
projectId: string,
orgId: string,
+ apiKeyId: string,
+ context: AuthorizationContext,
) {
const validatedBody = MembershipSchema.safeParse(req.body);
if (!validatedBody.success) {
@@ -88,24 +99,17 @@ export async function handleUpdateMembership(
});
}
- // Upsert the project membership
- const membership = await prisma.projectMembership.upsert({
- where: {
- projectId_userId: {
- userId: validatedBody.data.userId,
- projectId: projectId,
- },
- },
- update: {
- role: validatedBody.data.role,
- },
- create: {
+ const membership = await prisma.$transaction((tx) =>
+ updateMembership(tx, {
+ projectId,
+ orgId,
+ apiKeyId,
+ context,
userId: validatedBody.data.userId,
- projectId: projectId,
role: validatedBody.data.role,
orgMembershipId: orgMembership.id,
- },
- });
+ }),
+ );
return res.status(200).json({
userId: membership.userId,
@@ -115,12 +119,14 @@ export async function handleUpdateMembership(
});
}
-// DELETE - Remove a project membership
+/** handleDeleteMembership removes and audits an authorized project membership. */
export async function handleDeleteMembership(
req: NextApiRequest,
res: NextApiResponse,
projectId: string,
orgId: string,
+ apiKeyId: string,
+ context: AuthorizationContext,
) {
const validatedBody = DeleteMembershipSchema.safeParse(req.body);
if (!validatedBody.success) {
@@ -130,48 +136,201 @@ export async function handleDeleteMembership(
});
}
- // Check if membership exists
- const membership = await prisma.projectMembership.findUnique({
- where: {
- projectId_userId: {
- userId: validatedBody.data.userId,
- projectId: projectId,
- },
- },
- include: {
- organizationMembership: {
- select: {
- orgId: true,
- },
- },
- },
- });
+ const deleted = await prisma.$transaction((tx) =>
+ deleteMembership(tx, {
+ projectId,
+ orgId,
+ apiKeyId,
+ context,
+ userId: validatedBody.data.userId,
+ }),
+ );
- if (!membership) {
+ if (!deleted) {
return res.status(404).json({
error: "Project membership not found",
});
}
- // Verify the membership belongs to the correct organization
- if (membership.organizationMembership.orgId !== orgId) {
- return res.status(403).json({
- error: "Project membership does not belong to this organization",
- });
- }
+ return res.status(200).json({
+ message: "Project membership deleted successfully",
+ userId: validatedBody.data.userId,
+ });
+}
+
+/** updateMembership authorizes and audits the upsert within its transaction. */
+async function updateMembership(
+ tx: Prisma.TransactionClient,
+ params: MembershipMutation & { role: Role; orgMembershipId: string },
+) {
+ const { projectId, orgId, userId, role, orgMembershipId, context } = params;
+ await lockProject(tx, projectId, orgId);
+ const before = await tx.projectMembership.findUnique({
+ where: { projectId_userId: { projectId, userId } },
+ });
+ assertAuthorizeMembershipChange({
+ context,
+ orgId,
+ projectId,
+ from: before?.role,
+ to: role,
+ });
+ const after = await upsertMembership(tx, {
+ projectId,
+ userId,
+ role,
+ orgMembershipId,
+ });
+ await auditMembershipUpsert(tx, params, before ?? undefined, after);
+ return after;
+}
- // Delete the membership
- await prisma.projectMembership.delete({
+function upsertMembership(
+ tx: Prisma.TransactionClient,
+ data: {
+ projectId: string;
+ userId: string;
+ role: Role;
+ orgMembershipId: string;
+ },
+) {
+ return tx.projectMembership.upsert({
where: {
- projectId_userId: {
- userId: validatedBody.data.userId,
- projectId: projectId,
- },
+ projectId_userId: { projectId: data.projectId, userId: data.userId },
},
+ update: { role: data.role },
+ create: data,
});
+}
- return res.status(200).json({
- message: "Project membership deleted successfully",
- userId: validatedBody.data.userId,
+/** deleteMembership authorizes and audits removal within its transaction. */
+async function deleteMembership(
+ tx: Prisma.TransactionClient,
+ params: MembershipMutation,
+) {
+ const { projectId, orgId, userId, context } = params;
+ await lockProject(tx, projectId, orgId);
+ const before = await findMembershipWithOrganization(tx, projectId, userId);
+ assertAuthorizeMembershipChange({
+ context,
+ orgId,
+ projectId,
+ from: before?.role,
+ });
+ if (!before) return false;
+ assertMembershipOrganization(before.organizationMembership.orgId, orgId);
+ const membership = await tx.projectMembership.delete({
+ where: { projectId_userId: { projectId, userId: before.userId } },
});
+ await auditMembershipDeletion(tx, params, membership);
+ return true;
}
+
+function findMembershipWithOrganization(
+ tx: Prisma.TransactionClient,
+ projectId: string,
+ userId: string,
+) {
+ return tx.projectMembership.findUnique({
+ where: { projectId_userId: { projectId, userId } },
+ include: { organizationMembership: { select: { orgId: true } } },
+ });
+}
+
+function assertMembershipOrganization(membershipOrgId: string, orgId: string) {
+ if (membershipOrgId !== orgId) {
+ throw new ForbiddenError(
+ "Project membership does not belong to this organization",
+ );
+ }
+}
+
+function auditMembershipUpsert(
+ tx: Prisma.TransactionClient,
+ { orgId, projectId, apiKeyId }: MembershipMutation,
+ before: ProjectMembership | undefined,
+ after: ProjectMembership,
+) {
+ return auditLog(
+ {
+ orgId,
+ projectId,
+ apiKeyId,
+ resourceType: "projectMembership",
+ resourceId: `${projectId}--${after.userId}`,
+ action: before ? "update" : "create",
+ before,
+ after,
+ },
+ tx,
+ );
+}
+
+function auditMembershipDeletion(
+ tx: Prisma.TransactionClient,
+ { orgId, projectId, apiKeyId }: MembershipMutation,
+ before: ProjectMembership,
+) {
+ return auditLog(
+ {
+ orgId,
+ projectId,
+ apiKeyId,
+ resourceType: "projectMembership",
+ resourceId: `${projectId}--${before.userId}`,
+ action: "delete",
+ before,
+ },
+ tx,
+ );
+}
+
+/** lockProject serializes membership API mutations before reading ownership. */
+async function lockProject(
+ tx: Prisma.TransactionClient,
+ projectId: string,
+ orgId: string,
+) {
+ await tx.$queryRaw`SELECT id FROM projects WHERE id = ${projectId} AND org_id = ${orgId} FOR UPDATE`;
+}
+
+function assertAuthorizeMembershipChange({
+ context,
+ orgId,
+ projectId,
+ from,
+ to,
+}: {
+ context: AuthorizationContext;
+ orgId: string;
+ projectId: string;
+ from: Role | undefined;
+ to?: Role;
+}) {
+ const organization = OrganizationId(orgId);
+ const project = ProjectId(projectId);
+ const membershipAccess = authorize(
+ context,
+ organization,
+ "projectMembers:CUD",
+ project,
+ );
+ if (!membershipAccess.success) throw membershipAccess.error;
+ if (from !== Role.OWNER && to !== Role.OWNER) return;
+ const ownershipAccess = authorize(
+ context,
+ organization,
+ "projectMembers:manageOwnership",
+ project,
+ );
+ if (!ownershipAccess.success) throw ownershipAccess.error;
+}
+
+/** MembershipMutation carries the caller and target for a project membership write. */
+type MembershipMutation = {
+ projectId: string;
+ orgId: string;
+ apiKeyId: string;
+ userId: string;
+ context: AuthorizationContext;
+};
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 5c24b10e73..9a228d4b45 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -401,7 +401,6 @@ export const env = createEnv({
.number()
.default(60),
- // auth migration; self-host and default stay legacy
API_AUTH_MIGRATION: z
.enum(["legacy", "shadow", "enforce"])
.default("legacy"),
diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx
index e041a022b2..99355cd6f3 100644
--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx
+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/CreateGatewayApiKeyDialogController/CreateGatewayApiKeyDialogController.tsx
@@ -38,7 +38,7 @@ export function CreateGatewayApiKeyDialogController({
organizationId: string;
children: (control: { openDialog: () => void }) => ReactNode;
}) {
- const [note, setNote] = useState("");
+ const [name, setName] = useState("");
const [metadata, setMetadata] = useState<MetadataField[]>(() => [
{ id: 1, key: "", value: "" },
]);
@@ -55,7 +55,7 @@ export function CreateGatewayApiKeyDialogController({
});
const reset = () => {
- setNote("");
+ setName("");
setMetadata([{ id: 1, key: "", value: "" }]);
setIsMetadataOpen(false);
setGeneratedKeys(null);
@@ -73,7 +73,7 @@ export function CreateGatewayApiKeyDialogController({
try {
const created = await create.mutateAsync({
orgId: organizationId,
- note: note.trim() || undefined,
+ name: name.trim() || undefined,
metadata: metadataObject,
});
setGeneratedKeys({
@@ -108,7 +108,7 @@ export function CreateGatewayApiKeyDialogController({
<DialogBody>
<div>
<Label
- htmlFor="gateway-key-note"
+ htmlFor="gateway-key-name"
className="flex items-center gap-1.5"
>
Description
@@ -118,12 +118,12 @@ export function CreateGatewayApiKeyDialogController({
</InfoTooltip>
</Label>
<Input
- id="gateway-key-note"
+ id="gateway-key-name"
className="mt-1.5"
maxLength={500}
placeholder="e.g. Checkout agent, backend service"
- value={note}
- onChange={(event) => setNote(event.target.value)}
+ value={name}
+ onChange={(event) => setName(event.target.value)}
/>
</div>
<Collapsible
diff --git a/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts b/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts
index 0251aaf1de..468e996d85 100644
--- a/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts
+++ b/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts
@@ -1,9 +1,10 @@
import { InternalServerError, LangfuseNotFoundError } from "@langfuse/shared";
import type { PrismaClient } from "@langfuse/shared/src/db";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
deleteApiKeyFromDb,
} from "@langfuse/shared/src/server/auth/apiKeys";
+import { OrganizationId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import type { Cluster, Redis } from "ioredis";
import { auditLog } from "@/src/features/audit-logs/server";
@@ -28,18 +29,16 @@ export class GatewayApiKeyService {
async create(params: {
organizationId: string;
- note?: string;
+ name?: string;
metadata: GatewayMetadata;
session: OrgAuthedContext["session"];
}) {
const key = await this.prisma.$transaction(async (tx) => {
- // TODO: Narrow this virtual key to the `gateway:invoke` permission once granular API-key scopes are available.
- const key = await createAndAddApiKeysToDb({
- prisma: tx,
- entityId: params.organizationId,
- scope: "ORGANIZATION",
- note: params.note,
- createdByUserId: params.session.user.id,
+ const key = await createApiKey(tx, {
+ owner: OrganizationId(params.organizationId),
+ role: SystemRoleId("AI_GATEWAY"),
+ createdBy: UserId(params.session.user.id),
+ name: params.name,
});
await tx.gatewayApiKeyAssociation.create({
data: {
diff --git a/web/src/features/ai-gateway/server/router.ts b/web/src/features/ai-gateway/server/router.ts
index e49e8f1fd7..7cbd80b446 100644
--- a/web/src/features/ai-gateway/server/router.ts
+++ b/web/src/features/ai-gateway/server/router.ts
@@ -215,7 +215,7 @@ export const aiGatewayRouter = createTRPCRouter({
createApiKey: protectedOrganizationProcedureWithoutTracing
.input(
organizationInput.extend({
- note: z.string().max(500).optional(),
+ name: z.string().max(500).optional(),
metadata: GatewayMetadataSchema.default({}),
}),
)
@@ -223,7 +223,7 @@ export const aiGatewayRouter = createTRPCRouter({
requireGatewayAdmin({ session: ctx.session, orgId: input.orgId });
const key = await new GatewayApiKeyService(ctx.prisma, redis).create({
organizationId: input.orgId,
- note: input.note,
+ name: input.name,
metadata: input.metadata,
session: ctx.session,
});
diff --git a/web/src/features/apiKey/apiKeyRepository.ts b/web/src/features/apiKey/apiKeyRepository.ts
index bc7012b0e8..83bb3dfb70 100644
--- a/web/src/features/apiKey/apiKeyRepository.ts
+++ b/web/src/features/apiKey/apiKeyRepository.ts
@@ -3,14 +3,19 @@ import {
type PrismaClient,
prisma as defaultPrisma,
} from "@langfuse/shared/src/db";
-import { type InternalServerError } from "@langfuse/shared";
+import {
+ type InternalServerError,
+ type ServiceUnavailableError,
+} from "@langfuse/shared";
import { logger } from "@langfuse/shared/src/server";
import {
internalServerError,
+ serviceUnavailableError,
type ErrorResult,
type Success,
} from "@/src/features/auth/policy/types";
+import { isPrismaException } from "@/src/utils/exceptions";
/** ApiKeyRepository reads `ApiKey` rows by the two disjoint unique indexes and backfills the fast hash, returning infra failures as values; caching lives at the Authenticator. */
export class ApiKeyRepository {
@@ -24,8 +29,9 @@ export class ApiKeyRepository {
});
return { success: true, apiKey };
} catch (error) {
- return internalServerError(
+ return dbError(
`api key lookup by fast hash failed: ${String(error)}`,
+ error,
);
}
}
@@ -38,8 +44,9 @@ export class ApiKeyRepository {
});
return { success: true, apiKey };
} catch (error) {
- return internalServerError(
+ return dbError(
`api key lookup by public key failed: ${String(error)}`,
+ error,
);
}
}
@@ -57,7 +64,17 @@ export class ApiKeyRepository {
}
}
+/** dbError classifies a caught database error: a transient infra failure as 503, anything else as 500. */
+function dbError(
+ message: string,
+ error: unknown,
+): ErrorResult<ServiceUnavailableError | InternalServerError> {
+ return isPrismaException(error)
+ ? serviceUnavailableError(message)
+ : internalServerError(message);
+}
+
/** FindApiKeyResult is a hit, a miss (null), or an infra failure; a miss is normal control flow, not an error. */
export type FindApiKeyResult =
| (Success & { apiKey: ApiKey | null })
- | ErrorResult<InternalServerError>;
+ | ErrorResult<ServiceUnavailableError | InternalServerError>;
diff --git a/web/src/features/apiKey/authenticator.ts b/web/src/features/apiKey/authenticator.ts
index f5d3938577..66540bb2ed 100644
--- a/web/src/features/apiKey/authenticator.ts
+++ b/web/src/features/apiKey/authenticator.ts
@@ -3,6 +3,7 @@ import { type IncomingHttpHeaders } from "http";
import {
type ForbiddenError,
type InternalServerError,
+ type ServiceUnavailableError,
type UnauthorizedError,
} from "@langfuse/shared";
@@ -31,14 +32,14 @@ export class Authenticator {
private readonly cache: AuthenticatorCache = new AuthenticatorCache(),
) {}
- /** authenticate runs the full pipeline read-through the context cache and enforces route settings on the resolved principal on every path, returning a typed failure rather than throwing. */
+ /** authenticate resolves credentials and enforces route settings on cache hits and misses. */
async authenticate(params: ApiKeyAuthParams): Promise<ApiKeyAuthResults> {
const credential = parseAuthorizationHeader(params.headers.authorization);
if (credential.kind === "malformed") {
return unauthorizedError(invalidCredentials);
}
- let authResult = await this.cache.get(credential);
+ let authResult: ApiKeyAuthResults | null = await this.cache.get(credential);
if (!authResult) {
authResult = await this.verifyAndResolve(credential);
}
@@ -53,7 +54,7 @@ export class Authenticator {
return authResult;
}
- /** verifyAndResolve authenticates and materializes on a cache miss, writing every cacheable outcome back to the cache. */
+ /** verifyAndResolve resolves and caches verified credentials. */
private async verifyAndResolve(
credential: Credential,
): Promise<ApiKeyAuthResults> {
@@ -63,7 +64,14 @@ export class Authenticator {
return verified;
}
const resolved = await this.authz.resolve(verified);
- await this.cache.set(credential, resolved);
+ const expiresAt = "apiKey" in verified ? verified.apiKey.expiresAt : null;
+ // Revocation requires the persisted fast hash.
+ if (
+ verified.authorization !== "privateKey" ||
+ verified.apiKey.fastHashedSecretKey
+ ) {
+ await this.cache.set(credential, resolved, expiresAt);
+ }
return resolved;
}
}
@@ -108,7 +116,12 @@ export type ApiKeyAuthParams = {
/** ApiKeyAuthResults is the pipeline's outcome: the resolved context, or a typed failure. */
export type ApiKeyAuthResults =
| Authenticated
- | ErrorResult<UnauthorizedError | ForbiddenError | InternalServerError>;
+ | ErrorResult<
+ | UnauthorizedError
+ | ForbiddenError
+ | InternalServerError
+ | ServiceUnavailableError
+ >;
/** Authenticated is the pipeline's success outcome: the resolved authorization context. */
export type Authenticated = Success & { context: AuthorizationContext };
diff --git a/web/src/features/apiKey/authenticatorCache.ts b/web/src/features/apiKey/authenticatorCache.ts
index 756138a9e4..955a84e62d 100644
--- a/web/src/features/apiKey/authenticatorCache.ts
+++ b/web/src/features/apiKey/authenticatorCache.ts
@@ -1,6 +1,5 @@
import { type Redis, type Cluster } from "ioredis";
-import { UnauthorizedError } from "@langfuse/shared";
import {
redis as defaultRedis,
createShaHash,
@@ -9,26 +8,24 @@ import {
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
-import { type Credential } from "@/src/features/apiKey/helpers/parseAuthorizationHeader";
import {
type ApiKeyAuthResults,
type Authenticated,
} from "@/src/features/apiKey/authenticator";
-import {
- unauthorizedError,
- type AuthorizationContext,
- type ErrorResult,
-} from "@/src/features/auth/policy/types";
+import { matchesAdminApiKey } from "@/src/features/apiKey/helpers/matchesAdminApiKey";
+import { type Credential } from "@/src/features/apiKey/helpers/parseAuthorizationHeader";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
-/** AuthenticatorCache is the read-through context cache keyed by credential; it owns key derivation and stores the Authenticator's resolved result. */
+/** AuthenticatorCache stores authorization contexts by credential. */
export class AuthenticatorCache {
constructor(
private readonly redis: Redis | Cluster | null = defaultRedis,
private readonly salt: string = env.SALT,
+ private readonly adminApiKey: string | undefined = env.ADMIN_API_KEY,
) {}
- /** get returns the cached result for a credential, or null on a miss — distinct from a cached 401. */
- async get(credential: Credential): Promise<ResolveContextResult | null> {
+ /** get returns a cached context, or null on a miss. */
+ async get(credential: Credential): Promise<Authenticated | null> {
const key = this.keyFor(credential);
const redis = this.redis;
if (!key || !cacheEnabled(redis)) return null;
@@ -42,21 +39,45 @@ export class AuthenticatorCache {
}
}
- /** set persists a success context or a 401 under a fixed TTL, skips a 500 (fail open), and returns whether it wrote. */
+ /** keyFor derives credential cache keys, excluding environment admins. */
+ private keyFor(credential: Credential): string | null {
+ if (credential.kind === "basic") {
+ return createAuthzContextCacheKey(
+ "basic",
+ createShaHash(credential.secretKey, this.salt),
+ );
+ }
+ if (credential.kind === "bearer") {
+ if (matchesAdminApiKey(credential.token, this.adminApiKey)) return null;
+ return createAuthzContextCacheKey(
+ "bearer",
+ createShaHash(credential.token, this.salt),
+ );
+ }
+ return null;
+ }
+
+ /** set caches database-key successes until their TTL or expiry. */
async set(
credential: Credential,
result: ApiKeyAuthResults,
+ expiresAt: Date | null = null,
): Promise<boolean> {
const key = this.keyFor(credential);
- const entry = toEntry(result);
+ if (!result.success || result.context.principal.kind === "admin") {
+ return false;
+ }
+ const ttlSeconds = ttlFor(expiresAt);
const redis = this.redis;
- if (!key || !entry || !cacheEnabled(redis)) return false;
+ if (!key || ttlSeconds <= 0 || !cacheEnabled(redis)) {
+ return false;
+ }
try {
await redis.set(
key,
- JSON.stringify(entry),
+ JSON.stringify({ context: result.context }),
"EX",
- env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS,
+ ttlSeconds,
);
return true;
} catch (error) {
@@ -64,21 +85,6 @@ export class AuthenticatorCache {
return false;
}
}
-
- /** keyFor derives the namespaced cache key from a credential's secret material, or null when uncacheable. */
- private keyFor(credential: Credential): string | null {
- if (credential.kind === "basic") {
- return createAuthzContextCacheKey(
- createShaHash(credential.secretKey, this.salt),
- );
- }
- if (credential.kind === "bearer") {
- return createAuthzContextCacheKey(
- createShaHash(credential.token, this.salt),
- );
- }
- return null;
- }
}
/** cacheEnabled is the shared on/off switch for the context cache, reusing the legacy api-key cache flag. */
@@ -86,25 +92,16 @@ function cacheEnabled(redis: Redis | Cluster | null): redis is Redis | Cluster {
return Boolean(redis) && env.LANGFUSE_CACHE_API_KEY_ENABLED === "true";
}
-/** toEntry maps a resolved result to its cache row, yielding null for a 500 so it is never negatively cached. */
-function toEntry(result: ApiKeyAuthResults): CachedEntry | null {
- if (result.success) return { context: result.context };
- if (result.error instanceof UnauthorizedError) {
- return { unauthorized: result.error.message };
- }
- return null;
+/** ttlFor is the cache TTL in seconds, floored to the key's remaining lifetime so an entry never outlives its key. */
+function ttlFor(expiresAt: Date | null): number {
+ const ttl = env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS;
+ if (!expiresAt) return ttl;
+ return Math.min(ttl, Math.floor((expiresAt.getTime() - Date.now()) / 1000));
}
-/** deserialize reconstructs a cache hit from its stored row. */
-function deserialize(entry: CachedEntry): ResolveContextResult {
- if ("context" in entry) return { success: true, context: entry.context };
- return unauthorizedError(entry.unauthorized);
+function deserialize(entry: CachedEntry): Authenticated | null {
+ if (!entry?.context) return null;
+ return { success: true, context: entry.context };
}
-/** ResolveContextResult is a cache hit: a resolved context or a replayed 401, never a 500. */
-export type ResolveContextResult =
- | Authenticated
- | ErrorResult<UnauthorizedError>;
-
-/** CachedEntry is the redis-serialized cache value: a materialized context, or a negative 401 body. */
-type CachedEntry = { context: AuthorizationContext } | { unauthorized: string };
+type CachedEntry = { context: AuthorizationContext };
diff --git a/web/src/features/apiKey/helpers/isApiKeyExpired.ts b/web/src/features/apiKey/helpers/isApiKeyExpired.ts
new file mode 100644
index 0000000000..2066d1ec60
--- /dev/null
+++ b/web/src/features/apiKey/helpers/isApiKeyExpired.ts
@@ -0,0 +1,8 @@
+/** isApiKeyExpired reports whether an api key's expiry is at or before now; a null expiry never expires. */
+export function isApiKeyExpired(
+ expiresAt: Date | string | null | undefined,
+ now: number = Date.now(),
+): boolean {
+ if (!expiresAt) return false;
+ return new Date(expiresAt).getTime() <= now;
+}
diff --git a/web/src/features/apiKey/helpers/matchesAdminApiKey.ts b/web/src/features/apiKey/helpers/matchesAdminApiKey.ts
new file mode 100644
index 0000000000..5176fb657a
--- /dev/null
+++ b/web/src/features/apiKey/helpers/matchesAdminApiKey.ts
@@ -0,0 +1,19 @@
+import { timingSafeEqual } from "node:crypto";
+
+/** matchesAdminApiKey compares a token against the nonempty, trimmed admin secret. */
+export function matchesAdminApiKey(
+ token: string,
+ configuredKey: string | undefined,
+): boolean {
+ const adminApiKey = configuredKey?.trim();
+ if (!adminApiKey) return false;
+ return timingSafeTokenEquals(token, adminApiKey);
+}
+
+function timingSafeTokenEquals(token: string, expectedToken: string): boolean {
+ const supplied = Buffer.from(token);
+ const expected = Buffer.from(expectedToken);
+ return (
+ supplied.length === expected.length && timingSafeEqual(supplied, expected)
+ );
+}
diff --git a/web/src/features/apiKey/verifier.ts b/web/src/features/apiKey/verifier.ts
index 64b2f12af9..a47fb42ce6 100644
--- a/web/src/features/apiKey/verifier.ts
+++ b/web/src/features/apiKey/verifier.ts
@@ -1,8 +1,7 @@
-import crypto from "node:crypto";
-
import { type ApiKey } from "@langfuse/shared/src/db";
import {
type InternalServerError,
+ type ServiceUnavailableError,
type UnauthorizedError,
} from "@langfuse/shared";
import { createShaHash, verifySecretKey } from "@langfuse/shared/src/server";
@@ -10,6 +9,8 @@ import { createShaHash, verifySecretKey } from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
import { type Credential } from "@/src/features/apiKey/helpers/parseAuthorizationHeader";
import { ApiKeyRepository } from "@/src/features/apiKey/apiKeyRepository";
+import { isApiKeyExpired } from "@/src/features/apiKey/helpers/isApiKeyExpired";
+import { matchesAdminApiKey } from "@/src/features/apiKey/helpers/matchesAdminApiKey";
import {
internalServerError,
unauthorizedError,
@@ -32,7 +33,7 @@ export class Verifier {
private readonly adminApiKey: string | undefined = env.ADMIN_API_KEY,
) {}
- /** verify resolves a parsed credential to a presentation, or a typed failure. */
+ /** verify resolves a parsed credential to a presentation, or a typed failure; an expired key 401s like an unknown one. */
async verify(credential: Credential): Promise<VerifyApiKeyResult> {
if (credential.kind === "basic") {
return this.verifyBasic(credential.publicKey, credential.secretKey);
@@ -49,10 +50,10 @@ export class Verifier {
secretKey: string,
): Promise<VerifyApiKeyResult> {
const byPrivateKey = await this.verifyPrivateKey(secretKey);
- if (byPrivateKey) return byPrivateKey;
+ if (byPrivateKey) return rejectExpired(byPrivateKey);
const bySlowHash = await this.backfillSlowHash(publicKey, secretKey);
- if (bySlowHash) return bySlowHash;
+ if (bySlowHash) return rejectExpired(bySlowHash);
return unauthorizedError(invalidCredentials);
}
@@ -63,10 +64,10 @@ export class Verifier {
if (admin) return admin;
const byPublicKey = await this.verifyPublicKey(token);
- if (byPublicKey) return byPublicKey;
+ if (byPublicKey) return rejectExpired(byPublicKey);
const byPrivateKey = await this.verifyPrivateKey(token);
- if (byPrivateKey) return byPrivateKey;
+ if (byPrivateKey) return rejectExpired(byPrivateKey);
return unauthorizedError(invalidCredentials);
}
@@ -83,14 +84,14 @@ export class Verifier {
return null;
}
- /** backfillSlowHash bcrypt-verifies a secret against the public key's row, backfilling the fast hash on a match, or null on a miss. */
+ /** backfillSlowHash bcrypt-verifies keys without a fast hash and backfills matching secrets. */
private async backfillSlowHash(
publicKey: string,
secretKey: string,
): Promise<VerifyApiKeyResult | null> {
const found = await this.apiKeyRepo.findByPublicKey(publicKey);
if (!found.success) return found;
- if (!found.apiKey) return null;
+ if (!found.apiKey || found.apiKey.fastHashedSecretKey !== null) return null;
let valid: boolean;
try {
@@ -107,20 +108,11 @@ export class Verifier {
return privateKey(found.apiKey);
}
- /** verifyAdminKey resolves a token that timing-safe matches the admin key, or null; the key is ignored unless set and non-empty after trimming. */
+ /** verifyAdminKey recognizes the configured environment admin. */
private verifyAdminKey(token: string): VerifyApiKeyResult | null {
- const adminApiKey = this.adminApiKey?.trim();
- if (!adminApiKey) return null;
- try {
- if (
- crypto.timingSafeEqual(Buffer.from(token), Buffer.from(adminApiKey))
- ) {
- return { success: true, authorization: "admin" };
- }
- } catch {
- return null;
- }
- return null;
+ return matchesAdminApiKey(token, this.adminApiKey)
+ ? { success: true, authorization: "admin" }
+ : null;
}
/** verifyPublicKey resolves a public-key token to its scores-only presentation, or null when it is not a public key or is unknown. */
@@ -143,6 +135,18 @@ function privateKey(apiKey: ApiKey): VerifyApiKeyResult {
return { success: true, authorization: "privateKey", apiKey };
}
+/** rejectExpired maps a verified key past its expiry to the unknown-key 401. */
+function rejectExpired(result: VerifyApiKeyResult): VerifyApiKeyResult {
+ if (
+ result.success &&
+ result.authorization !== "admin" &&
+ isApiKeyExpired(result.apiKey.expiresAt)
+ ) {
+ return unauthorizedError(invalidCredentials);
+ }
+ return result;
+}
+
/** VerifiedCredential is the presentation the resolver consumes: an api key with how it was presented, or the admin key. */
type VerifiedCredential =
| { authorization: "publicKey" | "privateKey"; apiKey: ApiKey }
@@ -151,4 +155,6 @@ type VerifiedCredential =
/** VerifyApiKeyResult is the verified credential, or a typed failure; verify returns, never throws. */
export type VerifyApiKeyResult =
| (Success & VerifiedCredential)
- | ErrorResult<UnauthorizedError | InternalServerError>;
+ | ErrorResult<
+ UnauthorizedError | InternalServerError | ServiceUnavailableError
+ >;
diff --git a/web/src/features/auth/policy/authorize.ts b/web/src/features/auth/policy/authorize.ts
deleted file mode 100644
index 66c418db44..0000000000
--- a/web/src/features/auth/policy/authorize.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import {
- forbiddenError,
- wildcard,
- type Action,
- type AuthorizationContext,
- type Decision,
- type Policy,
- type Resource,
-} from "./types";
-
-/** authorize evaluates the policies for action on resource: a matching deny 403s, else a matching allow succeeds, else implicit-deny 403. */
-export function authorize(
- ctx: AuthorizationContext,
- action: Action,
- resource: Resource,
-): Decision {
- const matches = ctx.policies
- .filter(hasResourceKind(resource))
- .filter(hasAction(action))
- .filter(hasResourceId(resource));
-
- if (matches.some(hasEffect("deny"))) {
- return forbiddenError();
- }
- if (matches.some(hasEffect("allow"))) {
- return { success: true };
- }
- return forbiddenError();
-}
-
-/** hasResourceKind matches a policy of the kind that governs the checked resource. */
-const hasResourceKind = (resource: Resource) => (p: Policy) =>
- p.kind === ("projectId" in resource ? "project" : "organization");
-
-/** hasResourceId matches a policy whose resources cover the checked resource's id, by wildcard or listing. */
-const hasResourceId = (resource: Resource) => (p: Policy) =>
- p.resources === wildcard ||
- p.resources.includes(
- "projectId" in resource ? resource.projectId : resource.orgId,
- );
-
-/** hasAction matches a policy granting the action explicitly; actions are never wildcarded. */
-const hasAction = (action: Action) => (p: Policy) =>
- (p.actions as readonly string[]).includes(action);
-
-/** hasEffect matches a policy of the given effect. */
-const hasEffect = (effect: Policy["effect"]) => (p: Policy) =>
- p.effect === effect;
diff --git a/web/src/features/auth/policy/contextResolver.ts b/web/src/features/auth/policy/contextResolver.ts
index ee8d022aab..a03f23e4bc 100644
--- a/web/src/features/auth/policy/contextResolver.ts
+++ b/web/src/features/auth/policy/contextResolver.ts
@@ -1,30 +1,41 @@
-import { type ApiKey } from "@langfuse/shared/src/db";
+import {
+ type ApiKey,
+ type PrismaClient,
+ prisma as defaultPrisma,
+} from "@langfuse/shared/src/db";
import { CloudConfigSchema, type InternalServerError } from "@langfuse/shared";
-
-import { apiKeyAccessRights } from "@/src/features/rbac/constants/apiKeyAccessRights";
+import {
+ ApiKeyId,
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ systemRoleAccessRights,
+} from "@langfuse/shared/rbac";
+
+import { getRolesForPrincipal } from "@/src/features/rbac/getRolesForPrincipal";
import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server";
import {
OrganizationRepository,
type GetOrganizationResult,
type OrganizationWithProjects,
} from "./organizationRepository";
+import { authorize } from "@/src/features/rbac/authorize";
+import { type Policy } from "@/src/features/rbac/types";
import {
internalServerError,
- wildcard,
type AuthorizationContext,
type BoundResource,
type ErrorResult,
- type Policy,
type Principal,
type PrincipalOrganization,
type Success,
- type SystemPolicy,
} from "./types";
/** ContextResolver materializes an authenticated credential into its `AuthorizationContext`, loading and enriching the org it implies. */
export class ContextResolver {
constructor(
private readonly orgs: OrganizationRepository = new OrganizationRepository(),
+ private readonly prisma: PrismaClient = defaultPrisma,
) {}
/** resolve turns a verified credential into its context, collapsing a missing org to a 500 invariant break. */
@@ -36,10 +47,11 @@ export class ContextResolver {
if (!org.success) return org;
return {
success: true,
- context: materialize(
+ context: await materialize(
params.apiKey,
params.authorization,
org.organization,
+ this.prisma,
),
};
}
@@ -82,11 +94,12 @@ export class ContextResolver {
}
/** materialize expands the `ApiKey` row and its presentation into the policies the credential implies. */
-function materialize(
+async function materialize(
apiKey: ApiKey,
authorization: "publicKey" | "privateKey",
org: PrincipalOrganization,
-): AuthorizationContext {
+ prisma: PrismaClient,
+): Promise<AuthorizationContext> {
const principal: Principal = {
kind: "apiKey",
apiKeyId: apiKey.id,
@@ -99,21 +112,62 @@ function materialize(
boundResource: boundResourceFor(apiKey, org),
};
- const grants =
- authorization === "publicKey"
- ? apiKeyAccessRights.SCORES_INGEST
- : apiKeyAccessRights[apiKey.scope];
- const policies = grants.map((p) => bind(p, principal));
- return { principal, policies };
+ const roles = await getRolesForPrincipal(ApiKeyId(apiKey.id), prisma);
+ const context = {
+ principal,
+ policies: roles.flatMap((role) => role.policies),
+ };
+ if (authorization === "publicKey") {
+ return { principal, policies: publicBearerPolicies(context, apiKey, org) };
+ }
+ return context;
}
-/** adminContext is the admin context: no key row, the ADMIN role bound to the wildcard resource. */
+/** publicBearerPolicies narrows a public-key bearer to scores:save on its own project, granted only when the key's stored roles allow it there. */
+function publicBearerPolicies(
+ roleContext: AuthorizationContext,
+ apiKey: ApiKey,
+ org: PrincipalOrganization,
+): Policy[] {
+ const tenantId = OrganizationId(org.orgId);
+ const project = ProjectId(apiKey.projectId!);
+ if (!authorize(roleContext, tenantId, "scores:save", project).success) {
+ return [];
+ }
+ const resources = [project];
+ const roleId = SystemRoleId("SCORES_INGEST");
+ return systemRoleAccessRights.SCORES_INGEST.policies.map((policy) => ({
+ id: `${roleId}:${policy.resourceKind}`,
+ roleId,
+ tenantId,
+ effect: policy.effect,
+ actions: policy.actions,
+ resources,
+ }));
+}
+
+/** 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. */
function adminContext(): AuthorizationContext {
const principal: Principal = { kind: "admin", userId: null };
- return {
- principal,
- policies: apiKeyAccessRights.ADMIN.map((policy) => bind(policy, principal)),
- };
+ const roleId = SystemRoleId("OWNER");
+ const tenantId = OrganizationId("*");
+ const policies: Policy[] = systemRoleAccessRights.OWNER.policies.map(
+ (policy) => ({
+ id: `${roleId}:${policy.resourceKind}`,
+ roleId,
+ tenantId,
+ effect: policy.effect,
+ actions: policy.actions,
+ resources: [
+ policy.resourceKind === "organization"
+ ? OrganizationId("*")
+ : ProjectId("*"),
+ ],
+ }),
+ );
+ return { principal, policies };
}
/** boundResourceFor is the target a request resolves against with no header: the key's org, narrowed to its project when the key is project-scoped. */
@@ -125,37 +179,6 @@ function boundResourceFor(
return { orgId: org.orgId, projectId: apiKey.projectId! };
}
-/** bind fixes a resource-less SystemPolicy to the resources the principal covers, by the policy's kind. */
-function bind(policy: SystemPolicy, principal: Principal): Policy {
- return policy.kind === "organization"
- ? { ...policy, resources: orgResources(principal) }
- : { ...policy, resources: projectResources(principal) };
-}
-
-/** orgResources are the org ids an org-kind policy binds to: the bound org, or the wildcard for admin. */
-function orgResources(principal: Principal): Policy["resources"] {
- if (principal.kind === "admin") return wildcard;
- return boundOrgs(principal).map((o) => o.orgId);
-}
-
-/** projectResources are the project ids a project-kind policy binds to: the bound project, the bound org's projects, or the wildcard for admin. */
-function projectResources(principal: Principal): Policy["resources"] {
- if (principal.kind === "admin") return wildcard;
- const bound =
- principal.kind === "apiKey" ? principal.boundResource : undefined;
- if (bound?.projectId) return [bound.projectId];
- return boundOrgs(principal).flatMap((o) => o.projectIds);
-}
-
-/** boundOrgs are the principal's organizations, narrowed to the bound org when the credential bound one. */
-function boundOrgs(principal: NonAdminPrincipal): PrincipalOrganization[] {
- const bound =
- principal.kind === "apiKey" ? principal.boundResource : undefined;
- return bound
- ? principal.organizations.filter((o) => o.orgId === bound.orgId)
- : principal.organizations;
-}
-
/** toPrincipalOrganization derives an org's `PrincipalOrganization` caps and liveness from its raw row. */
function toPrincipalOrganization(
org: OrganizationWithProjects,
@@ -190,6 +213,3 @@ export type ResolveContextParams =
export type Resolved =
| (Success & { context: AuthorizationContext })
| ErrorResult<InternalServerError>;
-
-/** NonAdminPrincipal is a user or api-key principal, the credentials that carry organizations. */
-type NonAdminPrincipal = Exclude<Principal, { kind: "admin" }>;
diff --git a/web/src/features/auth/policy/types.ts b/web/src/features/auth/policy/types.ts
index fcd1368b42..26e5396eb2 100644
--- a/web/src/features/auth/policy/types.ts
+++ b/web/src/features/auth/policy/types.ts
@@ -4,48 +4,14 @@ import {
ForbiddenError,
InternalServerError,
LangfuseNotFoundError,
- projectScopes,
ServiceUnavailableError,
UnauthorizedError,
type ApiKeyScope,
type CloudConfigRateLimit,
type Plan,
- type ProjectScope,
} from "@langfuse/shared";
-import {
- organizationScopes,
- type OrganizationScope,
-} from "@/src/features/rbac/constants/organizationAccessRights";
-
-/** wildcard matches any resource in a policy. */
-export const wildcard = "*" as const;
-
-/** allProjectActions is the full project action vocabulary. */
-export const allProjectActions: ProjectAction[] = [...projectScopes];
-
-/** allOrganizationActions is the full organization action vocabulary. */
-export const allOrganizationActions: OrganizationAction[] = [
- ...organizationScopes,
-];
-
-/** organizationActionSet is allOrganizationActions indexed for membership tests. */
-const organizationActionSet: ReadonlySet<string> = new Set(organizationScopes);
-
-/** isOrgAction reports whether an action belongs to the disjoint org vocabulary. */
-export const isOrgAction = (action: Action): action is OrganizationAction =>
- organizationActionSet.has(action);
-
-/** Wildcard is the type of the wildcard resource matcher literal. */
-type Wildcard = typeof wildcard;
-
-/** ProjectAction is an action assignable to a project policy. */
-export type ProjectAction = ProjectScope;
-
-/** OrganizationAction is an action assignable to an organization policy. */
-export type OrganizationAction = OrganizationScope;
-/** Action is any checkable action. */
-export type Action = ProjectAction | OrganizationAction;
+import { type Policy } from "@/src/features/rbac/types";
/** PrincipalOrganization carries an org's static caps and its ingestion-suspension liveness state, enforced at the seam not the PDP. */
export type PrincipalOrganization = {
@@ -73,9 +39,6 @@ export type Principal =
boundResource: BoundResource;
};
-/** Source describes where a policy came from: a role or an explicit grant. */
-type Source = { kind: "role"; id: string } | { kind: "grant" };
-
/** ProjectResource identifies a project by its globally-unique id. */
type ProjectResource = { projectId: string };
@@ -88,30 +51,6 @@ export type Resource = ProjectResource | OrgResource;
/** BoundResource is what a credential is bound to: its organization, narrowed to one project when the credential is project-scoped. */
export type BoundResource = OrgResource & { projectId?: string };
-/** BasePolicy carries the origin and effect every policy shares. */
-type BasePolicy = {
- source: Source;
- effect: "allow" | "deny";
-};
-
-/** OrganizationSystemPolicy is a resource-less org-level policy. */
-type OrganizationSystemPolicy = BasePolicy & {
- kind: "organization";
- actions: OrganizationAction[];
-};
-
-/** ProjectSystemPolicy is a resource-less project-level policy. */
-type ProjectSystemPolicy = BasePolicy & {
- kind: "project";
- actions: ProjectAction[];
-};
-
-/** SystemPolicy is a policy before its resource is bound. */
-export type SystemPolicy = OrganizationSystemPolicy | ProjectSystemPolicy;
-
-/** Policy is a SystemPolicy bound to the flat ids its kind targets, or the wildcard. */
-export type Policy = SystemPolicy & { resources: string[] | Wildcard };
-
/** AuthorizationContext is the PIP output and PDP input for one principal. */
export type AuthorizationContext = {
principal: Principal;
diff --git a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
index 29dd6557b1..85c7375ea6 100644
--- a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
+++ b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
@@ -51,7 +51,7 @@ const DatasetAggregateCellContent = ({
const hasAnnotationWriteAccess = useHasProjectAccess({
projectId,
- scope: "scores:CUD",
+ scope: "scores:save",
});
// Merge server columns with cache-only columns
diff --git a/web/src/features/experiments/components/table/ExperimentGridView.tsx b/web/src/features/experiments/components/table/ExperimentGridView.tsx
index 531e6d6e4c..d07bb80991 100644
--- a/web/src/features/experiments/components/table/ExperimentGridView.tsx
+++ b/web/src/features/experiments/components/table/ExperimentGridView.tsx
@@ -101,7 +101,7 @@ export const ExperimentGridView = ({
setRowSelection,
highlightAllRows,
}: ExperimentGridViewProps) => {
- const canAnnotate = useHasProjectAccess({ projectId, scope: "scores:CUD" });
+ const canAnnotate = useHasProjectAccess({ projectId, scope: "scores:save" });
const capture = usePostHogClientCapture();
const [summaryExpanded, setSummaryExpanded] = useState(true);
// Keep the explicit baseline separate from the comparison list. A baseline
diff --git a/web/src/features/mcp/server/mcpServer.ts b/web/src/features/mcp/server/mcpServer.ts
index 56c0ab4f9d..1f1dbc6540 100644
--- a/web/src/features/mcp/server/mcpServer.ts
+++ b/web/src/features/mcp/server/mcpServer.ts
@@ -140,7 +140,7 @@ export function createMcpServer(context: ServerContext): Server {
return server;
}
-/** assertToolAuthorized authorizes a tool call through the per-item seam, throwing an enforce-mode deny as an MCP error. */
+/** assertToolAuthorized reports enforce-mode denials as MCP errors. */
function assertToolAuthorized(
definition: ToolDefinition,
context: ServerContext,
@@ -149,7 +149,10 @@ function assertToolAuthorized(
ctx: context.auth,
action: definition.action,
resource: { projectId: context.projectId },
- accessLevel: context.accessLevel,
+ legacyDecision: {
+ success: true,
+ scope: { accessLevel: context.accessLevel },
+ },
});
if (!decision.success) throw formatErrorForUser(decision.error);
}
diff --git a/web/src/features/mcp/server/scores/tools/createScore.ts b/web/src/features/mcp/server/scores/tools/createScore.ts
index 5822365fa7..cbc7ea5398 100644
--- a/web/src/features/mcp/server/scores/tools/createScore.ts
+++ b/web/src/features/mcp/server/scores/tools/createScore.ts
@@ -79,7 +79,7 @@ export const [createScoreTool, handleCreateScore] = defineTool({
"Create one score in the current Langfuse project.",
"Score reads are eventually consistent: after creation, getScore and listScores may not return the new score immediately. Wait briefly and retry reads when confirming creation.",
].join("\n"),
- action: "scores:create",
+ action: "scores:save",
baseSchema: CreateScoreBaseSchema,
inputSchema: PostScoresBodyV1,
destructiveHint: true,
diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.ts
index 45df1a1840..970b6320a9 100644
--- a/web/src/features/projects/server/projectsRouter.ts
+++ b/web/src/features/projects/server/projectsRouter.ts
@@ -20,6 +20,7 @@ import {
getEnvironmentsForProject,
invalidateCachedOrgApiKeys,
} from "@langfuse/shared/src/server";
+import { transferRoleAssignments } from "@langfuse/shared/rbac/server";
import { randomUUID } from "crypto";
import { LangfuseConflictError, StringNoHTMLNonEmpty } from "@langfuse/shared";
import type { PrismaClient } from "@langfuse/shared/src/db";
@@ -323,13 +324,13 @@ export const projectsRouter = createTRPCRouter({
after: { orgId: input.targetOrgId },
});
- await ctx.prisma.$transaction([
- ctx.prisma.projectMembership.deleteMany({
+ await ctx.prisma.$transaction(async (tx) => {
+ await tx.projectMembership.deleteMany({
where: {
projectId: input.projectId,
},
- }),
- ctx.prisma.project.update({
+ });
+ await tx.project.update({
where: {
id: input.projectId,
orgId: ctx.session.orgId,
@@ -337,8 +338,11 @@ export const projectsRouter = createTRPCRouter({
data: {
orgId: input.targetOrgId,
},
- }),
- ]);
+ });
+ // Move the project's api-key assignments to the destination org and
+ // drop its user assignments, matching the membership wipe above.
+ await transferRoleAssignments(tx, input.projectId, input.targetOrgId);
+ });
// API keys need to be deleted from cache. Otherwise, they will still be valid.
// It has to be called after the db is done to prevent new API keys from being cached.
diff --git a/web/src/features/prompts/server/utils/authorizeProtectedLabelMutation.ts b/web/src/features/prompts/server/utils/authorizeProtectedLabelMutation.ts
index 1ef10bdb47..0a80fa837b 100644
--- a/web/src/features/prompts/server/utils/authorizeProtectedLabelMutation.ts
+++ b/web/src/features/prompts/server/utils/authorizeProtectedLabelMutation.ts
@@ -1,7 +1,12 @@
-import { type Prisma, Role } from "@langfuse/shared/src/db";
import { ForbiddenError, hasProjectAccessByRole } from "@langfuse/shared";
+import { type Prisma, Role } from "@langfuse/shared/src/db";
import { type ApiAccessLevel } from "@langfuse/shared/src/server";
-import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+
+import { env } from "@/src/env.mjs";
+import {
+ type AuthorizationContext,
+ type Decision,
+} from "@/src/features/auth/policy/types";
import { shadowAuthorize } from "@/src/features/public-api/server";
import { checkHasProtectedLabels } from "./checkHasProtectedLabels";
@@ -115,7 +120,7 @@ async function assertInAppAgentMayMutateProtectedLabels(params: {
}
}
-/** Authorize protected-label mutations for project API keys and their creators. */
+/** authorizeProtectedLabelMutation checks key and creator permissions for protected labels. */
export async function authorizeProtectedLabelMutation(params: {
prisma: Prisma.TransactionClient;
context: ApiKeyProjectContext;
@@ -135,18 +140,55 @@ export async function authorizeProtectedLabelMutation(params: {
return;
}
+ const legacyParams = {
+ prisma: params.prisma,
+ context: params.context,
+ protectedLabels,
+ forbiddenErrorMessage: params.forbiddenErrorMessage,
+ };
+ const legacyDecision =
+ env.API_AUTH_MIGRATION === "shadow"
+ ? await protectedLabelLegacyDecision(legacyParams)
+ : { success: true as const };
+ assertProtectedLabelPolicy(params, legacyDecision);
+ await assertProtectedLabelLegacyDecision(legacyParams, legacyDecision);
+}
+
+function assertProtectedLabelPolicy(
+ params: Parameters<typeof authorizeProtectedLabelMutation>[0],
+ legacyDecision: Decision,
+): void {
const decision = shadowAuthorize({
ctx: params.ctx,
action: "promptProtectedLabels:CUD",
resource: { projectId: params.context.projectId },
- accessLevel: params.context.accessLevel,
+ legacyDecision: legacyDecision.success
+ ? { success: true, scope: { accessLevel: params.context.accessLevel } }
+ : legacyDecision,
});
if (!decision.success) throw decision.error;
+}
- await assertInAppAgentMayMutateProtectedLabels({
- prisma: params.prisma,
- context: params.context,
- protectedLabels,
- forbiddenErrorMessage: params.forbiddenErrorMessage,
- });
+/** assertProtectedLabelLegacyDecision reuses the creator check captured for comparison. */
+async function assertProtectedLabelLegacyDecision(
+ params: Parameters<typeof assertInAppAgentMayMutateProtectedLabels>[0],
+ legacyDecision: Decision,
+): Promise<void> {
+ if (!legacyDecision.success) throw legacyDecision.error;
+ if (env.API_AUTH_MIGRATION !== "shadow") {
+ await assertInAppAgentMayMutateProtectedLabels(params);
+ }
+}
+
+/** protectedLabelLegacyDecision captures creator permission denials for shadow comparison. */
+async function protectedLabelLegacyDecision(
+ params: Parameters<typeof assertInAppAgentMayMutateProtectedLabels>[0],
+): Promise<Decision> {
+ try {
+ await assertInAppAgentMayMutateProtectedLabels(params);
+ return { success: true };
+ } catch (error) {
+ if (error instanceof ForbiddenError) return { success: false, error };
+ throw error;
+ }
}
diff --git a/web/src/features/public-api/components/ApiKeyCreateDialogContent.stories.tsx b/web/src/features/public-api/components/ApiKeyCreateDialogContent.stories.tsx
index f59907c2a5..9920d18abc 100644
--- a/web/src/features/public-api/components/ApiKeyCreateDialogContent.stories.tsx
+++ b/web/src/features/public-api/components/ApiKeyCreateDialogContent.stories.tsx
@@ -1,16 +1,30 @@
import preview from "../../../../.storybook/preview";
import { Dialog } from "@/src/components/ui/dialog";
+import { type Session } from "next-auth";
+import { SessionProvider } from "next-auth/react";
import { fn } from "storybook/test";
import { ApiKeyCreateDialogContent } from "./ApiKeyCreateDialogContent";
+const sessionWithRoleSelection = {
+ expires: "2999-01-01T00:00:00.000Z",
+ user: null,
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: null,
+ apiKeyRoleSelectionEnabled: true,
+ },
+} as unknown as Session;
+
const meta = preview.meta({
component: ApiKeyCreateDialogContent,
decorators: [
(Story) => (
- <Dialog open onOpenChange={fn()}>
- <Story />
- </Dialog>
+ <SessionProvider session={sessionWithRoleSelection}>
+ <Dialog open onOpenChange={fn()}>
+ <Story />
+ </Dialog>
+ </SessionProvider>
),
],
parameters: {
@@ -22,13 +36,38 @@ export const Default = meta.story({
args: {
type: "form",
scope: "project",
- note: "Production key",
- onNoteChange: fn(),
onSubmit: fn(),
isPending: false,
},
});
+export const OrganizationScope = meta.story({
+ args: {
+ type: "form",
+ scope: "organization",
+ onSubmit: fn(),
+ isPending: false,
+ },
+});
+
+export const WithoutRoleSelection = meta.story({
+ args: {
+ type: "form",
+ scope: "project",
+ onSubmit: fn(),
+ isPending: false,
+ },
+ decorators: [
+ (Story) => (
+ <SessionProvider session={null}>
+ <Dialog open onOpenChange={fn()}>
+ <Story />
+ </Dialog>
+ </SessionProvider>
+ ),
+ ],
+});
+
export const Created = meta.story({
args: {
type: "detail",
diff --git a/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx b/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
index eb083652ae..5bdbd87311 100644
--- a/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
+++ b/web/src/features/public-api/components/ApiKeyCreateDialogContent.tsx
@@ -1,4 +1,14 @@
-import React from "react";
+import React, { useState } from "react";
+import { ArrowUpRight } from "lucide-react";
+import { useSession } from "next-auth/react";
+
+import { type SystemRole } from "@langfuse/shared/src/db";
+import {
+ apiKeyRolesForScope,
+ legacyApiKeyRoleForScope,
+ systemRoleAccessRights,
+} from "@langfuse/shared/rbac";
+
import { Button } from "@/src/components/ui/button";
import {
DialogBody,
@@ -9,17 +19,41 @@ import {
} from "@/src/components/ui/dialog";
import { Input } from "@/src/components/ui/input";
import { Label } from "@/src/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
import { ApiKeyDetailContent } from "@/src/features/public-api/components/ApiKeyDetailContent";
+import { rolePermissionCountLabel } from "@/src/features/rbac/components/RolePermissionList";
+import { RolePermissionPopup } from "@/src/features/rbac/components/RolePermissionPopup";
+import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";
+import { roleIcons } from "@/src/features/rbac/components/roleIcons";
+import {
+ expiryPresetOptions,
+ localDateInputValue,
+ resolveExpiresAt,
+ type ExpiryPreset,
+} from "@/src/features/public-api/components/apiKeyFormOptions";
type ApiKeyScope = "project" | "organization";
+const DEFAULT_ROLE: SystemRole = "ADMIN";
+
+/** ApiKeyCreateValues is the resolved create-form payload the button forwards to the create mutation. */
+export type ApiKeyCreateValues = {
+ name: string;
+ role: SystemRole;
+ expiresAt: Date | null;
+};
+
export type ApiKeyCreateDialogContentProps =
| {
scope: ApiKeyScope;
type: "form";
- note: string;
- onNoteChange: (value: string) => void;
- onSubmit: () => void;
+ onSubmit: (values: ApiKeyCreateValues) => void;
isPending?: boolean;
}
| (Omit<
@@ -55,35 +89,161 @@ export function ApiKeyCreateDialogContent(
);
}
- const { note, onNoteChange, onSubmit, isPending } = props;
+ return <ApiKeyCreateForm {...props} />;
+}
+
+function ApiKeyCreateForm({
+ scope,
+ onSubmit,
+ isPending,
+}: Extract<ApiKeyCreateDialogContentProps, { type: "form" }>) {
+ const roles = apiKeyRolesForScope(scope);
+ const { data: session } = useSession();
+ const roleSelectionEnabled =
+ session?.environment?.apiKeyRoleSelectionEnabled ?? false;
+
+ const [name, setName] = useState("");
+ const [role, setRole] = useState<SystemRole>(DEFAULT_ROLE);
+ const [expiryPreset, setExpiryPreset] = useState<ExpiryPreset>("never");
+ const [customExpiry, setCustomExpiry] = useState("");
+ const [roleSelectOpen, setRoleSelectOpen] = useState(false);
+ const [permissionsOpen, setPermissionsOpen] = useState(false);
+ const [permissionsRole, setPermissionsRole] = useState<SystemRole | null>(
+ null,
+ );
+
+ const expiresAt = resolveExpiresAt(expiryPreset, customExpiry);
+ const submitDisabled = name.trim() === "" || expiresAt === undefined;
+
+ const openPermissions = (target: SystemRole) => {
+ setRoleSelectOpen(false);
+ setPermissionsRole(target);
+ setPermissionsOpen(true);
+ };
+
+ const submit = () => {
+ if (submitDisabled) return;
+ onSubmit({
+ name: name.trim(),
+ role: roleSelectionEnabled ? role : legacyApiKeyRoleForScope(scope),
+ expiresAt,
+ });
+ };
+
+ const selectedRoleDef = systemRoleAccessRights[role];
+ const SelectedRoleIcon = roleIcons[role];
return (
<DialogContent closeOnInteractionOutside>
<DialogHeader>
- <DialogTitle>Create API Keys</DialogTitle>
+ <DialogTitle>Create API key</DialogTitle>
</DialogHeader>
<DialogBody>
- <div className="space-y-4">
- <div>
- <Label htmlFor="note">Note (optional)</Label>
+ <div className="flex flex-col gap-5">
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor="apiKeyName">Name</Label>
<Input
- id="note"
- placeholder="Production key"
- value={note}
- onChange={(e) => onNoteChange(e.target.value)}
+ id="apiKeyName"
+ placeholder="e.g. Production server"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
- if (e.key === "Enter") {
- onSubmit();
- }
+ if (e.key === "Enter") submit();
}}
- className="mt-1.5"
/>
</div>
+
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor="apiKeyExpiry">Expiration</Label>
+ <div className={expiryPreset === "custom" ? "flex gap-2" : ""}>
+ <Select
+ value={expiryPreset}
+ onValueChange={(value) =>
+ setExpiryPreset(value as ExpiryPreset)
+ }
+ >
+ <SelectTrigger id="apiKeyExpiry" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {expiryPresetOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {expiryPreset === "custom" && (
+ <Input
+ type="date"
+ aria-label="Custom expiration date"
+ min={localDateInputValue(new Date())}
+ value={customExpiry}
+ onChange={(e) => setCustomExpiry(e.target.value)}
+ />
+ )}
+ </div>
+ </div>
+
+ {roleSelectionEnabled && (
+ <div className="flex flex-col gap-1.5">
+ <Label>Permissions</Label>
+ <Select
+ open={roleSelectOpen}
+ onOpenChange={setRoleSelectOpen}
+ value={role}
+ onValueChange={(value) => setRole(value as SystemRole)}
+ >
+ <SelectTrigger className="h-auto" disableValueLineClamp>
+ <div className="flex items-start gap-2 text-left">
+ <SelectedRoleIcon className="icon-base mt-0.5 shrink-0" />
+ <div className="flex flex-col">
+ <span className="font-bold">{selectedRoleDef.name}</span>
+ <span className="text-muted-foreground text-xs">
+ {selectedRoleDef.description}
+ </span>
+ </div>
+ </div>
+ </SelectTrigger>
+ <SelectContent>
+ {roles.map((r) => (
+ <RoleSelectItem
+ key={r}
+ role={r}
+ onViewPermissions={openPermissions}
+ />
+ ))}
+ </SelectContent>
+ </Select>
+ <button
+ type="button"
+ onClick={() => {
+ setPermissionsRole(role);
+ setPermissionsOpen(true);
+ }}
+ className="text-muted-foreground hover:text-foreground ml-1 w-fit text-xs"
+ >
+ View{" "}
+ <span className="inline-flex items-center gap-0.5 underline">
+ {rolePermissionCountLabel(role)}
+ <ArrowUpRight className="icon-sm" />
+ </span>
+ </button>
+ </div>
+ )}
</div>
+
+ {roleSelectionEnabled && (
+ <RolePermissionPopup
+ open={permissionsOpen}
+ onOpenChange={setPermissionsOpen}
+ role={permissionsRole}
+ />
+ )}
</DialogBody>
<DialogFooter>
- <Button onClick={onSubmit} loading={isPending}>
- Create API keys
+ <Button onClick={submit} loading={isPending} disabled={submitDisabled}>
+ Create API key
</Button>
</DialogFooter>
</DialogContent>
diff --git a/web/src/features/public-api/components/ApiKeyList.clienttest.tsx b/web/src/features/public-api/components/ApiKeyList.clienttest.tsx
index f2fb13c076..3c890132b0 100644
--- a/web/src/features/public-api/components/ApiKeyList.clienttest.tsx
+++ b/web/src/features/public-api/components/ApiKeyList.clienttest.tsx
@@ -39,13 +39,13 @@ vi.mock("@/src/utils/api", () => {
options?.enabled ? { data: projectApiKeys } : {},
},
create: { useMutation: noopMutation },
- updateNote: { useMutation: noopMutation },
+ updateName: { useMutation: noopMutation },
delete: { useMutation: noopMutation },
},
organizationApiKeys: {
byOrganizationId: { useQuery: () => ({}) },
create: { useMutation: noopMutation },
- updateNote: { useMutation: noopMutation },
+ updateName: { useMutation: noopMutation },
delete: { useMutation: noopMutation },
},
useUtils: () => ({
diff --git a/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.stories.tsx b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.stories.tsx
index b2d679954d..25f17d2649 100644
--- a/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.stories.tsx
+++ b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.stories.tsx
@@ -5,29 +5,43 @@ import { ApiKeySettingsTable } from "./ApiKeySettingsTable";
const meta = preview.meta({ component: ApiKeySettingsTable });
+const apiKey = {
+ id: "key-1",
+ createdAt: new Date("2026-09-01"),
+ expiresAt: null,
+ lastUsedAt: null,
+ note: "Production key",
+ publicKey: "pk-lf-1234",
+ displaySecretKey: "sk-lf-...5678",
+ createdByUser: {
+ id: "user-1",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ image: "https://i.pravatar.cc/[email protected]",
+ },
+ createdByApiKey: null,
+};
+
export const Default = meta.story({
args: {
- editNoteAction: { hasAccess: true, onClick: fn() },
+ editNameAction: { hasAccess: true, onClick: fn() },
hasWriteAccess: true,
onDelete: fn(),
data: {
status: "success",
data: [
+ apiKey,
+ {
+ ...apiKey,
+ id: "key-2",
+ note: "Expired key",
+ expiresAt: new Date("2020-01-01T12:00:00Z"),
+ },
{
- id: "key-1",
- createdAt: new Date("2026-09-01"),
- expiresAt: null,
- lastUsedAt: null,
- note: "Production key",
- publicKey: "pk-lf-1234",
- displaySecretKey: "sk-lf-...5678",
- createdByUser: {
- id: "user-1",
- name: "Ada Lovelace",
- email: "[email protected]",
- image: "https://i.pravatar.cc/[email protected]",
- },
- createdByApiKey: null,
+ ...apiKey,
+ id: "key-3",
+ note: "Future expiration",
+ expiresAt: new Date("2099-01-01T12:00:00Z"),
},
],
},
@@ -36,7 +50,7 @@ export const Default = meta.story({
export const Loading = meta.story({
args: {
- editNoteAction: { hasAccess: true, onClick: fn() },
+ editNameAction: { hasAccess: true, onClick: fn() },
hasWriteAccess: true,
onDelete: fn(),
data: { status: "loading" },
diff --git a/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx
index a6ae4b317d..ec6fafebab 100644
--- a/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx
+++ b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx
@@ -5,8 +5,12 @@ import { type TableProps } from "@/src/components/design-system/table/Table";
import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";
import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";
import { createUserTableColumn } from "@/src/components/design-system/table/columns/createUserTableColumn";
+import { createTableColumn } from "@/src/components/design-system/table/columns/utils/createTableColumn";
import { SettingsTable } from "@/src/components/SettingsTable/SettingsTable";
import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { Skeleton } from "@/src/components/ui/skeleton";
+import { isApiKeyExpired } from "@/src/features/apiKey/helpers/isApiKeyExpired";
+import { buildLocalIsoDatePresentation } from "@/src/utils/dates";
import { type RouterOutput } from "@/src/utils/types";
export type ApiKeySettingsTableRow =
@@ -14,7 +18,7 @@ export type ApiKeySettingsTableRow =
| RouterOutput["organizationApiKeys"]["byOrganizationId"][number];
export function ApiKeySettingsTable({
- editNoteAction,
+ editNameAction,
hasWriteAccess,
onDelete,
...tableProps
@@ -22,7 +26,7 @@ export function ApiKeySettingsTable({
TableProps<ApiKeySettingsTableRow>,
"data" | "loadingRowCount" | "noResultsMessage"
> & {
- editNoteAction: {
+ editNameAction: {
hasAccess: boolean;
onClick: (apiKey: ApiKeySettingsTableRow) => void;
};
@@ -31,11 +35,20 @@ export function ApiKeySettingsTable({
}) {
const columns = useMemo<LangfuseColumnDef<ApiKeySettingsTableRow>[]>(
() => [
- createDateTableColumn<ApiKeySettingsTableRow>({
- accessorKey: "createdAt",
- header: "Created",
- hideBelowMd: true,
+ createTextTableColumn<ApiKeySettingsTableRow>({
+ id: "note",
+ accessorFn: (apiKey) => apiKey.note || null,
+ header: "Name",
enableResizing: false,
+ nullValue: "—",
+ trailingAction: editNameAction.hasAccess
+ ? {
+ type: "custom",
+ icon: Pencil,
+ label: "Edit name",
+ onClick: ({ row }) => editNameAction.onClick(row.original),
+ }
+ : undefined,
}),
createUserTableColumn<ApiKeySettingsTableRow>({
accessorKey: "createdByUser",
@@ -61,21 +74,6 @@ export function ApiKeySettingsTable({
return undefined;
},
}),
- createTextTableColumn<ApiKeySettingsTableRow>({
- id: "note",
- accessorFn: (apiKey) => apiKey.note || null,
- header: "Note",
- enableResizing: false,
- nullValue: "—",
- trailingAction: editNoteAction.hasAccess
- ? {
- type: "custom",
- icon: Pencil,
- label: "Edit note",
- onClick: ({ row }) => editNoteAction.onClick(row.original),
- }
- : undefined,
- }),
createTextTableColumn<ApiKeySettingsTableRow>({
accessorKey: "publicKey",
header: "Public Key",
@@ -87,8 +85,35 @@ export function ApiKeySettingsTable({
header: "Secret Key",
enableResizing: false,
}),
+ createTableColumn<ApiKeySettingsTableRow, Date>({
+ accessorKey: "expiresAt",
+ header: "Expiration",
+ hideBelowMd: true,
+ enableResizing: false,
+ loadingCell: <Skeleton className="h-4 w-1/2" />,
+ renderCell: (expiresAt) => {
+ if (!expiresAt) {
+ return <span className="text-muted-foreground">No expiration</span>;
+ }
+ const date = buildLocalIsoDatePresentation({ date: expiresAt });
+ if (!date) return null;
+
+ return (
+ <span className="block w-full truncate" title={date.title}>
+ {isApiKeyExpired(expiresAt) ? "Expired on " : ""}
+ {date.display}
+ </span>
+ );
+ },
+ }),
+ createDateTableColumn<ApiKeySettingsTableRow>({
+ accessorKey: "createdAt",
+ header: "Created",
+ hideBelowMd: true,
+ enableResizing: false,
+ }),
],
- [editNoteAction],
+ [editNameAction],
);
const actions = useCallback<
@@ -113,6 +138,7 @@ export function ApiKeySettingsTable({
return (
<SettingsTable
tableName="API keys"
+ columnOrderKey="apiKeysColumnOrder-v2"
columns={columns}
actions={actions}
{...tableProps}
diff --git a/web/src/features/public-api/components/ApiKeySettingsTable/ConnectedApiKeySettingsTable.tsx b/web/src/features/public-api/components/ApiKeySettingsTable/ConnectedApiKeySettingsTable.tsx
index 71c247f1cb..5200768231 100644
--- a/web/src/features/public-api/components/ApiKeySettingsTable/ConnectedApiKeySettingsTable.tsx
+++ b/web/src/features/public-api/components/ApiKeySettingsTable/ConnectedApiKeySettingsTable.tsx
@@ -54,8 +54,8 @@ export function ConnectedApiKeySettingsTable({
scope === "project" ? deleteProjectApiKey : deleteOrganizationApiKey;
return (
- <ConnectedApiKeyNoteDialogController entityId={entityId} scope={scope}>
- {({ openDialog: openEditNoteDialog }) => (
+ <ConnectedApiKeyNameDialogController entityId={entityId} scope={scope}>
+ {({ openDialog: openEditNameDialog }) => (
<ConfirmationDialogController<{ id: string }>
title="Delete API key"
text="Are you sure you want to delete this API key? This action cannot be undone."
@@ -87,9 +87,9 @@ export function ConnectedApiKeySettingsTable({
{({ openDialog: openDeleteDialog }) => (
<ApiKeySettingsTable
data={tableData}
- editNoteAction={{
+ editNameAction={{
hasAccess: hasWriteAccess,
- onClick: openEditNoteDialog,
+ onClick: openEditNameDialog,
}}
hasWriteAccess={hasWriteAccess}
onDelete={openDeleteDialog}
@@ -98,11 +98,11 @@ export function ConnectedApiKeySettingsTable({
)}
</ConfirmationDialogController>
)}
- </ConnectedApiKeyNoteDialogController>
+ </ConnectedApiKeyNameDialogController>
);
}
-function ConnectedApiKeyNoteDialogController({
+function ConnectedApiKeyNameDialogController({
children,
entityId,
scope,
@@ -115,11 +115,11 @@ function ConnectedApiKeyNoteDialogController({
}) {
const utils = api.useUtils();
const instance = useRef(0);
- const updateProjectApiKey = api.projectApiKeys.updateNote.useMutation({
+ const updateProjectApiKey = api.projectApiKeys.updateName.useMutation({
onSuccess: () => utils.projectApiKeys.invalidate(),
});
const updateOrganizationApiKey =
- api.organizationApiKeys.updateNote.useMutation({
+ api.organizationApiKeys.updateName.useMutation({
onSuccess: () => utils.organizationApiKeys.invalidate(),
});
const updateApiKey =
@@ -130,24 +130,24 @@ function ConnectedApiKeyNoteDialogController({
onBeforeClose={() => !updateApiKey.isPending}
onDismiss={updateApiKey.reset}
renderDialog={({ state, closeDialog }) => (
- <ApiKeyNoteDialog
+ <ApiKeyNameDialog
key={state.instance}
apiKey={state}
error={updateApiKey.error?.message}
isPending={updateApiKey.isPending}
- onSave={async (note) => {
+ onSave={async (name) => {
try {
if (scope === "project") {
await updateProjectApiKey.mutateAsync({
projectId: entityId,
keyId: state.id,
- note,
+ name,
});
} else {
await updateOrganizationApiKey.mutateAsync({
orgId: entityId,
keyId: state.id,
- note,
+ name,
});
}
closeDialog();
@@ -168,7 +168,7 @@ function ConnectedApiKeyNoteDialogController({
);
}
-function ApiKeyNoteDialog({
+function ApiKeyNameDialog({
apiKey,
error,
isPending,
@@ -177,32 +177,32 @@ function ApiKeyNoteDialog({
apiKey: ApiKeySettingsTableRow;
error?: string;
isPending: boolean;
- onSave: (note: string) => Promise<void>;
+ onSave: (name: string) => Promise<void>;
}) {
const inputId = useId();
- const [note, setNote] = useState(apiKey.note ?? "");
+ const [name, setName] = useState(apiKey.note ?? "");
return (
<Dialog
- title="Edit API key note"
+ title="Edit API key name"
actions={[
{
label: "Save",
loading: isPending,
- disabled: note === (apiKey.note ?? ""),
- onClick: () => onSave(note),
+ disabled: name === (apiKey.note ?? ""),
+ onClick: () => onSave(name),
},
]}
>
<Dialog.Body>
<div className="grid gap-2">
<label htmlFor={inputId} className="text-sm leading-none font-bold">
- Note
+ Name
</label>
<Input
id={inputId}
- value={note}
- onChange={(event) => setNote(event.target.value)}
+ value={name}
+ onChange={(event) => setName(event.target.value)}
disabled={isPending}
error={Boolean(error)}
autoFocus
diff --git a/web/src/features/public-api/components/CreateApiKeyButton.tsx b/web/src/features/public-api/components/CreateApiKeyButton.tsx
index c113998844..1f61998382 100644
--- a/web/src/features/public-api/components/CreateApiKeyButton.tsx
+++ b/web/src/features/public-api/components/CreateApiKeyButton.tsx
@@ -5,7 +5,10 @@ import { useState } from "react";
import { PlusIcon } from "lucide-react";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useLangfuseBaseUrl } from "@/src/features/public-api/hooks/useLangfuseEnvCode";
-import { ApiKeyCreateDialogContent } from "@/src/features/public-api/components/ApiKeyCreateDialogContent";
+import {
+ ApiKeyCreateDialogContent,
+ type ApiKeyCreateValues,
+} from "@/src/features/public-api/components/ApiKeyCreateDialogContent";
type ApiKeyScope = "project" | "organization";
@@ -24,7 +27,6 @@ export function CreateApiKeyButton(props: {
});
const [open, setOpen] = useState(false);
- const [note, setNote] = useState("");
const [generatedKeys, setGeneratedKeys] = useState<{
secretKey: string;
publicKey: string;
@@ -33,40 +35,44 @@ export function CreateApiKeyButton(props: {
const handleOpenChange = (newOpen: boolean) => {
setOpen(newOpen);
- if (!newOpen) {
- // Reset state when closing
- setGeneratedKeys(null);
- setNote("");
- }
+ if (!newOpen) setGeneratedKeys(null);
+ };
+
+ const onCreated = (keys: { secretKey: string; publicKey: string }) => {
+ setGeneratedKeys(keys);
};
- const createApiKey = () => {
+ const createApiKey = (values: ApiKeyCreateValues) => {
if (props.scope === "project") {
mutCreateProjectApiKey
.mutateAsync({
projectId: props.entityId,
- note: note || undefined,
+ name: values.name || undefined,
+ role: values.role,
+ expiresAt: values.expiresAt,
})
.then(({ secretKey, publicKey }) => {
- setGeneratedKeys({
- secretKey,
- publicKey,
+ onCreated({ secretKey, publicKey });
+ capture(`${props.scope}_settings:api_key_create`, {
+ role: values.role,
+ expiresAt: values.expiresAt?.toISOString() ?? null,
});
- capture(`${props.scope}_settings:api_key_create`);
})
.catch((error) => reportNonTrpcError(error, "api-keys"));
} else {
mutCreateOrgApiKey
.mutateAsync({
orgId: props.entityId,
- note: note || undefined,
+ name: values.name || undefined,
+ role: values.role,
+ expiresAt: values.expiresAt,
})
.then(({ secretKey, publicKey }) => {
- setGeneratedKeys({
- secretKey,
- publicKey,
+ onCreated({ secretKey, publicKey });
+ capture(`${props.scope}_settings:api_key_create`, {
+ role: values.role,
+ expiresAt: values.expiresAt?.toISOString() ?? null,
});
- capture(`${props.scope}_settings:api_key_create`);
})
.catch((error) => reportNonTrpcError(error, "api-keys"));
}
@@ -92,8 +98,6 @@ export function CreateApiKeyButton(props: {
}
: {
type: "form" as const,
- note,
- onNoteChange: setNote,
onSubmit: createApiKey,
isPending:
mutCreateProjectApiKey.isPending ||
diff --git a/web/src/features/public-api/components/apiKeyFormOptions.clienttest.ts b/web/src/features/public-api/components/apiKeyFormOptions.clienttest.ts
new file mode 100644
index 0000000000..2f617b634a
--- /dev/null
+++ b/web/src/features/public-api/components/apiKeyFormOptions.clienttest.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveExpiresAt } from "./apiKeyFormOptions";
+
+describe("resolveExpiresAt", () => {
+ const now = new Date("2026-01-01T00:00:00.000Z");
+
+ it("returns null when the key never expires", () => {
+ expect(resolveExpiresAt("never", "", now)).toBeNull();
+ });
+
+ it("offsets a preset by its day count from now", () => {
+ expect(resolveExpiresAt("30d", "", now)).toEqual(
+ new Date("2026-01-31T00:00:00.000Z"),
+ );
+ expect(resolveExpiresAt("1y", "", now)).toEqual(
+ new Date("2027-01-01T00:00:00.000Z"),
+ );
+ });
+
+ it("expires a custom date at the end of that local day", () => {
+ expect(resolveExpiresAt("custom", "2026-06-15", now)).toEqual(
+ new Date(2026, 5, 15, 23, 59, 59, 999),
+ );
+ });
+
+ it("leaves a missing, invalid, or past custom date unresolved", () => {
+ expect(resolveExpiresAt("custom", "", now)).toBeUndefined();
+ expect(resolveExpiresAt("custom", "not-a-date", now)).toBeUndefined();
+ expect(resolveExpiresAt("custom", "2026-02-30", now)).toBeUndefined();
+ expect(resolveExpiresAt("custom", "2025-12-01", now)).toBeUndefined();
+ });
+});
diff --git a/web/src/features/public-api/components/apiKeyFormOptions.ts b/web/src/features/public-api/components/apiKeyFormOptions.ts
new file mode 100644
index 0000000000..91a030f6ce
--- /dev/null
+++ b/web/src/features/public-api/components/apiKeyFormOptions.ts
@@ -0,0 +1,50 @@
+/** ExpiryPreset is a selectable key-lifetime option; `custom` defers to a picked date. */
+export type ExpiryPreset = "never" | "30d" | "60d" | "90d" | "1y" | "custom";
+
+/** expiryPresetOptions lists the lifetime presets in display order; `days` is null when the choice carries no fixed offset. */
+export const expiryPresetOptions: {
+ value: ExpiryPreset;
+ label: string;
+ days: number | null;
+}[] = [
+ { value: "never", label: "No expiration", days: null },
+ { value: "30d", label: "30 days", days: 30 },
+ { value: "60d", label: "60 days", days: 60 },
+ { value: "90d", label: "90 days", days: 90 },
+ { value: "1y", label: "1 year", days: 365 },
+ { value: "custom", label: "Custom date…", days: null },
+];
+
+const MS_PER_DAY = 24 * 60 * 60 * 1000;
+
+/** resolveExpiresAt turns an expiry preset into an absolute date, null when the key never expires, or undefined when the custom date is missing, invalid, or not in the future. */
+export const resolveExpiresAt = (
+ preset: ExpiryPreset,
+ customDate: string,
+ now: Date = new Date(),
+): Date | null | undefined => {
+ if (preset === "custom") return parseCustomExpiry(customDate, now);
+ const days =
+ expiryPresetOptions.find((o) => o.value === preset)?.days ?? null;
+ if (days === null) return null;
+ return new Date(now.getTime() + days * MS_PER_DAY);
+};
+
+/** localDateInputValue formats a date as the local `yyyy-mm-dd` value a date input expects. */
+export const localDateInputValue = (date: Date): string =>
+ [
+ date.getFullYear(),
+ String(date.getMonth() + 1).padStart(2, "0"),
+ String(date.getDate()).padStart(2, "0"),
+ ].join("-");
+
+/** parseCustomExpiry resolves a `yyyy-mm-dd` value to the end of that local day, or undefined unless it is a real date after now. */
+const parseCustomExpiry = (customDate: string, now: Date): Date | undefined => {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(customDate);
+ if (!match) return undefined;
+ const [year, month, day] = [match[1], match[2], match[3]].map(Number);
+ const endOfDay = new Date(year, month - 1, day, 23, 59, 59, 999);
+ const isRealDate =
+ endOfDay.getMonth() === month - 1 && endOfDay.getDate() === day;
+ return isRealDate && endOfDay > now ? endOfDay : undefined;
+};
diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.ts
index f5de4b4e03..93368eb402 100644
--- a/web/src/features/public-api/server/apiAuth.ts
+++ b/web/src/features/public-api/server/apiAuth.ts
@@ -27,7 +27,8 @@ import { isPrismaException } from "@/src/utils/exceptions";
import { type Redis, type Cluster } from "ioredis";
import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server";
import { type z } from "zod";
-import { CloudConfigSchema, isPlan } from "@langfuse/shared";
+import { CloudConfigSchema, isPlan, UnauthorizedError } from "@langfuse/shared";
+import { isApiKeyExpired } from "@/src/features/apiKey/helpers/isApiKeyExpired";
type VerifyAuthHeaderOptions = {
allowInAppAgentKey?: boolean;
@@ -161,6 +162,10 @@ export class ApiAuthService {
);
throw new Error("Invalid credentials");
}
+ if (isApiKeyExpired(finalApiKey.expiresAt)) {
+ logger.info(`Expired api key: ${finalApiKey.publicKey}`);
+ throw new UnauthorizedError("Invalid credentials");
+ }
const plan = finalApiKey.plan;
if (!isPlan(plan)) {
@@ -328,6 +333,10 @@ export class ApiAuthService {
);
throw new Error("Invalid public key");
}
+ if (isApiKeyExpired(dbKey.expiresAt)) {
+ logger.info(`Expired api key: ${dbKey.publicKey}`);
+ throw new UnauthorizedError("Invalid public key");
+ }
return dbKey;
}
@@ -524,6 +533,7 @@ export class ApiAuthService {
const newApiKey = OrgEnrichedApiKey.parse({
...apiKeyAndOrganisation,
createdAt: apiKeyAndOrganisation.createdAt?.toISOString(),
+ expiresAt: apiKeyAndOrganisation.expiresAt?.toISOString() ?? null,
orgId,
organizationCreatedAt: organizationCreatedAt.toISOString(),
plan: getOrganizationPlanServerSide(cloudConfig),
diff --git a/web/src/features/public-api/server/assertApiKeyRoleForMigration.ts b/web/src/features/public-api/server/assertApiKeyRoleForMigration.ts
new file mode 100644
index 0000000000..ff44ff8f21
--- /dev/null
+++ b/web/src/features/public-api/server/assertApiKeyRoleForMigration.ts
@@ -0,0 +1,20 @@
+import { InvalidRequestError } from "@langfuse/shared";
+import { isLegacyApiKeyRole } from "@langfuse/shared/rbac";
+import { type SystemRole } from "@langfuse/shared/src/db";
+
+import { env } from "@/src/env.mjs";
+
+/** assertApiKeyRoleForMigration rejects a role the active migration mode will not honor. */
+export function assertApiKeyRoleForMigration(role: SystemRole): void {
+ const enforce = env.API_AUTH_MIGRATION === "enforce";
+ if (enforce && isLegacyApiKeyRole(role)) {
+ throw new InvalidRequestError(
+ `Legacy role ${role} cannot be assigned to a new API key`,
+ );
+ }
+ if (!enforce && !isLegacyApiKeyRole(role)) {
+ throw new InvalidRequestError(
+ `Role ${role} cannot be assigned until API key authorization is enforced`,
+ );
+ }
+}
diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
index f3a2874d8f..1a5a41b6e6 100644
--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
@@ -35,10 +35,8 @@ import { attachDeprecation } from "@/src/features/public-api/server/deprecations
import { applyLegacyApiOrganizationCutoff } from "@/src/features/public-api/server/legacyApiOrganizationCutoff";
import { type RouteAccessLevel } from "@/src/features/public-api/server/verifyProjectApiKeyAuth";
import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";
-import {
- type AuthorizationContext,
- type ProjectAction,
-} from "@/src/features/auth/policy/types";
+import { type ProjectAction } from "@langfuse/shared/rbac";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
// Next's res.json uses JSON.stringify; V8 throws this when the JSON string
// exceeds the engine limit. Keep this check scoped to the response write.
@@ -93,7 +91,7 @@ export type AuthedProjectAPIRouteConfig<
* Admin API key authentication requires:
* - Authorization: Bearer <ADMIN_API_KEY>
* - x-langfuse-admin-api-key: <ADMIN_API_KEY> (must match exactly for redundancy)
- * - x-langfuse-project-id: <project-id> (target project)
+ * - x-langfuse-project-id or langfuse-project-id: <project-id> (target project)
*
* This authentication method is ONLY available when NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is not set (self-hosted).
*
diff --git a/web/src/features/public-api/server/enforceAuth.ts b/web/src/features/public-api/server/enforceAuth.ts
index 2a3052351b..4ec39d40db 100644
--- a/web/src/features/public-api/server/enforceAuth.ts
+++ b/web/src/features/public-api/server/enforceAuth.ts
@@ -4,25 +4,31 @@ import {
type ForbiddenError,
type InternalServerError,
type LangfuseNotFoundError,
+ type ServiceUnavailableError,
type UnauthorizedError,
} from "@langfuse/shared";
import { type ApiAccessScope } from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
+import {
+ isOrgAction,
+ OrganizationId,
+ ProjectId,
+ type Action,
+ type ResourceId,
+ type TenantId,
+} from "@langfuse/shared/rbac";
-import { authorize } from "@/src/features/auth/policy/authorize";
+import { authorize } from "@/src/features/rbac/authorize";
import { authenticator } from "@/src/features/apiKey/server";
import { toApiAccessScope } from "@/src/features/public-api/server/toApiAccessScope";
import {
forbiddenError,
internalServerError,
- isOrgAction,
notFoundError,
- type Action,
type AuthorizationContext,
type Decision,
type ErrorResult,
type Principal,
- type Resource,
type Success,
} from "@/src/features/auth/policy/types";
@@ -30,10 +36,10 @@ import {
export const __dangerouslySkipAuthz = "__dangerouslySkipAuthz" as const;
/** orgIdHeader selects the target org. */
-const orgIdHeader = "x-langfuse-organization-id";
+const orgIdHeader = "langfuse-organization-id";
/** projectIdHeader selects the target project for keys without a bound project. */
-const projectIdHeader = "x-langfuse-project-id";
+const projectIdHeader = "langfuse-project-id";
/** enforceAuth authenticates the request and authorizes the action for the given endpoint, or only resolves context when the route skips authz (combines authz and authn). */
export async function enforceAuth({
@@ -74,7 +80,12 @@ async function enforceAdminAuthz(
const org = await lookupProjectOrgId(projectId);
if (!org.success) return org;
- const decision = authorizeAction(context, action, { projectId });
+ const decision = authorizeAction(
+ context,
+ OrganizationId(org.orgId),
+ action,
+ ProjectId(projectId),
+ );
if (!decision.success) return decision;
return access(context, org.orgId, projectId);
@@ -89,7 +100,12 @@ function enforceOrgAuthz(
const org = getOrgId(context, req);
if (!org.success) return org;
- const decision = authorizeAction(context, action, { orgId: org.orgId });
+ const decision = authorizeAction(
+ context,
+ OrganizationId(org.orgId),
+ action,
+ OrganizationId(org.orgId),
+ );
if (!decision.success) return decision;
return access(context, org.orgId);
@@ -108,25 +124,29 @@ function enforceProjectAuthz(
return notFoundError("Project not found or you don't have access to it");
}
- const decision = authorizeAction(context, action, {
- projectId: project.projectId,
- });
- if (!decision.success) return decision;
-
const orgId = getBoundOrgId(context);
if (!orgId) return internalServerError(`Missing bound org on api-key`);
+ const decision = authorizeAction(
+ context,
+ OrganizationId(orgId),
+ action,
+ ProjectId(project.projectId),
+ );
+ if (!decision.success) return decision;
+
return access(context, orgId, project.projectId);
}
-/** authorizeAction authorizes against a given action, or passes when the route skips authz and authorizes each call itself. */
+/** authorizeAction authorizes against a given action within a tenant, or passes when the route skips authz and authorizes each call itself. */
function authorizeAction(
context: AuthorizationContext,
+ tenant: TenantId,
action: ApiAction,
- resource: Resource,
+ resource: ResourceId,
): Decision {
if (action === __dangerouslySkipAuthz) return { success: true };
- return authorize(context, action, resource);
+ return authorize(context, tenant, action, resource);
}
/** getOrgId resolves the target org the key's bound org and the header agree on. */
@@ -195,12 +215,12 @@ function getBoundProjectId(context: AuthorizationContext): string | undefined {
/** getHeaderOrgId returns the target org from the header. */
function getHeaderOrgId(req: NextApiRequest): string | undefined {
- return getHeaderValue(req.headers[orgIdHeader]) || undefined;
+ return getHeaderValue(req, orgIdHeader);
}
/** getHeaderProjectId returns the target project from the header. */
function getHeaderProjectId(req: NextApiRequest): string | undefined {
- return getHeaderValue(req.headers[projectIdHeader]) || undefined;
+ return getHeaderValue(req, projectIdHeader);
}
/** getUrlProjectId returns the target project from the URL param. */
@@ -210,10 +230,14 @@ function getUrlProjectId(req: NextApiRequest): string | undefined {
: undefined;
}
-/** getHeaderValue normalizes a possibly-repeated header to its first value. */
-const getHeaderValue = (
- value: string | string[] | undefined,
-): string | undefined => (Array.isArray(value) ? value[0] : value);
+/** getHeaderValue prefers the X-prefixed alias and normalizes repeated headers to their first value. */
+function getHeaderValue(
+ req: NextApiRequest,
+ header: string,
+): string | undefined {
+ const value = req.headers[`x-${header}`] ?? req.headers[header];
+ return (Array.isArray(value) ? value[0] : value) || undefined;
+}
/** equal returns true when every defined value agrees. */
function equal(os: (string | undefined)[]): boolean {
@@ -271,6 +295,7 @@ export type EnforceAuthResult =
| InternalServerError
| ForbiddenError
| LangfuseNotFoundError
+ | ServiceUnavailableError
>;
/** ResolvedOrg is org target resolution's success outcome. */
diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.ts
index 0fb701ae46..2bdefc8657 100644
--- a/web/src/features/public-api/server/organizationApiKeyRouter.ts
+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts
@@ -9,7 +9,21 @@ import * as z from "zod";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { redis } from "@langfuse/shared/src/server";
import { LangfuseNotFoundError } from "@langfuse/shared";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
+import {
+ apiKeyRolesAcceptedForScope,
+ OrganizationId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
+import { SystemRole } from "@langfuse/shared/src/db";
+
+import { assertApiKeyRoleForMigration } from "@/src/features/public-api/server/assertApiKeyRoleForMigration";
+
+const organizationApiKeyRoles = apiKeyRolesAcceptedForScope("organization") as [
+ SystemRole,
+ ...SystemRole[],
+];
export const organizationApiKeysRouter = createTRPCRouter({
byOrganizationId: protectedOrganizationProcedure
@@ -63,7 +77,14 @@ export const organizationApiKeysRouter = createTRPCRouter({
.input(
z.object({
orgId: z.string(),
- note: z.string().optional(),
+ name: z.string().optional(),
+ role: z.enum(organizationApiKeyRoles).default(SystemRole.ADMIN),
+ expiresAt: z
+ .date()
+ .nullish()
+ .refine((date) => date == null || date.getTime() > Date.now(), {
+ message: "Expiration date must be in the future",
+ }),
}),
)
.mutation(async ({ input, ctx }) => {
@@ -81,12 +102,14 @@ export const organizationApiKeysRouter = createTRPCRouter({
orgId: input.orgId,
});
- const apiKeyMeta = await createAndAddApiKeysToDb({
- prisma: ctx.prisma,
- entityId: input.orgId,
- note: input.note,
- scope: "ORGANIZATION",
- createdByUserId: ctx.session.user.id,
+ assertApiKeyRoleForMigration(input.role);
+
+ const apiKeyMeta = await createApiKey(ctx.prisma, {
+ owner: OrganizationId(input.orgId),
+ role: SystemRoleId(input.role),
+ createdBy: UserId(ctx.session.user.id),
+ name: input.name,
+ expiresAt: input.expiresAt,
});
await auditLog({
@@ -94,16 +117,20 @@ export const organizationApiKeysRouter = createTRPCRouter({
resourceType: "apiKey",
resourceId: apiKeyMeta.id,
action: "create",
+ after: {
+ role: input.role,
+ expiresAt: input.expiresAt ?? null,
+ },
});
return apiKeyMeta;
}),
- updateNote: protectedOrganizationProcedure
+ updateName: protectedOrganizationProcedure
.input(
z.object({
orgId: z.string(),
keyId: z.string(),
- note: z.string(),
+ name: z.string(),
}),
)
.mutation(async ({ input, ctx }) => {
@@ -139,7 +166,7 @@ export const organizationApiKeysRouter = createTRPCRouter({
isInAppAgentKey: false,
},
data: {
- note: input.note,
+ note: input.name,
},
});
diff --git a/web/src/features/public-api/server/projectApiKeyRouter.ts b/web/src/features/public-api/server/projectApiKeyRouter.ts
index dbed8a5fde..a02ab13c2f 100644
--- a/web/src/features/public-api/server/projectApiKeyRouter.ts
+++ b/web/src/features/public-api/server/projectApiKeyRouter.ts
@@ -7,8 +7,22 @@ import {
import * as z from "zod";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { redis } from "@langfuse/shared/src/server";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
import { LangfuseNotFoundError, StringNoHTML } from "@langfuse/shared";
+import {
+ apiKeyRolesAcceptedForScope,
+ ProjectId,
+ SystemRoleId,
+ UserId,
+} from "@langfuse/shared/rbac";
+import { SystemRole } from "@langfuse/shared/src/db";
+
+import { assertApiKeyRoleForMigration } from "@/src/features/public-api/server/assertApiKeyRoleForMigration";
+
+const projectApiKeyRoles = apiKeyRolesAcceptedForScope("project") as [
+ SystemRole,
+ ...SystemRole[],
+];
export const projectApiKeysRouter = createTRPCRouter({
byProjectId: protectedProjectProcedure
@@ -62,7 +76,14 @@ export const projectApiKeysRouter = createTRPCRouter({
.input(
z.object({
projectId: z.string(),
- note: StringNoHTML.optional(),
+ name: StringNoHTML.optional(),
+ role: z.enum(projectApiKeyRoles).default(SystemRole.ADMIN),
+ expiresAt: z
+ .date()
+ .nullish()
+ .refine((date) => date == null || date.getTime() > Date.now(), {
+ message: "Expiration date must be in the future",
+ }),
}),
)
.mutation(async ({ input, ctx }) => {
@@ -72,12 +93,14 @@ export const projectApiKeysRouter = createTRPCRouter({
scope: "apiKeys:CUD",
});
- const apiKeyMeta = await createAndAddApiKeysToDb({
- prisma: ctx.prisma,
- entityId: input.projectId,
- note: input.note,
- scope: "PROJECT",
- createdByUserId: ctx.session.user.id,
+ assertApiKeyRoleForMigration(input.role);
+
+ const apiKeyMeta = await createApiKey(ctx.prisma, {
+ owner: ProjectId(input.projectId),
+ role: SystemRoleId(input.role),
+ createdBy: UserId(ctx.session.user.id),
+ name: input.name,
+ expiresAt: input.expiresAt,
});
await auditLog({
@@ -85,16 +108,17 @@ export const projectApiKeysRouter = createTRPCRouter({
resourceType: "apiKey",
resourceId: apiKeyMeta.id,
action: "create",
+ after: { role: input.role, expiresAt: input.expiresAt ?? null },
});
return apiKeyMeta;
}),
- updateNote: protectedProjectProcedure
+ updateName: protectedProjectProcedure
.input(
z.object({
projectId: z.string(),
keyId: z.string(),
- note: StringNoHTML,
+ name: StringNoHTML,
}),
)
.mutation(async ({ input, ctx }) => {
@@ -130,7 +154,7 @@ export const projectApiKeysRouter = createTRPCRouter({
isInAppAgentKey: false,
},
data: {
- note: input.note,
+ note: input.name,
},
});
diff --git a/web/src/features/public-api/server/shadowAuth.ts b/web/src/features/public-api/server/shadowAuth.ts
index ff764d7e63..241c78e132 100644
--- a/web/src/features/public-api/server/shadowAuth.ts
+++ b/web/src/features/public-api/server/shadowAuth.ts
@@ -1,13 +1,21 @@
import { type NextApiRequest } from "next";
-import { ApiError, type BaseError } from "@langfuse/shared";
+import { ApiError, isBaseError, type BaseError } from "@langfuse/shared";
import {
type ApiAccessLevel,
type ApiAccessScope,
+ logger,
+ redactLangfuseSecretKeys,
redis,
traceException,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
+import {
+ OrganizationId,
+ ProjectId,
+ type ResourceId,
+ type TenantId,
+} from "@langfuse/shared/rbac";
import { env } from "@/src/env.mjs";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
@@ -23,9 +31,10 @@ import {
type EnforceAuthResult,
} from "@/src/features/public-api/server/enforceAuth";
import { shadowAuthDiff } from "@/src/features/public-api/server/shadowAuthDiff";
-import { authorize } from "@/src/features/auth/policy/authorize";
+import { authorize } from "@/src/features/rbac/authorize";
import {
forbiddenError,
+ internalServerError,
serviceUnavailableError,
unauthorizedError,
type AuthorizationContext,
@@ -46,8 +55,50 @@ export async function shadowAuth(
}
/** enforceOnly authorizes solely with the new pipeline and returns its scope or error. */
-function enforceOnly(params: ShadowAuthParams): Promise<ShadowAuthResult> {
- return runNewAuth(params);
+async function enforceOnly(
+ params: ShadowAuthParams,
+): Promise<ShadowAuthResult> {
+ try {
+ const result = await runNewAuth(params);
+ if (result.success || result.error.httpCode < 500) return result;
+ return enforceInfrastructureError(result.error);
+ } catch (error) {
+ if (isBaseError(error) && error.isUserError()) throw error;
+ return enforceInfrastructureError(error);
+ }
+}
+
+/** enforceInfrastructureError logs diagnostics and returns a generic failure. */
+function enforceInfrastructureError(error: unknown): ErrorResult<BaseError> {
+ logAuthenticationError(error);
+ return genericInfrastructureError(infrastructureHttpCode(error));
+}
+
+function logAuthenticationError(error: unknown): void {
+ logger.error("Public API authentication failed", {
+ error: redactLangfuseSecretKeys(errorDiagnostic(error)),
+ });
+}
+
+function errorDiagnostic(error: unknown): string {
+ return error instanceof Error
+ ? (error.stack ?? error.message)
+ : String(error);
+}
+
+/** infrastructureHttpCode preserves typed statuses and maps Prisma failures to 503. */
+function infrastructureHttpCode(error: unknown): number {
+ const fallbackCode = isPrismaException(error) ? 503 : 500;
+ return isBaseError(error) ? error.httpCode : fallbackCode;
+}
+
+function genericInfrastructureError(httpCode: number): ErrorResult<BaseError> {
+ if (httpCode === 503) return serviceUnavailableError();
+ if (httpCode === 500) return internalServerError();
+ return {
+ success: false,
+ error: new ApiError("Internal Server Error", httpCode),
+ };
}
/** legacyWithShadow lets legacy decide while the new pipeline records parity. */
@@ -141,34 +192,69 @@ function isOrgFamily(allowedAccessLevels: ApiAccessLevel[]): boolean {
);
}
-/** shadowAuthorize authorizes one item against a shadowAuth-resolved context for the active migration mode: legacy and ungated items pass, shadow only diffs against legacy's implicit allow, and enforce returns the decision the caller disposes of. */
+/** shadowAuthorize enforces per-item permissions or compares them with the caller's legacy decision. */
export function shadowAuthorize(params: ShadowAuthorizeParams): Decision {
- if (params.action === __dangerouslySkipAuthz || !params.ctx) {
+ if (params.action === __dangerouslySkipAuthz) {
return { success: true };
}
- const decision = authorize(params.ctx, params.action, params.resource);
+ if (!params.ctx) return skipAuthorization(params);
+ const decision = authorize(
+ params.ctx,
+ tenantFor(params.ctx, params.resource),
+ params.action,
+ toResourceId(params.resource),
+ );
+ return diffOrGate(params, decision);
+}
+
+/** skipAuthorization returns an early decision when policy evaluation is skipped or unavailable. */
+function skipAuthorization(params: ShadowAuthorizeParams): Decision {
+ if (env.API_AUTH_MIGRATION === "enforce") {
+ return unauthorizedError("Missing authz context");
+ }
+ return params.legacyDecision;
+}
+
+/** diffOrGate shadows the authorization outcome or enforces it depending on the AUTH_API_MIGRATION */
+function diffOrGate(
+ params: ShadowAuthorizeParams,
+ decision: Decision,
+): Decision {
if (env.API_AUTH_MIGRATION === "shadow") {
- shadowAuthDiff(
- decision,
- { success: true, scope: { accessLevel: params.accessLevel } },
- params.action,
- );
- return { success: true };
+ shadowAuthDiff(decision, params.legacyDecision, params.action);
+ return params.legacyDecision;
}
return decision;
}
+/** toResourceId tags a per-item resource for the PDP. */
+function toResourceId(resource: Resource): ResourceId {
+ return "projectId" in resource
+ ? ProjectId(resource.projectId)
+ : OrganizationId(resource.orgId);
+}
+
+/** tenantFor is the resource's tenant: an org resource is its own tenant; a per-item project is scoped to the key's already-resolved bound org. Admin carries no tenant and the PDP grants it directly. */
+function tenantFor(ctx: AuthorizationContext, resource: Resource): TenantId {
+ if ("orgId" in resource) return OrganizationId(resource.orgId);
+ const boundOrg =
+ ctx.principal.kind === "apiKey" ? ctx.principal.boundResource.orgId : "";
+ return OrganizationId(boundOrg);
+}
+
/** ShadowAuthParams is enforceAuth's params plus the access levels the legacy verify gates on. */
export type ShadowAuthParams = EnforceAuthParams & {
allowedAccessLevels: ApiAccessLevel[];
};
-/** ShadowAuthorizeParams is one per-item authorization: the resolved context, the action the item asserts or the explicit opt-out, the resource it targets, and the access level the shadow diff records. */
+/** ShadowAuthorizeParams carries the per-item action, context, resource, and legacy decision. */
export type ShadowAuthorizeParams = {
ctx: AuthorizationContext | undefined;
action: ApiAction;
resource: Resource;
- accessLevel: ApiAccessLevel;
+ legacyDecision:
+ | { success: true; scope: { accessLevel: ApiAccessLevel } }
+ | ErrorResult<BaseError>;
};
/** ShadowAuthAccessResult is a verified scope; the authorizing context rides along only when the new pipeline produced it. */
diff --git a/web/src/features/public-api/server/verifyProjectApiKeyAuth.ts b/web/src/features/public-api/server/verifyProjectApiKeyAuth.ts
index e13ce4f0e9..a8f1f4b339 100644
--- a/web/src/features/public-api/server/verifyProjectApiKeyAuth.ts
+++ b/web/src/features/public-api/server/verifyProjectApiKeyAuth.ts
@@ -72,7 +72,7 @@ async function verifyApiKeyAuth(
* This function checks if the request contains valid admin API key credentials:
* 1. Authorization header must be Bearer token format with ADMIN_API_KEY value
* 2. x-langfuse-admin-api-key header must match ADMIN_API_KEY env var exactly (for redundancy)
- * 3. x-langfuse-project-id header must be present and specify a valid project ID
+ * 3. x-langfuse-project-id or langfuse-project-id header must be present and specify a valid project ID
* 4. NEXT_PUBLIC_LANGFUSE_CLOUD_REGION must NOT be set (self-hosted instances only)
*
* The ADMIN_API_KEY must be set as an environment variable on the server.
@@ -90,7 +90,8 @@ async function verifyAdminApiKeyAuth(req: NextApiRequest): Promise<
> {
const authHeader = req.headers.authorization;
const adminApiKeyHeader = req.headers["x-langfuse-admin-api-key"];
- const projectIdHeader = req.headers["x-langfuse-project-id"];
+ const projectIdHeader =
+ req.headers["x-langfuse-project-id"] ?? req.headers["langfuse-project-id"];
// If not attempting admin auth, return null to proceed with regular auth
if (!authHeader?.startsWith("Bearer ") || !adminApiKeyHeader) return null;
@@ -140,7 +141,7 @@ async function verifyAdminApiKeyAuth(req: NextApiRequest): Promise<
throw {
status: 400,
message:
- "x-langfuse-project-id header is required for admin API key authentication",
+ "langfuse-project-id header is required for admin API key authentication",
};
}
diff --git a/web/src/features/rbac/authorize.ts b/web/src/features/rbac/authorize.ts
new file mode 100644
index 0000000000..0a5bd6398b
--- /dev/null
+++ b/web/src/features/rbac/authorize.ts
@@ -0,0 +1,71 @@
+import {
+ hasProjectKind,
+ type Action,
+ type Effect,
+ type OrganizationId,
+ type ProjectId,
+ type ResourceId,
+ type TenantId,
+} from "@langfuse/shared/rbac";
+
+import { type Policy } from "./types";
+import {
+ forbiddenError,
+ type AuthorizationContext,
+ type Decision,
+} from "@/src/features/auth/policy/types";
+
+/** wildcardProjectId is the project-kind wildcard an org role binds to; it matches every project of its tenant but is never a valid authorization target. */
+const wildcardProjectId: ProjectId = "project/*";
+
+/** wildcardOrgId is the org-kind wildcard a cross-tenant role binds to; as a tenant it matches every tenant, and as a resource it matches every org target, but it is never a valid authorization target itself. */
+const wildcardOrgId: OrganizationId = "organization/*";
+
+/** authorize evaluates the tenant's policies for action on resource: with no matching grant, or any matching deny, it 403s; otherwise it succeeds. A policy on the organization/* tenant matches every tenant, and an organization/* resource matches every org target — the machinery the all-tenant admin role evaluates through. */
+export function authorize(
+ ctx: AuthorizationContext,
+ tenant: TenantId,
+ action: Action,
+ resource: ResourceId,
+): Decision {
+ if (hasWildcard(resource)) return forbiddenError();
+
+ const policiesForResource = matchesResource(ctx, tenant, resource);
+ const grant = policiesForResource.filter(byAction(action));
+ if (grant.length === 0 || grant.some(byEffect("DENY"))) {
+ return forbiddenError();
+ }
+ return { success: true };
+}
+
+/** matchesResource scopes the context to the resource's tenant, preferring an exact-resource match over the kind's wildcard: a project target falls back to project/*, an org target to organization/*. */
+function matchesResource(
+ ctx: AuthorizationContext,
+ tenant: TenantId,
+ resource: ResourceId,
+): Policy[] {
+ const owning = ctx.policies.filter(byTenant(tenant));
+ const exact = owning.filter(byResource(resource));
+ if (exact.length > 0) return exact;
+ const wildcard = hasProjectKind(resource) ? wildcardProjectId : wildcardOrgId;
+ return owning.filter((p) => p.resources.includes(wildcard));
+}
+
+/** hasWildcard reports whether resource is a kind wildcard, never authorizable in itself. */
+const hasWildcard = (resource: ResourceId): boolean =>
+ resource === wildcardProjectId || resource === wildcardOrgId;
+
+/** byTenant matches a policy scoped to the resource's tenant, or to the organization/* wildcard tenant that spans every tenant. */
+const byTenant = (tenant: TenantId) => (p: Policy) =>
+ p.tenantId === tenant || p.tenantId === wildcardOrgId;
+
+/** byResource matches a policy listing the exact resource. */
+const byResource = (resource: ResourceId) => (p: Policy) =>
+ p.resources.includes(resource);
+
+/** byAction matches a policy granting the action explicitly; actions are never wildcarded. */
+const byAction = (action: Action) => (p: Policy) =>
+ (p.actions as readonly string[]).includes(action);
+
+/** byEffect matches a policy of the given effect. */
+const byEffect = (effect: Effect) => (p: Policy) => p.effect === effect;
diff --git a/web/src/features/rbac/components/CreateProjectMemberDialog.tsx b/web/src/features/rbac/components/CreateProjectMemberDialog.tsx
index a936fee5b8..6e6c670f4f 100644
--- a/web/src/features/rbac/components/CreateProjectMemberDialog.tsx
+++ b/web/src/features/rbac/components/CreateProjectMemberDialog.tsx
@@ -15,13 +15,7 @@ import {
FormMessage,
} from "@/src/components/ui/form";
import { Input } from "@/src/components/ui/input";
-import {
- Select,
- SelectContent,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
-import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";
+import { RoleSelect } from "@/src/features/rbac/components/RoleSelect";
import { reportTrpcErrorWithoutToast } from "@/src/utils/api";
const roleValues = {
@@ -125,25 +119,11 @@ export function CreateProjectMemberDialog({
render={({ field }) => (
<FormItem>
<FormLabel>Organization Role</FormLabel>
- <Select
- defaultValue={field.value}
- onValueChange={(value) =>
- field.onChange(
- value as (typeof roleValues)[keyof typeof roleValues],
- )
- }
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue placeholder="Select an organization role" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {Object.values(roleValues).map((role) => (
- <RoleSelectItem role={role} key={role} />
- ))}
- </SelectContent>
- </Select>
+ <RoleSelect
+ roles={Object.values(roleValues)}
+ value={field.value}
+ onValueChange={field.onChange}
+ />
<FormMessage />
</FormItem>
)}
@@ -156,35 +136,16 @@ export function CreateProjectMemberDialog({
render={({ field }) => (
<FormItem>
<FormLabel>Project Role</FormLabel>
- <Select
- defaultValue={field.value}
- onValueChange={(value) =>
- field.onChange(
- value as (typeof roleValues)[keyof typeof roleValues],
- )
- }
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue placeholder="Select a project role" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {Object.values(roleValues)
- .filter(
- (role) =>
- !hasOnlySingleProjectAccess ||
- role !== roleValues.NONE,
- )
- .map((role) => (
- <RoleSelectItem
- role={role}
- key={role}
- isProjectRole
- />
- ))}
- </SelectContent>
- </Select>
+ <RoleSelect
+ isProjectRole
+ roles={Object.values(roleValues).filter(
+ (role) =>
+ !hasOnlySingleProjectAccess ||
+ role !== roleValues.NONE,
+ )}
+ value={field.value}
+ onValueChange={field.onChange}
+ />
{!hasOnlySingleProjectAccess && (
<FormDescription>
This project role will override the default role for
diff --git a/web/src/features/rbac/components/MembersSettingsTable/MembersSettingsTable.tsx b/web/src/features/rbac/components/MembersSettingsTable/MembersSettingsTable.tsx
index 2cf1f642d8..9ea32d6988 100644
--- a/web/src/features/rbac/components/MembersSettingsTable/MembersSettingsTable.tsx
+++ b/web/src/features/rbac/components/MembersSettingsTable/MembersSettingsTable.tsx
@@ -13,17 +13,11 @@ import { createBadgeListTableColumn } from "@/src/components/design-system/table
import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";
import { createUserTableColumn } from "@/src/components/design-system/table/columns/createUserTableColumn";
import { type LangfuseColumnDef } from "@/src/components/table/types";
-import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";
+import { RoleSelect } from "@/src/features/rbac/components/RoleSelect";
import { orderedRoles } from "@/src/features/rbac/constants/orderedRoles";
import type { FeaturePreviewFlag } from "@/src/features/feature-flags";
import { UserFeaturePreviewsControl } from "@/src/features/feature-flags/components/UserFeaturePreviewsPopover";
import type { RouterOutput } from "@/src/utils/types";
-import {
- Select,
- SelectContent,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";
import Link from "next/link";
import { Popover, PopoverTrigger } from "@/src/components/ui/popover";
@@ -32,7 +26,9 @@ import { Button } from "@/src/components/ui/button";
const formatRoleLabel = (role: Role) =>
role.charAt(0).toUpperCase() + role.slice(1).toLowerCase();
-const roleFilterOptions = (Object.keys(orderedRoles) as Role[])
+const allRoles = Object.keys(orderedRoles) as Role[];
+
+const roleFilterOptions = allRoles
.toSorted((a, b) => orderedRoles[b] - orderedRoles[a])
.map((role) => ({ value: role, label: formatRoleLabel(role) }));
@@ -126,7 +122,9 @@ export function MembersSettingsTable({
cell: ({ row }) => {
const select = (
<RoleSelect
+ roles={allRoles}
value={row.original.orgRole}
+ size="compact"
disabled={
!hasOrgCudAccess ||
Boolean(project) ||
@@ -134,7 +132,7 @@ export function MembersSettingsTable({
row.original.meta.orgMembershipId,
)
}
- onChange={(role) => onUpdateOrgRole(row.original, role)}
+ onValueChange={(role) => onUpdateOrgRole(row.original, role)}
/>
);
@@ -184,15 +182,19 @@ export function MembersSettingsTable({
if (!projectRolesEntitlement) return "N/A on plan";
return (
<RoleSelect
+ roles={allRoles}
value={row.original.projectRole ?? "NONE"}
isProjectRole
+ size="compact"
disabled={
(!hasOrgCudAccess && !hasProjectCudAccess) ||
updatingProjectRoleMembershipIds.has(
row.original.meta.orgMembershipId,
)
}
- onChange={(role) => onUpdateProjectRole(row.original, role)}
+ onValueChange={(role) =>
+ onUpdateProjectRole(row.original, role)
+ }
/>
);
},
@@ -318,36 +320,3 @@ export function MembersSettingsTable({
/>
);
}
-
-function RoleSelect({
- value,
- disabled,
- isProjectRole = false,
- onChange,
-}: {
- value: Role;
- disabled: boolean;
- isProjectRole?: boolean;
- onChange: (role: Role) => void;
-}) {
- return (
- <Select
- disabled={disabled}
- value={value}
- onValueChange={(role) => onChange(role as Role)}
- >
- <SelectTrigger className="w-[120px]">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {(Object.keys(orderedRoles) as Role[]).map((role) => (
- <RoleSelectItem
- role={role}
- key={role}
- isProjectRole={isProjectRole}
- />
- ))}
- </SelectContent>
- </Select>
- );
-}
diff --git a/web/src/features/rbac/components/RolePermissionList.tsx b/web/src/features/rbac/components/RolePermissionList.tsx
new file mode 100644
index 0000000000..02e45ba0b8
--- /dev/null
+++ b/web/src/features/rbac/components/RolePermissionList.tsx
@@ -0,0 +1,198 @@
+import { Fragment, useEffect, useRef, useState } from "react";
+
+import {
+ systemRoleAccessRights,
+ type SystemRolePolicy,
+} from "@langfuse/shared/rbac";
+import { type SystemRole } from "@langfuse/shared/src/db";
+import { Badge } from "@/src/components/ui/badge";
+import { cn } from "@/src/utils/tailwind";
+
+const resourceKindLabels: Record<ResourceKind, string> = {
+ organization: "Organization",
+ project: "Project",
+};
+
+const resourceKindOrder: ResourceKind[] = ["organization", "project"];
+
+const actionOrder = [
+ "read",
+ "create",
+ "update",
+ "save",
+ "delete",
+ "CUD",
+ "CRUD",
+];
+
+const entityLabels: Record<string, string> = {
+ projects: "Project management",
+ organization: "Organization",
+ organizationMembers: "Organization members",
+ langfuseCloudBilling: "Billing",
+ orgAuditLogs: "Organization audit logs",
+ projectAuditLogs: "Project audit logs",
+ projectMembers: "Project members",
+ apiKeys: "API keys",
+ objects: "Objects",
+ traces: "Traces",
+ media: "Media",
+ scores: "Scores",
+ scoreConfigs: "Score configs",
+ annotationQueues: "Annotation queues",
+ annotationQueueAssignments: "Annotation queue assignments",
+ project: "Project",
+ integrations: "Integrations",
+ datasets: "Datasets",
+ prompts: "Prompts",
+ promptProtectedLabels: "Prompt protected labels",
+ dashboards: "Dashboards",
+ models: "Models",
+ batchExports: "Batch exports",
+ evaluator: "Evaluators",
+ evaluationRule: "Evaluation rules",
+ evalJobExecution: "Eval job execution",
+ evalDefaultModel: "Eval default model",
+ llmApiKeys: "LLM API keys",
+ llmSchemas: "LLM schemas",
+ llmTools: "LLM tools",
+ playground: "Playground",
+ comments: "Comments",
+ promptExperiments: "Prompt experiments",
+ TableViewPresets: "Table view presets",
+ automations: "Automations",
+ alerts: "Alerts",
+ gateway: "AI Gateway",
+ experiments: "Experiments",
+ sessions: "Sessions",
+ metrics: "Metrics",
+ feedback: "Feedback",
+};
+
+/** RolePermissionList groups permissions by resource kind and entity. */
+export const RolePermissionList = ({ role }: { role: SystemRole }) => {
+ const { policies } = systemRoleAccessRights[role];
+
+ if (policies.length === 0)
+ return (
+ <p className="text-muted-foreground text-xs italic">
+ No permissions granted.
+ </p>
+ );
+
+ return (
+ <div className="grid grid-cols-[max-content_1fr] items-center gap-x-6 gap-y-2 pb-5">
+ {resourceKindOrder.map((kind) => {
+ const scopes = policies
+ .filter((policy) => policy.resourceKind === kind)
+ .flatMap((policy) => policy.actions);
+ if (scopes.length === 0) return null;
+
+ return (
+ <Fragment key={kind}>
+ <SectionHeader label={resourceKindLabels[kind]} />
+ {groupByEntity(scopes).map((group) => (
+ <div key={group.entity} className="contents">
+ <span className="pl-4 text-xs leading-tight font-bold whitespace-nowrap">
+ {group.title}
+ </span>
+ <div className="flex flex-wrap gap-1 pr-4">
+ {group.actions.map((action) => (
+ <Badge
+ key={action}
+ variant="outline"
+ className="px-1.5 py-0 font-mono text-[0.65rem] font-normal"
+ >
+ {action}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ ))}
+ </Fragment>
+ );
+ })}
+ </div>
+ );
+};
+
+/** SectionHeader adds a shadow while pinned. */
+const SectionHeader = ({ label }: { label: string }) => {
+ const ref = useRef<HTMLSpanElement>(null);
+ const [stuck, setStuck] = useState(false);
+
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ let root: HTMLElement | null = el.parentElement;
+ while (root && getComputedStyle(root).overflowY === "visible")
+ root = root.parentElement;
+ const observer = new IntersectionObserver(
+ // Pinned headers clip by one pixel.
+ ([entry]) => setStuck(entry.intersectionRatio < 1),
+ { root, threshold: [1] },
+ );
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+
+ return (
+ <span
+ ref={ref}
+ className={cn(
+ "bg-modal text-muted-foreground sticky -top-px z-10 col-span-2 block px-4 pt-4 pb-2 text-[0.65rem] font-bold tracking-wider uppercase",
+ stuck && "shadow-[0_8px_8px_-4px_hsl(var(--modal))]",
+ )}
+ >
+ {label}
+ </span>
+ );
+};
+
+/** groupByEntity groups scope actions by entity and sorts each group. */
+const groupByEntity = (scopes: string[]): EntityGroup[] => {
+ const byEntity = new Map<string, string[]>();
+ for (const scope of scopes) {
+ const separator = scope.indexOf(":");
+ const entity = separator === -1 ? scope : scope.slice(0, separator);
+ const action = separator === -1 ? scope : scope.slice(separator + 1);
+ const actions = byEntity.get(entity) ?? [];
+ if (!actions.includes(action)) actions.push(action);
+ byEntity.set(entity, actions);
+ }
+ return Array.from(byEntity.entries()).map(([entity, actions]) => ({
+ entity,
+ title: entityLabels[entity] ?? entity,
+ actions: [...actions].sort(compareActions),
+ }));
+};
+
+/** compareActions puts unranked actions last, alphabetically. */
+const compareActions = (a: string, b: string): number => {
+ const rankA = actionOrder.indexOf(a);
+ const rankB = actionOrder.indexOf(b);
+ if (rankA === -1 && rankB === -1) return a.localeCompare(b);
+ if (rankA === -1) return 1;
+ if (rankB === -1) return -1;
+ return rankA - rankB;
+};
+
+export const rolePermissionCountLabel = (role: SystemRole): string =>
+ `${rolePermissionCount(role)} ${rolePermissionNoun(role)}`;
+
+export const rolePermissionNoun = (role: SystemRole): string =>
+ rolePermissionCount(role) === 1 ? "permission" : "permissions";
+
+export const rolePermissionCount = (role: SystemRole): number =>
+ systemRoleAccessRights[role].policies.reduce(
+ (total, policy) => total + policy.actions.length,
+ 0,
+ );
+
+type ResourceKind = SystemRolePolicy["resourceKind"];
+
+type EntityGroup = {
+ entity: string;
+ title: string;
+ actions: string[];
+};
diff --git a/web/src/features/rbac/components/RolePermissionPopup.tsx b/web/src/features/rbac/components/RolePermissionPopup.tsx
new file mode 100644
index 0000000000..d1fbd8f3b5
--- /dev/null
+++ b/web/src/features/rbac/components/RolePermissionPopup.tsx
@@ -0,0 +1,73 @@
+import { type SystemRole } from "@langfuse/shared/src/db";
+import { systemRoleAccessRights } from "@langfuse/shared/rbac";
+
+import { Badge } from "@/src/components/ui/badge";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import {
+ RolePermissionList,
+ rolePermissionCount,
+ rolePermissionNoun,
+} from "@/src/features/rbac/components/RolePermissionList";
+import { roleIcons } from "@/src/features/rbac/components/roleIcons";
+
+/** RolePermissionPopup must remain outside the Select content. */
+export function RolePermissionPopup({
+ open,
+ onOpenChange,
+ role,
+ emptyStateComment,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ role: SystemRole | null;
+ emptyStateComment?: string;
+}) {
+ const def = role ? systemRoleAccessRights[role] : undefined;
+ const Icon = role ? roleIcons[role] : undefined;
+ const showEmptyStateComment =
+ role !== null &&
+ emptyStateComment !== undefined &&
+ rolePermissionCount(role) === 0;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ closeOnInteractionOutside
+ className="min-h-[25.5rem] min-w-[32rem]"
+ >
+ {role && def && Icon && (
+ <>
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Icon className="icon-base shrink-0" />
+ <span>{def.name}</span>
+ <Badge
+ variant="tertiary"
+ className="ml-1 shrink-0 text-[0.7rem] tabular-nums"
+ >
+ <span className="font-bold">{rolePermissionCount(role)}</span>{" "}
+ {rolePermissionNoun(role)}
+ </Badge>
+ </DialogTitle>
+ </DialogHeader>
+ <DialogBody className={showEmptyStateComment ? undefined : "p-0"}>
+ {showEmptyStateComment ? (
+ <p className="text-muted-foreground text-sm">
+ {emptyStateComment}
+ </p>
+ ) : (
+ <RolePermissionList role={role} />
+ )}
+ </DialogBody>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/features/rbac/components/RoleSelect.tsx b/web/src/features/rbac/components/RoleSelect.tsx
new file mode 100644
index 0000000000..cbb39cc15e
--- /dev/null
+++ b/web/src/features/rbac/components/RoleSelect.tsx
@@ -0,0 +1,108 @@
+import { useState } from "react";
+import { cva, type VariantProps } from "class-variance-authority";
+import { projectNoneRoleComment, type Role } from "@langfuse/shared";
+import { type SystemRole } from "@langfuse/shared/src/db";
+import {
+ orgNoneRoleComment,
+ systemRoleAccessRights,
+} from "@langfuse/shared/rbac";
+
+import {
+ Select,
+ SelectContent,
+ SelectTrigger,
+} from "@/src/components/ui/select";
+import { RolePermissionPopup } from "@/src/features/rbac/components/RolePermissionPopup";
+import { RoleSelectItem } from "@/src/features/rbac/components/RoleSelectItem";
+import { roleIcons } from "@/src/features/rbac/components/roleIcons";
+
+const triggerVariants = cva("", {
+ variants: {
+ size: {
+ default: "",
+ compact: "w-30",
+ },
+ },
+ defaultVariants: {
+ size: "default",
+ },
+});
+
+/** RoleSelect offers permission previews for each role. */
+export function RoleSelect({
+ roles,
+ value,
+ onValueChange,
+ isProjectRole = false,
+ disabled = false,
+ triggerId,
+ size,
+}: {
+ roles: Role[];
+ value: Role;
+ onValueChange: (role: Role) => void;
+ isProjectRole?: boolean;
+ disabled?: boolean;
+ triggerId?: string;
+} & VariantProps<typeof triggerVariants>) {
+ const [open, setOpen] = useState(false);
+ const [permissionsOpen, setPermissionsOpen] = useState(false);
+ const [permissionsRole, setPermissionsRole] = useState<SystemRole | null>(
+ null,
+ );
+
+ const openPermissions = (role: SystemRole) => {
+ setOpen(false);
+ setPermissionsRole(role);
+ setPermissionsOpen(true);
+ };
+
+ const SelectedIcon = roleIcons[value];
+ const keepDefaultNote = value === "NONE" && isProjectRole;
+ const label = `${systemRoleAccessRights[value].name}${
+ keepDefaultNote ? " (keep default role)" : ""
+ }`;
+
+ return (
+ <>
+ <Select
+ open={open}
+ onOpenChange={setOpen}
+ value={value}
+ onValueChange={(role) => onValueChange(role as Role)}
+ disabled={disabled}
+ >
+ <SelectTrigger
+ id={triggerId}
+ className={triggerVariants({ size })}
+ disableValueLineClamp
+ >
+ <span className="flex min-w-0 items-center gap-2">
+ <SelectedIcon className="icon-base shrink-0" />
+ <span className="truncate" title={label}>
+ {label}
+ </span>
+ </span>
+ </SelectTrigger>
+ <SelectContent>
+ {roles.map((role) => (
+ <RoleSelectItem
+ key={role}
+ role={role}
+ isProjectRole={isProjectRole}
+ onViewPermissions={openPermissions}
+ />
+ ))}
+ </SelectContent>
+ </Select>
+ <RolePermissionPopup
+ open={permissionsOpen}
+ onOpenChange={setPermissionsOpen}
+ role={permissionsRole}
+ emptyStateComment={
+ isProjectRole ? projectNoneRoleComment : orgNoneRoleComment
+ }
+ />
+ </>
+ );
+}
diff --git a/web/src/features/rbac/components/RoleSelectItem.tsx b/web/src/features/rbac/components/RoleSelectItem.tsx
index 66689f02bd..cf75874a14 100644
--- a/web/src/features/rbac/components/RoleSelectItem.tsx
+++ b/web/src/features/rbac/components/RoleSelectItem.tsx
@@ -1,120 +1,61 @@
-/* eslint-disable no-nested-ternary */
-import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";
+import { SquareArrowOutUpRight } from "lucide-react";
+import { type SystemRole } from "@langfuse/shared/src/db";
+import { systemRoleAccessRights } from "@langfuse/shared/rbac";
+
+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";
import { SelectItem } from "@/src/components/ui/select";
-import {
- projectNoneRoleComment,
- projectRoleAccessRights,
- type Role,
-} from "@langfuse/shared";
-import {
- organizationRoleAccessRights,
- orgNoneRoleComment,
-} from "@/src/features/rbac/constants/organizationAccessRights";
-import { orderedRoles } from "@/src/features/rbac/constants/orderedRoles";
+import { roleIcons } from "@/src/features/rbac/components/roleIcons";
+/** RoleSelectItem adds a permission preview to a role option. */
export const RoleSelectItem = ({
role,
isProjectRole,
+ onViewPermissions,
}: {
- role: Role;
+ role: SystemRole;
isProjectRole?: boolean;
+ onViewPermissions: (role: SystemRole) => void;
}) => {
- const isProjectNoneRole = role === "NONE" && isProjectRole;
- const isOrgNoneRole = role === "NONE" && !isProjectRole;
- const orgScopes = reduceScopesToListItems(organizationRoleAccessRights, role);
- const projectScopes = reduceScopesToListItems(projectRoleAccessRights, role);
+ const def = systemRoleAccessRights[role];
+ const Icon = roleIcons[role];
+ const keepDefaultNote = role === "NONE" && isProjectRole;
return (
- <HoverCard
- openDelay={0}
- closeDelay={0}
- hideWhenDetached
- placement="right"
- content={
- <div className="w-64 p-3">
- {isProjectNoneRole ? (
- <div className="text-xs">{projectNoneRoleComment}</div>
- ) : isOrgNoneRole ? (
- <div className="text-xs">{orgNoneRoleComment}</div>
- ) : (
- <>
- <div className="font-bold">Role: {formatRole(role)}</div>
- <p className="mt-2 text-xs font-bold">Organization Scopes</p>
- <ul className="list-inside list-disc text-xs">{orgScopes}</ul>
- <p className="mt-2 text-xs font-bold">Project Scopes</p>
- <ul className="list-inside list-disc text-xs">{projectScopes}</ul>
- <p className="mt-2 border-t pt-2 text-xs">
- Note:{" "}
- <span className="text-muted-foreground">Muted scopes</span> are
- inherited from lower role.
- </p>
- </>
- )}
- </div>
- }
+ <SelectItem
+ value={role}
+ className="group pl-2 [&>span:not([data-checkmark])]:flex-1 [&>span[data-checkmark]]:hidden"
>
- {({ getTriggerProps }) => (
- <SelectItem value={role} className="max-w-56" {...getTriggerProps()}>
- <span>
- {formatRole(role)}
- {isProjectNoneRole ? " (keep default role)" : ""}
+ <div className="flex w-full items-start gap-2 text-left">
+ <Icon className="icon-base mt-0.5 shrink-0" />
+ <div className="flex flex-col">
+ <span className="font-bold">
+ {def.name}
+ {keepDefaultNote ? " (keep default role)" : ""}
</span>
- </SelectItem>
- )}
- </HoverCard>
- );
-};
-
-const reduceScopesToListItems = (
- accessRights: Record<string, string[]>,
- role: Role,
-) => {
- const currentRoleLevel = orderedRoles[role];
- const lowerRole = Object.entries(orderedRoles).find(
- ([_role, level]) => level === currentRoleLevel - 1,
- )?.[0] as Role | undefined;
- const inheritedScopes = lowerRole ? accessRights[lowerRole] : [];
-
- return accessRights[role].length > 0 ? (
- <>
- {Object.entries(
- accessRights[role].reduce(
- (acc, scope) => {
- const [resource, action] = scope.split(":");
- if (!acc[resource]) {
- acc[resource] = [];
- }
- acc[resource].push(action);
- return acc;
- },
- {} as Record<string, string[]>,
- ),
- ).map(([resource, actions]) => {
- const inheritedActions = actions.filter((action) =>
- inheritedScopes.includes(`${resource}:${action}`),
- );
- const newActions = actions.filter(
- (action) => !inheritedScopes.includes(`${resource}:${action}`),
- );
-
- return (
- <li key={resource}>
- <span>{resource}: </span>
- <span className="text-muted-foreground">
- {inheritedActions.length > 0 ? inheritedActions.join(", ") : ""}
- {newActions.length > 0 && inheritedActions.length > 0 ? ", " : ""}
- </span>
- <span className="font-bold">
- {newActions.length > 0 ? newActions.join(", ") : ""}
- </span>
- </li>
- );
- })}
- </>
- ) : (
- <li>None</li>
+ <span className="text-muted-foreground text-xs">
+ {def.description}
+ </span>
+ </div>
+ <Tooltip label="View permissions" hoverableContent={false} delay={0}>
+ {({ getTriggerProps }) => (
+ <button
+ type="button"
+ {...getTriggerProps()}
+ onPointerDown={(e) => e.stopPropagation()}
+ onPointerUp={(e) => e.stopPropagation()}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onViewPermissions(role);
+ }}
+ aria-label={`View ${def.name} permissions`}
+ className="text-muted-foreground hover:bg-background hover:text-foreground ml-auto flex h-6 w-6 shrink-0 items-center justify-center self-center rounded-full opacity-0 group-hover:opacity-100 group-data-highlighted:opacity-100 focus-visible:opacity-100"
+ >
+ <SquareArrowOutUpRight className="icon-base" />
+ </button>
+ )}
+ </Tooltip>
+ </div>
+ </SelectItem>
);
};
-
-const formatRole = (role: Role) =>
- role.charAt(0).toUpperCase() + role.slice(1).toLowerCase();
diff --git a/web/src/features/rbac/components/roleIcons.ts b/web/src/features/rbac/components/roleIcons.ts
new file mode 100644
index 0000000000..c5fb2b69d1
--- /dev/null
+++ b/web/src/features/rbac/components/roleIcons.ts
@@ -0,0 +1,28 @@
+import {
+ Ban,
+ Building2,
+ Eye,
+ FolderGit2,
+ Network,
+ Radio,
+ ShieldCheck,
+ Star,
+ User,
+ type LucideIcon,
+} from "lucide-react";
+
+import { type SystemRole } from "@langfuse/shared/src/db";
+
+/** roleIcons maps every system role to a lucide icon for role pickers and permission popups. */
+export const roleIcons: Record<SystemRole, LucideIcon> = {
+ OWNER: ShieldCheck,
+ ADMIN: ShieldCheck,
+ MEMBER: User,
+ VIEWER: Eye,
+ NONE: Ban,
+ LEGACY_PROJECT_API_KEY: FolderGit2,
+ LEGACY_ORGANIZATION_API_KEY: Building2,
+ SCORES_INGEST: Star,
+ INGEST: Radio,
+ AI_GATEWAY: Network,
+};
diff --git a/web/src/features/rbac/constants/apiKeyAccessRights.ts b/web/src/features/rbac/constants/apiKeyAccessRights.ts
deleted file mode 100644
index 2432c9b047..0000000000
--- a/web/src/features/rbac/constants/apiKeyAccessRights.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import {
- allOrganizationActions,
- allProjectActions,
- type ProjectAction,
- type SystemPolicy,
-} from "@/src/features/auth/policy/types";
-
-/** ApiKeyRole is the policy layer's role vocabulary for an API key, decoupled from the DB `ApiKeyScope` enum. */
-export type ApiKeyRole = "PROJECT" | "ORGANIZATION" | "SCORES_INGEST" | "ADMIN";
-
-/** orgKeyProjectActions are the project-kind actions an ORGANIZATION key holds against its own projects. */
-const orgKeyProjectActions: ProjectAction[] = [
- "project:read",
- "apiKeys:read",
- "apiKeys:CUD",
- "projectMembers:read",
- "projectMembers:CUD",
- "project:update",
- "project:delete",
-];
-
-/** projectKeyActions is the project vocabulary a PROJECT key holds, less the project-administration actions reserved for ORGANIZATION keys and the session user. */
-const projectKeyActions: ProjectAction[] = allProjectActions.filter(
- (action) =>
- action === "project:read" || !orgKeyProjectActions.includes(action),
-);
-
-/** apiKeyAccessRights maps each `ApiKeyRole` to its resource-less grants; the resolver binds each to the key's project/org, or the wildcard for ADMIN. */
-export const apiKeyAccessRights: Record<ApiKeyRole, SystemPolicy[]> = {
- PROJECT: [
- {
- kind: "project",
- source: { kind: "role", id: "PROJECT" },
- effect: "allow",
- actions: projectKeyActions,
- },
- ],
- ORGANIZATION: [
- {
- kind: "organization",
- source: { kind: "role", id: "ORGANIZATION" },
- effect: "allow",
- actions: allOrganizationActions,
- },
- {
- kind: "project",
- source: { kind: "role", id: "ORGANIZATION" },
- effect: "allow",
- actions: orgKeyProjectActions,
- },
- ],
- SCORES_INGEST: [
- {
- kind: "project",
- source: { kind: "role", id: "SCORES_INGEST" },
- effect: "allow",
- actions: ["scores:create"],
- },
- ],
- ADMIN: [
- {
- kind: "project",
- source: { kind: "role", id: "ADMIN" },
- effect: "allow",
- actions: allProjectActions,
- },
- {
- kind: "organization",
- source: { kind: "role", id: "ADMIN" },
- effect: "allow",
- actions: allOrganizationActions,
- },
- ],
-};
diff --git a/web/src/features/rbac/getRolesForPrincipal.ts b/web/src/features/rbac/getRolesForPrincipal.ts
new file mode 100644
index 0000000000..f68656ff4a
--- /dev/null
+++ b/web/src/features/rbac/getRolesForPrincipal.ts
@@ -0,0 +1,84 @@
+import { InternalServerError } from "@langfuse/shared";
+import {
+ hasOrganizationKind,
+ hasProjectKind,
+ OrganizationId,
+ ProjectId,
+ SystemRoleId,
+ systemRoleAccessRights,
+ type OwnerId,
+ type PrincipalId,
+ type ResourceId,
+ type RoleId,
+ type SystemRolePolicy,
+ 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 Policy, type Role } from "./types";
+
+/** getRolesForPrincipal loads a principal's roles with policies bound to each assignment. */
+export async function getRolesForPrincipal(
+ principalId: PrincipalId,
+ prisma: PrismaClient = defaultPrisma,
+): Promise<Role[]> {
+ const assignments = await getRoleAssignmentsForPrincipal(prisma, principalId);
+ return assignments.map(toRole);
+}
+
+/** toRole binds a stored assignment's system role to its tenant and owner. */
+function toRole(assignment: RoleAssignment): Role {
+ const definition = systemRoleAccessRights[assignment.systemRole];
+ const roleId = SystemRoleId(assignment.systemRole);
+ const tenantId = OrganizationId(assignment.orgId);
+ const ownerId = toOwnerId(assignment);
+ const resources = hasProjectKind(ownerId)
+ ? [ownerId]
+ : [ownerId, ProjectId("*")];
+ return {
+ id: roleId,
+ tenantId,
+ name: definition.name,
+ description: definition.description,
+ policies: definition.policies
+ .map((policy) => toPolicy(policy, roleId, tenantId, resources))
+ .filter((policy): policy is Policy => policy !== null),
+ tags: definition.tags,
+ };
+}
+
+/** 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");
+}
+
+/** toPolicy binds a catalog policy to resources of its kind. */
+function toPolicy(
+ definition: SystemRolePolicy,
+ roleId: RoleId,
+ tenantId: TenantId,
+ resources: ResourceId[],
+): Policy | null {
+ const ofKind = resources.filter(
+ definition.resourceKind === "organization"
+ ? hasOrganizationKind
+ : hasProjectKind,
+ );
+ if (ofKind.length === 0) return null;
+ return {
+ id: `${roleId}:${definition.resourceKind}`,
+ roleId,
+ tenantId,
+ effect: definition.effect,
+ actions: definition.actions,
+ resources: ofKind,
+ };
+}
diff --git a/web/src/features/rbac/index.ts b/web/src/features/rbac/index.ts
index 7534deda1f..610e9fc7fd 100644
--- a/web/src/features/rbac/index.ts
+++ b/web/src/features/rbac/index.ts
@@ -13,13 +13,8 @@
// putting those tables on the barrel pulled CreateProjectMemberDialog
// (react-hook-form) into instrumentation and API routes.
//
-// auth/policy/types.ts keeps importing organizationAccessRights by file
-// path: it needs the runtime `organizationScopes` value, and routing
-// that module through this door would pull the React access hooks into
-// the policy types graph. auth/policy/contextResolver.ts keeps importing
-// apiKeyAccessRights by file path for the same reason, and because that
-// file already imports auth/policy/types — putting it on this door would
-// close a cycle if types ever moved onto the door too.
+// The role catalog (definitions, policies, tags, and access-right tables)
+// lives in `@langfuse/shared/rbac`; only policy resolution stays here.
export {
hasProjectAccess,
throwIfNoProjectAccess,
@@ -35,4 +30,4 @@ export {
export {
organizationRoleAccessRights,
type OrganizationScope,
-} from "@/src/features/rbac/constants/organizationAccessRights";
+} from "@langfuse/shared/rbac";
diff --git a/web/src/features/rbac/types.ts b/web/src/features/rbac/types.ts
new file mode 100644
index 0000000000..7c5a9d2b8f
--- /dev/null
+++ b/web/src/features/rbac/types.ts
@@ -0,0 +1,27 @@
+import {
+ type Action,
+ type Effect,
+ type ResourceId,
+ type RoleId,
+ type TenantId,
+} from "@langfuse/shared/rbac";
+
+/** Policy is a role's effect on a set of actions over tagged resources within one tenant. */
+export type Policy = {
+ id: string;
+ tenantId: TenantId;
+ roleId: RoleId;
+ effect: Effect;
+ actions: Action[];
+ resources: ResourceId[];
+};
+
+/** Role is a named, tenant-scoped bundle of policies. */
+export type Role = {
+ id: RoleId;
+ tenantId: TenantId;
+ name: string;
+ description: string;
+ policies: Policy[];
+ tags: string[];
+};
diff --git a/web/src/features/rbac/utils/checkOrganizationAccess.ts b/web/src/features/rbac/utils/checkOrganizationAccess.ts
index 7f25e29a3e..317752a3d9 100644
--- a/web/src/features/rbac/utils/checkOrganizationAccess.ts
+++ b/web/src/features/rbac/utils/checkOrganizationAccess.ts
@@ -1,7 +1,7 @@
import {
organizationRoleAccessRights,
type OrganizationScope,
-} from "@/src/features/rbac/constants/organizationAccessRights";
+} from "@langfuse/shared/rbac";
import { type Role } from "@langfuse/shared/src/db";
import { TRPCError } from "@trpc/server";
import { type Session } from "next-auth";
diff --git a/web/src/features/scores/components/AnnotateDrawerController.tsx b/web/src/features/scores/components/AnnotateDrawerController.tsx
index 4b28c89bfd..ae87e42aba 100644
--- a/web/src/features/scores/components/AnnotateDrawerController.tsx
+++ b/web/src/features/scores/components/AnnotateDrawerController.tsx
@@ -52,7 +52,7 @@ export function AnnotateDrawerController<Target extends ScoreTarget>({
const triggerRef = useRef<HTMLElement | null>(null);
const hasAccess = useHasProjectAccess({
projectId,
- scope: "scores:CUD",
+ scope: "scores:save",
});
const disabled = !hasAccess;
diff --git a/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.tsx b/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.tsx
index fbabb6109b..0a65dad123 100644
--- a/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.tsx
+++ b/web/src/features/traces/components/IOPreview/components/CorrectedOutputField.tsx
@@ -43,7 +43,7 @@ export function CorrectedOutputField({
environment = "default",
compact = false,
}: CorrectedOutputFieldProps) {
- const hasAccess = useHasProjectAccess({ projectId, scope: "scores:CUD" });
+ const hasAccess = useHasProjectAccess({ projectId, scope: "scores:save" });
const capture = usePostHogClientCapture();
// JSON validation toggle (persisted in localStorage)
diff --git a/web/src/features/traces/components/Trace.tsx b/web/src/features/traces/components/Trace.tsx
index 747873025b..c638363e1f 100644
--- a/web/src/features/traces/components/Trace.tsx
+++ b/web/src/features/traces/components/Trace.tsx
@@ -278,7 +278,7 @@ function DesktopTraceReviewWorkspace({
projectId: string;
}) {
const { query } = useRouter();
- const canAnnotate = useHasProjectAccess({ projectId, scope: "scores:CUD" });
+ const canAnnotate = useHasProjectAccess({ projectId, scope: "scores:save" });
const reviewOpen =
(query.annotation === "open" && canAnnotate) || query.comments === "open";
return (
diff --git a/web/src/features/traces/components/TraceReviewPanel.tsx b/web/src/features/traces/components/TraceReviewPanel.tsx
index c658cb86ab..d9e79815e4 100644
--- a/web/src/features/traces/components/TraceReviewPanel.tsx
+++ b/web/src/features/traces/components/TraceReviewPanel.tsx
@@ -191,7 +191,7 @@ export function TraceReviewPanel({ projectId }: { projectId: string }) {
const commentsKey = useStore(store, (state) => state.comments?.key);
const hasAnnotation = useStore(store, (state) => state.annotation !== null);
const { query } = useRouter();
- const canAnnotate = useHasProjectAccess({ projectId, scope: "scores:CUD" });
+ const canAnnotate = useHasProjectAccess({ projectId, scope: "scores:save" });
const annotationOpen = query.annotation === "open" && canAnnotate;
return (
<ReviewPanel
@@ -214,7 +214,7 @@ export function SessionReviewPanel({ projectId }: { projectId: string }) {
const active = useStore(store, (state) => state.active);
const comments = useStore(store, (state) => state.comments);
const annotation = useStore(store, (state) => state.annotation);
- const canAnnotate = useHasProjectAccess({ projectId, scope: "scores:CUD" });
+ const canAnnotate = useHasProjectAccess({ projectId, scope: "scores:save" });
return (
<ReviewPanel active={active}>
{comments && (
diff --git a/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx b/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
index 4529c3c58f..7eb19e6622 100644
--- a/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
+++ b/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
@@ -1436,7 +1436,7 @@ describe("V4MigrationHeaderContent", () => {
fireEvent.click(createButton);
expect(mocks.createProjectApiKey).toHaveBeenCalledWith({
projectId: "project-1",
- note: "v4-migration-key",
+ name: "v4-migration-key",
});
await waitFor(() =>
@@ -1502,7 +1502,7 @@ describe("V4MigrationHeaderContent", () => {
);
expect(mocks.createProjectApiKey).toHaveBeenLastCalledWith({
projectId: "project-2",
- note: "v4-migration-key",
+ name: "v4-migration-key",
});
});
});
diff --git a/web/src/features/v4-migration/V4MigrationContent.tsx b/web/src/features/v4-migration/V4MigrationContent.tsx
index 6409ee09c9..bc01824ba6 100644
--- a/web/src/features/v4-migration/V4MigrationContent.tsx
+++ b/web/src/features/v4-migration/V4MigrationContent.tsx
@@ -1377,7 +1377,7 @@ export function V4MigrationAgentUpgradeSection({
mutCreateProjectApiKey
.mutateAsync({
projectId,
- note: "v4-migration-key",
+ name: "v4-migration-key",
})
.then(({ secretKey, publicKey }) => {
setGeneratedKeys({
diff --git a/web/src/initialize.ts b/web/src/initialize.ts
index dbd27c8857..c0a856e370 100644
--- a/web/src/initialize.ts
+++ b/web/src/initialize.ts
@@ -1,10 +1,11 @@
import { env } from "@/src/env.mjs";
import { createUserEmailPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";
import { prisma } from "@langfuse/shared/src/db";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server";
import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";
import { CloudConfigSchema } from "@langfuse/shared";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import {
initializeClickhouseCompatibility,
logger,
@@ -111,46 +112,10 @@ if (env.LANGFUSE_INIT_ORG_ID) {
retentionDays,
},
});
-
- // Add API Keys: Project -> API Key
- if (
- env.LANGFUSE_INIT_PROJECT_SECRET_KEY &&
- env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY
- ) {
- const existingApiKey = await prisma.apiKey.findUnique({
- where: { publicKey: env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY },
- });
-
- // Delete key if project changed
- if (
- existingApiKey &&
- existingApiKey.projectId !== env.LANGFUSE_INIT_PROJECT_ID
- ) {
- await prisma.apiKey.delete({
- where: { publicKey: env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY },
- });
- }
-
- // Create new key if it doesn't exist or project changed
- if (
- !existingApiKey ||
- existingApiKey.projectId !== env.LANGFUSE_INIT_PROJECT_ID
- ) {
- await createAndAddApiKeysToDb({
- prisma,
- entityId: env.LANGFUSE_INIT_PROJECT_ID,
- note: "Provisioned API Key",
- scope: "PROJECT",
- predefinedKeys: {
- secretKey: env.LANGFUSE_INIT_PROJECT_SECRET_KEY,
- publicKey: env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY,
- },
- });
- }
- }
}
// Create User: Org -> User
+ let initUserId: string | undefined;
if (env.LANGFUSE_INIT_USER_EMAIL && env.LANGFUSE_INIT_USER_PASSWORD) {
const email = env.LANGFUSE_INIT_USER_EMAIL.toLowerCase();
const existingUser = await prisma.user.findUnique({
@@ -168,6 +133,8 @@ if (env.LANGFUSE_INIT_ORG_ID) {
);
}
+ initUserId = userId;
+
// Create OrgMembership: Org -> OrgMembership <- User
const orgMembership = await prisma.organizationMembership.upsert({
where: {
@@ -209,4 +176,43 @@ if (env.LANGFUSE_INIT_ORG_ID) {
});
}
}
+
+ // Add API Keys: Project -> API Key. Minted after the user so the provisioned
+ // key is attributed to the init user when one is configured.
+ if (
+ env.LANGFUSE_INIT_PROJECT_ID &&
+ env.LANGFUSE_INIT_PROJECT_SECRET_KEY &&
+ env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY
+ ) {
+ const existingApiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY },
+ });
+
+ // Delete key if project changed
+ if (
+ existingApiKey &&
+ existingApiKey.projectId !== env.LANGFUSE_INIT_PROJECT_ID
+ ) {
+ await prisma.apiKey.delete({
+ where: { publicKey: env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY },
+ });
+ }
+
+ // Create new key if it doesn't exist or project changed
+ if (
+ !existingApiKey ||
+ existingApiKey.projectId !== env.LANGFUSE_INIT_PROJECT_ID
+ ) {
+ await createApiKey(prisma, {
+ owner: ProjectId(env.LANGFUSE_INIT_PROJECT_ID),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: initUserId ? UserId(initUserId) : "system",
+ name: "Provisioned API Key",
+ predefinedKeys: {
+ secretKey: env.LANGFUSE_INIT_PROJECT_SECRET_KEY,
+ publicKey: env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY,
+ },
+ });
+ }
+ }
}
diff --git a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts
index d0eeca7e63..65c0b3af39 100644
--- a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts
+++ b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts
@@ -1,5 +1,6 @@
import { type NextApiRequest, type NextApiResponse } from "next";
import { logger } from "@langfuse/shared/src/server";
+import { isBaseError } from "@langfuse/shared";
import { AdminApiAuthService } from "@/src/ee/features/admin-api/server";
import {
validateQueryAndExtractId,
@@ -61,6 +62,9 @@ export default async function handler(
return;
}
} catch (e) {
+ if (isBaseError(e) && e.isUserError()) {
+ return res.status(e.httpCode).json({ error: e.message });
+ }
logger.error("Failed to process organization API key request", e);
res.status(500).json({ error: "Internal server error" });
}
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index d582fe7bca..95355ed329 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -40,9 +40,10 @@ import {
shadowAuthorize,
__dangerouslySkipAuthz,
} from "@/src/features/public-api/server";
+import { type ProjectAction } from "@langfuse/shared/rbac";
import {
+ unauthorizedError,
type AuthorizationContext,
- type ProjectAction,
} from "@/src/features/auth/policy/types";
export const config = {
@@ -350,7 +351,7 @@ export function filterBatchForEventsOnly(
return { batchForProcessing, rejectedErrors };
}
-/** authorizeIngestionBatch authorizes each event against the resolved context, dropping enforce-mode denials as 207 rejections; legacy and shadow keep every event. */
+/** authorizeIngestionBatch filters out unauthorized events from the batch */
function authorizeIngestionBatch(
batch: unknown[],
ctx: AuthorizationContext | undefined,
@@ -359,13 +360,12 @@ function authorizeIngestionBatch(
): IngestionBatchFilter {
const batchForProcessing: unknown[] = [];
const rejectedErrors: IngestionEventRejection[] = [];
-
for (const event of batch) {
const decision = shadowAuthorize({
ctx,
action: ingestionActionForEventType(eventTypeOf(event)),
resource: { projectId },
- accessLevel,
+ legacyDecision: ingestionLegacyDecision(eventTypeOf(event), accessLevel),
});
if (!decision.success) {
rejectedErrors.push({
@@ -381,12 +381,26 @@ function authorizeIngestionBatch(
return { batchForProcessing, rejectedErrors };
}
+function ingestionLegacyDecision(
+ eventType: string | null,
+ accessLevel: ApiAccessLevel,
+) {
+ if (
+ eventType === eventTypes.SDK_LOG ||
+ accessLevel === "project" ||
+ (eventType === eventTypes.SCORE_CREATE && accessLevel === "scores")
+ ) {
+ return { success: true as const, scope: { accessLevel } };
+ }
+ return unauthorizedError("Access Scope Denied");
+}
+
/** ingestionActionForEventType maps an event type to the project action its write asserts; SDK logs skip authz. */
function ingestionActionForEventType(
type: string | null,
): ProjectAction | typeof __dangerouslySkipAuthz {
if (type === eventTypes.SDK_LOG) return __dangerouslySkipAuthz;
- if (type === eventTypes.SCORE_CREATE) return "scores:create";
+ if (type === eventTypes.SCORE_CREATE) return "scores:save";
return "traces:create";
}
diff --git a/web/src/pages/api/public/organizations/apiKeys/index.ts b/web/src/pages/api/public/organizations/apiKeys/index.ts
index 7993f4cd0d..7fbff00a0f 100644
--- a/web/src/pages/api/public/organizations/apiKeys/index.ts
+++ b/web/src/pages/api/public/organizations/apiKeys/index.ts
@@ -52,7 +52,7 @@ export default async function handler(
// Route to the handler
try {
- return handleGetApiKeys(req, res, authCheck.scope.orgId);
+ return await handleGetApiKeys(req, res, authCheck.scope.orgId);
} catch (error) {
logger.error(
`Error handling organization API keys for ${req.method}`,
diff --git a/web/src/pages/api/public/organizations/memberships/index.ts b/web/src/pages/api/public/organizations/memberships/index.ts
index cd28b0b4de..2aaa833181 100644
--- a/web/src/pages/api/public/organizations/memberships/index.ts
+++ b/web/src/pages/api/public/organizations/memberships/index.ts
@@ -1,14 +1,19 @@
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { logger } from "@langfuse/shared/src/server";
-import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
+import { type NextApiRequest, type NextApiResponse } from "next";
+
import {
+ handleDeleteMembership,
handleGetMemberships,
handleUpdateMembership,
- handleDeleteMembership,
} from "@/src/ee/features/admin-api/server/memberships";
-import { shadowAuth, writeOrgError } from "@/src/features/public-api/server";
-import { type NextApiRequest, type NextApiResponse } from "next";
+import { authenticator } from "@/src/features/apiKey/server";
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server";
+import { shadowAuth, writeOrgError } from "@/src/features/public-api/server";
+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { BaseError } from "@langfuse/shared";
+import { logger } from "@langfuse/shared/src/server";
+
+/** handler serves organization memberships for authenticated API keys. */
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
@@ -59,13 +64,35 @@ export default async function handler(
// Route to the appropriate handler based on HTTP method
try {
+ if (req.method === "GET") {
+ return await handleGetMemberships(req, res, authCheck.scope.orgId);
+ }
+ let context = authCheck.ctx;
+ if (!context) {
+ const authentication = await authenticator.authenticate({
+ headers: req.headers,
+ });
+ if (!authentication.success)
+ return writeOrgError(res, authentication.error);
+ context = authentication.context;
+ }
switch (req.method) {
- case "GET":
- return handleGetMemberships(req, res, authCheck.scope.orgId);
case "PUT":
- return handleUpdateMembership(req, res, authCheck.scope.orgId);
+ return await handleUpdateMembership(
+ req,
+ res,
+ authCheck.scope.orgId,
+ authCheck.scope.apiKeyId,
+ context,
+ );
case "DELETE":
- return handleDeleteMembership(req, res, authCheck.scope.orgId);
+ return await handleDeleteMembership(
+ req,
+ res,
+ authCheck.scope.orgId,
+ authCheck.scope.apiKeyId,
+ context,
+ );
default:
// This should never happen due to the check at the beginning
return res.status(405).json({
@@ -73,6 +100,9 @@ export default async function handler(
});
}
} catch (error) {
+ if (error instanceof BaseError) {
+ return res.status(error.httpCode).json({ error: error.message });
+ }
logger.error(
`Error handling organization memberships for ${req.method}`,
error,
diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts
index 6a205abc56..b12f7cd212 100644
--- a/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts
+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts
@@ -13,6 +13,7 @@ import {
writeProjectError,
} from "@/src/features/public-api/server";
+/** handler deletes project keys for authorized organization credentials. */
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
@@ -61,7 +62,6 @@ export default async function handler(
return rateLimitCheck.sendRestResponseIfLimited(res);
}
- // Check if project exists and belongs to the organization
const project = await prisma.project.findFirst({
where: {
id: projectId,
@@ -75,7 +75,6 @@ export default async function handler(
.json({ message: "Project not found or you don't have access to it" });
}
- // Handle different HTTP methods
switch (req.method) {
case "DELETE":
return await handleDeleteApiKey(
@@ -84,6 +83,7 @@ export default async function handler(
projectId,
apiKeyId,
authCheck.scope.orgId,
+ authCheck.scope.apiKeyId,
);
default:
res.status(405).json({ message: "Method Not Allowed" });
diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts
index 5c3447fa87..cd08e14cd4 100644
--- a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts
+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts
@@ -1,5 +1,6 @@
import { type NextApiRequest, type NextApiResponse } from "next";
import { prisma } from "@langfuse/shared/src/db";
+import { isBaseError } from "@langfuse/shared";
import { logger } from "@langfuse/shared/src/server";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
@@ -91,6 +92,9 @@ export default async function handler(
return;
}
} catch (e) {
+ if (isBaseError(e) && e.isUserError()) {
+ return res.status(e.httpCode).json({ message: e.message });
+ }
logger.error("Failed to process project API key request", e);
res.status(500).json({ message: "Internal server error" });
}
diff --git a/web/src/pages/api/public/projects/[projectId]/memberships/index.ts b/web/src/pages/api/public/projects/[projectId]/memberships/index.ts
index e0a83f4dd4..02c88a3e64 100644
--- a/web/src/pages/api/public/projects/[projectId]/memberships/index.ts
+++ b/web/src/pages/api/public/projects/[projectId]/memberships/index.ts
@@ -1,15 +1,20 @@
-import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { prisma } from "@langfuse/shared/src/db";
-import { logger } from "@langfuse/shared/src/server";
-import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server";
+import { type NextApiRequest, type NextApiResponse } from "next";
+
import {
+ handleDeleteMembership,
handleGetMemberships,
handleUpdateMembership,
- handleDeleteMembership,
} from "@/src/ee/features/admin-api/server/projects/projectById/memberships";
-
-import { type NextApiRequest, type NextApiResponse } from "next";
+import { authenticator } from "@/src/features/apiKey/server";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server";
import { shadowAuth, writeOrgError } from "@/src/features/public-api/server";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { BaseError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { logger } from "@langfuse/shared/src/server";
+
+/** handler serves project memberships for authenticated API keys. */
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
@@ -84,22 +89,39 @@ export default async function handler(
// Route to the appropriate handler based on HTTP method
try {
+ if (req.method === "GET") {
+ return await handleGetMemberships(
+ req,
+ res,
+ projectId,
+ authCheck.scope.orgId,
+ );
+ }
+ const authentication = await authenticateMembershipMutation(
+ req,
+ authCheck.ctx,
+ );
+ if (!authentication.success)
+ return writeOrgError(res, authentication.error);
+ const context = authentication.context;
switch (req.method) {
- case "GET":
- return handleGetMemberships(req, res, projectId, authCheck.scope.orgId);
case "PUT":
- return handleUpdateMembership(
+ return await handleUpdateMembership(
req,
res,
projectId,
authCheck.scope.orgId,
+ authCheck.scope.apiKeyId,
+ context,
);
case "DELETE":
- return handleDeleteMembership(
+ return await handleDeleteMembership(
req,
res,
projectId,
authCheck.scope.orgId,
+ authCheck.scope.apiKeyId,
+ context,
);
default:
// This should never happen due to the check at the beginning
@@ -108,6 +130,9 @@ export default async function handler(
});
}
} catch (error) {
+ if (error instanceof BaseError) {
+ return res.status(error.httpCode).json({ error: error.message });
+ }
logger.error(
`Error handling project memberships for ${req.method} on project ${projectId}`,
error,
@@ -117,3 +142,12 @@ export default async function handler(
});
}
}
+
+/** authenticateMembershipMutation reuses the route context when available. */
+async function authenticateMembershipMutation(
+ req: NextApiRequest,
+ context: AuthorizationContext | undefined,
+) {
+ if (context) return { success: true as const, context };
+ return authenticator.authenticate({ headers: req.headers });
+}
diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].ts
index 87ae7c8047..24d8044afa 100644
--- a/web/src/pages/api/public/scores/[scoreId].ts
+++ b/web/src/pages/api/public/scores/[scoreId].ts
@@ -44,7 +44,7 @@ export default withMiddlewares({
}),
DELETE: createAuthedProjectAPIRoute({
name: "Delete Score",
- action: "scores:CUD",
+ action: "scores:delete",
querySchema: DeleteScoreQueryV1,
responseSchema: DeleteScoreResponseV1,
rateLimitResource: "score-delete",
diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.ts
index fb69bda361..7136c9f958 100644
--- a/web/src/pages/api/public/scores/index.ts
+++ b/web/src/pages/api/public/scores/index.ts
@@ -19,7 +19,7 @@ import { clampToDataAccessDays } from "@/src/features/entitlements/server";
export default withMiddlewares({
POST: createAuthedProjectAPIRoute({
name: "Create Score",
- action: "scores:create",
+ action: "scores:save",
bodySchema: PostScoresBodyV1,
responseSchema: PostScoresResponseV1,
allowedAccessLevels: ["project", "scores"],
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index 58ce47f2c8..b436571e10 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -577,7 +577,7 @@ export const scoresRouter = createTRPCRouter({
throwIfNoProjectAccess({
session: ctx.session,
projectId: input.projectId,
- scope: "scores:CUD",
+ scope: "scores:save",
});
const inflatedParams = isTraceScore(input.scoreTarget)
@@ -708,7 +708,7 @@ export const scoresRouter = createTRPCRouter({
throwIfNoProjectAccess({
session: ctx.session,
projectId: input.projectId,
- scope: "scores:CUD",
+ scope: "scores:save",
});
let updatedScore: ScoreDomain | null | undefined = null;
@@ -970,7 +970,7 @@ export const scoresRouter = createTRPCRouter({
throwIfNoProjectAccess({
session: ctx.session,
projectId: input.projectId,
- scope: "scores:CUD",
+ scope: "scores:delete",
});
// Corrections can be ingested via the API and are still deletable in the UI
@@ -1021,7 +1021,7 @@ export const scoresRouter = createTRPCRouter({
throwIfNoProjectAccess({
session: ctx.session,
projectId: input.projectId,
- scope: "scores:CUD",
+ scope: "scores:save",
});
// eslint-disable-next-line @typescript-eslint/no-deprecated
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 3509a0a195..e0a39b9b78 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -867,6 +867,7 @@ export async function getAuthOptions(signupAttribution?: {
// If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)
selfHostedInstancePlan: getSelfHostedInstancePlanServerSide(),
v4WriteMode,
+ apiKeyRoleSelectionEnabled: env.API_AUTH_MIGRATION === "enforce",
},
user:
dbUser !== null
diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.ts
index 604529573e..15f1588d45 100644
--- a/web/types/next-auth.d.ts
+++ b/web/types/next-auth.d.ts
@@ -78,6 +78,9 @@ declare module "next-auth" {
// Optional so existing session mocks need not set it; the real session
// callback always populates it.
v4WriteMode?: "legacy" | "dual" | "events_only";
+ // Whether API key creation offers per-key role selection (API_AUTH_MIGRATION=enforce).
+ // Optional so existing session mocks need not set it.
+ apiKeyRoleSelectionEnabled?: boolean;
};
}
diff --git a/worker/src/__tests__/dataRetentionProcessing.test.ts b/worker/src/__tests__/dataRetentionProcessing.test.ts
index a0961b26b3..67c6e8e626 100644
--- a/worker/src/__tests__/dataRetentionProcessing.test.ts
+++ b/worker/src/__tests__/dataRetentionProcessing.test.ts
@@ -30,7 +30,8 @@ import { env as sharedEnv } from "@langfuse/shared/src/env";
import { isEnterpriseLicenseAvailable } from "@langfuse/shared/src/server/ee/licenseCheck";
import { handleDataRetentionProcessingJob } from "../ee/dataRetention/handleDataRetentionProcessingJob";
import { Job } from "bullmq";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import { InAppAgentRunStatus } from "@langfuse/shared/in-app-agent";
type LicenseCheckModule =
@@ -119,10 +120,16 @@ describe("DataRetentionProcessingJob", () => {
});
try {
- const key = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
+ const creator = await prisma.user.create({
+ data: {
+ email: `retention-${randomUUID()}@langfuse.com`,
+ name: "retention-user",
+ },
+ });
+ const key = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(creator.id),
isInAppAgentKey: true,
});
keyIds.push(key.id);
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
index 141785ea19..f6d143a964 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts
@@ -5,7 +5,9 @@ import { createOrgProjectAndApiKey, logger } from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { env as sharedEnv } from "@langfuse/shared/src/env";
import { IN_APP_AGENT_TOOL_APPROVAL_EVENT_NAME } from "@langfuse/shared/in-app-agent";
-import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";
+import { IN_APP_AGENT_RUN_MAX_DURATION_MS } from "@langfuse/shared/in-app-agent/server/tunables";
+import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import { ResumeForwardedPropsSchema } from "./runtime/types";
import { env } from "../../env";
@@ -454,8 +456,11 @@ describe("executeInAppAgentRun", () => {
const { projectId, conversation, run } = await seedBackgroundRun();
let keysDuringRun = -1;
+ let keyExpiresAt: Date | null | undefined;
scenarioRef.current = async ({ options }) => {
- keysDuringRun = (await getInAppAgentApiKeys(projectId)).length;
+ const keys = await getInAppAgentApiKeys(projectId);
+ keysDuringRun = keys.length;
+ keyExpiresAt = keys[0]?.expiresAt;
await options.onEvent({
type: "RUN_STARTED",
threadId: conversation.id,
@@ -477,6 +482,11 @@ describe("executeInAppAgentRun", () => {
expect(finished.errorCode).toBeNull();
// Key was minted and linked during the run, deleted and unlinked after.
expect(keysDuringRun).toBe(1);
+ expect(keyExpiresAt).toEqual(
+ new Date(
+ finished.claimedAt!.getTime() + IN_APP_AGENT_RUN_MAX_DURATION_MS,
+ ),
+ );
expect(await getInAppAgentApiKeys(projectId)).toHaveLength(0);
expect(finished.mcpApiKeyId).toBeNull();
@@ -878,13 +888,12 @@ describe("executeInAppAgentRun", () => {
status: "RUNNING",
});
const twoMinutesAgo = new Date(Date.now() - 2 * 60_000);
- const key = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "stale-run mcp key",
+ const key = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ name: "stale-run mcp key",
isInAppAgentKey: true,
- createdByUserId: user.id,
});
await prisma.inAppAgentRun.update({
where: { id_projectId: { id: run.id, projectId } },
@@ -918,13 +927,12 @@ describe("executeInAppAgentRun", () => {
status: "RUNNING",
});
const twoMinutesAgo = new Date(Date.now() - 2 * 60_000);
- const key = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "already-deleted mcp key",
+ const key = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ name: "already-deleted mcp key",
isInAppAgentKey: true,
- createdByUserId: user.id,
});
await prisma.inAppAgentRun.update({
where: { id_projectId: { id: run.id, projectId } },
@@ -969,13 +977,12 @@ describe("executeInAppAgentRun", () => {
status: "RUNNING",
});
const twoMinutesAgo = new Date(Date.now() - 2 * 60_000);
- const userKey = await createAndAddApiKeysToDb({
- prisma,
- entityId: projectId,
- scope: "PROJECT",
- note: "user project key",
+ const userKey = await createApiKey(prisma, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(user.id),
+ name: "user project key",
isInAppAgentKey: false,
- createdByUserId: user.id,
});
await prisma.inAppAgentRun.update({
where: { id_projectId: { id: run.id, projectId } },
diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
index c61537f0f6..e2b64fd3ae 100644
--- a/worker/src/features/in-app-agent/executeInAppAgentRun.ts
+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts
@@ -9,9 +9,10 @@ import {
traceException,
} from "@langfuse/shared/src/server";
import {
- createAndAddApiKeysToDb,
+ createApiKey,
deleteInAppAgentMcpApiKeyFromDb,
} from "@langfuse/shared/src/server/auth/apiKeys";
+import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";
import {
InAppAgentRunErrorCode,
InAppAgentRunRequestSchema,
@@ -53,7 +54,10 @@ import {
getInAppAgentRegistryToolName,
type InAppAgentUserAccess,
} from "@langfuse/shared/in-app-agent/server/mcpPolicy";
-import { IN_APP_AGENT_HEARTBEAT_INTERVAL_MS } from "@langfuse/shared/in-app-agent/server/tunables";
+import {
+ IN_APP_AGENT_HEARTBEAT_INTERVAL_MS,
+ IN_APP_AGENT_RUN_MAX_DURATION_MS,
+} from "@langfuse/shared/in-app-agent/server/tunables";
import {
createInAppAgentSandboxProvider,
getDefaultInAppAgentSandboxProviderType,
@@ -66,7 +70,7 @@ import type { AgUiRunAgentInput } from "./runtime/types";
import { env } from "../../env";
-const IN_APP_AGENT_API_KEY_NOTE = "In-app agent MCP session";
+const inAppAgentApiKeyName = "In-app agent MCP session";
type AbortReason = "cancelled" | "fenced" | "worker_shutdown";
@@ -247,9 +251,10 @@ export async function executeInAppAgentRun(params: {
// implicitly mean "trusted system".
throw new InAppAgentRunInitError("Run has no triggering user");
}
+ const triggeredByUserId = run.triggeredByUserId;
const access = await resolveUserProjectAccess({
- userId: run.triggeredByUserId,
+ userId: triggeredByUserId,
projectId,
orgId: project.orgId,
});
@@ -382,16 +387,18 @@ export async function executeInAppAgentRun(params: {
})
: undefined;
- // ---- Temp MCP key: mint + link to the run in one transaction, so no
- // crash window can leave a key that is not discoverable from its run. ----
+ // Link the key atomically to prevent orphan credentials.
mcpApiKey = await prisma.$transaction(async (tx) => {
- const key = await createAndAddApiKeysToDb({
- prisma: tx,
- entityId: projectId,
- scope: "PROJECT",
- note: IN_APP_AGENT_API_KEY_NOTE,
+ const key = await createApiKey(tx, {
+ owner: ProjectId(projectId),
+ role: SystemRoleId("LEGACY_PROJECT_API_KEY"),
+ createdBy: UserId(triggeredByUserId),
+ name: inAppAgentApiKeyName,
+ expiresAt: new Date(
+ (run.claimedAt ?? run.createdAt).getTime() +
+ IN_APP_AGENT_RUN_MAX_DURATION_MS,
+ ),
isInAppAgentKey: true,
- createdByUserId: run.triggeredByUserId ?? undefined,
});
await tx.inAppAgentRun.updateMany({