Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Never let bad keys from an address lock out a good key from it
Claude709f99efab49
diff --git a/docs/api.md b/docs/api.mdindex a993416..0af11a5 100644--- a/docs/api.md+++ b/docs/api.md@@ -47,7 +47,9 @@ What to know about keys:- **Keys skip two-step sign-in.** They are for servers, so keep them in yourapp's secret settings (for example a Vercel environment variable), neverin a browser or a mobile app, and revoke a key as soon as it may have- leaked. The `sdk_` prefix lets secret scanners such as GitHub's spot one.+ leaked. The `sdk_` prefix makes a leaked key easy to search for. Secret+ scanners do not know it out of the box, but one that takes custom+ patterns can be given `sdk_[A-Za-z0-9_-]{43}`.- Each administrator can have up to 25 keys that have not been revoked orexpired.- Making and revoking keys is recorded in the site audit trail (Settings,@@ -88,8 +90,8 @@ stands:- `RateLimit-Reset`: seconds until the window starts again.The limits the web app has on creating and sending envelopes apply to keys-too. An address that sends 30 bad keys in 10 minutes is turned away until-the 10 minutes are up.+too. An address that sends 30 bad keys in 10 minutes gets 429 for any more+bad keys until the 10 minutes are up. Good keys from it keep working.## Endpointsdiff --git a/src/lib/auth/api-key.dbtest.ts b/src/lib/auth/api-key.dbtest.tsnew file mode 100644index 0000000..dddb98c--- /dev/null+++ b/src/lib/auth/api-key.dbtest.ts@@ -0,0 +1,140 @@+import assert from "node:assert/strict";+import { randomBytes, randomUUID } from "node:crypto";+import { registerHooks } from "node:module";+import { after, before, test } from "node:test";++import type pg from "pg";++import { createApiKey } from "../api-keys.ts";+import { replaceDbPoolForTests } from "../db/connection.ts";+import { openTestDatabase } from "../db/test-database.ts";+import { clearRateLimit } from "../security/rate-limit.ts";+import type { requireApiKey as RequireApiKey } from "./api-key.ts";++// The /api/v1 auth path against a real Postgres. Run with `npm run test:db`.++// The API's responses come from next/server, which Next.js resolves for+// itself. Plain Node needs the file name.+registerHooks({+ resolve(specifier, context, nextResolve) {+ if (/^next\/[a-z-]+$/.test(specifier)) {+ return nextResolve(`${specifier}.js`, context);+ }++ return nextResolve(specifier, context);+ },+});++let database: pg.Pool;+let replaced: pg.Pool | null = null;+let requireApiKey: typeof RequireApiKey;+const createdUsers: string[] = [];++before(async () => {+ database = await openTestDatabase();+ replaced = replaceDbPoolForTests(database);+ ({ requireApiKey } = await import("./api-key.ts"));+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ replaceDbPoolForTests(replaced ?? database);+ await database.end();+});++async function createAdmin() {+ const id = randomUUID();++ createdUsers.push(id);+ await database.query(+ `+ insert into public."user" (id, name, email, role, "emailVerified")+ values ($1, $2, $3, 'admin', true)+ `,+ [id, `Person ${id.slice(0, 4)}`, `${id}@example.test`],+ );++ return { email: `${id}@example.test`, userId: id };+}++function apiRequest(key: string, address?: string) {+ const headers = new Headers({ authorization: `Bearer ${key}` });++ if (address) {+ headers.set("x-forwarded-for", address);+ }++ return new Request("https://sign.example.test/api/v1/me", { headers });+}++test("bad keys from an address get 429 in the end, but never lock out a good key from it", async () => {+ const admin = await createAdmin();+ const { key } = await createApiKey(+ admin,+ { expiresInDays: null, name: "Billing worker", scope: "read" },+ database,+ );+ // A documentation address of its own, so no other run's count is in it.+ const address = `2001:db8::${randomBytes(2).toString("hex")}`;+ const failureKey = `api-key-failures:${address}`;+ const badKey = `sdk_${"A".repeat(43)}`;++ await clearRateLimit(failureKey);++ try {+ for (let attempt = 1; attempt <= 30; attempt += 1) {+ const refused = await requireApiKey(apiRequest(badKey, address), "read");++ assert.ok(refused instanceof Response);+ assert.equal(refused.status, 401, `bad key ${String(attempt)}`);+ }++ const turnedAway = await requireApiKey(apiRequest(badKey, address), "read");++ assert.ok(turnedAway instanceof Response);+ assert.equal(turnedAway.status, 429);+ assert.ok(Number(turnedAway.headers.get("retry-after")) >= 1);+ assert.deepEqual(await turnedAway.json(), {+ error: {+ code: "rate_limited",+ message: "Too many requests with a bad key. Try again later.",+ },+ });++ const accepted = await requireApiKey(apiRequest(key, address), "read");++ assert.ok(!(accepted instanceof Response));+ assert.equal(accepted.user.id, admin.userId);+ assert.equal(accepted.apiKey.name, "Billing worker");+ } finally {+ await clearRateLimit(failureKey);+ }+});++test("a read-only key is let in to read and refused for writing", async () => {+ const admin = await createAdmin();+ const { key } = await createApiKey(+ admin,+ { expiresInDays: 30, name: "Dashboard", scope: "read" },+ database,+ );++ const reading = await requireApiKey(apiRequest(key), "read");++ assert.ok(!(reading instanceof Response));+ assert.equal(reading.apiKey.scope, "read");++ const writing = await requireApiKey(apiRequest(key), "write");++ assert.ok(writing instanceof Response);+ assert.equal(writing.status, 403);+ assert.equal(writing.headers.get("ratelimit-limit"), "600");+ assert.deepEqual(await writing.json(), {+ error: {+ code: "forbidden",+ message: "This key is read-only. Use a key with write access.",+ },+ });+});diff --git a/src/lib/auth/api-key.ts b/src/lib/auth/api-key.tsindex bffe646..fa087ea 100644--- a/src/lib/auth/api-key.ts+++ b/src/lib/auth/api-key.ts@@ -13,7 +13,7 @@ import { getClientIpAddress, getRequestPathname } from "../security/request.ts";/** Requests one key may make in a window, across every endpoint. */export const API_KEY_RATE_LIMIT = 600;export const API_KEY_RATE_WINDOW_MS = 10 * 60 * 1000;-/** Failed attempts one address may make before it is turned away. */+/** Bad keys one address may send before more of them get 429. */const FAILED_ATTEMPT_LIMIT = 30;const FAILED_ATTEMPT_WINDOW_MS = 10 * 60 * 1000;@@ -39,42 +39,14 @@ export async function requireApiKey(});}- const failureKey = `api-key-failures:${ipAddress ?? "unknown"}`;- const failures = await peekRateLimit({- key: failureKey,- limit: FAILED_ATTEMPT_LIMIT,- });-- // An address that keeps sending bad keys is turned away before the- // database is asked about another one.- if (!failures.allowed) {- return apiError(- 429,- "rate_limited",- "Too many requests with a bad key. Try again later.",- { "retry-after": String(failures.retryAfterSeconds) },- );- }-+ // The key is looked up first, so bad keys from an address never turn+ // away a good one from it: another worker of an app still sending a key+ // that was revoked, or, off Vercel, a stranger who forged the address in+ // X-Forwarded-For to lock an integration out.const principal = await authenticateApiKey(presented);if (!principal) {- await consumeRateLimit({- key: failureKey,- limit: FAILED_ATTEMPT_LIMIT,- windowMs: FAILED_ATTEMPT_WINDOW_MS,- });- logSecurityEvent("warn", {- category: "api_key_rejected",- ipAddress,- message:- "Refused an API request with an unknown, revoked or expired key.",- path: getRequestPathname(request),- });-- return apiError(401, "unauthorized", UNAUTHORIZED_MESSAGE, {- "www-authenticate": 'Bearer realm="signudoc", error="invalid_token"',- });+ return refuseBadKey(request, ipAddress);}const decision = await consumeRateLimit({@@ -123,6 +95,47 @@ export async function requireApiKey(return { ...principal, rateLimit };}+/**+ * The answer to a key that does not work. Bad keys are counted per+ * address. Once an address has sent too many, it gets 429 instead of 401+ * until the window ends, and nothing more is written or logged for it.+ */+async function refuseBadKey(+ request: Request,+ ipAddress: string | null,+): Promise<Response> {+ const failureKey = `api-key-failures:${ipAddress ?? "unknown"}`;+ const failures = await peekRateLimit({+ key: failureKey,+ limit: FAILED_ATTEMPT_LIMIT,+ });++ if (!failures.allowed) {+ return apiError(+ 429,+ "rate_limited",+ "Too many requests with a bad key. Try again later.",+ { "retry-after": String(failures.retryAfterSeconds) },+ );+ }++ await consumeRateLimit({+ key: failureKey,+ limit: FAILED_ATTEMPT_LIMIT,+ windowMs: FAILED_ATTEMPT_WINDOW_MS,+ });+ logSecurityEvent("warn", {+ category: "api_key_rejected",+ ipAddress,+ message: "Refused an API request with an unknown, revoked or expired key.",+ path: getRequestPathname(request),+ });++ return apiError(401, "unauthorized", UNAUTHORIZED_MESSAGE, {+ "www-authenticate": 'Bearer realm="signudoc", error="invalid_token"',+ });+}+export type RateLimitState = {limit: number;remaining: number;