Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Fix the review findings on API keys

Claudebae672e716b8
diff --git a/src/app/api/v1/me/route.ts b/src/app/api/v1/me/route.ts
index 887973a..9595919 100644
--- a/src/app/api/v1/me/route.ts
+++ b/src/app/api/v1/me/route.ts
@@ -1,9 +1,31 @@
-import { apiJson } from "@/lib/api/http";
+import { apiError, apiJson } from "@/lib/api/http";
import { requireApiKey, withRateLimitHeaders } from "@/lib/auth/api-key";
+import { logRouteError } from "@/lib/security/logging";
+import { getRequestPathname } from "@/lib/security/request";
// Which key this is and whom it acts as. The simplest way to check that a
// key works.
export async function GET(request: Request) {
+ try {
+ return await answer(request);
+ } catch (error) {
+ // Such as the database being out of reach: still the API's own error
+ // shape, not Next.js's error page.
+ logRouteError(error, {
+ category: "api_me_failure",
+ message: "Unexpected failure in an API request.",
+ path: getRequestPathname(request),
+ });
+
+ return apiError(
+ 500,
+ "internal_error",
+ "Something went wrong on the install. Try again later.",
+ );
+ }
+}
+
+async function answer(request: Request) {
const principal = await requireApiKey(request, "read");
if (principal instanceof Response) {
diff --git a/src/lib/api-keys.dbtest.ts b/src/lib/api-keys.dbtest.ts
index 3cc841b..6f1633e 100644
--- a/src/lib/api-keys.dbtest.ts
+++ b/src/lib/api-keys.dbtest.ts
@@ -9,11 +9,13 @@ import {
authenticateApiKey,
createApiKey,
listApiKeys,
+ LISTED_REVOKED_API_KEYS,
MAX_API_KEYS_PER_USER,
revokeApiKey,
} from "./api-keys.ts";
import { openTestDatabase } from "./db/test-database.ts";
import { setPersonRole } from "./people.ts";
+import { SYSTEM_AUDIT_LOCK_ID } from "./services/system-audit.ts";
// API keys against a real Postgres. Run with `npm run test:db`.
@@ -215,3 +217,72 @@ test("an administrator can have only so many keys at once", async () => {
error instanceof ApiKeyError && error.statusCode === 409,
);
});
+
+test("every key that is not revoked stays in the list, however many are revoked after it", async () => {
+ const admin = await createUser();
+ const { summary: old } = await createApiKey(
+ admin,
+ { expiresInDays: null, name: "Oldest app", scope: "read" },
+ database,
+ );
+
+ for (let index = 0; index < LISTED_REVOKED_API_KEYS + 10; index += 1) {
+ const { summary } = await createApiKey(
+ admin,
+ { expiresInDays: null, name: `Spent ${String(index)}`, scope: "read" },
+ database,
+ );
+
+ await revokeApiKey(admin, summary.id, database);
+ }
+
+ const listed = await listApiKeys(database);
+
+ assert.ok(listed.some((row) => row.id === old.id));
+ assert.equal(
+ listed.filter((row) => row.revokedAt !== null).length,
+ LISTED_REVOKED_API_KEYS,
+ );
+});
+
+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
+ // holding the audit chain, or the two would deadlock.
+ const stays = await createUser();
+ const leaves = await createUser();
+ const { summary } = await createApiKey(
+ leaves,
+ { expiresInDays: null, name: "Contested app", scope: "write" },
+ database,
+ );
+ const holder = await database.connect();
+
+ try {
+ await holder.query("begin");
+ await holder.query(`select id from api_keys where id = $1 for update`, [
+ summary.id,
+ ]);
+
+ const roleChange = setPersonRole(
+ stays.userId,
+ leaves.userId,
+ "user",
+ database,
+ );
+
+ // Give it time to reach the key row.
+ await new Promise((resolve) => setTimeout(resolve, 300));
+
+ const free = await holder.query<{ locked: boolean }>(
+ `select pg_try_advisory_xact_lock($1) as locked`,
+ [SYSTEM_AUDIT_LOCK_ID],
+ );
+
+ assert.equal(free.rows[0]?.locked, true);
+ await holder.query("rollback");
+ await roleChange;
+ } finally {
+ holder.release();
+ }
+});
diff --git a/src/lib/api-keys.ts b/src/lib/api-keys.ts
index c3f67d8..6842833 100644
--- a/src/lib/api-keys.ts
+++ b/src/lib/api-keys.ts
@@ -274,23 +274,44 @@ async function getApiKeySummary(
);
}
+/** How many revoked keys Settings still lists, newest first. */
+export const LISTED_REVOKED_API_KEYS = 50;
+
/**
- * Every key on the install, newest first. Administrators manage each
- * other's keys, since a key acts for the organization.
+ * Every key on the install that is not revoked (expired ones too, so none
+ * that could still matter is ever out of sight), newest first, then the
+ * most recently revoked. Administrators manage each other's keys, since a
+ * key acts for the organization.
*/
export async function listApiKeys(
database: DbExecutor = getDb(),
): Promise<ApiKeySummary[]> {
- return queryMany<ApiKeySummary>(
- database,
- `
- SELECT ${SUMMARY_COLUMNS}
- FROM api_keys k
- JOIN "user" u ON u.id = k.user_id
- ORDER BY k.revoked_at IS NOT NULL, k.created_at DESC
- LIMIT 200
- `,
- );
+ 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];
}
/** Revokes a key for the administrator `actor`. Revoking twice is fine. */
diff --git a/src/lib/people.ts b/src/lib/people.ts
index 04dd9f2..774b731 100644
--- a/src/lib/people.ts
+++ b/src/lib/people.ts
@@ -283,6 +283,19 @@ export async function setPersonRole(
`UPDATE "user" SET role = $1, "updatedAt" = now() WHERE id = $2`,
[role, targetUserId],
);
+
+ if (role === "user") {
+ // A key acts as its administrator. One who is no longer one loses
+ // their keys for good, so making them one again later does not
+ // quietly bring old keys back. Done before the audit event below:
+ // revokeApiKey locks a key row and then the audit chain, so this
+ // takes them in the same order and the two cannot deadlock.
+ await revokeApiKeysForUser(targetUserId, "role_removed", tx, {
+ email: actor.email,
+ userId: actingUserId,
+ });
+ }
+
await recordSystemAuditEvent(
{
actorEmail: actor.email,
@@ -299,16 +312,6 @@ export async function setPersonRole(
tx,
);
- if (role === "user") {
- // A key acts as its administrator. One who is no longer one loses
- // their keys for good, so making them one again later does not
- // quietly bring old keys back.
- await revokeApiKeysForUser(targetUserId, "role_removed", tx, {
- email: actor.email,
- userId: actingUserId,
- });
- }
-
if (keeperId) {
// The account's row has been held since it was read above. A closed
// account's envelopes are handed over only while holding the
diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.ts
index 18ed1d3..b494cbc 100644
--- a/src/lib/services/system-audit.ts
+++ b/src/lib/services/system-audit.ts
@@ -73,7 +73,7 @@ export type RecordSystemAuditEventInput = {
};
/** One key for the whole chain: writers take turns. */
-const SYSTEM_AUDIT_LOCK_ID = 746108325;
+export const SYSTEM_AUDIT_LOCK_ID = 746108325;
type ChainedFields = Omit<SystemAuditEvent, never>;