🪢 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: add api key actions to auditlog table (#5932)
Steffen Schmitz286b78a1feca
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 45178c36cb..2603cf9564 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -59,6 +59,11 @@ export const CommentObjectType = {PROMPT: "PROMPT"} as const;export type CommentObjectType = (typeof CommentObjectType)[keyof typeof CommentObjectType];+export const AuditLogRecordType = {+ USER: "USER",+ API_KEY: "API_KEY"+} as const;+export type AuditLogRecordType = (typeof AuditLogRecordType)[keyof typeof AuditLogRecordType];export const JobType = {EVAL: "EVAL"} as const;@@ -132,9 +137,11 @@ export type AuditLog = {id: string;created_at: Generated<Timestamp>;updated_at: Generated<Timestamp>;- user_id: string;+ type: Generated<AuditLogRecordType>;+ api_key_id: string | null;+ user_id: string | null;org_id: string;- user_org_role: string;+ user_org_role: string | null;project_id: string | null;user_project_role: string | null;resource_type: string;diff --git a/packages/shared/prisma/migrations/20250310100328_add_api_key_to_audit_log/migration.sql b/packages/shared/prisma/migrations/20250310100328_add_api_key_to_audit_log/migration.sqlnew file mode 100644index 0000000000..8750221d63--- /dev/null+++ b/packages/shared/prisma/migrations/20250310100328_add_api_key_to_audit_log/migration.sql@@ -0,0 +1,11 @@+-- CreateEnum+CREATE TYPE "AuditLogRecordType" AS ENUM ('USER', 'API_KEY');++-- AlterTable+ALTER TABLE "audit_logs" ADD COLUMN "api_key_id" TEXT,+ADD COLUMN "type" "AuditLogRecordType" NOT NULL DEFAULT 'USER',+ALTER COLUMN "user_id" DROP NOT NULL,+ALTER COLUMN "user_org_role" DROP NOT NULL;++-- CreateIndex+CREATE INDEX "audit_logs_api_key_id_idx" ON "audit_logs"("api_key_id");diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 6a97d5f004..a13b031c02 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -696,23 +696,31 @@ model Price {@@map("prices")}+enum AuditLogRecordType {+ USER+ API_KEY+}+// No FK constraints to preserve audit logsmodel AuditLog {- id String @id @default(cuid())- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")- userId String @map("user_id")- orgId String @map("org_id")- userOrgRole String @map("user_org_role")- projectId String? @map("project_id")- userProjectRole String? @map("user_project_role")- resourceType String @map("resource_type")- resourceId String @map("resource_id")+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ type AuditLogRecordType @default(USER)+ apiKeyId String? @map("api_key_id")+ userId String? @map("user_id")+ orgId String @map("org_id")+ userOrgRole String? @map("user_org_role")+ projectId String? @map("project_id")+ userProjectRole String? @map("user_project_role")+ resourceType String @map("resource_type")+ resourceId String @map("resource_id")action String- before String? //stringified JSON+ before String? // stringified JSONafter String? // stringified JSON@@index([projectId])+ @@index([apiKeyId])@@index([userId])@@index([orgId])@@index([createdAt])diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex b684c67072..a740e4a419 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -43,4 +43,5 @@ export type ApiAccessScope = {orgId: string;plan: Plan;rateLimitOverrides: z.infer<typeof CloudConfigRateLimit>;+ apiKeyId: string;};diff --git a/web/src/ee/features/audit-log-viewer/AuditLogsTable.tsx b/web/src/ee/features/audit-log-viewer/AuditLogsTable.tsxindex 60ee154071..89ab62fad9 100644--- a/web/src/ee/features/audit-log-viewer/AuditLogsTable.tsx+++ b/web/src/ee/features/audit-log-viewer/AuditLogsTable.tsx@@ -39,30 +39,47 @@ export function AuditLogsTable(props: { projectId: string }) {},},{- accessorKey: "user",- header: "User",+ accessorKey: "actor",+ header: "Actor",headerTooltip: {- description: "The user within Langfuse who performed the action.",+ description: "The actor within Langfuse who performed the action.",},cell: (row) => {- const user = row.getValue() as AuditLogRow["user"];- return (- <div className="flex items-center gap-2">- <Avatar className="h-6 w-6">- {user?.image && (- <AvatarImage src={user.image} alt={user?.name ?? "User"} />- )}- <AvatarFallback>- {user?.name?.charAt(0) ?? user?.email?.charAt(0) ?? "U"}- </AvatarFallback>- </Avatar>- <span- className={cn("text-sm", !user?.name && "text-muted-foreground")}- >- {user?.name ?? user?.email ?? user.id}- </span>- </div>- );+ const actor = row.getValue() as AuditLogRow["actor"];+ if (actor.type === "USER") {+ const user = actor.body;+ return (+ <div className="flex items-center gap-2">+ <Avatar className="h-6 w-6">+ {user?.image && (+ <AvatarImage src={user.image} alt={user?.name ?? "User"} />+ )}+ <AvatarFallback>+ {user?.name?.charAt(0) ?? user?.email?.charAt(0) ?? "U"}+ </AvatarFallback>+ </Avatar>+ <span+ className={cn(+ "text-sm",+ !user?.name && "text-muted-foreground",+ )}+ >+ {user?.name ?? user?.email ?? user.id}+ </span>+ </div>+ );+ }++ if (actor.type === "API_KEY") {+ const apiKey = actor.body;+ return (+ <div className="flex items-center gap-2">+ <span className="text-sm">{apiKey?.publicKey ?? apiKey?.id}</span>+ </div>+ );+ }++ return null;},},{diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex 31349b9ab2..31da3540e3 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -1,4 +1,8 @@-import { prisma as _prisma, type Role } from "@langfuse/shared/src/db";+import {+ prisma as _prisma,+ type Role,+ AuditLogRecordType,+} from "@langfuse/shared/src/db";export type AuditableResource =| "annotationQueue"@@ -40,7 +44,7 @@ type AuditLog = {| {userId: string;orgId: string;- orgRole: Role;+ orgRole?: Role;projectId?: string;projectRole?: Role;}@@ -50,11 +54,16 @@ type AuditLog = {id: string;};orgId: string;- orgRole: Role;+ orgRole?: Role;projectId?: string;projectRole?: Role;};}+ | {+ apiKeyId: string;+ orgId: string;+ projectId?: string;+ });export async function auditLog(log: AuditLog, prisma?: typeof _prisma) {@@ -66,14 +75,23 @@ export async function auditLog(log: AuditLog, prisma?: typeof _prisma) {userOrgRole: log.session.orgRole,projectId: log.session.projectId,userProjectRole: log.session.projectRole,+ type: AuditLogRecordType.USER,}- : {- userId: log.userId,- orgId: log.orgId,- userOrgRole: log.orgRole,- projectId: log.projectId,- userProjectRole: log.projectRole,- };+ : "userId" in log+ ? {+ userId: log.userId,+ orgId: log.orgId,+ userOrgRole: log.orgRole,+ projectId: log.projectId,+ userProjectRole: log.projectRole,+ type: AuditLogRecordType.USER,+ }+ : {+ apiKeyId: log.apiKeyId,+ orgId: log.orgId,+ projectId: log.projectId,+ type: AuditLogRecordType.API_KEY,+ };await (prisma ?? _prisma).auditLog.create({data: {diff --git a/web/src/features/prompts/server/handlers/promptVersionHandler.ts b/web/src/features/prompts/server/handlers/promptVersionHandler.tsindex d59eb7f9f3..a238c648e7 100644--- a/web/src/features/prompts/server/handlers/promptVersionHandler.ts+++ b/web/src/features/prompts/server/handlers/promptVersionHandler.ts@@ -5,6 +5,7 @@ import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewareimport { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";import { updatePrompt } from "@/src/features/prompts/server/actions/updatePrompts";import { LangfuseNotFoundError } from "@langfuse/shared";+import { auditLog } from "@/src/features/audit-logs/auditLog";const UpdatePromptBodySchema = z.object({newLabels: z@@ -31,6 +32,15 @@ export const promptVersionHandler = withMiddlewares({newLabels,});+ await auditLog({+ action: "update",+ resourceType: "prompt",+ resourceId: prompt.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ });+logger.info(`Prompt updated ${JSON.stringify(prompt)}`);return res.status(200).json(prompt);diff --git a/web/src/features/prompts/server/handlers/promptsHandler.ts b/web/src/features/prompts/server/handlers/promptsHandler.tsindex 7cfd14bf61..eac3200863 100644--- a/web/src/features/prompts/server/handlers/promptsHandler.ts+++ b/web/src/features/prompts/server/handlers/promptsHandler.ts@@ -11,6 +11,7 @@ import { prisma } from "@langfuse/shared/src/db";import { authorizePromptRequestOrThrow } from "../utils/authorizePromptRequest";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";import { InvalidRequestError } from "@langfuse/shared";+import { auditLog } from "@/src/features/audit-logs/auditLog";const getPromptsHandler = async (req: NextApiRequest, res: NextApiResponse) => {const authCheck = await authorizePromptRequestOrThrow(req);@@ -69,6 +70,16 @@ const postPromptsHandler = async (throw err;});+ await auditLog({+ action: "create",+ resourceType: "prompt",+ resourceId: createdPrompt.id,+ projectId: authCheck.scope.projectId,+ orgId: authCheck.scope.orgId,+ apiKeyId: authCheck.scope.apiKeyId,+ after: createdPrompt,+ });+return res.status(201).json(createdPrompt);};diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 18126f9024..688c055644 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -193,6 +193,7 @@ export class ApiAuthService {orgId: finalApiKey.orgId,plan: plan,rateLimitOverrides: finalApiKey.rateLimitOverrides ?? [],+ apiKeyId: finalApiKey.id,},};}@@ -216,6 +217,7 @@ export class ApiAuthService {orgId: dbKey.project.organization.id,plan: getOrganizationPlanServerSide(cloudConfig),rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],+ apiKeyId: dbKey.id,},};}diff --git a/web/src/pages/api/public/comments/index.ts b/web/src/pages/api/public/comments/index.tsindex 74f0fda108..6b9bb49de8 100644--- a/web/src/pages/api/public/comments/index.ts+++ b/web/src/pages/api/public/comments/index.ts@@ -10,6 +10,7 @@ import { prisma } from "@langfuse/shared/src/db";import { v4 } from "uuid";import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";import { LangfuseNotFoundError } from "@langfuse/shared";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({POST: createAuthedAPIRoute({@@ -34,6 +35,16 @@ export default withMiddlewares({},});+ await auditLog({+ action: "create",+ resourceType: "comment",+ resourceId: comment.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ after: comment,+ });+return { id: comment.id };},}),diff --git a/web/src/pages/api/public/dataset-items/[datasetItemId].ts b/web/src/pages/api/public/dataset-items/[datasetItemId].tsindex 17d67a21f2..69859301fd 100644--- a/web/src/pages/api/public/dataset-items/[datasetItemId].ts+++ b/web/src/pages/api/public/dataset-items/[datasetItemId].ts@@ -9,6 +9,7 @@ import {transformDbDatasetItemToAPIDatasetItem,} from "@/src/features/public-api/types/datasets";import { LangfuseNotFoundError } from "@langfuse/shared";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({GET: createAuthedAPIRoute({@@ -76,6 +77,16 @@ export default withMiddlewares({},});+ await auditLog({+ action: "delete",+ resourceType: "datasetItem",+ resourceId: datasetItemId,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ before: datasetItem,+ });+return {message: "Dataset item successfully deleted" as const,};diff --git a/web/src/pages/api/public/dataset-items/index.ts b/web/src/pages/api/public/dataset-items/index.tsindex 6ea6177cdc..a1f4cd7768 100644--- a/web/src/pages/api/public/dataset-items/index.ts+++ b/web/src/pages/api/public/dataset-items/index.ts@@ -15,6 +15,7 @@ import {Prisma,} from "@langfuse/shared";import { logger } from "@langfuse/shared/src/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({POST: createAuthedAPIRoute({@@ -94,6 +95,16 @@ export default withMiddlewares({throw e;}+ await auditLog({+ action: "create",+ resourceType: "datasetItem",+ resourceId: item.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ after: item,+ });+return transformDbDatasetItemToAPIDatasetItem({...item,datasetName: dataset.name,diff --git a/web/src/pages/api/public/datasets/[name]/runs/[runName].ts b/web/src/pages/api/public/datasets/[name]/runs/[runName].tsindex 17ec7b4dde..2b52cfe5d2 100644--- a/web/src/pages/api/public/datasets/[name]/runs/[runName].ts+++ b/web/src/pages/api/public/datasets/[name]/runs/[runName].ts@@ -10,6 +10,7 @@ import {import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";import { ApiError, LangfuseNotFoundError } from "@langfuse/shared";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({GET: createAuthedAPIRoute({@@ -94,6 +95,16 @@ export default withMiddlewares({},});+ await auditLog({+ action: "delete",+ resourceType: "datasetRun",+ resourceId: datasetRun.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ before: datasetRun,+ });+return {message: "Dataset run successfully deleted" as const,};diff --git a/web/src/pages/api/public/models/[modelId]/index.ts b/web/src/pages/api/public/models/[modelId]/index.tsindex 52fb4b3c5c..81c524234c 100644--- a/web/src/pages/api/public/models/[modelId]/index.ts+++ b/web/src/pages/api/public/models/[modelId]/index.ts@@ -9,6 +9,7 @@ import {prismaToApiModelDefinition,} from "@/src/features/public-api/types/models";import { LangfuseNotFoundError } from "@langfuse/shared";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({GET: createAuthedAPIRoute({@@ -63,6 +64,15 @@ export default withMiddlewares({projectId: auth.scope.projectId,},});+ await auditLog({+ action: "delete",+ resourceType: "model",+ resourceId: query.modelId,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ before: model,+ });return {message: "Model successfully deleted" as const,};diff --git a/web/src/pages/api/public/models/index.ts b/web/src/pages/api/public/models/index.tsindex 1f3c5372d8..3e26ecb0ad 100644--- a/web/src/pages/api/public/models/index.ts+++ b/web/src/pages/api/public/models/index.ts@@ -10,6 +10,7 @@ import {} from "@/src/features/public-api/types/models";import { InvalidRequestError } from "@langfuse/shared";import { isValidPostgresRegex } from "@/src/features/models/server/isValidPostgresRegex";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({GET: createAuthedAPIRoute({@@ -108,6 +109,16 @@ export default withMiddlewares({),);+ await auditLog({+ action: "create",+ resourceType: "model",+ resourceId: createdModel.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ after: createdModel,+ });+return createdModel;});diff --git a/web/src/pages/api/public/score-configs/index.ts b/web/src/pages/api/public/score-configs/index.tsindex 69956c9b71..633ae203e8 100644--- a/web/src/pages/api/public/score-configs/index.ts+++ b/web/src/pages/api/public/score-configs/index.ts@@ -14,6 +14,7 @@ import {} from "@langfuse/shared";import { Prisma, prisma } from "@langfuse/shared/src/db";import { traceException } from "@langfuse/shared/src/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";const inflateConfigBody = (body: z.infer<typeof PostScoreConfigBody>) => {if (isBooleanDataType(body.dataType)) {@@ -45,6 +46,16 @@ export default withMiddlewares({},});+ await auditLog({+ action: "create",+ resourceType: "scoreConfig",+ resourceId: config.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ after: config,+ });+return validateDbScoreConfig(config);},}),diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].tsindex 01ffc41b4d..7f718fac1a 100644--- a/web/src/pages/api/public/scores/[scoreId].ts+++ b/web/src/pages/api/public/scores/[scoreId].ts@@ -14,6 +14,7 @@ import {logger,traceException,} from "@langfuse/shared/src/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({GET: createAuthedAPIRoute({@@ -45,6 +46,14 @@ export default withMiddlewares({fn: async ({ query, auth }) => {const { scoreId } = query;await deleteScore(auth.scope.projectId, scoreId);+ await auditLog({+ action: "delete",+ resourceType: "score",+ resourceId: scoreId,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ });return { message: "Score deleted successfully" };},}),diff --git a/web/src/pages/api/public/v2/datasets/index.ts b/web/src/pages/api/public/v2/datasets/index.tsindex 4bb1285bd8..3982d95f58 100644--- a/web/src/pages/api/public/v2/datasets/index.ts+++ b/web/src/pages/api/public/v2/datasets/index.ts@@ -7,6 +7,7 @@ import {} from "@/src/features/public-api/types/datasets";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({POST: createAuthedAPIRoute({@@ -35,6 +36,16 @@ export default withMiddlewares({},});+ await auditLog({+ action: "create",+ resourceType: "dataset",+ resourceId: dataset.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ after: dataset,+ });+return dataset;},}),diff --git a/web/src/server/api/routers/auditLogs.ts b/web/src/server/api/routers/auditLogs.tsindex d7c512392c..fbb8d9d17a 100644--- a/web/src/server/api/routers/auditLogs.ts+++ b/web/src/server/api/routers/auditLogs.ts@@ -3,6 +3,7 @@ import { createTRPCRouter, protectedProjectProcedure } from "../trpc";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";import { paginationZod } from "@langfuse/shared";+import { AuditLogRecordType } from "@langfuse/shared/src/db";export const auditLogsRouter = createTRPCRouter({all: protectedProjectProcedure@@ -46,44 +47,108 @@ export const auditLogsRouter = createTRPCRouter({]);// Fetch user information for each audit log- const userIds = [...new Set(auditLogs.map((log) => log.userId))];- const users = await ctx.prisma.user.findMany({- where: {- id: {- in: userIds,- },- organizationMemberships: {- some: {- organization: {- projects: {- some: {- id: input.projectId,+ const userIds = [+ ...new Set(+ auditLogs.flatMap((log) => (log?.userId ? [log.userId] : [])),+ ),+ ];+ const apiKeyIds = [+ ...new Set(+ auditLogs.flatMap((log) => (log?.apiKeyId ? [log.apiKeyId] : [])),+ ),+ ];++ const [users, apiKeys] = await Promise.all([+ ctx.prisma.user.findMany({+ where: {+ id: {+ in: userIds,+ },+ organizationMemberships: {+ some: {+ organization: {+ projects: {+ some: {+ id: input.projectId,+ },},},},},},- },- select: {- id: true,- name: true,- email: true,- image: true,- },- });+ select: {+ id: true,+ name: true,+ email: true,+ image: true,+ },+ }),+ ctx.prisma.apiKey.findMany({+ where: {+ id: {+ in: apiKeyIds,+ },+ projectId: input.projectId,+ },+ select: {+ id: true,+ publicKey: true,+ },+ }),+ ]);const userMap = new Map(users.map((user) => [user.id, user]));+ const apiKeyMap = new Map(apiKeys.map((apiKey) => [apiKey.id, apiKey]));return {- data: auditLogs.map((log) => ({- ...log,- user: userMap.get(log.userId) ?? {- id: log.userId,- name: null,- email: null,- image: null,- },- })),+ data: auditLogs.map((log) => {+ let actor:+ | {+ type: "API_KEY";+ body: { id: string | null; publicKey: string | null };+ }+ | {+ type: "USER";+ body: {+ id: string | null;+ name: string | null;+ email: string | null;+ image: string | null;+ };+ }+ | null = null;+ switch (log.type) {+ case AuditLogRecordType.USER:+ actor = {+ type: log.type,+ body: userMap.get(log.userId ?? "") ?? {+ id: log.userId,+ name: null,+ email: null,+ image: null,+ },+ };+ break;+ case AuditLogRecordType.API_KEY:+ actor = {+ type: log.type,+ body: apiKeyMap.get(log.apiKeyId ?? "") ?? {+ id: log.apiKeyId,+ publicKey: null,+ },+ };+ break;+ default:+ /* eslint-disable-next-line @typescript-eslint/no-unused-vars */+ const exhaustiveCheckDefault: never = log.type;+ throw new Error(`Type ${log.type} not found`);+ }++ return {+ ...log,+ actor,+ };+ }),totalCount,};}),