🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
import { createHash } from "node:crypto";
import { Readable } from "node:stream";
import { propagation, ROOT_CONTEXT } from "@opentelemetry/api";
import type { NextApiRequest, NextApiResponse } from "next";
import { afterEach, describe, expect, it, vi } from "vitest";
import { signHmacSha256 } from "@/src/server/utils/hmac";
import { createShaHash } from "@langfuse/shared/src/server/auth/apiKeys";
import {
contextWithGatewayRequestId,
withGatewayModelsSignatureVerification,
withGatewayResolveSignatureVerification,
} from "./gatewayRequestSignatureVerifier";
vi.mock("@/src/env.mjs", () => ({
env: {
LANGFUSE_AI_GATEWAY_SERVICE_KEY: "current-service-secret",
LANGFUSE_AI_GATEWAY_SERVICE_KEY_PREVIOUS: "previous-service-secret",
LANGFUSE_AI_GATEWAY_DEPLOYED: "true",
LANGFUSE_AI_GATEWAY_ENABLED: "false",
LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST: ["org-1"],
SALT: "test-salt",
},
}));
const now = new Date("2026-09-07T12:00:00.000Z");
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
function response() {
const res = {
setHeader: vi.fn(),
status: vi.fn(),
json: vi.fn(),
};
res.status.mockReturnValue(res);
res.json.mockReturnValue(res);
return res as unknown as NextApiResponse;
}
function request(input: {
authorization?: string;
gatewayAuthorization?: string;
body?: string;
method?: string;
query?: NextApiRequest["query"];
}) {
return Object.assign(Readable.from([input.body ?? ""]), {
method: input.method ?? "POST",
headers: {
authorization: input.authorization,
"langfuse-gateway-authorization": input.gatewayAuthorization,
},
body: undefined,
query: input.query ?? {},
}) as unknown as NextApiRequest;
}
function gatewayAuthorization(input: {
secret: string;
timestamp?: number;
key?: string;
}) {
const timestamp = input.timestamp ?? Math.floor(now.getTime() / 1000);
const sha256 = (value: string) =>
createHash("sha256").update(value, "utf8").digest("hex");
const canonicalMessage = [
"gateway-web-v1",
timestamp.toString(),
sha256(input.key ?? "sk-gateway"),
].join("\n");
return `HMAC timestamp=${timestamp},signature=${signHmacSha256(
canonicalMessage,
input.secret,
)}`;
}
describe("withGatewayResolveSignatureVerification", () => {
it.each([
undefined,
"Basic sk-gateway",
"Bearer",
"Bearer ",
"bearer sk-gateway",
"Bearer sk-gateway extra",
])("rejects an invalid Bearer header: %s", async (authorization) => {
const handler = vi.fn();
const res = response();
await withGatewayResolveSignatureVerification(handler)(
request({
authorization,
body: '{"apiFormat":"openai.responses"}',
}),
res,
);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ error: "Invalid Bearer token" });
expect(handler).not.toHaveBeenCalled();
});
it.each(["current-service-secret", "previous-service-secret"])(
"verifies the RFC payload with configured secret %s",
async (secret) => {
vi.useFakeTimers();
vi.setSystemTime(now);
const body =
'{ "apiFormat": "openai.responses", "model": "gpt-5", "requestBytes": 512 }\n';
const req = request({
authorization: " Bearer sk-gateway ",
gatewayAuthorization: gatewayAuthorization({ secret }),
body,
});
const res = response();
const handler = vi.fn().mockResolvedValue(undefined);
await withGatewayResolveSignatureVerification(handler)(req, res);
expect(handler).toHaveBeenCalledWith({
req,
res,
fastHashedSecretKey: createShaHash("sk-gateway", "test-salt"),
apiFormat: "openai.responses",
model: "gpt-5",
requestBytes: 512,
});
},
);
it.each(["production: ", "production:\t"])(
"rejects a whitespace-only provider model in %j",
async (model) => {
const handler = vi.fn();
const res = response();
await withGatewayResolveSignatureVerification(handler)(
request({
authorization: "Bearer sk-gateway",
body: JSON.stringify({
apiFormat: "openai.responses",
model,
requestBytes: 0,
}),
}),
res,
);
expect(res.status).toHaveBeenCalledWith(400);
expect(res.json).toHaveBeenCalledWith({ error: "Invalid request" });
expect(handler).not.toHaveBeenCalled();
},
);
it("rejects a missing Bearer token on the models endpoint", async () => {
const handler = vi.fn();
const res = response();
await withGatewayModelsSignatureVerification(handler)(
request({ method: "GET", query: { api_format: "anthropic.messages" } }),
res,
);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ error: "Invalid Bearer token" });
expect(handler).not.toHaveBeenCalled();
});
it("accepts the same signature on the models endpoint", async () => {
vi.useFakeTimers();
vi.setSystemTime(now);
const handler = vi.fn().mockResolvedValue(undefined);
const req = request({
method: "GET",
authorization: "Bearer sk-gateway",
gatewayAuthorization: gatewayAuthorization({
secret: "current-service-secret",
}),
query: { api_format: "anthropic.messages" },
});
const res = response();
await withGatewayModelsSignatureVerification(handler)(req, res);
expect(handler).toHaveBeenCalledWith({
req,
res,
fastHashedSecretKey: createShaHash("sk-gateway", "test-salt"),
apiFormat: "anthropic.messages",
});
});
it("rejects a signature made for a different gateway key", async () => {
vi.useFakeTimers();
vi.setSystemTime(now);
const handler = vi.fn();
const res = response();
await withGatewayResolveSignatureVerification(handler)(
request({
authorization: "Bearer sk-gateway",
gatewayAuthorization: gatewayAuthorization({
secret: "current-service-secret",
key: "sk-other-gateway",
}),
body: '{"apiFormat":"openai.responses","model":"gpt-5","requestBytes":0}',
}),
res,
);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.setHeader).toHaveBeenCalledWith(
"langfuse-gateway-error-code",
"invalid_gateway_authorization",
);
expect(handler).not.toHaveBeenCalled();
});
it("rejects stale signatures and headers containing a key id", async () => {
vi.useFakeTimers();
vi.setSystemTime(now);
const body =
'{"apiFormat":"openai.responses","model":"gpt-5","requestBytes":0}';
const staleHeader = gatewayAuthorization({
secret: "current-service-secret",
timestamp: Math.floor(now.getTime() / 1000) - 301,
});
for (const header of [staleHeader, `${staleHeader},keyid=current`]) {
const handler = vi.fn();
const res = response();
await withGatewayResolveSignatureVerification(handler)(
request({
authorization: "Bearer sk-gateway",
gatewayAuthorization: header,
body,
}),
res,
);
expect(res.status).toHaveBeenCalledWith(401);
expect(handler).not.toHaveBeenCalled();
}
});
});
describe("contextWithGatewayRequestId", () => {
const requestId = "0192b6f4-6c1e-7a3b-8c4d-5e6f7a8b9c0d";
const loggedRequestId = (headers: NextApiRequest["headers"]) =>
propagation
.getBaggage(
contextWithGatewayRequestId(
{ headers } as NextApiRequest,
ROOT_CONTEXT,
),
)
?.getEntry("langfuse.gateway.request.id")?.value;
it("adds the gateway request ID to the log context", () => {
expect(loggedRequestId({ "langfuse-gateway-request-id": requestId })).toBe(
requestId,
);
});
it.each([
["missing", {}],
["not a UUID", { "langfuse-gateway-request-id": "req\ninjected" }],
["repeated", { "langfuse-gateway-request-id": [requestId, requestId] }],
])("ignores a %s request ID", (_, headers) => {
expect(loggedRequestId(headers)).toBeUndefined();
});
});