Skip to content

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

chore: send webhooks for admin actions (#12207)

Max Deichmanna5d52864d36d
diff --git a/web/src/__tests__/async/admin-access-webhook.servertest.ts b/web/src/__tests__/async/admin-access-webhook.servertest.ts
new file mode 100644
index 0000000000..fc322dc276
--- /dev/null
+++ b/web/src/__tests__/async/admin-access-webhook.servertest.ts
@@ -0,0 +1,187 @@
+import { env } from "@/src/env.mjs";
+import {
+ resetAdminAccessWebhookCacheForTests,
+ sendAdminAccessWebhook,
+} from "@/src/server/adminAccessWebhook";
+
+describe("sendAdminAccessWebhook", () => {
+ const originalWebhook = env.LANGFUSE_ADMIN_ACCESS_WEBHOOK;
+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+
+ beforeEach(() => {
+ resetAdminAccessWebhookCacheForTests();
+ jest.restoreAllMocks();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = originalWebhook;
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;
+ });
+
+ it("should not send when webhook is not configured", async () => {
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = undefined;
+ const fetchSpy = jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue({ ok: true } as Response);
+
+ await sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ });
+
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("should not send when email is missing", async () => {
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";
+ const fetchSpy = jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue({ ok: true } as Response);
+
+ await sendAdminAccessWebhook({
+ email: null,
+ projectId: "project-1",
+ orgId: "org-1",
+ });
+
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("should send expected payload including project, org and region", async () => {
+ jest.useFakeTimers();
+ jest.setSystemTime(new Date("2026-02-19T19:39:37.000Z"));
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "HIPAA";
+
+ const fetchSpy = jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue({ ok: true } as Response);
+
+ await sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ });
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(fetchSpy).toHaveBeenCalledWith("https://example.com/hook", {
+ method: "POST",
+ body: JSON.stringify({
+ email: "[email protected]",
+ timestamp: "2026-02-19T19:39:37.000Z",
+ project: "project-1",
+ org: "org-1",
+ region: "HIPAA",
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ });
+
+ it("should dedupe repeated sends within 60 seconds for same email/project/org", async () => {
+ jest.useFakeTimers();
+ jest.setSystemTime(new Date("2026-02-19T19:39:37.000Z"));
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";
+
+ const fetchSpy = jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue({ ok: true } as Response);
+
+ await sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ });
+ await sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ });
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("should send again after dedupe window has passed", async () => {
+ jest.useFakeTimers();
+ jest.setSystemTime(new Date("2026-02-19T19:39:37.000Z"));
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";
+
+ const fetchSpy = jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue({ ok: true } as Response);
+
+ await sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ });
+
+ jest.setSystemTime(new Date("2026-02-19T19:40:38.000Z"));
+
+ await sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ });
+
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it("should not dedupe when email/project/org differ", async () => {
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";
+
+ const fetchSpy = jest
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue({ ok: true } as Response);
+
+ await sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ });
+ await sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-2",
+ orgId: "org-1",
+ });
+
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it("should not throw when fetch rejects", async () => {
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";
+
+ jest
+ .spyOn(globalThis, "fetch")
+ .mockRejectedValue(new Error("network error"));
+
+ await expect(
+ sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it("should not throw when fetch returns non-ok response", async () => {
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";
+
+ jest.spyOn(globalThis, "fetch").mockResolvedValue({
+ ok: false,
+ status: 500,
+ statusText: "Internal Server Error",
+ } as Response);
+
+ await expect(
+ sendAdminAccessWebhook({
+ email: "[email protected]",
+ projectId: "project-1",
+ orgId: "org-1",
+ }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts b/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts
new file mode 100644
index 0000000000..769deaeabb
--- /dev/null
+++ b/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts
@@ -0,0 +1,218 @@
+/** @jest-environment node */
+
+import type { Session } from "next-auth";
+import * as z from "zod/v4";
+import { env } from "@/src/env.mjs";
+
+jest.mock("@langfuse/shared/src/server", () => {
+ const originalModule = jest.requireActual("@langfuse/shared/src/server");
+ return {
+ ...originalModule,
+ getTraceById: jest.fn(),
+ };
+});
+
+import {
+ createTRPCRouter,
+ createInnerTRPCContext,
+ protectedProjectProcedureWithoutTracing,
+ protectedGetTraceProcedure,
+ protectedGetSessionProcedure,
+} from "@/src/server/api/trpc";
+import { resetAdminAccessWebhookCacheForTests } from "@/src/server/adminAccessWebhook";
+import { getTraceById } from "@langfuse/shared/src/server";
+
+const middlewareTestRouter = createTRPCRouter({
+ project: protectedProjectProcedureWithoutTracing
+ .input(z.object({ projectId: z.string() }))
+ .query(() => ({ ok: true })),
+ trace: protectedGetTraceProcedure
+ .input(z.object({ traceId: z.string(), projectId: z.string() }))
+ .query(() => ({ ok: true })),
+ session: protectedGetSessionProcedure
+ .input(z.object({ sessionId: z.string(), projectId: z.string() }))
+ .query(() => ({ ok: true })),
+});
+
+const createAdminSession = (
+ projects: Array<{ id: string; name?: string }> = [],
+): Session => ({
+ expires: "1",
+ user: {
+ id: "admin-user-id",
+ email: "[email protected]",
+ canCreateOrganizations: true,
+ name: "Admin User",
+ organizations: [
+ {
+ id: "session-org-id",
+ name: "Session Organization",
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ projects: projects.map((project) => ({
+ id: project.id,
+ role: "OWNER",
+ retentionDays: 30,
+ deletedAt: null,
+ name: project.name ?? "Project",
+ })),
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ },
+ admin: true,
+ },
+ environment: {} as any,
+});
+
+const createTestCaller = (params: {
+ session: Session;
+ projectOrgId?: string;
+ traceSession?: { public: boolean } | null;
+}) => {
+ const mockPrisma = {
+ project: {
+ findFirst: jest.fn().mockResolvedValue({
+ orgId: params.projectOrgId ?? "db-org-id",
+ }),
+ },
+ traceSession: {
+ findFirst: jest.fn().mockResolvedValue(
+ params.traceSession ?? {
+ public: false,
+ },
+ ),
+ },
+ };
+
+ const context = createInnerTRPCContext({
+ session: params.session,
+ headers: {},
+ });
+
+ return {
+ caller: middlewareTestRouter.createCaller({
+ ...context,
+ prisma: mockPrisma as any,
+ }),
+ mockPrisma,
+ };
+};
+
+describe("admin access webhook in tRPC authorization middleware", () => {
+ const mockGetTraceById = jest.mocked(getTraceById);
+ const originalWebhook = env.LANGFUSE_ADMIN_ACCESS_WEBHOOK;
+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+
+ beforeAll(() => {
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "US";
+ });
+
+ beforeEach(() => {
+ resetAdminAccessWebhookCacheForTests();
+ jest.restoreAllMocks();
+ jest.clearAllMocks();
+ jest.spyOn(globalThis, "fetch").mockResolvedValue({ ok: true } as Response);
+ mockGetTraceById.mockResolvedValue({
+ id: "trace-id",
+ input: "{}",
+ output: "{}",
+ public: false,
+ sessionId: null,
+ } as any);
+ });
+
+ afterAll(() => {
+ (env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = originalWebhook;
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;
+ });
+
+ it("sends webhook when admin accesses a project they are not a member of", async () => {
+ const projectId = "project-id-non-member";
+ const orgId = "org-id-from-db";
+ const { caller, mockPrisma } = createTestCaller({
+ session: createAdminSession([]),
+ projectOrgId: orgId,
+ });
+
+ await caller.project({ projectId });
+
+ expect(mockPrisma.project.findFirst).toHaveBeenCalledWith({
+ select: {
+ orgId: true,
+ },
+ where: {
+ id: projectId,
+ deletedAt: null,
+ },
+ });
+ const fetchSpy = jest.mocked(globalThis.fetch);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const request = fetchSpy.mock.calls[0]?.[1] as RequestInit;
+ const payload = JSON.parse(String(request.body));
+ expect(payload).toMatchObject({
+ email: "[email protected]",
+ project: projectId,
+ org: orgId,
+ });
+ });
+
+ it("sends webhook when admin accesses trace in a project they are not a member of", async () => {
+ const projectId = "trace-project-id";
+ const { caller } = createTestCaller({
+ session: createAdminSession([]),
+ });
+
+ await caller.trace({
+ traceId: "trace-id",
+ projectId,
+ });
+
+ const fetchSpy = jest.mocked(globalThis.fetch);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const request = fetchSpy.mock.calls[0]?.[1] as RequestInit;
+ const payload = JSON.parse(String(request.body));
+ expect(payload).toMatchObject({
+ email: "[email protected]",
+ project: projectId,
+ org: null,
+ });
+ });
+
+ it("sends webhook when admin accesses session in a project they are not a member of", async () => {
+ const projectId = "session-project-id";
+ const { caller, mockPrisma } = createTestCaller({
+ session: createAdminSession([]),
+ traceSession: { public: false },
+ });
+
+ await caller.session({
+ sessionId: "session-id",
+ projectId,
+ });
+
+ expect(mockPrisma.traceSession.findFirst).toHaveBeenCalledWith({
+ where: {
+ id: "session-id",
+ projectId,
+ },
+ select: {
+ public: true,
+ },
+ });
+ const fetchSpy = jest.mocked(globalThis.fetch);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const request = fetchSpy.mock.calls[0]?.[1] as RequestInit;
+ const payload = JSON.parse(String(request.body));
+ expect(payload).toMatchObject({
+ email: "[email protected]",
+ project: projectId,
+ org: null,
+ });
+ });
+});
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 743a236c5c..956913b972 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -47,6 +47,7 @@ export const env = createEnv({
NEXTAUTH_COOKIE_DOMAIN: z.string().optional(),
LANGFUSE_TEAM_SLACK_WEBHOOK: z.string().url().optional(),
LANGFUSE_NEW_USER_SIGNUP_WEBHOOK: z.string().url().optional(),
+ LANGFUSE_ADMIN_ACCESS_WEBHOOK: z.string().url().optional(),
// Add `.min(1) on ID and SECRET if you want to make sure they're not empty
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: z.enum(["true", "false"]).optional(),
SALT: z.string({
@@ -456,6 +457,7 @@ export const env = createEnv({
LANGFUSE_TEAM_SLACK_WEBHOOK: process.env.LANGFUSE_TEAM_SLACK_WEBHOOK,
LANGFUSE_NEW_USER_SIGNUP_WEBHOOK:
process.env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK,
+ LANGFUSE_ADMIN_ACCESS_WEBHOOK: process.env.LANGFUSE_ADMIN_ACCESS_WEBHOOK,
SALT: process.env.SALT,
LANGFUSE_CSP_ENFORCE_HTTPS: process.env.LANGFUSE_CSP_ENFORCE_HTTPS,
TELEMETRY_ENABLED: process.env.TELEMETRY_ENABLED,
diff --git a/web/src/server/adminAccessWebhook.ts b/web/src/server/adminAccessWebhook.ts
new file mode 100644
index 0000000000..04caa3637a
--- /dev/null
+++ b/web/src/server/adminAccessWebhook.ts
@@ -0,0 +1,82 @@
+import { env } from "@/src/env.mjs";
+import { logger } from "@langfuse/shared/src/server";
+
+type AdminAccessWebhookPayload = {
+ email: string;
+ timestamp: string;
+ project: string | null;
+ org: string | null;
+ region: string;
+};
+
+const DEDUPE_WINDOW_MS = 60_000;
+const lastWebhookByKey = new Map<string, number>();
+
+export const resetAdminAccessWebhookCacheForTests = () => {
+ lastWebhookByKey.clear();
+};
+
+const shouldSkipDueToRecentDuplicate = (payload: AdminAccessWebhookPayload) => {
+ const dedupeKey = [payload.email, payload.project, payload.org].join(":");
+ const nowMs = Date.now();
+ const lastSentMs = lastWebhookByKey.get(dedupeKey);
+
+ if (lastSentMs && nowMs - lastSentMs < DEDUPE_WINDOW_MS) {
+ return true;
+ }
+
+ lastWebhookByKey.set(dedupeKey, nowMs);
+ return false;
+};
+
+export const sendAdminAccessWebhook = async (params: {
+ email: string | null | undefined;
+ projectId?: string | null;
+ orgId?: string | null;
+}) => {
+ if (!env.LANGFUSE_ADMIN_ACCESS_WEBHOOK) return;
+ if (!params.email) return;
+
+ logger.info("Sending admin access webhook", {
+ email: params.email,
+ projectId: params.projectId,
+ orgId: params.orgId,
+ });
+
+ const payload: AdminAccessWebhookPayload = {
+ email: params.email,
+ timestamp: new Date().toISOString(),
+ project: params.projectId ?? null,
+ org: params.orgId ?? null,
+ region: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ?? "self-hosted",
+ };
+
+ if (shouldSkipDueToRecentDuplicate(payload)) return;
+
+ try {
+ const response = await fetch(env.LANGFUSE_ADMIN_ACCESS_WEBHOOK, {
+ method: "POST",
+ body: JSON.stringify(payload),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ logger.warn("Failed to send admin access webhook", {
+ status: response.status,
+ statusText: response.statusText,
+ email: payload.email,
+ project: payload.project,
+ org: payload.org,
+ });
+ }
+ } catch (error) {
+ logger.warn("Error while sending admin access webhook", {
+ error,
+ email: payload.email,
+ project: payload.project,
+ org: payload.org,
+ });
+ }
+};
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index cdd5623372..00ef70f36f 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -23,6 +23,7 @@ import * as z from "zod/v4";
import * as opentelemetry from "@opentelemetry/api";
import { type IncomingHttpHeaders } from "node:http";
import { getTRPCErrorCodeFromHTTPStatusCode } from "@/src/server/utils/trpc-utils";
+import { sendAdminAccessWebhook } from "@/src/server/adminAccessWebhook";
type CreateContextOptions = {
session: Session | null;
@@ -299,6 +300,11 @@ const enforceUserIsAuthedAndProjectMember = t.middleware(async (opts) => {
message: "Project not found",
});
}
+ await sendAdminAccessWebhook({
+ email: ctx.session.user.email,
+ projectId,
+ orgId: dbProject.orgId,
+ });
return next({
ctx: {
// infers the `session` as non-nullable
@@ -321,6 +327,14 @@ const enforceUserIsAuthedAndProjectMember = t.middleware(async (opts) => {
});
}
+ if (ctx.session.user.admin === true) {
+ await sendAdminAccessWebhook({
+ email: ctx.session.user.email,
+ projectId,
+ orgId: sessionProject.organization.id,
+ });
+ }
+
return next({
ctx: {
// infers the `session` as non-nullable
@@ -376,6 +390,13 @@ const enforceIsAuthedAndOrgMember = t.middleware(async (opts) => {
});
}
+ if (ctx.session.user.admin === true) {
+ await sendAdminAccessWebhook({
+ email: ctx.session.user.email,
+ orgId,
+ });
+ }
+
return next({
ctx: {
session: {
@@ -486,6 +507,14 @@ const enforceTraceAccess = t.middleware(async (opts) => {
"User is not a member of this project and this trace is not public",
});
}
+
+ if (ctx.session?.user?.admin === true) {
+ await sendAdminAccessWebhook({
+ email: ctx.session.user.email,
+ projectId,
+ });
+ }
+
return next({
ctx: {
session: {
@@ -526,7 +555,7 @@ const enforceSessionAccess = t.middleware(async (opts) => {
const { sessionId, projectId } = result.data;
// trace sessions are stored in postgres. No need to check for clickhouse eligibility.
- const session = await prisma.traceSession.findFirst({
+ const session = await ctx.prisma.traceSession.findFirst({
where: {
id: sessionId,
projectId,
@@ -565,6 +594,13 @@ const enforceSessionAccess = t.middleware(async (opts) => {
});
}
+ if (ctx.session?.user?.admin === true) {
+ await sendAdminAccessWebhook({
+ email: ctx.session.user.email,
+ projectId,
+ });
+ }
+
return next({
ctx: {
session: {