⚡ 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(api): keep API key headers out of Better Auth's own 429s and shared caches
Andrej9b879b66ba42
diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 4c8160c77..fd8ca679e 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -445,7 +445,7 @@ export function createApp() {await next();c.set("apiKeyHeaders",- apiKeyResponseHeaders(+ await apiKeyResponseHeaders(await readApiKeyCheck(apiKeyHeader),c.res,new Date(),@@ -749,7 +749,7 @@ export function createApp() {const response = await auth.handler(new Request(c.req.raw, { headers }));c.set("apiKeyHeaders",- apiKeyResponseHeaders(+ await apiKeyResponseHeaders(await readApiKeyCheck(bearerToken),response,new Date(),diff --git a/apps/api/src/utils/api-key-rejection.ts b/apps/api/src/utils/api-key-rejection.tsindex 56c8412e0..7a05ce530 100644--- a/apps/api/src/utils/api-key-rejection.ts+++ b/apps/api/src/utils/api-key-rejection.ts@@ -3,7 +3,7 @@ import {type ApiKeyCheck,type ApiKeyDenial,apiKeyDenialHeaders,- retryAfterSeconds,+ retryAfterFromBody,} from "./rate-limit-headers";function tooManyRequests(message: string, headers: Record<string, string>) {@@ -29,25 +29,15 @@ export function betterAuthLimitRejection(now = new Date(),) {if (check && check.status !== "valid") return apiKeyRejection(check, now);- const { code, details } = (body ?? {}) as {- code?: unknown;- details?: { tryAgainIn?: unknown };- };+ const { code } = (body ?? {}) as { code?: unknown };if (code === "USAGE_EXCEEDED")return apiKeyRejection({ status: "usage_exceeded", retryAt: null, rateLimit: null },now,);- const tryAgainIn = details?.tryAgainIn;+ const retryAfter = retryAfterFromBody(body, now);return tooManyRequests("Rate limit exceeded",- typeof tryAgainIn === "number"- ? {- "Retry-After": retryAfterSeconds(- new Date(now.getTime() + tryAgainIn),- now,- ),- }- : {},+ retryAfter ? { "Retry-After": retryAfter } : {},);}diff --git a/apps/api/src/utils/apply-api-key-headers.test.ts b/apps/api/src/utils/apply-api-key-headers.test.tsindex e9e4c4d90..a0e2aeac6 100644--- a/apps/api/src/utils/apply-api-key-headers.test.ts+++ b/apps/api/src/utils/apply-api-key-headers.test.ts@@ -2,7 +2,10 @@ import { Hono } from "hono";import { describe, expect, it } from "vite-plus/test";import { applyApiKeyHeaders } from "./apply-api-key-headers";-function appWith(cacheControl: string, apiKeyHeaders?: Record<string, string>) {+function appWith(+ cacheControl: string | null,+ apiKeyHeaders?: Record<string, string>,+) {const app = new Hono<{Variables: { apiKeyHeaders?: Record<string, string> };}>();@@ -10,7 +13,7 @@ function appWith(cacheControl: string, apiKeyHeaders?: Record<string, string>) {app.get("/", (c) => {if (apiKeyHeaders) c.set("apiKeyHeaders", apiKeyHeaders);return new Response("asset", {- headers: { "Cache-Control": cacheControl },+ headers: cacheControl ? { "Cache-Control": cacheControl } : {},});});return app;@@ -30,23 +33,37 @@ describe("applyApiKeyHeaders", () => {expect(response.headers.get("cache-control")).toBe("no-store");});- it("keeps per-key headers out of shared caches", async () => {- const response = await appWith("public, max-age=300", limitHeaders).request(- "/",- );+ it.each([+ [null, "private"],+ ["public, max-age=300", "private, max-age=300"],+ ["max-age=60", "private, max-age=60"],+ ["private, max-age=60", "private, max-age=60"],+ ["no-store", "no-store"],+ ])(+ "keeps per-key headers out of shared caches when Cache-Control is %s",+ async (cacheControl, expected) => {+ const response = await appWith(cacheControl, limitHeaders).request("/");- expect(response.headers.get("x-ratelimit-limit")).toBe("100");- expect(response.headers.get("cache-control")).toBe("private, max-age=300");+ expect(response.headers.get("x-ratelimit-limit")).toBe("100");+ expect(response.headers.get("cache-control")).toBe(expected);+ },+ );++ it("marks a Retry-After-only response private", async () => {+ const response = await appWith(null, { "Retry-After": "42" }).request("/");++ expect(response.headers.get("retry-after")).toBe("42");+ expect(response.headers.get("cache-control")).toBe("private");});it("leaves responses without key headers untouched", async () => {- for (const headers of [undefined, {}]) {- const response = await appWith("public, max-age=300", headers).request(- "/",- );+ for (const cacheControl of ["public, max-age=300", null]) {+ for (const headers of [undefined, {}]) {+ const response = await appWith(cacheControl, headers).request("/");- expect(response.headers.get("cache-control")).toBe("public, max-age=300");- expect(response.headers.get("x-ratelimit-limit")).toBeNull();+ expect(response.headers.get("cache-control")).toBe(cacheControl);+ expect(response.headers.get("x-ratelimit-limit")).toBeNull();+ }}});});diff --git a/apps/api/src/utils/apply-api-key-headers.ts b/apps/api/src/utils/apply-api-key-headers.tsindex 72bae8e8e..c8718187c 100644--- a/apps/api/src/utils/apply-api-key-headers.ts+++ b/apps/api/src/utils/apply-api-key-headers.ts@@ -1,5 +1,13 @@import { createMiddleware } from "hono/factory";+function privateCacheControl(cacheControl: string | null) {+ if (!cacheControl) return "private";+ if (/\b(private|no-store)\b/i.test(cacheControl)) return cacheControl;+ if (/\bpublic\b/i.test(cacheControl))+ return cacheControl.replace(/\bpublic\b/gi, "private");+ return `private, ${cacheControl}`;+}+export const applyApiKeyHeaders = createMiddleware<{Variables: { apiKeyHeaders?: Record<string, string> };}>(async (c, next) => {@@ -7,7 +15,8 @@ export const applyApiKeyHeaders = createMiddleware<{const headers = Object.entries(c.get("apiKeyHeaders") ?? {});if (headers.length === 0) return;for (const [name, value] of headers) c.header(name, value);- const cacheControl = c.res.headers.get("Cache-Control");- if (cacheControl && /\bpublic\b/i.test(cacheControl))- c.header("Cache-Control", cacheControl.replace(/\bpublic\b/gi, "private"));+ c.header(+ "Cache-Control",+ privateCacheControl(c.res.headers.get("Cache-Control")),+ );});diff --git a/apps/api/src/utils/rate-limit-headers.test.ts b/apps/api/src/utils/rate-limit-headers.test.tsindex 093820434..3ec0ab556 100644--- a/apps/api/src/utils/rate-limit-headers.test.ts+++ b/apps/api/src/utils/rate-limit-headers.test.ts@@ -3,6 +3,7 @@ import {apiKeyDenialHeaders,apiKeyResponseHeaders,rateLimitHeaders,+ retryAfterFromBody,retryAfterSeconds,} from "./rate-limit-headers";@@ -72,20 +73,44 @@ describe("apiKeyDenialHeaders", () => {});});+describe("retryAfterFromBody", () => {+ it("turns Better Auth's tryAgainIn milliseconds into seconds", () => {+ expect(retryAfterFromBody({ details: { tryAgainIn: 4_500 } }, now)).toBe(+ "5",+ );+ });++ it("returns null without a numeric wait", () => {+ for (const body of [+ null,+ "slow down",+ {},+ { details: { tryAgainIn: "5" } },+ ])+ expect(retryAfterFromBody(body, now)).toBeNull();+ });+});+describe("apiKeyResponseHeaders", () => {const window = { limit: 5, remaining: 2, resetAt: at(30_000) };+ const valid = { status: "valid" as const, rateLimit: window };const ok = new Response("ok");const tooMany = new Response("slow down", { status: 429 });+ const ipLimited = (retryAfter = "42") =>+ new Response(+ JSON.stringify({ message: "Too many requests. Please try again later." }),+ { status: 429, headers: { "X-Retry-After": retryAfter } },+ );- it("reports the window after a successful request", () => {- expect(- apiKeyResponseHeaders({ status: "valid", rateLimit: window }, ok, now),- ).toEqual(rateLimitHeaders(window));+ it("reports the window after a successful request", async () => {+ expect(await apiKeyResponseHeaders(valid, ok, now)).toEqual(+ rateLimitHeaders(window),+ );});- it("still reports the window when the request spent the last quota unit", () => {+ it("still reports the window when the request spent the last quota unit", async () => {expect(- apiKeyResponseHeaders(+ await apiKeyResponseHeaders({ status: "usage_exceeded", retryAt: null, rateLimit: window },ok,now,@@ -93,9 +118,9 @@ describe("apiKeyResponseHeaders", () => {).toEqual(rateLimitHeaders(window));});- it("reports an empty window when the request filled it", () => {+ it("reports an empty window when the request filled it", async () => {expect(- apiKeyResponseHeaders(+ await apiKeyResponseHeaders({ status: "rate_limited", limit: 5, resetAt: at(30_000) },ok,now,@@ -103,24 +128,24 @@ describe("apiKeyResponseHeaders", () => {).toEqual(rateLimitHeaders({ ...window, remaining: 0 }));});- it("adds the retry headers to a 429 that lacks Retry-After", () => {+ it("adds the retry headers to a 429 that lacks Retry-After", async () => {const denial = {status: "rate_limited" as const,limit: 5,resetAt: at(30_000),};- expect(apiKeyResponseHeaders(denial, tooMany, now)).toEqual(+ expect(await apiKeyResponseHeaders(denial, tooMany, now)).toEqual(apiKeyDenialHeaders(denial, now),);});- it("leaves Retry-After alone when the 429 already has one", () => {+ it("leaves Retry-After alone when the 429 already has one", async () => {const answered = new Response(null, {status: 429,headers: { "Retry-After": "7" },});expect(- apiKeyResponseHeaders(+ await apiKeyResponseHeaders({ status: "rate_limited", limit: 5, resetAt: at(30_000) },answered,now,@@ -128,7 +153,48 @@ describe("apiKeyResponseHeaders", () => {).not.toHaveProperty("Retry-After");});- it("sends nothing when the key could not be read", () => {- expect(apiKeyResponseHeaders(null, tooMany, now)).toEqual({});+ it("copies Better Auth's X-Retry-After without the key's window on an IP limit", async () => {+ expect(await apiKeyResponseHeaders(valid, ipLimited(), now)).toEqual({+ "Retry-After": "42",+ });+ expect(await apiKeyResponseHeaders(valid, ipLimited("0"), now)).toEqual({+ "Retry-After": "1",+ });+ });++ it("treats an IP limit as Better Auth's even when the key is also exhausted", async () => {+ expect(+ await apiKeyResponseHeaders(+ { status: "rate_limited", limit: 5, resetAt: at(30_000) },+ ipLimited(),+ now,+ ),+ ).toEqual({ "Retry-After": "42" });+ });++ it("computes Retry-After from the body of a 429 the key did not cause", async () => {+ const limited = new Response(+ JSON.stringify({ code: "RATE_LIMITED", details: { tryAgainIn: 2_500 } }),+ { status: 429 },+ );+ expect(await apiKeyResponseHeaders(valid, limited, now)).toEqual({+ "Retry-After": "3",+ });+ expect(await limited.json()).toMatchObject({ code: "RATE_LIMITED" });+ });++ it("adds nothing to a 429 the key did not cause without a known wait", async () => {+ expect(await apiKeyResponseHeaders(valid, tooMany.clone(), now)).toEqual(+ {},+ );+ const answered = new Response(null, {+ status: 429,+ headers: { "Retry-After": "7", "X-Retry-After": "7" },+ });+ expect(await apiKeyResponseHeaders(valid, answered, now)).toEqual({});+ });++ it("sends nothing when the key could not be read", async () => {+ expect(await apiKeyResponseHeaders(null, ipLimited(), now)).toEqual({});});});diff --git a/apps/api/src/utils/rate-limit-headers.ts b/apps/api/src/utils/rate-limit-headers.tsindex f05c40fe2..7e7bd5f05 100644--- a/apps/api/src/utils/rate-limit-headers.ts+++ b/apps/api/src/utils/rate-limit-headers.ts@@ -53,12 +53,39 @@ export function apiKeyDenialHeaders(: {};}-export function apiKeyResponseHeaders(+export function retryAfterFromBody(body: unknown, now: Date) {+ const tryAgainIn = (body as { details?: { tryAgainIn?: unknown } } | null)+ ?.details?.tryAgainIn;+ return typeof tryAgainIn === "number"+ ? retryAfterSeconds(new Date(now.getTime() + tryAgainIn), now)+ : null;+}++async function betterAuthRetryAfter(response: Response, now: Date) {+ const seconds = Number.parseFloat(+ response.headers.get("X-Retry-After") ?? "",+ );+ if (Number.isFinite(seconds)) return String(Math.max(1, Math.ceil(seconds)));+ try {+ return retryAfterFromBody(await response.clone().json(), now);+ } catch {+ return null;+ }+}++export async function apiKeyResponseHeaders(check: ApiKeyCheck | null,response: Response,now: Date,-): Record<string, string> {+): Promise<Record<string, string>> {if (!check) return {};+ const keyLimited =+ check.status !== "valid" && !response.headers.has("X-Retry-After");+ if (response.status === 429 && !keyLimited) {+ if (response.headers.has("Retry-After")) return {};+ const retryAfter = await betterAuthRetryAfter(response, now);+ return retryAfter ? { "Retry-After": retryAfter } : {};+ }if (check.status !== "valid" &&response.status === 429 &&diff --git a/apps/docs/api-reference/authentication.mdx b/apps/docs/api-reference/authentication.mdxindex a62ab421c..e4851772e 100644--- a/apps/docs/api-reference/authentication.mdx+++ b/apps/docs/api-reference/authentication.mdx@@ -56,6 +56,8 @@ When a key goes over its limit, Kaneo answers `429 Too Many Requests` with the sA key with a usage quota also gets `429` once the quota runs out, with the message `API key usage limit exceeded`. `Retry-After` is included when the quota refills at a known time.+Auth endpoints under `/api/auth` can also have their own per-IP limits, for example on sign-up and invitations. Those `429` responses include `Retry-After` but no `X-RateLimit` headers, because the request did not count against the key.+## Device authorizationBy default, self-hosted Kaneo allows the built-in device clients `kaneo-cli` and `kaneo-mcp`.diff --git a/tests/api-integration/api-key-rate-limit.test.ts b/tests/api-integration/api-key-rate-limit.test.tsindex cdacb22f5..c1ae31c3c 100644--- a/tests/api-integration/api-key-rate-limit.test.ts+++ b/tests/api-integration/api-key-rate-limit.test.ts@@ -75,6 +75,7 @@ describe("API key rate limits", () => {const after = Date.now();expect(first.status).toBe(200);+ expect(first.headers.get("cache-control")).toBe("private");const headers = limitHeaders(first);expect(headers).toMatchObject({limit: String(LIMIT),@@ -263,6 +264,45 @@ describe("API key rate limits", () => {},);+ it.each([+ [+ "x-api-key",+ "/api/auth/get-session",+ (key: string) => ({ "x-api-key": key }),+ ],+ [+ "a Bearer key",+ "/api/auth/organization/list",+ (key: string) => ({ Authorization: `Bearer ${key}` }),+ ],+ ])(+ "answers Better Auth's own 429 with its Retry-After and no key window via %s",+ async (_, path, headersFor) => {+ const { key, row } = await seedKey();+ vi.spyOn(auth, "handler").mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ message: "Too many requests. Please try again later.",+ }),+ { status: 429, headers: { "X-Retry-After": "42" } },+ ),+ );+ const { app } = createApp();++ const response = await app.request(path, { headers: headersFor(key) });++ expect(response.status).toBe(429);+ expect(limitHeaders(response)).toEqual({+ limit: null,+ remaining: null,+ reset: null,+ retryAfter: "42",+ });+ expect(response.headers.get("cache-control")).toBe("private");+ expect((await savedKey(row.id)).requestCount).toBe(0);+ },+ );+it("still answers when the rate limit headers cannot be read", async () => {const { key, row } = await seedKey();const handler = auth.handler;@@ -354,12 +394,14 @@ describe("API key rate limits", () => {limit: String(LIMIT),remaining: String(LIMIT - 1),});+ expect(missing.headers.get("cache-control")).toBe("private");const unknownRoute = await app.request("/api/no-such-route", {headers: { "x-api-key": key },});expect(unknownRoute.status).toBe(404);expect(limitHeaders(unknownRoute).remaining).toBe(String(LIMIT - 2));+ expect(unknownRoute.headers.get("cache-control")).toBe("private");});it("answers 429 when the usage quota is exhausted", async () => {