Skip to content

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

TypeScript

Take the administrator's account row before the envelope when deleting

Claude479d91ae137c
diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.ts
index bcd95f6..414c10d 100644
--- a/src/lib/envelope-deletion.dbtest.ts
+++ b/src/lib/envelope-deletion.dbtest.ts
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
import { after, before, test } from "node:test";
import type pg from "pg";
@@ -26,6 +27,9 @@ import {
const SOURCE_HASH = "a".repeat(64);
const SIGNED_HASH = "b".repeat(64);
const EVIDENCE_HASH = "c".repeat(64);
+const RECIPIENT_EVIDENCE_HASH = "d".repeat(64);
+// The install audit trail's lock (services/system-audit.ts).
+const SYSTEM_AUDIT_LOCK_ID = 746108325;
let database: pg.Pool;
let storageDir: string;
@@ -108,10 +112,10 @@ async function createEnvelope(
id, user_id, title, status, source_pdf_key, source_pdf_filename,
source_pdf_size_bytes, page_count, source_pdf_hash, sent_at,
completed_at, declined_at, voided_at, signed_pdf_key, evidence_key,
- signed_pdf_sha256, evidence_sha256, part11
+ signed_pdf_sha256, evidence_sha256, part11, recipient_evidence_sha256
) values (
$1, $2, 'Lease', $3, $4, 'lease.pdf', 4, 1, $14, $5,
- $6, $7, $8, $9, $10, $11, $12, $13
+ $6, $7, $8, $9, $10, $11, $12, $13, $15
)
`,
[
@@ -129,6 +133,7 @@ async function createEnvelope(
finished ? EVIDENCE_HASH : null,
part11,
SOURCE_HASH,
+ finished ? RECIPIENT_EVIDENCE_HASH : null,
],
);
await database.query(
@@ -199,6 +204,7 @@ for (const status of ["completed", "declined", "voided"] as const) {
envelopeId: event?.metadata?.envelopeId,
evidenceSha256: event?.metadata?.evidenceSha256,
reason: event?.metadata?.reason,
+ recipientEvidenceSha256: event?.metadata?.recipientEvidenceSha256,
sourcePdfHash: event?.metadata?.sourcePdfHash,
status: event?.metadata?.status,
title: event?.metadata?.title,
@@ -207,6 +213,7 @@ for (const status of ["completed", "declined", "voided"] as const) {
envelopeId: envelope.envelopeId,
evidenceSha256: EVIDENCE_HASH,
reason: "Kept long enough.",
+ recipientEvidenceSha256: RECIPIENT_EVIDENCE_HASH,
sourcePdfHash: SOURCE_HASH,
status,
title: "Lease",
@@ -362,3 +369,74 @@ test("when the deletion fails before it commits, no file is touched", async () =
assert.equal(await envelopeExists(envelope.envelopeId), true);
assert.ok((await filesExist(envelope.stored)).every(Boolean));
});
+
+test("an administrator whose role is being taken away waits for it, and is then refused", async () => {
+ const admin = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, { status: "completed" });
+ const demotion = await database.connect();
+
+ try {
+ // As taking the role away does: the account row first.
+ await demotion.query("begin");
+ await demotion.query(
+ `select id from public."user" where id = $1 for update`,
+ [admin.userId],
+ );
+
+ const deletion = deleteAs(admin, envelope.envelopeId, "Done.");
+
+ await delay(300);
+ await demotion.query(
+ `update public."user" set role = 'user' where id = $1`,
+ [admin.userId],
+ );
+ await demotion.query("commit");
+
+ await assert.rejects(deletion, rejectsWith(403));
+ } finally {
+ demotion.release();
+ }
+
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+ assert.ok((await filesExist(envelope.stored)).every(Boolean));
+});
+
+test("a deletion running while the administrator's handed-over envelopes move does not deadlock", async () => {
+ const admin = await createUser("admin");
+ const keeper = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, { status: "completed" });
+ const demotion = await database.connect();
+
+ try {
+ // In the order taking the role away uses: the account row, the audit
+ // trail lock, then the envelopes it moves to the administrator who stays.
+ await demotion.query("begin");
+ await demotion.query(
+ `select id from public."user" where id = $1 for update`,
+ [admin.userId],
+ );
+ await demotion.query(
+ `update public."user" set role = 'user' where id = $1`,
+ [admin.userId],
+ );
+ await demotion.query("select pg_advisory_xact_lock($1)", [
+ SYSTEM_AUDIT_LOCK_ID,
+ ]);
+
+ const deletion = deleteAs(admin, envelope.envelopeId, "Done.");
+
+ await delay(300);
+ await demotion.query(`update envelopes set user_id = $1 where id = $2`, [
+ keeper.userId,
+ envelope.envelopeId,
+ ]);
+ await demotion.query("commit");
+
+ // The envelope is no longer the deleting account's to delete.
+ await assert.rejects(deletion, rejectsWith(404));
+ } finally {
+ demotion.release();
+ }
+
+ assert.equal(await envelopeExists(envelope.envelopeId), true);
+});
diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.ts
index 2cec3b0..211127d 100644
--- a/src/lib/envelope-deletion.ts
+++ b/src/lib/envelope-deletion.ts
@@ -27,6 +27,7 @@ type FinishedEnvelopeRow = {
finishedAt: number | null;
id: string;
part11: boolean;
+ recipientEvidenceSha256: string | null;
signedPdfSha256: string | null;
sourcePdfHash: string;
status: string;
@@ -86,7 +87,19 @@ export async function deleteFinishedEnvelope(
): Promise<{ deletedEnvelopeId: string }> {
const { deletedEnvelopeId, storageKeys } = await withTransaction(
async (tx) => {
- // The envelope row first, as everything that changes an envelope takes
+ // The administrator's own account row before the envelope row. Taking
+ // away the role holds that row (FOR UPDATE) before it takes the audit
+ // trail lock and moves the account's handed-over envelopes, so the
+ // two wait for each other here instead of each holding what the
+ // other needs. Read under this lock, the role is the one in force:
+ // a change since the page loaded is honored.
+ const actorRole = await queryOne<{ role: string }>(
+ tx,
+ `SELECT role FROM public."user" WHERE id = $1 FOR SHARE`,
+ [actor.userId],
+ );
+
+ // Then the envelope row, as everything that changes an envelope takes
// it; the install's audit trail lock comes after.
const envelope = await queryOne<FinishedEnvelopeRow>(
tx,
@@ -99,6 +112,7 @@ export async function deleteFinishedEnvelope(
source_pdf_hash AS "sourcePdfHash",
signed_pdf_sha256 AS "signedPdfSha256",
evidence_sha256 AS "evidenceSha256",
+ recipient_evidence_sha256 AS "recipientEvidenceSha256",
COALESCE(completed_at, declined_at, voided_at) AS "finishedAt"
FROM envelopes
WHERE id = $1 AND user_id = $2
@@ -120,14 +134,6 @@ export async function deleteFinishedEnvelope(
);
}
- // Asked again here, not only by the route: the role is read from the
- // database, and a change since the page loaded is honored.
- const actorRole = await queryOne<{ role: string }>(
- tx,
- `SELECT role FROM public."user" WHERE id = $1`,
- [actor.userId],
- );
-
if (actorRole?.role !== "admin") {
throw new EnvelopeMutationError(
"Only an administrator can delete a finished envelope.",
@@ -149,6 +155,7 @@ export async function deleteFinishedEnvelope(
finishedAt: envelope.finishedAt,
part11: envelope.part11,
reason: deletionReason,
+ recipientEvidenceSha256: envelope.recipientEvidenceSha256,
signedPdfSha256: envelope.signedPdfSha256,
sourcePdfHash: envelope.sourcePdfHash,
status: envelope.status,