From ba203fa06179c87d89090366b1084052c1306036 Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Thu, 15 Oct 2026 16:27:27 -0400 Subject: [PATCH 1/5] feat(store): make every delete a soft delete Deletes of users, projects, donors, donations, expenditures and reports now stamp a nullable deleted_at instead of removing the row. A project stamps its donations, expenditures and reports with the same time; a donor stamps its donations. Memberships and both rollups are still hard-deleted, and a user delete still clears expenditures.entered_by, so every read returns exactly what it did before. - Every read of the six tables filters deleted_at IS NULL (left joins in the ON clause). A static guard test fails a read that forgets. - The store's Kysely strips deleted_at from every result row. - Inserts under a soft-deleted parent throw 23503, as the FK did. - Drop UNIQUE(donor_id, project_id): a donor can give to a project more than once. Drop UNIQUE(email): a deleted user keeps the email, and Cognito still enforces uniqueness among live accounts. - S3 objects are kept on delete; the Cognito user is still deleted. - Per-lambda parity tests: soft-delete, snapshot every GET, purge the soft-deleted rows, snapshot again, expect identical responses. Co-Authored-By: Claude Opus 5.5 --- apps/backend/AGENTS.md | 3 +- .../V20261015195651__add_users_deleted_at.sql | 21 ++ ...0261015195652__add_projects_deleted_at.sql | 21 ++ ...V20261015195654__add_donors_deleted_at.sql | 21 ++ ...5656__add_project_donations_deleted_at.sql | 21 ++ ...015195658__add_expenditures_deleted_at.sql | 21 ++ ...20261015195700__add_reports_deleted_at.sql | 21 ++ ...project_donations_donor_project_unique.sql | 22 ++ ...0261015195703__drop_users_email_unique.sql | 22 ++ apps/backend/db/testkit.ts | 28 +- apps/backend/lambdas/auth/controllers/mfa.ts | 1 + .../lambdas/auth/controllers/register.ts | 1 + .../lambdas/donors/controllers/donations.ts | 16 +- .../lambdas/donors/controllers/donors.ts | 9 +- .../lambdas/donors/test/donors.test.ts | 22 +- .../test/soft-delete-parity.e2e.test.ts | 113 ++++++++ .../expenditures/controllers/expenditures.ts | 7 +- .../expenditures/services/expenditures.ts | 61 ++-- .../test/expenditures.e2e.test.ts | 47 +++- .../test/expenditures.unit.test.ts | 264 +++++------------- .../test/soft-delete-parity.e2e.test.ts | 121 ++++++++ .../lambdas/projects/controllers/dashboard.ts | 11 +- .../lambdas/projects/controllers/donors.ts | 4 + .../projects/controllers/expenditures.ts | 2 + .../lambdas/projects/controllers/members.ts | 1 + .../lambdas/projects/controllers/projects.ts | 19 +- .../lambdas/projects/services/projects.ts | 75 +---- .../projects/test/delete-objects.unit.test.ts | 115 +------- .../projects/test/rollup-store.e2e.test.ts | 29 +- .../lambdas/projects/test/rollups.e2e.test.ts | 29 +- .../test/soft-delete-parity.e2e.test.ts | 114 ++++++++ .../lambdas/reports/controllers/reports.ts | 55 +--- .../backend/lambdas/reports/report-service.ts | 11 +- .../lambdas/reports/test/reports.e2e.test.ts | 35 ++- .../lambdas/reports/test/reports.unit.test.ts | 202 +++----------- .../test/soft-delete-parity.e2e.test.ts | 132 +++++++++ .../lambdas/users/controllers/users.ts | 15 +- .../users/test/soft-delete-parity.e2e.test.ts | 125 +++++++++ .../users/test/user.photos.unit.test.ts | 12 +- .../lambdas/users/test/user.unit.test.ts | 3 + apps/backend/lambdas/users/test/users.test.ts | 42 ++- apps/frontend/AGENTS.md | 2 +- .../app/components/ConfirmDeleteDialog.tsx | 6 +- .../src/app/projects/ProjectDetailView.tsx | 12 +- apps/frontend/src/app/reports/page.tsx | 2 +- shared/lambda-auth/src/authenticate.ts | 1 + shared/lambda-auth/test/authenticate.test.ts | 11 +- shared/store/src/connection.ts | 24 +- shared/store/src/donations.ts | 32 ++- shared/store/src/expenditures.ts | 10 +- shared/store/src/live.ts | 46 +++ shared/store/src/projects.ts | 27 +- shared/store/src/reports.ts | 9 +- shared/store/src/users.ts | 27 +- shared/store/test/soft-delete-guard.test.ts | 109 ++++++++ shared/types/db-types.d.ts | 6 + 56 files changed, 1504 insertions(+), 714 deletions(-) create mode 100644 apps/backend/db/migrations/V20261015195651__add_users_deleted_at.sql create mode 100644 apps/backend/db/migrations/V20261015195652__add_projects_deleted_at.sql create mode 100644 apps/backend/db/migrations/V20261015195654__add_donors_deleted_at.sql create mode 100644 apps/backend/db/migrations/V20261015195656__add_project_donations_deleted_at.sql create mode 100644 apps/backend/db/migrations/V20261015195658__add_expenditures_deleted_at.sql create mode 100644 apps/backend/db/migrations/V20261015195700__add_reports_deleted_at.sql create mode 100644 apps/backend/db/migrations/V20261015195702__drop_project_donations_donor_project_unique.sql create mode 100644 apps/backend/db/migrations/V20261015195703__drop_users_email_unique.sql create mode 100644 apps/backend/lambdas/donors/test/soft-delete-parity.e2e.test.ts create mode 100644 apps/backend/lambdas/expenditures/test/soft-delete-parity.e2e.test.ts create mode 100644 apps/backend/lambdas/projects/test/soft-delete-parity.e2e.test.ts create mode 100644 apps/backend/lambdas/reports/test/soft-delete-parity.e2e.test.ts create mode 100644 apps/backend/lambdas/users/test/soft-delete-parity.e2e.test.ts create mode 100644 shared/store/src/live.ts create mode 100644 shared/store/test/soft-delete-guard.test.ts diff --git a/apps/backend/AGENTS.md b/apps/backend/AGENTS.md index 367974e7..d3ace0c8 100644 --- a/apps/backend/AGENTS.md +++ b/apps/backend/AGENTS.md @@ -47,6 +47,7 @@ http://localhost:3000//health - **Analytics reads go through the rollups, never the base tables.** `expenditure_rollup` (grain: project × month × category × status) and `project_rollup` (per project: member/donation/report counts and `total_donated`) are maintained by `@branch/store` in the same transaction as the write, so they are exact rather than eventually consistent. Spend lives **only** in `expenditure_rollup`. Increments upsert; decrements are a plain `UPDATE`, and emptied buckets stay at zero. Time-relative figures (the active-project count, "spend on active projects") cannot be rolled up and still read `projects` live. - **`@branch/store` (`shared/store`) is the only connection and the only writer.** It exports `db` (a read-only `Kysely`) and one named operation per write, each of which maintains the rollups. Env `DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME`; a DSQL `DB_HOST` switches it to IAM-token auth with no password. Query with the `branch.` schema prefix: `db.selectFrom('branch.users')`. - **Changing the schema:** `make new-migration NAME=add_thing` → write SQL → `make migrate` (applies it and regenerates `shared/types/db-types.d.ts`). `make show-migrations` shows applied vs pending; the ledger is `branch.flyway_schema_history`. Forward-only — never edit a merged migration, and never hand-edit `db-types.d.ts`. Migrations apply to prod automatically on merge **before** the lambda deploy, so a single PR may only contain additive changes; see `db/README.md` for expand/contract. +- **Deletes are soft.** `users`, `projects`, `donors`, `project_donations`, `expenditures` and `reports` carry a nullable `deleted_at`; every `remove*` in `@branch/store` stamps it instead of deleting (a project stamps its donations, expenditures and reports with the same time; a donor its donations). `project_memberships` and both rollups are still hard-deleted, so the rollups only ever count live rows, and a user delete still clears `expenditures.entered_by` as `ON DELETE SET NULL` did. **Every read of those six tables filters `deleted_at IS NULL`** — on a `leftJoin`, in the `ON` clause, so the parent row survives with null joined fields — and `shared/store/test/soft-delete-guard.test.ts` fails a query that forgets; each lambda's `soft-delete-parity.e2e.test.ts` proves its GETs read a soft-deleted row exactly like an absent one. The store's Kysely strips `deleted_at` from every result row, so responses never carry it. Inserts under a soft-deleted parent throw a `23503`, as the FK did. S3 objects and the row stay; the Cognito user is still deleted. There is no restore endpoint — recover by SQL (clear `deleted_at` on the row and its same-timestamp children, then rebuild the rollups). - The migration runner is Flyway over plain `.sql` files, configured once in `db/flyway.sh`; `db/src/` holds seeding, the schema rebuild and type generation. Root `package.json` still carries NestJS/TypeORM **dependencies** from the original scaffold, but nothing uses them; its dead `migration:*` scripts have been removed. ## Shared packages @@ -67,7 +68,7 @@ Automatic on push to `main` touching `apps/backend/lambdas/**` or `shared/types/ ## Env vars (lambdas) -`DB_HOST DB_PORT DB_USER DB_PASSWORD DB_NAME`, `COGNITO_USER_POOL_ID`, `COGNITO_CLIENT_ID` (or `COGNITO_APP_CLIENT_ID`), `REPORTS_BUCKET_NAME` (reports, expenditures and projects — one bucket holds both the `reports/` and `receipts/` prefixes, and all three delete out of it), `AWS_REGION` (default `us-east-2`, Lambda-reserved — never set it in Terraform). +`DB_HOST DB_PORT DB_USER DB_PASSWORD DB_NAME`, `COGNITO_USER_POOL_ID`, `COGNITO_CLIENT_ID` (or `COGNITO_APP_CLIENT_ID`), `REPORTS_BUCKET_NAME` (reports, expenditures and projects — one bucket holds both the `reports/` and `receipts/` prefixes; deletes leave the objects in place, see soft deletes below), `AWS_REGION` (default `us-east-2`, Lambda-reserved — never set it in Terraform). **Anything a lambda reads from `process.env` must be declared in the `environment` block of `infrastructure/aws/lambda.tf`.** That block is authoritative and is deliberately not in `lifecycle.ignore_changes`, so a value set by hand in the console is deleted on the next apply. Locally the Cognito values must be the real shared dev-pool IDs (`apps/backend/.env`) — auth talks to the real pool for JWKS and `InitiateAuth` — but no AWS credentials are needed, because every Cognito API on the sign-in path is unsigned. diff --git a/apps/backend/db/migrations/V20261015195651__add_users_deleted_at.sql b/apps/backend/db/migrations/V20261015195651__add_users_deleted_at.sql new file mode 100644 index 00000000..e16862c4 --- /dev/null +++ b/apps/backend/db/migrations/V20261015195651__add_users_deleted_at.sql @@ -0,0 +1,21 @@ +-- V20261015195651__add_users_deleted_at +-- +-- Flyway runs this file inside a SINGLE transaction, with search_path = +-- branch, public -- so table names can be unqualified. +-- +-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its +-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE, +-- and at most 3,000 rows changed. CI lints this file with dsql-lint. +-- +-- This migration is applied to PRODUCTION automatically when the PR merges, +-- BEFORE the new lambda code is deployed. It must be safe for the code that is +-- live right now: additive changes only. See apps/backend/db/README.md for the +-- expand/contract rules that destructive changes need. +-- +-- Forward-only: there is no rollback. Fix a mistake with a new migration, and +-- never edit a migration that has been merged -- Flyway checksums it, and +-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not +-- silent drift. + + +ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP; diff --git a/apps/backend/db/migrations/V20261015195652__add_projects_deleted_at.sql b/apps/backend/db/migrations/V20261015195652__add_projects_deleted_at.sql new file mode 100644 index 00000000..c826a4fa --- /dev/null +++ b/apps/backend/db/migrations/V20261015195652__add_projects_deleted_at.sql @@ -0,0 +1,21 @@ +-- V20261015195652__add_projects_deleted_at +-- +-- Flyway runs this file inside a SINGLE transaction, with search_path = +-- branch, public -- so table names can be unqualified. +-- +-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its +-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE, +-- and at most 3,000 rows changed. CI lints this file with dsql-lint. +-- +-- This migration is applied to PRODUCTION automatically when the PR merges, +-- BEFORE the new lambda code is deployed. It must be safe for the code that is +-- live right now: additive changes only. See apps/backend/db/README.md for the +-- expand/contract rules that destructive changes need. +-- +-- Forward-only: there is no rollback. Fix a mistake with a new migration, and +-- never edit a migration that has been merged -- Flyway checksums it, and +-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not +-- silent drift. + + +ALTER TABLE projects ADD COLUMN deleted_at TIMESTAMP; diff --git a/apps/backend/db/migrations/V20261015195654__add_donors_deleted_at.sql b/apps/backend/db/migrations/V20261015195654__add_donors_deleted_at.sql new file mode 100644 index 00000000..a4ed9827 --- /dev/null +++ b/apps/backend/db/migrations/V20261015195654__add_donors_deleted_at.sql @@ -0,0 +1,21 @@ +-- V20261015195654__add_donors_deleted_at +-- +-- Flyway runs this file inside a SINGLE transaction, with search_path = +-- branch, public -- so table names can be unqualified. +-- +-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its +-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE, +-- and at most 3,000 rows changed. CI lints this file with dsql-lint. +-- +-- This migration is applied to PRODUCTION automatically when the PR merges, +-- BEFORE the new lambda code is deployed. It must be safe for the code that is +-- live right now: additive changes only. See apps/backend/db/README.md for the +-- expand/contract rules that destructive changes need. +-- +-- Forward-only: there is no rollback. Fix a mistake with a new migration, and +-- never edit a migration that has been merged -- Flyway checksums it, and +-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not +-- silent drift. + + +ALTER TABLE donors ADD COLUMN deleted_at TIMESTAMP; diff --git a/apps/backend/db/migrations/V20261015195656__add_project_donations_deleted_at.sql b/apps/backend/db/migrations/V20261015195656__add_project_donations_deleted_at.sql new file mode 100644 index 00000000..5f390397 --- /dev/null +++ b/apps/backend/db/migrations/V20261015195656__add_project_donations_deleted_at.sql @@ -0,0 +1,21 @@ +-- V20261015195656__add_project_donations_deleted_at +-- +-- Flyway runs this file inside a SINGLE transaction, with search_path = +-- branch, public -- so table names can be unqualified. +-- +-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its +-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE, +-- and at most 3,000 rows changed. CI lints this file with dsql-lint. +-- +-- This migration is applied to PRODUCTION automatically when the PR merges, +-- BEFORE the new lambda code is deployed. It must be safe for the code that is +-- live right now: additive changes only. See apps/backend/db/README.md for the +-- expand/contract rules that destructive changes need. +-- +-- Forward-only: there is no rollback. Fix a mistake with a new migration, and +-- never edit a migration that has been merged -- Flyway checksums it, and +-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not +-- silent drift. + + +ALTER TABLE project_donations ADD COLUMN deleted_at TIMESTAMP; diff --git a/apps/backend/db/migrations/V20261015195658__add_expenditures_deleted_at.sql b/apps/backend/db/migrations/V20261015195658__add_expenditures_deleted_at.sql new file mode 100644 index 00000000..ca93294f --- /dev/null +++ b/apps/backend/db/migrations/V20261015195658__add_expenditures_deleted_at.sql @@ -0,0 +1,21 @@ +-- V20261015195658__add_expenditures_deleted_at +-- +-- Flyway runs this file inside a SINGLE transaction, with search_path = +-- branch, public -- so table names can be unqualified. +-- +-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its +-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE, +-- and at most 3,000 rows changed. CI lints this file with dsql-lint. +-- +-- This migration is applied to PRODUCTION automatically when the PR merges, +-- BEFORE the new lambda code is deployed. It must be safe for the code that is +-- live right now: additive changes only. See apps/backend/db/README.md for the +-- expand/contract rules that destructive changes need. +-- +-- Forward-only: there is no rollback. Fix a mistake with a new migration, and +-- never edit a migration that has been merged -- Flyway checksums it, and +-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not +-- silent drift. + + +ALTER TABLE expenditures ADD COLUMN deleted_at TIMESTAMP; diff --git a/apps/backend/db/migrations/V20261015195700__add_reports_deleted_at.sql b/apps/backend/db/migrations/V20261015195700__add_reports_deleted_at.sql new file mode 100644 index 00000000..c6529232 --- /dev/null +++ b/apps/backend/db/migrations/V20261015195700__add_reports_deleted_at.sql @@ -0,0 +1,21 @@ +-- V20261015195700__add_reports_deleted_at +-- +-- Flyway runs this file inside a SINGLE transaction, with search_path = +-- branch, public -- so table names can be unqualified. +-- +-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its +-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE, +-- and at most 3,000 rows changed. CI lints this file with dsql-lint. +-- +-- This migration is applied to PRODUCTION automatically when the PR merges, +-- BEFORE the new lambda code is deployed. It must be safe for the code that is +-- live right now: additive changes only. See apps/backend/db/README.md for the +-- expand/contract rules that destructive changes need. +-- +-- Forward-only: there is no rollback. Fix a mistake with a new migration, and +-- never edit a migration that has been merged -- Flyway checksums it, and +-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not +-- silent drift. + + +ALTER TABLE reports ADD COLUMN deleted_at TIMESTAMP; diff --git a/apps/backend/db/migrations/V20261015195702__drop_project_donations_donor_project_unique.sql b/apps/backend/db/migrations/V20261015195702__drop_project_donations_donor_project_unique.sql new file mode 100644 index 00000000..6b359a3e --- /dev/null +++ b/apps/backend/db/migrations/V20261015195702__drop_project_donations_donor_project_unique.sql @@ -0,0 +1,22 @@ +-- V20261015195702__drop_project_donations_donor_project_unique +-- +-- Flyway runs this file inside a SINGLE transaction, with search_path = +-- branch, public -- so table names can be unqualified. +-- +-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its +-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE, +-- and at most 3,000 rows changed. CI lints this file with dsql-lint. +-- +-- This migration is applied to PRODUCTION automatically when the PR merges, +-- BEFORE the new lambda code is deployed. It must be safe for the code that is +-- live right now: additive changes only. See apps/backend/db/README.md for the +-- expand/contract rules that destructive changes need. +-- +-- Forward-only: there is no rollback. Fix a mistake with a new migration, and +-- never edit a migration that has been merged -- Flyway checksums it, and +-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not +-- silent drift. + + +-- A donor may give to the same project more than once. +ALTER TABLE project_donations DROP CONSTRAINT project_donations_donor_id_project_id_key; diff --git a/apps/backend/db/migrations/V20261015195703__drop_users_email_unique.sql b/apps/backend/db/migrations/V20261015195703__drop_users_email_unique.sql new file mode 100644 index 00000000..af117aaa --- /dev/null +++ b/apps/backend/db/migrations/V20261015195703__drop_users_email_unique.sql @@ -0,0 +1,22 @@ +-- V20261015195703__drop_users_email_unique +-- +-- Flyway runs this file inside a SINGLE transaction, with search_path = +-- branch, public -- so table names can be unqualified. +-- +-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its +-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE, +-- and at most 3,000 rows changed. CI lints this file with dsql-lint. +-- +-- This migration is applied to PRODUCTION automatically when the PR merges, +-- BEFORE the new lambda code is deployed. It must be safe for the code that is +-- live right now: additive changes only. See apps/backend/db/README.md for the +-- expand/contract rules that destructive changes need. +-- +-- Forward-only: there is no rollback. Fix a mistake with a new migration, and +-- never edit a migration that has been merged -- Flyway checksums it, and +-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not +-- silent drift. + + +-- Soft-deleted users keep their email; Cognito enforces uniqueness among live accounts. +ALTER TABLE users DROP CONSTRAINT users_email_key; diff --git a/apps/backend/db/testkit.ts b/apps/backend/db/testkit.ts index c9eeba87..c2318d5a 100644 --- a/apps/backend/db/testkit.ts +++ b/apps/backend/db/testkit.ts @@ -239,6 +239,7 @@ const EXPECTED_EXPENDITURE_ROLLUP = ` SUM(amount) AS total_amount, COUNT(*)::int AS expenditure_count FROM ${SCHEMA}.expenditures + WHERE deleted_at IS NULL GROUP BY project_id, date_trunc('month', spent_on)::date, category, status`; const EXPECTED_PROJECT_ROLLUP = ` @@ -250,10 +251,31 @@ const EXPECTED_PROJECT_ROLLUP = ` FROM ${SCHEMA}.projects p LEFT JOIN (SELECT project_id, COUNT(*) AS c FROM ${SCHEMA}.project_memberships GROUP BY project_id) m ON m.project_id = p.project_id - LEFT JOIN (SELECT project_id, COUNT(*) AS c, SUM(amount) AS total FROM ${SCHEMA}.project_donations GROUP BY project_id) d + LEFT JOIN (SELECT project_id, COUNT(*) AS c, SUM(amount) AS total FROM ${SCHEMA}.project_donations WHERE deleted_at IS NULL GROUP BY project_id) d ON d.project_id = p.project_id - LEFT JOIN (SELECT project_id, COUNT(*) AS c FROM ${SCHEMA}.reports GROUP BY project_id) r - ON r.project_id = p.project_id`; + LEFT JOIN (SELECT project_id, COUNT(*) AS c FROM ${SCHEMA}.reports WHERE deleted_at IS NULL GROUP BY project_id) r + ON r.project_id = p.project_id + WHERE p.deleted_at IS NULL`; + +/** + * Hard-deletes every soft-deleted row, children first. Read-parity tests snapshot the + * API before and after: a soft-deleted row must read exactly like an absent one. + */ +export async function purgeSoftDeleted(client: Queryable): Promise { + for (const table of ['expenditures', 'reports', 'project_donations', 'donors', 'projects', 'users']) { + await client.query(`DELETE FROM ${SCHEMA}.${table} WHERE deleted_at IS NOT NULL`); + } +} + +/** Seed ids the parity tests delete: one of each kind, plus a project and a user with children. */ +export const PARITY_DELETES = { + expenditure: 1, + donation: 2, + donor: 3, + report: 4, + project: 3, + user: 5, +} as const; // A zero-count expenditure_rollup row equals a missing one: _remove decrements without deleting. export async function findRollupDrift(client: Queryable): Promise { diff --git a/apps/backend/lambdas/auth/controllers/mfa.ts b/apps/backend/lambdas/auth/controllers/mfa.ts index 6763312d..d3d5e2d5 100644 --- a/apps/backend/lambdas/auth/controllers/mfa.ts +++ b/apps/backend/lambdas/auth/controllers/mfa.ts @@ -71,6 +71,7 @@ export const handleMfaSetup: RouteHandler = async ({ event, auth }) => { const me = await db .selectFrom('branch.users') .where('cognito_sub', '=', user.cognitoSub) + .where('deleted_at', 'is', null) .select(['email']) .executeTakeFirst(); diff --git a/apps/backend/lambdas/auth/controllers/register.ts b/apps/backend/lambdas/auth/controllers/register.ts index 1b6d76a5..a4c9db11 100644 --- a/apps/backend/lambdas/auth/controllers/register.ts +++ b/apps/backend/lambdas/auth/controllers/register.ts @@ -51,6 +51,7 @@ export async function handleRegister(event: any): Promise const existingUser = await db .selectFrom('branch.users') .where('email', '=', email.toLowerCase()) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); diff --git a/apps/backend/lambdas/donors/controllers/donations.ts b/apps/backend/lambdas/donors/controllers/donations.ts index 3e816a7f..a3641aa2 100644 --- a/apps/backend/lambdas/donors/controllers/donations.ts +++ b/apps/backend/lambdas/donors/controllers/donations.ts @@ -42,11 +42,13 @@ export async function getDonations({ event, auth }: RouteCtx) { let countQuery = db .selectFrom('branch.project_donations') + .where('deleted_at', 'is', null) .select(db.fn.count('donation_id').as('count')); if (inScope) countQuery = countQuery.where(inScope); let pageQuery = db .selectFrom('branch.project_donations') + .where('deleted_at', 'is', null) .selectAll() .orderBy('donation_id', 'asc'); if (inScope) pageQuery = pageQuery.where(inScope); @@ -66,7 +68,7 @@ export async function getDonations({ event, auth }: RouteCtx) { }); } - let query = db.selectFrom('branch.project_donations').selectAll(); + let query = db.selectFrom('branch.project_donations').where('deleted_at', 'is', null).selectAll(); if (inScope) query = query.where(inScope); const donations = await query.execute(); return json(200, { data: donations }); @@ -115,11 +117,17 @@ export async function createDonation({ event }: RouteCtx) { // 404, but only with the combined "Donor or project not found" message, and // these two tell the caller which id was wrong. const [donor, project] = await Promise.all([ - db.selectFrom('branch.donors').select('donor_id').where('donor_id', '=', donorId).executeTakeFirst(), + db + .selectFrom('branch.donors') + .select('donor_id') + .where('donor_id', '=', donorId) + .where('deleted_at', 'is', null) + .executeTakeFirst(), db .selectFrom('branch.projects') .select('project_id') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .executeTakeFirst(), ]); @@ -141,9 +149,6 @@ export async function createDonation({ event }: RouteCtx) { return json(201, { data: donation }); } catch (err: any) { - if (err?.code === '23505') { - return json(409, { message: 'A donation from this donor to this project already exists' }); - } if (err?.code === '23503') { return json(404, { message: 'Donor or project not found' }); } @@ -161,6 +166,7 @@ export async function deleteDonation({ params, auth }: RouteCtx) { const donation = await db .selectFrom('branch.project_donations') .where('donation_id', '=', Number(id)) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); diff --git a/apps/backend/lambdas/donors/controllers/donors.ts b/apps/backend/lambdas/donors/controllers/donors.ts index 9753fa96..00999f24 100644 --- a/apps/backend/lambdas/donors/controllers/donors.ts +++ b/apps/backend/lambdas/donors/controllers/donors.ts @@ -32,9 +32,14 @@ export async function getDonors({ event }: RouteCtx) { // The count does not depend on the page, so both go out at once. const [totalCount, donors] = await Promise.all([ - db.selectFrom('branch.donors').select(db.fn.count('donor_id').as('count')).executeTakeFirst(), db .selectFrom('branch.donors') + .where('deleted_at', 'is', null) + .select(db.fn.count('donor_id').as('count')) + .executeTakeFirst(), + db + .selectFrom('branch.donors') + .where('deleted_at', 'is', null) .selectAll() .orderBy('donor_id', 'asc') .limit(limit) @@ -51,7 +56,7 @@ export async function getDonors({ event }: RouteCtx) { }); } - const donors = await db.selectFrom('branch.donors').selectAll().execute(); + const donors = await db.selectFrom('branch.donors').where('deleted_at', 'is', null).selectAll().execute(); return json(200, { data: donors }); } diff --git a/apps/backend/lambdas/donors/test/donors.test.ts b/apps/backend/lambdas/donors/test/donors.test.ts index e591b2d3..12054fff 100644 --- a/apps/backend/lambdas/donors/test/donors.test.ts +++ b/apps/backend/lambdas/donors/test/donors.test.ts @@ -368,6 +368,18 @@ describe("Donor API with data", () => { expect(Number(body.data.amount)).toBe(500); }); + test("POST /donations accepts a second donation from the same donor to the same project", async () => { + mockAuthenticateRequest.mockResolvedValueOnce(adminUser); + // Seed donation 1 is donor 1 -> project 1. + const res = await handler(createEvent('POST', '/donations', { + donor_id: 1, project_id: 1, amount: 250, + })); + const body = JSON.parse(res.body); + expect(res.statusCode).toBe(201); + expect(body.data.donor_id).toBe(1); + expect(body.data.project_id).toBe(1); + }); + test("POST /donations honours an explicit donated_at", async () => { mockAuthenticateRequest.mockResolvedValueOnce(adminUser); const res = await handler(createEvent('POST', '/donations', { @@ -489,7 +501,7 @@ describe("Donor API with data", () => { test("DELETE /donors/{id} returns 200 for admin and removes the donor", async () => { mockAuthenticateRequest.mockResolvedValueOnce(adminUser); - // Donor 2 (Harvard Medical) — note this cascades and also removes donation_id 2 + // Donor 2 (Harvard Medical) — note this also soft-deletes donation_id 2 const res = await handler(createEvent('DELETE', '/donors/2')); const body = JSON.parse(res.body); @@ -499,8 +511,8 @@ describe("Donor API with data", () => { const client = await pool.connect(); try { - const result = await client.query('SELECT * FROM branch.donors WHERE donor_id = 2'); - expect(result.rows.length).toBe(0); + const result = await client.query('SELECT * FROM branch.donors WHERE donor_id = 2 AND deleted_at IS NOT NULL'); + expect(result.rows.length).toBe(1); } finally { client.release(); } @@ -543,8 +555,8 @@ describe("Donor API with data", () => { const client = await pool.connect(); try { - const result = await client.query('SELECT * FROM branch.project_donations WHERE donation_id = 3'); - expect(result.rows.length).toBe(0); + const result = await client.query('SELECT * FROM branch.project_donations WHERE donation_id = 3 AND deleted_at IS NOT NULL'); + expect(result.rows.length).toBe(1); } finally { client.release(); } diff --git a/apps/backend/lambdas/donors/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/donors/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..d1ba6ce9 --- /dev/null +++ b/apps/backend/lambdas/donors/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,113 @@ +/** + * A soft-deleted row must read exactly like a hard-deleted one. Delete one of each + * kind through the store, snapshot every GET, purge the soft-deleted rows, and + * snapshot again: the two must be identical. + */ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const PAGES: Record[] = [ + {}, + { page: '1', limit: '2' }, + { page: '2', limit: '2' }, + { page: '1', limit: '100' }, +]; + +const REQUESTS: [string, Record][] = ['/donors', '/donors/donations'].flatMap((path) => + PAGES.map((query): [string, Record] => [path, query]), +); + +async function snapshot(): Promise> { + const out: Record = {}; + for (const [rawPath, queryStringParameters] of REQUESTS) { + const res = await handler({ + rawPath, + requestContext: { http: { method: 'GET' } }, + body: undefined, + queryStringParameters, + } as any); + out[`${rawPath}?${new URLSearchParams(queryStringParameters)}`] = { status: res.statusCode, body: res.body }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every donors GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + const donors = JSON.parse(soft['/donors?'].body).data as { donor_id: number }[]; + expect(donors.map((d) => d.donor_id)).not.toContain(PARITY_DELETES.donor); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/expenditures/controllers/expenditures.ts b/apps/backend/lambdas/expenditures/controllers/expenditures.ts index 78e33068..60d575ee 100644 --- a/apps/backend/lambdas/expenditures/controllers/expenditures.ts +++ b/apps/backend/lambdas/expenditures/controllers/expenditures.ts @@ -317,11 +317,8 @@ export const deleteExpenditure: RouteHandler = async ({ params, auth }) => { return json(404, { message: 'Expenditure not found' }); } - // After the row, never before: if the object went first and the delete - // below failed, the receipt would be gone with a row still pointing at it. - const receiptDeleted = await expendituresService.deleteReceiptObject(expenditure.receipt_url); - - return json(200, { ok: true, route: 'DELETE /expenditures/{id}', pathParams: { id }, receiptDeleted }); + // The receipt object stays in S3 so a soft delete can be restored. + return json(200, { ok: true, route: 'DELETE /expenditures/{id}', pathParams: { id } }); }; // PATCH /expenditures/{id}/status — approve/decline. `expense:review` on the diff --git a/apps/backend/lambdas/expenditures/services/expenditures.ts b/apps/backend/lambdas/expenditures/services/expenditures.ts index 9de79f78..e4a55e8f 100644 --- a/apps/backend/lambdas/expenditures/services/expenditures.ts +++ b/apps/backend/lambdas/expenditures/services/expenditures.ts @@ -1,7 +1,6 @@ import { Insertable, Updateable } from 'kysely'; -import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'; +import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; -import { reportError } from '@branch/lambda-http'; import type { DB } from '@branch/types'; import { db, recordExpenditure, editExpenditure, removeExpenditure } from '@branch/store'; import type { ExpenditureStatus } from '../validation-utils'; @@ -21,36 +20,6 @@ export function receiptKeyFromUrl(objectUrl: string): string | null { return match ? decodeURIComponent(match[1]) : null; } -/** - * Best-effort removal of the receipt behind a deleted expenditure. - * - * Deliberately never throws: the row is already gone by the time this runs, and - * the caller must not turn a successful delete into a 500 because S3 was - * unreachable or the role is missing `s3:DeleteObject`. A leftover object is - * recoverable; a row that cannot be deleted is not. - */ -export async function deleteReceiptObject(receiptUrl: string | null): Promise { - if (!receiptUrl) return true; - const key = receiptKeyFromUrl(receiptUrl); - if (!key) return false; - // Read at call time rather than using the module-level BUCKET: the value is - // then observable to callers that set it after import, which is what the - // unit tests do. - const bucket = process.env.REPORTS_BUCKET_NAME ?? ''; - if (!bucket) { - console.error('REPORTS_BUCKET_NAME is not set; leaving receipt object', key); - return false; - } - try { - await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: key })); - return true; - } catch (err) { - console.error('Failed to delete receipt object', key, err); - reportError(err, { key }); - return false; - } -} - export async function countExpenditures(projectId: number | null, scope: ExpenditureScope): Promise { // Only the unscoped count can come from the rollup. A scoped one is // `project_id IN (...) OR entered_by = me`, and entered_by is not in the @@ -65,7 +34,10 @@ export async function countExpenditures(projectId: number | null, scope: Expendi return Number(rolledUp?.count || 0); } - let query = db.selectFrom('branch.expenditures').select(db.fn.count('expenditure_id').as('count')); + let query = db + .selectFrom('branch.expenditures') + .where('deleted_at', 'is', null) + .select(db.fn.count('expenditure_id').as('count')); if (projectId !== null) query = query.where('project_id', '=', projectId); const totalCount = await applyExpenditureScope(query, scope).executeTakeFirst(); @@ -77,7 +49,7 @@ export async function queryExpenditures( scope: ExpenditureScope, page?: { limit: number; offset: number }, ) { - let query = db.selectFrom('branch.expenditures').selectAll(); + let query = db.selectFrom('branch.expenditures').where('deleted_at', 'is', null).selectAll(); if (projectId !== null) query = query.where('project_id', '=', projectId); const scoped = applyExpenditureScope(query, scope).orderBy('spent_on', 'desc'); @@ -94,7 +66,12 @@ export async function findMembership(projectId: number, userId: number) { } export async function findProjectById(projectId: number) { - return db.selectFrom('branch.projects').where('project_id', '=', projectId).selectAll().executeTakeFirst(); + return db + .selectFrom('branch.projects') + .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) + .selectAll() + .executeTakeFirst(); } /** @@ -108,8 +85,12 @@ export async function findExpenditureWithNames(id: number) { return db .selectFrom('branch.expenditures as e') .innerJoin('branch.projects as p', 'p.project_id', 'e.project_id') - .leftJoin('branch.users as u', 'u.user_id', 'e.entered_by') + .leftJoin('branch.users as u', (join) => + join.onRef('u.user_id', '=', 'e.entered_by').on('u.deleted_at', 'is', null), + ) .where('e.expenditure_id', '=', id) + .where('e.deleted_at', 'is', null) + .where('p.deleted_at', 'is', null) .selectAll('e') .select(['p.name as project_name', 'u.name as submitted_by_name']) .executeTakeFirst(); @@ -120,7 +101,12 @@ export async function insertExpenditure(values: Insertable { @@ -152,6 +138,7 @@ export async function getUserContact(userId: number) { return db .selectFrom('branch.users') .where('user_id', '=', userId) + .where('deleted_at', 'is', null) .select(['name', 'email']) .executeTakeFirst(); } diff --git a/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts index 5f4f8fb4..80bd6fd7 100644 --- a/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts +++ b/apps/backend/lambdas/expenditures/test/expenditures.e2e.test.ts @@ -1,7 +1,7 @@ import { describe, test, expect, beforeAll, beforeEach, afterAll, jest } from '@jest/globals'; import { Pool } from 'pg'; import { ensureSchema, resetData } from '../../../db/testkit'; -import { db, closeConnection } from '@branch/store'; +import { db, closeConnection, removeUser } from '@branch/store'; // mock auth only for now jest.mock('../auth', () => { @@ -158,12 +158,12 @@ async function firstExpenditureId(projectId: number): Promise { } } -// Directly queries the DB to confirm whether a row still exists +// Directly queries the DB to confirm whether a row is still live async function expenditureExists(id: number): Promise { const client = await pool.connect(); try { const result = await client.query( - 'SELECT 1 FROM branch.expenditures WHERE expenditure_id = $1', + 'SELECT 1 FROM branch.expenditures WHERE expenditure_id = $1 AND deleted_at IS NULL', [id] ); return (result.rowCount ?? 0) > 0; @@ -172,6 +172,15 @@ async function expenditureExists(id: number): Promise { } } +// A delete keeps the row and stamps it +async function expenditureSoftDeleted(id: number): Promise { + const result = await pool.query( + 'SELECT 1 FROM branch.expenditures WHERE expenditure_id = $1 AND deleted_at IS NOT NULL', + [id] + ); + return (result.rowCount ?? 0) > 0; +} + describe('Expenditures integration tests', () => { beforeEach(async () => { jest.clearAllMocks(); @@ -546,6 +555,30 @@ describe('Expenditures integration tests', () => { const res = await handler(idRequestEvent('GET', id)); expect(res.statusCode).toBe(200); }); + + // As ON DELETE SET NULL left it: the expense survives, its author reads as null. + test('200: a soft-deleted author reads as null', async () => { + const id = await firstExpenditureId(1); // entered_by 4 + await removeUser(4); + + const res = await handler(idRequestEvent('GET', id)); + expect(res.statusCode).toBe(200); + const body = JSON.parse(res.body).body; + expect(body.enteredBy).toBeNull(); + expect(body.submittedByName).toBeNull(); + + const list = JSON.parse((await handler(getEvent('/'))).body).data; + expect(list.find((e: { expenditure_id: number }) => e.expenditure_id === id).entered_by).toBeNull(); + expect(list[0]).not.toHaveProperty('deleted_at'); + }); + + test('404: a soft-deleted expenditure is not found', async () => { + const id = await firstExpenditureId(1); + await pool.query('UPDATE branch.expenditures SET deleted_at = now() WHERE expenditure_id = $1', [id]); + + const res = await handler(idRequestEvent('GET', id)); + expect(res.statusCode).toBe(404); + }); }); describe('DELETE /expenditures/{id}', () => { @@ -619,7 +652,7 @@ describe('Expenditures integration tests', () => { const res = await handler(idRequestEvent('DELETE', id)); expect(res.statusCode).toBe(200); - expect(await expenditureExists(id)).toBe(false); + expect(await expenditureSoftDeleted(id)).toBe(true); }); test('200: admin can delete an expenditure on any project', async () => { @@ -627,7 +660,7 @@ describe('Expenditures integration tests', () => { const res = await handler(idRequestEvent('DELETE', id)); expect(res.statusCode).toBe(200); - expect(await expenditureExists(id)).toBe(false); + expect(await expenditureSoftDeleted(id)).toBe(true); }); test('404: deleting the same expenditure twice returns 404 the second time', async () => { @@ -644,7 +677,7 @@ describe('Expenditures integration tests', () => { const client = await pool.connect(); let totalBefore: number; try { - const result = await client.query('SELECT COUNT(*)::int AS count FROM branch.expenditures'); + const result = await client.query('SELECT COUNT(*)::int AS count FROM branch.expenditures WHERE deleted_at IS NULL'); totalBefore = result.rows[0].count; } finally { client.release(); @@ -656,7 +689,7 @@ describe('Expenditures integration tests', () => { const client2 = await pool.connect(); try { - const result = await client2.query('SELECT COUNT(*)::int AS count FROM branch.expenditures'); + const result = await client2.query('SELECT COUNT(*)::int AS count FROM branch.expenditures WHERE deleted_at IS NULL'); expect(result.rows[0].count).toBe(totalBefore - 1); } finally { client2.release(); diff --git a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts index 39e55f78..8ad54425 100644 --- a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts +++ b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts @@ -32,8 +32,8 @@ jest.mock('@aws-sdk/s3-request-presigner', () => ({ getSignedUrl: jest.fn(async () => 'https://signed.example/url'), })); -// Nor must the receipt delete on DELETE /expenditures/{id}. Shared across -// instances so the assertions below can see the call. +// Nor must any S3 call. Shared across instances so the assertions below can +// see that DELETE /expenditures/{id} sends no DeleteObject. const mockS3Send = jest.fn<(command: unknown) => Promise>(); jest.mock('@aws-sdk/client-s3', () => ({ S3Client: jest.fn().mockImplementation(() => ({ send: mockS3Send })), @@ -124,59 +124,49 @@ const fakeExpenditure = { created_at: new Date('2025-06-01'), }; +// A query builder whose every method returns itself, so a mock does not break +// when a filter is added. `resolve` sees the builder calls made so far. +function mockQuery(result: unknown | ((calls: string[]) => unknown)) { + const calls: string[] = []; + const settle = async () => (typeof result === 'function' ? (result as (c: string[]) => unknown)(calls) : result); + const methods: Record = {}; + const builder: any = new Proxy(methods, { + get(target, prop) { + if (typeof prop !== 'string' || prop === 'then') return undefined; + if (!(prop in target)) { + target[prop] = prop === 'execute' || prop === 'executeTakeFirst' + ? jest.fn(settle) + : jest.fn(() => { + calls.push(prop); + return builder; + }); + } + return target[prop]; + }, + }); + return builder; +} + +function mockQueryError(err: Error) { + return mockQuery(() => { + throw err; + }); +} + // Mocks the query chain used by the handler to fetch a single expenditure function mockSelectExpenditure(result: any, name?: string) { - return { - // GET /expenditures/{id} reads the row and the submitter and project names - // in one joined statement, so those names arrive as columns on the row. - innerJoin: jest.fn().mockReturnValue({ - leftJoin: jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest - .fn() - .mockReturnValue( - result && name - ? { ...result, project_name: name, submitted_by_name: name } - : result, - ), - }), - }), - }), - }), - }), - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(result), - }), - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(name ? { name } : undefined), - }), - }), - }; + // GET /expenditures/{id} reads the row and the submitter and project names + // in one joined statement, so those names arrive as columns on the row. + return mockQuery((calls: string[]) => + calls.includes('innerJoin') && result && name + ? { ...result, project_name: name, submitted_by_name: name } + : result, + ); } // Mocks the query chain used by the handler to check project membership function mockMembership(result: any) { - return { - where: jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(result), - }), - }), - }), - }; -} - -// Mocks the query chain used by the handler to delete an expenditure -function mockDelete(numDeletedRows: bigint) { - return { - where: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue([{ numDeletedRows }]), - }), - }; + return mockQuery(result); } // Default authenticated admin user @@ -420,17 +410,11 @@ describe('POST /expenditures unit tests', () => { test('response has correct HTTP headers', async () => { // Setup mocks for successful expenditure creation - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 1, - name: 'Test Project', - total_budget: 50000, - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 1, + name: 'Test Project', + total_budget: 50000, + })); mockDb.insertInto.mockReturnValue({ values: jest.fn().mockReturnValue({ @@ -455,16 +439,10 @@ describe('POST /expenditures unit tests', () => { describe('Success Cases', () => { test('201: successful POST returns 201 status and correct response shape', async () => { // Mock: project exists - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 1, - name: 'Test Project', - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 1, + name: 'Test Project', + })); // Mock: insert succeeds mockDb.insertInto.mockReturnValue({ @@ -495,16 +473,10 @@ describe('POST /expenditures unit tests', () => { }); test('201: accepts explicit status and receipt_url', async () => { - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 1, - name: 'Test Project', - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 1, + name: 'Test Project', + })); mockDb.insertInto.mockReturnValue({ values: jest.fn().mockReturnValue({ @@ -529,13 +501,7 @@ describe('POST /expenditures unit tests', () => { test('404: returns 404 when project not found', async () => { // Mock: project doesn't exist - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(null as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(null)); const res = await handler( postEvent({ @@ -551,16 +517,10 @@ describe('POST /expenditures unit tests', () => { test('201: handles optional fields correctly', async () => { // Mock: project exists - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 2, - name: 'Another Project', - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 2, + name: 'Another Project', + })); // Mock: insert succeeds mockDb.insertInto.mockReturnValue({ @@ -587,16 +547,10 @@ describe('POST /expenditures unit tests', () => { describe('Error Handling', () => { test('500: returns 500 when database insert fails', async () => { // Mock: project exists - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 1, - name: 'Test Project', - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 1, + name: 'Test Project', + })); mockRecordExpenditure.mockRejectedValue(new Error('Database connection failed')); @@ -614,13 +568,7 @@ describe('POST /expenditures unit tests', () => { test('500: returns 500 when project lookup fails', async () => { // Mock: project lookup throws error - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: (jest.fn() as any).mockRejectedValue(new Error('Database error')), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQueryError(new Error('Database error'))); const res = await handler( postEvent({ @@ -643,13 +591,7 @@ describe('POST /expenditures unit tests', () => { }); test('200: returns data array without pagination when no params', async () => { - mockDb.selectFrom.mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue(fakeExpenditures as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(fakeExpenditures)); const res = await handler(getEvent()); expect(res.statusCode).toBe(200); @@ -660,23 +602,9 @@ describe('POST /expenditures unit tests', () => { test('200: returns paginated response with page and limit', async () => { // count query - mockDb.selectFrom.mockReturnValueOnce({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ count: '3' } as any), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery({ count: '3' })); // data query - mockDb.selectFrom.mockReturnValueOnce({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - limit: jest.fn().mockReturnValue({ - offset: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue([fakeExpenditures[0]] as any), - }), - }), - }), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery([fakeExpenditures[0]])); const res = await handler(getEvent({ page: '1', limit: '1' })); expect(res.statusCode).toBe(200); @@ -917,55 +845,21 @@ describe('DELETE /expenditures/{id} unit tests', () => { }); }); - describe('the receipt goes with the row', () => { - const withReceipt = { - ...fakeExpenditure, - receipt_url: 'https://bucket.s3.us-east-2.amazonaws.com/receipts/1/flight.pdf', - }; - - beforeEach(() => { - mockMemberships.length = 0; - process.env.REPORTS_BUCKET_NAME = 'bucket'; - mockDb.selectFrom.mockReturnValueOnce(mockSelectExpenditure(withReceipt)); - mockRemoveExpenditure.mockResolvedValue(1n); - mockS3Send.mockResolvedValue({}); - }); - - test('deletes the receipt object', async () => { - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).receiptDeleted).toBe(true); - expect(mockS3Send).toHaveBeenCalledWith( - expect.objectContaining({ - __type: 'DeleteObject', - Bucket: 'bucket', - Key: 'receipts/1/flight.pdf', - }), - ); - }); - - test('a failing S3 delete still deletes the row', async () => { - // An orphaned object is recoverable; a row that cannot be deleted is not. - mockS3Send.mockRejectedValue(new Error('AccessDenied')); - - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).receiptDeleted).toBe(false); - }); - }); - - test('an expenditure with no receipt makes no S3 call', async () => { + // A soft delete keeps the receipt so the row can be restored. + test('the receipt object is left in S3', async () => { process.env.REPORTS_BUCKET_NAME = 'bucket'; - mockDb.selectFrom.mockReturnValueOnce(mockSelectExpenditure(fakeExpenditure)); + mockDb.selectFrom.mockReturnValueOnce( + mockSelectExpenditure({ + ...fakeExpenditure, + receipt_url: 'https://bucket.s3.us-east-2.amazonaws.com/receipts/1/flight.pdf', + }), + ); mockRemoveExpenditure.mockResolvedValue(1n); const res = await handler(idEvent('DELETE', '5')); expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).receiptDeleted).toBe(true); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockS3Send).not.toHaveBeenCalledWith(expect.objectContaining({ __type: 'DeleteObject' })); }); describe('Success cases', () => { @@ -1035,15 +929,7 @@ describe('PATCH /expenditures/{id}/status unit tests', () => { ); mockDb.selectFrom.mockImplementation((table: string) => { - if (table === 'branch.users') { - return { - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: (jest.fn() as any).mockResolvedValue(submitter ?? undefined), - }), - }), - }; - } + if (table === 'branch.users') return mockQuery(submitter ?? undefined); throw new Error(`mockExpenditureForPatch: unexpected table "${table}"`); }); } diff --git a/apps/backend/lambdas/expenditures/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/expenditures/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..a71557f1 --- /dev/null +++ b/apps/backend/lambdas/expenditures/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,121 @@ +/** + * A soft-deleted row must read exactly like a hard-deleted one. Delete one of each + * kind through the store, snapshot every GET, purge the soft-deleted rows, and + * snapshot again: the two must be identical. + */ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); +jest.mock('../mailer'); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const LIST_QUERIES: Record[] = [ + {}, + { page: '1', limit: '3' }, + { page: '2', limit: '3' }, + { page: '1', limit: '100' }, + ...[1, 2, 3, 4].flatMap((projectId): Record[] => [ + { projectId: String(projectId) }, + { projectId: String(projectId), page: '1', limit: '100' }, + ]), +]; + +const REQUESTS: [string, Record][] = [ + ...LIST_QUERIES.map((query): [string, Record] => ['/expenditures', query]), + ...[1, 2, 3, 4, 5, 6].flatMap((id): [string, Record][] => [ + [`/expenditures/${id}`, {}], + [`/expenditures/${id}/receipt`, {}], + ]), +]; + +async function snapshot(): Promise> { + const out: Record = {}; + for (const [rawPath, queryStringParameters] of REQUESTS) { + const res = await handler({ + rawPath, + requestContext: { http: { method: 'GET' } }, + headers: { Authorization: 'Bearer fake-token' }, + queryStringParameters, + } as any); + out[`${rawPath}?${new URLSearchParams(queryStringParameters)}`] = { status: res.statusCode, body: res.body }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every expenditures GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + expect(soft[`/expenditures/${PARITY_DELETES.expenditure}?`].status).toBe(404); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/projects/controllers/dashboard.ts b/apps/backend/lambdas/projects/controllers/dashboard.ts index 334e878d..8e62dc25 100644 --- a/apps/backend/lambdas/projects/controllers/dashboard.ts +++ b/apps/backend/lambdas/projects/controllers/dashboard.ts @@ -48,6 +48,7 @@ export const getDashboard: RouteHandler = async () => { // Not a rollup: "active" changes with the clock, not with a write. db.selectFrom('branch.projects') .select(db.fn.count('project_id').as('count')) + .where('deleted_at', 'is', null) .where(isActive('end_date')) .executeTakeFirst(), db.selectFrom('branch.expenditure_rollup') @@ -68,6 +69,7 @@ export const getDashboard: RouteHandler = async () => { .where('er.status', '=', APPROVED_EXPENDITURE_STATUS) .where('er.month', '>=', yearStart as any) .where('er.month', '<', nextYearStart as any) + .where('p.deleted_at', 'is', null) .where(isActive('p.end_date')) .executeTakeFirst(), // Spend stays a pre-aggregated subquery: the rollup is per @@ -93,6 +95,7 @@ export const getDashboard: RouteHandler = async () => { 'spend.total as spent', 'pr.member_count as staff_count', ]) + .where('p.deleted_at', 'is', null) .orderBy('p.project_id', 'asc') .execute(), db.selectFrom('branch.expenditure_rollup') @@ -183,11 +186,17 @@ export const getOverview: RouteHandler = async (ctx) => { // None of the three below depend on the project row, so all four go out at // once and the 404 is settled from the result rather than ahead of them. const [project, members, expenditures, donationRow] = await Promise.all([ - db.selectFrom('branch.projects').where('project_id', '=', id).selectAll().executeTakeFirst(), + db + .selectFrom('branch.projects') + .where('project_id', '=', id) + .where('deleted_at', 'is', null) + .selectAll() + .executeTakeFirst(), listRoster(id), db .selectFrom('branch.expenditures') .where('project_id', '=', id) + .where('deleted_at', 'is', null) .selectAll() .orderBy('spent_on', 'desc') .execute(), diff --git a/apps/backend/lambdas/projects/controllers/donors.ts b/apps/backend/lambdas/projects/controllers/donors.ts index d8fe6270..2444404f 100644 --- a/apps/backend/lambdas/projects/controllers/donors.ts +++ b/apps/backend/lambdas/projects/controllers/donors.ts @@ -18,6 +18,7 @@ export const getProjectDonors: RouteHandler = async (ctx) => { const project = await db .selectFrom('branch.projects as p') .where('p.project_id', '=', projectId) + .where('p.deleted_at', 'is', null) .selectAll() .executeTakeFirst(); @@ -36,6 +37,9 @@ export const getProjectDonors: RouteHandler = async (ctx) => { .where('p.project_id', '=', projectId) .innerJoin('branch.project_donations as bpd', 'bpd.project_id', 'p.project_id') .innerJoin('branch.donors as bd', 'bd.donor_id', 'bpd.donor_id') + .where('p.deleted_at', 'is', null) + .where('bpd.deleted_at', 'is', null) + .where('bd.deleted_at', 'is', null) .select([ 'bd.donor_id', 'bd.organization', diff --git a/apps/backend/lambdas/projects/controllers/expenditures.ts b/apps/backend/lambdas/projects/controllers/expenditures.ts index 0ddeee94..a5c873e5 100644 --- a/apps/backend/lambdas/projects/controllers/expenditures.ts +++ b/apps/backend/lambdas/projects/controllers/expenditures.ts @@ -12,6 +12,7 @@ export const getProjectExpenditures: RouteHandler = async (ctx) => { const project = await db .selectFrom('branch.projects') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); @@ -22,6 +23,7 @@ export const getProjectExpenditures: RouteHandler = async (ctx) => { const expenditures = await db .selectFrom('branch.expenditures') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .selectAll() .orderBy('spent_on', 'desc') .execute(); diff --git a/apps/backend/lambdas/projects/controllers/members.ts b/apps/backend/lambdas/projects/controllers/members.ts index 06b10c1d..fb7c1e98 100644 --- a/apps/backend/lambdas/projects/controllers/members.ts +++ b/apps/backend/lambdas/projects/controllers/members.ts @@ -30,6 +30,7 @@ export const getAssignableStaff: RouteHandler = async () => { .selectFrom('branch.users') .select(['user_id', 'name', 'email', 'profile_image']) .where('is_admin', 'is not', true) + .where('deleted_at', 'is', null) .orderBy('name', 'asc') .execute(); return json(200, { staff }); diff --git a/apps/backend/lambdas/projects/controllers/projects.ts b/apps/backend/lambdas/projects/controllers/projects.ts index 15776c9c..eb7c143c 100644 --- a/apps/backend/lambdas/projects/controllers/projects.ts +++ b/apps/backend/lambdas/projects/controllers/projects.ts @@ -6,7 +6,6 @@ import { DEFAULT_PROJECT_ROLE, ProjectValidationUtils } from '../validation-util import { requireVisibleProject } from './project-guard'; import { ADMIN_ASSIGNMENT_MESSAGE, - deleteProjectObjects, findAdminUserIds, findUnknownUserIds, isProjectActive, @@ -28,7 +27,11 @@ export const listProjects: RouteHandler = async ({ auth }) => { // plan cache whatever the caller's project count. const scope = projectScopeIds(auth.subject); - let query = db.selectFrom('branch.projects').selectAll().orderBy('project_id', 'asc'); + let query = db + .selectFrom('branch.projects') + .where('deleted_at', 'is', null) + .selectAll() + .orderBy('project_id', 'asc'); if (scope) query = query.where(sql`project_id = ANY(${scope})`); const projects = await query.execute(); @@ -61,6 +64,7 @@ export const getProject: RouteHandler = async (ctx) => { const project = await db .selectFrom('branch.projects') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); if (!project) return json(404, { message: `Project not found for id: ${projectId}` }); @@ -100,6 +104,7 @@ export const updateProject: RouteHandler = async ({ event, params, auth }) => { const existing = await db .selectFrom('branch.projects') .where('project_id', '=', Number(id)) + .where('deleted_at', 'is', null) .select(['start_date', 'end_date']) .executeTakeFirst(); if (!existing) return json(404, { message: `Project not found for id: ${id}` }); @@ -155,14 +160,8 @@ export const deleteProject: RouteHandler = async ({ params }) => { return json(404, { message: 'Project not found' }); } - // The expenditure and report rows went with the project via ON DELETE - // CASCADE, so nothing is left to tell us which files they owned. Both - // services key their objects by project id, so clear those prefixes — - // otherwise every receipt and report for the project is orphaned at once, - // which is the single largest source of unreferenced objects. - const filesDeleted = await deleteProjectObjects(Number(id)); - - return json(200, { ok: true, route: 'DELETE /projects/{projectId}', pathParams: { id }, filesDeleted }); + // Files are kept so a soft-deleted project can be restored. + return json(200, { ok: true, route: 'DELETE /projects/{projectId}', pathParams: { id } }); }; // POST /projects — admin-only via `project:create` on the route. diff --git a/apps/backend/lambdas/projects/services/projects.ts b/apps/backend/lambdas/projects/services/projects.ts index ca2c30db..9146738d 100644 --- a/apps/backend/lambdas/projects/services/projects.ts +++ b/apps/backend/lambdas/projects/services/projects.ts @@ -1,77 +1,8 @@ -import { - S3Client, - ListObjectsV2Command, - DeleteObjectsCommand, -} from '@aws-sdk/client-s3'; -import { reportError } from '@branch/lambda-http'; import type { DB } from '@branch/types'; import { db } from '@branch/store'; import { ADMIN_MEMBER_ROLE, type MemberDisplayRole } from '@branch/rbac'; import { APPROVED_EXPENDITURE_STATUS, MemberAssignment } from '../validation-utils'; -const s3 = new S3Client({ region: process.env.AWS_REGION ?? 'us-east-2' }); - -/** Deletes every object under one prefix, following pagination. */ -async function deletePrefix(bucket: string, prefix: string): Promise { - let removed = 0; - let ContinuationToken: string | undefined; - - do { - const listed = await s3.send( - new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, ContinuationToken }), - ); - const keys = (listed.Contents ?? []) - .map((o) => o.Key) - .filter((k): k is string => Boolean(k)); - - if (keys.length > 0) { - // DeleteObjects caps at 1000 keys, which is also ListObjectsV2's page - // size, so one page maps to one delete call. - await s3.send( - new DeleteObjectsCommand({ - Bucket: bucket, - Delete: { Objects: keys.map((Key) => ({ Key })), Quiet: true }, - }), - ); - removed += keys.length; - } - - // Only follow the cursor while truncated; IsTruncated false ends the loop. - ContinuationToken = listed.IsTruncated ? listed.NextContinuationToken : undefined; - } while (ContinuationToken); - - return removed; -} - -/** - * Best-effort cleanup of the files a deleted project owned. - * - * Deliberately never throws: the project is already gone by the time this runs, - * and a delete that succeeded must not be reported as a 500 because S3 was - * unreachable or the role is missing `s3:DeleteObject`. Leftover objects are - * recoverable; a project that cannot be deleted is not. - */ -export async function deleteProjectObjects(projectId: number): Promise { - // Read at call time rather than at module load: the value is then observable - // to callers that set it after import, which is what the unit tests do. - const bucket = process.env.REPORTS_BUCKET_NAME ?? ''; - if (!bucket) { - console.error('REPORTS_BUCKET_NAME is not set; leaving files for project', projectId); - return null; - } - try { - const counts = await Promise.all([ - deletePrefix(bucket, `receipts/${projectId}/`), - deletePrefix(bucket, `reports/${projectId}/`), - ]); - return counts[0] + counts[1]; - } catch (err) { - console.error('Failed to delete objects for project', projectId, err); - reportError(err, { projectId }); - return null; - } -} - /** * Path segments carrying a project id are matched with this rather than a bare * "is there a segment here" check. Without it `/projects/assignable-staff` @@ -155,6 +86,7 @@ export async function listRoster(projectId: number): Promise { .selectFrom('branch.users') .select(['user_id', 'name', 'email', 'profile_image']) .where('is_admin', 'is', true) + .where('deleted_at', 'is', null) .orderBy('name', 'asc') .execute(), db @@ -162,6 +94,7 @@ export async function listRoster(projectId: number): Promise { .innerJoin('branch.users as u', 'u.user_id', 'pm.user_id') .select(['u.user_id', 'u.name', 'u.email', 'u.profile_image', 'pm.role']) .where('pm.project_id', '=', projectId) + .where('u.deleted_at', 'is', null) .orderBy('u.name', 'asc') .execute(), ]); @@ -185,6 +118,7 @@ export async function loadAdminHeadcount(projectIds: number[]): Promise<{ .selectFrom('branch.users') .select((eb) => eb.fn.countAll().as('count')) .where('is_admin', 'is', true) + .where('deleted_at', 'is', null) .executeTakeFirst(), projectIds.length === 0 ? Promise.resolve([]) @@ -193,6 +127,7 @@ export async function loadAdminHeadcount(projectIds: number[]): Promise<{ .innerJoin('branch.users as u', 'u.user_id', 'pm.user_id') .select(['pm.project_id', (eb) => eb.fn.countAll().as('count')]) .where('u.is_admin', 'is', true) + .where('u.deleted_at', 'is', null) .where('pm.project_id', 'in', projectIds) .groupBy('pm.project_id') .execute(), @@ -213,6 +148,7 @@ export async function findAdminUserIds(members: MemberAssignment[]): Promise r.user_id)); return ids.filter((id) => !known.has(id)); diff --git a/apps/backend/lambdas/projects/test/delete-objects.unit.test.ts b/apps/backend/lambdas/projects/test/delete-objects.unit.test.ts index bbd10019..000637ae 100644 --- a/apps/backend/lambdas/projects/test/delete-objects.unit.test.ts +++ b/apps/backend/lambdas/projects/test/delete-objects.unit.test.ts @@ -1,11 +1,6 @@ /** - * DELETE /projects/{id} clears the project's files out of the bucket. - * - * The expenditure and report rows go with the project via ON DELETE CASCADE, so - * by the time the handler could look, nothing names the files any more. Both - * services key their objects by project id, so the prefixes are the only record - * left — which makes a project delete the single largest source of orphans if - * this does not run. + * DELETE /projects/{id} keeps the project's files: the delete is soft, so a + * restore must find its receipts and reports still in the bucket. */ import { describe, test, expect, beforeEach, jest } from '@jest/globals'; @@ -38,12 +33,8 @@ jest.mock('@branch/store', () => ({ const mockS3Send = jest.fn<(command: any) => Promise>(); jest.mock('@aws-sdk/client-s3', () => ({ S3Client: jest.fn().mockImplementation(() => ({ send: mockS3Send })), - ListObjectsV2Command: jest - .fn() - .mockImplementation((p: unknown) => ({ __type: 'List', ...(p as object) })), - DeleteObjectsCommand: jest - .fn() - .mockImplementation((p: unknown) => ({ __type: 'DeleteObjects', ...(p as object) })), + ListObjectsV2Command: jest.fn(), + DeleteObjectsCommand: jest.fn(), })); import { handler } from '../handler'; @@ -61,107 +52,29 @@ const adminContext = { user: { cognitoSub: 'admin-sub', userId: 1, email: 'admin@branch.org', isAdmin: true }, }; -/** Answers a List for `prefix` with `keys`, and every other List as empty. */ -function listReturns(map: Record) { - mockS3Send.mockImplementation(async (command: any) => { - if (command.__type === 'List') { - const keys = map[command.Prefix] ?? []; - return { Contents: keys.map((Key) => ({ Key })), IsTruncated: false }; - } - return {}; - }); -} - -describe('DELETE /projects/{id} object cleanup', () => { +describe('DELETE /projects/{id} keeps files', () => { beforeEach(() => { jest.clearAllMocks(); process.env.REPORTS_BUCKET_NAME = 'bucket'; mockSubject.isAdmin = true; - mockAuthenticateRequest.mockResolvedValue(adminContext as never); + mockAuthenticateRequest.mockResolvedValue(adminContext as never); mockDeleteExecute.mockResolvedValue(1n as never); }); - test('clears both the receipts and reports prefixes for that project', async () => { - listReturns({ - 'receipts/7/': ['receipts/7/a.pdf', 'receipts/7/b.pdf'], - 'reports/7/': ['reports/7/q1.docx'], - }); - + test('deletes the project without touching S3', async () => { const res = await handler(deleteEvent(7)); expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).filesDeleted).toBe(3); - - const deleted = mockS3Send.mock.calls - .map(([c]) => c) - .filter((c: any) => c.__type === 'DeleteObjects') - .flatMap((c: any) => c.Delete.Objects.map((o: any) => o.Key)); - - expect(deleted.sort()).toEqual([ - 'receipts/7/a.pdf', - 'receipts/7/b.pdf', - 'reports/7/q1.docx', - ]); - }); - - test('scopes the listing to that project, not the whole bucket', async () => { - listReturns({}); - - await handler(deleteEvent(7)); - - const prefixes = mockS3Send.mock.calls - .map(([c]) => c) - .filter((c: any) => c.__type === 'List') - .map((c: any) => c.Prefix); - - expect(prefixes.sort()).toEqual(['receipts/7/', 'reports/7/']); - }); - - test('issues no delete when the project owns no files', async () => { - listReturns({}); - - const res = await handler(deleteEvent(7)); - - expect(JSON.parse(res.body).filesDeleted).toBe(0); - expect( - mockS3Send.mock.calls.map(([c]) => c).some((c: any) => c.__type === 'DeleteObjects'), - ).toBe(false); - }); - - test('follows pagination past the 1000-key page limit', async () => { - let call = 0; - mockS3Send.mockImplementation(async (command: any) => { - if (command.__type !== 'List') return {}; - if (command.Prefix !== 'receipts/7/') return { Contents: [], IsTruncated: false }; - call += 1; - // First page is truncated, so the loop must come back with the cursor. - return call === 1 - ? { Contents: [{ Key: 'receipts/7/1.pdf' }], IsTruncated: true, NextContinuationToken: 'tok' } - : { Contents: [{ Key: 'receipts/7/2.pdf' }], IsTruncated: false }; + expect(JSON.parse(res.body)).toEqual({ + ok: true, + route: 'DELETE /projects/{projectId}', + pathParams: { id: '7' }, }); - - const res = await handler(deleteEvent(7)); - - expect(JSON.parse(res.body).filesDeleted).toBe(2); - const second = mockS3Send.mock.calls - .map(([c]) => c) - .find((c: any) => c.__type === 'List' && c.ContinuationToken === 'tok'); - expect(second).toBeDefined(); - }); - - test('a failing S3 cleanup still deletes the project', async () => { - // Leftover objects are recoverable; a project that cannot be deleted is not. - mockS3Send.mockRejectedValue(new Error('AccessDenied') as never); - - const res = await handler(deleteEvent(7)); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).filesDeleted).toBeNull(); + expect(mockS3Send).not.toHaveBeenCalled(); }); - test('touches nothing when the row was already gone', async () => { + test('404s when the row was already gone', async () => { mockDeleteExecute.mockResolvedValue(0n as never); - listReturns({ 'receipts/7/': ['receipts/7/a.pdf'] }); const res = await handler(deleteEvent(7)); @@ -175,6 +88,6 @@ describe('DELETE /projects/{id} object cleanup', () => { const res = await handler(deleteEvent(7)); expect(res.statusCode).toBe(403); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockDeleteExecute).not.toHaveBeenCalled(); }); }); diff --git a/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts b/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts index 5fdc8a8b..17fd8ed7 100644 --- a/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts @@ -46,6 +46,7 @@ async function auditRollups(client: PoolClient): Promise { COALESCE(category, '') AS cat_key, status, SUM(amount) AS total_amount, COUNT(*)::int AS expenditure_count FROM branch.expenditures + WHERE deleted_at IS NULL GROUP BY 1, 2, 3, 4 ) live USING (project_id, month, cat_key, status) WHERE er.total_amount IS DISTINCT FROM live.total_amount @@ -63,10 +64,11 @@ async function auditRollups(client: PoolClient): Promise { FULL OUTER JOIN ( SELECT p.project_id, (SELECT count(*) FROM branch.project_memberships m WHERE m.project_id = p.project_id) AS member_count, - (SELECT COALESCE(SUM(amount), 0) FROM branch.project_donations d WHERE d.project_id = p.project_id) AS total_donated, - (SELECT count(*) FROM branch.project_donations d WHERE d.project_id = p.project_id) AS donation_count, - (SELECT count(*) FROM branch.reports r WHERE r.project_id = p.project_id) AS report_count + (SELECT COALESCE(SUM(amount), 0) FROM branch.project_donations d WHERE d.project_id = p.project_id AND d.deleted_at IS NULL) AS total_donated, + (SELECT count(*) FROM branch.project_donations d WHERE d.project_id = p.project_id AND d.deleted_at IS NULL) AS donation_count, + (SELECT count(*) FROM branch.reports r WHERE r.project_id = p.project_id AND r.deleted_at IS NULL) AS report_count FROM branch.projects p + WHERE p.deleted_at IS NULL ) live USING (project_id) WHERE pr.member_count IS DISTINCT FROM live.member_count OR pr.total_donated IS DISTINCT FROM live.total_donated @@ -239,11 +241,22 @@ describe('expenditure_rollup', () => { const orphans = await client.query(` SELECT (SELECT count(*)::int FROM branch.expenditure_rollup er - LEFT JOIN branch.projects p USING (project_id) WHERE p.project_id IS NULL) AS exp_orphans, + LEFT JOIN branch.projects p ON p.project_id = er.project_id AND p.deleted_at IS NULL + WHERE p.project_id IS NULL) AS exp_orphans, (SELECT count(*)::int FROM branch.project_rollup pr - LEFT JOIN branch.projects p USING (project_id) WHERE p.project_id IS NULL) AS proj_orphans + LEFT JOIN branch.projects p ON p.project_id = pr.project_id AND p.deleted_at IS NULL + WHERE p.project_id IS NULL) AS proj_orphans `); expect(orphans.rows[0]).toEqual({ exp_orphans: 0, proj_orphans: 0 }); + + // Soft delete: the children stay, stamped. + const kept = await client.query(` + SELECT (SELECT count(*)::int FROM branch.expenditures + WHERE project_id = 4 AND deleted_at IS NOT NULL) AS expenditures, + (SELECT count(*)::int FROM branch.reports + WHERE project_id = 4 AND deleted_at IS NOT NULL) AS reports + `); + expect(kept.rows[0]).toEqual({ expenditures: 1, reports: 1 }); }); }); @@ -308,8 +321,10 @@ describe('project_rollup', () => { expect(await removeUser(4)).toBe(1n); await auditRollups(client); - const gone = await client.query('SELECT 1 FROM branch.users WHERE user_id = 4'); - expect(gone.rows).toHaveLength(0); + const gone = await client.query( + 'SELECT 1 FROM branch.users WHERE user_id = 4 AND deleted_at IS NOT NULL', + ); + expect(gone.rows).toHaveLength(1); const orphaned = await client.query( 'SELECT 1 FROM branch.project_memberships WHERE user_id = 4', ); diff --git a/apps/backend/lambdas/projects/test/rollups.e2e.test.ts b/apps/backend/lambdas/projects/test/rollups.e2e.test.ts index 32fa0fa6..5b0095d4 100644 --- a/apps/backend/lambdas/projects/test/rollups.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/rollups.e2e.test.ts @@ -81,6 +81,7 @@ async function auditRollups(client: PoolClient): Promise { COALESCE(category, '') AS cat_key, status, SUM(amount) AS total_amount, COUNT(*)::int AS expenditure_count FROM branch.expenditures + WHERE deleted_at IS NULL GROUP BY 1, 2, 3, 4 ) live USING (project_id, month, cat_key, status) WHERE er.total_amount IS DISTINCT FROM live.total_amount @@ -98,10 +99,11 @@ async function auditRollups(client: PoolClient): Promise { FULL OUTER JOIN ( SELECT p.project_id, (SELECT count(*) FROM branch.project_memberships m WHERE m.project_id = p.project_id) AS member_count, - (SELECT COALESCE(SUM(amount), 0) FROM branch.project_donations d WHERE d.project_id = p.project_id) AS total_donated, - (SELECT count(*) FROM branch.project_donations d WHERE d.project_id = p.project_id) AS donation_count, - (SELECT count(*) FROM branch.reports r WHERE r.project_id = p.project_id) AS report_count + (SELECT COALESCE(SUM(amount), 0) FROM branch.project_donations d WHERE d.project_id = p.project_id AND d.deleted_at IS NULL) AS total_donated, + (SELECT count(*) FROM branch.project_donations d WHERE d.project_id = p.project_id AND d.deleted_at IS NULL) AS donation_count, + (SELECT count(*) FROM branch.reports r WHERE r.project_id = p.project_id AND r.deleted_at IS NULL) AS report_count FROM branch.projects p + WHERE p.deleted_at IS NULL ) live USING (project_id) WHERE pr.member_count IS DISTINCT FROM live.member_count OR pr.total_donated IS DISTINCT FROM live.total_donated @@ -273,11 +275,22 @@ describe('expenditure spend reaches the dashboard', () => { const orphans = await client.query(` SELECT (SELECT count(*)::int FROM branch.expenditure_rollup er - LEFT JOIN branch.projects p USING (project_id) WHERE p.project_id IS NULL) AS exp_orphans, + LEFT JOIN branch.projects p ON p.project_id = er.project_id AND p.deleted_at IS NULL + WHERE p.project_id IS NULL) AS exp_orphans, (SELECT count(*)::int FROM branch.project_rollup pr - LEFT JOIN branch.projects p USING (project_id) WHERE p.project_id IS NULL) AS proj_orphans + LEFT JOIN branch.projects p ON p.project_id = pr.project_id AND p.deleted_at IS NULL + WHERE p.project_id IS NULL) AS proj_orphans `); expect(orphans.rows[0]).toEqual({ exp_orphans: 0, proj_orphans: 0 }); + + // Soft delete: the children stay, stamped. + const kept = await client.query(` + SELECT (SELECT count(*)::int FROM branch.expenditures + WHERE project_id = 4 AND deleted_at IS NOT NULL) AS expenditures, + (SELECT count(*)::int FROM branch.reports + WHERE project_id = 4 AND deleted_at IS NOT NULL) AS reports + `); + expect(kept.rows[0]).toEqual({ expenditures: 1, reports: 1 }); }); }); @@ -365,7 +378,7 @@ describe('rollup-backed read paths agree with the base tables', () => { test('dashboard totalSpent equals the approved sum for the year', async () => { const { rows } = await client.query(` SELECT COALESCE(SUM(amount), 0) AS total FROM branch.expenditures - WHERE status = 'approved' + WHERE status = 'approved' AND deleted_at IS NULL AND spent_on >= date_trunc('year', CURRENT_DATE) AND spent_on < date_trunc('year', CURRENT_DATE) + INTERVAL '1 year' `); @@ -376,7 +389,7 @@ describe('rollup-backed read paths agree with the base tables', () => { test('dashboard per-project spend equals the approved sum per project', async () => { const { rows } = await client.query(` SELECT project_id, SUM(amount) AS total FROM branch.expenditures - WHERE status = 'approved' GROUP BY project_id + WHERE status = 'approved' AND deleted_at IS NULL GROUP BY project_id `); const expected = new Map(rows.map((r) => [r.project_id, Number(r.total)])); @@ -391,7 +404,7 @@ describe('rollup-backed read paths agree with the base tables', () => { SELECT to_char(date_trunc('month', spent_on), 'YYYY-MM') AS month, category, SUM(amount) AS total FROM branch.expenditures - WHERE status = 'approved' AND category IS NOT NULL + WHERE status = 'approved' AND category IS NOT NULL AND deleted_at IS NULL AND spent_on >= date_trunc('year', CURRENT_DATE) AND spent_on < date_trunc('year', CURRENT_DATE) + INTERVAL '1 year' GROUP BY 1, 2 ORDER BY 1, 2 diff --git a/apps/backend/lambdas/projects/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/projects/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..e88c91b4 --- /dev/null +++ b/apps/backend/lambdas/projects/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,114 @@ +/** + * A soft-deleted row must read exactly like a hard-deleted one. Delete one of each + * kind through the store, snapshot every GET, purge the soft-deleted rows, and + * snapshot again: the two must be identical. + */ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const PATHS = [ + '/projects', + '/projects/dashboard', + '/projects/assignable-staff', + ...[1, 2, 3, 4].flatMap((id) => [ + `/projects/${id}`, + `/projects/${id}/members`, + `/projects/${id}/overview`, + `/projects/${id}/donors`, + `/projects/${id}/expenditures`, + ]), +]; + +async function snapshot(): Promise> { + const out: Record = {}; + for (const rawPath of PATHS) { + const res = await handler({ + rawPath, + requestContext: { http: { method: 'GET' } }, + headers: { Authorization: 'Bearer fake-token' }, + queryStringParameters: {}, + } as any); + out[rawPath] = { status: res.statusCode, body: res.body }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every projects GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + expect(soft[`/projects/${PARITY_DELETES.project}`].status).toBe(404); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/reports/controllers/reports.ts b/apps/backend/lambdas/reports/controllers/reports.ts index 4530b247..25e2ffb4 100644 --- a/apps/backend/lambdas/reports/controllers/reports.ts +++ b/apps/backend/lambdas/reports/controllers/reports.ts @@ -1,6 +1,6 @@ -import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'; +import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; -import { json, parseBody, reportError, serverError } from '@branch/lambda-http'; +import { json, parseBody, serverError } from '@branch/lambda-http'; import type { RouteHandler } from '@branch/lambda-http'; import { db, recordReport, removeReport } from '@branch/store'; import { @@ -37,36 +37,6 @@ type ReportType = typeof REPORT_TYPES[number]; // Numeric-only id, mirroring the old REPORT_ID_ROUTE/REPORT_DOWNLOAD_ROUTE regexes // so a non-numeric :id falls through to the same 404 as an unmatched route. -/** - * Best-effort removal of the generated file behind a deleted report. - * - * Deliberately never throws: the row is already gone by the time this runs, and - * the caller must not turn a successful delete into a 500 because S3 was - * unreachable or the role is missing `s3:DeleteObject`. A leftover object is - * recoverable; a row that cannot be deleted is not. - */ -async function deleteReportObject(objectUrl: string | null): Promise { - if (!objectUrl) return true; - const key = keyFromObjectUrl(objectUrl); - if (!key) return false; - // Read at call time rather than using the module-level BUCKET: the value is - // then observable to callers that set it after import, which is what the - // unit tests do. - const bucket = process.env.REPORTS_BUCKET_NAME ?? ''; - if (!bucket) { - console.error('REPORTS_BUCKET_NAME is not set; leaving report object', key); - return false; - } - try { - await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: key })); - return true; - } catch (err) { - console.error('Failed to delete report object', key, err); - reportError(err, { key }); - return false; - } -} - function notFoundUnlessNumericId(id: string, path: string, method: string) { return /^\d+$/.test(id) ? undefined : json(404, { message: 'Not Found', path, method }); } @@ -165,7 +135,7 @@ export const listReports: RouteHandler = async ({ event }) => { ? db.selectFrom('branch.project_rollup').where('project_id', '=', projectId).select('report_count as count').executeTakeFirst() : db.selectFrom('branch.project_rollup').select(db.fn.sum('report_count').as('count')).executeTakeFirst(); - let pageQuery = db.selectFrom('branch.reports').selectAll().orderBy('date_created', 'desc'); + let pageQuery = db.selectFrom('branch.reports').where('deleted_at', 'is', null).selectAll().orderBy('date_created', 'desc'); if (projectId !== null) pageQuery = pageQuery.where('project_id', '=', projectId); const [totalCount, reports] = await Promise.all([ @@ -183,8 +153,8 @@ export const listReports: RouteHandler = async ({ event }) => { } const reports = projectId !== null - ? await db.selectFrom('branch.reports').where('project_id', '=', projectId).selectAll().orderBy('date_created', 'desc').execute() - : await db.selectFrom('branch.reports').selectAll().orderBy('date_created', 'desc').execute(); + ? await db.selectFrom('branch.reports').where('project_id', '=', projectId).where('deleted_at', 'is', null).selectAll().orderBy('date_created', 'desc').execute() + : await db.selectFrom('branch.reports').where('deleted_at', 'is', null).selectAll().orderBy('date_created', 'desc').execute(); return json(200, { data: reports }); }; @@ -211,6 +181,7 @@ export const getUploadUrl: RouteHandler = async ({ event }) => { const projectExists = await db.selectFrom('branch.projects') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .select('project_id') .executeTakeFirst(); if (!projectExists) return json(404, { message: 'Project not found' }); @@ -250,6 +221,7 @@ export const createReport: RouteHandler = async ({ event }) => { const projectExists = await db.selectFrom('branch.projects') .where('project_id', '=', projectId as number) + .where('deleted_at', 'is', null) .select('project_id') .executeTakeFirst(); if (!projectExists) return json(404, { message: 'Project not found' }); @@ -276,7 +248,7 @@ export const downloadReport: RouteHandler = async ({ params, path, method }) => if (notFound) return notFound; const id = params.id; - const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).selectAll().executeTakeFirst(); + const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).where('deleted_at', 'is', null).selectAll().executeTakeFirst(); if (!report) return json(404, { message: 'Report not found' }); const key = keyFromObjectUrl(report.object_url); @@ -297,7 +269,7 @@ export const getReport: RouteHandler = async ({ params, path, method }) => { if (notFound) return notFound; const id = params.id; - const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).selectAll().executeTakeFirst(); + const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).where('deleted_at', 'is', null).selectAll().executeTakeFirst(); if (!report) return json(404, { message: 'Report not found' }); return json(200, { ok: true, route: 'GET /reports/{id}', pathParams: { id }, body: report }); @@ -308,7 +280,7 @@ export const deleteReport: RouteHandler = async ({ params, path, method }) => { if (notFound) return notFound; const id = params.id; - const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).selectAll().executeTakeFirst(); + const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).where('deleted_at', 'is', null).select('report_id').executeTakeFirst(); if (!report) return json(404, { message: 'Report not found' }); const deleted = await removeReport(Number(id)); @@ -316,11 +288,8 @@ export const deleteReport: RouteHandler = async ({ params, path, method }) => { return json(404, { message: 'Report not found' }); } - // After the row, never before: if the file went first and this delete - // failed, the report would be gone with a row still pointing at it. - const fileDeleted = await deleteReportObject(report.object_url); - - return json(200, { ok: true, route: 'DELETE /reports/{id}', pathParams: { id }, fileDeleted }); + // The file stays in S3 so a soft delete can be restored. + return json(200, { ok: true, route: 'DELETE /reports/{id}', pathParams: { id } }); }; async function withSizes(rows: T[]) { diff --git a/apps/backend/lambdas/reports/report-service.ts b/apps/backend/lambdas/reports/report-service.ts index 2522e5c9..03826f23 100644 --- a/apps/backend/lambdas/reports/report-service.ts +++ b/apps/backend/lambdas/reports/report-service.ts @@ -127,6 +127,7 @@ export async function fetchReportData(projectId: number): Promise + join + .onRef('branch.users.user_id', '=', 'branch.expenditures.entered_by') + .on('branch.users.deleted_at', 'is', null), + ) .where('branch.expenditures.project_id', '=', projectId) + .where('branch.expenditures.deleted_at', 'is', null) .where('branch.expenditures.status', '=', APPROVED_EXPENDITURE_STATUS) .select([ 'branch.expenditures.category', diff --git a/apps/backend/lambdas/reports/test/reports.e2e.test.ts b/apps/backend/lambdas/reports/test/reports.e2e.test.ts index 02629035..815fdf50 100644 --- a/apps/backend/lambdas/reports/test/reports.e2e.test.ts +++ b/apps/backend/lambdas/reports/test/reports.e2e.test.ts @@ -465,19 +465,34 @@ describe('Reports e2e tests', () => { }; } - test('200: admin can delete a report, removed from db', async () => { + test('200: admin can delete a report, soft-deleted in db', async () => { const res = await handler(idEvent('DELETE', 4)); expect(res.statusCode).toBe(200); const client = await pool.connect(); try { - const result = await client.query('SELECT * FROM branch.reports WHERE report_id = 4'); - expect(result.rows.length).toBe(0); + const result = await client.query('SELECT deleted_at FROM branch.reports WHERE report_id = 4'); + expect(result.rows.length).toBe(1); + expect(result.rows[0].deleted_at).not.toBeNull(); } finally { client.release(); } }); + test('a deleted report is gone from reads', async () => { + expect((await handler(idEvent('DELETE', 4))).statusCode).toBe(200); + + expect((await handler(idEvent('GET', 4))).statusCode).toBe(404); + const list = await handler({ + rawPath: '/reports', + requestContext: { http: { method: 'GET' } }, + headers: { Authorization: 'Bearer fake-token' }, + queryStringParameters: {}, + }); + const ids = JSON.parse(list.body).data.map((r: { report_id: number }) => r.report_id); + expect(ids).not.toContain(4); + }); + test('404: non-numeric id falls through to catch-all', async () => { const res = await handler(idEvent('DELETE', 'abc')); expect(res.statusCode).toBe(404); @@ -506,7 +521,7 @@ describe('Reports e2e tests', () => { const client = await pool.connect(); let totalBefore: number; try { - const result = await client.query('SELECT COUNT(*)::int AS count FROM branch.reports'); + const result = await client.query('SELECT COUNT(*)::int AS count FROM branch.reports WHERE deleted_at IS NULL'); totalBefore = result.rows[0].count; } finally { client.release(); @@ -517,25 +532,23 @@ describe('Reports e2e tests', () => { const client2 = await pool.connect(); try { - const result = await client2.query('SELECT COUNT(*)::int AS count FROM branch.reports'); + const result = await client2.query('SELECT COUNT(*)::int AS count FROM branch.reports WHERE deleted_at IS NULL'); expect(result.rows[0].count).toBe(totalBefore - 1); } finally { client2.release(); } }); - test('200: deleting a report whose object_url is not under the reports bucket still deletes the row, fileDeleted false', async () => { - // Seed report 5's object_url ('https://s3.amazonaws.com/reports/b.pdf' or - // similar legacy-style URL) may not resolve via keyFromObjectUrl against + test('200: deleting a report whose object_url is not under the reports bucket still deletes the row', async () => { + // Seed report 2's object_url may not resolve via keyFromObjectUrl against // the current REPORTS_BUCKET_NAME; either way the row must go. const res = await handler(idEvent('DELETE', 2)); expect(res.statusCode).toBe(200); - expect(typeof JSON.parse(res.body).fileDeleted).toBe('boolean'); const client = await pool.connect(); try { - const result = await client.query('SELECT * FROM branch.reports WHERE report_id = 2'); - expect(result.rows.length).toBe(0); + const result = await client.query('SELECT 1 FROM branch.reports WHERE report_id = 2 AND deleted_at IS NOT NULL'); + expect(result.rows.length).toBe(1); } finally { client.release(); } diff --git a/apps/backend/lambdas/reports/test/reports.unit.test.ts b/apps/backend/lambdas/reports/test/reports.unit.test.ts index 5d3545d8..d9650546 100644 --- a/apps/backend/lambdas/reports/test/reports.unit.test.ts +++ b/apps/backend/lambdas/reports/test/reports.unit.test.ts @@ -23,7 +23,7 @@ jest.mock('../auth', () => { ), }; }); -// Shared across instances so the delete assertions below can see the call. +// Shared across instances so the assertions below can see that a delete sends no DeleteObject. const mockS3Send = jest.fn<(command: unknown) => Promise>(); jest.mock('@aws-sdk/client-s3', () => ({ S3Client: jest.fn().mockImplementation(() => ({ send: mockS3Send })), @@ -63,6 +63,24 @@ const mockRecordReport = recordReport as jest.MockedFunction; const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; const mockReportService = reportService as jest.Mocked; + +// A query builder whose every method returns itself, so a mock does not break +// when a filter is added. +function mockQuery(result: unknown) { + const methods: Record = {}; + const builder: any = new Proxy(methods, { + get(target, prop) { + if (typeof prop !== 'string' || prop === 'then') return undefined; + if (!(prop in target)) { + target[prop] = prop === 'execute' || prop === 'executeTakeFirst' + ? jest.fn(async () => result) + : jest.fn(() => builder); + } + return target[prop]; + }, + }); + return builder; +} function getEvent(queryStringParameters?: Record) { return { rawPath: '/', @@ -280,13 +298,7 @@ describe('GET /reports unit tests', () => { describe('Response format', () => { test('200: returns data array without pagination when no params', async () => { - mockDb.selectFrom.mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue(fakeReports as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(fakeReports)); const res = await handler(getEvent()); expect(res.statusCode).toBe(200); @@ -314,22 +326,8 @@ describe('GET /reports unit tests', () => { // file_size at all, so these live under Pagination rather than Response format. describe('File sizes (paginated results only)', () => { function mockPaginatedQuery(rows: typeof fakeReports) { - mockDb.selectFrom.mockReturnValueOnce({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ count: String(rows.length) } as any), - }), - }); - mockDb.selectFrom.mockReturnValueOnce({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - limit: jest.fn().mockReturnValue({ - offset: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue(rows as any), - }), - }), - }), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery({ count: String(rows.length) })); + mockDb.selectFrom.mockReturnValueOnce(mockQuery(rows)); } test('200: each report includes file_size sourced from getObjectSize', async () => { @@ -356,23 +354,9 @@ describe('GET /reports unit tests', () => { describe('Pagination', () => { test('200: returns paginated response with page and limit', async () => { // count query - mockDb.selectFrom.mockReturnValueOnce({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ count: '3' } as any), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery({ count: '3' })); // data query - mockDb.selectFrom.mockReturnValueOnce({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - limit: jest.fn().mockReturnValue({ - offset: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue([fakeReports[0]] as any), - }), - }), - }), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery([fakeReports[0]])); const res = await handler(getEvent({ page: '1', limit: '1' })); expect(res.statusCode).toBe(200); @@ -385,13 +369,7 @@ describe('GET /reports unit tests', () => { }); test('200: only page provided returns all without pagination', async () => { - mockDb.selectFrom.mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue(fakeReports as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(fakeReports)); const res = await handler(getEvent({ page: '1' })); const json = JSON.parse(res.body); @@ -400,13 +378,7 @@ describe('GET /reports unit tests', () => { }); test('200: only limit provided returns all without pagination', async () => { - mockDb.selectFrom.mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue(fakeReports as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(fakeReports)); const res = await handler(getEvent({ limit: '2' })); const json = JSON.parse(res.body); @@ -466,13 +438,7 @@ describe('GET /reports/upload-url unit tests', () => { } function setupProjectMock(project: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(project as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery(project)); } beforeEach(() => { @@ -614,17 +580,11 @@ describe('Route precedence', () => { // the three-segment download route must be matched before the two-segment // getReport route swallows it as an id lookup with a trailing extra segment. test('GET /reports/{id}/download reaches downloadReport, not the /reports/{id} controller', async () => { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - report_id: 5, - project_id: 1, - object_url: 'https://bucket.s3.us-east-2.amazonaws.com/reports/1/gen.pdf', - } as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery({ + report_id: 5, + project_id: 1, + object_url: 'https://bucket.s3.us-east-2.amazonaws.com/reports/1/gen.pdf', + })); const res = await handler({ rawPath: '/reports/5/download', requestContext: { http: { method: 'GET' } }, @@ -658,13 +618,7 @@ describe('POST /reports unit tests', () => { } function setupProjectMock(project: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(project as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery(project)); } beforeEach(() => { @@ -807,13 +761,7 @@ describe('GET /reports/{id} unit tests', () => { }; function setupReportMock(report: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(report as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery(report)); } beforeEach(() => { @@ -906,13 +854,7 @@ describe('GET /reports/{id}/download unit tests', () => { }; function setupReportMock(report: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(report as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery(report)); } beforeEach(() => { @@ -993,13 +935,7 @@ describe('DELETE /reports/{id} unit tests', () => { }; function setupReportMock(report: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(report as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery(report)); } function setupDeleteMock(numDeletedRows: bigint) { @@ -1075,69 +1011,19 @@ describe('DELETE /reports/{id} unit tests', () => { expect(res.statusCode).toBe(403); }); - test('200: a report with no object_url deletes cleanly, fileDeleted is true, and S3 is never called', async () => { - setupReportMock({ ...fakeReport, object_url: null }); - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).fileDeleted).toBe(true); - expect(mockS3Send).not.toHaveBeenCalled(); - }); - - describe('the generated file goes with the row', () => { - const storedReport = { + // A soft delete keeps the file so the row can be restored. + test('200: the generated file is left in S3', async () => { + process.env.REPORTS_BUCKET_NAME = 'bucket'; + setupReportMock({ ...fakeReport, object_url: 'https://bucket.s3.us-east-2.amazonaws.com/reports/2/gen.pdf', - }; - - beforeEach(() => { - process.env.REPORTS_BUCKET_NAME = 'bucket'; - setupReportMock(storedReport); - mockS3Send.mockResolvedValue({}); }); - test('deletes the object behind the report', async () => { - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).fileDeleted).toBe(true); - expect(mockS3Send).toHaveBeenCalledWith( - expect.objectContaining({ - __type: 'DeleteObject', - Bucket: 'bucket', - Key: 'reports/2/gen.pdf', - }), - ); - }); - - test('a failing S3 delete still deletes the row', async () => { - // An orphaned object is recoverable; a row that cannot be deleted is - // not, so S3 trouble must not turn a successful delete into a 500. - mockS3Send.mockRejectedValue(new Error('AccessDenied')); - - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).fileDeleted).toBe(false); - }); + const res = await handler(idEvent('DELETE', '5')); - test('the row is deleted before the object', async () => { - const order: string[] = []; - mockRemoveReport.mockImplementation(async () => { - order.push('row'); - return 1n; - }); - mockS3Send.mockImplementation(async () => { - order.push('object'); - return {}; - }); - - await handler(idEvent('DELETE', '5')); - - // Reversed, a failed row delete would leave a row pointing at a file - // that no longer exists. - expect(order).toEqual(['row', 'object']); - }); + expect(res.statusCode).toBe(200); + expect(mockRemoveReport).toHaveBeenCalledWith(5); + expect(mockS3Send).not.toHaveBeenCalledWith(expect.objectContaining({ __type: 'DeleteObject' })); }); }); }); \ No newline at end of file diff --git a/apps/backend/lambdas/reports/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/reports/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..c7215cae --- /dev/null +++ b/apps/backend/lambdas/reports/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,132 @@ +/** + * A soft-deleted row must read exactly like a hard-deleted one. Delete one of each + * kind through the store, snapshot every GET, purge the soft-deleted rows, and + * snapshot again: the two must be identical. + */ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); +jest.mock('@aws-sdk/client-s3', () => ({ + S3Client: jest.fn().mockImplementation(() => ({ + send: jest.fn().mockReturnValue({} as any), + })), + PutObjectCommand: jest.fn().mockImplementation((params: unknown) => params), + GetObjectCommand: jest.fn().mockImplementation((params: unknown) => params), +})); +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockReturnValue('https://presigned.example.com/upload' as any), +})); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +process.env.REPORTS_BUCKET_NAME = 'bucket'; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const LIST_QUERIES: Record[] = [ + {}, + { page: '1', limit: '2' }, + { page: '2', limit: '2' }, + { page: '1', limit: '100' }, + ...[1, 2, 3, 4].flatMap((projectId): Record[] => [ + { projectId: String(projectId) }, + { projectId: String(projectId), page: '1', limit: '100' }, + ]), +]; + +const REQUESTS: [string, Record][] = [ + ...LIST_QUERIES.map((query): [string, Record] => ['/reports', query]), + ...[1, 2, 3, 4, 5].flatMap((id): [string, Record][] => [ + [`/reports/${id}`, {}], + [`/reports/${id}/download`, {}], + ]), +]; + +async function snapshot(): Promise> { + const out: Record = {}; + for (const [rawPath, queryStringParameters] of REQUESTS) { + const res = await handler({ + rawPath, + requestContext: { http: { method: 'GET' } }, + headers: { Authorization: 'Bearer fake-token' }, + queryStringParameters, + } as any); + out[`${rawPath}?${new URLSearchParams(queryStringParameters)}`] = { status: res.statusCode, body: res.body }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every reports GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + expect(soft[`/reports/${PARITY_DELETES.report}?`].status).toBe(404); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/users/controllers/users.ts b/apps/backend/lambdas/users/controllers/users.ts index be06bbb0..09ca441b 100644 --- a/apps/backend/lambdas/users/controllers/users.ts +++ b/apps/backend/lambdas/users/controllers/users.ts @@ -51,9 +51,14 @@ export const listUsers: RouteHandler = async ({ event }) => { // The count does not depend on the page, so both go out at once. const [totalCount, users] = await Promise.all([ - db.selectFrom('branch.users').select(db.fn.count('user_id').as('count')).executeTakeFirst(), db .selectFrom('branch.users') + .where('deleted_at', 'is', null) + .select(db.fn.count('user_id').as('count')) + .executeTakeFirst(), + db + .selectFrom('branch.users') + .where('deleted_at', 'is', null) .selectAll() .orderBy('user_id', 'asc') .limit(limit) @@ -76,6 +81,7 @@ export const listUsers: RouteHandler = async ({ event }) => { const users = await db .selectFrom('branch.users') + .where('deleted_at', 'is', null) .selectAll() .execute(); @@ -89,7 +95,7 @@ export const getUser: RouteHandler = async ({ params, auth }) => { const denied = requirePermission(auth.subject, 'profile:view', { userId: Number(userId) }); if (denied) return denied; - const user = await db.selectFrom("branch.users").where("user_id", "=", Number(userId)).selectAll().executeTakeFirst(); + const user = await db.selectFrom("branch.users").where("user_id", "=", Number(userId)).where("deleted_at", "is", null).selectAll().executeTakeFirst(); if (!user) return json(404, { message: 'User not found' }); return json(200, { @@ -214,7 +220,7 @@ export const deleteUser: RouteHandler = async ({ params }) => { const userId = params.userId; if (!/^\d+$/.test(userId)) return json(400, { message: 'userId must be a positive integer' }); - const user = await db.selectFrom('branch.users').where('user_id', '=', Number(userId)).select('email').executeTakeFirst(); + const user = await db.selectFrom('branch.users').where('user_id', '=', Number(userId)).where('deleted_at', 'is', null).select('email').executeTakeFirst(); if (!user) return json(404, { message: 'User not found' }); const deleted = await removeUser(Number(userId)); @@ -273,10 +279,11 @@ export const createUser: RouteHandler = async ({ event }) => { const isAdmin = isAdminResult.value as boolean; const profile_image = profileImageResult.value ?? undefined; - // Check if user with this email already exists in DB + // Live users only: a soft-deleted row keeps its email, and its Cognito account is gone. const existingUser = await db .selectFrom('branch.users') .where('email', '=', email) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); diff --git a/apps/backend/lambdas/users/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/users/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..5730efa2 --- /dev/null +++ b/apps/backend/lambdas/users/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,125 @@ +/** + * A soft-deleted row must read exactly like a hard-deleted one. Delete one of each + * kind through the store, snapshot every GET, purge the soft-deleted rows, and + * snapshot again: the two must be identical. + */ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('@aws-sdk/client-cognito-identity-provider', () => ({ + CognitoIdentityProviderClient: jest.fn().mockImplementation(() => ({ + send: jest.fn().mockResolvedValue({ + User: { Attributes: [{ Name: 'sub', Value: 'test-cognito-sub-123' }] }, + } as never), + })), + AdminCreateUserCommand: jest.fn().mockImplementation((args) => args), + AdminDeleteUserCommand: jest.fn().mockImplementation((args) => args), +})); + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const REQUESTS: [string, Record | null][] = [ + ['/users', null], + ['/users', { page: '1', limit: '3' }], + ['/users', { page: '2', limit: '3' }], + ['/users', { page: '1', limit: '100' }], + ...[1, 2, 3, 4, 5, 6].map((id): [string, null] => [`/users/${id}`, null]), +]; + +async function snapshot(): Promise> { + const out: Record = {}; + for (const [rawPath, queryStringParameters] of REQUESTS) { + const res = await handler({ + rawPath, + path: rawPath, + requestContext: { http: { method: 'GET' } }, + httpMethod: 'GET', + body: null, + queryStringParameters, + headers: {}, + } as any); + out[`${rawPath}?${new URLSearchParams(queryStringParameters ?? {})}`] = { + status: res.statusCode, + body: res.body, + }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every users GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + expect(soft[`/users/${PARITY_DELETES.user}?`].status).toBe(404); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/users/test/user.photos.unit.test.ts b/apps/backend/lambdas/users/test/user.photos.unit.test.ts index 8a8b2885..b34a142e 100644 --- a/apps/backend/lambdas/users/test/user.photos.unit.test.ts +++ b/apps/backend/lambdas/users/test/user.photos.unit.test.ts @@ -60,13 +60,13 @@ function mockSelfAuth(userId = 1) { } function mockUserRow(row: Record) { - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: (jest.fn() as any).mockResolvedValue(row), - }), + const chain = { + where: jest.fn().mockReturnThis(), + selectAll: jest.fn().mockReturnValue({ + executeTakeFirst: (jest.fn() as any).mockResolvedValue(row), }), - }); + }; + mockDb.selectFrom.mockReturnValue({ where: jest.fn().mockReturnValue(chain) }); } beforeEach(() => { diff --git a/apps/backend/lambdas/users/test/user.unit.test.ts b/apps/backend/lambdas/users/test/user.unit.test.ts index ae76a2de..7eb09dae 100644 --- a/apps/backend/lambdas/users/test/user.unit.test.ts +++ b/apps/backend/lambdas/users/test/user.unit.test.ts @@ -330,6 +330,7 @@ describe('POST /users unit tests', () => { // Setup mocks for successful user creation // Mock the email check to return null (user doesn't exist) const whereChain = { + where: jest.fn().mockReturnThis(), selectAll: jest.fn().mockReturnValue({ executeTakeFirst: (jest.fn() as any).mockResolvedValue(null), }), @@ -359,6 +360,7 @@ describe('POST /users unit tests', () => { test('409: POST returns 409 when user already exists', async () => { // Mock: user already exists const whereChain = { + where: jest.fn().mockReturnThis(), selectAll: jest.fn().mockReturnValue({ executeTakeFirst: (jest.fn() as any).mockResolvedValue({ user_id: 1, @@ -384,6 +386,7 @@ describe('POST /users unit tests', () => { expect(res.statusCode).toBe(409); const json = JSON.parse(res.body); expect(json).toHaveProperty('message'); + expect(whereChain.where).toHaveBeenCalledWith('deleted_at', 'is', null); }); }); }); diff --git a/apps/backend/lambdas/users/test/users.test.ts b/apps/backend/lambdas/users/test/users.test.ts index b3fc5691..6e681507 100644 --- a/apps/backend/lambdas/users/test/users.test.ts +++ b/apps/backend/lambdas/users/test/users.test.ts @@ -608,4 +608,44 @@ test("regular user cannot delete users", async () => { const res = await handler(event); expect(res.statusCode).toBe(403); -}); \ No newline at end of file +}); +test("POST user succeeds for the email of a deleted user, which keeps its row", async () => { + mockAdminAuth(); + + const del = await handler(createEvent({ method: 'DELETE', path: '/2' })); + expect(del.statusCode).toBe(200); + + const res = await handler(createEvent({ + method: 'POST', + path: '/users', + body: { name: "Renee Again", email: "renee@branch.org", isAdmin: false }, + })); + expect(res.statusCode).toBe(201); + expect(JSON.parse(res.body).body.email).toBe("renee@branch.org"); + + const client = await pool.connect(); + try { + const old = await client.query('SELECT email, deleted_at FROM branch.users WHERE user_id = 2'); + expect(old.rows[0].email).toBe('renee@branch.org'); + expect(old.rows[0].deleted_at).not.toBeNull(); + const live = await client.query( + "SELECT user_id FROM branch.users WHERE email = 'renee@branch.org' AND deleted_at IS NULL", + ); + expect(live.rows).toHaveLength(1); + expect(live.rows[0].user_id).not.toBe(2); + } finally { + client.release(); + } +}); + +test("POST user 409 when a live user has the email", async () => { + mockAdminAuth(); + + const res = await handler(createEvent({ + method: 'POST', + path: '/users', + body: { name: "Sam Again", email: "sam@branch.org", isAdmin: false }, + })); + expect(res.statusCode).toBe(409); + expect(JSON.parse(res.body).message).toBe('User with this email already exists'); +}); diff --git a/apps/frontend/AGENTS.md b/apps/frontend/AGENTS.md index f6bf8e7f..7fe2ef4f 100644 --- a/apps/frontend/AGENTS.md +++ b/apps/frontend/AGENTS.md @@ -107,7 +107,7 @@ The animations live in `globals.css` (`.branch-spinner`, `.branch-skeleton`, and **Popovers — `hooks/useAnchoredPopover.ts`.** Anything that floats next to a trigger (`DatePickerField`, `StaffPicker`) goes through this hook. The caller owns the open state and passes it in with `onDismiss` and an `estimatedHeight`; the hook returns `{ anchorRef, popoverRef, boundaryRef, position }`, where `position` is viewport coordinates to spread onto a `position: fixed` panel. It flips above the anchor when the viewport would clip it, repositions on scroll and resize, and dismisses on outside-click and `Escape`. Render the panel through `createPortal` into `document.body` — a popover left in normal flow is clipped by the modal body's scroll container, which is the bug this hook exists to prevent. -**Deletes — `components/ConfirmDeleteDialog.tsx` + `components/RowDeleteButton.tsx`.** No destructive action goes straight to the API. The dialog owns its own in-flight and error state: pass an `onConfirm` that returns a promise and it closes on success, or stays open and shows the reason on rejection — so the page never needs its own "failed to delete" banner. Give it `consequences` whenever the delete cascades; every foreign key in the schema is `ON DELETE CASCADE`, so deleting a project also destroys its expenses, donations, memberships and reports, and the user has to be told before it happens, not after. `requireTypedConfirmation` gates the confirm button behind retyping the record's name — use it where the cascade reaches financial history. `RowDeleteButton` is the icon-only trash for a table row or card; it stops click propagation, because every list that has row actions also has an `onRowClick` that opens the record. +**Deletes — `components/ConfirmDeleteDialog.tsx` + `components/RowDeleteButton.tsx`.** No destructive action goes straight to the API. The dialog owns its own in-flight and error state: pass an `onConfirm` that returns a promise and it closes on success, or stays open and shows the reason on rejection — so the page never needs its own "failed to delete" banner. Give it `consequences` whenever the delete reaches other records: deleting a project also removes its expenses, donations, memberships and reports, and a donor takes its donations, so the user has to be told before it happens, not after. Deletes are soft on the backend (rows are kept with `deleted_at`, recoverable by SQL only), but the UI treats them as gone. `requireTypedConfirmation` gates the confirm button behind retyping the record's name — use it where the cascade reaches financial history. `RowDeleteButton` is the icon-only trash for a table row or card; it stops click propagation, because every list that has row actions also has an `onRowClick` that opens the record. Gate the affordance on the same rule the backend enforces, not a looser one — deleting a project is admin-only (`projects/auth.ts`), which is narrower than the `canEdit` that governs the Edit button. diff --git a/apps/frontend/src/app/components/ConfirmDeleteDialog.tsx b/apps/frontend/src/app/components/ConfirmDeleteDialog.tsx index b2b5df00..7b4adc05 100644 --- a/apps/frontend/src/app/components/ConfirmDeleteDialog.tsx +++ b/apps/frontend/src/app/components/ConfirmDeleteDialog.tsx @@ -16,14 +16,14 @@ interface ConfirmDeleteDialogProps { /** The record being removed, echoed back so the user can check the row. */ itemName?: string; /** - * What else disappears. Every foreign key in the schema is ON DELETE CASCADE, - * so a delete here can take rows the user never sees — say so explicitly. + * What else disappears. A delete here can take rows the user never sees + * (a project's expenses, a donor's donations) — say so explicitly. */ consequences?: React.ReactNode; confirmLabel?: string; /** * Gate the confirm button behind retyping `itemName`. For deletes that - * cascade into financial history, where a misclick is unrecoverable. + * reach into financial history, where a misclick is costly to undo. */ requireTypedConfirmation?: boolean; } diff --git a/apps/frontend/src/app/projects/ProjectDetailView.tsx b/apps/frontend/src/app/projects/ProjectDetailView.tsx index ac743e60..851d95d3 100644 --- a/apps/frontend/src/app/projects/ProjectDetailView.tsx +++ b/apps/frontend/src/app/projects/ProjectDetailView.tsx @@ -106,9 +106,9 @@ export default function ProjectDetailView({ id }: { id: string }) { Edit Project )} - {/* Deleting a project cascades to its memberships, donations, - expenditures and reports, so it is its own permission even - though both currently resolve to admin. */} + {/* Deleting a project takes its memberships, donations, + expenditures and reports with it, so it is its own permission + even though both currently resolve to admin. */} {can('project:delete') && (