Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Look at the keeper again before a closed account's records move
Claudeb0281e7b355b
diff --git a/src/lib/people.dbtest.ts b/src/lib/people.dbtest.tsindex 216c1d2..4ce56ce 100644--- a/src/lib/people.dbtest.ts+++ b/src/lib/people.dbtest.ts@@ -1,21 +1,28 @@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 { openTestDatabase } from "./db/test-database.ts";import { listPeople, PeopleError, setPersonRole } from "./people.ts";+import { runRetentionSweep } from "./retention.ts";+import { createStorageService } from "./services/storage.ts";// Administrator roles against a real Postgres: there is always at least// one, even when two removals arrive at once. Run with `npm run test:db`.let database: pg.Pool;+let storageDir: string;const createdUsers: string[] = [];let administratorsBefore: string[] = [];before(async () => {database = await openTestDatabase();+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-people-"));// The rule under test is about every administrator in the database, so// the ones other tests left behind step aside while this file runs.@@ -35,6 +42,7 @@ after(async () => {[administratorsBefore],);await database.end();+ await rm(storageDir, { force: true, recursive: true });});async function createUser({@@ -206,6 +214,75 @@ test("a request already under way does not outlive its administrator's role", asassert.equal(await roleOf(staying), "admin");});+test("a closed account's records do not go to someone whose role is being taken away", async () => {+ await resetRoles();++ // The older of the two administrators is the one a closed account's+ // finished envelopes are handed to.+ const removed = await createUser({ role: "admin" });+ const staying = await createUser({ role: "admin" });+ const leaver = await createUser();+ const envelopeId = randomUUID();++ await database.query(+ `update public."user" set "createdAt" = now() - interval '1 day' where id = $1`,+ [removed],+ );+ 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, completed_at+ ) values ($1, $2, 'Lease', 'completed', $3, 'lease.pdf', 10, 1, $4, 1)+ `,+ [envelopeId, leaver, `test/${envelopeId}.pdf`, "a".repeat(64)],+ );+ 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)+ `,+ [leaver],+ );++ const holder = await database.connect();++ try {+ // A removal that is under way and has not been committed yet, so the+ // hand-over still finds an administrator when it chooses.+ await holder.query("begin");+ await holder.query(`update public."user" set role = 'user' where id = $1`, [+ removed,+ ]);++ const sweep = runRetentionSweep({+ database,+ storageService: createStorageService({+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },+ }),+ });++ sweep.catch(() => undefined);+ // The hand-over waits for the removal instead of going ahead of it.+ await waitForLockWaiters(1);+ await holder.query("commit");++ assert.ok(!(await sweep).accountPurgeFailures.includes(leaver));+ } finally {+ await holder.query("rollback").catch(() => undefined);+ holder.release();+ }++ const owner = await database.query<{ user_id: string }>(+ `select user_id from envelopes where id = $1`,+ [envelopeId],+ );++ assert.equal(owner.rows[0]?.user_id, staying);+ assert.equal(await roleOf(leaver), null);+});+test("an administrator whose account is closing does not count as the one that stays", async () => {await resetRoles();diff --git a/src/lib/retention.ts b/src/lib/retention.tsindex 92cc268..1df9156 100644--- a/src/lib/retention.ts+++ b/src/lib/retention.ts@@ -338,6 +338,8 @@ export async function scheduleAccountClosure(}const FINISHED_ENVELOPE_STATUSES = ["completed", "declined", "voided"];+/** How many keepers in a row may lose the role before the next run takes over. */+const MAX_KEEPER_ATTEMPTS = 5;/*** On a self-hosted install the organization owns its signed records, so a@@ -345,59 +347,84 @@ const FINISHED_ENVELOPE_STATUSES = ["completed", "declined", "voided"];* administrator before the* account is deleted. Only an administrator may receive them: anyone else* would gain documents they were never party to. Returns false when there- * is no administrator to keep them.+ * is no administrator to keep them, which leaves the account for the next+ * run.*/async function handOverFinishedEnvelopes(userId: string,database: DbExecutor,): Promise<boolean> {- const finished = await queryOne<{ count: string }>(- database,- `- SELECT count(*)::text AS count- FROM envelopes- WHERE user_id = $1 AND status = ANY($2::text[])- `,- [userId, FINISHED_ENVELOPE_STATUSES],- );+ for (let attempt = 0; attempt < MAX_KEEPER_ATTEMPTS; attempt += 1) {+ const finished = await queryOne<{ count: string }>(+ database,+ `+ SELECT count(*)::text AS count+ FROM envelopes+ WHERE user_id = $1 AND status = ANY($2::text[])+ `,+ [userId, FINISHED_ENVELOPE_STATUSES],+ );- if (Number(finished?.count ?? 0) === 0) {- return true;- }+ if (Number(finished?.count ?? 0) === 0) {+ return true;+ }- const keeper = await queryOne<{ id: string }>(- database,- `- SELECT u.id- FROM "user" u- WHERE u.id <> $1- AND u.role = 'admin'- AND NOT EXISTS (- SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id- )- ORDER BY u."createdAt" ASC, u.id ASC- LIMIT 1- `,- [userId],- );+ const keeper = await queryOne<{ id: string }>(+ database,+ `+ SELECT u.id+ FROM "user" u+ WHERE u.id <> $1+ AND u.role = 'admin'+ AND NOT EXISTS (+ SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id+ )+ ORDER BY u."createdAt" ASC, u.id ASC+ LIMIT 1+ `,+ [userId],+ );- if (!keeper) {- return false;- }+ if (!keeper) {+ return false;+ }- await database.query(- `- UPDATE envelopes- SET user_id = $1- WHERE user_id = $2 AND status = ANY($3::text[])- `,- [keeper.id, userId, FINISHED_ENVELOPE_STATUSES],- );- console.info(- `Moved finished envelopes from closed account ${userId} to ${keeper.id}.`,- );+ // The keeper was an administrator when chosen, but that role can be+ // taken away at any moment. So the move looks at the keeper again while+ // it holds their row: a removal already under way finishes first and is+ // seen here, and one that starts now waits until the records have+ // moved. Nothing moves to someone who is no longer an administrator.+ const moved = await database.query(+ `+ UPDATE envelopes e+ SET user_id = k.id+ FROM (+ SELECT u.id+ FROM "user" u+ WHERE u.id = $1+ AND u.role = 'admin'+ AND NOT EXISTS (+ SELECT 1 FROM account_closure_requests c WHERE c.user_id = u.id+ )+ FOR SHARE OF u+ ) k+ WHERE e.user_id = $2 AND e.status = ANY($3::text[])+ `,+ [keeper.id, userId, FINISHED_ENVELOPE_STATUSES],+ );- return true;+ if ((moved.rowCount ?? 0) > 0) {+ console.info(+ `Moved finished envelopes from closed account ${userId} to ${keeper.id}.`,+ );++ return true;+ }++ // The keeper stopped being one in between. Look for another.+ }++ return false;}export class AccountPurgeDeferredError extends Error {