Skip to content

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

feat: cache api keys in redis (#2739)

Max Deichmann41ab5e0b7b5b
diff --git a/.env.prod.example b/.env.prod.example
index cdf7143970..0db0c7adbb 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -157,5 +157,9 @@ LANGFUSE_CSP_ENFORCE_HTTPS="true"
# REDIS_AUTH=
# REDIS_CONNECTION_STRING=
+# Cache configuration
+# LANGFUSE_CACHE_API_KEY_ENABLED=
+# LANGFUSE_CACHE_API_KEY_TTL=
+
### END Langfuse Cloud Config
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c73a1049c0..765c8028d2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -40,7 +40,7 @@ importers:
next-auth:
specifier: ^4.24.7
zod:
specifier: ^3.23.8
version: 3.23.8
@@ -423,6 +423,9 @@ importers:
bcryptjs:
specifier: ^2.4.3
version: 2.4.3
+ bullmq:
+ specifier: ^5.4.2
+ version: 5.4.3
class-variance-authority:
specifier: ^0.7.0
version: 0.7.0
@@ -453,6 +456,9 @@ importers:
graphql:
specifier: ^16.9.0
version: 16.9.0
+ ioredis:
+ specifier: ^5.4.1
+ version: 5.4.1
ip-address:
specifier: ^9.0.5
version: 9.0.5
@@ -476,7 +482,7 @@ importers:
next-auth:
specifier: ^4.24.7
next-query-params:
specifier: ^5.0.0
@@ -15296,7 +15302,7 @@ snapshots:
'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 7.12.0([email protected])([email protected])
eslint-config-prettier: 9.1.0([email protected])
+ eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))
eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
eslint-plugin-eslint-comments: 3.2.0([email protected])
@@ -17005,7 +17011,7 @@ snapshots:
eslint: 8.57.0
eslint-plugin-turbo: 1.13.4([email protected])
dependencies:
@@ -19814,6 +19820,23 @@ snapshots:
optionalDependencies:
nodemailer: 6.9.13
+ dependencies:
+ '@babel/runtime': 7.24.5
+ '@panva/hkdf': 1.1.1
+ cookie: 0.5.0
+ jose: 4.15.5
+ oauth: 0.9.15
+ openid-client: 5.6.5
+ preact: 10.19.7
+ preact-render-to-string: 5.2.6([email protected])
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ uuid: 8.3.2
+ optionalDependencies:
+ nodemailer: 6.9.13
+
dependencies:
'@babel/runtime': 7.24.5
diff --git a/web/jest.config.mjs b/web/jest.config.mjs
index bf6c6b646c..9c97d09ad1 100644
--- a/web/jest.config.mjs
+++ b/web/jest.config.mjs
@@ -10,8 +10,6 @@ const clientTestConfig = {
displayName: "client",
testMatch: ["/**/*.clienttest.[jt]s?(x)"],
testEnvironment: "jest-environment-jsdom",
- // setupFilesAfterEnv: ["<rootDir>/src/__tests__/after-teardown.ts"],
- // globalTeardown: "<rootDir>/src/__tests__/teardown.ts",
};
const serverTestConfig = {
diff --git a/web/package.json b/web/package.json
index b07790da1a..7c5607679f 100644
--- a/web/package.json
+++ b/web/package.json
@@ -14,7 +14,7 @@
"prettier": "prettier --write ./src *.{ts,js}",
"clean": "rm -rf node_modules",
"start": "dotenv -e ../.env -- sh -c 'NEXT_MANUAL_SIG_HANDLE=true next start'",
- "test": "dotenv -e ../.env -- jest --runInBand --detectOpenHandles",
+ "test": "dotenv -e ../.env -- jest --runInBand --detectOpenHandles --verbose",
"test:watch": "dotenv -e ../.env -- jest --watch --runInBand",
"test:e2e": "dotenv -e ../.env -- playwright test",
"models:migrate": "dotenv -e ../.env -- tsx scripts/model-match.ts",
@@ -78,6 +78,7 @@
"@uiw/react-codemirror": "^4.21.25",
"ai": "^3.0.23",
"bcryptjs": "^2.4.3",
+ "bullmq": "^5.4.2",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
@@ -88,6 +89,7 @@
"dompurify": "^3.1.5",
"exponential-backoff": "^3.1.1",
"graphql": "^16.9.0",
+ "ioredis": "^5.4.1",
"ip-address": "^9.0.5",
"js-tiktoken": "^1.0.12",
"kysely": "^0.27.3",
diff --git a/web/src/__tests__/api-auth.servertest.ts b/web/src/__tests__/api-auth.servertest.ts
index 972b3ee187..106d204042 100644
--- a/web/src/__tests__/api-auth.servertest.ts
+++ b/web/src/__tests__/api-auth.servertest.ts
@@ -2,87 +2,347 @@ import {
getDisplaySecretKey,
hashSecretKey,
} from "@langfuse/shared/src/server";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
-import { prisma } from "@langfuse/shared/src/db";
+import {
+ ApiAuthService,
+ ApiKeyZod,
+} from "@/src/features/public-api/server/apiAuth";
+import { type PrismaClient, prisma } from "@langfuse/shared/src/db";
+import { Redis } from "ioredis";
+import { env } from "@/src/env.mjs";
-describe("Validate api calls", () => {
+describe("Authenticate API calls", () => {
beforeEach(async () => {
await prisma.score.deleteMany();
await prisma.observation.deleteMany();
await prisma.trace.deleteMany();
await prisma.apiKey.deleteMany();
});
+ afterEach(async () => {
+ await prisma.score.deleteMany();
+ await prisma.observation.deleteMany();
+ await prisma.trace.deleteMany();
+ await prisma.apiKey.deleteMany();
+ });
- it("should create new api key", async () => {
- await createAPIKey();
- const auth = await verifyAuthHeaderAndReturnScope(
- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
- );
- expect(auth.validKey).toBe(true);
+ describe("validates without redis", () => {
+ it("should create new api key", async () => {
+ await createAPIKey();
+ const auth = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
- const apiKey = await prisma.apiKey.findUnique({
- where: { publicKey: "pk-lf-1234567890" },
+ expect(auth.validKey).toBe(true);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
});
- expect(apiKey).not.toBeNull();
- expect(apiKey?.fastHashedSecretKey).not.toBeNull();
- });
- it("should create new api key and succeed with new key", async () => {
- await createAPIKey();
- const auth = await verifyAuthHeaderAndReturnScope(
- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
- );
- expect(auth.validKey).toBe(true);
+ it("should create new api key and succeed with new key", async () => {
+ await createAPIKey();
+ const auth = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+ expect(auth.validKey).toBe(true);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
- const apiKey = await prisma.apiKey.findUnique({
- where: { publicKey: "pk-lf-1234567890" },
+ const auth2 = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+ expect(auth2.validKey).toBe(true);
});
- expect(apiKey).not.toBeNull();
- expect(apiKey?.fastHashedSecretKey).not.toBeNull();
- const auth2 = await verifyAuthHeaderAndReturnScope(
- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
- );
- expect(auth2.validKey).toBe(true);
- });
+ it("should fail on wrong api key with new key", async () => {
+ await createAPIKey();
+ const auth = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+ expect(auth.validKey).toBe(true);
- it("should fail on wrong api key with new key", async () => {
- await createAPIKey();
- const auth = await verifyAuthHeaderAndReturnScope(
- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
- );
- expect(auth.validKey).toBe(true);
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
- const apiKey = await prisma.apiKey.findUnique({
- where: { publicKey: "pk-lf-1234567890" },
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
+
+ const wrongAuth = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",
+ );
+ expect(wrongAuth.validKey).toBe(false);
});
- expect(apiKey).not.toBeNull();
- expect(apiKey?.fastHashedSecretKey).not.toBeNull();
- const wrongAuth = await verifyAuthHeaderAndReturnScope(
- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",
- );
- expect(wrongAuth.validKey).toBe(false);
+ it("should fail on wrong api key without new key", async () => {
+ await createAPIKey();
+ const initialApiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(initialApiKey).not.toBeNull();
+ expect(initialApiKey?.fastHashedSecretKey).toBeNull();
+
+ const auth = await new ApiAuthService(
+ prisma,
+ null,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",
+ );
+ expect(auth.validKey).toBe(false);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).toBeNull();
+ });
});
- it("should fail on wrong api key without new key", async () => {
- await createAPIKey();
- const initialApiKey = await prisma.apiKey.findUnique({
- where: { publicKey: "pk-lf-1234567890" },
+ describe("validates with redis", () => {
+ const redis = new Redis("redis://:[email protected]:6379", {
+ maxRetriesPerRequest: null,
+ });
+
+ afterEach(async () => {
+ // if we do not remove the key, it will remain in the cache and
+ // calling the test twice will not add the key to the cache
+ const keys = await redis.keys("api-key*");
+ if (keys.length > 0) {
+ await redis.del(keys);
+ }
+ });
+ beforeEach(async () => {
+ // if we do not remove the key, it will remain in the cache and
+ // calling the test twice will not add the key to the cache
+ const keys = await redis.keys("api-key*");
+ if (keys.length > 0) {
+ await redis.del(keys);
+ }
+ });
+
+ afterAll(async () => {
+ redis.disconnect();
+ });
+
+ it("should create new api key and read from cache", async () => {
+ await createAPIKey();
+
+ // first auth will generate the fast hashed api key
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
+
+ const cachedKey = await redis.get(
+ `api-key:${apiKey?.fastHashedSecretKey}`,
+ );
+ expect(cachedKey).toBeNull();
+
+ // second will add the key to redis
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ const cachedKey2 = await redis.get(
+ `api-key:${apiKey?.fastHashedSecretKey}`,
+ );
+
+ expect(cachedKey2).not.toBeNull();
+
+ const parsed = ApiKeyZod.parse(JSON.parse(cachedKey2!));
+
+ expect(parsed).toEqual({
+ ...apiKey,
+ createdAt: apiKey?.createdAt.toISOString(),
+ });
});
- expect(initialApiKey).not.toBeNull();
- expect(initialApiKey?.fastHashedSecretKey).toBeNull();
- const auth = await verifyAuthHeaderAndReturnScope(
- "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkx",
- );
- expect(auth.validKey).toBe(false);
+ it("prisma should not be used when reading cached keys", async () => {
+ await createAPIKey();
+
+ // Mock prisma
+ const mockPrisma = {
+ apiKey: {
+ findUnique: jest.fn(),
+ },
+ };
+
+ // first auth will generate the fast hashed api key
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ // second will add the key to redis
+ const auth2 = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ // third will read from redis only
+ await new ApiAuthService(
+ mockPrisma as unknown as PrismaClient,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ expect(auth2.validKey).toBe(true);
+
+ // Ensure prisma was not called
+ expect(mockPrisma.apiKey.findUnique).not.toHaveBeenCalled();
+
+ const cachedKey = await redis.get(
+ "api-key:ed6818ada09bdad405a74ac72773dde1708dd3fc6fe8bb81b59927400419d227",
+ );
+ expect(cachedKey).not.toBeNull();
+
+ const parsed = ApiKeyZod.parse(JSON.parse(cachedKey!));
+
+ expect(parsed).toEqual({
+ id: expect.any(String),
+ note: "seeded key",
+ publicKey: "pk-lf-1234567890",
+ hashedSecretKey: expect.any(String),
+ fastHashedSecretKey: expect.any(String),
+ displaySecretKey: expect.any(String),
+ createdAt: expect.any(String),
+ lastUsedAt: null,
+ expiresAt: null,
+ projectId: expect.any(String),
+ });
+ });
+
+ it("ttl should be increased when reading from redis", async () => {
+ await createAPIKey();
+
+ // Mock prisma
+ const mockPrisma = {
+ apiKey: {
+ findUnique: jest.fn(),
+ },
+ };
+
+ // first auth will generate the fast hashed api key
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ // second will add the key to redis
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ // third will read from redis only
+ await new ApiAuthService(
+ mockPrisma as unknown as PrismaClient,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ const ttl = await redis.ttl(
+ "api-key:ed6818ada09bdad405a74ac72773dde1708dd3fc6fe8bb81b59927400419d227",
+ );
+
+ expect(ttl).toBeGreaterThan(env.LANGFUSE_CACHE_API_KEY_TTL - 2);
+
+ // wait for 5 seconds
+ await new Promise((resolve) => setTimeout(resolve, 5000));
+
+ await new ApiAuthService(
+ mockPrisma as unknown as PrismaClient,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ const ttl2 = await redis.ttl(
+ "api-key:ed6818ada09bdad405a74ac72773dde1708dd3fc6fe8bb81b59927400419d227",
+ );
+
+ expect(ttl2).toBeGreaterThan(env.LANGFUSE_CACHE_API_KEY_TTL - 2);
+ }, 10000);
+
+ it("should delete API keys from cache and db", async () => {
+ await createAPIKey();
+
+ // first auth will generate the fast hashed api key
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ // second will add the key to redis
+ const auth2 = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(
+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",
+ );
+
+ expect(auth2.validKey).toBe(true);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: "pk-lf-1234567890" },
+ });
+
+ expect(apiKey).not.toBeNull();
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
+
+ const cachedKey = await redis.get(
+ `api-key:${apiKey?.fastHashedSecretKey}`,
+ );
+ expect(cachedKey).not.toBeNull();
+
+ const parsed = ApiKeyZod.parse(JSON.parse(cachedKey!));
+
+ expect(parsed).toEqual({
+ ...apiKey,
+ createdAt: apiKey?.createdAt.toISOString(),
+ });
+
+ await new ApiAuthService(prisma, redis).deleteApiKey(
+ apiKey?.id!,
+ apiKey?.projectId!,
+ );
+
+ const deletedApiKey = await prisma.apiKey.findUnique({
+ where: { id: apiKey?.id! },
+ });
+ expect(deletedApiKey).toBeNull();
- const apiKey = await prisma.apiKey.findUnique({
- where: { publicKey: "pk-lf-1234567890" },
+ const deletedCachedKey = await redis.get(
+ `api-key:${apiKey?.fastHashedSecretKey}`,
+ );
+ expect(deletedCachedKey).toBeNull();
});
- expect(apiKey).not.toBeNull();
- expect(apiKey?.fastHashedSecretKey).toBeNull();
});
const createAPIKey = async () => {
diff --git a/web/src/__tests__/teardown.ts b/web/src/__tests__/teardown.ts
index e19329f2d3..9b92a1e8e4 100644
--- a/web/src/__tests__/teardown.ts
+++ b/web/src/__tests__/teardown.ts
@@ -4,7 +4,7 @@ export default async function teardown() {
if (!redis) {
return;
}
- if (redis.status === "end") {
+ if (redis.status === "end" || redis.status === "close") {
console.log("Redis connection already closed");
return;
}
diff --git a/web/src/env.mjs b/web/src/env.mjs
index b18d5a2132..f4c09dc5e5 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -132,6 +132,9 @@ export const env = createEnv({
.nullable(),
REDIS_AUTH: z.string().nullish(),
REDIS_CONNECTION_STRING: z.string().nullish(),
+ // langfuse caching
+ LANGFUSE_CACHE_API_KEY_ENABLED: z.enum(["true", "false"]).default("false"),
+ LANGFUSE_CACHE_API_KEY_TTL: z.number().default(60),
},
/**
@@ -255,6 +258,9 @@ export const env = createEnv({
REDIS_PORT: process.env.REDIS_PORT,
REDIS_AUTH: process.env.REDIS_AUTH,
REDIS_CONNECTION_STRING: process.env.REDIS_CONNECTION_STRING,
+ // langfuse caching
+ LANGFUSE_CACHE_API_KEY_ENABLED: process.env.LANGFUSE_CACHE_API_KEY_ENABLED,
+ LANGFUSE_CACHE_API_KEY_TTL: process.env.LANGFUSE_CACHE_API_KEY_TTL,
},
// Skip validation in Docker builds
// DOCKER_BUILD is set in Dockerfile
diff --git a/web/src/features/prompts/server/utils/authorizePromptRequest.ts b/web/src/features/prompts/server/utils/authorizePromptRequest.ts
index fda7c1d45f..9cbea2ed6d 100644
--- a/web/src/features/prompts/server/utils/authorizePromptRequest.ts
+++ b/web/src/features/prompts/server/utils/authorizePromptRequest.ts
@@ -1,11 +1,14 @@
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { type NextApiRequest } from "next";
import { UnauthorizedError, ForbiddenError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { redis } from "@langfuse/shared/src/server";
export async function authorizePromptRequestOrThrow(req: NextApiRequest) {
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
if (authCheck.scope.accessLevel !== "all")
throw new ForbiddenError(
diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.ts
index 766db7eeaa..29e88898c1 100644
--- a/web/src/features/public-api/server/apiAuth.ts
+++ b/web/src/features/public-api/server/apiAuth.ts
@@ -1,9 +1,11 @@
import { env } from "@/src/env.mjs";
import { createShaHash, verifySecretKey } from "@langfuse/shared/src/server";
import { type ApiAccessScope } from "@/src/features/public-api/server/types";
-import { prisma } from "@langfuse/shared/src/db";
+import { type PrismaClient, type ApiKey } from "@langfuse/shared/src/db";
import { isPrismaException } from "@/src/utils/exceptions";
import * as Sentry from "@sentry/node";
+import { type Redis } from "ioredis";
+import { z } from "zod";
export type AuthHeaderVerificationResult =
| AuthHeaderValidVerificationResult
@@ -17,123 +19,262 @@ export type AuthHeaderValidVerificationResult = {
scope: ApiAccessScope;
};
-export async function verifyAuthHeaderAndReturnScope(
- authHeader: string | undefined,
-): Promise<AuthHeaderVerificationResult> {
- if (!authHeader) {
- console.error("No authorization header");
- return {
- validKey: false,
- error: "No authorization header",
- };
+export const ApiKeyZod = z.object({
+ id: z.string(),
+ note: z.string().nullable(),
+ publicKey: z.string(),
+ hashedSecretKey: z.string(),
+ fastHashedSecretKey: z.string().nullable(),
+ displaySecretKey: z.string(),
+ createdAt: z.string().datetime().nullable(),
+ lastUsedAt: z.string().datetime().nullable(),
+ expiresAt: z.string().datetime().nullable(),
+ projectId: z.string(),
+});
+
+export class ApiAuthService {
+ prisma: PrismaClient;
+ redis: Redis | null;
+
+ constructor(prisma: PrismaClient, redis: Redis | null) {
+ this.prisma = prisma;
+ this.redis = redis;
+ }
+
+ async deleteApiKey(id: string, projectId: string) {
+ // Make sure the API key exists and belongs to the project the user has access to
+ const apiKey = await this.prisma.apiKey.findFirstOrThrow({
+ where: {
+ id: id,
+ projectId: projectId,
+ },
+ });
+ if (!apiKey) {
+ return false;
+ }
+
+ // if redis is available, delete the key from there as well
+ // delete from redis even if caching is disabled via env for consistency
+ if (this.redis && apiKey.fastHashedSecretKey) {
+ await this.redis.del(this.createRedisKey(apiKey.fastHashedSecretKey));
+ }
+
+ await this.prisma.apiKey.delete({
+ where: {
+ id: apiKey.id,
+ },
+ });
+ return true;
}
- try {
- // Basic auth, full scope, needs secret key and public key
- if (authHeader.startsWith("Basic ")) {
- const { username: publicKey, password: secretKey } =
- extractBasicAuthCredentials(authHeader);
-
- const salt = env.SALT;
- const hashFromProvidedKey = createShaHash(secretKey, salt);
- const apiKey = await prisma.apiKey.findUnique({
- where: { fastHashedSecretKey: hashFromProvidedKey },
- });
- let projectId = apiKey?.projectId;
-
- if (!apiKey || !apiKey.fastHashedSecretKey) {
- const dbKey = await findDbKeyOrThrow(publicKey);
- const isValid = await verifySecretKey(secretKey, dbKey.hashedSecretKey);
-
- if (!isValid) {
- console.log("Old key is invalid", publicKey);
+ async verifyAuthHeaderAndReturnScope(
+ authHeader: string | undefined,
+ ): Promise<AuthHeaderVerificationResult> {
+ if (!authHeader) {
+ console.error("No authorization header");
+ return {
+ validKey: false,
+ error: "No authorization header",
+ };
+ }
+
+ try {
+ // Basic auth, full scope, needs secret key and public key
+ if (authHeader.startsWith("Basic ")) {
+ const { username: publicKey, password: secretKey } =
+ this.extractBasicAuthCredentials(authHeader);
+
+ const salt = env.SALT;
+ const hashFromProvidedKey = createShaHash(secretKey, salt);
+
+ // fetches by redis if available, fallback to postgres
+ const apiKey = await this.fetchApiKeyByHash(hashFromProvidedKey);
+
+ let projectId = apiKey?.projectId;
+
+ if (!apiKey || !apiKey.fastHashedSecretKey) {
+ const dbKey = await this.findDbKeyOrThrow(publicKey);
+ const isValid = await verifySecretKey(
+ secretKey,
+ dbKey.hashedSecretKey,
+ );
+
+ if (!isValid) {
+ console.log("Old key is invalid", publicKey);
+ throw new Error("Invalid credentials");
+ }
+
+ const shaKey = createShaHash(secretKey, salt);
+
+ await this.prisma.apiKey.update({
+ where: { publicKey },
+ data: {
+ fastHashedSecretKey: shaKey,
+ },
+ });
+ projectId = dbKey.projectId;
+ }
+
+ if (!projectId) {
+ console.log("No project id found for key", publicKey);
throw new Error("Invalid credentials");
}
- const shaKey = createShaHash(secretKey, salt);
+ Sentry.setUser({
+ id: projectId,
+ });
- await prisma.apiKey.update({
- where: { publicKey },
- data: {
- fastHashedSecretKey: shaKey,
+ return {
+ validKey: true,
+ scope: {
+ projectId: projectId,
+ accessLevel: "all",
},
- });
- projectId = dbKey.projectId;
+ };
}
+ // Bearer auth, limited scope, only needs public key
+ if (authHeader.startsWith("Bearer ")) {
+ const publicKey = authHeader.replace("Bearer ", "");
+
+ const dbKey = await this.findDbKeyOrThrow(publicKey);
+ Sentry.setUser({
+ id: dbKey.projectId,
+ });
- if (!projectId) {
- console.log("No project id found for key", publicKey);
- throw new Error("Invalid credentials");
+ return {
+ validKey: true,
+ scope: {
+ projectId: dbKey.projectId,
+ accessLevel: "scores",
+ },
+ };
}
+ } catch (error: unknown) {
+ console.error("Error verifying auth header: ", error);
- Sentry.setUser({
- id: projectId,
- });
+ if (isPrismaException(error)) {
+ throw error;
+ }
return {
- validKey: true,
- scope: {
- projectId: projectId,
- accessLevel: "all",
- },
+ validKey: false,
+ error:
+ (error instanceof Error ? error.message : "Authorization error") +
+ ". Confirm that you've configured the correct host.",
};
}
- // Bearer auth, limited scope, only needs public key
- if (authHeader.startsWith("Bearer ")) {
- const publicKey = authHeader.replace("Bearer ", "");
+ return {
+ validKey: false,
+ error: "Invalid authorization header",
+ };
+ }
+
+ extractBasicAuthCredentials(basicAuthHeader: string): {
+ username: string;
+ password: string;
+ } {
+ const authValue = basicAuthHeader.split(" ")[1];
+ if (!authValue) throw new Error("Invalid authorization header");
+
+ const [username, password] = atob(authValue).split(":");
+ if (!username || !password) throw new Error("Invalid authorization header");
+ return { username, password };
+ }
+
+ async findDbKeyOrThrow(publicKey: string) {
+ const dbKey = await this.prisma.apiKey.findUnique({
+ where: { publicKey },
+ });
+ if (!dbKey) {
+ console.log("No api key found for public key:", publicKey);
+ throw new Error("Invalid public key");
+ }
+ return dbKey;
+ }
- const dbKey = await findDbKeyOrThrow(publicKey);
- Sentry.setUser({
- id: dbKey.projectId,
- });
+ async fetchApiKeyByHash(hash: string) {
+ // first get the API key from redis, this does not throw
+ const redisApiKey = await this.fetchApiKeyFromRedis(hash);
- return {
- validKey: true,
- scope: {
- projectId: dbKey.projectId,
- accessLevel: "scores",
- },
- };
+ // if we found something, return the object.
+ if (redisApiKey) {
+ Sentry.metrics.increment("api_key_cache_hit");
+ console.log(
+ `Found key with id ${redisApiKey.id} for project ${redisApiKey.projectId} in redis`,
+ );
+ return redisApiKey;
}
- } catch (error: unknown) {
- console.error("Error verifying auth header: ", error);
- if (isPrismaException(error)) {
- throw error;
+ Sentry.metrics.increment("api_key_cache_miss");
+ // if redis not available or object not found, try the database
+ const apiKey = await this.prisma.apiKey.findUnique({
+ where: { fastHashedSecretKey: hash },
+ });
+
+ // add the key to redis for future use if available, this does not throw
+ // only do so if the new hashkey exists already.
+ if (apiKey && apiKey.fastHashedSecretKey) {
+ console.log(
+ `Add key with id ${apiKey.id} for project ${apiKey.projectId} to redis`,
+ );
+ await this.addApiKeyToRedis(hash, apiKey);
}
+ return apiKey;
+ }
- return {
- validKey: false,
- error:
- (error instanceof Error ? error.message : "Authorization error") +
- ". Confirm that you've configured the correct host.",
- };
+ async addApiKeyToRedis(hash: string, apiKey: ApiKey) {
+ if (!this.redis || !env.LANGFUSE_CACHE_API_KEY_ENABLED) {
+ return;
+ }
+
+ try {
+ await this.redis.set(
+ this.createRedisKey(hash),
+ JSON.stringify(apiKey),
+ "EX",
+ env.LANGFUSE_CACHE_API_KEY_TTL, // redis API is in seconds
+ );
+ } catch (error: unknown) {
+ console.error("Error adding key to redis", error);
+ }
}
- return {
- validKey: false,
- error: "Invalid authorization header",
- };
-}
-function extractBasicAuthCredentials(basicAuthHeader: string): {
- username: string;
- password: string;
-} {
- const authValue = basicAuthHeader.split(" ")[1];
- if (!authValue) throw new Error("Invalid authorization header");
+ async fetchApiKeyFromRedis(hash: string) {
+ if (!this.redis || !env.LANGFUSE_CACHE_API_KEY_ENABLED) {
+ return null;
+ }
- const [username, password] = atob(authValue).split(":");
- if (!username || !password) throw new Error("Invalid authorization header");
- return { username, password };
-}
+ try {
+ const redisApiKey = await this.redis.getex(
+ this.createRedisKey(hash),
+ "EX",
+ env.LANGFUSE_CACHE_API_KEY_TTL, // redis API is in seconds
+ );
+
+ if (!redisApiKey) {
+ return null;
+ }
+
+ const parsedApiKey = ApiKeyZod.safeParse(JSON.parse(redisApiKey));
+
+ if (parsedApiKey.success) {
+ return parsedApiKey.data;
+ }
+
+ if (!parsedApiKey.success) {
+ console.error(
+ "Failed to parse API key from Redis:",
+ parsedApiKey.error,
+ );
+ }
+ return null;
+ } catch (error: unknown) {
+ console.error("Error fetching key from redis", error);
+ return null;
+ }
+ }
-async function findDbKeyOrThrow(publicKey: string) {
- const dbKey = await prisma.apiKey.findUnique({
- where: { publicKey },
- });
- if (!dbKey) {
- console.log("No api key found for public key:", publicKey);
- throw new Error("Invalid public key");
+ createRedisKey(hash: string) {
+ return `api-key:${hash}`;
}
- return dbKey;
}
diff --git a/web/src/features/public-api/server/apiKeyRouter.ts b/web/src/features/public-api/server/apiKeyRouter.ts
index 481f76deb8..711da135a5 100644
--- a/web/src/features/public-api/server/apiKeyRouter.ts
+++ b/web/src/features/public-api/server/apiKeyRouter.ts
@@ -6,6 +6,8 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import * as z from "zod";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
+import { redis } from "@langfuse/shared/src/server";
export const apiKeysRouter = createTRPCRouter({
byProjectId: protectedProjectProcedure
@@ -101,20 +103,9 @@ export const apiKeysRouter = createTRPCRouter({
action: "delete",
});
- // Make sure the API key exists and belongs to the project the user has access to
- const apiKey = await ctx.prisma.apiKey.findFirstOrThrow({
- where: {
- id: input.id,
- projectId: input.projectId,
- },
- });
-
- await ctx.prisma.apiKey.delete({
- where: {
- id: apiKey.id,
- },
- });
-
- return true;
+ return await new ApiAuthService(ctx.prisma, redis).deleteApiKey(
+ input.id,
+ input.projectId,
+ );
}),
});
diff --git a/web/src/features/public-api/server/createAuthedAPIRoute.ts b/web/src/features/public-api/server/createAuthedAPIRoute.ts
index 4fb568e6c1..ae5c744490 100644
--- a/web/src/features/public-api/server/createAuthedAPIRoute.ts
+++ b/web/src/features/public-api/server/createAuthedAPIRoute.ts
@@ -2,9 +2,11 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { type ZodType, type z } from "zod";
import * as Sentry from "@sentry/node";
import {
- verifyAuthHeaderAndReturnScope,
+ ApiAuthService,
type AuthHeaderValidVerificationResult,
} from "@/src/features/public-api/server/apiAuth";
+import { prisma } from "@langfuse/shared/src/db";
+import { redis } from "@langfuse/shared/src/server";
type RouteConfig<
TQuery extends ZodType<any>,
@@ -33,9 +35,10 @@ export const createAuthedAPIRoute = <
routeConfig: RouteConfig<TQuery, TBody, TResponse>,
): ((req: NextApiRequest, res: NextApiResponse) => Promise<void>) => {
return async (req: NextApiRequest, res: NextApiResponse) => {
- const auth = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
+ const auth = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
if (!auth.validKey) {
res.status(401).json({ message: auth.error });
return;
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index 7a40b1d86b..f53dfdb503 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -1,6 +1,6 @@
import {
type AuthHeaderVerificationResult,
- verifyAuthHeaderAndReturnScope,
+ ApiAuthService,
} from "@/src/features/public-api/server/apiAuth";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
@@ -40,6 +40,7 @@ import {
ForbiddenError,
UnauthorizedError,
} from "@langfuse/shared";
+import { redis } from "@langfuse/shared/src/server";
import { isSigtermReceived } from "@/src/utils/shutdown";
@@ -67,9 +68,10 @@ export default async function handler(
if (req.method !== "POST") throw new MethodNotAllowedError();
// CHECK AUTH FOR ALL EVENTS
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
diff --git a/web/src/pages/api/public/projects.ts b/web/src/pages/api/public/projects.ts
index 709359e03a..15340a2be8 100644
--- a/web/src/pages/api/public/projects.ts
+++ b/web/src/pages/api/public/projects.ts
@@ -1,7 +1,8 @@
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
import { isPrismaException } from "@/src/utils/exceptions";
+import { redis } from "@langfuse/shared/src/server";
import { type NextApiRequest, type NextApiResponse } from "next";
@@ -12,9 +13,10 @@ export default async function handler(
await runMiddleware(req, res, cors);
// CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
if (!authCheck.validKey)
return res.status(401).json({
message: authCheck.error,
diff --git a/web/src/pages/api/public/prompts.ts b/web/src/pages/api/public/prompts.ts
index f7a27ca95a..f2dbe5875b 100644
--- a/web/src/pages/api/public/prompts.ts
+++ b/web/src/pages/api/public/prompts.ts
@@ -1,5 +1,5 @@
import { createPrompt } from "@/src/features/prompts/server/actions/createPrompt";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
import { isPrismaException } from "@/src/utils/exceptions";
@@ -18,6 +18,7 @@ import {
} from "@langfuse/shared";
import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";
import * as Sentry from "@sentry/node";
+import { redis } from "@langfuse/shared/src/server";
export default async function handler(
req: NextApiRequest,
@@ -27,9 +28,11 @@ export default async function handler(
try {
// Authentication and authorization
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
+
if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
if (authCheck.scope.accessLevel !== "all")
throw new ForbiddenError(
diff --git a/web/src/pages/api/public/users.ts b/web/src/pages/api/public/users.ts
index 0162986313..1d54de539d 100644
--- a/web/src/pages/api/public/users.ts
+++ b/web/src/pages/api/public/users.ts
@@ -7,9 +7,10 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
-import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { paginationZod } from "@langfuse/shared";
import { isPrismaException } from "@/src/utils/exceptions";
+import { redis } from "@langfuse/shared/src/server";
const GetUsersSchema = z.object({
...paginationZod,
@@ -22,9 +23,10 @@ export default async function handler(
await runMiddleware(req, res, cors);
// CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
if (!authCheck.validKey)
return res.status(401).json({
message: authCheck.error,