🪢 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
feat(api): invalidate all cached api keys (#14359)
Max Deichmann78d44817d884
diff --git a/packages/shared/src/server/auth/apiKeyCache.ts b/packages/shared/src/server/auth/apiKeyCache.tsnew file mode 100644index 0000000000..4f2c89061c--- /dev/null+++ b/packages/shared/src/server/auth/apiKeyCache.ts@@ -0,0 +1,6 @@+export const API_KEY_CACHE_KEY_PREFIX = "api-key:";++export const createApiKeyCacheKey = (hash: string) =>+ `${API_KEY_CACHE_KEY_PREFIX}${hash}`;++export const API_KEY_CACHE_PATTERN = createApiKeyCacheKey("*");diff --git a/packages/shared/src/server/auth/invalidateApiKeys.ts b/packages/shared/src/server/auth/invalidateApiKeys.tsindex 4f6f940792..0f95c0a13e 100644--- a/packages/shared/src/server/auth/invalidateApiKeys.ts+++ b/packages/shared/src/server/auth/invalidateApiKeys.ts@@ -1,9 +1,10 @@import { prisma } from "../../db";-import { redis, safeMultiDel } from "..";+import { redis, safeMultiDel, scanKeys } from "..";import { logger } from "../logger";import type { Cluster, Redis } from "ioredis";import { type ApiKey } from "../../db";+import { API_KEY_CACHE_PATTERN, createApiKeyCacheKey } from "./apiKeyCache";/*** Invalidate cached API keys from Redis cache@@ -37,7 +38,7 @@ export async function invalidateCachedApiKeys(if (redisClient) {logger.info(`Invalidating API keys in redis for ${identifier}`);- const keysToDelete = filteredHashKeys.map((hash) => `api-key:${hash}`);+ const keysToDelete = filteredHashKeys.map(createApiKeyCacheKey);await safeMultiDel(redisClient, keysToDelete);}}@@ -83,7 +84,7 @@ export async function invalidateCachedOrgApiKeys(if (redisClient) {logger.info(`Invalidating API keys in redis for org ${orgId}`);- const keysToDelete = hashKeys.map((hash) => `api-key:${hash}`);+ const keysToDelete = hashKeys.map(createApiKeyCacheKey);await safeMultiDel(redisClient, keysToDelete);}}@@ -119,7 +120,36 @@ export async function invalidateCachedProjectApiKeys(if (redisClient) {logger.info(`Invalidating API keys in redis for project ${projectId}`);- const keysToDelete = hashKeys.map((hash) => `api-key:${hash}`);+ const keysToDelete = hashKeys.map(createApiKeyCacheKey);await safeMultiDel(redisClient, keysToDelete);}}++/**+ * Invalidate every cached API key entry from Redis.+ *+ * This removes only API key cache entries, including cached misses, and does not+ * delete or modify API keys in the database.+ *+ * @returns Number of cache entries invalidated+ */+export async function invalidateAllCachedApiKeys(+ redisClient: Redis | Cluster | null = redis,+): Promise<number> {+ if (!redisClient) {+ logger.info("No redis client available to invalidate cached API keys");+ return 0;+ }++ const keysToDelete = await scanKeys(redisClient, API_KEY_CACHE_PATTERN);++ if (keysToDelete.length === 0) {+ logger.info("No cached API keys to invalidate");+ return 0;+ }++ await safeMultiDel(redisClient, keysToDelete);+ logger.info(`Invalidated ${keysToDelete.length} cached API keys in redis`);++ return keysToDelete.length;+}diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 3431ffd889..227fed1f2a 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -28,6 +28,7 @@ export * from "./evals/codeEvalExecution";export * from "./evals/evalScoreIds";export * from "./evals/extractObservationVariables";export * from "./utils/traceId";+export * from "./auth/apiKeyCache";export * from "./auth/apiKeys";export * from "./auth/invalidateApiKeys";export * from "./auth/customSsoProvider";diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.tsindex c7a8a89209..787079cb8c 100644--- a/packages/shared/src/server/instrumentation/index.ts+++ b/packages/shared/src/server/instrumentation/index.ts@@ -5,6 +5,7 @@ import {import * as opentelemetry from "@opentelemetry/api";import * as dd from "dd-trace";import { env } from "../../env";+import { API_KEY_CACHE_KEY_PREFIX } from "../auth/apiKeyCache";import { logger } from "../logger";// type CallbackFn<T> = () => T;@@ -25,8 +26,8 @@ export function ioredisRequestHook(return;}const args = [...cmdArgs].map(String);- // Redact API key cache values: SET [prefix:]api-key:{hash} <json>- if (args[0]?.includes("api-key:")) {+ // Redact API key cache values.+ if (args[0]?.includes(API_KEY_CACHE_KEY_PREFIX)) {for (let i = 1; i < args.length; i++) {args[i] = "[REDACTED]";}diff --git a/packages/shared/src/server/redis/redis.test.ts b/packages/shared/src/server/redis/redis.test.tsnew file mode 100644index 0000000000..3fd3062a57--- /dev/null+++ b/packages/shared/src/server/redis/redis.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it, vi } from "vitest";+import type { Redis } from "ioredis";++vi.mock("../../env", () => ({+ env: {+ REDIS_CLUSTER_ENABLED: "false",+ REDIS_ENABLE_AUTO_PIPELINING: "false",+ REDIS_SENTINEL_ENABLED: "false",+ },+}));++import { scanKeys } from "./redis";++type ScanCall = [string, "MATCH", string, "COUNT", number];++const createRedisStub = (+ scanResults: Array<[string, string[]]>,+ options: { keyPrefix?: string } = {},+) => {+ let callIndex = 0;+ const scan = vi.fn(+ async (..._args: ScanCall): Promise<[string, string[]]> =>+ scanResults[callIndex++] ?? ["0", []],+ );++ return {+ client: { options, scan } as unknown as Redis,+ scan,+ };+};++describe("scanKeys", () => {+ it("scans every cursor page and returns unique keys", async () => {+ const { client, scan } = createRedisStub([+ ["42", ["cache:first", "cache:second"]],+ ["0", ["cache:second", "cache:third"]],+ ]);++ await expect(scanKeys(client, "cache:*")).resolves.toEqual([+ "cache:first",+ "cache:second",+ "cache:third",+ ]);++ expect(scan).toHaveBeenNthCalledWith(+ 1,+ "0",+ "MATCH",+ "cache:*",+ "COUNT",+ 1000,+ );+ expect(scan).toHaveBeenNthCalledWith(+ 2,+ "42",+ "MATCH",+ "cache:*",+ "COUNT",+ 1000,+ );+ });++ it("scans physical prefixed keys but returns logical keys", async () => {+ const { client, scan } = createRedisStub(+ [["0", ["tenant:api-key:first", "tenant:api-key:second"]]],+ { keyPrefix: "tenant:" },+ );++ await expect(scanKeys(client, "api-key:*")).resolves.toEqual([+ "api-key:first",+ "api-key:second",+ ]);++ expect(scan).toHaveBeenCalledWith(+ "0",+ "MATCH",+ "tenant:api-key:*",+ "COUNT",+ 1000,+ );+ });+});diff --git a/packages/shared/src/server/redis/redis.ts b/packages/shared/src/server/redis/redis.tsindex 0c09412471..8d68e8a6e3 100644--- a/packages/shared/src/server/redis/redis.ts+++ b/packages/shared/src/server/redis/redis.ts@@ -319,23 +319,41 @@ const scanKeysForNode = async (client: Redis,pattern: string,collector: Set<string>,+ keyPrefix: string,) => {let cursor = "0";+ // ioredis keyPrefix is not applied to SCAN patterns, but it is applied to+ // DEL/GET/SET keys. Scan physical keys and return logical keys to callers.+ const scanPattern = keyPrefix ? `${keyPrefix}${pattern}` : pattern;do {const [nextCursor, keys]: [string, string[]] = await client.scan(cursor,"MATCH",- pattern,+ scanPattern,"COUNT",REDIS_SCAN_COUNT,);- keys.forEach((key) => collector.add(key));+ keys.forEach((key) =>+ collector.add(+ keyPrefix && key.startsWith(keyPrefix)+ ? key.slice(keyPrefix.length)+ : key,+ ),+ );cursor = nextCursor;} while (cursor !== "0");};+const getRedisKeyPrefix = (redis: Redis | Cluster): string => {+ const keyPrefix =+ redis.options?.keyPrefix ??+ (redis instanceof Cluster ? redis.options.redisOptions?.keyPrefix : "");++ return keyPrefix?.toString() ?? "";+};+export const scanKeys = async (redis: Redis | Cluster | null,pattern: string,@@ -343,15 +361,18 @@ export const scanKeys = async (if (!redis) return [];const collectedKeys = new Set<string>();+ const keyPrefix = getRedisKeyPrefix(redis);if (env.REDIS_CLUSTER_ENABLED === "true") {await Promise.all((redis as Cluster).nodes("master")- .map((node) => scanKeysForNode(node, pattern, collectedKeys)),+ .map((node) =>+ scanKeysForNode(node, pattern, collectedKeys, keyPrefix),+ ),);} else {- await scanKeysForNode(redis as Redis, pattern, collectedKeys);+ await scanKeysForNode(redis as Redis, pattern, collectedKeys, keyPrefix);}return Array.from(collectedKeys);diff --git a/web/src/__tests__/server/admin-api-keys.servertest.ts b/web/src/__tests__/server/admin-api-keys.servertest.tsnew file mode 100644index 0000000000..4b82df4007--- /dev/null+++ b/web/src/__tests__/server/admin-api-keys.servertest.ts@@ -0,0 +1,90 @@+import type { NextApiRequest, NextApiResponse } from "next";+import { createMocks } from "node-mocks-http";+import { env } from "@/src/env.mjs";+import {+ API_KEY_CACHE_PATTERN,+ createApiKeyCacheKey,+ redis,+} from "@langfuse/shared/src/server";+import handler from "../../pages/api/admin/api-keys";+import {+ clearRedisKeysByPatternSafely,+ ensureRedisReady,+ getRedisValue,+ setRedisValue,+ type RedisTestClient,+} from "@/src/__tests__/server/redis-test-utils";++describe("Admin API keys route", () => {+ const ADMIN_API_KEY = "test-admin-api-key";+ const originalAdminApiKey = env.ADMIN_API_KEY;+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;++ const getRedisClient = (): RedisTestClient => {+ if (!redis) {+ throw new Error("Redis is required for admin API key cache tests.");+ }++ return redis;+ };++ beforeAll(() => {+ (env as any).ADMIN_API_KEY = ADMIN_API_KEY;+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ });++ beforeEach(async () => {+ const redisClient = getRedisClient();+ await ensureRedisReady(redisClient);+ await clearRedisKeysByPatternSafely(redisClient, API_KEY_CACHE_PATTERN);+ await clearRedisKeysByPatternSafely(redisClient, "other-cache:*");+ });++ afterEach(async () => {+ const redisClient = getRedisClient();+ await clearRedisKeysByPatternSafely(redisClient, API_KEY_CACHE_PATTERN);+ await clearRedisKeysByPatternSafely(redisClient, "other-cache:*");+ });++ afterAll(() => {+ (env as any).ADMIN_API_KEY = originalAdminApiKey;+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ });++ it("invalidates all cached API keys without deleting other redis entries", async () => {+ const redisClient = getRedisClient();+ const existingApiKeyCacheKey = createApiKeyCacheKey("existing-key");+ const missingApiKeyCacheKey = createApiKeyCacheKey("missing-key");++ await setRedisValue(redisClient, existingApiKeyCacheKey, "cached-api-key");+ await setRedisValue(+ redisClient,+ missingApiKeyCacheKey,+ '"api-key-non-existent"',+ );+ await setRedisValue(redisClient, "other-cache:existing-key", "untouched");++ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "POST",+ headers: {+ authorization: `Bearer ${ADMIN_API_KEY}`,+ },+ body: {+ action: "invalidate-all",+ },+ });++ await handler(req, res);++ expect(res._getStatusCode()).toBe(200);+ expect(res._getJSONData()).toEqual({+ message: "All cached API keys invalidated",+ invalidatedCount: 2,+ });+ expect(await getRedisValue(redisClient, existingApiKeyCacheKey)).toBeNull();+ expect(await getRedisValue(redisClient, missingApiKeyCacheKey)).toBeNull();+ expect(await getRedisValue(redisClient, "other-cache:existing-key")).toBe(+ "untouched",+ );+ });+});diff --git a/web/src/__tests__/server/unit/api-auth-span.servertest.ts b/web/src/__tests__/server/unit/api-auth-span.servertest.tsindex 0116e36e78..855ff0d73f 100644--- a/web/src/__tests__/server/unit/api-auth-span.servertest.ts+++ b/web/src/__tests__/server/unit/api-auth-span.servertest.ts@@ -61,6 +61,7 @@ vi.mock("@langfuse/shared/src/server", () => ({parse: vi.fn((value) => value),},addUserToSpan: addUserToSpanMock,+ createApiKeyCacheKey: vi.fn((hash: string) => `api-key:${hash}`),createShaHash: createShaHashMock,deleteApiKeyFromDb: vi.fn(),invalidateCachedApiKeys: vi.fn(),diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 1b6c8befe5..c56ae4ff5b 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -13,6 +13,7 @@ import {invalidateCachedApiKeys as invalidateCachedApiKeysShared,invalidateCachedOrgApiKeys as invalidateCachedOrgApiKeysShared,invalidateCachedProjectApiKeys as invalidateCachedProjectApiKeysShared,+ createApiKeyCacheKey,} from "@langfuse/shared/src/server";import {type PrismaClient,@@ -356,7 +357,7 @@ export class ApiAuthService {try {await this.redis.set(- this.createRedisKey(hash),+ createApiKeyCacheKey(hash),JSON.stringify(newApiKey),"EX",env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS, // redis API is in seconds@@ -373,7 +374,7 @@ export class ApiAuthService {try {const redisApiKey = await this.redis.getex(- this.createRedisKey(hash),+ createApiKeyCacheKey(hash),"EX",env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS, // redis API is in seconds);@@ -393,7 +394,7 @@ export class ApiAuthService {"Failed to parse API key from Redis, deleting existing key from cache",parsedApiKey.error,);- await this.redis.del(this.createRedisKey(hash));+ await this.redis.del(createApiKeyCacheKey(hash));}return null;} catch (error: unknown) {@@ -402,10 +403,6 @@ export class ApiAuthService {}}- private createRedisKey(hash: string) {- return `api-key:${hash}`;- }-private extractOrgIdAndCloudConfig(apiKeyAndOrganisation: ApiKey & {project: {diff --git a/web/src/pages/api/admin/api-keys/index.ts b/web/src/pages/api/admin/api-keys/index.tsindex ef66f3a735..71cee91436 100644--- a/web/src/pages/api/admin/api-keys/index.ts+++ b/web/src/pages/api/admin/api-keys/index.ts@@ -1,7 +1,11 @@import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import {+ invalidateAllCachedApiKeys,+ logger,+ redis,+} from "@langfuse/shared/src/server";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";@@ -20,9 +24,14 @@ const InvalidateApiKeySchema = z.object({projectIds: z.array(z.string()),});+const InvalidateAllApiKeysSchema = z.object({+ action: z.literal("invalidate-all"),+});+const ApiKeyAction = z.discriminatedUnion("action", [DeleteApiKeySchema,InvalidateApiKeySchema,+ InvalidateAllApiKeysSchema,]);export default async function handler(@@ -107,6 +116,14 @@ export default async function handler(`Invalidated API keys for projects ${body.data.projectIds.join(", ")}`,);return res.status(200).json({ message: "API keys invalidated" });+ } else if (body.data.action === "invalidate-all") {+ const invalidatedCount = await invalidateAllCachedApiKeys(redis);++ logger.info(`Invalidated all cached API keys (${invalidatedCount})`);+ return res.status(200).json({+ message: "All cached API keys invalidated",+ invalidatedCount,+ });}// return not implemented error