Skip to content

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

feat: add server-side ingestion masking for OTEL traces (#11906)

Steffen Schmitz2b8701afc458
diff --git a/packages/shared/package.json b/packages/shared/package.json
index ae82082a94..8dafd95bcb 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -32,6 +32,10 @@
"./encryption": {
"import": "./dist/src/encryption/index.js",
"require": "./dist/src/encryption/index.js"
+ },
+ "./src/server/ee/ingestionMasking": {
+ "import": "./dist/src/server/ee/ingestionMasking/index.js",
+ "require": "./dist/src/server/ee/ingestionMasking/index.js"
}
},
"scripts": {
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 014970c0ee..5cb0bcced4 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -283,9 +283,34 @@ const EnvSchema = z.object({
LANGFUSE_DATASET_SERVICE_READ_FROM_VERSIONED_IMPLEMENTATION: z
.enum(["true", "false"])
.default("true"),
+
+ // EE License
+ LANGFUSE_EE_LICENSE_KEY: z.string().optional(),
+
+ // Ingestion Masking (EE feature)
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL: z.string().url().optional(),
+ LANGFUSE_INGESTION_MASKING_CALLBACK_TIMEOUT_MS: z.coerce
+ .number()
+ .positive()
+ .default(500),
+ LANGFUSE_INGESTION_MASKING_CALLBACK_FAIL_CLOSED: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_INGESTION_MASKING_MAX_RETRIES: z.coerce
+ .number()
+ .nonnegative()
+ .default(1),
+ LANGFUSE_INGESTION_MASKING_PROPAGATED_HEADERS: z
+ .string()
+ .optional()
+ .transform((s) =>
+ s ? s.split(",").map((h) => h.toLowerCase().trim()) : [],
+ ),
});
-export const env: z.infer<typeof EnvSchema> =
+export type SharedEnv = z.infer<typeof EnvSchema>;
+
+export const env: SharedEnv =
process.env.DOCKER_BUILD === "1" // eslint-disable-line turbo/no-undeclared-env-vars
? (process.env as any)
: EnvSchema.parse(removeEmptyEnvVariables(process.env));
diff --git a/packages/shared/src/server/ee/ingestionMasking/applyIngestionMasking.ts b/packages/shared/src/server/ee/ingestionMasking/applyIngestionMasking.ts
new file mode 100644
index 0000000000..ef6098b191
--- /dev/null
+++ b/packages/shared/src/server/ee/ingestionMasking/applyIngestionMasking.ts
@@ -0,0 +1,216 @@
+import { env, type SharedEnv } from "../../../env";
+import { logger } from "../../logger";
+import {
+ traceException,
+ recordHistogram,
+ recordIncrement,
+} from "../../instrumentation";
+import { isEnterpriseLicenseAvailable } from "../licenseCheck";
+import type {
+ IngestionMaskingConfig,
+ ApplyIngestionMaskingParams,
+ MaskingResult,
+} from "./types";
+
+/**
+ * Get ingestion masking configuration from environment variables.
+ * Returns null if the callback URL is not configured.
+ */
+export function getIngestionMaskingConfig(
+ envOverride?: SharedEnv,
+): IngestionMaskingConfig | null {
+ const e = envOverride ?? env;
+ const callbackUrl = e.LANGFUSE_INGESTION_MASKING_CALLBACK_URL;
+ if (!callbackUrl) {
+ return null;
+ }
+
+ return {
+ callbackUrl,
+ timeoutMs: e.LANGFUSE_INGESTION_MASKING_CALLBACK_TIMEOUT_MS,
+ failClosed: e.LANGFUSE_INGESTION_MASKING_CALLBACK_FAIL_CLOSED === "true",
+ maxRetries: e.LANGFUSE_INGESTION_MASKING_MAX_RETRIES,
+ propagatedHeaders: e.LANGFUSE_INGESTION_MASKING_PROPAGATED_HEADERS,
+ };
+}
+
+/**
+ * Check if ingestion masking is enabled.
+ * Returns true only if:
+ * 1. The callback URL is configured
+ * 2. An EE license is available (cloud or self-hosted with license)
+ */
+export function isIngestionMaskingEnabled(envOverride?: SharedEnv): boolean {
+ const config = getIngestionMaskingConfig(envOverride);
+ if (!config) {
+ return false;
+ }
+
+ if (!isEnterpriseLicenseAvailable(envOverride)) {
+ logger.warn(
+ "Ingestion masking callback URL is configured but enterprise license is not available. Masking will be disabled. Ingestion masking requires Langfuse Cloud or a self-hosted enterprise license (langfuse_ee_*).",
+ );
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Make an HTTP POST request to the masking callback with retry support.
+ */
+async function makeCallbackRequest<T>(params: {
+ config: IngestionMaskingConfig;
+ data: T;
+ projectId: string;
+ orgId?: string;
+ propagatedHeaders?: Record<string, string>;
+ attempt: number;
+}): Promise<{ success: boolean; data: T; error?: string }> {
+ const { config, data, projectId, orgId, propagatedHeaders, attempt } = params;
+ const startTime = Date.now();
+
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), config.timeoutMs);
+
+ try {
+ const headers: Record<string, string> = {
+ "Content-Type": "application/json",
+ "X-Langfuse-Org-Id": orgId ?? "",
+ "X-Langfuse-Project-Id": projectId,
+ ...propagatedHeaders,
+ };
+
+ const response = await fetch(config.callbackUrl, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(data),
+ signal: controller.signal,
+ });
+
+ const duration = Date.now() - startTime;
+ recordHistogram(
+ "langfuse.ingestion.masking.callback_duration_ms",
+ duration,
+ {
+ status: response.ok ? "success" : "error",
+ attempt: attempt.toString(),
+ },
+ );
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => "Unknown error");
+ return {
+ success: false,
+ data,
+ error: `HTTP ${response.status}: ${errorText}`,
+ };
+ }
+
+ const maskedData = (await response.json()) as T;
+ return { success: true, data: maskedData };
+ } catch (error) {
+ const duration = Date.now() - startTime;
+ recordHistogram(
+ "langfuse.ingestion.masking.callback_duration_ms",
+ duration,
+ {
+ status: "error",
+ attempt: attempt.toString(),
+ },
+ );
+
+ if (error instanceof Error && error.name === "AbortError") {
+ return { success: false, data, error: "Request timeout" };
+ }
+
+ return {
+ success: false,
+ data,
+ error: error instanceof Error ? error.message : "Unknown error",
+ };
+ } finally {
+ clearTimeout(timeoutId);
+ }
+}
+
+/**
+ * Apply ingestion masking to data by making an HTTP callback to an external masking endpoint.
+ *
+ * This feature masks sensitive data from OTEL events before storage in ClickHouse.
+ *
+ * @param params - The parameters for the masking operation
+ * @returns A MaskingResult containing the (potentially masked) data and success status
+ */
+export async function applyIngestionMasking<T>(
+ params: ApplyIngestionMaskingParams<T>,
+ envOverride?: SharedEnv,
+): Promise<MaskingResult<T>> {
+ const { data, projectId, orgId, propagatedHeaders } = params;
+
+ if (!isIngestionMaskingEnabled(envOverride)) {
+ return { success: true, data, masked: false };
+ }
+
+ const config = getIngestionMaskingConfig(envOverride)!;
+
+ // Attempt the callback with retries
+ let lastError: string | undefined;
+ for (let attempt = 1; attempt <= config.maxRetries + 1; attempt++) {
+ const result = await makeCallbackRequest({
+ config,
+ data,
+ projectId,
+ orgId,
+ propagatedHeaders,
+ attempt,
+ });
+
+ if (result.success) {
+ recordIncrement("langfuse.ingestion.masking.success", 1, {
+ attempt: attempt.toString(),
+ });
+ return { success: true, data: result.data, masked: true };
+ }
+
+ lastError = result.error;
+ logger.warn(
+ `Ingestion masking callback failed (attempt ${attempt}/${config.maxRetries + 1}): ${lastError}`,
+ { projectId, orgId },
+ );
+
+ // Don't retry if this was the last attempt
+ if (attempt <= config.maxRetries) {
+ // Small delay before retry (exponential backoff capped at 1 second)
+ const delay = Math.min(100 * Math.pow(2, attempt - 1), 1000);
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ }
+
+ // All retries exhausted
+ recordIncrement("langfuse.ingestion.masking.failure", 1, {
+ fail_closed: config.failClosed.toString(),
+ });
+
+ const error = new Error(
+ `Ingestion masking callback failed after ${config.maxRetries + 1} attempts: ${lastError}`,
+ );
+ traceException(error);
+
+ if (config.failClosed) {
+ // Fail closed: return failure so the event is dropped
+ return {
+ success: false,
+ data,
+ masked: false,
+ error: lastError,
+ };
+ }
+
+ // Fail open: return success with original data
+ logger.warn(
+ `Ingestion masking failed, processing with original data (fail-open mode)`,
+ { projectId, orgId, error: lastError },
+ );
+ return { success: true, data, masked: false };
+}
diff --git a/packages/shared/src/server/ee/ingestionMasking/index.ts b/packages/shared/src/server/ee/ingestionMasking/index.ts
new file mode 100644
index 0000000000..0f77ae9a43
--- /dev/null
+++ b/packages/shared/src/server/ee/ingestionMasking/index.ts
@@ -0,0 +1,2 @@
+export * from "./types";
+export * from "./applyIngestionMasking";
diff --git a/packages/shared/src/server/ee/ingestionMasking/types.ts b/packages/shared/src/server/ee/ingestionMasking/types.ts
new file mode 100644
index 0000000000..a8aad972aa
--- /dev/null
+++ b/packages/shared/src/server/ee/ingestionMasking/types.ts
@@ -0,0 +1,44 @@
+/**
+ * Configuration for ingestion masking callback.
+ * Read from environment variables.
+ */
+export interface IngestionMaskingConfig {
+ /** URL of the external masking callback endpoint */
+ callbackUrl: string;
+ /** Timeout in milliseconds for the callback request */
+ timeoutMs: number;
+ /** If true, drop events when masking fails. If false, process original data. */
+ failClosed: boolean;
+ /** Maximum number of retry attempts for failed requests */
+ maxRetries: number;
+ /** List of header names to propagate from the original request */
+ propagatedHeaders: string[];
+}
+
+/**
+ * Input parameters for the applyIngestionMasking function.
+ */
+export interface ApplyIngestionMaskingParams<T> {
+ /** The data to be masked */
+ data: T;
+ /** The project ID for the data */
+ projectId: string;
+ /** The organization ID for the data */
+ orgId?: string;
+ /** Headers to propagate to the masking callback */
+ propagatedHeaders?: Record<string, string>;
+}
+
+/**
+ * Result of the masking operation.
+ */
+export interface MaskingResult<T> {
+ /** Whether the masking operation succeeded */
+ success: boolean;
+ /** The (potentially masked) data */
+ data: T;
+ /** Whether the data was actually masked */
+ masked: boolean;
+ /** Error message if the operation failed */
+ error?: string;
+}
diff --git a/packages/shared/src/server/ee/licenseCheck/index.ts b/packages/shared/src/server/ee/licenseCheck/index.ts
new file mode 100644
index 0000000000..e28324846e
--- /dev/null
+++ b/packages/shared/src/server/ee/licenseCheck/index.ts
@@ -0,0 +1,26 @@
+import { env, type SharedEnv } from "../../../env";
+
+/**
+ * Check if enterprise EE license is available.
+ * Returns true for:
+ * - Langfuse Cloud (any region)
+ * - Self-hosted with enterprise license key (starts with "langfuse_ee_")
+ *
+ * Note: Pro tier (langfuse_pro_*) does NOT count as enterprise.
+ */
+export function isEnterpriseLicenseAvailable(envOverride?: SharedEnv): boolean {
+ const e = envOverride ?? env;
+
+ // Langfuse Cloud always has enterprise features
+ if (e.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined) {
+ return true;
+ }
+
+ // Self-hosted: must have enterprise license key (not pro)
+ const licenseKey = e.LANGFUSE_EE_LICENSE_KEY;
+ if (licenseKey && licenseKey.startsWith("langfuse_ee_")) {
+ return true;
+ }
+
+ return false;
+}
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
index 8e24178642..39fa02f678 100644
--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
@@ -38,6 +38,8 @@ interface TraceState {
export interface OtelIngestionProcessorConfig {
projectId: string;
publicKey?: string;
+ orgId?: string;
+ propagatedHeaders?: Record<string, string>;
}
interface CreateTraceEventParams {
@@ -114,10 +116,14 @@ export class OtelIngestionProcessor {
};
private readonly projectId: string;
private readonly publicKey?: string;
+ private readonly orgId?: string;
+ private readonly propagatedHeaders?: Record<string, string>;
constructor(config: OtelIngestionProcessorConfig) {
this.projectId = config.projectId;
this.publicKey = config.publicKey;
+ this.orgId = config.orgId;
+ this.propagatedHeaders = config.propagatedHeaders;
}
/**
@@ -157,8 +163,10 @@ export class OtelIngestionProcessor {
scope: {
projectId: this.projectId,
accessLevel: "project" as const,
+ orgId: this.orgId,
},
},
+ propagatedHeaders: this.propagatedHeaders,
},
})
: Promise.reject("Failed to instantiate otel ingestion queue");
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index e4cd00287e..aa12a14cd5 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -36,8 +36,10 @@ export const OtelIngestionEvent = z.object({
scope: z.object({
projectId: z.string(),
accessLevel: z.literal("project"),
+ orgId: z.string().optional(),
}),
}),
+ propagatedHeaders: z.record(z.string(), z.string()).optional(),
});
export const BatchExportJobSchema = z.object({
diff --git a/web/src/env.mjs b/web/src/env.mjs
index e6bcc19fcc..36f0aa4c9e 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -221,6 +221,14 @@ export const env = createEnv({
OTEL_SERVICE_NAME: z.string().default("web"),
OTEL_TRACE_SAMPLING_RATIO: z.coerce.number().gt(0).lte(1).default(1),
+ // OTel Masking
+ LANGFUSE_INGESTION_MASKING_PROPAGATED_HEADERS: z
+ .string()
+ .optional()
+ .transform((s) =>
+ s ? s.split(",").map((h) => h.toLowerCase().trim()) : [],
+ ),
+
// clickhouse
CLICKHOUSE_URL: z.string().url(),
CLICKHOUSE_CLUSTER_NAME: z.string().default("default"),
@@ -591,6 +599,9 @@ export const env = createEnv({
OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,
OTEL_TRACE_SAMPLING_RATIO: process.env.OTEL_TRACE_SAMPLING_RATIO,
+ LANGFUSE_INGESTION_MASKING_PROPAGATED_HEADERS:
+ process.env.LANGFUSE_INGESTION_MASKING_PROPAGATED_HEADERS,
+
// S3 media upload
LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH:
process.env.LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH,
diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.ts
index 7152b12d7d..75c7fa957a 100644
--- a/web/src/pages/api/public/otel/v1/traces/index.ts
+++ b/web/src/pages/api/public/otel/v1/traces/index.ts
@@ -9,6 +9,7 @@ import { z } from "zod/v4";
import { $root } from "@/src/pages/api/public/otel/otlp-proto/generated/root";
import { gunzip } from "node:zlib";
import { ForbiddenError } from "@langfuse/shared";
+import { env } from "@/src/env.mjs";
export const config = {
api: {
@@ -103,9 +104,25 @@ export default withMiddlewares({
return {};
}
+ // Extract headers to propagate for ingestion masking
+ const propagatedHeaderNames =
+ env.LANGFUSE_INGESTION_MASKING_PROPAGATED_HEADERS;
+ const propagatedHeaders: Record<string, string> = {};
+ for (const headerName of propagatedHeaderNames) {
+ const value = req.headers[headerName];
+ if (typeof value === "string") {
+ propagatedHeaders[headerName] = value;
+ }
+ }
+
const processor = new OtelIngestionProcessor({
projectId: auth.scope.projectId,
publicKey: auth.scope.publicKey,
+ orgId: auth.scope.orgId,
+ propagatedHeaders:
+ Object.keys(propagatedHeaders).length > 0
+ ? propagatedHeaders
+ : undefined,
});
// At this point, we have the raw OpenTelemetry Span body. We upload the full batch to S3
diff --git a/worker/src/__tests__/ingestionMasking.test.ts b/worker/src/__tests__/ingestionMasking.test.ts
new file mode 100644
index 0000000000..406b7f4f25
--- /dev/null
+++ b/worker/src/__tests__/ingestionMasking.test.ts
@@ -0,0 +1,492 @@
+import {
+ describe,
+ it,
+ expect,
+ beforeEach,
+ beforeAll,
+ afterAll,
+ afterEach,
+} from "vitest";
+import { setupServer } from "msw/node";
+import { http, HttpResponse, delay } from "msw";
+import type { SharedEnv } from "@langfuse/shared/src/env";
+import {
+ applyIngestionMasking,
+ isIngestionMaskingEnabled,
+} from "@langfuse/shared/src/server/ee/ingestionMasking";
+
+// Sample OTEL span data for testing
+const sampleSpanData = [
+ {
+ resource: {
+ attributes: [
+ { key: "service.name", value: { stringValue: "test-service" } },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: { name: "test-scope" },
+ spans: [
+ {
+ traceId: "abc123",
+ spanId: "def456",
+ name: "test-span",
+ attributes: [
+ { key: "sensitive.data", value: { stringValue: "secret-value" } },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+];
+
+// Masked version of the sample data
+const maskedSpanData = [
+ {
+ resource: {
+ attributes: [
+ { key: "service.name", value: { stringValue: "test-service" } },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: { name: "test-scope" },
+ spans: [
+ {
+ traceId: "abc123",
+ spanId: "def456",
+ name: "test-span",
+ attributes: [
+ {
+ key: "sensitive.data",
+ value: { stringValue: "***REDACTED***" },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+];
+
+// Mock webhook server for testing HTTP requests
+class MaskingCallbackTestServer {
+ private server;
+ private receivedRequests: Array<{
+ url: string;
+ method: string;
+ headers: Record<string, string>;
+ body: unknown;
+ }> = [];
+
+ constructor() {
+ this.server = setupServer(
+ // Success endpoint - returns masked data
+ http.post("https://masking.example.com/success", async ({ request }) => {
+ this.receivedRequests.push({
+ url: request.url,
+ method: request.method,
+ headers: Object.fromEntries(request.headers.entries()),
+ body: await request.json(),
+ });
+ return HttpResponse.json(maskedSpanData, { status: 200 });
+ }),
+
+ // Echo endpoint - returns the same data it receives
+ http.post("https://masking.example.com/echo", async ({ request }) => {
+ const body = await request.json();
+ this.receivedRequests.push({
+ url: request.url,
+ method: request.method,
+ headers: Object.fromEntries(request.headers.entries()),
+ body,
+ });
+ return HttpResponse.json(body, { status: 200 });
+ }),
+
+ // Error endpoint - returns 500
+ http.post("https://masking.example.com/error", async ({ request }) => {
+ this.receivedRequests.push({
+ url: request.url,
+ method: request.method,
+ headers: Object.fromEntries(request.headers.entries()),
+ body: await request.json(),
+ });
+ return HttpResponse.json(
+ { error: "Internal Server Error" },
+ { status: 500 },
+ );
+ }),
+
+ // Timeout endpoint - delays response
+ http.post("https://masking.example.com/timeout", async ({ request }) => {
+ this.receivedRequests.push({
+ url: request.url,
+ method: request.method,
+ headers: Object.fromEntries(request.headers.entries()),
+ body: await request.json(),
+ });
+ // Delay longer than the timeout
+ await delay(5000);
+ return HttpResponse.json(maskedSpanData, { status: 200 });
+ }),
+ );
+ }
+
+ setup() {
+ this.server.listen();
+ }
+
+ reset() {
+ this.receivedRequests = [];
+ this.server.resetHandlers();
+ }
+
+ teardown() {
+ this.server.close();
+ }
+
+ getReceivedRequests() {
+ return this.receivedRequests;
+ }
+
+ getLastRequest() {
+ return this.receivedRequests[this.receivedRequests.length - 1];
+ }
+}
+
+const maskingServer = new MaskingCallbackTestServer();
+
+const VALID_EE_LICENSE_KEY = "langfuse_ee_test-license-key";
+
+// Default test env with masking disabled
+const defaultTestEnv: SharedEnv = {
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL: undefined,
+ LANGFUSE_INGESTION_MASKING_CALLBACK_TIMEOUT_MS: 500,
+ LANGFUSE_INGESTION_MASKING_CALLBACK_FAIL_CLOSED: "false",
+ LANGFUSE_INGESTION_MASKING_MAX_RETRIES: 1,
+ LANGFUSE_INGESTION_MASKING_PROPAGATED_HEADERS: [],
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined,
+ LANGFUSE_EE_LICENSE_KEY: undefined,
+} as SharedEnv;
+
+function createTestEnv(overrides: Partial<SharedEnv> = {}): SharedEnv {
+ return { ...defaultTestEnv, ...overrides } as SharedEnv;
+}
+
+describe("Ingestion Masking", () => {
+ beforeAll(() => {
+ maskingServer.setup();
+ });
+
+ beforeEach(() => {
+ maskingServer.reset();
+ });
+
+ afterEach(() => {
+ maskingServer.reset();
+ });
+
+ afterAll(() => {
+ maskingServer.teardown();
+ });
+
+ describe("isIngestionMaskingEnabled", () => {
+ it("should return false when callback URL is not configured", () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ });
+
+ expect(isIngestionMaskingEnabled(testEnv)).toBe(false);
+ });
+
+ it("should return false when EE license is not available", () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/success",
+ });
+
+ expect(isIngestionMaskingEnabled(testEnv)).toBe(false);
+ });
+
+ it("should return true when callback URL and EE license are configured", () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/success",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ });
+
+ expect(isIngestionMaskingEnabled(testEnv)).toBe(true);
+ });
+
+ it("should return true when callback URL is configured and running in cloud region", () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/success",
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "US",
+ });
+
+ expect(isIngestionMaskingEnabled(testEnv)).toBe(true);
+ });
+ });
+
+ describe("applyIngestionMasking", () => {
+ it("should return original data immediately when masking is not configured", async () => {
+ const testEnv = createTestEnv();
+
+ const result = await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.masked).toBe(false);
+ expect(result.data).toEqual(sampleSpanData);
+
+ // Verify no HTTP call was made
+ expect(maskingServer.getReceivedRequests()).toHaveLength(0);
+ });
+
+ it("should return original data when EE license is not available", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/success",
+ });
+
+ const result = await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.masked).toBe(false);
+ expect(result.data).toEqual(sampleSpanData);
+
+ // Verify no HTTP call was made
+ expect(maskingServer.getReceivedRequests()).toHaveLength(0);
+ });
+
+ it("should return masked data on successful callback", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/success",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ });
+
+ const result = await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.masked).toBe(true);
+ expect(result.data).toEqual(maskedSpanData);
+
+ // Verify HTTP call was made
+ const requests = maskingServer.getReceivedRequests();
+ expect(requests).toHaveLength(1);
+ expect(requests[0].body).toEqual(sampleSpanData);
+ });
+
+ it("should include X-Langfuse-Org-Id and X-Langfuse-Project-Id headers", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/success",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ });
+
+ await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project-123",
+ orgId: "test-org-456",
+ },
+ testEnv,
+ );
+
+ const request = maskingServer.getLastRequest();
+ expect(request?.headers["x-langfuse-org-id"]).toBe("test-org-456");
+ expect(request?.headers["x-langfuse-project-id"]).toBe(
+ "test-project-123",
+ );
+ });
+
+ it("should propagate custom headers when configured", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/success",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ });
+
+ await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ propagatedHeaders: {
+ "x-custom-header": "custom-value",
+ "x-another-header": "another-value",
+ },
+ },
+ testEnv,
+ );
+
+ const request = maskingServer.getLastRequest();
+ expect(request?.headers["x-custom-header"]).toBe("custom-value");
+ expect(request?.headers["x-another-header"]).toBe("another-value");
+ });
+
+ it("should return original data on HTTP 500 with fail-open (default)", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/error",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ LANGFUSE_INGESTION_MASKING_CALLBACK_FAIL_CLOSED: "false",
+ LANGFUSE_INGESTION_MASKING_MAX_RETRIES: 0,
+ });
+
+ const result = await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.masked).toBe(false);
+ expect(result.data).toEqual(sampleSpanData);
+ });
+
+ it("should return failure on HTTP 500 with fail-closed", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/error",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ LANGFUSE_INGESTION_MASKING_CALLBACK_FAIL_CLOSED: "true",
+ LANGFUSE_INGESTION_MASKING_MAX_RETRIES: 0,
+ });
+
+ const result = await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.masked).toBe(false);
+ expect(result.error).toContain("500");
+ });
+
+ it("should retry on failure", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/error",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ LANGFUSE_INGESTION_MASKING_CALLBACK_FAIL_CLOSED: "false",
+ LANGFUSE_INGESTION_MASKING_MAX_RETRIES: 2,
+ });
+
+ await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ // Should have made 3 requests (1 initial + 2 retries)
+ const requests = maskingServer.getReceivedRequests();
+ expect(requests).toHaveLength(3);
+ });
+
+ it("should handle timeout with fail-open", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/timeout",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ LANGFUSE_INGESTION_MASKING_CALLBACK_TIMEOUT_MS: 100, // Short timeout
+ LANGFUSE_INGESTION_MASKING_CALLBACK_FAIL_CLOSED: "false",
+ LANGFUSE_INGESTION_MASKING_MAX_RETRIES: 0,
+ });
+
+ const result = await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.masked).toBe(false);
+ expect(result.data).toEqual(sampleSpanData);
+ }, 10000);
+
+ it("should handle timeout with fail-closed", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/timeout",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ LANGFUSE_INGESTION_MASKING_CALLBACK_TIMEOUT_MS: 100, // Short timeout
+ LANGFUSE_INGESTION_MASKING_CALLBACK_FAIL_CLOSED: "true",
+ LANGFUSE_INGESTION_MASKING_MAX_RETRIES: 0,
+ });
+
+ const result = await applyIngestionMasking(
+ {
+ data: sampleSpanData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.masked).toBe(false);
+ expect(result.error).toContain("timeout");
+ }, 10000);
+
+ it("should work with generic data types", async () => {
+ const testEnv = createTestEnv({
+ LANGFUSE_INGESTION_MASKING_CALLBACK_URL:
+ "https://masking.example.com/echo",
+ LANGFUSE_EE_LICENSE_KEY: VALID_EE_LICENSE_KEY,
+ });
+
+ const customData = { key: "value", nested: { data: [1, 2, 3] } };
+
+ const result = await applyIngestionMasking(
+ {
+ data: customData,
+ projectId: "test-project",
+ orgId: "test-org",
+ },
+ testEnv,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.masked).toBe(true);
+ expect(result.data).toEqual(customData);
+ });
+ });
+});
diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.ts
index a05effcc32..f7778ad914 100644
--- a/worker/src/queues/otelIngestionQueue.ts
+++ b/worker/src/queues/otelIngestionQueue.ts
@@ -19,6 +19,10 @@ import {
compareVersions,
ResourceSpan,
} from "@langfuse/shared/src/server";
+import {
+ applyIngestionMasking,
+ isIngestionMaskingEnabled,
+} from "@langfuse/shared/src/server/ee/ingestionMasking";
import { env } from "../env";
import { IngestionService } from "../services/IngestionService";
import { prisma } from "@langfuse/shared/src/db";
@@ -158,12 +162,34 @@ export const otelIngestionQueueProcessor: Processor = async (
},
);
+ // Parse spans from S3 download
+ let parsedSpans = JSON.parse(resourceSpans);
+
+ // Apply ingestion masking if enabled (EE feature)
+ if (isIngestionMaskingEnabled()) {
+ const maskingResult = await applyIngestionMasking({
+ data: parsedSpans,
+ projectId,
+ orgId: job.data.payload.authCheck.scope.orgId,
+ propagatedHeaders: job.data.payload.propagatedHeaders,
+ });
+
+ if (!maskingResult.success) {
+ // Fail-closed: drop event
+ logger.warn(`Dropping OTEL event due to masking failure`, {
+ projectId,
+ error: maskingResult.error,
+ });
+ return;
+ }
+ parsedSpans = maskingResult.data;
+ }
+
// Generate events via OtelIngestionProcessor
const processor = new OtelIngestionProcessor({
projectId,
publicKey,
});
- const parsedSpans = JSON.parse(resourceSpans);
const events: IngestionEventType[] =
await processor.processToIngestionEvents(parsedSpans);
// Here, we split the events into observations and non-observations.