⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(auth): reject keys that expire while awaiting quota locks
Tine10a7a01848d
diff --cc apps/api/src/utils/verify-api-key.tsindex 2e55d2dc8,09035be75..13b86ee9c--- a/apps/api/src/utils/verify-api-key.ts+++ b/apps/api/src/utils/verify-api-key.ts@@@ -37,124 -37,66 +37,126 @@@ function parsePermissions(raw: stringreturn permissions;}-export async function verifyApiKey(key: string) {+export async function verifyApiKey(+ key: string,+ options: { consume?: boolean } = {},+) {const hashedKey = await hashApiKey(key);- const [apiKey] = await db- .select()- .from(schema.apikeyTable)- .where(- and(- eq(schema.apikeyTable.key, hashedKey),- eq(schema.apikeyTable.enabled, true),- // Fail closed even before legacy databases finish the repair migration.- exists(- db- .select({ id: schema.userTable.id })- .from(schema.userTable)- .where(- and(- eq(- schema.userTable.id,- sql`coalesce(${schema.apikeyTable.referenceId}, ${schema.apikeyTable.userId})`,+ return db.transaction(async (tx) => {+ const [apiKey] = await tx+ .select()+ .from(schema.apikeyTable)+ .where(+ and(+ eq(schema.apikeyTable.key, hashedKey),+ eq(schema.apikeyTable.enabled, true),+ // Fail closed even before legacy databases finish the repair migration.+ exists(+ db+ .select({ id: schema.userTable.id })+ .from(schema.userTable)+ .where(+ and(+ eq(+ schema.userTable.id,+ sql`coalesce(${schema.apikeyTable.referenceId}, ${schema.apikeyTable.userId})`,+ ),+ notBannedCondition(),),- notBannedCondition(),),- ),+ ),+ or(+ isNull(schema.apikeyTable.expiresAt),+ gt(schema.apikeyTable.expiresAt, new Date()),+ ),),- or(- isNull(schema.apikeyTable.expiresAt),- gt(schema.apikeyTable.expiresAt, new Date()),- ),- ),- )- .limit(1);+ )+ .limit(1)+ .for("update");- if (!apiKey) {- return null;- }+ if (!apiKey) {+ return null;+ }++ // A key may expire while SELECT waits for another request's row lock.++ const now = new Date();++ if (apiKey.expiresAt && apiKey.expiresAt <= now) return null;++ if (options.consume === false)+ return {+ valid: true,+ key: {+ ...apiKey,+ userId: apiKey.referenceId ?? apiKey.userId ?? "",+ enabled: apiKey.enabled ?? false,+ permissions: parsePermissions(apiKey.permissions),+ metadata: null,+ },+ };++ // Locking the key serializes quota/refill and window accounting across API+ // instances. Neither a stale lookup nor a rejected request can restore quota.- const now = new Date();+ let remaining = apiKey.remaining;+ let lastRefillAt = apiKey.lastRefillAt;+ if (remaining !== null) {+ if (+ apiKey.refillInterval &&+ apiKey.refillAmount &&+ now.getTime() - (lastRefillAt ?? apiKey.createdAt).getTime() >=+ apiKey.refillInterval+ ) {+ remaining = apiKey.refillAmount;+ lastRefillAt = now;+ }+ if (remaining <= 0) return null;+ }+ let requestCount = apiKey.requestCount ?? 0;+ if (apiKey.rateLimitEnabled) {+ const window = apiKey.rateLimitTimeWindow ?? 60_000;+ if (+ !apiKey.lastRequest ||+ now.getTime() - apiKey.lastRequest.getTime() >= window+ )+ requestCount = 0;+ if (requestCount >= (apiKey.rateLimitMax ?? 100)) return null;+ }+ if (remaining !== null) remaining--;+ if (apiKey.rateLimitEnabled) requestCount++;+ await tx+ .update(schema.apikeyTable)+ .set({+ remaining,+ lastRefillAt,+ requestCount,+ lastRequest: now,+ updatedAt: now,+ })+ .where(eq(schema.apikeyTable.id, apiKey.id));- return {- valid: true,- key: {- id: apiKey.id,- userId: apiKey.referenceId ?? apiKey.userId ?? "",- name: apiKey.name,- prefix: apiKey.prefix,- start: apiKey.start,- enabled: apiKey.enabled ?? false,- expiresAt: apiKey.expiresAt,- permissions: parsePermissions(apiKey.permissions),- refillInterval: apiKey.refillInterval,- refillAmount: apiKey.refillAmount,- lastRefillAt: apiKey.lastRefillAt,- rateLimitEnabled: apiKey.rateLimitEnabled,- rateLimitTimeWindow: apiKey.rateLimitTimeWindow,- rateLimitMax: apiKey.rateLimitMax,- requestCount: apiKey.requestCount,- remaining: apiKey.remaining,- lastRequest: apiKey.lastRequest,- metadata: apiKey.metadata- ? (JSON.parse(apiKey.metadata) as Record<string, unknown>)- : null,- },- };+ return {+ valid: true,+ key: {+ id: apiKey.id,+ userId: apiKey.referenceId ?? apiKey.userId ?? "",+ name: apiKey.name,+ prefix: apiKey.prefix,+ start: apiKey.start,+ enabled: apiKey.enabled ?? false,+ expiresAt: apiKey.expiresAt,+ permissions: parsePermissions(apiKey.permissions),+ refillInterval: apiKey.refillInterval,+ refillAmount: apiKey.refillAmount,+ lastRefillAt,+ rateLimitEnabled: apiKey.rateLimitEnabled,+ rateLimitTimeWindow: apiKey.rateLimitTimeWindow,+ rateLimitMax: apiKey.rateLimitMax,+ requestCount,+ remaining,+ lastRequest: now,+ metadata: apiKey.metadata+ ? (JSON.parse(apiKey.metadata) as Record<string, unknown>)+ : null,+ },+ };+ });}diff --cc tests/api-integration/api-key-accounting.test.tsindex 38cc95b57,000000000..fb5fb4003mode 100644,000000..100644--- a/tests/api-integration/api-key-accounting.test.ts+++ b/tests/api-integration/api-key-accounting.test.ts@@@ -1,102 -1,0 +1,154 @@@+import { createHash } from "node:crypto";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it } from "vite-plus/test";+import { auth } from "../../apps/api/src/auth";- import db, { schema } from "../../apps/api/src/database";++import db, { getDatabasePool, schema } from "../../apps/api/src/database";+import { verifyApiKey } from "../../apps/api/src/utils/verify-api-key";+import { resetTestDatabase } from "./helpers/database";+import { createWorkspaceMember } from "./helpers/fixtures";++beforeEach(resetTestDatabase);+async function seedKey(+ overrides: Partial<typeof schema.apikeyTable.$inferInsert> = {},+) {+ const { user } = await createWorkspaceMember();+ const key = `review-test-${user.id}`.padEnd(64, "x");+ const [row] = await db+ .insert(schema.apikeyTable)+ .values({+ referenceId: user.id,+ userId: user.id,+ key: createHash("sha256").update(key).digest("base64url"),+ createdAt: new Date(),+ updatedAt: new Date(),+ rateLimitEnabled: true,+ rateLimitMax: 2,+ rateLimitTimeWindow: 60000,+ ...overrides,+ })+ .returning();+ return { key, row };+}++describe("API key accounting", () => {+ it("denies an exhausted quota", async () => {+ const { key } = await seedKey({ remaining: 0 });+ expect(await verifyApiKey(key)).toBeNull();+ });+ it("enforces a rate window across concurrent requests", async () => {+ const { key, row } = await seedKey();+ const results = await Promise.all(+ Array.from({ length: 6 }, () => verifyApiKey(key)),+ );+ expect(results.filter(Boolean)).toHaveLength(2);+ const [saved] = await db+ .select()+ .from(schema.apikeyTable)+ .where(eq(schema.apikeyTable.id, row.id));+ expect(saved.requestCount).toBe(2);+ });+ it("atomically consumes the last remaining request", async () => {+ const { key } = await seedKey({ remaining: 1, rateLimitEnabled: false });+ const results = await Promise.all(+ Array.from({ length: 5 }, () => verifyApiKey(key)),+ );+ expect(results.filter(Boolean)).toHaveLength(1);+ });+ it("refills eligible quota and resets an expired window", async () => {+ const old = new Date(Date.now() - 120000);+ const { key } = await seedKey({+ remaining: 0,+ refillAmount: 3,+ refillInterval: 60000,+ lastRefillAt: old,+ lastRequest: old,+ requestCount: 2,+ });+ expect(await verifyApiKey(key)).toMatchObject({ valid: true });+ });+});++it("charges an auth request once when the identity guard precedes Better Auth", async () => {+ const { key, row } = await seedKey({ remaining: 1, rateLimitEnabled: false });+ const { createApp } = await import("../../apps/api/src/index");+ const { app } = createApp();+ const response = await app.request("/api/auth/get-session", {+ headers: { "x-api-key": key },+ });+ expect(response.status, await response.clone().text()).toBe(200);+ expect(await response.json()).toMatchObject({+ user: { id: row.referenceId },+ });+ const [saved] = await db+ .select()+ .from(schema.apikeyTable)+ .where(eq(schema.apikeyTable.id, row.id));+ expect(saved.remaining).toBe(0);+});++it("creates normal API keys with the configured 100-per-minute limit", async () => {+ const { user } = await createWorkspaceMember();+ const created = await auth.api.createApiKey({+ body: { userId: user.id, name: "default limits" },+ });+ const [saved] = await db+ .select()+ .from(schema.apikeyTable)+ .where(eq(schema.apikeyTable.id, created.id));+ expect(saved.rateLimitMax).toBe(100);+ expect(saved.rateLimitTimeWindow).toBe(60_000);+ for (let i = 0; i < 11; i++)+ expect(await verifyApiKey(created.key)).not.toBeNull();+});++++it.each([true, false])(++ "rejects a key that expires while waiting for its row lock (consume=%s)",++ async (consume) => {++ const expiresAt = new Date(Date.now() + 1200);++ const { key, row } = await seedKey({ expiresAt, remaining: 1 });++ let release!: () => void;++ let ready!: () => void;++ const locked = new Promise<void>((resolve) => {++ ready = resolve;++ });++ const hold = new Promise<void>((resolve) => {++ release = resolve;++ });++ const holder = db.transaction(async (tx) => {++ await tx++ .select()++ .from(schema.apikeyTable)++ .where(eq(schema.apikeyTable.id, row.id))++ .for("update");++ ready();++ await hold;++ });++ await locked;++ try {++ const verification = verifyApiKey(key, { consume });++ let waiting = false;++ for (let attempt = 0; attempt < 100 && !waiting; attempt++) {++ const result = await getDatabasePool().query<{ waiting: boolean }>(++ `SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE '%"apikey"%') AS waiting`,++ );++ waiting = result.rows[0].waiting;++ if (!waiting) await new Promise((resolve) => setTimeout(resolve, 10));++ }++ expect(waiting).toBe(true);++ await new Promise((resolve) =>++ setTimeout(resolve, Math.max(0, expiresAt.getTime() - Date.now() + 50)),++ );++ release();++ await expect(verification).resolves.toBeNull();++ const [saved] = await db++ .select()++ .from(schema.apikeyTable)++ .where(eq(schema.apikeyTable.id, row.id));++ expect(saved.remaining).toBe(1);++ expect(saved.requestCount).toBe(0);++ } finally {++ release();++ await holder;++ }++ },++);