From d4aa32ae1ded07ad787cf36ed05641daaa809c07 Mon Sep 17 00:00:00 2001 From: Gautam Manchandani Date: Mon, 13 Apr 2026 17:48:00 +0530 Subject: [PATCH] fix(api-key): preserve deferred verify cleanup --- packages/api-key/src/api-key.test.ts | 35 +++++++++++++++++++ packages/api-key/src/routes/verify-api-key.ts | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/packages/api-key/src/api-key.test.ts b/packages/api-key/src/api-key.test.ts index 6feff42f5d..8fc9c1960e 100644 --- a/packages/api-key/src/api-key.test.ts +++ b/packages/api-key/src/api-key.test.ts @@ -4618,6 +4618,41 @@ describe("api-key", async () => { expect(deleteManySpy).not.toHaveBeenCalled(); }); + it("should not run verify cleanup inline when deferUpdates is disabled", async () => { + setCleanupCheckTime(); + + const { auth, signInWithTestUser } = await getTestInstance({ + plugins: [ + apiKey({ + keyExpiration: { + autoCleanup: true, + }, + }), + ], + }); + + const { user } = await signInWithTestUser(); + const ctx = await auth.$context; + const deleteManySpy = vi.spyOn(ctx.adapter, "deleteMany"); + + const createdKey = await auth.api.createApiKey({ + body: { + userId: user.id, + }, + }); + + deleteManySpy.mockClear(); + + const result = await auth.api.verifyApiKey({ + body: { + key: createdKey.key, + }, + }); + + expect(result.valid).toBe(true); + expect(deleteManySpy).not.toHaveBeenCalled(); + }); + it("should still delete expired API keys through the explicit cleanup endpoint when autoCleanup is false", async () => { setCleanupCheckTime(); diff --git a/packages/api-key/src/routes/verify-api-key.ts b/packages/api-key/src/routes/verify-api-key.ts index 402aec307f..a86480154d 100644 --- a/packages/api-key/src/routes/verify-api-key.ts +++ b/packages/api-key/src/routes/verify-api-key.ts @@ -298,7 +298,7 @@ export function verifyApiKey({ ? resolveConfiguration(ctx.context, configurations, apiKey.configId) : lookupOpts; - if (opts.keyExpiration.autoCleanup) { + if (opts.keyExpiration.autoCleanup && opts.deferUpdates) { const cleanupTask = deleteAllExpiredApiKeys(ctx.context).catch( (err) => { ctx.context.logger.error(