🪢 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(web): gate audit log writes on the audit-logs entitlement (#18285)
Der Gerätd271677e3a3b
diff --git a/web/src/__tests__/server/audit-log-license-gate.servertest.ts b/web/src/__tests__/server/audit-log-license-gate.servertest.tsnew file mode 100644index 0000000000..fba4bb63f5--- /dev/null+++ b/web/src/__tests__/server/audit-log-license-gate.servertest.ts@@ -0,0 +1,137 @@+import { randomUUID } from "crypto";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ cloudRegion: undefined as string | undefined,+ licenseKey: undefined as string | undefined,+}));++// Exercise the real gate rather than mocking it away: spread the real env and+// override only the two values the gate reads, so the full+// env -> plan -> entitlement chain runs against a real database.+vi.mock("@/src/env.mjs", async (importOriginal) => {+ const original = (await importOriginal()) as { env: Record<string, unknown> };+ return {+ ...original,+ env: new Proxy(original.env, {+ get: (target, prop) => {+ if (prop === "NEXT_PUBLIC_LANGFUSE_CLOUD_REGION")+ return mocks.cloudRegion;+ if (prop === "LANGFUSE_EE_LICENSE_KEY") return mocks.licenseKey;+ return Reflect.get(target, prop);+ },+ }),+ };+});++import { auditLog } from "@/src/features/audit-logs/server";+import { prisma } from "@langfuse/shared/src/db";+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";+import { createOrgProjectAndApiKey, logger } from "@langfuse/shared/src/server";++/**+ * Audit log records are an enterprise feature, so they are only persisted when+ * the instance is licensed for them. The actor log line that mirrors each+ * record is operator telemetry and stays on every plan.+ */+describe("audit log license gate", () => {+ let orgId: string;+ let projectId: string;+ let apiKeyId: string;+ const userId = randomUUID();++ beforeEach(async () => {+ mocks.cloudRegion = undefined;+ mocks.licenseKey = undefined;++ const org = await createOrgProjectAndApiKey();+ orgId = org.orgId;+ projectId = org.projectId;+ apiKeyId = (+ await createAndAddApiKeysToDb({+ prisma,+ entityId: org.projectId,+ scope: "PROJECT",+ note: "License gate test key",+ })+ ).id;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ /** Writes one record per actor shape, returns how many were persisted. */+ const auditAllActorShapes = async () => {+ const resourceIds = [randomUUID(), randomUUID(), randomUUID()];++ await auditLog({+ action: "create",+ resourceType: "job",+ resourceId: resourceIds[0],+ orgId,+ projectId,+ apiKeyId,+ });+ await auditLog({+ action: "update",+ resourceType: "job",+ resourceId: resourceIds[1],+ session: { user: { id: userId }, orgId, projectId },+ });+ await auditLog({+ action: "delete",+ resourceType: "job",+ resourceId: resourceIds[2],+ userId,+ orgId,+ projectId,+ });++ return prisma.auditLog.count({+ where: { resourceId: { in: resourceIds } },+ });+ };++ describe("self-hosted", () => {+ it("persists records with an enterprise license key", async () => {+ mocks.licenseKey = "langfuse_ee_test";++ expect(await auditAllActorShapes()).toBe(3);+ });++ it("persists no records without a license key", async () => {+ expect(await auditAllActorShapes()).toBe(0);+ });++ it("persists no records on a pro license key", async () => {+ // self-hosted:pro does not carry the audit-logs entitlement, so it must+ // not persist records it cannot view either.+ mocks.licenseKey = "langfuse_pro_test";++ expect(await auditAllActorShapes()).toBe(0);+ });+ });++ describe("cloud", () => {+ it("persists records on every plan", async () => {+ mocks.cloudRegion = "US";++ expect(await auditAllActorShapes()).toBe(3);+ });+ });++ it("still logs actor info when records are not persisted", async () => {+ // The actor log line is operator telemetry, not the audited record: it+ // carries ids only (no before/after diff) and is the sole actor trail for+ // mutations that have no parallel logger call of their own.+ const info = vi.spyOn(logger, "info");++ expect(await auditAllActorShapes()).toBe(0);++ const actorLines = info.mock.calls.filter(([message]) =>+ String(message).startsWith("Audit log: job."),+ );+ expect(actorLines).toHaveLength(3);+ });+});diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex 7d1877e58f..6f51397ce9 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -8,6 +8,7 @@ import {formatSubmittedPublicKeyForLog,logger,} from "@langfuse/shared/src/server";+import { isAuditLogEnabled } from "@/src/features/audit-logs/isAuditLogEnabled";type AuditableResource =| "annotationQueue"@@ -134,14 +135,26 @@ export async function auditLog(log: AuditLog,prisma?: typeof _prisma | Prisma.TransactionClient,) {+ // Audit log records are an enterprise feature, so they are only persisted+ // when the instance is licensed for them. logAuditEvent below is deliberately+ // NOT gated: it is operator telemetry rather than the audited record itself+ // (ids only, no before/after diff), it is the sole actor trail for mutations+ // that have no parallel logger call of their own, and the actor logging added+ // alongside it elsewhere — batch actions, trace deletion — is ungated too.+ const persistRecord = isAuditLogEnabled();+const db = prisma ?? _prisma;- const shared = {+ // Defer JSON.stringify(before/after) until we know the record will be+ // persisted — a full prompt or observation object is non-trivial to+ // serialise, and unlicensed self-hosted instances call auditLog() on every+ // mutation only to discard it at the persistRecord gate below.+ const makeShared = () => ({resourceType: log.resourceType,resourceId: log.resourceId,action: log.action,before: log.before ? JSON.stringify(log.before) : undefined,after: log.after ? JSON.stringify(log.after) : undefined,- };+ });if ("apiKeyId" in log) {// Sequential find + create, not $transaction. Interactive transactions@@ -161,6 +174,18 @@ export async function auditLog(? (apiKey.createdByUserId ?? undefined): undefined;+ // Actor telemetry is ungated — see top-of-function comment.+ logAuditEvent(log, {+ type: AuditLogRecordType.API_KEY,+ orgId: log.orgId,+ projectId: log.projectId,+ userId,+ apiKeyId: log.apiKeyId,+ publicKey: apiKey?.publicKey,+ });++ if (!persistRecord) return;+await db.auditLog.create({data: {apiKeyId: log.apiKeyId,@@ -168,23 +193,24 @@ export async function auditLog(orgId: log.orgId,projectId: log.projectId,type: AuditLogRecordType.API_KEY,- ...shared,+ ...makeShared(),},});- logAuditEvent(log, {- type: AuditLogRecordType.API_KEY,- orgId: log.orgId,- projectId: log.projectId,- userId,- apiKeyId: log.apiKeyId,- publicKey: apiKey?.publicKey,- });-return;}if ("session" in log) {+ // Actor telemetry is ungated — see top-of-function comment.+ logAuditEvent(log, {+ type: AuditLogRecordType.USER,+ orgId: log.session.orgId,+ projectId: log.session.projectId,+ userId: log.session.user.id,+ });++ if (!persistRecord) return;+await db.auditLog.create({data: {userId: log.session.user.id,@@ -193,21 +219,24 @@ export async function auditLog(projectId: log.session.projectId,userProjectRole: log.session.projectRole,type: AuditLogRecordType.USER,- ...shared,+ ...makeShared(),},});+ return;+ }++ if ("userId" in log) {+ // Actor telemetry is ungated — see top-of-function comment.logAuditEvent(log, {type: AuditLogRecordType.USER,- orgId: log.session.orgId,- projectId: log.session.projectId,- userId: log.session.user.id,+ orgId: log.orgId,+ projectId: log.projectId,+ userId: log.userId,});- return;- }+ if (!persistRecord) return;- if ("userId" in log) {await db.auditLog.create({data: {userId: log.userId,@@ -216,17 +245,10 @@ export async function auditLog(projectId: log.projectId,userProjectRole: log.projectRole,type: AuditLogRecordType.USER,- ...shared,+ ...makeShared(),},});- logAuditEvent(log, {- type: AuditLogRecordType.USER,- orgId: log.orgId,- projectId: log.projectId,- userId: log.userId,- });-return;}}diff --git a/web/src/features/audit-logs/isAuditLogEnabled.ts b/web/src/features/audit-logs/isAuditLogEnabled.tsnew file mode 100644index 0000000000..fe3dd10369--- /dev/null+++ b/web/src/features/audit-logs/isAuditLogEnabled.ts@@ -0,0 +1,37 @@+import { env } from "@/src/env.mjs";+import {+ getSelfHostedInstancePlanServerSide,+ hasEntitlementBasedOnPlan,+} from "@/src/features/entitlements/server";++/**+ * Whether audit log records may be persisted on this instance.+ *+ * Audit logs are an enterprise feature. Reading them is already gated on the+ * `audit-logs` entitlement (see `auditLogs` router and `batchExport`), but the+ * write path historically had no gate at all, so unlicensed self-hosted+ * instances accumulated records they can never view.+ *+ * The self-hosted branch derives from the same entitlement table the read path+ * uses, rather than hardcoding "enterprise license => audit logs", so the two+ * cannot drift apart. Today that means only `langfuse_ee_*` keys+ * (`self-hosted:enterprise`) persist records: `self-hosted:pro` and `oss` do+ * not. `isEnterpriseLicenseAvailable` in `@langfuse/shared` answers a similar+ * question for code that also runs in the worker, but hardcodes the license+ * tier instead of consulting the entitlement table.+ *+ * On Langfuse Cloud records are always written, on every plan. Retaining the+ * trail regardless of plan means upgrading to a plan that includes the audit+ * log viewer does not surface a gap in history.+ *+ * Synchronous and free of IO: both helpers read env that is parsed once at+ * startup, so this is safe to call on every mutation.+ */+export function isAuditLogEnabled(): boolean {+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined) return true;++ return hasEntitlementBasedOnPlan({+ plan: getSelfHostedInstancePlanServerSide(),+ entitlement: "audit-logs",+ });+}