Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Answer the review notes on API keys
Claude29858181eb53
diff --git a/src/components/settings/api-keys-panel.tsx b/src/components/settings/api-keys-panel.tsxindex 07fedf7..4e1674e 100644--- a/src/components/settings/api-keys-panel.tsx+++ b/src/components/settings/api-keys-panel.tsx@@ -89,9 +89,14 @@ export function ApiKeysPanel() {}, [revision]);async function createKey() {+ // A key on screen stays until Done, so its one-time secret is never lost+ // to a second key that then fails to be made.+ if (newKey) {+ return;+ }+setIsCreating(true);setError(null);- setNewKey(null);setCopied(false);try {@@ -115,8 +120,12 @@ export function ApiKeysPanel() {return;}- setNewKey({ key: payload.key, name: payload.summary.name });+ const created = payload.summary;++ setNewKey({ key: payload.key, name: created.name });setName("");+ // Shown at once, in case reading the list again fails.+ setKeys((current) => (current ? [created, ...current] : current));setRevision((value) => value + 1);} catch {setError(GENERIC_ERROR_MESSAGE);@@ -136,6 +145,7 @@ export function ApiKeysPanel() {);const payload = (await response.json().catch(() => null)) as {error?: string;+ key?: ApiKeySummary;} | null;if (!response.ok) {@@ -143,7 +153,21 @@ export function ApiKeysPanel() {return;}+ const revoked = payload?.key;+setRevokingId(null);++ // Shown as revoked at once, in case reading the list again fails.+ if (revoked) {+ setKeys((current) =>+ current+ ? current.map((listed) =>+ listed.id === revoked.id ? revoked : listed,+ )+ : current,+ );+ }+setRevision((value) => value + 1);} catch {setError(GENERIC_ERROR_MESSAGE);@@ -243,7 +267,7 @@ export function ApiKeysPanel() {<div className="flex items-end"><buttonclassName="btn-quiet min-h-12 w-full px-5 text-sm"- disabled={isCreating || trimmedName.length === 0}+ disabled={isCreating || newKey !== null || trimmedName.length === 0}onClick={() => void createKey()}type="button">diff --git a/src/lib/api-keys.dbtest.ts b/src/lib/api-keys.dbtest.tsindex 6f1633e..2af693e 100644--- a/src/lib/api-keys.dbtest.ts+++ b/src/lib/api-keys.dbtest.ts@@ -245,6 +245,34 @@ test("every key that is not revoked stays in the list, however many are revoked);});+/** Resolves once another session is waiting on a lock that `holder` has. */+async function waitUntilBlockedBy(holder: pg.PoolClient) {+ const self = await holder.query<{ pid: number }>(+ "select pg_backend_pid() as pid",+ );+ const holderPid = self.rows[0]?.pid;++ for (let attempt = 0; attempt < 500; attempt += 1) {+ const waiting = await database.query(+ `+ select 1+ from pg_stat_activity+ where $1::integer = any(pg_blocking_pids(pid))+ limit 1+ `,+ [holderPid],+ );++ if (waiting.rowCount) {+ return;+ }++ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ throw new Error("Nothing started waiting on the held key row.");+}+test("removing an administrator takes the key rows before the audit lock, as revoking a key does", async () => {// revokeApiKey locks a key row and then the audit chain. Hold a key row// the way it does, and the role change must wait for it without already@@ -271,8 +299,7 @@ test("removing an administrator takes the key rows before the audit lock, as revdatabase,);- // Give it time to reach the key row.- await new Promise((resolve) => setTimeout(resolve, 300));+ await waitUntilBlockedBy(holder);const free = await holder.query<{ locked: boolean }>(`select pg_try_advisory_xact_lock($1) as locked`,diff --git a/src/lib/api-keys.ts b/src/lib/api-keys.tsindex 6842833..d02d314 100644--- a/src/lib/api-keys.ts+++ b/src/lib/api-keys.ts@@ -286,32 +286,32 @@ export const LISTED_REVOKED_API_KEYS = 50;export async function listApiKeys(database: DbExecutor = getDb(),): Promise<ApiKeySummary[]> {- const [live, revoked] = await Promise.all([- queryMany<ApiKeySummary>(- database,- `- SELECT ${SUMMARY_COLUMNS}- FROM api_keys k- JOIN "user" u ON u.id = k.user_id- WHERE k.revoked_at IS NULL- ORDER BY k.created_at DESC, k.id- `,- ),- queryMany<ApiKeySummary>(- database,- `- SELECT ${SUMMARY_COLUMNS}- FROM api_keys k- JOIN "user" u ON u.id = k.user_id- WHERE k.revoked_at IS NOT NULL- ORDER BY k.revoked_at DESC, k.id- LIMIT $1- `,- [LISTED_REVOKED_API_KEYS],- ),- ]);-- return [...live, ...revoked];+ // One statement, so both groups come from the same moment: a key revoked+ // while the list is read shows once, not as both working and revoked.+ return queryMany<ApiKeySummary>(+ database,+ `+ WITH listed AS (+ SELECT id, 0 AS list_group, created_at AS sorted_by+ FROM api_keys+ WHERE revoked_at IS NULL+ UNION ALL+ (+ SELECT id, 1 AS list_group, revoked_at AS sorted_by+ FROM api_keys+ WHERE revoked_at IS NOT NULL+ ORDER BY revoked_at DESC, id+ LIMIT $1+ )+ )+ SELECT ${SUMMARY_COLUMNS}+ FROM listed l+ JOIN api_keys k ON k.id = l.id+ JOIN "user" u ON u.id = k.user_id+ ORDER BY l.list_group, l.sorted_by DESC, k.id+ `,+ [LISTED_REVOKED_API_KEYS],+ );}/** Revokes a key for the administrator `actor`. Revoking twice is fine. */@@ -505,11 +505,17 @@ export async function authenticateApiKey(row.lastUsedAt === null ||now - row.lastUsedAt >= LAST_USED_WRITE_INTERVAL_SECONDS) {+ // The interval is checked again against the row as it is now, so+ // requests at the same moment write once and an older time never+ // replaces a newer one.await database- .query(`UPDATE api_keys SET last_used_at = $1 WHERE id = $2`, [- now,- row.id,- ])+ .query(+ `+ UPDATE api_keys SET last_used_at = $1+ WHERE id = $2 AND (last_used_at IS NULL OR last_used_at <= $1 - $3)+ `,+ [now, row.id, LAST_USED_WRITE_INTERVAL_SECONDS],+ ).catch((error: unknown) => {console.error("Recording when an API key was used failed:", error);});diff --git a/src/lib/auth/api-key.ts b/src/lib/auth/api-key.tsindex fa087ea..35d4c27 100644--- a/src/lib/auth/api-key.ts+++ b/src/lib/auth/api-key.ts@@ -119,11 +119,23 @@ async function refuseBadKey();}- await consumeRateLimit({+ const counted = await consumeRateLimit({key: failureKey,limit: FAILED_ATTEMPT_LIMIT,windowMs: FAILED_ATTEMPT_WINDOW_MS,});++ // Bad keys sent at the same moment can all pass the check above, so the+ // count they leave decides too.+ if (!counted.allowed) {+ return apiError(+ 429,+ "rate_limited",+ "Too many requests with a bad key. Try again later.",+ { "retry-after": String(counted.retryAfterSeconds) },+ );+ }+logSecurityEvent("warn", {category: "api_key_rejected",ipAddress,