🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(ai-gateway): revoke gateway API keys when their user leaves the org (#19101)
Mark Salpeter42e974eb2e07
diff --git a/packages/shared/prisma/migrations/20261020134835_add_api_key_user_binding/migration.sql b/packages/shared/prisma/migrations/20261020134835_add_api_key_user_binding/migration.sqlnew file mode 100644index 0000000000..f60354f221--- /dev/null+++ b/packages/shared/prisma/migrations/20261020134835_add_api_key_user_binding/migration.sql@@ -0,0 +1,8 @@+-- AlterTable+ALTER TABLE "api_keys" ADD COLUMN IF NOT EXISTS "user_id" TEXT;++-- CreateIndex+CREATE INDEX IF NOT EXISTS "api_keys_user_id_organization_id_idx" ON "api_keys"("user_id", "organization_id");++-- AddForeignKey+ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex e18e2c2a54..80c9115e96 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -89,6 +89,7 @@ model User {inAppAgentConversations InAppAgentConversation[] @relation("InAppAgentConversationCreatedByUser")inAppAgentRuns InAppAgentRun[] @relation("InAppAgentRunTriggeredByUser")apiKeysCreated ApiKey[] @relation("ApiKeyCreatedByUser")+ apiKeys ApiKey[] @relation("ApiKeyUser")roleAssignments RoleAssignment[]evaluatorsCreated Evaluator[] @relation("EvaluatorCreatedByUser")evaluatorVersionsCreated EvaluatorVersion[] @relation("EvaluatorVersionCreatedByUser")@@ -248,6 +249,9 @@ model ApiKey {scope ApiKeyScope @default(PROJECT) @map("scope")createdByUserId String? @map("created_by_user_id")createdByUser User? @relation("ApiKeyCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)+ // user the key is bound to; the key is revoked when that user leaves the org+ userId String? @map("user_id")+ user User? @relation("ApiKeyUser", fields: [userId], references: [id], onDelete: Cascade)createdByApiKeyId String? @map("created_by_api_key_id")createdByApiKey ApiKey? @relation("ApiKeyCreatedByApiKey", fields: [createdByApiKeyId], references: [id], onDelete: SetNull)apiKeysCreated ApiKey[] @relation("ApiKeyCreatedByApiKey")@@ -259,6 +263,7 @@ model ApiKey {@@index(orgId)@@index(projectId)@@index(createdByApiKeyId)+ @@index([userId, orgId])@@index(publicKey)@@index(hashedSecretKey)@@index(fastHashedSecretKey)diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex d91c4005b0..5ea75e7192 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -235,7 +235,8 @@ async function main() {}))) {await createApiKey(prisma, {- owner: ProjectId(project1.id),+ tenant: OrganizationId(seedOrgId),+ scope: ProjectId(project1.id),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),name: seedApiKey.note,@@ -296,7 +297,8 @@ async function main() {}))) {await createApiKey(prisma, {- owner: ProjectId(project2.id),+ tenant: OrganizationId(seedOrgIdOrg2),+ scope: ProjectId(project2.id),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),name: secondKey.note,@@ -609,7 +611,8 @@ async function seedAiGateway(params: {const key =existingKey ??(await createApiKey(prisma, {- owner: OrganizationId(params.organizationId),+ tenant: OrganizationId(params.organizationId),+ scope: UserId(params.userId),role: SystemRoleId("AI_GATEWAY"),createdBy: UserId(params.userId),name: "Seeded gateway key",diff --git a/packages/shared/src/server/auth/apiKeys.test.ts b/packages/shared/src/server/auth/apiKeys.test.tsindex cc9b84d29e..08213f8d6d 100644--- a/packages/shared/src/server/auth/apiKeys.test.ts+++ b/packages/shared/src/server/auth/apiKeys.test.ts@@ -95,7 +95,7 @@ describe("createApiKey assignment rows", () => {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+ // assignment rows written and confirms 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.@@ -132,9 +132,6 @@ describe("createApiKey assignment rows", () => {},),},- project: {- findFirstOrThrow: vi.fn(async () => ({ orgId: ORG_ID })),- },};return { tx, assignments, getApiKeyData: () => apiKeyData };}@@ -146,7 +143,8 @@ describe("createApiKey assignment rows", () => {const { tx, assignments, getApiKeyData } = makeTx();await createApiKey(asTx(tx), {- owner: ProjectId("proj_1"),+ tenant: OrganizationId(ORG_ID),+ scope: ProjectId("proj_1"),role: SystemRoleId("VIEWER"),createdBy: UserId("user_1"),name: "project key",@@ -175,7 +173,8 @@ describe("createApiKey assignment rows", () => {const { tx, assignments, getApiKeyData } = makeTx();await createApiKey(asTx(tx), {- owner: OrganizationId(ORG_ID),+ tenant: OrganizationId(ORG_ID),+ scope: OrganizationId(ORG_ID),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: ApiKeyId("key_creator"),name: "org key",@@ -197,15 +196,57 @@ describe("createApiKey assignment rows", () => {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("binds a USER-scoped key to the user as an organization key in its tenant", async () => {+ const { tx, assignments, getApiKeyData } = makeTx();++ await createApiKey(asTx(tx), {+ tenant: OrganizationId(ORG_ID),+ scope: UserId("user_1"),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId("user_1"),+ });++ expect(assignments).toEqual([+ {+ orgId: ORG_ID,+ apiKeyId: KEY_ID,+ principalId: ApiKeyId(KEY_ID),+ ownerId: OrganizationId(ORG_ID),+ roleId: SystemRoleId("AI_GATEWAY"),+ projectId: null,+ systemRole: "AI_GATEWAY",+ },+ ]);+ const data = getApiKeyData();+ expect(data).toMatchObject({+ orgId: ORG_ID,+ userId: "user_1",+ scope: "ORGANIZATION",+ });+ expect(data.projectId).toBeUndefined();+ });++ it("leaves an ORGANIZATION-scoped key unbound even when a user creates it", async () => {+ const { tx, getApiKeyData } = makeTx();++ await createApiKey(asTx(tx), {+ tenant: OrganizationId(ORG_ID),+ scope: OrganizationId(ORG_ID),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId("user_1"),+ });++ expect(getApiKeyData().userId).toBeUndefined();});it("stores the secret only as a fast hash, with a placeholder no bcrypt check accepts", async () => {const { tx, getApiKeyData } = makeTx();const result = await createApiKey(asTx(tx), {- owner: ProjectId("proj_1"),+ tenant: OrganizationId(ORG_ID),+ scope: ProjectId("proj_1"),role: SystemRoleId("VIEWER"),createdBy: UserId("user_1"),});@@ -226,7 +267,8 @@ describe("createApiKey assignment rows", () => {const { tx, getApiKeyData } = makeTx();const result = await createApiKey(asTx(tx), {- owner: OrganizationId(ORG_ID),+ tenant: OrganizationId(ORG_ID),+ scope: OrganizationId(ORG_ID),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: "system",note,@@ -249,7 +291,8 @@ describe("createApiKey assignment rows", () => {await expect(createApiKey(asTx(tx), {- owner: OrganizationId(ORG_ID),+ tenant: OrganizationId(ORG_ID),+ scope: OrganizationId(ORG_ID),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: "system",...input,@@ -259,35 +302,4 @@ describe("createApiKey assignment rows", () => {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.tsindex be365c232a..725480ec30 100644--- a/packages/shared/src/server/auth/apiKeys.ts+++ b/packages/shared/src/server/auth/apiKeys.ts@@ -7,21 +7,16 @@ import { env } from "../../env";import { InvalidRequestError } from "../../errors";import {ApiKeyId,- OrganizationId,hasApiKeyKind,- hasOrganizationKind,hasProjectKind,- hasSystemRoleKind,- toSystemRole,untag,+ type OrganizationId,type OwnerId,+ type ProjectId,type RoleId,+ type TenantId,type UserId,} from "../../features/rbac/types";-import {- isApiKeyRole,- roleHasProjectPolicy,-} from "../../features/rbac/systemRoleAccessRights";import { logger } from "../logger";import { assignRole } from "../../features/rbac/roleAssignmentService";import { invalidateCachedApiKeys } from "./invalidateApiKeys";@@ -98,16 +93,12 @@ export function createShaHash(privateKey: string, salt: string): string {return hash;}-/** createApiKey inserts an api-key row and its single system-role assignment, keyed on the owner. */+/** createApiKey creates a new api key */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;+ opts: {+ tenant: TenantId;+ scope: OrganizationId | ProjectId | UserId;role: RoleId;createdBy: ApiKeyId | UserId | "system";name?: string;@@ -125,56 +116,87 @@ export async function createApiKey(displaySecretKey: string;secretKey: string;}> {- if (name !== undefined && note !== undefined) {- throw new InvalidRequestError("Provide either name or note, not both");- }+ const apiKeyParams = validateApiKeyParams(opts);+ const { secretKey, ...keyMaterialParams } = await generateKeyMaterial(opts);- const salt = env.SALT;- if (!salt) {- throw new Error("SALT is not set");- }-- 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 apiKey = await withTransaction(prisma, async (tx) => {+ const apiKey = await tx.apiKey.create({+ data: { ...apiKeyParams, ...keyMaterialParams },+ });+ await assignRole(tx, {+ tenantId: opts.tenant,+ principalId: ApiKeyId(apiKey.id),+ roleId: opts.role,+ ownerId: toOwnerId(opts),+ tags: [],+ });+ return apiKey;+ });+ return {+ id: apiKey.id,+ createdAt: apiKey.createdAt,+ note: apiKey.note,+ publicKey: apiKey.publicKey,+ displaySecretKey: apiKey.displaySecretKey,+ secretKey,+ };+}- const scope = hasOrganizationKind(opts.owner) ? "ORGANIZATION" : "PROJECT";- const data: Prisma.ApiKeyUncheckedCreateInput = {- ...(scope === "ORGANIZATION"- ? { orgId: untag(opts.owner) }- : { projectId: untag(opts.owner) }),- publicKey: pk,- hashedSecretKey: createLegacySecretKeyPlaceholder(),- displaySecretKey: getDisplaySecretKey(sk),- fastHashedSecretKey: createShaHash(sk, salt),- note: name ?? note,- scope,+/** validateApiKeyParams provides the validated non-secret columns for api key creation */+function validateApiKeyParams(opts: {+ tenant: TenantId;+ scope: OrganizationId | ProjectId | UserId;+ createdBy: ApiKeyId | UserId | "system";+ name?: string;+ note?: string;+ expiresAt?: Date | null;+ isInAppAgentKey?: boolean;+}): Omit<+ Prisma.ApiKeyUncheckedCreateInput,+ "publicKey" | "hashedSecretKey" | "fastHashedSecretKey" | "displaySecretKey"+> {+ return {+ ...noteColumn(opts),+ ...scopeColumns(opts.tenant, opts.scope),+ ...creatorColumns(opts.createdBy),expiresAt: opts.expiresAt ?? null,isInAppAgentKey: opts.isInAppAgentKey ?? false,- ...creatorColumns(opts.createdBy),};+}- const created = await withTransaction(prisma, (tx) =>- insertApiKey(tx, data, opts),- );- return { ...created, secretKey: sk };+/** noteColumn provides the note column for api key creation */+function noteColumn({+ name,+ note,+}: {+ name?: string;+ note?: string;+}): Pick<Prisma.ApiKeyUncheckedCreateInput, "note"> {+ if (name !== undefined && note !== undefined) {+ throw new InvalidRequestError("Provide either name or note, not both");+ }+ return { note: name ?? note };+}++/** scopeColumns provides scope columns for api key creation */+function scopeColumns(+ tenant: TenantId,+ scope: OrganizationId | ProjectId | UserId,+): Pick<+ Prisma.ApiKeyUncheckedCreateInput,+ "orgId" | "projectId" | "userId" | "scope"+> {+ if (hasUserScope(scope)) {+ return {+ orgId: untag(tenant),+ userId: untag(scope),+ scope: "ORGANIZATION",+ };+ }+ if (hasProjectKind(scope)) {+ return { projectId: untag(scope), scope: "PROJECT" };+ }+ return { orgId: untag(scope), scope: "ORGANIZATION" };}/** creatorColumns maps a key's creator to its api-key columns; "system" records none. */@@ -190,37 +212,55 @@ function creatorColumns(: { createdByUserId: untag(createdBy) };}-/** 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: [],- });+/** generateKeyMaterial provides the key columns and plaintext secret for api key creation */+async function generateKeyMaterial({+ predefinedKeys,+}: {+ predefinedKeys?: { secretKey: string; publicKey: string };+}): Promise<+ Pick<+ Prisma.ApiKeyUncheckedCreateInput,+ "publicKey" | "hashedSecretKey" | "fastHashedSecretKey" | "displaySecretKey"+ > & { secretKey: string }+> {+ const salt = env.SALT;+ if (!salt) {+ throw new Error("SALT is not set");+ }++ let keys = predefinedKeys;+ if (!keys) {+ const { pk, sk } = await generateKeySet();+ keys = { publicKey: pk, secretKey: sk };+ }return {- id: apiKey.id,- createdAt: apiKey.createdAt,- note: apiKey.note,- publicKey: apiKey.publicKey,- displaySecretKey: apiKey.displaySecretKey,+ publicKey: keys.publicKey,+ hashedSecretKey: createLegacySecretKeyPlaceholder(),+ fastHashedSecretKey: createShaHash(keys.secretKey, salt),+ displaySecretKey: getDisplaySecretKey(keys.secretKey),+ secretKey: keys.secretKey,};}+/** toOwnerId provides the role assignment owner for an api key's scope */+function toOwnerId({+ tenant,+ scope,+}: {+ tenant: TenantId;+ scope: OrganizationId | ProjectId | UserId;+}): OwnerId {+ if (hasUserScope(scope)) return tenant;+ return scope;+}++/** hasUserScope narrows an api key's scope to a user. */+function hasUserScope(+ scope: OrganizationId | ProjectId | UserId,+): scope is UserId {+ return scope.startsWith("user/");+}+export async function deleteApiKeyFromDb(p: {prisma: PrismaClient;id: string;diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex 4a92cb47a9..3eb05a323b 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -23,6 +23,7 @@ const ApiKeyBaseSchema = z.object({// these columns existedcreatedByUserId: z.string().nullish(),createdByApiKeyId: z.string().nullish(),+ userId: z.string().nullish(),});export const OrgEnrichedApiKey = z.discriminatedUnion("scope", [diff --git a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts b/web/src/__tests__/server/ai-gateway-control-plane.servertest.tsindex 6ae63478ae..ac44fa55e9 100644--- a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts+++ b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts@@ -1584,7 +1584,8 @@ describe("AI gateway control plane", () => {try {const { org, user } = await prepare();const adminKey = await createApiKey(prisma, {- owner: OrganizationId(org.id),+ tenant: OrganizationId(org.id),+ scope: OrganizationId(org.id),role: SystemRoleId("ADMIN"),createdBy: UserId(user.id),});diff --git a/web/src/__tests__/server/ai-gateway-user-bound-api-keys.servertest.ts b/web/src/__tests__/server/ai-gateway-user-bound-api-keys.servertest.tsnew file mode 100644index 0000000000..33b970202f--- /dev/null+++ b/web/src/__tests__/server/ai-gateway-user-bound-api-keys.servertest.ts@@ -0,0 +1,306 @@+import { randomUUID } from "node:crypto";+import type { Session } from "next-auth";+import { afterEach, describe, expect, it } from "vitest";++import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";+import { ForbiddenError } from "@langfuse/shared";+import { prisma, Role } from "@langfuse/shared/src/db";+import {+ createApiKey,+ createApiKeyCacheKey,+ createOrgProjectAndApiKey,+ redis,+} from "@langfuse/shared/src/server";+import { GatewayApiKeyService } from "@/src/features/ai-gateway/server/apiKey/gatewayApiKeyService";+import {+ deleteUserBoundApiKeys,+ evictRevokedApiKeys,+} from "@/src/features/ai-gateway/server/apiKey/userBoundApiKeys";+import type { OrgAuthedContext } from "@/src/server/api/trpc";+import {+ GATEWAY_RESOLVE_KEY_NON_EXISTENT,+ GatewayResolveCache,+} from "@/src/features/ai-gateway/server/resolve/gatewayResolveCache";+import { OrganizationId, SystemRoleId, UserId } from "@langfuse/shared/rbac";++const cleanupOrganizations: string[] = [];+const cleanupUsers: string[] = [];++afterEach(async () => {+ await prisma.auditLog.deleteMany({+ where: { orgId: { in: cleanupOrganizations } },+ });+ await prisma.organization.deleteMany({+ where: { id: { in: cleanupOrganizations.splice(0) } },+ });+ await prisma.user.deleteMany({+ where: { id: { in: cleanupUsers.splice(0) } },+ });+});++async function createOrg() {+ const { org } = await createOrgProjectAndApiKey();+ cleanupOrganizations.push(org.id);+ return org;+}++async function createUser() {+ const user = await prisma.user.create({+ data: { email: `bound-key-${randomUUID()}@example.test` },+ });+ cleanupUsers.push(user.id);+ return user;+}++async function boundUserOf(apiKeyId: string) {+ const row = await prisma.apiKey.findUniqueOrThrow({+ where: { id: apiKeyId },+ select: { userId: true },+ });+ return row.userId;+}++async function fastHashOf(apiKeyId: string) {+ const row = await prisma.apiKey.findUniqueOrThrow({+ where: { id: apiKeyId },+ select: { fastHashedSecretKey: true },+ });+ return row.fastHashedSecretKey!;+}++async function createGatewayKey(orgId: string, userId: string) {+ return createApiKey(prisma, {+ tenant: OrganizationId(orgId),+ scope: UserId(userId),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId(userId),+ });+}++function orgSession(+ user: { id: string; name: string | null },+ org: { id: string; name: string },+ role: Role,+): OrgAuthedContext["session"] {+ const session = {+ expires: "1",+ user: {+ id: user.id,+ name: user.name,+ canCreateOrganizations: true,+ featureFlags: testFeatureFlags({ templateFlag: false }),+ organizations: [+ {+ id: org.id,+ name: org.name,+ role,+ cloudConfig: undefined,+ plan: "oss",+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,+ projects: [],+ },+ ],+ },+ environment: {} as Session["environment"],+ } satisfies Session;+ return { ...session, orgId: org.id, orgRole: role };+}++async function existingKeyIds() {+ const rows = await prisma.apiKey.findMany({+ where: { orgId: { in: cleanupOrganizations } },+ select: { id: true },+ });+ return new Set(rows.map((row) => row.id));+}++describe("user-bound API keys", () => {+ describe("createApiKey binding", () => {+ it("binds a user-scoped key to its user", async () => {+ const org = await createOrg();+ const user = await createUser();++ const key = await createGatewayKey(org.id, user.id);++ expect(await boundUserOf(key.id)).toBe(user.id);+ });++ it("leaves organization-scoped keys unbound even when a user creates them", async () => {+ const org = await createOrg();+ const user = await createUser();++ const key = await createApiKey(prisma, {+ tenant: OrganizationId(org.id),+ scope: OrganizationId(org.id),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId(user.id),+ });++ expect(await boundUserOf(key.id)).toBeNull();+ });+ });++ describe("GatewayApiKeyService.create", () => {+ it("binds the key to a creator who can invoke the gateway", async () => {+ const org = await createOrg();+ const user = await createUser();+ await prisma.organizationMembership.create({+ data: { orgId: org.id, userId: user.id, role: Role.MEMBER },+ });++ const key = await new GatewayApiKeyService(prisma).create({+ organizationId: org.id,+ metadata: {},+ session: orgSession(user, org, Role.MEMBER),+ });++ expect(await boundUserOf(key.id)).toBe(user.id);+ });++ it("rejects a creator whose current role cannot invoke the gateway", async () => {+ const org = await createOrg();+ const user = await createUser();+ await prisma.organizationMembership.create({+ data: { orgId: org.id, userId: user.id, role: Role.VIEWER },+ });+ const before = await existingKeyIds();++ await expect(+ new GatewayApiKeyService(prisma).create({+ organizationId: org.id,+ metadata: {},+ session: orgSession(user, org, Role.OWNER),+ }),+ ).rejects.toThrow(ForbiddenError);+ expect(await existingKeyIds()).toEqual(before);+ });++ it("rejects a creator who is no longer a member", async () => {+ const org = await createOrg();+ const user = await createUser();+ const before = await existingKeyIds();++ await expect(+ new GatewayApiKeyService(prisma).create({+ organizationId: org.id,+ metadata: {},+ session: orgSession(user, org, Role.OWNER),+ }),+ ).rejects.toThrow(ForbiddenError);+ expect(await existingKeyIds()).toEqual(before);+ });+ });++ describe("deleteUserBoundApiKeys", () => {+ it("revokes only the user's bound keys in the given organization", async () => {+ const [org, otherOrg] = await Promise.all([createOrg(), createOrg()]);+ const [user, otherUser] = await Promise.all([createUser(), createUser()]);+ const revoked = await createGatewayKey(org.id, user.id);+ const otherOrgKey = await createGatewayKey(otherOrg.id, user.id);+ const otherUserKey = await createGatewayKey(org.id, otherUser.id);+ const unboundKey = await createApiKey(prisma, {+ tenant: OrganizationId(org.id),+ scope: OrganizationId(org.id),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: "system",+ });++ const deleted = await prisma.$transaction((tx) =>+ deleteUserBoundApiKeys(tx, { userId: user.id, orgId: org.id }),+ );++ expect(deleted.map((key) => key.id)).toEqual([revoked.id]);+ expect(await existingKeyIds()).toEqual(+ new Set([otherOrgKey.id, otherUserKey.id, unboundKey.id]),+ );+ });++ it("revokes the user's bound keys in every organization without an orgId", async () => {+ const [org, otherOrg] = await Promise.all([createOrg(), createOrg()]);+ const [user, otherUser] = await Promise.all([createUser(), createUser()]);+ const first = await createGatewayKey(org.id, user.id);+ const second = await createGatewayKey(otherOrg.id, user.id);+ const otherUserKey = await createGatewayKey(org.id, otherUser.id);++ const deleted = await prisma.$transaction((tx) =>+ deleteUserBoundApiKeys(tx, { userId: user.id }),+ );++ expect(new Set(deleted.map((key) => key.id))).toEqual(+ new Set([first.id, second.id]),+ );+ expect(await existingKeyIds()).toEqual(new Set([otherUserKey.id]));+ });+ });++ describe("evictRevokedApiKeys", () => {+ it("clears the auth and gateway resolve caches of revoked keys", async () => {+ const org = await createOrg();+ const user = await createUser();+ const key = await createGatewayKey(org.id, user.id);+ const hash = await fastHashOf(key.id);+ const resolveCache = new GatewayResolveCache();+ await redis!.set(createApiKeyCacheKey(hash), "cached");+ await resolveCache.set({+ fastHashedSecretKey: hash,+ apiFormat: "openai.responses",+ context: GATEWAY_RESOLVE_KEY_NON_EXISTENT,+ });++ const deleted = await prisma.$transaction((tx) =>+ deleteUserBoundApiKeys(tx, { userId: user.id, orgId: org.id }),+ );+ await evictRevokedApiKeys(deleted, { userId: user.id });++ expect(await redis!.exists(createApiKeyCacheKey(hash))).toBe(0);+ expect(+ await resolveCache.get({+ fastHashedSecretKey: hash,+ apiFormat: "openai.responses",+ }),+ ).toBeNull();+ });++ it("writes one delete audit entry per key with the unbinding reason", async () => {+ const org = await createOrg();+ const [user, admin] = await Promise.all([createUser(), createUser()]);+ const first = await createGatewayKey(org.id, user.id);+ const second = await createGatewayKey(org.id, user.id);+ await prisma.gatewayApiKeyAssociation.create({+ data: { apiKeyId: first.id, metadata: { team: "search" } },+ });++ const deleted = await prisma.$transaction((tx) =>+ deleteUserBoundApiKeys(tx, { userId: user.id, orgId: org.id }),+ );+ await evictRevokedApiKeys(deleted, { userId: admin.id });++ const entries = await prisma.auditLog.findMany({+ where: { resourceId: { in: [first.id, second.id] } },+ });+ expect(entries).toHaveLength(2);+ const firstEntry = entries.find((entry) => entry.resourceId === first.id);+ expect(firstEntry).toMatchObject({+ resourceType: "apiKey",+ action: "delete",+ userId: admin.id,+ orgId: org.id,+ });+ expect(JSON.parse(firstEntry!.before!)).toMatchObject({+ metadata: { team: "search" },+ apiKey: {+ id: first.id,+ publicKey: first.publicKey,+ displaySecretKey: first.displaySecretKey,+ createdByUserId: user.id,+ },+ });+ expect(JSON.parse(firstEntry!.after!)).toEqual({+ reason: "user_unbound",+ userId: user.id,+ });+ });+ });+});diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.tsindex 9ee952aae5..5cdd480cfe 100644--- a/web/src/__tests__/server/api-auth.servertest.ts+++ b/web/src/__tests__/server/api-auth.servertest.ts@@ -14,7 +14,12 @@ 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 {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import {clearRedisKeysByPatternSafely,createRedisTestClient,@@ -296,7 +301,8 @@ describe("Authenticate API calls", () => {data: { email: `apikey-creator-${v4()}@example.com` },});const apiKey = await createApiKey(prisma, {- owner: ProjectId(testApiKey.projectId),+ tenant: OrganizationId(testApiKey.orgId),+ scope: ProjectId(testApiKey.projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),isInAppAgentKey: true,@@ -321,7 +327,8 @@ describe("Authenticate API calls", () => {data: { email: `apikey-creator-${v4()}@example.com` },});const apiKey = await createApiKey(prisma, {- owner: ProjectId(testApiKey.projectId),+ tenant: OrganizationId(testApiKey.orgId),+ scope: ProjectId(testApiKey.projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),isInAppAgentKey: true,@@ -856,6 +863,7 @@ describe("Authenticate API calls", () => {isInAppAgentKey: false,createdByUserId: null,createdByApiKeyId: null,+ userId: null,projectId: expect.any(String),orgId: testApiKey.orgId,plan: "cloud:hobby",diff --git a/web/src/__tests__/server/api-key-list-filter.servertest.ts b/web/src/__tests__/server/api-key-list-filter.servertest.tsindex 9b41279815..d712560b71 100644--- a/web/src/__tests__/server/api-key-list-filter.servertest.ts+++ b/web/src/__tests__/server/api-key-list-filter.servertest.ts@@ -41,20 +41,22 @@ function createMockResponse() {describe("public API key list filters", () => {it("filters in-app agent keys from project API key responses", async () => {- const { projectId } = await createOrgProjectAndApiKey();+ const { orgId, projectId } = await createOrgProjectAndApiKey();const keyCreator = await prisma.user.create({data: { email: `apikey-creator-${randomUUID()}@example.com` },});const visibleKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),name: "Visible project key",});const inAppAgentKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),name: "Hidden project in-app agent key",@@ -81,14 +83,16 @@ describe("public API key list filters", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const visibleKey = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),name: "Visible org key",});const inAppAgentKey = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),name: "Hidden org in-app agent key",@@ -114,12 +118,14 @@ describe("public API key list filters", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const callerKey = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),});const inAppAgentKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),isInAppAgentKey: true,@@ -147,7 +153,8 @@ describe("public API key list filters", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const inAppAgentKey = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),isInAppAgentKey: true,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.tsindex 7144ccca74..b389bb455f 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@@ -4,7 +4,12 @@ import { auditLog } from "@/src/features/audit-logs/server";import { prisma, AuditLogRecordType } from "@langfuse/shared/src/db";import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";describe("in-app agent audit logging", () => {afterEach(() => {@@ -12,7 +17,7 @@ describe("in-app agent audit logging", () => {});it("stores the creator on in-app-agent MCP keys", async () => {- const { projectId } = await createOrgProjectAndApiKey();+ const { orgId, projectId } = await createOrgProjectAndApiKey();const user = await prisma.user.create({data: {email: `${randomUUID()}@test.com`,@@ -21,7 +26,8 @@ describe("in-app agent audit logging", () => {});const mcpApiKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),name: "In-app agent MCP session",@@ -52,7 +58,8 @@ describe("in-app agent audit logging", () => {});const mcpApiKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),name: "In-app agent MCP session",diff --git a/web/src/__tests__/server/audit-log-license-gate.servertest.ts b/web/src/__tests__/server/audit-log-license-gate.servertest.tsindex 6a2924ca21..579bc76d31 100644--- a/web/src/__tests__/server/audit-log-license-gate.servertest.ts+++ b/web/src/__tests__/server/audit-log-license-gate.servertest.ts@@ -35,7 +35,7 @@ import {deriveAuditLogEventId,logger,} from "@langfuse/shared/src/server";-import { ProjectId, SystemRoleId } from "@langfuse/shared/rbac";+import { OrganizationId, ProjectId, SystemRoleId } from "@langfuse/shared/rbac";/*** Audit log records are an enterprise feature, so they are only persisted when@@ -59,7 +59,8 @@ describe("audit log license gate", () => {projectId = org.projectId;apiKeyId = (await createApiKey(prisma, {- owner: ProjectId(org.projectId),+ tenant: OrganizationId(org.orgId),+ scope: ProjectId(org.projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: "system",name: "License gate test key",diff --git a/web/src/__tests__/server/audit-log-staging.servertest.ts b/web/src/__tests__/server/audit-log-staging.servertest.tsindex d75b2e2c30..eda0b6da03 100644--- a/web/src/__tests__/server/audit-log-staging.servertest.ts+++ b/web/src/__tests__/server/audit-log-staging.servertest.ts@@ -18,7 +18,12 @@ vi.mock("@/src/env.mjs", async (importOriginal) => {import { toAuditLogResourceRef, type AuditLogActor } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import {clickhouseClient,convertAuditLogStagingRowToClickhouse,@@ -417,7 +422,8 @@ describe("audit log staging", () => {data: { email: `${randomUUID()}@test.com`, name: "Agent Owner" },});const agentKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(creator.id),name: "In-app agent MCP session",diff --git a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts b/web/src/__tests__/server/blob-storage-integration-api.servertest.tsindex 7a5b1fc0ac..115eb1d908 100644--- a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-api.servertest.ts@@ -134,7 +134,8 @@ describe("Blob Storage Integrations API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const orgApiKey = await createApiKey(prisma, {- owner: OrganizationId(testOrgId),+ tenant: OrganizationId(testOrgId),+ scope: OrganizationId(testOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(orgKeyCreator.id),name: "Test API Key for Blob Storage API",@@ -248,7 +249,8 @@ describe("Blob Storage Integrations API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const projectApiKey = await createApiKey(prisma, {- owner: ProjectId(testProject1Id),+ tenant: OrganizationId(testOrgId),+ scope: ProjectId(testProject1Id),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),name: "Project API Key",@@ -1472,7 +1474,8 @@ describe("Blob Storage Integrations API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const projectApiKey = await createApiKey(prisma, {- owner: ProjectId(testProject1Id),+ tenant: OrganizationId(testOrgId),+ scope: ProjectId(testProject1Id),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),name: "Project API Key",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.tsindex a6df3bbeeb..5bcad12d16 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@@ -74,7 +74,8 @@ describe("Blob Storage Integration Status API - GET /api/public/integrations/blodata: { email: `apikey-creator-${randomUUID()}@example.com` },});const orgApiKey = await createApiKey(prisma, {- owner: OrganizationId(testOrgId),+ tenant: OrganizationId(testOrgId),+ scope: OrganizationId(testOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(orgKeyCreator.id),name: "Test API Key for Blob Status API",@@ -131,7 +132,8 @@ describe("Blob Storage Integration Status API - GET /api/public/integrations/blodata: { email: `apikey-creator-${randomUUID()}@example.com` },});const projectApiKey = await createApiKey(prisma, {- owner: ProjectId(testProjectId),+ tenant: OrganizationId(testOrgId),+ scope: ProjectId(testProjectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),name: "Project API Key for status test",diff --git a/web/src/__tests__/server/getRolesForPrincipal.servertest.ts b/web/src/__tests__/server/getRolesForPrincipal.servertest.tsindex 6aeaab5f21..b7cc6ed14f 100644--- a/web/src/__tests__/server/getRolesForPrincipal.servertest.ts+++ b/web/src/__tests__/server/getRolesForPrincipal.servertest.ts@@ -142,7 +142,8 @@ describe("getRolesForPrincipal decision-equivalence", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const key = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(creator.id),});@@ -169,7 +170,8 @@ describe("getRolesForPrincipal decision-equivalence", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const key = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(creator.id),});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.tsindex eea50eb073..21a9bc2411 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@@ -17,7 +17,12 @@ import {createBasicAuthHeader,createOrgProjectAndApiKey,} from "@langfuse/shared/src/server";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";const authMocks = vi.hoisted(() => ({getServerAuthSessionForRequest: vi.fn(),@@ -46,12 +51,13 @@ describe("in-app agent public API route auth", () => {});async function createInAppAgentAuthHeader() {- const { projectId } = await createOrgProjectAndApiKey();+ const { orgId, projectId } = await createOrgProjectAndApiKey();const keyCreator = await prisma.user.create({data: { email: `apikey-creator-${randomUUID()}@example.com` },});const apiKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: 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.tsindex f7d5dff57d..06c9089601 100644--- a/web/src/__tests__/server/mcp-auth-parity.servertest.ts+++ b/web/src/__tests__/server/mcp-auth-parity.servertest.ts@@ -151,7 +151,8 @@ describe("MCP connection auth parity", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const org = await createApiKey(prisma, {- owner: OrganizationId(base.orgId),+ tenant: OrganizationId(base.orgId),+ scope: OrganizationId(base.orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(orgKeyCreator.id),});@@ -161,7 +162,8 @@ describe("MCP connection auth parity", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const agent = await createApiKey(prisma, {- owner: ProjectId(base.projectId),+ tenant: OrganizationId(base.orgId),+ scope: ProjectId(base.projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(agentKeyCreator.id),isInAppAgentKey: true,diff --git a/web/src/__tests__/server/mcp-helpers.ts b/web/src/__tests__/server/mcp-helpers.tsindex e06ce9f8c4..b6c3704d4f 100644--- a/web/src/__tests__/server/mcp-helpers.ts+++ b/web/src/__tests__/server/mcp-helpers.ts@@ -9,7 +9,12 @@ import { randomUUID } from "crypto";import { prisma, type Role } from "@langfuse/shared/src/db";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import type { ServerContext } from "@/src/features/mcp/types";import { authenticator } from "@/src/features/apiKey/server";@@ -108,7 +113,8 @@ export async function createInAppAgentMcpContext(params: {})).id;const apiKey = await createApiKey(prisma, {- owner: ProjectId(params.projectId),+ tenant: OrganizationId(params.orgId),+ scope: ProjectId(params.projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(creatorUserId),name: "In-app agent MCP session",diff --git a/web/src/__tests__/server/members-trpc.servertest.ts b/web/src/__tests__/server/members-trpc.servertest.tsindex aa29fd3490..951dac96e8 100644--- a/web/src/__tests__/server/members-trpc.servertest.ts+++ b/web/src/__tests__/server/members-trpc.servertest.ts@@ -6,6 +6,8 @@ import { prisma } from "@langfuse/shared/src/db";import { Role, type Plan } from "@langfuse/shared";import { entitlementAccess } from "@/src/features/entitlements/constants/entitlements";import type { Session } from "next-auth";+import { createApiKey } from "@langfuse/shared/src/server";+import { OrganizationId, SystemRoleId, UserId } from "@langfuse/shared/rbac";// Session fixture sub-object types; casts keep the runtime fixtures unchanged// while satisfying newer required fields on the session user type.@@ -1109,3 +1111,58 @@ describe("membersRouter.updateProjectRole - project organization consistency", (expect(auditLogs).toHaveLength(0);});});++describe("membersRouter - gateway key revocation", () => {+ async function createBoundGatewayKey(orgId: string, userId: string) {+ return createApiKey(prisma, {+ tenant: OrganizationId(orgId),+ scope: UserId(userId),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId(userId),+ });+ }++ async function keyExists(id: string) {+ return (await prisma.apiKey.count({ where: { id } })) > 0;+ }++ it("deleteMembership revokes the removed member's bound gateway keys", async () => {+ const { org, caller } = await prepare("cloud:core");+ const member = await createTestUser();+ const membership = await prisma.organizationMembership.create({+ data: { userId: member.id, orgId: org.id, role: Role.MEMBER },+ });+ const key = await createBoundGatewayKey(org.id, member.id);++ await caller.members.deleteMembership({+ orgId: org.id,+ orgMembershipId: membership.id,+ });++ expect(await keyExists(key.id)).toBe(false);+ });++ it.each([+ [Role.MEMBER, true],+ [Role.VIEWER, false],+ [Role.NONE, false],+ ])(+ "updateOrgMembership from OWNER to %s keeps the bound gateway key: %s",+ async (role, kept) => {+ const { org, caller } = await prepare("cloud:core");+ const otherOwner = await createTestUser();+ const membership = await prisma.organizationMembership.create({+ data: { userId: otherOwner.id, orgId: org.id, role: Role.OWNER },+ });+ const key = await createBoundGatewayKey(org.id, otherOwner.id);++ await caller.members.updateOrgMembership({+ orgId: org.id,+ orgMembershipId: membership.id,+ role,+ });++ expect(await keyExists(key.id)).toBe(kept);+ },+ );+});diff --git a/web/src/__tests__/server/memberships-api.servertest.ts b/web/src/__tests__/server/memberships-api.servertest.tsindex f169c256c0..c48988d177 100644--- a/web/src/__tests__/server/memberships-api.servertest.ts+++ b/web/src/__tests__/server/memberships-api.servertest.ts@@ -89,7 +89,8 @@ describe("Memberships APIs", () => {// Create an organization API keyconst apiKey = await createApiKey(prisma, {- owner: OrganizationId(testOrgId),+ tenant: OrganizationId(testOrgId),+ scope: OrganizationId(testOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(testUserId),name: "Test API Key for Memberships API",@@ -166,7 +167,8 @@ describe("Memberships APIs", () => {it("should return 403 when using a non-organization API key", async () => {// Create a project API keyconst projectApiKey = await createApiKey(prisma, {- owner: ProjectId(testProjectId),+ tenant: OrganizationId(testOrgId),+ scope: ProjectId(testProjectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(testUserId),name: "Test API Key for Memberships API",@@ -598,7 +600,8 @@ describe("Organization membership safeguards", () => {const [ownerKey, adminKey] = await Promise.all((["LEGACY_ORGANIZATION_API_KEY", "ADMIN"] as const).map((role) =>createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId(role),createdBy: UserId(ownerId),}),@@ -738,7 +741,8 @@ describe("Organization membership safeguards", () => {it("rejects a VIEWER key without membership write grants", async () => {const key = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("VIEWER"),createdBy: UserId(ownerId),});@@ -895,6 +899,67 @@ describe("Organization membership safeguards", () => {expect((await membership(memberId))?.role).toBe(Role.ADMIN);expect(await logs()).toHaveLength(1);});++ describe("gateway key revocation", () => {+ const createBoundGatewayKey = (userId: string) =>+ createApiKey(prisma, {+ tenant: OrganizationId(orgId),+ scope: UserId(userId),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId(userId),+ });+ const keyExists = async (id: string) =>+ (await prisma.apiKey.count({ where: { id } })) === 1;+ const callHandler = async (+ handler: typeof handleUpdateMembership,+ method: "PUT" | "DELETE",+ body: { userId: string; role?: Role },+ ) => {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method,+ body,+ });+ await handler(req, res, orgId, apiKeyId, ownerContext);+ return res.statusCode;+ };++ it("revokes the gateway keys of a member removed via DELETE", async () => {+ const key = await createBoundGatewayKey(memberId);++ expect(+ await callHandler(handleDeleteMembership, "DELETE", {+ userId: memberId,+ }),+ ).toBe(200);++ expect(await keyExists(key.id)).toBe(false);+ });++ it.each([+ [Role.MEMBER, true],+ [Role.VIEWER, false],+ [Role.NONE, false],+ ])(+ "keeps gateway keys of an OWNER moved to %s only while the role can invoke the gateway",+ async (role, kept) => {+ await prisma.organizationMembership.update({+ where: { orgId_userId: { orgId, userId: memberId } },+ data: { role: Role.OWNER },+ });+ const key = await createBoundGatewayKey(memberId);++ expect(+ await callHandler(handleUpdateMembership, "PUT", {+ userId: memberId,+ role,+ }),+ ).toBe(200);++ expect((await membership(memberId))?.role).toBe(role);+ expect(await keyExists(key.id)).toBe(kept);+ },+ );+ });});describe("Project membership safeguards", () => {@@ -930,7 +995,8 @@ describe("Project membership safeguards", () => {});userId = user.id;const key = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("ADMIN"),createdBy: UserId(userId),});@@ -941,7 +1007,8 @@ describe("Project membership safeguards", () => {if (!authentication.success) throw authentication.error;adminContext = authentication.context;const projectKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("ADMIN"),createdBy: UserId(userId),});@@ -951,7 +1018,8 @@ describe("Project membership safeguards", () => {projectKey.secretKey,);const legacyKey = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(userId),});@@ -1034,7 +1102,8 @@ describe("Project membership safeguards", () => {mutableEnv.API_AUTH_MIGRATION = mode;expect((await request("PUT", Role.OWNER)).statusCode).toBe(403);const viewer = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("VIEWER"),createdBy: UserId(userId),});diff --git a/web/src/__tests__/server/organization-llm-connections-api.servertest.ts b/web/src/__tests__/server/organization-llm-connections-api.servertest.tsindex c3c4bb3492..d53c10e180 100644--- a/web/src/__tests__/server/organization-llm-connections-api.servertest.ts+++ b/web/src/__tests__/server/organization-llm-connections-api.servertest.ts@@ -22,7 +22,8 @@ import {async function createOrganizationApiKey(orgId: string): Promise<string> {const { publicKey, secretKey } = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: "system",});diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.tsindex 2a6a82b9d2..299ebc4425 100644--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts@@ -229,7 +229,8 @@ describe("organization API keys trpc", () => {it("filters in-app agent API keys", async () => {const inAppAgentKey = await createApiKey(prisma, {- owner: OrganizationId(organizationId),+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId("user-1"),name: "In-app agent key hidden from org UI",@@ -248,13 +249,15 @@ describe("organization API keys trpc", () => {it("filters AI Gateway keys", async () => {const gatewayKey = await createApiKey(prisma, {- owner: OrganizationId(organizationId),+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),role: SystemRoleId("AI_GATEWAY"),createdBy: UserId("user-1"),name: "Gateway key",});const ingestKey = await createApiKey(prisma, {- owner: OrganizationId(organizationId),+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),role: SystemRoleId("INGEST"),createdBy: UserId("user-1"),name: "Ingestion key",@@ -447,7 +450,8 @@ describe("organization API keys trpc", () => {it("does not update in-app agent API keys", async () => {const inAppAgentKey = await createApiKey(prisma, {- owner: OrganizationId(organizationId),+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId("user-1"),name: "Original in-app agent note",@@ -529,7 +533,8 @@ describe("organization API keys trpc", () => {it("stops a deleted gateway key from resolving through the gateway cache", async () => {Object.assign(env, { LANGFUSE_AI_GATEWAY_CACHE_RESOLVE_ENABLED: "true" });const gatewayKey = await createApiKey(prisma, {- owner: OrganizationId(organizationId),+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),role: SystemRoleId("AI_GATEWAY"),createdBy: UserId("user-1"),name: "Cached gateway key",@@ -575,7 +580,8 @@ describe("organization API keys trpc", () => {it("does not delete in-app agent API keys", async () => {const inAppAgentKey = await createApiKey(prisma, {- owner: OrganizationId(organizationId),+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId("user-1"),isInAppAgentKey: true,@@ -630,7 +636,8 @@ describe("organization API keys trpc", () => {// ability to see and revoke keys that were issued while entitled,// otherwise a downgrade would strand live credentials.const existingKey = await createApiKey(prisma, {- owner: OrganizationId(organizationId),+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId("user-1"),name: "Issued before downgrade",diff --git a/web/src/__tests__/server/organizations-api.servertest.ts b/web/src/__tests__/server/organizations-api.servertest.tsindex 27fcb6a1ec..b9eed88c66 100644--- a/web/src/__tests__/server/organizations-api.servertest.ts+++ b/web/src/__tests__/server/organizations-api.servertest.ts@@ -1000,7 +1000,8 @@ describe("Public Organizations API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const apiKey = await createApiKey(prisma, {- owner: OrganizationId(testOrgId),+ tenant: OrganizationId(testOrgId),+ scope: OrganizationId(testOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),name: "Test API Key for Organizations API",@@ -1072,7 +1073,8 @@ describe("Public Organizations API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const projectApiKey = await createApiKey(prisma, {- owner: ProjectId(testProject1Id),+ tenant: OrganizationId(testOrgId),+ scope: ProjectId(testProject1Id),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),name: "Test Project API Key",@@ -1176,7 +1178,8 @@ describe("Public Organizations API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const emptyOrgApiKey = await createApiKey(prisma, {- owner: OrganizationId(emptyOrg.id),+ tenant: OrganizationId(emptyOrg.id),+ scope: OrganizationId(emptyOrg.id),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),name: "Test API Key for Empty Org",@@ -1266,7 +1269,8 @@ describe("Public Organizations API", () => {// Create an organization API key for authenticationconst orgApiKey = await createApiKey(prisma, {- owner: OrganizationId(testOrgId),+ tenant: OrganizationId(testOrgId),+ scope: OrganizationId(testOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),name: "Org API Key for testing",@@ -1276,21 +1280,24 @@ describe("Public Organizations API", () => {// Create additional organization API keys to listawait createApiKey(prisma, {- owner: OrganizationId(testOrgId),+ tenant: OrganizationId(testOrgId),+ scope: OrganizationId(testOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),name: "First test key",});await createApiKey(prisma, {- owner: OrganizationId(testOrgId),+ tenant: OrganizationId(testOrgId),+ scope: OrganizationId(testOrgId),role: SystemRoleId("VIEWER"),createdBy: UserId(keyCreator.id),name: "Second test key",});const multiRoleKey = await createApiKey(prisma, {- owner: OrganizationId(testOrgId),+ tenant: OrganizationId(testOrgId),+ scope: OrganizationId(testOrgId),role: SystemRoleId("INGEST"),createdBy: UserId(keyCreator.id),name: "Multiple roles key",@@ -1314,7 +1321,8 @@ describe("Public Organizations API", () => {secondOrgId = secondOrg.id;const secondOrgKey = await createApiKey(prisma, {- owner: OrganizationId(secondOrgId),+ tenant: OrganizationId(secondOrgId),+ scope: OrganizationId(secondOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),name: "Second org API key",@@ -1439,7 +1447,8 @@ describe("Public Organizations API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const projectApiKey = await createApiKey(prisma, {- owner: ProjectId(project.id),+ tenant: OrganizationId(testOrgId),+ scope: ProjectId(project.id),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),name: "Project API key",diff --git a/web/src/__tests__/server/project-api-key-trpc.servertest.ts b/web/src/__tests__/server/project-api-key-trpc.servertest.tsindex 393c881ae4..c5ef574de2 100644--- a/web/src/__tests__/server/project-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/project-api-key-trpc.servertest.ts@@ -7,7 +7,12 @@ import {createApiKey,createOrgProjectAndApiKey,} from "@langfuse/shared/src/server";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import { env } from "@/src/env.mjs";import { randomUUID } from "crypto";@@ -96,15 +101,16 @@ describe("project API keys trpc", () => {const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });- return { caller, projectId, publicKey };+ return { caller, projectId, orgId, publicKey };}describe("projectApiKeys.byProjectId", () => {it("filters in-app agent API keys", async () => {- const { caller, projectId } = await createProjectCaller();+ const { caller, projectId, orgId } = await createProjectCaller();const inAppAgentKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId("user-1"),name: "In-app agent key hidden from project UI",@@ -301,9 +307,10 @@ describe("project API keys trpc", () => {});it("does not update in-app agent API keys", async () => {- const { caller, projectId } = await createProjectCaller();+ const { caller, projectId, orgId } = await createProjectCaller();const inAppAgentKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId("user-1"),name: "Original in-app agent note",@@ -327,10 +334,11 @@ 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 { caller, projectId, orgId } = await createProjectCaller();const key = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId("user-1"),name: "Key for role assignment test",@@ -373,9 +381,10 @@ describe("project API keys trpc", () => {});it("does not delete in-app agent API keys", async () => {- const { caller, projectId } = await createProjectCaller();+ const { caller, projectId, orgId } = await createProjectCaller();const inAppAgentKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: 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.tsindex 715daf7709..931ce397f4 100644--- a/web/src/__tests__/server/projects-api.servertest.ts+++ b/web/src/__tests__/server/projects-api.servertest.ts@@ -215,7 +215,8 @@ describe("Projects API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const orgKey = await createApiKey(prisma, {- owner: OrganizationId("seed-org-id"),+ tenant: OrganizationId("seed-org-id"),+ scope: OrganizationId("seed-org-id"),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),predefinedKeys: {@@ -1347,7 +1348,8 @@ describe("Projects API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const apiKeyMeta = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId("seed-org-id"),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),name: `Delete Test API Key ${randomUUID().substring(0, 8)}`,diff --git a/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts b/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.tsindex 3ddec3ea25..94643794fe 100644--- a/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts+++ b/web/src/__tests__/server/projectsRouter-chbProjectEvents.servertest.ts@@ -14,7 +14,12 @@ vi.mock("@/src/ee/features/billing/server/chb/chbProjectEvents", () => ({}));import { createApiKey } from "@langfuse/shared/src/server";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ 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";@@ -187,7 +192,8 @@ describe("projectsRouter system role assignments", () => {const caller = makeCaller({ userId: user.id, orgIds: [orgId], projectId });const key = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),});@@ -251,7 +257,8 @@ describe("projectsRouter system role assignments", () => {});const key = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(sourceOrgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),});diff --git a/web/src/__tests__/server/prompts.v2.servertest.ts b/web/src/__tests__/server/prompts.v2.servertest.tsindex 075224c335..0712b50e4a 100644--- a/web/src/__tests__/server/prompts.v2.servertest.ts+++ b/web/src/__tests__/server/prompts.v2.servertest.ts@@ -24,7 +24,12 @@ import {PromptService,redis,} from "@langfuse/shared/src/server";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import {createUserWithOrgRole,protectPromptLabel,@@ -3355,7 +3360,8 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {role: Role.MEMBER,});const apiKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(userId),isInAppAgentKey: true,@@ -3441,7 +3447,8 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {role: Role.MEMBER,});const apiKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(userId),isInAppAgentKey: true,diff --git a/web/src/__tests__/server/public-api-auth-parity.servertest.ts b/web/src/__tests__/server/public-api-auth-parity.servertest.tsindex 8fbea9b5a5..a93f768d88 100644--- a/web/src/__tests__/server/public-api-auth-parity.servertest.ts+++ b/web/src/__tests__/server/public-api-auth-parity.servertest.ts@@ -375,7 +375,8 @@ describe("public-api auth parity", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const org = await createApiKey(prisma, {- owner: OrganizationId(base.orgId),+ tenant: OrganizationId(base.orgId),+ scope: OrganizationId(base.orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(orgKeyCreator.id),});@@ -385,7 +386,8 @@ describe("public-api auth parity", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});const agent = await createApiKey(prisma, {- owner: ProjectId(base.projectId),+ tenant: OrganizationId(base.orgId),+ scope: ProjectId(base.projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(agentKeyCreator.id),isInAppAgentKey: true,diff --git a/web/src/__tests__/server/roleAssignmentService.servertest.ts b/web/src/__tests__/server/roleAssignmentService.servertest.tsindex c5c7d5709e..24ceae5606 100644--- a/web/src/__tests__/server/roleAssignmentService.servertest.ts+++ b/web/src/__tests__/server/roleAssignmentService.servertest.ts@@ -274,7 +274,8 @@ describe("API-key deletion", () => {data: { email: `apikey-creator-${v4()}@example.com` },});await createApiKey(prisma, {- owner: ProjectId(otherProject.id),+ tenant: OrganizationId(orgId),+ scope: ProjectId(otherProject.id),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(keyCreator.id),});diff --git a/web/src/__tests__/server/scim-api.servertest.ts b/web/src/__tests__/server/scim-api.servertest.tsindex 6c72cb5f6b..9f9b9fa6e7 100644--- a/web/src/__tests__/server/scim-api.servertest.ts+++ b/web/src/__tests__/server/scim-api.servertest.ts@@ -181,7 +181,8 @@ describe("SCIM API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(keyCreator.id),predefinedKeys: {@@ -1337,7 +1338,8 @@ describe("SCIM API", () => {scopedOrgPublicKey = `pk-lf-org-${randomUUID().substring(0, 8)}`;scopedOrgSecretKey = `sk-lf-org-${randomUUID().substring(0, 8)}`;await createApiKey(prisma, {- owner: OrganizationId(scopedOrgId),+ tenant: OrganizationId(scopedOrgId),+ scope: OrganizationId(scopedOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(owner.id),predefinedKeys: {@@ -1690,7 +1692,8 @@ describe("SCIM API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});await createApiKey(prisma, {- owner: OrganizationId(hobbyOrgId),+ tenant: OrganizationId(hobbyOrgId),+ scope: OrganizationId(hobbyOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(hobbyKeyCreator.id),predefinedKeys: {@@ -1714,7 +1717,8 @@ describe("SCIM API", () => {data: { email: `apikey-creator-${randomUUID()}@example.com` },});await createApiKey(prisma, {- owner: OrganizationId(teamOrgId),+ tenant: OrganizationId(teamOrgId),+ scope: OrganizationId(teamOrgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(teamKeyCreator.id),predefinedKeys: {@@ -1854,7 +1858,8 @@ describe("SCIM ownership boundary", () => {const [adminKey, ownerKey] = await Promise.all((["ADMIN", "LEGACY_ORGANIZATION_API_KEY"] as const).map((role) =>createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId(role),createdBy: UserId(ownerId),}),@@ -1929,7 +1934,8 @@ describe("SCIM ownership boundary", () => {it("rejects ownership changes without an authorization context", async () => {Object.assign(env, { API_AUTH_MIGRATION: "legacy" });const legacyKey = await createApiKey(prisma, {- owner: OrganizationId(orgId),+ tenant: OrganizationId(orgId),+ scope: OrganizationId(orgId),role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),createdBy: UserId(ownerId),});@@ -2041,4 +2047,52 @@ describe("SCIM ownership boundary", () => {expect(await call(scimUserRoute, "DELETE", undefined, memberId)).toBe(204);expect(await roleOf(memberId)).toBeUndefined();});++ describe("gateway key revocation", () => {+ const createBoundGatewayKey = (userId: string) =>+ createApiKey(prisma, {+ tenant: OrganizationId(orgId),+ scope: UserId(userId),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId(userId),+ });+ const keyExists = async (apiKeyId: string) =>+ (await prisma.apiKey.count({ where: { id: apiKeyId } })) === 1;++ it("revokes the gateway keys of a user removed via DELETE", async () => {+ const key = await createBoundGatewayKey(memberId);++ expect(await call(scimUserRoute, "DELETE", undefined, memberId)).toBe(+ 204,+ );++ expect(await keyExists(key.id)).toBe(false);+ });++ it.each([+ ["MEMBER", true],+ ["VIEWER", false],+ ["NONE", false],+ ])(+ "keeps gateway keys of an OWNER moved to %s only while the role can invoke the gateway",+ async (role, kept) => {+ const key = await createBoundGatewayKey(ownerId);++ const response = await callScimRoute(scimUserRoute, {+ method: "PUT",+ authorization: ownerAuth,+ userId: ownerId,+ body: {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ active: true,+ roles: [role],+ },+ });++ expect(response.status).toBe(200);+ expect(await roleOf(ownerId)).toBe(role);+ expect(await keyExists(key.id)).toBe(kept);+ },+ );+ });});diff --git a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.tsindex b643812a17..097d270068 100644--- a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts+++ b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts@@ -49,6 +49,7 @@ const apiKey = (over: Partial<ApiKey> = {}): ApiKey => ({scope: "PROJECT",createdByUserId: "user_1",createdByApiKeyId: null,+ userId: null,...over,});diff --git a/web/src/__tests__/server/unit/apiKey/invalidateApiKeys.servertest.ts b/web/src/__tests__/server/unit/apiKey/invalidateApiKeys.servertest.tsindex e9cd9af7c1..38cc9ab657 100644--- a/web/src/__tests__/server/unit/apiKey/invalidateApiKeys.servertest.ts+++ b/web/src/__tests__/server/unit/apiKey/invalidateApiKeys.servertest.ts@@ -28,6 +28,7 @@ const apiKey = (over: Partial<ApiKey> = {}): ApiKey => ({scope: "PROJECT",createdByUserId: "user_1",createdByApiKeyId: null,+ userId: null,...over,});diff --git a/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts b/web/src/__tests__/server/unit/policy/contextResolver.servertest.tsindex 4ceef2cfac..f7a69bd8dc 100644--- a/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts+++ b/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts@@ -127,6 +127,7 @@ const apiKey = (over: Partial<ApiKey> = {}): ApiKey => ({scope: "PROJECT",createdByUserId: USER,createdByApiKeyId: null,+ userId: null,...over,});const orgKey = (over: Partial<ApiKey> = {}): ApiKey =>diff --git a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts b/web/src/__tests__/server/unit/sfdc-sync.servertest.tsindex 393ae5c740..5e779ee978 100644--- a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts+++ b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts@@ -66,6 +66,8 @@ const { envMock, prismaMock, loggerMock, fetchMock } = vi.hoisted(() => {},apiKey: {findUnique: vi.fn(async (): Promise<unknown> => null),+ findMany: vi.fn(async (): Promise<unknown[]> => []),+ deleteMany: vi.fn(async () => ({ count: 0 })),},// Starter-org provisioning serializes on SELECT ... FOR UPDATE.$queryRaw: vi.fn(async (): Promise<unknown> => []),diff --git a/web/src/__tests__/server/userAccount.servertest.ts b/web/src/__tests__/server/userAccount.servertest.tsindex 67a3cf4e6b..2349fa72b5 100644--- a/web/src/__tests__/server/userAccount.servertest.ts+++ b/web/src/__tests__/server/userAccount.servertest.ts@@ -5,6 +5,8 @@ import { randomUUID } from "crypto";import type { Plan } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";+import { createApiKey } from "@langfuse/shared/src/server";+import { OrganizationId, SystemRoleId, UserId } from "@langfuse/shared/rbac";import { env } from "@/src/env.mjs";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -232,6 +234,49 @@ describe("userAccountRouter.signOutAllSessions", () => {});});+describe("userAccountRouter.delete", () => {+ it("audits the revocation of the user's bound gateway keys in each organization", async () => {+ const { caller, userId, orgId } = await createCaller();+ const otherOrg = await prisma.organization.create({+ data: { name: `User Account Test Org ${randomUUID()}` },+ });+ const keys = await Promise.all(+ [orgId, otherOrg.id].map((owner) =>+ createApiKey(prisma, {+ tenant: OrganizationId(owner),+ scope: UserId(userId),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId(userId),+ }),+ ),+ );++ await caller.userAccount.delete();++ const entries = await prisma.auditLog.findMany({+ where: { resourceId: { in: keys.map((key) => key.id) } },+ select: { resourceId: true, orgId: true, action: true, userId: true },+ });+ expect(entries).toHaveLength(2);+ expect(entries).toEqual(+ expect.arrayContaining([+ { resourceId: keys[0].id, orgId, action: "delete", userId },+ {+ resourceId: keys[1].id,+ orgId: otherOrg.id,+ action: "delete",+ userId,+ },+ ]),+ );+ expect(+ await prisma.apiKey.count({+ where: { id: { in: keys.map((key) => key.id) } },+ }),+ ).toBe(0);+ });+});+async function createCaller({admin = false,plan = "cloud:hobby",diff --git a/web/src/ee/features/admin-api/server/memberships.ts b/web/src/ee/features/admin-api/server/memberships.tsindex 006ac039f3..bce82ddb4b 100644--- a/web/src/ee/features/admin-api/server/memberships.ts+++ b/web/src/ee/features/admin-api/server/memberships.ts@@ -2,6 +2,11 @@ import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";import { getSfdcService } from "@/src/ee/features/sfdc-sync/server";+import {+ deleteUserBoundApiKeys,+ deleteUserBoundApiKeysForRole,+ evictRevokedApiKeys,+} from "@/src/features/ai-gateway/server/apiKey/userBoundApiKeys";import { auditLog } from "@/src/features/audit-logs/server";import { type AuthorizationContext } from "@/src/features/auth/policy/types";import { authorize } from "@/src/features/rbac/authorize";@@ -80,7 +85,7 @@ export async function handleUpdateMembership(});}- const membership = await prisma.$transaction(async (tx) => {+ const { membership, revokedKeys } = await prisma.$transaction(async (tx) => {const before = await tx.organizationMembership.findUnique({where: { orgId_userId: { orgId, userId: validatedBody.data.userId } },});@@ -113,8 +118,14 @@ export async function handleUpdateMembership(},tx,);- return after;+ const revokedKeys = await deleteUserBoundApiKeysForRole(tx, {+ userId: validatedBody.data.userId,+ orgId,+ role: validatedBody.data.role,+ });+ return { membership: after, revokedKeys };});+ await evictRevokedApiKeys(revokedKeys, { apiKeyId });await getSfdcService()?.setUserRole({orgId,@@ -147,12 +158,12 @@ export async function handleDeleteMembership(});}- const deleted = await prisma.$transaction(async (tx) => {+ const { deleted, revokedKeys } = await prisma.$transaction(async (tx) => {const before = await tx.organizationMembership.findUnique({where: { orgId_userId: { orgId, userId: validatedBody.data.userId } },});assertAuthorizeMembershipChange(context, orgId);- if (!before) return false;+ if (!before) return { deleted: false, revokedKeys: [] };await assertValidOwnershipChange({tx,context,@@ -173,8 +184,13 @@ export async function handleDeleteMembership(},tx,);- return true;+ const revokedKeys = await deleteUserBoundApiKeys(tx, {+ userId: validatedBody.data.userId,+ orgId,+ });+ return { deleted: true, revokedKeys };});+ await evictRevokedApiKeys(revokedKeys, { apiKeyId });if (deleted) {const user = await prisma.user.findUnique({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.tsindex 82feb47528..fe6c7c5e34 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@@ -68,7 +68,8 @@ export async function handleCreateApiKey(const { name, note, expiresAt, role } = validationResult.data;const apiKeyMeta = await createApiKey(prisma, {- owner: OrganizationId(organizationId),+ tenant: OrganizationId(organizationId),+ scope: OrganizationId(organizationId),role: SystemRoleId(role),createdBy: "system",name,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.tsindex 39f32b1a9d..c1f9100c3a 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@@ -4,7 +4,12 @@ import { logger } from "@langfuse/shared/src/server";import { auditLog } from "@/src/features/audit-logs/server";import { z } from "zod";import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";-import { ApiKeyId, ProjectId, SystemRoleId } from "@langfuse/shared/rbac";+import {+ ApiKeyId,+ OrganizationId,+ ProjectId,+ SystemRoleId,+} from "@langfuse/shared/rbac";import {projectApiKeyCreationSchema,apiKeyToResponse,@@ -99,7 +104,8 @@ export async function handleCreateApiKey(try {const apiKeyMeta = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId(role),createdBy: ApiKeyId(createdByApiKeyId),name,diff --git a/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts b/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.tsindex 6c462aa51d..02c1ed55c1 100644--- a/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts+++ b/web/src/features/ai-gateway/server/apiKey/gatewayApiKeyService.ts@@ -1,5 +1,9 @@-import { InternalServerError, LangfuseNotFoundError } from "@langfuse/shared";-import type { PrismaClient } from "@langfuse/shared/src/db";+import {+ ForbiddenError,+ InternalServerError,+ LangfuseNotFoundError,+} from "@langfuse/shared";+import { Prisma, type PrismaClient, type Role } from "@langfuse/shared/src/db";import {createApiKey,deleteApiKeyFromDb,@@ -11,6 +15,7 @@ import { auditLog } from "@/src/features/audit-logs/server";import type { GatewayMetadata } from "@/src/features/ai-gateway/server/provider";import type { OrgAuthedContext } from "@/src/server/api/trpc";import { invalidateGatewayResolveCacheForApiKey } from "@/src/features/ai-gateway/server/resolve/gatewayResolveCache";+import { hasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import { GatewayApiKeyRepository } from "./gatewayApiKeyRepository";export class GatewayApiKeyService {@@ -34,22 +39,27 @@ export class GatewayApiKeyService {expiresAt?: Date | null;session: OrgAuthedContext["session"];}) {- const key = await this.prisma.$transaction(async (tx) => {- const key = await createApiKey(tx, {- owner: OrganizationId(params.organizationId),- role: SystemRoleId("AI_GATEWAY"),- createdBy: UserId(params.session.user.id),- name: params.name,- expiresAt: params.expiresAt,- });- await tx.gatewayApiKeyAssociation.create({- data: {- apiKeyId: key.id,- metadata: params.metadata,- },- });- return key;- });+ const key = await this.prisma.$transaction(+ async (tx) => {+ await assertCreatorCanInvokeGateway(tx, params);+ const key = await createApiKey(tx, {+ tenant: OrganizationId(params.organizationId),+ scope: UserId(params.session.user.id),+ role: SystemRoleId("AI_GATEWAY"),+ createdBy: UserId(params.session.user.id),+ name: params.name,+ expiresAt: params.expiresAt,+ });+ await tx.gatewayApiKeyAssociation.create({+ data: {+ apiKeyId: key.id,+ metadata: params.metadata,+ },+ });+ return key;+ },+ { isolationLevel: Prisma.TransactionIsolationLevel.Serializable },+ );await auditLog({session: params.session,@@ -112,3 +122,25 @@ export class GatewayApiKeyService {);}}++/** assertCreatorCanInvokeGateway share-locks the creator's membership so removal and demotion order after the key insert. */+async function assertCreatorCanInvokeGateway(+ tx: Prisma.TransactionClient,+ params: { organizationId: string; session: OrgAuthedContext["session"] },+) {+ const [membership] = await tx.$queryRaw<{ role: Role }[]>`+ SELECT role FROM organization_memberships+ WHERE org_id = ${params.organizationId}+ AND user_id = ${params.session.user.id}+ FOR SHARE+ `;+ if (params.session.user.admin) return;+ if (+ !membership ||+ !hasOrganizationAccess({ role: membership.role, scope: "gateway:invoke" })+ ) {+ throw new ForbiddenError(+ "Only organization members who can invoke the gateway can create gateway API keys",+ );+ }+}diff --git a/web/src/features/ai-gateway/server/apiKey/userBoundApiKeys.ts b/web/src/features/ai-gateway/server/apiKey/userBoundApiKeys.tsnew file mode 100644index 0000000000..acb6d7955b--- /dev/null+++ b/web/src/features/ai-gateway/server/apiKey/userBoundApiKeys.ts@@ -0,0 +1,113 @@+import type { ApiKey, Prisma, Role } from "@langfuse/shared/src/db";+import { invalidateCachedApiKeys, logger } from "@langfuse/shared/src/server";+import { auditLog, type AuditLogActor } from "@/src/features/audit-logs/server";+import { invalidateGatewayResolveCacheForApiKey } from "@/src/features/ai-gateway/server/resolve/gatewayResolveCache";+import { hasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";++/** deleteUserBoundApiKeysForRole removes the user's gateway keys in orgId when role can no longer invoke the gateway. */+export async function deleteUserBoundApiKeysForRole(+ tx: Prisma.TransactionClient,+ p: { userId: string; orgId: string; role: Role },+): Promise<RevokedApiKey[]> {+ if (hasOrganizationAccess({ role: p.role, scope: "gateway:invoke" }))+ return [];+ return deleteUserBoundApiKeys(tx, { userId: p.userId, orgId: p.orgId });+}++/** deleteUserBoundApiKeys removes gateway keys bound to userId on the caller's transaction and returns them for post-commit eviction. */+export async function deleteUserBoundApiKeys(+ tx: Prisma.TransactionClient,+ p: { userId: string; orgId?: string },+): Promise<RevokedApiKey[]> {+ const keys = await tx.apiKey.findMany({+ where: { userId: p.userId, orgId: p.orgId ?? { not: null } },+ include: { gatewayAssociation: { select: { metadata: true } } },+ });+ if (keys.length === 0) return [];+ await tx.apiKey.deleteMany({+ where: { id: { in: keys.map((key) => key.id) } },+ });+ return keys.filter((key): key is RevokedApiKey => key.orgId !== null);+}++/** evictRevokedApiKeys clears the caches of committed revocations and writes one audit entry per key, logging instead of throwing; call after commit. */+export async function evictRevokedApiKeys(+ keys: RevokedApiKey[],+ actor: RevocationActor,+): Promise<void> {+ if (keys.length === 0) return;+ const results = await Promise.allSettled([+ evictCaches(keys),+ ...keys.map((key) => auditRevocation(key, actor)),+ ]);+ logFailures(results, keys);+}++/** evictCaches clears the auth and gateway resolve caches of the keys. */+async function evictCaches(keys: ApiKey[]) {+ await Promise.all([+ invalidateCachedApiKeys(keys, "user-bound gateway keys"),+ ...keys.map(evictGatewayResolveCache),+ ]);+}++/** evictGatewayResolveCache drops the key's cached resolve contexts when it has a hash. */+async function evictGatewayResolveCache(key: ApiKey) {+ if (!key.fastHashedSecretKey) return;+ await invalidateGatewayResolveCacheForApiKey(key.fastHashedSecretKey);+}++/** logFailures logs post-commit eviction failures without failing the committed change. */+function logFailures(+ results: PromiseSettledResult<unknown>[],+ keys: RevokedApiKey[],+) {+ for (const result of results) {+ if (result.status === "fulfilled") continue;+ logger.error("Failed to evict revoked user-bound gateway API keys", {+ apiKeyIds: keys.map((key) => key.id),+ error: result.reason,+ });+ }+}++/** auditRevocation records the deletion of one key in the key's organization. */+function auditRevocation(key: RevokedApiKey, actor: RevocationActor) {+ return auditLog({+ ...actorInOrg(actor, key.orgId),+ resourceType: "apiKey",+ resourceId: key.id,+ action: "delete",+ before: {+ metadata: key.gatewayAssociation?.metadata,+ apiKey: {+ id: key.id,+ publicKey: key.publicKey,+ displaySecretKey: key.displaySecretKey,+ note: key.note,+ createdAt: key.createdAt,+ expiresAt: key.expiresAt,+ lastUsedAt: key.lastUsedAt,+ createdByUserId: key.createdByUserId,+ },+ },+ after: { reason: "user_unbound", userId: key.userId },+ });+}++/** actorInOrg attributes a session-less actor to the revoked key's organization. */+function actorInOrg(actor: RevocationActor, orgId: string): AuditLogActor {+ if ("session" in actor) return actor;+ return { ...actor, orgId };+}++/** RevocationActor is the triggering actor; non-session actors take the key's orgId. */+export type RevocationActor =+ | Extract<AuditLogActor, { session: unknown }>+ | { userId: string }+ | { apiKeyId: string };++/** RevokedApiKey is a deleted org key row with the gateway metadata its audit entry records. */+export type RevokedApiKey = Prisma.ApiKeyGetPayload<{+ include: { gatewayAssociation: { select: { metadata: true } } };+}> & { orgId: string };diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.tsindex 8adcc451c7..4b7c784f2a 100644--- a/web/src/features/public-api/server/organizationApiKeyRouter.ts+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts@@ -95,7 +95,8 @@ export const organizationApiKeysRouter = createTRPCRouter({});const apiKeyMeta = await createApiKey(ctx.prisma, {- owner: OrganizationId(input.orgId),+ tenant: OrganizationId(input.orgId),+ scope: OrganizationId(input.orgId),role: SystemRoleId(input.role),createdBy: UserId(ctx.session.user.id),name: input.name,diff --git a/web/src/features/public-api/server/projectApiKeyRouter.ts b/web/src/features/public-api/server/projectApiKeyRouter.tsindex 0e5ac152d9..3875c7815c 100644--- a/web/src/features/public-api/server/projectApiKeyRouter.ts+++ b/web/src/features/public-api/server/projectApiKeyRouter.ts@@ -9,7 +9,12 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { redis } from "@langfuse/shared/src/server";import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";import { LangfuseNotFoundError, StringNoHTML } from "@langfuse/shared";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import { apiKeyCreationRoleSchema } from "@/src/features/public-api/server/apiKeyCreationRoleSchema";export const projectApiKeysRouter = createTRPCRouter({@@ -82,7 +87,8 @@ export const projectApiKeysRouter = createTRPCRouter({});const apiKeyMeta = await createApiKey(ctx.prisma, {- owner: ProjectId(input.projectId),+ tenant: OrganizationId(ctx.session.orgId),+ scope: ProjectId(input.projectId),role: SystemRoleId(input.role),createdBy: UserId(ctx.session.user.id),name: input.name,diff --git a/web/src/features/rbac/server/membersRouter.ts b/web/src/features/rbac/server/membersRouter.tsindex c27b7d79c7..7f0a85d09b 100644--- a/web/src/features/rbac/server/membersRouter.ts+++ b/web/src/features/rbac/server/membersRouter.ts@@ -35,6 +35,11 @@ import {} from "@/src/features/rbac/utils/checkProjectAccess";import { allMembersRoutes } from "@/src/features/rbac/server/allMembersRoutes";import { allInvitesRoutes } from "@/src/features/rbac/server/allInvitesRoutes";+import {+ deleteUserBoundApiKeys,+ deleteUserBoundApiKeysForRole,+ evictRevokedApiKeys,+} from "@/src/features/ai-gateway/server/apiKey/userBoundApiKeys";import { orderedRoles } from "@/src/features/rbac/constants/orderedRoles";import {userFeaturePreviewFlags,@@ -571,12 +576,22 @@ export const membersRouter = createTRPCRouter({before: orgMembership,});- const deleted = await ctx.prisma.organizationMembership.delete({- where: {- id: orgMembership.id,- orgId: input.orgId,+ const { deleted, revokedKeys } = await ctx.prisma.$transaction(+ async (tx) => {+ const deleted = await tx.organizationMembership.delete({+ where: {+ id: orgMembership.id,+ orgId: input.orgId,+ },+ });+ const revokedKeys = await deleteUserBoundApiKeys(tx, {+ userId: orgMembership.userId,+ orgId: input.orgId,+ });+ return { deleted, revokedKeys };},- });+ );+ await evictRevokedApiKeys(revokedKeys, { session: ctx.session });// SFDC: remove the org-member bridge.await getSfdcService()?.removeUser({@@ -699,15 +714,26 @@ export const membersRouter = createTRPCRouter({});}- const updatedMembership = await ctx.prisma.organizationMembership.update({- where: {- id: membership.id,- orgId: input.orgId,- },- data: {- role: input.role,+ const { updatedMembership, revokedKeys } = await ctx.prisma.$transaction(+ async (tx) => {+ const updatedMembership = await tx.organizationMembership.update({+ where: {+ id: membership.id,+ orgId: input.orgId,+ },+ data: {+ role: input.role,+ },+ });+ const revokedKeys = await deleteUserBoundApiKeysForRole(tx, {+ userId: membership.userId,+ orgId: input.orgId,+ role: input.role,+ });+ return { updatedMembership, revokedKeys };},- });+ );+ await evictRevokedApiKeys(revokedKeys, { session: ctx.session });await auditLog({session: ctx.session,diff --git a/web/src/initialize.ts b/web/src/initialize.tsindex c0a856e370..2d0995280f 100644--- a/web/src/initialize.ts+++ b/web/src/initialize.ts@@ -5,7 +5,12 @@ 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 {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import {initializeClickhouseCompatibility,logger,@@ -204,7 +209,8 @@ if (env.LANGFUSE_INIT_ORG_ID) {existingApiKey.projectId !== env.LANGFUSE_INIT_PROJECT_ID) {await createApiKey(prisma, {- owner: ProjectId(env.LANGFUSE_INIT_PROJECT_ID),+ tenant: OrganizationId(env.LANGFUSE_INIT_ORG_ID),+ scope: ProjectId(env.LANGFUSE_INIT_PROJECT_ID),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: initUserId ? UserId(initUserId) : "system",name: "Provisioned API Key",diff --git a/web/src/pages/api/public/scim/Users/[id].ts b/web/src/pages/api/public/scim/Users/[id].tsindex d23febf0ca..703da3a15e 100644--- a/web/src/pages/api/public/scim/Users/[id].ts+++ b/web/src/pages/api/public/scim/Users/[id].ts@@ -1,5 +1,10 @@import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { auditLog } from "@/src/features/audit-logs/server";+import {+ deleteUserBoundApiKeys,+ deleteUserBoundApiKeysForRole,+ evictRevokedApiKeys,+} from "@/src/features/ai-gateway/server/apiKey/userBoundApiKeys";import { Prisma, prisma, type User, type Role } from "@langfuse/shared/src/db";import { logger } from "@langfuse/shared/src/server";import { isBaseError, LangfuseConflictError } from "@langfuse/shared";@@ -91,7 +96,17 @@ async function provisionMembership({where: { orgId_userId: { orgId, userId } },data: { role: targetRole },});- return { t: "updated" as const, before: current, after: updated };+ const revokedKeys = await deleteUserBoundApiKeysForRole(tx, {+ userId,+ orgId,+ role: targetRole,+ });+ return {+ t: "updated" as const,+ before: current,+ after: updated,+ revokedKeys,+ };},{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },);@@ -103,6 +118,7 @@ async function provisionMembership({return { kind: "unchanged", role: result.role };}+ await evictRevokedApiKeys(result.revokedKeys, { apiKeyId });await auditLog({resourceType: "orgMembership",resourceId: result.after.id,@@ -265,13 +281,15 @@ async function deprovisionOrReject(await tx.organizationMembership.delete({where: { orgId_userId: { orgId, userId } },});- return { result: "deleted" as const, membership };+ const revokedKeys = await deleteUserBoundApiKeys(tx, { userId, orgId });+ return { result: "deleted" as const, membership, revokedKeys };},{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },);// Only audit and sync when a membership was actually removed.if (outcome.result === "deleted") {+ await evictRevokedApiKeys(outcome.revokedKeys, { apiKeyId });await auditLog({resourceType: "orgMembership",resourceId: outcome.membership.id,diff --git a/web/src/server/api/routers/userAccount.ts b/web/src/server/api/routers/userAccount.tsindex a4f666e2d7..e7ac853cc6 100644--- a/web/src/server/api/routers/userAccount.ts+++ b/web/src/server/api/routers/userAccount.ts@@ -18,6 +18,10 @@ import {INTERNAL_FEATURE_FLAG,} from "@/src/features/feature-flags/server";import { advanceSessionsExpiredAtForUser } from "@/src/features/auth/lib/sessionExpiration";+import {+ deleteUserBoundApiKeys,+ evictRevokedApiKeys,+} from "@/src/features/ai-gateway/server/apiKey/userBoundApiKeys";const updateDisplayNameSchema = z.object({name: StringNoHTML.min(1, "Name cannot be empty").max(@@ -195,7 +199,7 @@ export const userAccountRouter = createTRPCRouter({// Wrap check and delete in a serializable transaction to prevent race conditions// when organization owners are removed concurrently- const sfdcRemovals = await ctx.prisma.$transaction(+ const { sfdcRemovals, revokedKeys } = await ctx.prisma.$transaction(async (tx) => {// Verify user can be deletedconst { canDelete } = await checkUserCanBeDeleted(userId, tx);@@ -220,21 +224,28 @@ export const userAccountRouter = createTRPCRouter({select: { orgId: true },});+ const revokedKeys = await deleteUserBoundApiKeys(tx, { userId });+// Delete the user (cascade will handle related records)await tx.user.delete({where: { id: userId },});- return memberships.map(({ orgId }) => ({- orgId,- email: user?.email,- }));+ return {+ sfdcRemovals: memberships.map(({ orgId }) => ({+ orgId,+ email: user?.email,+ })),+ revokedKeys,+ };},{isolationLevel: Prisma.TransactionIsolationLevel.Serializable,},);+ await evictRevokedApiKeys(revokedKeys, { userId });+// SFDC: remove every org-member bridge the cascade just deleted. After// commit so a rolled-back delete never desyncs SFDC; removeUser never// throws, so per-org failures cannot fail the mutation.diff --git a/worker/src/__tests__/dataRetentionProcessing.test.ts b/worker/src/__tests__/dataRetentionProcessing.test.tsindex effaf47990..19676b1fbc 100644--- a/worker/src/__tests__/dataRetentionProcessing.test.ts+++ b/worker/src/__tests__/dataRetentionProcessing.test.ts@@ -31,7 +31,12 @@ import { isEnterpriseLicenseAvailable } from "@langfuse/shared/src/server/ee/licimport { handleDataRetentionProcessingJob } from "../ee/dataRetention/handleDataRetentionProcessingJob";import { Job } from "bullmq";import { createApiKey } from "@langfuse/shared/src/server/auth/apiKeys";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import { InAppAgentRunStatus } from "@langfuse/shared/in-app-agent";import { InAppAgentRetentionCleaner } from "../features/in-app-agent-retention-cleaner";@@ -133,7 +138,8 @@ describe("DataRetentionProcessingJob", () => {},});const key = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(creator.id),isInAppAgentKey: true,diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.test.tsindex f6d143a964..3f1c1c43de 100644--- a/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.test.ts@@ -7,7 +7,12 @@ import { env as sharedEnv } from "@langfuse/shared/src/env";import { IN_APP_AGENT_TOOL_APPROVAL_EVENT_NAME } from "@langfuse/shared/in-app-agent";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 {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import { ResumeForwardedPropsSchema } from "./runtime/types";import { env } from "../../env";@@ -884,12 +889,13 @@ describe("executeInAppAgentRun", () => {});it("reconciles a stale RUNNING delivery and acknowledges without starting the agent loop", async () => {- const { projectId, run, user } = await seedBackgroundRun({+ const { projectId, orgId, run, user } = await seedBackgroundRun({status: "RUNNING",});const twoMinutesAgo = new Date(Date.now() - 2 * 60_000);const key = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),name: "stale-run mcp key",@@ -923,12 +929,13 @@ describe("executeInAppAgentRun", () => {});it("clears the MCP pointer on claim-miss even when the key row is already gone", async () => {- const { projectId, run, user } = await seedBackgroundRun({+ const { projectId, orgId, run, user } = await seedBackgroundRun({status: "RUNNING",});const twoMinutesAgo = new Date(Date.now() - 2 * 60_000);const key = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),name: "already-deleted mcp key",@@ -973,12 +980,13 @@ describe("executeInAppAgentRun", () => {});it("leaves a user project key intact when mcpApiKeyId points at it", async () => {- const { projectId, run, user } = await seedBackgroundRun({+ const { projectId, orgId, run, user } = await seedBackgroundRun({status: "RUNNING",});const twoMinutesAgo = new Date(Date.now() - 2 * 60_000);const userKey = await createApiKey(prisma, {- owner: ProjectId(projectId),+ tenant: OrganizationId(orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(user.id),name: "user project key",diff --git a/worker/src/features/in-app-agent/executeInAppAgentRun.ts b/worker/src/features/in-app-agent/executeInAppAgentRun.tsindex 650419e385..1d2dfb3e66 100644--- a/worker/src/features/in-app-agent/executeInAppAgentRun.ts+++ b/worker/src/features/in-app-agent/executeInAppAgentRun.ts@@ -12,7 +12,12 @@ import {createApiKey,deleteInAppAgentMcpApiKeyFromDb,} from "@langfuse/shared/src/server/auth/apiKeys";-import { ProjectId, SystemRoleId, UserId } from "@langfuse/shared/rbac";+import {+ OrganizationId,+ ProjectId,+ SystemRoleId,+ UserId,+} from "@langfuse/shared/rbac";import {InAppAgentRunErrorCode,InAppAgentRunRequestSchema,@@ -393,7 +398,8 @@ export async function executeInAppAgentRun(params: {// Link the key atomically to prevent orphan credentials.mcpApiKey = await prisma.$transaction(async (tx) => {const key = await createApiKey(tx, {- owner: ProjectId(projectId),+ tenant: OrganizationId(project.orgId),+ scope: ProjectId(projectId),role: SystemRoleId("LEGACY_PROJECT_API_KEY"),createdBy: UserId(triggeredByUserId),name: inAppAgentApiKeyName,