Skip to content

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

TypeScript

Hand finished envelopes over inside the account's deleting transaction

Claude388b2b9ec7bf
diff --git a/src/lib/account-purge.dbtest.ts b/src/lib/account-purge.dbtest.ts
new file mode 100644
index 0000000..09ec324
--- /dev/null
+++ b/src/lib/account-purge.dbtest.ts
@@ -0,0 +1,276 @@
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, before, test } from "node:test";
+
+import type pg from "pg";
+
+import { afterStatement, openTestDatabase } from "./db/test-database.ts";
+import { runRetentionSweep } from "./retention.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+
+// Deleting a closed account against a real Postgres, timed against a signer
+// who finishes one of its envelopes at that moment. A signed record is the
+// organization's: it is handed to an administrator, never deleted with the
+// account. Run with `npm run test:db`.
+
+let database: pg.Pool;
+let storageDir: string;
+let storageService: StorageService;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-purge-"));
+ storageService = createStorageService({
+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },
+ });
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+ await rm(storageDir, { force: true, recursive: true });
+});
+
+async function createUser(role: "admin" | "user" = "user") {
+ const id = randomUUID();
+
+ createdUsers.push(id);
+ await database.query(
+ `
+ insert into public."user" (id, name, email, role, "emailVerified")
+ values ($1, $2, $3, $4, true)
+ `,
+ [id, `Person ${id.slice(0, 4)}`, `${id}@example.test`, role],
+ );
+
+ return id;
+}
+
+/** An envelope of this account that is out for signature, with its document. */
+async function createSentEnvelope(userId: string) {
+ const id = randomUUID();
+ const sourcePdfKey = `test/${id}.pdf`;
+
+ await storageService.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key: sourcePdfKey,
+ });
+ await database.query(
+ `
+ insert into envelopes (
+ id, user_id, title, status, source_pdf_key, source_pdf_filename,
+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at
+ ) values ($1, $2, 'Lease', 'sent', $3, 'lease.pdf', 4, 1, $4, 1)
+ `,
+ [id, userId, sourcePdfKey, "a".repeat(64)],
+ );
+
+ return { id, sourcePdfKey };
+}
+
+/** Asks for the account to be closed, with its notice already over. */
+async function closeAccount(userId: string) {
+ await database.query(
+ `
+ insert into account_closure_requests
+ (user_id, requested_at, export_expires_at, purge_after_at, updated_at)
+ values ($1, 1, 1, 1, 1)
+ `,
+ [userId],
+ );
+}
+
+/** What the last signer's signature does to the envelope. */
+function complete(envelopeId: string) {
+ return database.query(
+ `
+ update envelopes
+ set status = 'completed', completed_at = 2
+ where id = $1 and status = 'sent'
+ `,
+ [envelopeId],
+ );
+}
+
+/** Resolves once another session is held up behind a lock. */
+async function waitForLockWaiter() {
+ for (let attempt = 0; attempt < 300; attempt += 1) {
+ const result = await database.query(
+ `
+ select 1
+ from pg_stat_activity
+ where datname = current_database() and wait_event_type = 'Lock'
+ limit 1
+ `,
+ );
+
+ if (result.rowCount) {
+ return;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+}
+
+async function envelopeRow(envelopeId: string) {
+ const result = await database.query<{
+ handed_over_at: number | null;
+ status: string;
+ user_id: string;
+ }>(`select user_id, status, handed_over_at from envelopes where id = $1`, [
+ envelopeId,
+ ]);
+
+ return result.rows[0] ?? null;
+}
+
+async function accountExists(userId: string) {
+ const result = await database.query(
+ `select 1 from public."user" where id = $1`,
+ [userId],
+ );
+
+ return result.rowCount === 1;
+}
+
+test("an envelope completed while its sender's account is being deleted goes to an administrator", async () => {
+ await createUser("admin");
+
+ const leaver = await createUser();
+ const envelope = await createSentEnvelope(leaver);
+
+ await closeAccount(leaver);
+
+ // The last signature lands just after the deletion has taken hold of the
+ // account.
+ const summary = await runRetentionSweep({
+ database: afterStatement(
+ database,
+ (text, values) =>
+ text.includes(`FROM "user" WHERE id = $1 FOR UPDATE`) &&
+ values[0] === leaver,
+ async () => {
+ assert.equal((await complete(envelope.id)).rowCount, 1);
+ },
+ ),
+ storageService,
+ });
+
+ assert.ok(!summary.accountPurgeFailures.includes(leaver));
+ assert.equal(await accountExists(leaver), false);
+
+ // The signed record outlives the account, with its document.
+ const kept = await envelopeRow(envelope.id);
+
+ assert.ok(kept, "the completed envelope was deleted with the account");
+ assert.equal(kept.status, "completed");
+ assert.notEqual(kept.user_id, leaver);
+ assert.ok(kept.handed_over_at);
+ assert.equal(
+ (await storageService.headObject(envelope.sourcePdfKey)).exists,
+ true,
+ );
+});
+
+test("once the finished envelopes are handed over, no other envelope of the account can be completed", async () => {
+ await createUser("admin");
+
+ const leaver = await createUser();
+ const envelope = await createSentEnvelope(leaver);
+ let signature: Promise<pg.QueryResult> | undefined;
+
+ await closeAccount(leaver);
+
+ // The last signature arrives right after the deletion has looked for
+ // finished envelopes and found none. It has to wait for the deletion.
+ const summary = await runRetentionSweep({
+ database: afterStatement(
+ database,
+ (text, values) =>
+ text.includes("SELECT count(*)::text AS count") &&
+ text.includes("FROM envelopes") &&
+ values[0] === leaver,
+ async () => {
+ signature = complete(envelope.id);
+ await Promise.race([
+ signature.then(
+ () => undefined,
+ () => undefined,
+ ),
+ waitForLockWaiter(),
+ ]);
+ },
+ ),
+ storageService,
+ });
+
+ assert.ok(signature, "the deletion never looked for finished envelopes");
+ assert.ok(!summary.accountPurgeFailures.includes(leaver));
+ assert.equal(await accountExists(leaver), false);
+
+ // It found no envelope left to complete. Had it completed one, that
+ // record would have to be here still.
+ const completed = (await signature).rowCount === 1;
+
+ assert.equal(completed, false);
+ assert.equal(await envelopeRow(envelope.id), null);
+ assert.equal(
+ (await storageService.headObject(envelope.sourcePdfKey)).exists,
+ false,
+ );
+});
+
+test("with no administrator to take it, an envelope completed during the deletion keeps its account", async () => {
+ // No administrator is left for the length of this test.
+ const administrators = await database.query<{ id: string }>(
+ `update public."user" set role = 'user' where role = 'admin' returning id`,
+ );
+
+ try {
+ const leaver = await createUser();
+ const envelope = await createSentEnvelope(leaver);
+
+ await closeAccount(leaver);
+
+ const summary = await runRetentionSweep({
+ database: afterStatement(
+ database,
+ (text, values) =>
+ text.includes(`FROM "user" WHERE id = $1 FOR UPDATE`) &&
+ values[0] === leaver,
+ async () => {
+ assert.equal((await complete(envelope.id)).rowCount, 1);
+ },
+ ),
+ storageService,
+ });
+
+ // Nothing is deleted. The next run tries again.
+ assert.ok(summary.accountPurgeFailures.includes(leaver));
+ assert.equal(await accountExists(leaver), true);
+ assert.deepEqual(await envelopeRow(envelope.id), {
+ handed_over_at: null,
+ status: "completed",
+ user_id: leaver,
+ });
+ assert.equal(
+ (await storageService.headObject(envelope.sourcePdfKey)).exists,
+ true,
+ );
+ } finally {
+ await database.query(
+ `update public."user" set role = 'admin' where id = any($1)`,
+ [administrators.rows.map((row) => row.id)],
+ );
+ }
+});
diff --git a/src/lib/db/test-database.ts b/src/lib/db/test-database.ts
index 66afff1..15d65af 100644
--- a/src/lib/db/test-database.ts
+++ b/src/lib/db/test-database.ts
@@ -60,6 +60,60 @@ export async function openTestDatabase(): Promise<pg.Pool> {
return new pg.Pool({ connectionString, max: 12 });
}
+type QueryFunction = (text: unknown, values?: unknown[]) => unknown;
+
+/**
+ * The same database, except that `then` runs right after one chosen
+ * statement has, whether it went to the pool or to a client taken from it.
+ */
+export function afterStatement(
+ pool: pg.Pool,
+ isTheStatement: (text: string, values: unknown[]) => boolean,
+ then: () => Promise<void>,
+): pg.Pool {
+ function intercept<T extends object>(target: T): T {
+ return new Proxy(target, {
+ get(object, property) {
+ const value: unknown = Reflect.get(object, property);
+
+ if (property === "query") {
+ const query: QueryFunction = async (text, values) => {
+ const result = await (value as QueryFunction).call(
+ object,
+ text,
+ values,
+ );
+
+ if (
+ typeof text === "string" &&
+ isTheStatement(text, values ?? [])
+ ) {
+ await then();
+ }
+
+ return result;
+ };
+
+ return query;
+ }
+
+ if (property === "connect") {
+ return async () =>
+ intercept(
+ await (value as () => Promise<pg.PoolClient>).call(object),
+ );
+ }
+
+ return typeof value === "function"
+ ? (value.bind(object) as unknown)
+ : value;
+ },
+ });
+ }
+
+ return intercept(pool);
+}
+
/**
* Records an audit event the way a signer opening the signing page does,
* timed against something else that writes to the same envelope: the
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index 0bc37f5..eafd294 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -435,7 +435,9 @@ function isPool(database: DbExecutor): database is ReturnType<typeof getDb> {
/**
* Deletes the account with everything that hangs on it, and returns the
* files those rows pointed at. Returns null when the account is already
- * gone.
+ * gone. With `keepFinishedEnvelopes`, finished envelopes are handed to an
+ * administrator first, and the account stays (AccountPurgeDeferredError)
+ * when there is none to take them.
*
* The account's row is locked before the files are listed. Saving a
* template or uploading a document writes a row that points at the account,
@@ -447,6 +449,8 @@ function isPool(database: DbExecutor): database is ReturnType<typeof getDb> {
*/
async function deleteAccountRows(
userId: string,
+ now: number,
+ keepFinishedEnvelopes: boolean,
database: DbExecutor,
): Promise<string[] | null> {
const account = await queryOne<{ id: string }>(
@@ -459,6 +463,28 @@ async function deleteAccountRows(
return null;
}
+ if (keepFinishedEnvelopes) {
+ // The account's envelopes are locked before the finished ones are
+ // handed over, and stay locked until the account is gone. Signing,
+ // declining and voiding all change the envelope's row, so one that got
+ // in first has finished and its envelope is handed over here, and one
+ // that comes after waits and then finds no envelope. Without the lock
+ // an envelope could be completed between the hand-over and the delete,
+ // and its signed record would go with the account.
+ //
+ // The lock an UPDATE takes, not FOR UPDATE: a signer's audit event
+ // needs a share of this row for its foreign key, and FOR UPDATE would
+ // make it wait.
+ await database.query(
+ `SELECT id FROM envelopes WHERE user_id = $1 FOR NO KEY UPDATE`,
+ [userId],
+ );
+
+ if (!(await handOverFinishedEnvelopes(userId, now, database))) {
+ throw new AccountPurgeDeferredError(userId);
+ }
+ }
+
const envelopes = await listEnvelopeArtifactsForUser(userId, database);
const fieldImagesByEnvelopeId = await listFieldImagesForEnvelopeIds(
envelopes.map((envelope) => envelope.id),
@@ -505,19 +531,19 @@ async function purgeQueuedAccount(
storageService: StorageService,
env: EnvSource = process.env,
): Promise<boolean> {
- if (
- !isHostedMode(env) &&
- !(await handOverFinishedEnvelopes(userId, now, database))
- ) {
- throw new AccountPurgeDeferredError(userId);
- }
+ // On a self-hosted install the finished envelopes stay with the
+ // organization. Hosted mode keeps nothing of a closed account.
+ const keepFinishedEnvelopes = !isHostedMode(env);
- // One transaction, so the lock on the account holds from the list of its
- // files to the delete. A caller that hands in its own connection decides
- // where its transaction ends.
+ // One transaction, so the locks on the account and its envelopes hold
+ // from the hand-over and the list of its files to the delete. A caller
+ // that hands in its own connection decides where its transaction ends.
const storageKeys = isPool(database)
- ? await withTransaction((tx) => deleteAccountRows(userId, tx), database)
- : await deleteAccountRows(userId, database);
+ ? await withTransaction(
+ (tx) => deleteAccountRows(userId, now, keepFinishedEnvelopes, tx),
+ database,
+ )
+ : await deleteAccountRows(userId, now, keepFinishedEnvelopes, database);
if (!storageKeys) {
return false;
diff --git a/src/lib/templates.dbtest.ts b/src/lib/templates.dbtest.ts
index 7966fa4..ba0b29f 100644
--- a/src/lib/templates.dbtest.ts
+++ b/src/lib/templates.dbtest.ts
@@ -9,7 +9,7 @@ import { PDFDocument } from "pdf-lib";
import type pg from "pg";
import { ZodError } from "zod";
-import { openTestDatabase } from "./db/test-database.ts";
+import { afterStatement, openTestDatabase } from "./db/test-database.ts";
import {
createDraftEnvelope,
EnvelopeMutationError,
@@ -155,60 +155,6 @@ async function countEnvelopes(userId: string): Promise<number> {
return result.rows[0]!.total;
}
-type QueryFunction = (text: unknown, values?: unknown[]) => unknown;
-
-/**
- * The same database, except that `then` runs right after one chosen
- * statement has, whether it went to the pool or to a client taken from it.
- */
-function afterStatement(
- pool: pg.Pool,
- isTheStatement: (text: string, values: unknown[]) => boolean,
- then: () => Promise<void>,
-): pg.Pool {
- function intercept<T extends object>(target: T): T {
- return new Proxy(target, {
- get(object, property) {
- const value: unknown = Reflect.get(object, property);
-
- if (property === "query") {
- const query: QueryFunction = async (text, values) => {
- const result = await (value as QueryFunction).call(
- object,
- text,
- values,
- );
-
- if (
- typeof text === "string" &&
- isTheStatement(text, values ?? [])
- ) {
- await then();
- }
-
- return result;
- };
-
- return query;
- }
-
- if (property === "connect") {
- return async () =>
- intercept(
- await (value as () => Promise<pg.PoolClient>).call(object),
- );
- }
-
- return typeof value === "function"
- ? (value.bind(object) as unknown)
- : value;
- },
- });
- }
-
- return intercept(pool);
-}
-
function assertTemplateError(statusCode: number) {
return (error: unknown): true => {
assert.ok(error instanceof TemplateError, String(error));