Skip to content

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

TypeScript

Hold the administrator's row while a key is revoked

Claude1b24d493814a
diff --git a/src/lib/api-keys.dbtest.ts b/src/lib/api-keys.dbtest.ts
index fa4c88f..5b037fa 100644
--- a/src/lib/api-keys.dbtest.ts
+++ b/src/lib/api-keys.dbtest.ts
@@ -329,9 +329,54 @@ async function waitUntilBlockedBy(holder: pg.PoolClient) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
- throw new Error("Nothing started waiting on the held key row.");
+ throw new Error("Nothing started waiting on the held row.");
}
+test("a revocation by an administrator being removed at that moment waits, and is then refused", async () => {
+ const leaving = await createUser();
+ const other = await createUser();
+ const { summary } = await createApiKey(
+ other,
+ { expiresInDays: null, name: "Their app", scope: "write" },
+ database,
+ );
+ // The removal of the actor's role, under way but not yet committed.
+ const holder = await database.connect();
+ let revocation: Promise<unknown> | undefined;
+
+ try {
+ await holder.query("begin");
+ await holder.query(`update "user" set role = 'user' where id = $1`, [
+ leaving.userId,
+ ]);
+
+ revocation = revokeApiKey(leaving, summary.id, database);
+ // Handled at once, so a failure before it waits is reported below
+ // instead of as an unhandled rejection.
+ revocation.catch(() => undefined);
+
+ await waitUntilBlockedBy(holder);
+ await holder.query("commit");
+ } finally {
+ await holder.query("rollback").catch(() => undefined);
+ await revocation?.catch(() => undefined);
+ holder.release();
+ }
+
+ await assert.rejects(
+ revocation!,
+ (error: unknown) =>
+ error instanceof ApiKeyError && error.statusCode === 403,
+ );
+
+ const key = await database.query<{ revokedAt: number | null }>(
+ `select revoked_at as "revokedAt" from api_keys where id = $1`,
+ [summary.id],
+ );
+
+ assert.equal(key.rows[0]?.revokedAt, null);
+});
+
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
diff --git a/src/lib/api-keys.ts b/src/lib/api-keys.ts
index 614e260..494d0e7 100644
--- a/src/lib/api-keys.ts
+++ b/src/lib/api-keys.ts
@@ -335,9 +335,13 @@ export async function revokeApiKey(
const revokedAt = nowInSeconds();
await withTransaction(async (tx) => {
+ // Held until the revocation commits, as when a key is made, so a
+ // removal of the actor's role that lands at the same moment either
+ // waits for it or is seen here. The user row comes before the key row
+ // and the audit chain, the order a role change takes them in too.
const owner = await queryOne<{ role: string }>(
tx,
- `SELECT role FROM "user" WHERE id = $1`,
+ `SELECT role FROM "user" WHERE id = $1 FOR UPDATE`,
[actor.userId],
);