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(