Skip to content

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

TypeScript

Delete a finished envelope's files only after its deletion commits

Claude5457ba873834
diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsx
index f15d3ed..806e6b1 100644
--- a/src/components/envelopes/envelope-detail-shell.tsx
+++ b/src/components/envelopes/envelope-detail-shell.tsx
@@ -440,6 +440,11 @@ export function EnvelopeDetailShell({
}
window.location.assign(payload?.redirectPath ?? "/dashboard");
+ } catch {
+ // The request may or may not have reached the server.
+ setActionError(
+ "Could not reach the server. Reload the page to see whether the envelope was deleted.",
+ );
} finally {
setIsDeletingFinished(false);
}
diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.ts
index 7d424bc..bcd95f6 100644
--- a/src/lib/envelope-deletion.dbtest.ts
+++ b/src/lib/envelope-deletion.dbtest.ts
@@ -294,25 +294,71 @@ test("a reason that is not text, or too long, is refused", async () => {
assert.equal(await envelopeExists(envelope.envelopeId), true);
});
-test("when a file cannot be deleted, nothing is deleted and nothing is recorded", async () => {
+test("when a file cannot be deleted, the envelope is still deleted and recorded, and the file is logged", async () => {
const admin = await createUser("admin");
const envelope = await createEnvelope(admin.userId, { status: "completed" });
- const before = await listSystemAuditEvents({ limit: 1 }, database);
const failingStorage = {
...storageService,
deleteObject: async () => {
throw new Error("Storage is down.");
},
} as StorageService;
+ const logged: unknown[][] = [];
+ const originalConsoleError = console.error;
+
+ console.error = (...args: unknown[]) => {
+ logged.push(args);
+ };
+
+ try {
+ await deleteFinishedEnvelope(
+ envelope.envelopeId,
+ { actor: admin },
+ { database, storageService: failingStorage },
+ );
+ } finally {
+ console.error = originalConsoleError;
+ }
+
+ assert.equal(await envelopeExists(envelope.envelopeId), false);
+
+ const [event] = await listSystemAuditEvents({ limit: 1 }, database);
+
+ assert.equal(event?.event, "envelope_deleted");
+ assert.equal(event?.metadata?.envelopeId, envelope.envelopeId);
+ // Every file it held is named in the log, so it can be removed by hand.
+ for (const key of envelope.stored) {
+ assert.ok(
+ logged.some((args) => String(args[0]).includes(key)),
+ `expected ${key} to be logged`,
+ );
+ }
+});
+
+test("when the deletion fails before it commits, no file is touched", async () => {
+ const admin = await createUser("admin");
+ const envelope = await createEnvelope(admin.userId, {
+ part11: true,
+ status: "completed",
+ });
+ let deletes = 0;
+ const countingStorage = {
+ ...storageService,
+ deleteObject: async (key: string) => {
+ deletes += 1;
+ return storageService.deleteObject(key);
+ },
+ } as StorageService;
await assert.rejects(
deleteFinishedEnvelope(
envelope.envelopeId,
{ actor: admin },
- { database, storageService: failingStorage },
+ { database, storageService: countingStorage },
),
- /Storage is down/,
+ rejectsWith(400),
);
+ assert.equal(deletes, 0);
assert.equal(await envelopeExists(envelope.envelopeId), true);
- assert.deepEqual(await listSystemAuditEvents({ limit: 1 }, database), before);
+ assert.ok((await filesExist(envelope.stored)).every(Boolean));
});
diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.ts
index 177f0d2..2cec3b0 100644
--- a/src/lib/envelope-deletion.ts
+++ b/src/lib/envelope-deletion.ts
@@ -5,7 +5,7 @@ import {
withTransaction,
} from "./db/connection.ts";
import { EnvelopeMutationError } from "./envelopes.ts";
-import { deleteEnvelopesAndFiles } from "./retention.ts";
+import { listEnvelopeStorageKeys } from "./retention.ts";
import {
createStorageService,
type StorageService,
@@ -84,12 +84,13 @@ export async function deleteFinishedEnvelope(
storageService?: StorageService;
} = {},
): Promise<{ deletedEnvelopeId: string }> {
- return withTransaction(async (tx) => {
- // The envelope row first, as everything that changes an envelope takes
- // it; the install's audit trail lock comes after.
- const envelope = await queryOne<FinishedEnvelopeRow>(
- tx,
- `
+ const { deletedEnvelopeId, storageKeys } = await withTransaction(
+ async (tx) => {
+ // The envelope row first, as everything that changes an envelope takes
+ // it; the install's audit trail lock comes after.
+ const envelope = await queryOne<FinishedEnvelopeRow>(
+ tx,
+ `
SELECT
id,
title,
@@ -103,74 +104,87 @@ export async function deleteFinishedEnvelope(
WHERE id = $1 AND user_id = $2
FOR UPDATE
`,
- [envelopeId, actor.userId],
- );
-
- if (!envelope) {
- throw new EnvelopeMutationError("Envelope not found.", 404);
- }
-
- if (!(FINISHED_STATUSES as readonly string[]).includes(envelope.status)) {
- throw new EnvelopeMutationError(
- envelope.status === "sent"
- ? "This envelope is still out for signature. Void it first."
- : "Only finished envelopes can be deleted this way.",
- 409,
+ [envelopeId, actor.userId],
);
- }
-
- // 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.",
- 403,
+ if (!envelope) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ if (!(FINISHED_STATUSES as readonly string[]).includes(envelope.status)) {
+ throw new EnvelopeMutationError(
+ envelope.status === "sent"
+ ? "This envelope is still out for signature. Void it first."
+ : "Only finished envelopes can be deleted this way.",
+ 409,
+ );
+ }
+
+ // 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],
);
- }
-
- const deletionReason = parseReason(reason, envelope.part11);
-
- await recordSystemAuditEvent(
- {
- actorEmail: actor.email,
- actorUserId: actor.userId,
- event: "envelope_deleted",
- ipAddress,
- metadata: {
- envelopeId: envelope.id,
- evidenceSha256: envelope.evidenceSha256,
- finishedAt: envelope.finishedAt,
- part11: envelope.part11,
- reason: deletionReason,
- signedPdfSha256: envelope.signedPdfSha256,
- sourcePdfHash: envelope.sourcePdfHash,
- status: envelope.status,
- title: envelope.title,
- },
- userAgent,
- },
- tx,
- );
- // Files first, then the row, all while the row is held: if a file
- // cannot be deleted, the whole deletion rolls back and can be tried
- // again.
- const deleted = await deleteEnvelopesAndFiles(
- [envelope.id],
- tx,
- storageService,
- );
+ if (actorRole?.role !== "admin") {
+ throw new EnvelopeMutationError(
+ "Only an administrator can delete a finished envelope.",
+ 403,
+ );
+ }
+
+ const deletionReason = parseReason(reason, envelope.part11);
+
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ event: "envelope_deleted",
+ ipAddress,
+ metadata: {
+ envelopeId: envelope.id,
+ evidenceSha256: envelope.evidenceSha256,
+ finishedAt: envelope.finishedAt,
+ part11: envelope.part11,
+ reason: deletionReason,
+ signedPdfSha256: envelope.signedPdfSha256,
+ sourcePdfHash: envelope.sourcePdfHash,
+ status: envelope.status,
+ title: envelope.title,
+ },
+ userAgent,
+ },
+ tx,
+ );
- if (deleted !== 1) {
- throw new EnvelopeMutationError("Envelope not found.", 404);
- }
+ // The row and the record of its deletion commit together. The files
+ // cannot roll back with them, so they go only after the commit: a file
+ // left behind by a failure is logged, never an envelope that lost its
+ // files without a record of why.
+ const storageKeys = await listEnvelopeStorageKeys(envelope.id, tx);
+ const deleted = await tx.query(`DELETE FROM envelopes WHERE id = $1`, [
+ envelope.id,
+ ]);
+
+ if (deleted.rowCount !== 1) {
+ throw new EnvelopeMutationError("Envelope not found.", 404);
+ }
+
+ return { deletedEnvelopeId: envelope.id, storageKeys };
+ },
+ database,
+ );
+
+ for (const key of storageKeys) {
+ await storageService.deleteObject(key).catch((error: unknown) => {
+ console.error(
+ `Failed to delete stored file ${key} of deleted envelope ${deletedEnvelopeId}:`,
+ error,
+ );
+ });
+ }
- return { deletedEnvelopeId: envelope.id };
- }, database);
+ return { deletedEnvelopeId };
}
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index 7a77457..a62e74b 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -901,17 +901,11 @@ async function applyRetentionPeriod(
}
}
-/** Deletes these envelopes and their stored files. Returns how many went. */
-export async function deleteEnvelopesAndFiles(
+async function listEnvelopeArtifacts(
envelopeIds: readonly string[],
- database: DbExecutor = getDb(),
- storageService: StorageService = createStorageService(),
-): Promise<number> {
- if (envelopeIds.length === 0) {
- return 0;
- }
-
- const envelopes = await queryMany<EnvelopeArtifactRow>(
+ database: DbExecutor,
+): Promise<EnvelopeArtifactRow[]> {
+ return queryMany<EnvelopeArtifactRow>(
database,
`
SELECT
@@ -927,6 +921,45 @@ export async function deleteEnvelopesAndFiles(
`,
[envelopeIds],
);
+}
+
+/**
+ * Every stored file of an envelope: its PDFs, certificates, first-page
+ * picture, drawn signatures and signing-provider revisions. Read it before
+ * the row goes, as the row is what names them.
+ */
+export async function listEnvelopeStorageKeys(
+ envelopeId: string,
+ database: DbExecutor,
+): Promise<string[]> {
+ const [envelope] = await listEnvelopeArtifacts([envelopeId], database);
+
+ if (!envelope) {
+ return [];
+ }
+
+ const fieldImagesByEnvelopeId = await listFieldImagesForEnvelopeIds(
+ [envelope.id],
+ database,
+ );
+
+ return buildEnvelopeStorageKeys(
+ envelope,
+ fieldImagesByEnvelopeId.get(envelope.id) ?? [],
+ );
+}
+
+/** Deletes these envelopes and their stored files. Returns how many went. */
+export async function deleteEnvelopesAndFiles(
+ envelopeIds: readonly string[],
+ database: DbExecutor = getDb(),
+ storageService: StorageService = createStorageService(),
+): Promise<number> {
+ if (envelopeIds.length === 0) {
+ return 0;
+ }
+
+ const envelopes = await listEnvelopeArtifacts(envelopeIds, database);
const fieldImagesByEnvelopeId = await listFieldImagesForEnvelopeIds(
envelopes.map((envelope) => envelope.id),
database,