🪢 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: store non existence of api key in redis (#2763)
Max Deichmann8c1af8a046cd
diff --git a/web/src/__tests__/api-auth.servertest.ts b/web/src/__tests__/api-auth.servertest.tsindex 0b7cde7229..2c5d8373bb 100644--- a/web/src/__tests__/api-auth.servertest.ts+++ b/web/src/__tests__/api-auth.servertest.ts@@ -185,6 +185,55 @@ describe("Authenticate API calls", () => {});});+ it("searching for non-existing key stores flag in redis and fails auth", async () => {+ // key does not exist in database++ const verification = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ );++ expect(verification.validKey).toBe(false);++ const redisKeys = await redis.keys(`api-key:*`);+ expect(redisKeys.length).toBe(1);+ const redisValue = await redis.get(redisKeys[0]);+ expect(redisValue).toBe('"api-key-non-existent"');+ });++ it("searching for non-existing key again fails auth", async () => {+ // key does not exist in database++ const verification = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ );++ expect(verification.validKey).toBe(false);++ const redisKeys = await redis.keys(`api-key:*`);+ expect(redisKeys.length).toBe(1);+ const redisValue = await redis.get(redisKeys[0]);+ expect(redisValue).toBe('"api-key-non-existent"');++ const verification2 = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ );+ expect(verification2.validKey).toBe(false);++ const redisKeys2 = await redis.keys(`api-key:*`);+ expect(redisKeys2.length).toBe(1);+ const redisValue2 = await redis.get(redisKeys[0]);+ expect(redisValue2).toBe('"api-key-non-existent"');+ });+it("prisma should not be used when reading cached keys", async () => {await createAPIKey();diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex c05f3f0f1e..0a9b0d3dd2 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -32,6 +32,13 @@ export const ApiKeyZod = z.object({projectId: z.string(),});+const API_KEY_NON_EXISTENT = "api-key-non-existent";++export const CachedApiKey = z.union([+ ApiKeyZod,+ z.literal(API_KEY_NON_EXISTENT),+]);+export class ApiAuthService {prisma: PrismaClient;redis: Redis | null;@@ -88,12 +95,29 @@ export class ApiAuthService {const hashFromProvidedKey = createShaHash(secretKey, salt);// fetches by redis if available, fallback to postgres- const apiKey = await this.fetchApiKeyByHash(hashFromProvidedKey);+ const apiKey = await this.fetchApiKeyAndAddToRedis(hashFromProvidedKey);let projectId = apiKey?.projectId;if (!apiKey || !apiKey.fastHashedSecretKey) {- const dbKey = await this.findDbKeyOrThrow(publicKey);+ const dbKey = await this.prisma.apiKey.findUnique({+ where: { publicKey },+ });++ if (!dbKey) {+ console.error("No key found for public key", publicKey);+ if (this.redis) {+ console.log(+ `No key found, storing ${API_KEY_NON_EXISTENT} in redis`,+ );+ await this.addApiKeyToRedis(+ hashFromProvidedKey,+ API_KEY_NON_EXISTENT,+ );+ }+ throw new Error("Invalid credentials");+ }+const isValid = await verifySecretKey(secretKey,dbKey.hashedSecretKey,@@ -192,10 +216,16 @@ export class ApiAuthService {return dbKey;}- async fetchApiKeyByHash(hash: string) {+ async fetchApiKeyAndAddToRedis(hash: string) {// first get the API key from redis, this does not throwconst redisApiKey = await this.fetchApiKeyFromRedis(hash);+ if (redisApiKey === API_KEY_NON_EXISTENT) {+ Sentry.metrics.increment("api_key_cache_hit");+ console.log(`Found flag for non existing key in redis.`);+ throw new Error("Invalid credentials");+ }+// if we found something, return the object.if (redisApiKey) {Sentry.metrics.increment("api_key_cache_hit");@@ -206,6 +236,7 @@ export class ApiAuthService {}Sentry.metrics.increment("api_key_cache_miss");+// if redis not available or object not found, try the databaseconst apiKey = await this.prisma.apiKey.findUnique({where: { fastHashedSecretKey: hash },@@ -222,7 +253,10 @@ export class ApiAuthService {return apiKey;}- async addApiKeyToRedis(hash: string, apiKey: ApiKey) {+ async addApiKeyToRedis(+ hash: string,+ apiKey: ApiKey | typeof API_KEY_NON_EXISTENT,+ ) {if (!this.redis || env.LANGFUSE_CACHE_API_KEY_ENABLED !== "true") {return;}@@ -255,7 +289,7 @@ export class ApiAuthService {return null;}- const parsedApiKey = ApiKeyZod.safeParse(JSON.parse(redisApiKey));+ const parsedApiKey = CachedApiKey.safeParse(JSON.parse(redisApiKey));if (parsedApiKey.success) {return parsedApiKey.data;