Skip to content

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

fix(auth): evict the API key cache after deleting the row (#17651)

Steffen Reuther24c949d8dd56
diff --git a/.env.prod.example b/.env.prod.example
index 6a2ebd2588..a1874ee1a8 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -245,6 +245,9 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# REDIS_SENTINEL_PASSWORD=
# Cache configuration
+# API key lookups are cached in Redis. Cache entries are not refreshed on read,
+# so the TTL (default 60s) bounds how long a deleted API key can still
+# authenticate if its explicit cache eviction is missed.
# LANGFUSE_CACHE_API_KEY_ENABLED=
# LANGFUSE_CACHE_API_KEY_TTL_SECONDS=
diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.ts
index 1429a3a0b8..7fe0bcf568 100644
--- a/packages/shared/src/server/auth/apiKeys.ts
+++ b/packages/shared/src/server/auth/apiKeys.ts
@@ -157,14 +157,18 @@ export async function deleteApiKeyFromDb(p: {
return false;
}
- await invalidateCachedApiKeys([apiKey], `key ${p.id}`, p.redis);
-
+ // The row goes first, then the cache. In the other order, a request
+ // authenticating with this key in between misses the cache, still finds the
+ // row, and writes the key back into the cache after the eviction. `apiKey` is
+ // already loaded above, so eviction does not need the row to still exist.
await p.prisma.apiKey.delete({
where: {
id: apiKey.id,
},
});
+ await invalidateCachedApiKeys([apiKey], `key ${p.id}`, p.redis);
+
return true;
}
diff --git a/web/src/__tests__/server/api-auth.servertest.ts b/web/src/__tests__/server/api-auth.servertest.ts
index 4c2366d3c3..0bbe828aac 100644
--- a/web/src/__tests__/server/api-auth.servertest.ts
+++ b/web/src/__tests__/server/api-auth.servertest.ts
@@ -807,7 +807,7 @@ describe("Authenticate API calls", () => {
});
});
- it("ttl should be increased when reading from redis", async () => {
+ it("ttl should not be extended when reading from redis", async () => {
// Mock prisma
const mockPrisma = {
apiKey: {
@@ -847,14 +847,21 @@ describe("Authenticate API calls", () => {
expect(shortenedTtl).toBeGreaterThan(0);
expect(shortenedTtl).toBeLessThan(env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS);
- await new ApiAuthService(
+ // A cache hit must not push the expiry out. The entry has to age out a
+ // fixed TTL after it was written, so that revoking a key which is still
+ // in use takes effect within one TTL even if the eviction is missed.
+ const cachedAuth = await new ApiAuthService(
mockPrisma as unknown as PrismaClient,
redis,
).verifyAuthHeaderAndReturnScope(getValidAuthHeader());
+ expect(cachedAuth.validKey).toBe(true);
+ expect(mockPrisma.apiKey.findUnique).not.toHaveBeenCalled();
+
const ttl2 = await getRedisTtl(redis, redisKey);
- expect(ttl2).toBeGreaterThan(env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS - 2);
+ expect(ttl2).toBeGreaterThan(0);
+ expect(ttl2).toBeLessThanOrEqual(10);
});
it("should delete API keys from cache and db", async () => {
@@ -913,6 +920,59 @@ describe("Authenticate API calls", () => {
);
expect(deletedCachedKey).toBeNull();
});
+
+ it("should revoke a key even if a request re-caches it mid-deletion", async () => {
+ // generates the fast hashed secret key the cache is keyed by
+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(
+ getValidAuthHeader(),
+ );
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { publicKey: testApiKey.publicKey },
+ });
+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();
+
+ const redisKey = `api-key:${apiKey?.fastHashedSecretKey}`;
+ await redis.del(redisKey);
+
+ // Drives a request into the gap between the two steps of the deletion.
+ // It misses the cache, still finds the row, and writes the key back with
+ // a full TTL - so the eviction has to be the step that happens last.
+ const racingPrisma = {
+ apiKey: {
+ findFirstOrThrow: () =>
+ prisma.apiKey.findFirstOrThrow({ where: { id: apiKey!.id } }),
+ delete: async () => {
+ await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());
+
+ expect(await getRedisValue(redis, redisKey)).not.toBeNull();
+
+ return prisma.apiKey.delete({ where: { id: apiKey!.id } });
+ },
+ },
+ } as unknown as PrismaClient;
+
+ await new ApiAuthService(racingPrisma, redis).deleteApiKey(
+ apiKey!.id,
+ apiKey!.projectId!,
+ "PROJECT",
+ );
+
+ expect(
+ await prisma.apiKey.findUnique({ where: { id: apiKey!.id } }),
+ ).toBeNull();
+ expect(await getRedisValue(redis, redisKey)).toBeNull();
+
+ const afterRevocation = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(getValidAuthHeader());
+
+ expect(afterRevocation.validKey).toBe(false);
+ });
});
describe("invalidates api keys in redis", () => {
diff --git a/web/src/env.mjs b/web/src/env.mjs
index eb297bcbbe..3a6abc97c8 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -383,7 +383,10 @@ export const env = createEnv({
// langfuse caching
LANGFUSE_CACHE_API_KEY_ENABLED: z.enum(["true", "false"]).default("true"),
- LANGFUSE_CACHE_API_KEY_TTL_SECONDS: z.coerce.number().default(300),
+ // Bounds how long a revoked API key can still authenticate. Entries are
+ // not refreshed on read, so a key stops working at most one TTL after its
+ // last cache write. Shared with the policy-core authz context cache.
+ LANGFUSE_CACHE_API_KEY_TTL_SECONDS: z.coerce.number().default(60),
// The gateway data plane calls /resolve on every LLM request, so the
// lookup is cached. The TTL bounds how long a revoked key or a disabled
diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.ts
index cb27695719..f8ed67acc6 100644
--- a/web/src/features/public-api/server/apiAuth.ts
+++ b/web/src/features/public-api/server/apiAuth.ts
@@ -396,11 +396,12 @@ export class ApiAuthService {
}
try {
- const redisApiKey = await this.redis.getex(
- createApiKeyCacheKey(hash),
- "EX",
- env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS, // redis API is in seconds
- );
+ // A plain GET, not GETEX: an entry expires a fixed TTL after it was
+ // written, never a TTL after it was last read. A sliding TTL lets an entry
+ // that is still being read outlive the API key it caches, so a request
+ // that repopulates the cache while the key is being revoked could keep the
+ // revoked key valid for as long as its holder kept using it.
+ const redisApiKey = await this.redis.get(createApiKeyCacheKey(hash));
if (!redisApiKey) {
return null;