Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Lock the account before listing the files its deletion removes
Claude873f7abfeddd
diff --git a/src/lib/retention.ts b/src/lib/retention.tsindex 1df9156..c5b9858 100644--- a/src/lib/retention.ts+++ b/src/lib/retention.ts@@ -3,6 +3,7 @@ import {getDb,queryMany,queryOne,+ withTransaction,} from "./db/connection.ts";import {buildEnvelopeThumbnailKey,@@ -436,17 +437,35 @@ export class AccountPurgeDeferredError extends Error {}}-async function purgeQueuedAccount(+function isPool(database: DbExecutor): database is ReturnType<typeof getDb> {+ return "connect" in database && "totalCount" in database;+}++/**+ * 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.+ *+ * 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,+ * and Postgres makes such a write wait for this lock. So a save that got in+ * first has finished and its file is in the list, and one that comes after+ * finds no account, fails, and takes its own file back. Without the lock a+ * save could land between the list and the delete: its row went with the+ * account and its file stayed, with nothing left that knew of it.+ */+async function deleteAccountRows(userId: string,database: DbExecutor,- storageService: StorageService,- env: EnvSource = process.env,-): Promise<boolean> {- if (- !isHostedMode(env) &&- !(await handOverFinishedEnvelopes(userId, database))- ) {- throw new AccountPurgeDeferredError(userId);+): Promise<string[] | null> {+ const account = await queryOne<{ id: string }>(+ database,+ `SELECT id FROM "user" WHERE id = $1 FOR UPDATE`,+ [userId],+ );++ if (!account) {+ return null;}const envelopes = await listEnvelopeArtifactsForUser(userId, database);@@ -477,7 +496,7 @@ async function purgeQueuedAccount(storageKeys.add(template.sourcePdfKey);}- const deleteResult = await database.query(+ await database.query(`DELETE FROM "user"WHERE id = $1@@ -485,11 +504,35 @@ async function purgeQueuedAccount([userId],);- if (deleteResult.rowCount !== 1) {+ return [...storageKeys];+}++async function purgeQueuedAccount(+ userId: string,+ database: DbExecutor,+ storageService: StorageService,+ env: EnvSource = process.env,+): Promise<boolean> {+ if (+ !isHostedMode(env) &&+ !(await handOverFinishedEnvelopes(userId, database))+ ) {+ throw new AccountPurgeDeferredError(userId);+ }++ // 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.+ const storageKeys = isPool(database)+ ? await withTransaction((tx) => deleteAccountRows(userId, tx), database)+ : await deleteAccountRows(userId, database);++ if (!storageKeys) {return false;}- await deleteStorageKeys([...storageKeys], storageService).catch((error) => {+ // Only once the rows are gone for good.+ await deleteStorageKeys(storageKeys, storageService).catch((error) => {console.error(`Failed to delete storage artifacts for purged account ${userId}:`,error,diff --git a/src/lib/templates.dbtest.ts b/src/lib/templates.dbtest.tsindex 934ee12..7966fa4 100644--- a/src/lib/templates.dbtest.ts+++ b/src/lib/templates.dbtest.ts@@ -155,6 +155,60 @@ 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));@@ -672,3 +726,65 @@ test("closing the account removes its templates and their documents", async () =0,);});++test("a template saved while its account is being deleted leaves no document behind", async () => {+ const userId = await createUser();+ const { envelopeId } = await createPreparedDraft(userId);++ 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],+ );++ // The save starts when the deletion has just read which templates the+ // account has, and the deletion then waits: for the save to finish, or+ // long enough to show that the save is the one waiting.+ let save: Promise<unknown> | undefined;+ const summary = await runRetentionSweep({+ database: afterStatement(+ database,+ (text, values) =>+ text.includes("FROM templates WHERE user_id") && values[0] === userId,+ async () => {+ save = saveEnvelopeAsTemplate(+ userId,+ envelopeId,+ { name: "Lease" },+ { database, storageService },+ );+ await Promise.race([+ save.catch(() => undefined),+ new Promise((resolve) => setTimeout(resolve, 500)),+ ]);+ },+ ),+ storageService,+ });++ assert.ok(!summary.accountPurgeFailures.includes(userId));+ assert.ok(save, "the deletion read the account's templates");++ const refusal: unknown = await save.then(+ () => null,+ (error: unknown) => error,+ );+ const keptDocuments = (+ await readdir(path.join(storageDir, "users", userId, "templates"), {+ recursive: true,+ }).catch(() => [])+ ).filter((entry) => entry.endsWith("original.pdf"));++ assert.deepEqual(keptDocuments, []);+ // The deletion went first, so the save found no account to keep a+ // template for, and took its copy of the document back.+ assert.match(String(refusal), /foreign key/);+ assert.equal(+ (await database.query(`select 1 from "user" where id = $1`, [userId]))+ .rowCount,+ 0,+ );+});