Skip to content

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

feat(audit-logs): add the read-access audit gate and record two routes (#19211)

Steffen Reuther64982c0a8b47
diff --git a/.env.prod.example b/.env.prod.example
index 02f992bf88..6c000f8b19 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -450,6 +450,13 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# LANGFUSE_UI_VISIBLE_PRODUCT_MODULES=
# LANGFUSE_UI_HIDDEN_PRODUCT_MODULES=
+# Read-access audit events, requires an enterprise license.
+# org (default): recorded for organizations that enable access logging in their settings
+# enforced: recorded for every organization
+# disabled: never recorded
+# LANGFUSE_AUDIT_LOG_STAGING_ENABLED=false also stops recording.
+# LANGFUSE_AUDIT_LOG_ACCESS_EVENTS=org
+
### END Enterprise Edition Configuration
@@ -462,7 +469,8 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# Stages each audit event for ClickHouse next to its Postgres audit_logs row.
# Runs only when the cloud region above is set. Set to false to stop staging;
-# the Postgres row is written either way.
+# the Postgres row is written either way. Read-access events have no Postgres
+# row, so false also stops recording them, on any instance.
# LANGFUSE_AUDIT_LOG_STAGING_ENABLED=true
# Moves staged audit events from Postgres into ClickHouse. Runs only when the
diff --git a/packages/shared/prisma/migrations/20261022120000_add_organization_access_audit_log_enabled/migration.sql b/packages/shared/prisma/migrations/20261022120000_add_organization_access_audit_log_enabled/migration.sql
new file mode 100644
index 0000000000..fbbcabd921
--- /dev/null
+++ b/packages/shared/prisma/migrations/20261022120000_add_organization_access_audit_log_enabled/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "organizations" ADD COLUMN IF NOT EXISTS "access_audit_log_enabled" BOOLEAN NOT NULL DEFAULT false;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index a679b1cb8f..3a259c6640 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -123,6 +123,10 @@ model Organization {
cloudFreeTierUsageThresholdState String? @map("cloud_free_tier_usage_threshold_state")
aiFeaturesEnabled Boolean @default(false) @map("ai_features_enabled")
aiTelemetryEnabled Boolean @default(true) @map("ai_telemetry_enabled")
+ // Opt-in for read-access audit events (EE). Takes effect only when
+ // LANGFUSE_AUDIT_LOG_ACCESS_EVENTS is "org" and the org has the audit-logs
+ // entitlement.
+ accessAuditLogEnabled Boolean @default(false) @map("access_audit_log_enabled")
featureFlagOrgDefaults String[] @default([]) @map("feature_flag_org_defaults")
// SFDC Account / Organization ID returned by the Mulesoft org endpoint on
// Langfuse Cloud. NULL for self-hosted or pre-integration orgs. A mismatch
diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.ts
index 3eb05a323b..c9c4907c5b 100644
--- a/packages/shared/src/server/auth/types.ts
+++ b/packages/shared/src/server/auth/types.ts
@@ -21,6 +21,7 @@ const ApiKeyBaseSchema = z.object({
isInAppAgentKey: z.boolean().default(false),
// nullish for backward compatibility with cache entries written before
// these columns existed
+ accessAuditLogEnabled: z.boolean().nullish(),
createdByUserId: z.string().nullish(),
createdByApiKeyId: z.string().nullish(),
userId: z.string().nullish(),
@@ -77,6 +78,10 @@ type ApiAccessScopeMetadata = {
publicKey: string;
isIngestionSuspended: boolean | null | undefined;
isInAppAgentKey?: boolean;
+ // The org's opt-in for read-access audit events, carried here so recording
+ // a read needs no extra query. Null for credentials that carry no org, such
+ // as the self-hosted admin key; read it from the org instead.
+ accessAuditLogEnabled: boolean | null;
};
export type ApiAccessScopeIngestion = BaseApiAccessScope &
diff --git a/web/src/__tests__/server/access-audit-log-read-events.servertest.ts b/web/src/__tests__/server/access-audit-log-read-events.servertest.ts
new file mode 100644
index 0000000000..bff88f3a82
--- /dev/null
+++ b/web/src/__tests__/server/access-audit-log-read-events.servertest.ts
@@ -0,0 +1,262 @@
+import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";
+import { randomUUID } from "crypto";
+import type { NextApiRequest, NextApiResponse } from "next";
+import type { Session } from "next-auth";
+import { createMocks } from "node-mocks-http";
+import waitForExpect from "wait-for-expect";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type * as SharedServer from "@langfuse/shared/src/server";
+
+const staging = vi.hoisted(() => ({ fail: false }));
+
+// The events tables exist only after the ClickHouse dev-tables setup, which the
+// azure and redis-cluster CI runs skip.
+const eventsTableAvailable = vi.hoisted(
+ () => process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true",
+);
+
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const actual = await importOriginal<typeof SharedServer>();
+ return {
+ ...actual,
+ stageAuditLogEvents: async (
+ ...args: Parameters<typeof actual.stageAuditLogEvents>
+ ) => {
+ if (staging.fail) throw new Error("staging unavailable");
+ return actual.stageAuditLogEvents(...args);
+ },
+ };
+});
+
+import { Role } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ createEvent,
+ createEventsCh,
+ createOrgProjectAndApiKey,
+ createTrace,
+ createTracesCh,
+ getTraceByIdFromEventsTable,
+} from "@langfuse/shared/src/server";
+import getTraceHandler from "@/src/pages/api/public/traces/[traceId]";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+
+async function setupOrg(accessAuditLogEnabled: boolean) {
+ const fixture = await createOrgProjectAndApiKey({ plan: "Enterprise" });
+ await prisma.organization.update({
+ where: { id: fixture.orgId },
+ data: { accessAuditLogEnabled },
+ });
+ return fixture;
+}
+
+async function accessEvents(orgId: string) {
+ const rows = await prisma.auditLogStaging.findMany({
+ where: { payload: { path: ["orgId"], equals: orgId } },
+ });
+ return rows.map((row) => row.payload as Record<string, unknown>);
+}
+
+function trpcCaller(params: {
+ userId: string;
+ orgId: string;
+ projectId: string;
+ accessAuditLogEnabled: boolean;
+}) {
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: params.userId,
+ name: "Access Audit Reader",
+ email: "[email protected]",
+ canCreateOrganizations: true,
+ organizations: [
+ {
+ id: params.orgId,
+ name: "Access Audit Org",
+ role: Role.MEMBER,
+ plan: "cloud:enterprise",
+ cloudConfig: undefined,
+ metadata: {},
+ aiFeaturesEnabled: false,
+ aiTelemetryEnabled: false,
+ accessAuditLogEnabled: params.accessAuditLogEnabled,
+ projects: [
+ {
+ id: params.projectId,
+ name: "Access Audit Project",
+ role: Role.VIEWER,
+ retentionDays: null,
+ deletedAt: null,
+ hasTraces: true,
+ metadata: {},
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ },
+ ],
+ featureFlags: testFeatureFlags(),
+ admin: false,
+ },
+ environment: {} as any,
+ };
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+ return appRouter.createCaller({ ...ctx, prisma });
+}
+
+async function seedEventsTrace(projectId: string) {
+ const traceId = randomUUID();
+ const rootId = randomUUID();
+ const childId = randomUUID();
+ const startTime = Date.now() * 1000;
+ await createEventsCh([
+ createEvent({
+ id: rootId,
+ span_id: rootId,
+ trace_id: traceId,
+ project_id: projectId,
+ parent_span_id: "",
+ start_time: startTime,
+ }),
+ createEvent({
+ id: childId,
+ span_id: childId,
+ trace_id: traceId,
+ project_id: projectId,
+ parent_span_id: rootId,
+ start_time: startTime,
+ }),
+ ]);
+ await waitForExpect(async () => {
+ const trace = await getTraceByIdFromEventsTable({ projectId, traceId });
+ expect(trace?.id).toBe(traceId);
+ });
+ return { traceId, observationIds: [rootId, childId] };
+}
+
+async function getTraceViaPublicApi(auth: string, traceId: string) {
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "GET",
+ headers: { authorization: auth },
+ query: { traceId },
+ });
+ await getTraceHandler(req, res);
+ return res;
+}
+
+afterEach(() => {
+ staging.fail = false;
+});
+
+describe("access events on GET /api/public/traces/{traceId}", () => {
+ it("records the read with the API key as actor", async () => {
+ const { orgId, projectId, auth } = await setupOrg(true);
+ const trace = createTrace({ project_id: projectId });
+ await createTracesCh([trace]);
+
+ const res = await getTraceViaPublicApi(auth, trace.id);
+
+ expect(res._getStatusCode()).toBe(200);
+ const events = await accessEvents(orgId);
+ expect(events).toEqual([
+ expect.objectContaining({
+ kind: "access",
+ projectId,
+ surface: "public-api",
+ route: "GET /api/public/traces/{traceId}",
+ resourceType: "trace",
+ resourceId: trace.id,
+ action: "read",
+ outcome: "success",
+ actor: { type: "API_KEY", apiKeyId: expect.any(String) },
+ resourceRefs: [`trace:${trace.id}`, `session:${trace.session_id}`],
+ }),
+ ]);
+ });
+
+ it("fails the read when the event cannot be recorded", async () => {
+ const { orgId, projectId, auth } = await setupOrg(true);
+ const trace = createTrace({ project_id: projectId });
+ await createTracesCh([trace]);
+ staging.fail = true;
+
+ const res = await getTraceViaPublicApi(auth, trace.id);
+
+ expect(res._getStatusCode()).toBe(500);
+ expect(await accessEvents(orgId)).toEqual([]);
+ });
+});
+
+const maybe = eventsTableAvailable ? describe : describe.skip;
+
+maybe("access events on tRPC events.byTraceId", () => {
+ it("records the read with the user, the trace and its observations", async () => {
+ const { orgId, projectId } = await setupOrg(true);
+ const { traceId, observationIds } = await seedEventsTrace(projectId);
+ const userId = randomUUID();
+ const caller = trpcCaller({
+ userId,
+ orgId,
+ projectId,
+ accessAuditLogEnabled: true,
+ });
+
+ await caller.events.byTraceId({ projectId, traceId });
+
+ const events = await accessEvents(orgId);
+ expect(events).toEqual([
+ expect.objectContaining({
+ kind: "access",
+ projectId,
+ surface: "trpc",
+ route: "events.byTraceId",
+ resourceId: traceId,
+ resultCount: 2,
+ actor: expect.objectContaining({
+ type: "USER",
+ userId,
+ orgRole: Role.MEMBER,
+ projectRole: Role.VIEWER,
+ }),
+ }),
+ ]);
+ expect(events[0]?.resourceRefs).toEqual(
+ expect.arrayContaining([
+ `trace:${traceId}`,
+ ...observationIds.map((id) => `observation:${id}`),
+ ]),
+ );
+ });
+
+ it("records nothing for an org that has not opted in", async () => {
+ const { orgId, projectId } = await setupOrg(false);
+ const { traceId } = await seedEventsTrace(projectId);
+ const caller = trpcCaller({
+ userId: randomUUID(),
+ orgId,
+ projectId,
+ accessAuditLogEnabled: false,
+ });
+
+ await caller.events.byTraceId({ projectId, traceId });
+
+ expect(await accessEvents(orgId)).toEqual([]);
+ });
+
+ it("fails the read when the event cannot be recorded", async () => {
+ const { orgId, projectId } = await setupOrg(true);
+ const { traceId } = await seedEventsTrace(projectId);
+ const caller = trpcCaller({
+ userId: randomUUID(),
+ orgId,
+ projectId,
+ accessAuditLogEnabled: true,
+ });
+ staging.fail = true;
+
+ await expect(
+ caller.events.byTraceId({ projectId, traceId }),
+ ).rejects.toMatchObject({ code: "INTERNAL_SERVER_ERROR" });
+ });
+});
diff --git a/web/src/__tests__/server/access-audit-log-trpc.servertest.ts b/web/src/__tests__/server/access-audit-log-trpc.servertest.ts
new file mode 100644
index 0000000000..ad145eee8b
--- /dev/null
+++ b/web/src/__tests__/server/access-audit-log-trpc.servertest.ts
@@ -0,0 +1,138 @@
+import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";
+import { type Plan, Role } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import type { Session } from "next-auth";
+import { v4 as uuidv4 } from "uuid";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { env } from "@/src/env.mjs";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+
+async function accessAuditLogEnabled(orgId: string) {
+ const org = await prisma.organization.findUniqueOrThrow({
+ where: { id: orgId },
+ select: { accessAuditLogEnabled: true },
+ });
+ return org.accessAuditLogEnabled;
+}
+
+async function setup({ role, plan }: { role: Role; plan: Plan }) {
+ const orgId = uuidv4();
+ const userId = uuidv4();
+ await prisma.organization.create({
+ data: { id: orgId, name: `Access audit log ${orgId.slice(0, 8)}` },
+ });
+ await prisma.user.create({
+ data: {
+ id: userId,
+ email: `access-audit-${userId.slice(0, 8)}@test.com`,
+ name: "Access Audit Test User",
+ },
+ });
+ await prisma.organizationMembership.create({
+ data: { userId, orgId, role },
+ });
+
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: userId,
+ canCreateOrganizations: true,
+ name: "Access Audit Test User",
+ email: `access-audit-${userId.slice(0, 8)}@test.com`,
+ organizations: [
+ {
+ id: orgId,
+ name: "Access audit log",
+ role,
+ plan,
+ cloudConfig: undefined,
+ metadata: {},
+ aiFeaturesEnabled: false,
+ aiTelemetryEnabled: true,
+ accessAuditLogEnabled: false,
+ projects: [],
+ },
+ ],
+ featureFlags: testFeatureFlags(),
+ admin: false,
+ },
+ environment: {} as any,
+ };
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+ return { orgId, caller: appRouter.createCaller({ ...ctx, prisma }) };
+}
+
+describe("accessAuditLog.setEnabled", () => {
+ const originalMode = env.LANGFUSE_AUDIT_LOG_ACCESS_EVENTS;
+
+ afterEach(() => {
+ (env as any).LANGFUSE_AUDIT_LOG_ACCESS_EVENTS = originalMode;
+ });
+
+ it("stores the opt-in and records a change event for that field only", async () => {
+ (env as any).LANGFUSE_AUDIT_LOG_ACCESS_EVENTS = "org";
+ const { caller, orgId } = await setup({
+ role: Role.OWNER,
+ plan: "cloud:enterprise",
+ });
+
+ await caller.accessAuditLog.setEnabled({ orgId, enabled: true });
+
+ expect(await accessAuditLogEnabled(orgId)).toBe(true);
+ const changeEvent = await prisma.auditLog.findFirstOrThrow({
+ where: { orgId, resourceType: "organization", resourceId: orgId },
+ select: { action: true, before: true, after: true },
+ });
+ expect(changeEvent.action).toBe("update");
+ expect(JSON.parse(changeEvent.before!)).toEqual({
+ accessAuditLogEnabled: false,
+ });
+ expect(JSON.parse(changeEvent.after!)).toEqual({
+ accessAuditLogEnabled: true,
+ });
+ });
+
+ it.each(["enforced", "disabled"] as const)(
+ "rejects changes when the instance sets the mode to %s",
+ async (mode) => {
+ (env as any).LANGFUSE_AUDIT_LOG_ACCESS_EVENTS = mode;
+ const { caller, orgId } = await setup({
+ role: Role.OWNER,
+ plan: "cloud:enterprise",
+ });
+
+ await expect(
+ caller.accessAuditLog.setEnabled({ orgId, enabled: true }),
+ ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });
+ expect(await accessAuditLogEnabled(orgId)).toBe(false);
+ },
+ );
+
+ it("rejects organizations without the audit-logs entitlement", async () => {
+ (env as any).LANGFUSE_AUDIT_LOG_ACCESS_EVENTS = "org";
+ const { caller, orgId } = await setup({
+ role: Role.OWNER,
+ plan: "cloud:hobby",
+ });
+
+ await expect(
+ caller.accessAuditLog.setEnabled({ orgId, enabled: true }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(await accessAuditLogEnabled(orgId)).toBe(false);
+ });
+
+ it("rejects members without organization:update", async () => {
+ (env as any).LANGFUSE_AUDIT_LOG_ACCESS_EVENTS = "org";
+ const { caller, orgId } = await setup({
+ role: Role.MEMBER,
+ plan: "cloud:enterprise",
+ });
+
+ await expect(
+ caller.accessAuditLog.setEnabled({ orgId, enabled: true }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(await accessAuditLogEnabled(orgId)).toBe(false);
+ });
+});
diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.ts
index 0acdb42c4e..bd2a81ea88 100644
--- a/web/src/__tests__/server/api-auth.servertest.ts
+++ b/web/src/__tests__/server/api-auth.servertest.ts
@@ -623,6 +623,7 @@ describe("Authenticate API calls", () => {
createdAt: apiKey?.createdAt.toISOString(),
organizationCreatedAt: organization.createdAt.toISOString(),
isIngestionSuspended: expect.anything(),
+ accessAuditLogEnabled: false,
});
await prisma.organization.update({
@@ -740,6 +741,7 @@ describe("Authenticate API calls", () => {
createdAt: apiKey?.createdAt.toISOString(),
organizationCreatedAt: expect.any(String),
isIngestionSuspended: expect.anything(),
+ accessAuditLogEnabled: false,
});
await prisma.organization.update({
@@ -862,6 +864,7 @@ describe("Authenticate API calls", () => {
lastUsedAt: null,
expiresAt: null,
isIngestionSuspended: expect.anything(),
+ accessAuditLogEnabled: false,
isInAppAgentKey: false,
createdByUserId: null,
createdByApiKeyId: null,
@@ -881,6 +884,37 @@ describe("Authenticate API calls", () => {
});
});
+ it("carries the org's access-audit opt-in through the cached key", async () => {
+ await prisma.organization.update({
+ where: { id: testApiKey.orgId },
+ data: { accessAuditLogEnabled: true },
+ });
+ const mockPrisma = { apiKey: { findUnique: vi.fn() } };
+
+ // first auth generates the fast hashed api key, second caches it
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ getValidAuthHeader(),
+ );
+ const fromDb = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());
+ const fromCache = await new ApiAuthService(
+ mockPrisma as unknown as PrismaClient,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());
+
+ expect(mockPrisma.apiKey.findUnique).not.toHaveBeenCalled();
+ expect(fromDb).toMatchObject({
+ validKey: true,
+ scope: { accessAuditLogEnabled: true },
+ });
+ expect(fromCache).toMatchObject({
+ validKey: true,
+ scope: { accessAuditLogEnabled: true },
+ });
+ });
+
it("ttl should not be extended when reading from redis", async () => {
// Mock prisma
const mockPrisma = {
@@ -1015,6 +1049,7 @@ describe("Authenticate API calls", () => {
},
],
isIngestionSuspended: expect.anything(),
+ accessAuditLogEnabled: false,
});
await new ApiAuthService(prisma, redis).deleteApiKey(
diff --git a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
index e3ade7410a..6d5008d0a1 100644
--- a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
+++ b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
@@ -373,6 +373,21 @@ describe("API-key cache invalidation on project/org lifecycle", () => {
expect(await survivingKeys(keys)).toEqual([]);
});
+ it("accessAuditLog.setEnabled evicts the org's cached keys", async () => {
+ const orgId = await createOrg();
+ const user = await createUserInOrgs([orgId]);
+ const keys = await seedOrgScopedKey(orgId);
+
+ const caller = makeCaller({
+ userId: user.id,
+ orgIds: [orgId],
+ plan: "cloud:enterprise",
+ });
+ await caller.accessAuditLog.setEnabled({ orgId, enabled: true });
+
+ expect(await survivingKeys(keys)).toEqual([]);
+ });
+
it("admin project soft deletion preserves user permissions and evicts cached keys", async () => {
const orgId = await createOrg();
const projectId = await createProject(orgId);
diff --git a/web/src/__tests__/server/mcp-helpers.ts b/web/src/__tests__/server/mcp-helpers.ts
index b6c3704d4f..fcb4e947e0 100644
--- a/web/src/__tests__/server/mcp-helpers.ts
+++ b/web/src/__tests__/server/mcp-helpers.ts
@@ -58,6 +58,7 @@ export async function createMcpTestSetup(): Promise<{
publicKey: result.publicKey,
plan: "oss",
rateLimitOverrides: [],
+ accessAuditLogEnabled: false,
auth: authenticated.context,
};
@@ -138,6 +139,7 @@ export async function createInAppAgentMcpContext(params: {
publicKey: apiKey.publicKey,
plan: "oss",
rateLimitOverrides: [],
+ accessAuditLogEnabled: false,
auth: authenticated.context,
},
};
@@ -170,6 +172,7 @@ export function mockServerContext(
publicKey: overrides?.publicKey ?? "pk-lf-test",
plan: overrides?.plan ?? "oss",
rateLimitOverrides: overrides?.rateLimitOverrides ?? [],
+ accessAuditLogEnabled: overrides?.accessAuditLogEnabled ?? false,
...overrides,
};
}
diff --git a/web/src/__tests__/server/unit/access-audit-log-gate.servertest.ts b/web/src/__tests__/server/unit/access-audit-log-gate.servertest.ts
new file mode 100644
index 0000000000..27a7769e52
--- /dev/null
+++ b/web/src/__tests__/server/unit/access-audit-log-gate.servertest.ts
@@ -0,0 +1,102 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ mode: "org" as "org" | "enforced" | "disabled",
+ stagingEnabled: "true",
+ cloudRegion: undefined as string | undefined,
+ licenseKey: undefined as string | undefined,
+}));
+
+// Override only the values the gate reads, so the real
+// env -> plan -> entitlement chain runs.
+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 === "LANGFUSE_AUDIT_LOG_ACCESS_EVENTS") return mocks.mode;
+ if (prop === "LANGFUSE_AUDIT_LOG_STAGING_ENABLED")
+ return mocks.stagingEnabled;
+ 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 { isAccessAuditLogEnabled } from "@/src/ee/features/access-audit-log/server/isAccessAuditLogEnabled";
+
+describe("isAccessAuditLogEnabled", () => {
+ beforeEach(() => {
+ mocks.mode = "org";
+ mocks.stagingEnabled = "true";
+ mocks.cloudRegion = undefined;
+ mocks.licenseKey = undefined;
+ });
+
+ it("records nothing when disabled", () => {
+ mocks.mode = "disabled";
+ mocks.cloudRegion = "EU";
+ expect(
+ isAccessAuditLogEnabled({
+ plan: "cloud:enterprise",
+ accessAuditLogEnabled: true,
+ }),
+ ).toBe(false);
+ });
+
+ it("records nothing while the staging kill switch is off, even when enforced", () => {
+ mocks.mode = "enforced";
+ mocks.stagingEnabled = "false";
+ mocks.cloudRegion = "EU";
+ expect(
+ isAccessAuditLogEnabled({
+ plan: "cloud:enterprise",
+ accessAuditLogEnabled: true,
+ }),
+ ).toBe(false);
+ });
+
+ it("records every plan on Langfuse Cloud when enforced", () => {
+ mocks.mode = "enforced";
+ mocks.cloudRegion = "EU";
+ expect(
+ isAccessAuditLogEnabled({
+ plan: "cloud:hobby",
+ accessAuditLogEnabled: false,
+ }),
+ ).toBe(true);
+ });
+
+ it.each([
+ [undefined, false],
+ ["langfuse_pro_key", false],
+ ["langfuse_ee_key", true],
+ ])(
+ "records a self-hosted instance with license %s when enforced: %s",
+ (licenseKey, expected) => {
+ mocks.mode = "enforced";
+ mocks.licenseKey = licenseKey;
+ expect(
+ isAccessAuditLogEnabled({ plan: "oss", accessAuditLogEnabled: false }),
+ ).toBe(expected);
+ },
+ );
+
+ it.each([
+ ["cloud:enterprise", true, true],
+ ["cloud:enterprise", false, false],
+ ["cloud:pro", true, false],
+ ] as const)(
+ "records an org on %s with opt-in %s in org mode: %s",
+ (plan, accessAuditLogEnabled, expected) => {
+ mocks.cloudRegion = "EU";
+ expect(isAccessAuditLogEnabled({ plan, accessAuditLogEnabled })).toBe(
+ expected,
+ );
+ },
+ );
+});
diff --git a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts
index 097d270068..3cedebbd8d 100644
--- a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts
+++ b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts
@@ -70,6 +70,7 @@ const orgRow = {
createdAt: new Date("2026-09-16T00:00:00.000Z"),
cloudConfig: null,
cloudFreeTierUsageThresholdState: null,
+ accessAuditLogEnabled: false,
projects: [{ id: PRJ }],
} as unknown as OrganizationWithProjects;
diff --git a/web/src/__tests__/server/unit/assertToolAuthorized.servertest.ts b/web/src/__tests__/server/unit/assertToolAuthorized.servertest.ts
index 3fd459f9d7..8914e02087 100644
--- a/web/src/__tests__/server/unit/assertToolAuthorized.servertest.ts
+++ b/web/src/__tests__/server/unit/assertToolAuthorized.servertest.ts
@@ -67,6 +67,7 @@ const serverContext = (auth?: AuthorizationContext): ServerContext => ({
publicKey: "pk-lf-1",
plan: "cloud:hobby",
rateLimitOverrides: [],
+ accessAuditLogEnabled: false,
auth,
});
diff --git a/web/src/__tests__/server/unit/feedback-service.servertest.ts b/web/src/__tests__/server/unit/feedback-service.servertest.ts
index 473f3f69bb..eb9f71b312 100644
--- a/web/src/__tests__/server/unit/feedback-service.servertest.ts
+++ b/web/src/__tests__/server/unit/feedback-service.servertest.ts
@@ -53,6 +53,7 @@ const scope = {
apiKeyId: "api-key-1",
publicKey: "pk-test",
isIngestionSuspended: false,
+ accessAuditLogEnabled: false,
} as ApiAccessScope;
type SlackBlockForTest = {
diff --git a/web/src/__tests__/server/unit/mcp-calltool-error.servertest.ts b/web/src/__tests__/server/unit/mcp-calltool-error.servertest.ts
index bc98d17e04..c3d3d070cc 100644
--- a/web/src/__tests__/server/unit/mcp-calltool-error.servertest.ts
+++ b/web/src/__tests__/server/unit/mcp-calltool-error.servertest.ts
@@ -23,6 +23,7 @@ const context: ServerContext = {
publicKey: "pk-lf-test",
plan: "oss",
rateLimitOverrides: [],
+ accessAuditLogEnabled: false,
};
describe("MCP tool results", () => {
diff --git a/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts b/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts
index d6e67abad9..278ab15259 100644
--- a/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts
+++ b/web/src/__tests__/server/unit/mcp-define-tool.servertest.ts
@@ -94,6 +94,7 @@ describe("defineTool", () => {
publicKey: "pk-lf-test",
plan: "oss",
rateLimitOverrides: [],
+ accessAuditLogEnabled: false,
};
const input = {
id: "score-id",
diff --git a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
index 8b18f2e040..55b02abbe4 100644
--- a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
+++ b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
@@ -52,6 +52,7 @@ const PRJ = "prj_1";
const apiKey = (
apiKeyId: string,
boundResource: BoundResource,
+ accessAuditLogEnabled = false,
): AuthorizationContext => ({
principal: {
kind: "apiKey",
@@ -69,6 +70,7 @@ const apiKey = (
plan: "oss",
rateLimitOverrides: [],
isIngestionSuspended: false,
+ accessAuditLogEnabled,
},
],
boundResource,
@@ -230,6 +232,51 @@ describe.each(["x-langfuse-project-id", "langfuse-project-id"])(
},
);
+describe("enforceAuth access-audit opt-in", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(authorize).mockReturnValue({ success: true });
+ });
+
+ it.each([
+ ["organization", apiKey("key_1", { orgId: ORG }, true), "projects:read"],
+ [
+ "project",
+ apiKey("key_2", { orgId: ORG, projectId: PRJ }, true),
+ "traces:read",
+ ],
+ ] as const)(
+ "carries the %s key's org opt-in onto the scope",
+ async (_kind, context, action) => {
+ vi.mocked(authenticator.authenticate).mockResolvedValue({
+ success: true,
+ context,
+ });
+ expect(await enforceAuth({ req: req(), action })).toMatchObject({
+ success: true,
+ scope: { accessAuditLogEnabled: true },
+ });
+ },
+ );
+
+ it("leaves the opt-in unresolved for the admin key, which carries no org", async () => {
+ vi.mocked(authenticator.authenticate).mockResolvedValue({
+ success: true,
+ context: adminKey(),
+ });
+ vi.mocked(prisma.project.findUnique).mockResolvedValue({
+ orgId: ORG,
+ } as Awaited<ReturnType<typeof prisma.project.findUnique>>);
+ expect(
+ await enforceAuth({
+ req: req({}, { "x-langfuse-project-id": PRJ }),
+ action: "traces:read",
+ isAdminApiKeyAuthAllowed: true,
+ }),
+ ).toMatchObject({ success: true, scope: { accessAuditLogEnabled: null } });
+ });
+});
+
describe("enforceAuth span metadata", () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/web/src/__tests__/server/unit/public-api/toApiAccessScope.servertest.ts b/web/src/__tests__/server/unit/public-api/toApiAccessScope.servertest.ts
index fa8a0a736d..3f52161b5e 100644
--- a/web/src/__tests__/server/unit/public-api/toApiAccessScope.servertest.ts
+++ b/web/src/__tests__/server/unit/public-api/toApiAccessScope.servertest.ts
@@ -12,6 +12,7 @@ const scopeOrg = {
rateLimitOverrides: [],
projectIds: ["prj_1"],
isIngestionSuspended: false,
+ accessAuditLogEnabled: false,
};
const apiKeyPrincipal = (
@@ -43,6 +44,7 @@ const projectScope = {
publicKey: "pk-lf-1",
isIngestionSuspended: false,
isInAppAgentKey: false,
+ accessAuditLogEnabled: false,
};
describe("toApiAccessScope", () => {
@@ -63,6 +65,7 @@ describe("toApiAccessScope", () => {
publicKey: "pk-lf-1",
isIngestionSuspended: false,
isInAppAgentKey: false,
+ accessAuditLogEnabled: false,
});
});
@@ -100,6 +103,7 @@ describe("toApiAccessScope", () => {
publicKey: "ADMIN_API_KEY",
isIngestionSuspended: false,
isInAppAgentKey: false,
+ accessAuditLogEnabled: null,
});
});
diff --git a/web/src/__tests__/server/unit/rate-limit-response.servertest.ts b/web/src/__tests__/server/unit/rate-limit-response.servertest.ts
index 47349c0196..e75c88b3bb 100644
--- a/web/src/__tests__/server/unit/rate-limit-response.servertest.ts
+++ b/web/src/__tests__/server/unit/rate-limit-response.servertest.ts
@@ -109,6 +109,7 @@ describe("sendRateLimitResponse", () => {
publicKey: "pk-test",
isIngestionSuspended: false,
isInAppAgentKey: false,
+ accessAuditLogEnabled: false,
},
consumedPoints: 11,
isFirstInDuration: false,
diff --git a/web/src/__tests__/server/unit/run-mcp-tool.servertest.ts b/web/src/__tests__/server/unit/run-mcp-tool.servertest.ts
index 8361b2df78..16f0ddc9a9 100644
--- a/web/src/__tests__/server/unit/run-mcp-tool.servertest.ts
+++ b/web/src/__tests__/server/unit/run-mcp-tool.servertest.ts
@@ -50,6 +50,7 @@ const context: ServerContext = {
publicKey: "pk-lf-test",
plan: "oss",
rateLimitOverrides: [],
+ accessAuditLogEnabled: false,
};
describe("runMcpTool outcome telemetry", () => {
diff --git a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
index 5e779ee978..e20898c204 100644
--- a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
+++ b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts
@@ -961,6 +961,7 @@ describe("call site: admin API handleUpdateMembership", () => {
rateLimitOverrides: [],
projectIds: [],
isIngestionSuspended: false,
+ accessAuditLogEnabled: false,
},
],
boundResource: { orgId: "org-1" },
diff --git a/web/src/__tests__/server/unit/structured-public-api-error-contract.servertest.ts b/web/src/__tests__/server/unit/structured-public-api-error-contract.servertest.ts
index d4223bf12b..02a98be4ae 100644
--- a/web/src/__tests__/server/unit/structured-public-api-error-contract.servertest.ts
+++ b/web/src/__tests__/server/unit/structured-public-api-error-contract.servertest.ts
@@ -56,6 +56,7 @@ describe("structured public api error contract", () => {
publicKey: "pk-test",
isIngestionSuspended: false,
isInAppAgentKey: false,
+ accessAuditLogEnabled: false,
},
consumedPoints: 11,
isFirstInDuration: false,
diff --git a/web/src/components/layouts/header.tsx b/web/src/components/layouts/header.tsx
index a5b394c6bf..060a67bb1c 100644
--- a/web/src/components/layouts/header.tsx
+++ b/web/src/components/layouts/header.tsx
@@ -2,6 +2,7 @@
import Link from "next/link";
import DocPopup from "@/src/components/layouts/doc-popup";
import { Badge } from "@/src/components/design-system/Badge/Badge";
+import { InternalFeatureBadge } from "@/src/features/feature-flags";
import {
type Status,
StatusBadge,
@@ -14,6 +15,8 @@ type HeaderProps = {
status?: Status;
/** Plain informational badge next to the title, e.g. "Demo Org". Not a status. */
labelBadge?: string;
+ /** Marks a surface only internal users can see with the shared internal-feature badge. */
+ internal?: boolean;
label?: {
text: string;
href: string;
@@ -84,6 +87,7 @@ function BaseHeader({ ...props }: HeaderProps & { level: "h3" | "h4" | "h5" }) {
) : null}
</div>
{props.status && <StatusBadge type={props.status} />}
+ {props.internal && <InternalFeatureBadge />}
{props.labelBadge && (
<Badge
color="filled"
diff --git a/web/src/ee/features/access-audit-log/components/AccessLoggingSwitch.tsx b/web/src/ee/features/access-audit-log/components/AccessLoggingSwitch.tsx
new file mode 100644
index 0000000000..803b15e09e
--- /dev/null
+++ b/web/src/ee/features/access-audit-log/components/AccessLoggingSwitch.tsx
@@ -0,0 +1,16 @@
+import { SwitchInput } from "@/src/components/design-system/SwitchInput/SwitchInput";
+import { useAccessAuditLogSetting } from "@/src/ee/features/access-audit-log/hooks/useAccessAuditLogSetting";
+
+export function AccessLoggingSwitch(props: { orgId: string }) {
+ const setting = useAccessAuditLogSetting(props.orgId);
+
+ return (
+ <SwitchInput
+ id="access-audit-log-enabled"
+ description="Record an audit event whenever a user or API key reads traces, observations, or scores in this organization."
+ checked={setting.enabled}
+ disabled={setting.disabled}
+ onCheckedChange={setting.setEnabled}
+ />
+ );
+}
diff --git a/web/src/ee/features/access-audit-log/hooks/useAccessAuditLogSetting.ts b/web/src/ee/features/access-audit-log/hooks/useAccessAuditLogSetting.ts
new file mode 100644
index 0000000000..f92d18cfec
--- /dev/null
+++ b/web/src/ee/features/access-audit-log/hooks/useAccessAuditLogSetting.ts
@@ -0,0 +1,31 @@
+import { useQueryOrganization } from "@/src/features/organizations/hooks";
+import { useHasOrganizationAccess } from "@/src/features/rbac";
+import { api } from "@/src/utils/api";
+import { useSession } from "next-auth/react";
+
+/** The org's access-logging opt-in, including a change still in flight. */
+export function useAccessAuditLogSetting(orgId: string) {
+ const { update: updateSession } = useSession();
+ const utils = api.useUtils();
+ const organization = useQueryOrganization();
+ const hasAccess = useHasOrganizationAccess({
+ organizationId: orgId,
+ scope: "organization:update",
+ });
+
+ const mutation = api.accessAuditLog.setEnabled.useMutation({
+ onSuccess: async () => {
+ await updateSession();
+ // Admins resolve org context from this query, not the session
+ await utils.organizations.byId.invalidate();
+ },
+ });
+
+ return {
+ enabled: mutation.isPending
+ ? mutation.variables.enabled
+ : (organization?.accessAuditLogEnabled ?? false),
+ disabled: !hasAccess || mutation.isPending,
+ setEnabled: (value: boolean) => mutation.mutate({ orgId, enabled: value }),
+ };
+}
diff --git a/web/src/ee/features/access-audit-log/hooks/useShowAccessLoggingSetting.ts b/web/src/ee/features/access-audit-log/hooks/useShowAccessLoggingSetting.ts
new file mode 100644
index 0000000000..dfb2d4a39c
--- /dev/null
+++ b/web/src/ee/features/access-audit-log/hooks/useShowAccessLoggingSetting.ts
@@ -0,0 +1,16 @@
+import { useHasEntitlement } from "@/src/features/entitlements";
+import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";
+import { useSession } from "next-auth/react";
+
+/** Whether the org can set access logging: only in "org" mode, since "enforced" and "disabled" leave nothing to choose. */
+export function useShowAccessLoggingSetting(): boolean {
+ const { data: session } = useSession();
+ const hasEntitlement = useHasEntitlement("audit-logs");
+ // Internal until read access is recorded on every surface.
+ const internalFeaturesEnabled = useInternalFeaturesEnabled();
+ return (
+ internalFeaturesEnabled &&
+ hasEntitlement &&
+ session?.environment.accessAuditLogMode === "org"
+ );
+}
diff --git a/web/src/ee/features/access-audit-log/index.ts b/web/src/ee/features/access-audit-log/index.ts
new file mode 100644
index 0000000000..ef860d855f
--- /dev/null
+++ b/web/src/ee/features/access-audit-log/index.ts
@@ -0,0 +1,2 @@
+export { AccessLoggingSwitch } from "@/src/ee/features/access-audit-log/components/AccessLoggingSwitch";
+export { useShowAccessLoggingSetting } from "@/src/ee/features/access-audit-log/hooks/useShowAccessLoggingSetting";
diff --git a/web/src/ee/features/access-audit-log/server/accessAuditLogRouter.ts b/web/src/ee/features/access-audit-log/server/accessAuditLogRouter.ts
new file mode 100644
index 0000000000..fa3f6cdd76
--- /dev/null
+++ b/web/src/ee/features/access-audit-log/server/accessAuditLogRouter.ts
@@ -0,0 +1,67 @@
+import { env } from "@/src/env.mjs";
+import { auditLog } from "@/src/features/audit-logs/server";
+import { throwIfNoEntitlement } from "@/src/features/entitlements/server";
+import { throwIfNoOrganizationAccess } from "@/src/features/rbac";
+import {
+ createTRPCRouter,
+ protectedOrganizationProcedure,
+} from "@/src/server/api/trpc";
+import { invalidateCachedOrgApiKeys } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+import * as z from "zod";
+
+export const accessAuditLogRouter = createTRPCRouter({
+ // The org's opt-in only takes effect in "org" mode; in "enforced" and
+ // "disabled" the instance decides, so the setting is read-only.
+ setEnabled: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string(), enabled: z.boolean() }))
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoOrganizationAccess({
+ session: ctx.session,
+ organizationId: input.orgId,
+ scope: "organization:update",
+ });
+ throwIfNoEntitlement({
+ entitlement: "audit-logs",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ if (env.LANGFUSE_AUDIT_LOG_ACCESS_EVENTS !== "org") {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: "Access logging is set by the instance administrator.",
+ });
+ }
+
+ const before = await ctx.prisma.organization.findUnique({
+ where: { id: input.orgId },
+ select: { accessAuditLogEnabled: true },
+ });
+ if (!before) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Organization not found",
+ });
+ }
+ const after = await ctx.prisma.organization.update({
+ where: { id: input.orgId },
+ data: { accessAuditLogEnabled: input.enabled },
+ select: { accessAuditLogEnabled: true },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "organization",
+ resourceId: input.orgId,
+ action: "update",
+ before,
+ after,
+ });
+
+ // Cached API keys carry the opt-in, so public API and MCP reads pick up
+ // the change on their next request.
+ await invalidateCachedOrgApiKeys(input.orgId);
+
+ return after;
+ }),
+});
diff --git a/web/src/ee/features/access-audit-log/server/index.ts b/web/src/ee/features/access-audit-log/server/index.ts
new file mode 100644
index 0000000000..28c7fe6a90
--- /dev/null
+++ b/web/src/ee/features/access-audit-log/server/index.ts
@@ -0,0 +1,4 @@
+export {
+ recordPublicApiAccess,
+ recordTrpcAccess,
+} from "@/src/ee/features/access-audit-log/server/recordAccessEvent";
diff --git a/web/src/ee/features/access-audit-log/server/isAccessAuditLogEnabled.ts b/web/src/ee/features/access-audit-log/server/isAccessAuditLogEnabled.ts
new file mode 100644
index 0000000000..a48424d2f8
--- /dev/null
+++ b/web/src/ee/features/access-audit-log/server/isAccessAuditLogEnabled.ts
@@ -0,0 +1,39 @@
+import { type Plan } from "@langfuse/shared";
+
+import { env } from "@/src/env.mjs";
+import { isAuditLogEnabled } from "@/src/features/audit-logs/isAuditLogEnabled";
+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server";
+
+/** The org facts the gate reads. The session and API-key scopes carry them, so checking a read needs no query. */
+export type AccessAuditOrg = {
+ orgId: string;
+ plan: Plan;
+ accessAuditLogEnabled: boolean;
+};
+
+/**
+ * Whether reads in this organization are recorded as access events, per
+ * LANGFUSE_AUDIT_LOG_ACCESS_EVENTS. "enforced" follows the instance, not the
+ * org's plan: every org on Langfuse Cloud, every org on a self-hosted instance
+ * with an enterprise license, and none without one.
+ *
+ * The staging kill switch LANGFUSE_AUDIT_LOG_STAGING_ENABLED turns recording
+ * off in every mode. Reads then succeed unrecorded rather than fail.
+ */
+export function isAccessAuditLogEnabled(
+ org: Pick<AccessAuditOrg, "plan" | "accessAuditLogEnabled">,
+): boolean {
+ if (env.LANGFUSE_AUDIT_LOG_STAGING_ENABLED !== "true") return false;
+
+ switch (env.LANGFUSE_AUDIT_LOG_ACCESS_EVENTS) {
+ case "disabled":
+ return false;
+ case "enforced":
+ return isAuditLogEnabled();
+ case "org":
+ return (
+ org.accessAuditLogEnabled &&
+ hasEntitlementBasedOnPlan({ plan: org.plan, entitlement: "audit-logs" })
+ );
+ }
+}
diff --git a/web/src/ee/features/access-audit-log/server/recordAccessEvent.ts b/web/src/ee/features/access-audit-log/server/recordAccessEvent.ts
new file mode 100644
index 0000000000..3543aab14e
--- /dev/null
+++ b/web/src/ee/features/access-audit-log/server/recordAccessEvent.ts
@@ -0,0 +1,149 @@
+import { type IncomingHttpHeaders } from "node:http";
+import { type NextApiRequest } from "next";
+import { type Session } from "next-auth";
+
+import {
+ CloudConfigSchema,
+ InternalServerError,
+ type AuditLogResourceRef,
+} from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ logger,
+ recordIncrement,
+ stageAuditLogEvents,
+ type ApiAccessScope,
+ type StageAuditLogEventInput,
+} from "@langfuse/shared/src/server";
+
+import {
+ isAccessAuditLogEnabled,
+ type AccessAuditOrg,
+} from "@/src/ee/features/access-audit-log/server/isAccessAuditLogEnabled";
+import {
+ getAuditRequestContext,
+ toApiKeyActor,
+ toUserActor,
+} from "@/src/features/audit-logs/server";
+import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server";
+
+/** What a route returned: the resource it read, typed refs to every resource in the response, and the validated request input. */
+export type AccessRead = {
+ route: string;
+ resourceType: string;
+ resourceId?: string;
+ action: string;
+ resourceRefs: AuditLogResourceRef[];
+ params?: unknown;
+ resultCount?: number;
+};
+
+type AccessEvent = Omit<
+ Extract<StageAuditLogEventInput, { kind: "access" }>,
+ "kind"
+>;
+
+/** Stages the access event, failing closed: the read must not return data that was not recorded. */
+async function recordAccessEvent(event: AccessEvent): Promise<void> {
+ try {
+ await stageAuditLogEvents([{ kind: "access", ...event }]);
+ } catch (error) {
+ recordIncrement("langfuse.audit_log.access_event_write_failed");
+ logger.error("Failed to record access event, failing the read", {
+ error,
+ orgId: event.orgId,
+ projectId: event.projectId,
+ route: event.route,
+ });
+ throw new InternalServerError();
+ }
+}
+
+/** Loads the gate's org facts for a read whose credential does not carry them. */
+async function loadAccessAuditOrg(
+ where: { id: string } | { projects: { some: { id: string } } },
+): Promise<AccessAuditOrg | null> {
+ const org = await prisma.organization.findFirst({
+ where,
+ select: { id: true, cloudConfig: true, accessAuditLogEnabled: true },
+ });
+ if (!org) return null;
+ const cloudConfig = CloudConfigSchema.safeParse(org.cloudConfig);
+ return {
+ orgId: org.id,
+ plan: getOrganizationPlanServerSide(cloudConfig.data),
+ accessAuditLogEnabled: org.accessAuditLogEnabled,
+ };
+}
+
+/**
+ * Records a tRPC read when its org records access events. Call it before
+ * returning the data: a failed write fails the read. Anonymous viewers of
+ * public resources have no actor and are not recorded.
+ */
+export async function recordTrpcAccess(
+ ctx: {
+ session: { user?: Session["user"] } | null;
+ headers: IncomingHttpHeaders;
+ },
+ projectId: string,
+ read: AccessRead,
+): Promise<void> {
+ const user = ctx.session?.user;
+ if (!user) return;
+
+ const org = user.organizations.find((o) =>
+ o.projects.some((p) => p.id === projectId),
+ );
+ const project = org?.projects.find((p) => p.id === projectId);
+ // Admins and viewers of public resources read projects outside their session.
+ const auditOrg = org
+ ? {
+ orgId: org.id,
+ plan: org.plan,
+ accessAuditLogEnabled: org.accessAuditLogEnabled ?? false,
+ }
+ : await loadAccessAuditOrg({ projects: { some: { id: projectId } } });
+ if (!auditOrg || !isAccessAuditLogEnabled(auditOrg)) return;
+
+ await recordAccessEvent({
+ ...read,
+ orgId: auditOrg.orgId,
+ projectId,
+ actor: toUserActor(user, {
+ orgRole: org?.role,
+ projectRole: project?.role,
+ }),
+ surface: "trpc",
+ request: getAuditRequestContext(ctx.headers),
+ });
+}
+
+/**
+ * Records a public API read when its org records access events. Call it
+ * before returning the data: a failed write fails the read.
+ */
+export async function recordPublicApiAccess(
+ { scope, req }: { scope: ApiAccessScope; req: NextApiRequest },
+ read: AccessRead,
+): Promise<void> {
+ // Credentials without an org, such as the admin key, carry no opt-in.
+ const auditOrg =
+ scope.accessAuditLogEnabled === null
+ ? await loadAccessAuditOrg({ id: scope.orgId })
+ : {
+ orgId: scope.orgId,
+ plan: scope.plan,
+ accessAuditLogEnabled: scope.accessAuditLogEnabled,
+ };
+ if (!auditOrg || !isAccessAuditLogEnabled(auditOrg)) return;
+
+ await recordAccessEvent({
+ ...read,
+ orgId: auditOrg.orgId,
+ projectId: scope.projectId ?? undefined,
+ actor: toApiKeyActor(scope.apiKeyId, undefined, undefined),
+ surface: "public-api",
+ request: getAuditRequestContext(req.headers, req.socket.remoteAddress),
+ });
+}
diff --git a/web/src/ee/features/audit-log-viewer/OrgAuditLogsSettingsPage.tsx b/web/src/ee/features/audit-log-viewer/OrgAuditLogsSettingsPage.tsx
index 79b75ba302..85194219f1 100644
--- a/web/src/ee/features/audit-log-viewer/OrgAuditLogsSettingsPage.tsx
+++ b/web/src/ee/features/audit-log-viewer/OrgAuditLogsSettingsPage.tsx
@@ -1,5 +1,9 @@
import Header from "@/src/components/layouts/header";
import { Alert } from "@/src/components/design-system/Alert/Alert";
+import {
+ AccessLoggingSwitch,
+ useShowAccessLoggingSetting,
+} from "@/src/ee/features/access-audit-log";
import { ConnectedAuditLogsTable } from "@/src/ee/features/audit-log-viewer/AuditLogsTable/ConnectedAuditLogsTable";
import { useHasEntitlement } from "@/src/features/entitlements";
import { useHasOrganizationAccess } from "@/src/features/rbac";
@@ -10,6 +14,7 @@ export function OrgAuditLogsSettingsPage(props: { orgId: string }) {
scope: "orgAuditLogs:read",
});
const hasEntitlement = useHasEntitlement("audit-logs");
+ const showAccessLogging = useShowAccessLoggingSetting();
const body = (() => {
if (!hasEntitlement) {
@@ -34,14 +39,22 @@ export function OrgAuditLogsSettingsPage(props: { orgId: string }) {
})();
return (
- <>
- <Header title="Organization Audit Logs" />
- <p className="text-muted-foreground mb-2 text-sm">
- Track who changed what in your organization and when. Monitor
- organization settings, project creation/deletion, and membership changes
- over time.
- </p>
- {body}
- </>
+ <div className="flex flex-col gap-6">
+ {showAccessLogging && (
+ <div>
+ <Header title="Access Logging" internal />
+ <AccessLoggingSwitch orgId={props.orgId} />
+ </div>
+ )}
+ <div>
+ <Header title="Organization Audit Logs" />
+ <p className="text-muted-foreground mb-2 text-sm">
+ Track who changed what in your organization and when. Monitor
+ organization settings, project creation/deletion, and membership
+ changes over time.
+ </p>
+ {body}
+ </div>
+ </div>
);
}
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 0d826db360..ac543cd0cd 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -737,10 +737,24 @@ export const env = createEnv({
// Kill switch for staging audit events for the ClickHouse audit_logs table
// on Langfuse Cloud. The Postgres audit_logs row is written either way.
+ // Read-access events have no Postgres row, so turning it off stops
+ // recording them; reads still succeed.
LANGFUSE_AUDIT_LOG_STAGING_ENABLED: z
.enum(["true", "false"])
.default("true"),
+ // Read-access audit events (EE).
+ // "org": recorded for organizations whose plan includes audit logs and
+ // that enable access logging in their settings.
+ // "enforced": recorded for every organization. On Langfuse Cloud this
+ // covers every plan; self-hosted instances need an enterprise license,
+ // without one nothing is recorded.
+ // "disabled": never recorded.
+ // LANGFUSE_AUDIT_LOG_STAGING_ENABLED=false also stops recording.
+ LANGFUSE_AUDIT_LOG_ACCESS_EVENTS: z
+ .enum(["org", "enforced", "disabled"])
+ .default("org"),
+
// Background-migration env gates. Mirror worker/src/env.ts (names, defaults)
// so the background-migrations status endpoint can tell dormant, env-gated
// rows apart from migrations the worker will actually pick up. The worker
@@ -1331,6 +1345,8 @@ export const env = createEnv({
LANGFUSE_TRUSTED_PROXY_COUNT: process.env.LANGFUSE_TRUSTED_PROXY_COUNT,
LANGFUSE_AUDIT_LOG_STAGING_ENABLED:
process.env.LANGFUSE_AUDIT_LOG_STAGING_ENABLED,
+ LANGFUSE_AUDIT_LOG_ACCESS_EVENTS:
+ process.env.LANGFUSE_AUDIT_LOG_ACCESS_EVENTS,
LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL:
process.env.LANGFUSE_BACKGROUND_MIGRATION_V4_ENABLE_HISTORIC_BACKFILL,
LANGFUSE_BACKGROUND_MIGRATION_V4_DROP_PID_TID_SORTING_TABLES:
diff --git a/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.ts b/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.ts
index ffece5ab08..b30690cd91 100644
--- a/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.ts
+++ b/web/src/features/ai-gateway/server/auth/ingestionTokenVerifier.ts
@@ -166,6 +166,7 @@ export async function verifyGatewayIngestionAuthorization(
id: true,
cloudConfig: true,
cloudFreeTierUsageThresholdState: true,
+ accessAuditLogEnabled: true,
},
},
},
@@ -196,6 +197,7 @@ export async function verifyGatewayIngestionAuthorization(
isIngestionSuspended:
project.organization.cloudFreeTierUsageThresholdState === "BLOCKED",
isInAppAgentKey: false,
+ accessAuditLogEnabled: project.organization.accessAuditLogEnabled,
},
};
}
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index 0dc281dd44..b114c5950f 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -329,7 +329,7 @@ export async function auditLog(
}
}
-function toUserActor(
+export function toUserActor(
user: { id: string; name?: string | null; email?: string | null },
roles: { orgRole?: Role; projectRole?: Role },
): StagedAuditLogActor {
@@ -347,7 +347,7 @@ function toUserActor(
}
/** `creator` is the user an in-app agent key acts for. */
-function toApiKeyActor(
+export function toApiKeyActor(
apiKeyId: string,
userId: string | undefined,
creator: { name?: string | null; email?: string | null } | null | undefined,
diff --git a/web/src/features/audit-logs/server/index.ts b/web/src/features/audit-logs/server/index.ts
index 1d12cec3b8..ed0e4c3d77 100644
--- a/web/src/features/audit-logs/server/index.ts
+++ b/web/src/features/audit-logs/server/index.ts
@@ -3,6 +3,8 @@
// server code and reaches it through here.
export {
auditLog,
+ toApiKeyActor,
+ toUserActor,
type AuditLogActor,
} from "@/src/features/audit-logs/auditLog";
export { getAuditRequestContext } from "@/src/features/audit-logs/server/getAuditRequestContext";
diff --git a/web/src/features/auth/policy/contextResolver.ts b/web/src/features/auth/policy/contextResolver.ts
index a883379fe6..33a994944a 100644
--- a/web/src/features/auth/policy/contextResolver.ts
+++ b/web/src/features/auth/policy/contextResolver.ts
@@ -247,6 +247,7 @@ function toPrincipalOrganization(
rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],
projectIds: org.projects.map((p) => p.id),
isIngestionSuspended: org.cloudFreeTierUsageThresholdState === "BLOCKED",
+ accessAuditLogEnabled: org.accessAuditLogEnabled,
};
}
diff --git a/web/src/features/auth/policy/types.ts b/web/src/features/auth/policy/types.ts
index 26e5396eb2..f5ce8b22b1 100644
--- a/web/src/features/auth/policy/types.ts
+++ b/web/src/features/auth/policy/types.ts
@@ -21,6 +21,8 @@ export type PrincipalOrganization = {
rateLimitOverrides: z.infer<typeof CloudConfigRateLimit>;
projectIds: string[];
isIngestionSuspended: boolean;
+ /** Absent on authz contexts cached before the field existed; no org could have opted in then. */
+ accessAuditLogEnabled?: boolean;
};
/** Principal is an authorized admin, user, or api key, discriminated on kind. */
diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.ts
index 19c1387ccf..4e3d9e83b4 100644
--- a/web/src/features/events/server/eventsRouter.ts
+++ b/web/src/features/events/server/eventsRouter.ts
@@ -21,6 +21,7 @@ import {
paginationZod,
singleFilterList,
timeFilter,
+ toAuditLogResourceRef,
} from "@langfuse/shared";
import {
toDomainArrayWithStringifiedMetadata,
@@ -38,6 +39,7 @@ import {
EVENT_FILTER_OPTIONS_COLUMNS,
} from "./eventsService";
import { loadTraceTranscript } from "./loadTraceTranscript";
+import { recordTrpcAccess } from "@/src/ee/features/access-audit-log/server";
import {
instrumentAsync,
getCurrentSpan,
@@ -544,6 +546,26 @@ export const eventsRouter = createTRPCRouter({
timestamp: ctx.trace?.timestamp ?? input.timestamp,
});
+ await recordTrpcAccess(ctx, input.projectId, {
+ route: "events.byTraceId",
+ resourceType: "trace",
+ resourceId: input.traceId,
+ action: "read",
+ resourceRefs: [toAuditLogResourceRef("trace", input.traceId)]
+ .concat(
+ ctx.trace?.sessionId
+ ? [toAuditLogResourceRef("session", ctx.trace.sessionId)]
+ : [],
+ )
+ .concat(
+ observations.map((o) =>
+ toAuditLogResourceRef("observation", o.id),
+ ),
+ ),
+ params: input,
+ resultCount: observations.length,
+ });
+
return {
observations: toDomainArrayWithStringifiedMetadata(observations),
cutoffObservationsAfterMaxCount:
diff --git a/web/src/features/in-app-agent/server/rateLimit.ts b/web/src/features/in-app-agent/server/rateLimit.ts
index 6546822a1c..ed0f94a34b 100644
--- a/web/src/features/in-app-agent/server/rateLimit.ts
+++ b/web/src/features/in-app-agent/server/rateLimit.ts
@@ -17,7 +17,8 @@ type SessionUser = NonNullable<Session["user"]>;
* Build the org-scoped rate-limit scope for an in-app agent request.
*
* Used by `startRun` to build the same org-scoped API access shape as other
- * authenticated project requests.
+ * authenticated project requests. The scope only keys the rate limit and never
+ * authorizes a read, so it leaves the access-audit opt-in unresolved.
*
* TODO: this bucket is org-scoped only; a per-user submission cap needs the
* rate-limit service to support non-org keys. Concurrency is capped per user by
@@ -50,6 +51,7 @@ export function getInAppAgentApiAccessScope(
apiKeyId: "in-app-agent-session",
publicKey: "in-app-agent-session",
isIngestionSuspended: false,
+ accessAuditLogEnabled: null,
};
}
@@ -65,6 +67,7 @@ export function getInAppAgentApiAccessScope(
apiKeyId: "in-app-agent-session",
publicKey: "in-app-agent-session",
isIngestionSuspended: false,
+ accessAuditLogEnabled: null,
};
}
diff --git a/web/src/features/mcp/server/feedback/tools/submitFeedback.ts b/web/src/features/mcp/server/feedback/tools/submitFeedback.ts
index ff6db5316e..7bbd1ba494 100644
--- a/web/src/features/mcp/server/feedback/tools/submitFeedback.ts
+++ b/web/src/features/mcp/server/feedback/tools/submitFeedback.ts
@@ -34,6 +34,7 @@ export const [submitFeedbackTool, handleSubmitFeedback] = defineTool({
apiKeyId: context.apiKeyId,
publicKey: context.publicKey,
isIngestionSuspended: false,
+ accessAuditLogEnabled: context.accessAuditLogEnabled,
},
}),
}),
diff --git a/web/src/features/mcp/server/publicApi.ts b/web/src/features/mcp/server/publicApi.ts
index 93ea1d78df..ba540cbf28 100644
--- a/web/src/features/mcp/server/publicApi.ts
+++ b/web/src/features/mcp/server/publicApi.ts
@@ -15,6 +15,7 @@ export type McpPublicApiAuth = {
rateLimitOverrides: [];
isIngestionSuspended: false;
isInAppAgentKey: boolean;
+ accessAuditLogEnabled: boolean | null;
};
};
@@ -42,6 +43,7 @@ export const getMcpPublicApiAuth = async (
rateLimitOverrides: [],
isIngestionSuspended: false,
isInAppAgentKey: context.inAppAgent !== undefined,
+ accessAuditLogEnabled: context.accessAuditLogEnabled,
},
};
};
diff --git a/web/src/features/mcp/types.ts b/web/src/features/mcp/types.ts
index 7277358f90..f326a52bbf 100644
--- a/web/src/features/mcp/types.ts
+++ b/web/src/features/mcp/types.ts
@@ -60,6 +60,9 @@ export interface ServerContext {
/** Org-level rate limit overrides from the cloud config */
rateLimitOverrides: ApiAccessScope["rateLimitOverrides"];
+ /** The org's opt-in for read-access audit events */
+ accessAuditLogEnabled: ApiAccessScope["accessAuditLogEnabled"];
+
/** User agent from the MCP client's HTTP request */
userAgent?: string;
diff --git a/web/src/features/organizations/server/adminOrgContext.ts b/web/src/features/organizations/server/adminOrgContext.ts
index 6ca83c3761..ecc96559df 100644
--- a/web/src/features/organizations/server/adminOrgContext.ts
+++ b/web/src/features/organizations/server/adminOrgContext.ts
@@ -70,6 +70,7 @@ export async function buildAdminOrgContext(ctx: {
metadata: (organization.metadata as Record<string, unknown>) ?? {},
aiFeaturesEnabled: organization.aiFeaturesEnabled,
aiTelemetryEnabled: organization.aiTelemetryEnabled,
+ accessAuditLogEnabled: organization.accessAuditLogEnabled,
cloudConfig: parsedCloudConfig.data,
projects: organization.projects.map((project) => ({
id: project.id,
diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.ts
index 93368eb402..157929f62c 100644
--- a/web/src/features/public-api/server/apiAuth.ts
+++ b/web/src/features/public-api/server/apiAuth.ts
@@ -212,6 +212,8 @@ export class ApiAuthService {
publicKey: finalApiKey.publicKey,
isIngestionSuspended: finalApiKey.isIngestionSuspended,
isInAppAgentKey: finalApiKey.isInAppAgentKey,
+ accessAuditLogEnabled:
+ finalApiKey.accessAuditLogEnabled ?? false,
},
};
@@ -234,6 +236,7 @@ export class ApiAuthService {
organizationCreatedAt,
cloudConfig,
cloudFreeTierUsageThresholdState,
+ accessAuditLogEnabled,
} = this.extractOrgIdAndCloudConfig(dbKey);
const plan = getOrganizationPlanServerSide(cloudConfig);
@@ -263,6 +266,7 @@ export class ApiAuthService {
isInAppAgentKey: dbKey.isInAppAgentKey,
isIngestionSuspended:
cloudFreeTierUsageThresholdState === "BLOCKED",
+ accessAuditLogEnabled,
},
};
@@ -447,6 +451,7 @@ export class ApiAuthService {
updatedAt: Date;
cloudConfig: Prisma.JsonValue;
cloudFreeTierUsageThresholdState: string | null;
+ accessAuditLogEnabled: boolean;
};
} | null;
} & {
@@ -457,6 +462,7 @@ export class ApiAuthService {
updatedAt: Date;
cloudConfig: Prisma.JsonValue;
cloudFreeTierUsageThresholdState: string | null;
+ accessAuditLogEnabled: boolean;
} | null;
},
) {
@@ -473,6 +479,10 @@ export class ApiAuthService {
apiKeyAndOrganisation.project?.organization
.cloudFreeTierUsageThresholdState ??
apiKeyAndOrganisation.organization?.cloudFreeTierUsageThresholdState;
+ const accessAuditLogEnabled =
+ apiKeyAndOrganisation.project?.organization.accessAuditLogEnabled ??
+ apiKeyAndOrganisation.organization?.accessAuditLogEnabled ??
+ false;
if (!orgId || !organizationCreatedAt) {
logger.error(
@@ -490,6 +500,7 @@ export class ApiAuthService {
organizationCreatedAt,
cloudConfig,
cloudFreeTierUsageThresholdState,
+ accessAuditLogEnabled,
};
}
@@ -510,6 +521,7 @@ export class ApiAuthService {
updatedAt: Date;
cloudConfig: Prisma.JsonValue;
cloudFreeTierUsageThresholdState: string | null;
+ accessAuditLogEnabled: boolean;
};
} | null;
} & {
@@ -520,6 +532,7 @@ export class ApiAuthService {
updatedAt: Date;
cloudConfig: Prisma.JsonValue;
cloudFreeTierUsageThresholdState: string | null;
+ accessAuditLogEnabled: boolean;
} | null;
},
) {
@@ -528,6 +541,7 @@ export class ApiAuthService {
organizationCreatedAt,
cloudConfig,
cloudFreeTierUsageThresholdState,
+ accessAuditLogEnabled,
} = this.extractOrgIdAndCloudConfig(apiKeyAndOrganisation);
const newApiKey = OrgEnrichedApiKey.parse({
@@ -539,6 +553,7 @@ export class ApiAuthService {
plan: getOrganizationPlanServerSide(cloudConfig),
rateLimitOverrides: cloudConfig?.rateLimitOverrides,
isIngestionSuspended: cloudFreeTierUsageThresholdState === "BLOCKED",
+ accessAuditLogEnabled,
});
if (!orgId) {
diff --git a/web/src/features/public-api/server/toApiAccessScope.ts b/web/src/features/public-api/server/toApiAccessScope.ts
index ff6c8df99d..33caba08f9 100644
--- a/web/src/features/public-api/server/toApiAccessScope.ts
+++ b/web/src/features/public-api/server/toApiAccessScope.ts
@@ -33,6 +33,8 @@ function adminScope(target: TargetResource): ApiAccessScope {
publicKey: "ADMIN_API_KEY",
isIngestionSuspended: false,
isInAppAgentKey: false,
+ // The admin key carries no org.
+ accessAuditLogEnabled: null,
};
}
@@ -52,6 +54,7 @@ function apiKeyScope(
publicKey: principal.publicKey,
isIngestionSuspended: org.isIngestionSuspended,
isInAppAgentKey: principal.isInAppAgentKey,
+ accessAuditLogEnabled: org.accessAuditLogEnabled ?? false,
accessLevel: apiKeyAccessLevel(principal, target.projectId),
};
}
diff --git a/web/src/features/public-api/server/verifyProjectApiKeyAuth.ts b/web/src/features/public-api/server/verifyProjectApiKeyAuth.ts
index a8f1f4b339..a4e044b026 100644
--- a/web/src/features/public-api/server/verifyProjectApiKeyAuth.ts
+++ b/web/src/features/public-api/server/verifyProjectApiKeyAuth.ts
@@ -168,6 +168,8 @@ async function verifyAdminApiKeyAuth(req: NextApiRequest): Promise<
publicKey: "ADMIN_API_KEY",
isIngestionSuspended: false,
isInAppAgentKey: false,
+ // The admin key carries no org.
+ accessAuditLogEnabled: null,
},
};
}
diff --git a/web/src/pages/api/public/mcp/index.ts b/web/src/pages/api/public/mcp/index.ts
index 56c7a4815f..c72b413347 100644
--- a/web/src/pages/api/public/mcp/index.ts
+++ b/web/src/pages/api/public/mcp/index.ts
@@ -135,6 +135,7 @@ export default async function handler(
publicKey: scope.publicKey,
plan: scope.plan,
rateLimitOverrides: scope.rateLimitOverrides,
+ accessAuditLogEnabled: scope.accessAuditLogEnabled,
userAgent: req.headers["user-agent"],
inAppAgent: getInAppAgentContext(req, scope.isInAppAgentKey),
auth: ctx,
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index a789de5e42..3a89ea3d44 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -17,6 +17,7 @@ import { env } from "@/src/env.mjs";
import {
filterAndValidateDbLegacyTraceScoreList,
LangfuseNotFoundError,
+ toAuditLogResourceRef,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
@@ -30,6 +31,7 @@ import Decimal from "decimal.js";
import { auditLog } from "@/src/features/audit-logs/server";
import { legacyPublicApiRateLimitUpgradePaths } from "@/src/features/public-api/server/rateLimitUpgradePaths";
import { TRACES_DEPRECATION } from "@/src/features/public-api/server/deprecations";
+import { recordPublicApiAccess } from "@/src/ee/features/access-audit-log/server";
export default withMiddlewares(
{
@@ -42,7 +44,7 @@ export default withMiddlewares(
responseSchema: GetTraceV1Response,
rateLimitUpgradePath: legacyPublicApiRateLimitUpgradePaths.traceGet,
rejectInEventsOnlyMode: true,
- fn: async ({ query, auth }) => {
+ fn: async ({ query, auth, req }) => {
const { traceId } = query;
let effectiveFields: readonly TraceFieldGroup[] =
@@ -181,6 +183,38 @@ export default withMiddlewares(
}
return undefined;
})();
+
+ await recordPublicApiAccess(
+ { scope: auth.scope, req },
+ {
+ route: "GET /api/public/traces/{traceId}",
+ resourceType: "trace",
+ resourceId: traceId,
+ action: "read",
+ resourceRefs: [toAuditLogResourceRef("trace", traceId)]
+ .concat(
+ trace.sessionId
+ ? [toAuditLogResourceRef("session", trace.sessionId)]
+ : [],
+ )
+ .concat(
+ includeObservations
+ ? outObservations.map((o) =>
+ toAuditLogResourceRef("observation", o.id),
+ )
+ : [],
+ )
+ .concat(
+ includeScores
+ ? validatedScores.map((s) =>
+ toAuditLogResourceRef("score", s.id),
+ )
+ : [],
+ ),
+ params: query,
+ },
+ );
+
return {
...trace,
externalId: null,
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index d41cace360..ec924429a2 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -46,6 +46,7 @@ import { experimentsRouter } from "@/src/features/experiments/server/router";
import { mediaRouter } from "@/src/server/api/routers/media";
import { backgroundMigrationsRouter } from "@/src/features/background-migrations/server/background-migrations-router";
import { auditLogsRouter } from "./routers/auditLogs";
+import { accessAuditLogRouter } from "@/src/ee/features/access-audit-log/server/accessAuditLogRouter";
import { tableRouter } from "@/src/features/table/server/tableRouter";
import { batchActionRouter } from "@/src/features/batch-actions/server/batchActionRouter";
import { cloudStatusRouter } from "@/src/features/cloud-status-notification/server/cloud-status-router";
@@ -124,6 +125,7 @@ export const appRouter = createTRPCRouter({
media: mediaRouter,
backgroundMigrations: backgroundMigrationsRouter,
auditLogs: auditLogsRouter,
+ accessAuditLog: accessAuditLogRouter,
table: tableRouter,
batchAction: batchActionRouter,
cloudStatus: cloudStatusRouter,
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 9437a5753c..9356a5d11c 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -916,6 +916,7 @@ export async function getAuthOptions(
apiKeyOrgRoleSelectionEnabled:
env.API_AUTH_MIGRATION === "enforce" &&
env.API_KEY_ORG_ROLES_ENABLE === "true",
+ accessAuditLogMode: env.LANGFUSE_AUDIT_LOG_ACCESS_EVENTS,
},
user:
dbUser !== null
@@ -976,6 +977,8 @@ export async function getAuthOptions(
orgMembership.organization.aiFeaturesEnabled,
aiTelemetryEnabled:
orgMembership.organization.aiTelemetryEnabled,
+ accessAuditLogEnabled:
+ orgMembership.organization.accessAuditLogEnabled,
featureFlags: parseFlagsWithOrganizationDefaults(
dbUser.featureFlags,
orgMembership.organization.featureFlagOrgDefaults,
diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.ts
index a27f229f0d..b5167145cd 100644
--- a/web/types/next-auth.d.ts
+++ b/web/types/next-auth.d.ts
@@ -44,6 +44,9 @@ declare module "next-auth" {
metadata: Record<string, unknown>;
aiFeaturesEnabled: boolean;
aiTelemetryEnabled: boolean;
+ // Optional so existing session mocks need not set it; the session
+ // callback and the admin org fallback always populate it.
+ accessAuditLogEnabled?: boolean;
featureFlags?: Flags;
projects: {
id: PrismaProject["id"];
@@ -88,6 +91,9 @@ declare module "next-auth" {
// Role selection requires API_AUTH_MIGRATION=enforce and the scope's rollout flag.
apiKeyProjectRoleSelectionEnabled?: boolean;
apiKeyOrgRoleSelectionEnabled?: boolean;
+ // Mirrors LANGFUSE_AUDIT_LOG_ACCESS_EVENTS. Optional so existing session
+ // mocks need not set it.
+ accessAuditLogMode?: "org" | "enforced" | "disabled";
};
}