Skip to content

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

TypeScript

Remove a failed void's or decline's certificates only while the envelope is unclaimed

njarrarb066e7f789a0
diff --git a/src/lib/certificate-cleanup.ts b/src/lib/certificate-cleanup.ts
new file mode 100644
index 0000000..8ba65d0
--- /dev/null
+++ b/src/lib/certificate-cleanup.ts
@@ -0,0 +1,58 @@
+import { type DbPool, queryOne, withTransaction } from "./db/connection.ts";
+import type { StorageService } from "./services/storage.ts";
+
+/**
+ * Removes the certificates a void or a decline stored before it failed.
+ *
+ * The files have fixed keys, and whatever ends an envelope stores them while
+ * it holds the envelope's row. A statement that fails inside a transaction
+ * makes Postgres give that row up at once, before the failure is even
+ * reported, so by now something else may have ended the envelope and stored
+ * certificates of its own under the same keys. The row is therefore taken
+ * again, and the files are removed only while the envelope is still out for
+ * signature: then nothing has claimed them, and nothing can while the row is
+ * held.
+ *
+ * If the row cannot be taken the files stay. A file nothing points at is
+ * written over by whatever ends the envelope next; a certificate deleted
+ * from under a finished envelope is gone for good.
+ */
+export async function removeUnclaimedEnvelopeCertificates(
+ {
+ envelopeId,
+ keys,
+ storageService,
+ }: {
+ envelopeId: string;
+ keys: readonly string[];
+ storageService: Pick<StorageService, "deleteObject">;
+ },
+ database: DbPool,
+): Promise<void> {
+ if (keys.length === 0) {
+ return;
+ }
+
+ await withTransaction(async (tx) => {
+ const envelope = await queryOne<{ status: string }>(
+ tx,
+ `
+ SELECT status
+ FROM envelopes
+ WHERE id = $1
+ FOR NO KEY UPDATE
+ `,
+ [envelopeId],
+ );
+
+ if (envelope && envelope.status !== "sent") {
+ return;
+ }
+
+ await Promise.all(
+ keys.map((key) =>
+ storageService.deleteObject(key).catch(() => undefined),
+ ),
+ );
+ }, database).catch(() => undefined);
+}
diff --git a/src/lib/certificate-race.dbtest.ts b/src/lib/certificate-race.dbtest.ts
index 78d529b..c44d470 100644
--- a/src/lib/certificate-race.dbtest.ts
+++ b/src/lib/certificate-race.dbtest.ts
@@ -189,9 +189,17 @@ function signEnvelope(envelope: Envelope, pool: pg.Pool = database) {
);
}
-/** Resolves once another session is held up behind a lock. */
-async function waitForLockWaiter() {
+/**
+ * Resolves once another session is held up behind a lock, or once `isOver()`
+ * says the one expected to wait has finished without waiting. Anything else
+ * means the two never overlapped, and the test would prove nothing.
+ */
+async function waitForLockWaiter(isOver: () => boolean) {
for (let attempt = 0; attempt < 300; attempt += 1) {
+ if (isOver()) {
+ return;
+ }
+
const waiting = await database.query(
`
select 1
@@ -207,6 +215,25 @@ async function waitForLockWaiter() {
await new Promise((resolve) => setTimeout(resolve, 10));
}
+
+ throw new Error("Nothing came to wait for the envelope.");
+}
+
+/** Starts the rival, and waits until it is over or held up behind a lock. */
+async function startRival(start: () => Promise<unknown>) {
+ let over = false;
+ const rival = start();
+
+ rival.then(
+ () => {
+ over = true;
+ },
+ () => {
+ over = true;
+ },
+ );
+
+ return { rival, waiting: waitForLockWaiter(() => over) };
}
/**
@@ -224,20 +251,98 @@ function withRivalAfter(
database,
(text) => !started.rival && text.includes(`status = '${status}'`),
async () => {
- started.rival = start();
- await Promise.race([
- started.rival.then(
- () => undefined,
- () => undefined,
- ),
- waitForLockWaiter(),
- ]);
+ const { rival, waiting } = await startRival(start);
+
+ started.rival = rival;
+ await waiting;
},
);
return { pool, started };
}
+type QueryFunction = (text: unknown, values?: unknown[]) => Promise<unknown>;
+
+/**
+ * The same database, except that the one using it fails right after it has
+ * written `status`: Postgres refuses a statement of its, which ends its
+ * transaction there and frees the envelope before the failure is reported.
+ * `start()` was waiting for the envelope by then, and is left to finish
+ * first.
+ */
+function withFailureAfter(
+ status: "declined" | "voided",
+ start: () => Promise<unknown>,
+) {
+ const started: { rival?: Promise<unknown> } = {};
+
+ function bound(object: object, property: string | symbol): unknown {
+ const value: unknown = Reflect.get(object, property);
+
+ return typeof value === "function"
+ ? (value.bind(object) as unknown)
+ : value;
+ }
+
+ const pool = new Proxy(database, {
+ get(target, property) {
+ if (property !== "connect") {
+ return bound(target, property);
+ }
+
+ return async () => {
+ const client = await target.connect();
+
+ return new Proxy(client, {
+ get(object, name) {
+ if (name !== "query") {
+ return bound(object, name);
+ }
+
+ const query = bound(object, name) as QueryFunction;
+ const failing: QueryFunction = async (text, values) => {
+ const result = await query(text, values);
+
+ if (
+ started.rival ||
+ typeof text !== "string" ||
+ !text.includes(`status = '${status}'`)
+ ) {
+ return result;
+ }
+
+ const { rival, waiting } = await startRival(start);
+
+ started.rival = rival;
+ await waiting;
+ await assert.rejects(query("select 1 / 0"));
+ await rival.catch(() => undefined);
+
+ throw new Error("The statement failed.");
+ };
+
+ return failing;
+ },
+ });
+ };
+ },
+ });
+
+ return { pool, started };
+}
+
+async function certificatesStored(envelope: Envelope) {
+ const stored = await Promise.all(
+ (["internal", "recipient"] as const).map(async (audience) => {
+ const key = buildEnvelopeCertificateKey({ ...envelope, audience });
+
+ return (await storageService.headObject(key)).exists;
+ }),
+ );
+
+ return stored;
+}
+
/**
* The envelope ended the way the winner ended it, and both of its
* certificates are the files the winner stored: still there, and still the
@@ -359,3 +464,44 @@ test("a void that loses to the last signature leaves the finished certificates a
await assertRefused(started.rival, EnvelopeMutationError);
await assertCertificatesKept(envelope, "completed");
});
+
+test("a void that fails after storing its certificates leaves alone those of the void that went through", async () => {
+ const envelope = await createSignableEnvelope();
+ const { pool, started } = withFailureAfter("voided", () =>
+ voidEnvelope(envelope),
+ );
+
+ await assert.rejects(voidEnvelope(envelope, pool), /The statement failed/);
+
+ assert.ok(started.rival, "the failing void never wrote its status");
+ await started.rival;
+ await assertCertificatesKept(envelope, "voided");
+});
+
+test("a decline that fails after storing its certificates leaves alone those of the void that went through", async () => {
+ const envelope = await createSignableEnvelope();
+ const { pool, started } = withFailureAfter("declined", () =>
+ voidEnvelope(envelope),
+ );
+
+ await assert.rejects(declineEnvelope(envelope, pool), /The statement failed/);
+
+ assert.ok(started.rival, "the failing decline never wrote its status");
+ await started.rival;
+ await assertCertificatesKept(envelope, "voided");
+});
+
+test("a void that fails with nothing else ending the envelope removes the certificates it stored", async () => {
+ const envelope = await createSignableEnvelope();
+ const { pool } = withFailureAfter("voided", async () => undefined);
+
+ await assert.rejects(voidEnvelope(envelope, pool), /The statement failed/);
+
+ const row = await database.query<{ status: string }>(
+ `select status from envelopes where id = $1`,
+ [envelope.envelopeId],
+ );
+
+ assert.equal(row.rows[0]?.status, "sent");
+ assert.deepEqual(await certificatesStored(envelope), [false, false]);
+});
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index c71e34d..e6fce42 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import { type Branding } from "./branding.ts";
+import { removeUnclaimedEnvelopeCertificates } from "./certificate-cleanup.ts";
import {
type DbExecutor,
type DbPool,
@@ -2586,6 +2587,7 @@ export async function voidSentEnvelope(
voidedAuditEvent,
];
const storedCertificateKeys: string[] = [];
+ let failedAfterLock = false;
// The seal's key and the install's name, read before the transaction:
// sealing inside it then needs no second connection from the pool.
const seal = await loadInstallSealer();
@@ -2714,16 +2716,25 @@ export async function voidSentEnvelope(
tx,
);
} catch (error) {
- // Removed while the envelope is still locked, so these can only be the
- // files this call wrote.
- await Promise.all(
- storedCertificateKeys.map((key) =>
- storageService.deleteObject(key).catch(() => undefined),
- ),
- );
+ failedAfterLock = true;
throw error;
}
- }, database);
+ }, database).catch(async (error: unknown) => {
+ // Only once the envelope was this call's to end: before that, the files
+ // under these keys are not ones it stored.
+ if (failedAfterLock) {
+ await removeUnclaimedEnvelopeCertificates(
+ {
+ envelopeId: envelopeId,
+ keys: storedCertificateKeys,
+ storageService,
+ },
+ database,
+ );
+ }
+
+ throw error;
+ });
const branding = await getBranding().catch(() => null);
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index b82375c..63a41f8 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -2,6 +2,7 @@ import { Buffer } from "node:buffer";
import { randomUUID } from "node:crypto";
import { type Branding } from "./branding.ts";
+import { removeUnclaimedEnvelopeCertificates } from "./certificate-cleanup.ts";
import {
type DbExecutor,
type DbPool,
@@ -2940,6 +2941,7 @@ export async function declineSigningForToken(
declinedAuditEvent,
];
const storedCertificateKeys: string[] = [];
+ let failedAfterLock = false;
// The seal's key and the install's name, read before the transaction:
// sealing inside it then needs no second connection from the pool.
const seal = await loadInstallSealer();
@@ -3061,16 +3063,25 @@ export async function declineSigningForToken(
tx,
);
} catch (error) {
- // Removed while the envelope is still locked, so these can only be the
- // files this call wrote.
- await Promise.all(
- storedCertificateKeys.map((key) =>
- storageService.deleteObject(key).catch(() => undefined),
- ),
- );
+ failedAfterLock = true;
throw error;
}
- }, database);
+ }, database).catch(async (error: unknown) => {
+ // Only once the envelope was this call's to end: before that, the files
+ // under these keys are not ones it stored.
+ if (failedAfterLock) {
+ await removeUnclaimedEnvelopeCertificates(
+ {
+ envelopeId: context.envelope.id,
+ keys: storedCertificateKeys,
+ storageService,
+ },
+ database,
+ );
+ }
+
+ throw error;
+ });
try {
const delivery = await emailService.send(