Skip to content

fix(privacy): carry out account deletion requests after a 14-day grace period, with cancel (#1313) - #1320

Merged
thinkclay merged 4 commits into
mainfrom
fix/1313-account-deletion
Oct 18, 2026
Merged

thinkclay merged 4 commits into
mainfrom
fix/1313-account-deletion

Conversation

@thinkclay

Copy link
Copy Markdown
Contributor

Fixes #1313

Account deletion requests are now carried out. A request waits out a 14-day grace period, during which the user can sign in and cancel. After that a daily job deletes the account, keeps the legally retained records with the person's id removed, and emails a confirmation. That always lands inside the 30 days that Settings, the FAQ and the privacy policy promise.

Found on the way: no request has ever been recorded. POST /v1/account-deletion/worker answered 401 to every signed-in user, because nothing on its path set supabaseAdmin (requireAuth only). That explains why core.account_deletions is empty on all three projects. It is fixed here, and the gated REST test shows it red against the current runtime and green against this branch.

What changed

Database (migrations 390, 391; local only, not applied anywhere else)

390 account_deletions

  • New columns: scheduled_for, cancelled_at, attempts, last_attempt_at, plus a 'cancelled' status.
  • scheduled_for is set by an insert trigger from core.account_deletion_grace_period() (14 days). That function is the only place the grace period lives.
  • A client inserting through the 130 insert policy cannot set its own date or status.
  • A unique index allows one open request per worker.

390 blocking foreign keys

Each foreign key is looked up by column, not by name, so an environment that skipped a migration does not fail.

  • SET NULL. Each of these columns records who acted on a row that belongs to someone else, so the row stays and the pointer is cleared:
    • account_deletions.requested_by_user_id
    • organization_payment_methods.created_by
    • credit_ledger.created_by
    • hire_agreements.agreed_by_user_id
    • api_keys.created_by (now nullable)
    • public.webhooks.created_by and public.webhooks.updated_by
    • application_activity.actor_user_id
    • privacy_data_requests.processed_by
    • eeo_reports.generated_by
    • hiring_projects.created_by
    • hiring_project_crew.assigned_by
    • interview_slots.proposed_by (now nullable)
    • scheduling_links.created_by (now nullable)
    • hris_connections.created_by
    • background_check_providers.created_by
    • user_skills.verified_by, work_logs.verified_by_user_id and skill_evidence.verified_by
  • CASCADE. These rows are the person's own and mean nothing without them: hiring_project_crew.user_id, interview_bookings.candidate_id.
  • inquiry_audit_log.actor_id is now nullable. It was NOT NULL with ON DELETE SET NULL, so deleting anyone who had acted on another person's inquiry raised an error. The test reproduces this before the migration.
  • RESTRICT references are left as they are, and treated as blockers: tasks, punchlists, organization documents / versions / shares / folders, organization locations and projects.created_by. These are content other people depend on.
  • After 390, pg_constraint shows no NO ACTION reference to a user and no NOT NULL + SET NULL pair. Only those RESTRICT ones remain.

390 service-only helpers

Each is SECURITY DEFINER, uses search_path = '', is revoked from PUBLIC/anon/authenticated and granted to service_role.

  • claim_due_account_deletions: UPDATE … RETURNING over FOR UPDATE SKIP LOCKED. Retries wait 12 hours, and a row stuck in_progress is reclaimed after 1 hour. It never claims organization requests.
  • account_deletion_storage_objects: lists a user's storage objects.
  • account_deletion_purge_unlinked: clears rows that carry the user's id with no foreign key: archived_notifications, inquiry_comments.read_by and organization_audit_log.actor_email.
  • 390 also revokes client EXECUTE on anonymize_worker_payment_data.

391

  • core.run_account_deletion_processor() follows 377's pattern: it reads Vault and raises if a secret is missing.
  • pg_cron job account-deletion-process runs daily at 15 6 * * *.

Shared deletion core

_shared/user-deletion.ts holds findDeletionBlockers, releaseNullableReferences and deleteAuthUser, extracted from DELETE /v1/office/users/:id.

  • The office route's responses are unchanged: 409 with blockedBy, 500 on a failed delete, and still 500 for an id that does not exist.
  • projects.created_by is added to the blockers. That case used to 500 with an FK error.
  • The pinned source test now follows the code into the shared module. It also pins that the processor checks blockers before its first write.

Edge function account-deletion-process

  • Service-bearer only. Runs up to 25 requests in a 45 s budget, one claim at a time. It takes an optional ids to re-run named requests, which are still only ones past their date.
  • Steps, in order (_shared/account-deletion/process.ts):
    1. Blockers. If anything blocks, the request is marked failed, the blocking tables are named, and nothing else is written.
    2. Detach payment, background-check and ID-verification rows (anonymize_worker_payment_data).
    3. Purge rows that have no foreign key.
    4. Remove storage objects, then check again that none are left.
    5. Release verification pointers.
    6. Delete the auth user.
    7. Send the confirmation email through the existing Resend adapter. The address is read before step 6 and held in memory only.
  • Each step records itself in compliance_log.steps, so a retry only redoes what did not finish. The log holds counts and timestamps only; the test asserts it contains neither the email nor the user id.
  • Final status: completed, failed (stopped before anything was deleted, so the user can still cancel) or partial (stopped after a deletion). error_message is set for the last two. Retries continue up to 5 attempts.
  • Retention choices are in one file, _shared/account-deletion/policy.ts (buckets). The tables kept come from anonymize_worker_payment_data, which that file names.
  • Organization deletions are recorded but not carried out. Deleting an organization needs product decisions about its members, its Stripe customer and its documents. They show in the office list as needsManualHandling. The org panel's "All members will be notified" was false, and now says the team will carry it out within 30 days.
  • The processor also refuses to delete an organization's owner. That would leave an organization nobody can administer. The office route still allows it.

API

  • POST /v1/account-deletion/worker
    • Fixed the 401.
    • Returns scheduledFor and canCancel.
    • Idempotent: a second request returns the one already open.
  • GET /v1/account-deletion/status (new): the signed-in user's open request, or null.
  • POST /v1/account-deletion/cancel (new): one conditional UPDATE, so it can never race the processor's claim. Answers 404 when there is nothing to cancel, and 409 when deletion is already under way.
  • GET /v1/office/account-deletions?filter=attention|all (new, office role): failed, partial, overdue (past 30 days) and organization requests.

SDK (Scaffald/sdk#37, pointer bumped to that branch)

accountDeletion.getStatus(), cancel() and listForOffice(), with MSW tests. Merge #37 first, then re-point the submodule to sdk main.

App

  • PendingDeletionNotice: on sign-in, a modal reads "Your account is scheduled for deletion on " with Cancel deletion and Close.
    • It is mounted in (protected)/_layout.tsx as a sibling of <Slot />, never in place of it.
    • It waits until the gate's loading overlay is gone.
  • Settings → Account (AccountDeletionPanel):
    • A pending request shows its date and Cancel instead of the request button.
    • Copy now matches the job: deleted after 14 days, cancellable until then, payment and background-check records detached.
  • Support FAQ: adds the 14-day wait and how to cancel ("always within 30 days").
  • The privacy and terms pages are still accurate and are unchanged.
  • The copy logic is in features/profile/utils/scheduledDeletion.ts, with a vitest test.

How I verified (all local)

  • Red before.
    • Processor test before 390: fails on the missing schema.
    • Deleting the seeded subject before 390 raised null value in column "actor_id" of relation "inquiry_audit_log".
    • REST test against the current shared runtime: POST /worker → {"error":"Unauthorized"} for a signed-in user.
  • Green after.
    • tests/routers/account-deletion-process.test.ts (6/6) seeds a real user with: profile, csi skill, application, application message, notification, archived notification, an inquiry_audit_log row on someone else's inquiry, a background check, a payment transaction, avatar / resume / background-check-report files, and a task blocker. It asserts:
      • The blocked request fails with nothing written.
      • After the blocker is removed and a day passes, the request completes.
      • The auth user and core rows are gone; storage under {uid}/ is empty except background-check-documents.
      • The payment and background-check rows are kept with a null user id, and the audit row is kept with a null actor.
      • account_deletions keeps both user ids null and a PII-free log.
      • One confirmation email goes to the right address (Resend faked, as a third party).
      • A second run is a no-op.
      • Not-before-scheduled_for and cancel-during-grace are covered.
    • account-deletion-rest.test.ts (9/9) covers request, idempotency, status, cancel and its 404/409 cases, cross-user isolation, the trigger ignoring a client-sent date and status, anon 401, and the office list with a worker refused.
    • office-users-delete-rest.test.ts (1/1): 409 with blockedBy, then success.
    • All three are added to GATED.txt.
  • Other checks.
    • node scripts/check-migrations.mjs passes.
    • node scripts/db/security-fingerprint.mjs check local: 0 new, 0 stale. Privileges checked on the objects with has_function_privilege.
    • 390 re-applied cleanly (idempotent).
    • The related gated suites (rls-matrix, schema-regression, db-access-hardening, payments-settlement) pass: 68/68.
    • deno fmt --check and deno lint pass in functions/api, and deno check passes on the new function and routes.
    • The api static tests pass, including the pinned deletion test.
    • tsc for scf-core and the app: 0 errors. nx run scf-core:test: 1631 passed, 0 failed.
    • pnpm prepush passes. Its gated tests ran against this branch's api, served on :8313, because the shared edge runtime serves another checkout.
  • Not verified: the modal and panel were not checked in a browser. I could not add a preview config from this worktree, so the UI is covered by typecheck and the copy unit test only.

Deploy steps

For each env, in this order: dev, then preview, then prod. Nothing here has been applied or deployed.

  1. Prerequisite (Vault): edge_functions_url and service_role_key must exist in Vault. They already do for the 337/362/377 crons, and 391's wrapper raises if they are missing. The service-role key must match the project's runtime key format (see fix(dev): migration 337 cannot be applied — dev is missing both vault secrets the notification cron depends on #564). RESEND_API_KEY must be set for the confirmation email; without it the deletion still completes and the log records the email as not sent.
  2. Apply 390_account_deletion_processing.sql, then 391_account_deletion_cron.sql (scripts/apply-migration.sh <env> …).
    • The renumber rule applies: if anything ≥ 390 lands first, these move above it.
    • Then check the objects, not the ledger: node scripts/db/security-fingerprint.mjs check <env> and select jobname, schedule from cron.job where jobname = 'account-deletion-process'.
  3. Deploy the functions with scripts/deploy-functions.sh <env>. It now includes account-deletion-process and ships api, which carries the new routes and the 401 fix.
  4. Ship the app web build and the iOS build so users get the sign-in notice and the Settings cancel.
  5. Merge feat(account-deletion): getStatus(), cancel() and listForOffice() (Scaffald/SaaS#1313) sdk#37 and re-point packages/sdk to sdk main before this merges.
  6. Optional smoke test on dev: select core.run_account_deletion_processor(); then read net._http_response. It should be a 200 with claimed: 0.

Needs legal sign-off

These are the working line Clay set on 2026-10-18 and may change. To change them, edit _shared/account-deletion/policy.ts (buckets) or core.anonymize_worker_payment_data (tables).

  • Kept, user id cleared:
    • payment_transactions.user_id
    • success_fees.worker_user_id
    • background_checks.user_id
    • background_check_consent.worker_user_id
    • background_check_disputes.user_id
    • id_verifications.worker_user_id
  • These kept rows still hold content tied to the person:
    • background_checks: consent IP and user agent, consent signature, findings and summary, and encrypted results.
    • background_check_consent: IP and user agent.
    • id_verifications.verification_data (the Persona payload).
    • None of these are scrubbed.
  • Kept files: background-check-documents/{uid}/… (background-check report files), until the FCRA retention period is confirmed.
  • Kept, detached:
    • hire_agreements (agreed_by cleared)
    • organization_audit_log (actor and actor email cleared)
    • inquiry_audit_log (actor cleared)
    • application_activity, circumvention_reports, content_reports and oauth_app_audit_log (actor or user cleared)
    • The account_deletions row itself, including the free-text reason the user typed
  • Deleted: everything else.
    • Through the auth cascade: profile, skills, education, experience, certifications, applications, application messages, notifications, notification devices and preferences, work logs, reviews, connections, EEO self-identification, privacy/CCPA requests, OAuth tokens, community and engagement rows, interview bookings and crew places.
    • By the processor: archived notifications, inquiry read receipts, and the user's files in avatars, certifications, portfolio, resumes, work-log photos and exports, feedback screenshots, application attachments and community media.
  • Not touched, and needs a decision:
    • Legacy public.consent_records, public.audit_log and public.privacy_requests. They are keyed by user id with no foreign key; they may be compliance evidence or may be dead tables.
    • oauth_apps.owner_email.
  • Stripe: workers have no stored Stripe customer, so the worker path has nothing to clean up. The organization path (detaching payment methods and deleting the customer) is not implemented, because organization requests are handled by hand.

🤖 Generated with Claude Code

…e period, with cancel (#1313)

A deletion request was a 'pending' row nothing read. It was in fact never
written: POST /v1/account-deletion/worker answered 401 to every signed-in
user because nothing on its path set supabaseAdmin. Now:

- Migration 390: account_deletions gains scheduled_for (requested_at + 14
  days, set by trigger, never by the client), cancelled_at, attempts,
  last_attempt_at and a 'cancelled' status, with one open request per
  worker. Every NO ACTION reference to a user becomes SET NULL (or CASCADE
  for a crew place and an interview booking), and inquiry_audit_log.actor_id
  is nullable, so the delete no longer fails on them. RESTRICT references
  stay as deliberate blockers. Service-only helpers: claim (SKIP LOCKED,
  retry delay), storage listing, purge of rows with no FK.
- Migration 391: daily pg_cron at 06:15 UTC through a Vault-reading wrapper
  that raises when a secret is missing (377's pattern).
- _shared/user-deletion.ts: the blocker check, reference release and delete,
  extracted from the office route, which keeps its behaviour (projects is
  now a blocker too; it used to 500).
- account-deletion-process function + _shared/account-deletion: claim,
  blockers first, detach payment/background-check/ID rows, purge rows with
  no FK, remove files from every user-keyed bucket except
  background-check-documents, delete the auth user, send a confirmation
  email. Per-step flags in compliance_log (no PII); completed/partial/failed.
  Organization requests are left for manual handling.
- API: GET /status and POST /cancel for the user; GET
  /v1/office/account-deletions for office.
- App: a sign-in notice with the date and Cancel; the Settings panel shows a
  pending request; FAQ and org-deletion copy corrected.
- Gated tests: processor against real DB/storage, REST routes, office delete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… ratchet back within baseline

- Regenerate types.ts (CI: "types.ts is stale").
- scheduled_for gets DEFAULT 'infinity', which the insert trigger reads as
  not given, so generated Insert types no longer require it. The two
  existing inserts (api route, legacy tRPC router) type-check again.
- process.ts narrows result unions with `ok === false`: the shared
  functions/deno.json is not strict, so `!x.ok` did not narrow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@thinkclay

Copy link
Copy Markdown
Contributor Author

CI fix pushed (19de233):

  • types.ts regenerated for migrations 390/391.
  • scheduled_for defaults to 'infinity'. The insert trigger reads that as "not given" and sets it to requested_at + 14 days. Explicit values from the service role still win, so the processor and REST tests that backdate requests behave as before. A NOT NULL column with no default is required in the generated Insert types, which put two new errors in the legacy tRPC router and masked two in the api route.
  • process.ts narrows with ok === false, because the shared functions/deno.json isn't strict.

Migration 390 is amended in place: it hasn't been applied anywhere remote. Locally, the processor suite passes 6/6 and the edge type ratchet is within baseline.

@github-actions

Copy link
Copy Markdown
Contributor

📊 Performance Benchmark Results

    CPU | Intel(R) Xeon(R) Platinum 8370C CPU @ 2.80GHz
Runtime | Deno 2.9.7 (x86_64-unknown-linux-gnu)

file:///home/runner/work/SaaS/SaaS/packages/supabase/functions/api/__tests__/benchmarks/rest-vs-trpc.bench.ts

| benchmark                                     | time/iter (avg) |        iter/s |      (min … max)      |      p75 |      p99 |     p995 |
| --------------------------------------------- | --------------- | ------------- | --------------------- | -------- | -------- | -------- |

group jobs-list
REST: GET /v1/jobs (paginated list):   → Average response time: 14.12ms
REST: GET /v1/jobs (paginated list):   → Average response time: 14.28ms
REST: GET /v1/jobs (paginated list):   → Average response time: 13.74ms
REST: GET /v1/jobs (paginated list):   → Average response time: 12.39ms
REST: GET /v1/jobs (paginated list):   → Average response time: 13.86ms
| REST: GET /v1/jobs (paginated list)           |           1.5 s |           0.7 | (   1.4 s …    1.5 s) |    1.5 s |    1.5 s |    1.5 s |

group job-details
REST: GET /v1/jobs/:id (single job):   → Average response time: 12.33ms
REST: GET /v1/jobs/:id (single job):   → Average response time: 12.13ms
REST: GET /v1/jobs/:id (single job):   → Average response time: 12.07ms
REST: GET /v1/jobs/:id (single job):   → Average response time: 14.03ms
REST: GET /v1/jobs/:id (single job):   → Average response time: 12.70ms
| REST: GET /v1/jobs/:id (single job)           |           1.4 s |           0.7 | (   1.4 s …    1.4 s) |    1.4 s |    1.4 s |    1.4 s |

group application-create
REST: POST /v1/applications (create):   → Average response time: 30.20ms
REST: POST /v1/applications (create):   → Average response time: 11.76ms
REST: POST /v1/applications (create):   → Average response time: 11.73ms
REST: POST /v1/applications (create):   → Average response time: 11.54ms
REST: POST /v1/applications (create):   → Average response time: 11.84ms
| REST: POST /v1/applications (create)          |           1.7 s |           0.6 | (   1.7 s …    1.7 s) |    1.7 s |    1.7 s |    1.7 s |

group concurrency
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 35.38 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 282.67ms
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 180.92 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 55.27ms
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 178.62 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 55.98ms
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 149.70 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 66.80ms
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 178.17 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 56.13ms
| REST: Concurrent GET /v1/jobs (10 parallel)   |           2.1 s |           0.5 | (   2.0 s …    2.2 s) |    2.1 s |    2.2 s |    2.2 s |

group filtered-queries
REST: GET /v1/jobs with multiple filters:   → Average response time: 13.35ms
REST: GET /v1/jobs with multiple filters:   → Average response time: 13.00ms
REST: GET /v1/jobs with multiple filters:   → Average response time: 12.74ms
REST: GET /v1/jobs with multiple filters:   → Average response time: 11.72ms
REST: GET /v1/jobs with multiple filters:   → Average response time: 13.27ms
| REST: GET /v1/jobs with multiple filters      |           1.5 s |           0.7 | (   1.5 s …    1.5 s) |    1.5 s |    1.5 s |    1.5 s |


@github-actions

Copy link
Copy Markdown
Contributor

📊 Performance Benchmark Results

    CPU | INTEL(R) XEON(R) PLATINUM 8573C
Runtime | Deno 2.9.7 (x86_64-unknown-linux-gnu)

file:///home/runner/work/SaaS/SaaS/packages/supabase/functions/api/__tests__/benchmarks/rest-vs-trpc.bench.ts

| benchmark                                     | time/iter (avg) |        iter/s |      (min … max)      |      p75 |      p99 |     p995 |
| --------------------------------------------- | --------------- | ------------- | --------------------- | -------- | -------- | -------- |

group jobs-list
REST: GET /v1/jobs (paginated list):   → Average response time: 13.41ms
REST: GET /v1/jobs (paginated list):   → Average response time: 13.47ms
REST: GET /v1/jobs (paginated list):   → Average response time: 14.27ms
REST: GET /v1/jobs (paginated list):   → Average response time: 15.79ms
REST: GET /v1/jobs (paginated list):   → Average response time: 14.52ms
| REST: GET /v1/jobs (paginated list)           |           1.5 s |           0.7 | (   1.5 s …    1.5 s) |    1.5 s |    1.5 s |    1.5 s |

group job-details
REST: GET /v1/jobs/:id (single job):   → Average response time: 12.35ms
REST: GET /v1/jobs/:id (single job):   → Average response time: 12.87ms
REST: GET /v1/jobs/:id (single job):   → Average response time: 13.66ms
REST: GET /v1/jobs/:id (single job):   → Average response time: 13.92ms
REST: GET /v1/jobs/:id (single job):   → Average response time: 12.90ms
| REST: GET /v1/jobs/:id (single job)           |           1.5 s |           0.7 | (   1.4 s …    1.5 s) |    1.5 s |    1.5 s |    1.5 s |

group application-create
REST: POST /v1/applications (create):   → Average response time: 30.80ms
REST: POST /v1/applications (create):   → Average response time: 13.59ms
REST: POST /v1/applications (create):   → Average response time: 12.28ms
REST: POST /v1/applications (create):   → Average response time: 10.82ms
REST: POST /v1/applications (create):   → Average response time: 11.89ms
| REST: POST /v1/applications (create)          |           1.7 s |           0.6 | (   1.7 s …    1.8 s) |    1.7 s |    1.8 s |    1.8 s |

group concurrency
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 35.62 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 280.72ms
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 175.46 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 56.99ms
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 173.34 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 57.69ms
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 153.02 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 65.35ms
REST: Concurrent GET /v1/jobs (10 parallel):   → Throughput: 194.58 req/s
REST: Concurrent GET /v1/jobs (10 parallel):   → Average time per batch: 51.39ms
| REST: Concurrent GET /v1/jobs (10 parallel)   |           2.1 s |           0.5 | (   2.0 s …    2.2 s) |    2.1 s |    2.2 s |    2.2 s |

group filtered-queries
REST: GET /v1/jobs with multiple filters:   → Average response time: 15.19ms
REST: GET /v1/jobs with multiple filters:   → Average response time: 13.32ms
REST: GET /v1/jobs with multiple filters:   → Average response time: 11.82ms
REST: GET /v1/jobs with multiple filters:   → Average response time: 13.84ms
REST: GET /v1/jobs with multiple filters:   → Average response time: 13.87ms
| REST: GET /v1/jobs with multiple filters      |           1.5 s |           0.7 | (   1.5 s …    1.6 s) |    1.5 s |    1.6 s |    1.6 s |


@thinkclay
thinkclay merged commit fe6d3bd into main Oct 18, 2026
19 checks passed
@thinkclay
thinkclay deleted the fix/1313-account-deletion branch October 18, 2026 19:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(privacy): account deletion requests are recorded but never carried out, while the app promises completion within 30 days

1 participant