🪢 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
feat(api-keys): track creator of project and org API keys (#14724)
Steffen Schmitz422a9c5b3848
diff --git a/packages/shared/prisma/migrations/20260706000000_add_api_key_created_by/migration.sql b/packages/shared/prisma/migrations/20260706000000_add_api_key_created_by/migration.sqlnew file mode 100644index 0000000000..252a3b3409--- /dev/null+++ b/packages/shared/prisma/migrations/20260706000000_add_api_key_created_by/migration.sql@@ -0,0 +1,12 @@+-- AlterTable+ALTER TABLE "api_keys" ADD COLUMN "created_by_user_id" TEXT,+ADD COLUMN "created_by_api_key_id" TEXT;++-- CreateIndex+CREATE INDEX "api_keys_created_by_api_key_id_idx" ON "api_keys"("created_by_api_key_id");++-- AddForeignKey+ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_created_by_user_id_fkey" FOREIGN KEY ("created_by_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_created_by_api_key_id_fkey" FOREIGN KEY ("created_by_api_key_id") REFERENCES "api_keys"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 36aaea8fba..5d70d36907 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -79,6 +79,7 @@ model User {defaultViews DefaultView[] @relation("DefaultViewUser")inAppAgentConversations InAppAgentConversation[] @relation("InAppAgentConversationCreatedByUser")inAppAgentRuns InAppAgentRun[] @relation("InAppAgentRunTriggeredByUser")+ apiKeysCreated ApiKey[] @relation("ApiKeyCreatedByUser")@@map("users")}@@ -207,9 +208,15 @@ model ApiKey {orgId String? @map("organization_id")organization Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)scope ApiKeyScope @default(PROJECT) @map("scope")+ createdByUserId String? @map("created_by_user_id")+ createdByUser User? @relation("ApiKeyCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)+ createdByApiKeyId String? @map("created_by_api_key_id")+ createdByApiKey ApiKey? @relation("ApiKeyCreatedByApiKey", fields: [createdByApiKeyId], references: [id], onDelete: SetNull)+ apiKeysCreated ApiKey[] @relation("ApiKeyCreatedByApiKey")@@index(orgId)@@index(projectId)+ @@index(createdByApiKeyId)@@index(publicKey)@@index(hashedSecretKey)@@index(fastHashedSecretKey)diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.tsindex 60120697dc..2f9275e26b 100644--- a/packages/shared/src/server/auth/apiKeys.ts+++ b/packages/shared/src/server/auth/apiKeys.ts@@ -44,6 +44,10 @@ export async function createAndAddApiKeysToDb(p: {scope: ApiKeyScope;note?: string;isInAppAgentKey?: boolean;+ /** User who created the key, e.g. via the UI. */+ createdByUserId?: string;+ /** API key that created the key, e.g. an org-scoped key using the public API. */+ createdByApiKeyId?: string;predefinedKeys?: {secretKey: string;publicKey: string;@@ -76,6 +80,8 @@ export async function createAndAddApiKeysToDb(p: {note: p.note,scope: p.scope,isInAppAgentKey: p.isInAppAgentKey ?? false,+ createdByUserId: p.createdByUserId,+ createdByApiKeyId: p.createdByApiKeyId,},});diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex fb34c6f2dc..ca32736b35 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -18,6 +18,10 @@ const ApiKeyBaseSchema = z.object({rateLimitOverrides: CloudConfigRateLimit.nullish(),isIngestionSuspended: z.boolean().nullish(),isInAppAgentKey: z.boolean().default(false),+ // nullish for backward compatibility with cache entries written before+ // these columns existed+ createdByUserId: z.string().nullish(),+ createdByApiKeyId: z.string().nullish(),});export const OrgEnrichedApiKey = z.discriminatedUnion("scope", [diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.tsindex 1eb90a52be..f8d0874252 100644--- a/web/src/__tests__/server/api-auth.servertest.ts+++ b/web/src/__tests__/server/api-auth.servertest.ts@@ -683,6 +683,8 @@ describe("Authenticate API calls", () => {expiresAt: null,isIngestionSuspended: expect.anything(),isInAppAgentKey: false,+ createdByUserId: null,+ createdByApiKeyId: null,projectId: expect.any(String),orgId: testApiKey.orgId,plan: "cloud:hobby",diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.tsindex ca4927f198..753b54cfa0 100644--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts@@ -8,6 +8,23 @@ import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server";describe("organization API keys trpc", () => {const organizationId = "seed-org-id";+ // The session user is persisted as the API key creator, so it must exist+ // in the database (CI does not run the seeder that creates user-1).+ // createMany + skipDuplicates is atomic, so concurrently running test+ // files can ensure the user without racing each other.+ beforeAll(async () => {+ await prisma.user.createMany({+ data: [+ {+ id: "user-1",+ name: "Demo User",+ email: "[email protected]",+ },+ ],+ skipDuplicates: true,+ });+ });+const ownerSession: Session = {expires: "1",user: {@@ -179,6 +196,26 @@ describe("organization API keys trpc", () => {expect(apiKeyResult.note).toBe("Test API Key");});+ it("stores the creating user and returns it in the list", async () => {+ const apiKeyResult = await ownerCaller.organizationApiKeys.create({+ orgId: organizationId,+ note: "Key for creator attribution test",+ });++ const dbKey = await prisma.apiKey.findUniqueOrThrow({+ where: { id: apiKeyResult.id },+ });+ expect(dbKey.createdByUserId).toBe("user-1");+ expect(dbKey.createdByApiKeyId).toBeNull();++ const apiKeys = await ownerCaller.organizationApiKeys.byOrganizationId({+ orgId: organizationId,+ });+ const listedKey = apiKeys.find((key) => key.id === apiKeyResult.id);+ expect(listedKey?.createdByUser?.id).toBe("user-1");+ expect(listedKey?.createdByApiKey).toBeNull();+ });+it("regular member cannot create organization API keys", async () => {await expect(memberCaller.organizationApiKeys.create({diff --git a/web/src/__tests__/server/project-api-key-trpc.servertest.ts b/web/src/__tests__/server/project-api-key-trpc.servertest.tsindex 9c354c873a..24843c4041 100644--- a/web/src/__tests__/server/project-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/project-api-key-trpc.servertest.ts@@ -8,6 +8,23 @@ import {} from "@langfuse/shared/src/server";describe("project API keys trpc", () => {+ // The session user is persisted as the API key creator, so it must exist+ // in the database (CI does not run the seeder that creates user-1).+ // createMany + skipDuplicates is atomic, so concurrently running test+ // files can ensure the user without racing each other.+ beforeAll(async () => {+ await prisma.user.createMany({+ data: [+ {+ id: "user-1",+ name: "Demo User",+ email: "[email protected]",+ },+ ],+ skipDuplicates: true,+ });+ });+async function createProjectCaller() {const { projectId, orgId } = await createOrgProjectAndApiKey();@@ -72,6 +89,28 @@ describe("project API keys trpc", () => {});});+ describe("projectApiKeys.create", () => {+ it("stores the creating user and returns it in the list", async () => {+ const { caller, projectId } = await createProjectCaller();++ const apiKeyResult = await caller.projectApiKeys.create({+ projectId,+ note: "Key for creator attribution test",+ });++ const dbKey = await prisma.apiKey.findUniqueOrThrow({+ where: { id: apiKeyResult.id },+ });+ expect(dbKey.createdByUserId).toBe("user-1");+ expect(dbKey.createdByApiKeyId).toBeNull();++ const apiKeys = await caller.projectApiKeys.byProjectId({ projectId });+ const listedKey = apiKeys.find((key) => key.id === apiKeyResult.id);+ expect(listedKey?.createdByUser?.id).toBe("user-1");+ expect(listedKey?.createdByApiKey).toBeNull();+ });+ });+describe("projectApiKeys.updateNote", () => {it("does not update in-app agent API keys", async () => {const { caller, projectId } = await createProjectCaller();diff --git a/web/src/__tests__/server/projects-api.servertest.ts b/web/src/__tests__/server/projects-api.servertest.tsindex bc68764f56..e5e67afdb0 100644--- a/web/src/__tests__/server/projects-api.servertest.ts+++ b/web/src/__tests__/server/projects-api.servertest.ts@@ -874,6 +874,13 @@ describe("Projects API", () => {expect(apiKey?.note).toBe(note);expect(apiKey?.projectId).toBe(projectId);expect(apiKey?.scope).toBe("PROJECT");++ // Verify the creating org API key is referenced+ const orgKeyRecord = await prisma.apiKey.findUnique({+ where: { publicKey: orgApiKey },+ });+ expect(apiKey?.createdByApiKeyId).toBe(orgKeyRecord?.id);+ expect(apiKey?.createdByUserId).toBeNull();});it("should return 403 when using project API key instead of organization API key", async () => {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 a15f32d392..5f3b6e2e5b 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@@ -49,6 +49,7 @@ export async function handleCreateApiKey(res: NextApiResponse,projectId: string,orgId: string,+ createdByApiKeyId?: string,) {// Validate the request bodyconst createApiKeySchema = z.object({@@ -99,6 +100,7 @@ export async function handleCreateApiKey(entityId: projectId,note,scope: "PROJECT",+ createdByApiKeyId,predefinedKeys:publicKey && secretKey ? { publicKey, secretKey } : undefined,});diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.tsindex be8564a6f7..b56d969caa 100644--- a/web/src/ee/features/in-app-agent/server/handler.ts+++ b/web/src/ee/features/in-app-agent/server/handler.ts@@ -267,6 +267,7 @@ export default async function handler(request: Request) {{projectId,runId: sanitizedInput.runId,+ userId,toolName: getInAppAgentMcpRegistryToolName(resumeApprovalRequest?.toolName,),@@ -643,18 +644,27 @@ function getLangfuseMcpUrl(): string {return baseUrl.toString();}-async function createInAppAgentMcpApiKey(projectId: string) {+async function createInAppAgentMcpApiKey(+ projectId: string,+ createdByUserId: string,+) {return createAndAddApiKeysToDb({prisma,entityId: projectId,scope: "PROJECT",note: IN_APP_AGENT_API_KEY_NOTE,isInAppAgentKey: true,+ createdByUserId,});}async function withInAppAgentMcpApiKeyCleanup<T>(- params: { projectId: string; runId: string; toolName?: McpToolName },+ params: {+ projectId: string;+ runId: string;+ userId: string;+ toolName?: McpToolName;+ },createResponse: (mcpApiKey: Awaited<ReturnType<typeof createInAppAgentMcpApiKey>>,runOverride: string | undefined,@@ -663,7 +673,10 @@ async function withInAppAgentMcpApiKeyCleanup<T>(): Promise<T> {// Each run gets a temporary in-app-agent API key. Approved MCP resumes also// get a tool-scoped run override for the single mutating registry tool.- const mcpApiKey = await createInAppAgentMcpApiKey(params.projectId);+ const mcpApiKey = await createInAppAgentMcpApiKey(+ params.projectId,+ params.userId,+ );let cleanupPromise: Promise<void> | undefined;const cleanupMcpApiKey = () => {diff --git a/web/src/features/public-api/components/ApiKeyList.tsx b/web/src/features/public-api/components/ApiKeyList.tsxindex ffea4b7701..21b4811e66 100644--- a/web/src/features/public-api/components/ApiKeyList.tsx+++ b/web/src/features/public-api/components/ApiKeyList.tsx@@ -26,6 +26,14 @@ import { useLangfuseEnvCode } from "@/src/features/public-api/hooks/useLangfuseEtype ApiKeyScope = "project" | "organization";type ApiKeyEntity = { id: string; note: string | null };+type ApiKeyCreator = {+ createdByUser: {+ id: string;+ name: string | null;+ email: string | null;+ } | null;+ createdByApiKey: { id: string; publicKey: string } | null;+};export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {const { entityId, scope } = props;@@ -100,6 +108,9 @@ export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {<TableHead className="text-primary hidden md:table-cell">Created</TableHead>+ <TableHead className="text-primary hidden md:table-cell">+ Created By+ </TableHead><TableHead className="text-primary">Note</TableHead><TableHead className="text-primary">Public Key</TableHead><TableHead className="text-primary">Secret Key</TableHead>@@ -112,7 +123,7 @@ export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {<TableRow><TableCelldensity="comfortable"- colSpan={5}+ colSpan={6}className="text-center">None@@ -130,6 +141,12 @@ export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {>{apiKey.createdAt.toLocaleDateString()}</TableCell>+ <TableCell+ density="comfortable"+ className="hidden md:table-cell"+ >+ <ApiKeyCreatedBy apiKey={apiKey} />+ </TableCell><TableCell density="comfortable"><ApiKeyNoteapiKey={apiKey}@@ -248,6 +265,28 @@ function DeleteApiKeyButton(props: {);}+function ApiKeyCreatedBy({ apiKey }: { apiKey: ApiKeyCreator }) {+ if (apiKey.createdByUser) {+ const { name, email } = apiKey.createdByUser;+ return (+ <span className="truncate" title={email ?? undefined}>+ {name ?? email ?? "Unknown user"}+ </span>+ );+ }+ if (apiKey.createdByApiKey) {+ return (+ <span+ className="truncate font-mono"+ title={`Created via API by key ${apiKey.createdByApiKey.publicKey}`}+ >+ {apiKey.createdByApiKey.publicKey}+ </span>+ );+ }+ return <span>—</span>;+}+function ApiKeyNote({apiKey,entityId,diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.tsindex 1f155d0c02..c6ee1a1bb5 100644--- a/web/src/features/public-api/server/organizationApiKeyRouter.ts+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts@@ -37,6 +37,19 @@ export const organizationApiKeysRouter = createTRPCRouter({note: true,publicKey: true,displaySecretKey: true,+ createdByUser: {+ select: {+ id: true,+ name: true,+ email: true,+ },+ },+ createdByApiKey: {+ select: {+ id: true,+ publicKey: true,+ },+ },},orderBy: {createdAt: "asc",@@ -62,6 +75,7 @@ export const organizationApiKeysRouter = createTRPCRouter({entityId: input.orgId,note: input.note,scope: "ORGANIZATION",+ createdByUserId: ctx.session.user.id,});await auditLog({diff --git a/web/src/features/public-api/server/projectApiKeyRouter.ts b/web/src/features/public-api/server/projectApiKeyRouter.tsindex 5e8cce04c4..8b638198c7 100644--- a/web/src/features/public-api/server/projectApiKeyRouter.ts+++ b/web/src/features/public-api/server/projectApiKeyRouter.ts@@ -38,6 +38,19 @@ export const projectApiKeysRouter = createTRPCRouter({note: true,publicKey: true,displaySecretKey: true,+ createdByUser: {+ select: {+ id: true,+ name: true,+ email: true,+ },+ },+ createdByApiKey: {+ select: {+ id: true,+ publicKey: true,+ },+ },},orderBy: {createdAt: "asc",@@ -63,6 +76,7 @@ export const projectApiKeysRouter = createTRPCRouter({entityId: input.projectId,note: input.note,scope: "PROJECT",+ createdByUserId: ctx.session.user.id,});await auditLog({diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.tsindex 94d3d8436d..f6cafd54a9 100644--- a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts@@ -95,6 +95,7 @@ export default async function handler(res,projectId,authCheck.scope.orgId,+ authCheck.scope.apiKeyId,);default:res.status(405).json({ message: "Method Not Allowed" });