Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(auth): enforce api key quotas and rate limits

Tin2ccc97447bb6
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 8c0eaa963..581850554 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -395,7 +395,10 @@ export function createApp() {
api.use("/auth/*", async (c, next) => {
const apiKeyHeader = c.req.header("x-api-key")?.trim();
- if (apiKeyHeader && !(await verifyApiKey(apiKeyHeader))) {
+ if (
+ apiKeyHeader &&
+ !(await verifyApiKey(apiKeyHeader, { consume: false }))
+ ) {
throw new HTTPException(401, { message: "Unauthorized" });
}
return next();
@@ -682,7 +685,7 @@ export function createApp() {
return auth.handler(new Request(c.req.raw, { headers }));
}
- if (!(await verifyApiKey(bearerToken))) {
+ if (!(await verifyApiKey(bearerToken, { consume: false }))) {
throw new HTTPException(401, { message: "Unauthorized" });
}
diff --git a/apps/api/src/utils/verify-api-key.ts b/apps/api/src/utils/verify-api-key.ts
index 09035be75..17fa3220f 100644
--- a/apps/api/src/utils/verify-api-key.ts
+++ b/apps/api/src/utils/verify-api-key.ts
@@ -37,66 +37,124 @@ function parsePermissions(raw: string | null): Record<string, string[]> | null {
return 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;
+ }
+
+ 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--;
+ 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 --git a/tests/api-integration/api-key-accounting.test.ts b/tests/api-integration/api-key-accounting.test.ts
new file mode 100644
index 000000000..6fc29297f
--- /dev/null
+++ b/tests/api-integration/api-key-accounting.test.ts
@@ -0,0 +1,86 @@
+import { createHash } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vite-plus/test";
+import db, { 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);
+});