Skip to content

fix(platform): atomic hold-aware org deletion, immutable slug - #3162

Merged
larryro merged 4 commits into
mainfrom
fix/org-lifecycle-integrity
Sep 3, 2026
Merged

larryro merged 4 commits into
mainfrom
fix/org-lifecycle-integrity

Conversation

@larryro

@larryro larryro commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

The invariant

"Delete my organization" either fully completes or changes nothing visible; data under a legal hold cannot be deleted; renaming an organization never loses its files.

Before: deletion was client-orchestrated — POST /organizations/:id/prepare-deletion committed the organization_deleted audit row, deleted the org's app.user_preferences and enqueued the config-tree rm -rf in its own transaction, and only then did the browser call Better Auth's organization.delete. A failed or missing second call left a live organization gutted with a false deletion audit; the raw Better Auth door itself deleted with no hold check, no audit and orphaned app state. The legal-hold guard was a stale TODO. And beforeUpdateOrganization applied slug renames with no compensation although the slug is the tenant key of every blob (s3KeyBelongsToOrg), the config tree ($TALE_CONFIG_DIR/<slug>) and the knowledge corpora.

Per finding

1. prepare-deletion destroys org config and preferences before the org is actually deleted — fixed

  • The app now owns the single deletion door, POST /api/app/organizations/:id/delete, as one serializable transaction (deleteOrganization): every guard first — membership, owner role, default-org protection, legal holds — with nothing written until all pass; then the audit row (while the actor's membership still exists), the per-user cascade (user_preferences, memories, lastActiveOrganizationId and session.activeOrganizationId pointers), Better Auth's rows leaf-first (teamMember, team, invitation, member, organization), and the org.cleanup_files job enqueued through the same transaction (addJobInTx) — the job exists only if the deletion committed.
  • Better Auth's own /organization/delete is closed (disableOrganizationDeletion: true → 404 ORGANIZATION_DELETION_DISABLED), so no second door bypasses the gate. On base that door returned 200 and removed the org, members and teams while leaving user_preferences and the config tree behind; it also stranded team/teamMember rows — the app door removes them.
  • The cleanup job re-checks that no live organization still owns the slug before removing a tree (stale job from an older release, or the slug re-taken by a new org). On base a queued cleanup removed a live organization's config tree.
  • Client: one call; errorToast: false so the hook owns feedback (the previous flow double-toasted); the hold refusal maps to a translated, actionable line (settings.organization.deleteBlockedByLegalHold, en/de/fr).
  • Tests: domains/organizations/service.test.ts (recording tx) — a refusal under either hold issues zero writes and no job; non-owner/stranger/default-org refused before any write; the happy path's order is guards → audit → cascade → Better Auth rows → org row → job, every write bound to the org id, "user" never deleted from; a lost delete race throws so the tx rolls back. Integration (checkOrganizationLifecycle): aborted teardown transaction leaves rows/audit/jobs untouched; the committed delete removes rows, writes the audit row (actor_role=owner, slug in metadata), cascades preferences/pointers/teams, drops the config tree; a queued cleanup for a live org's slug leaves its tree alone.
  • User/compliance impact: a failed delete can no longer strip a live org of its config, preferences and personalization or leave a false organization_deleted audit row. Old SPAs mid-rollout calling prepare-deletion/Better Auth delete get 404s and nothing is destroyed (fail-safe direction).

2. Org deletion bypasses legal holds — fixed

  • describeOrganizationHoldBlock(loadActiveHolds(tx, orgId)) at the door: an org-wide hold or any custodian (userMembership) hold refuses with 409 LEGAL_HOLD_ACTIVE and an actionable message (the whole tenant is what a deletion would destroy, so both granularities the schema supports block). Same LegalHoldError the other destructive paths throw; the route returns { error, message }.
  • Tests: unit (verdict per granularity + zero-write refusal), integration (custodian hold → 409, org intact; org-wide hold → 409, org intact; on base both answered 404 — no gate existed).
  • User/compliance impact: an owner can no longer destroy evidence under an active hold (spoliation guard). Docs: legal-hold.md (en/de/fr) names the block.

3. Org slug rename strands blobs, config tree, corpus — fixed (refuse with reason)

  • The slug is immutable once set: beforeUpdateOrganization classifies the update (classifyOrgSlugUpdate): rename → 400 The organization slug cannot be changed: files, configuration and knowledge are stored under it. Create a new organization instead.; unchanged (re-sent beside a name change) and initial (a slug-less org receiving its first) still land; fail-closed when the org can't be identified.
  • Real user impact sized: the settings form only ever sends name + metadata (organization-settings.tsx), so the UI never exposed slug rename — the only path was the raw /api/auth/organization/update API. Refusing is honest: rename-with-data was never supported (no blob re-keying, no config move, no corpus re-scope exists), and a full migration would need a compensating multi-store transaction the codebase has no primitive for.
  • Tests: unit (org-slug.test.ts), integration (rename → 400, slug and config tree unchanged — on base the rename was applied, slug=…-moved with the tree still at the old slug; unchanged slug + new name → 200).

Gates (observed)

Gate Branch Base (the five source files swapped to main, same harness/tests, fresh stack)
bunx tsc --noEmit (platform) exit 0 —
bunx oxlint --type-aware (touched files) exit 0 —
new unit tests (service.test.ts, org-slug.test.ts) 14/14 pass 12/14 fail (the functions do not exist on main)
platform i18n parity/usage (lib/i18n) 48/48 —
@tale/ui (incl. the 26 i18n checks) 1173/1173 —
@tale/docs structural 194/194 —
backend:integration (throwaway tale-db + MinIO) 290/290 281/290 — all 9 reds are the new lifecycle defect probes; the 2 lifecycle regression guards and every pre-existing check are green

Refuted / scoped

  • Nothing refuted: all three findings verified in code before changing.
  • Cross-class (not touched): org deletion still leaves org-scoped app.* rows (documents, threads, projects…), S3 blobs and the knowledge corpus in place — the 0.5 ledger's known gap; that is an erasure-job design (multi-store, out-of-transaction), not a change to this door.
  • Cross-class (tooling): .claude/hooks/format.sh runs oxfmt with the main clone's config and an absolute worktree path, so the **/*.md / **/*.yml ignore patterns don't match in worktrees — it pads markdown tables and re-wraps yml folded scalars the repo formatter never touches. The pre-commit hook (relative paths) skips them correctly. The noise it produced here was removed; the hook itself is left for its own fix.

Deletion was client-orchestrated: the app's prepare-deletion endpoint
committed the organization_deleted audit row, deleted the org's
user_preferences and enqueued the config-tree removal in its own
transaction, and only then did the client call Better Auth's
organization.delete. A failed or missing second call left a live
organization gutted with a false deletion audit, and the TODO'd
legal-hold guard was never re-added once the governance domain landed.

The app now owns the single deletion door, POST
/api/app/organizations/:id/delete, as one serializable transaction:
every guard first (membership, owner role, default-org protection, an
org-wide OR any custodian legal hold refuses with 409 LEGAL_HOLD_ACTIVE
and nothing written), then the audit row, the per-user cascade
(user_preferences, memories, last-active and session pointers), Better
Auth's rows leaf-first (teamMember, team, invitation, member, the org),
and the org.cleanup_files job enqueued through the same transaction.
Better Auth's own /organization/delete is disabled so no second door
bypasses the gate, and the cleanup job re-checks that no live
organization still owns the slug before removing a tree.

The client makes one call and maps the hold refusal to a translated,
actionable toast (en/de/fr); the legal-hold docs name the new block.
beforeUpdateOrganization validated and applied a slug change with no
compensation, while the slug is the tenant key of everything outside
the database: blob keys embed it (s3KeyBelongsToOrg), the config tree
lives at $TALE_CONFIG_DIR/<slug>, the knowledge corpora are scoped by
it. One rename silently orphaned every stored file, every config file
and the corpus, with new writes landing under the new slug.

The slug is immutable once set: a differing value is refused with an
actionable 400, re-sending the current slug beside a name change still
lands, and a slug-less organization may still receive its first. The
settings form never sent the slug, so the only affected path was the
raw API.
A dedicated user with two organizations proves, against real Postgres:
a custodian hold and an org-wide hold each refuse deletion and leave
the org intact; Better Auth's delete door answers 404; a non-owner is
refused; a slug rename is refused while the unchanged slug still
updates; an aborted teardown transaction leaves rows, audit and jobs
untouched; a queued cleanup for a slug a live organization owns leaves
its tree alone; the committed delete removes rows, writes the audit
row, cascades preferences and pointers and drops the config tree; and
the shared user keeps their account and their other organization.
…egrity

# Conflicts:
#	docs/de/platform/admin/governance/legal-hold.md
#	docs/en/platform/admin/governance/legal-hold.md
#	docs/fr/platform/admin/governance/legal-hold.md
#	services/platform/backend/MIGRATION.md
@larryro
larryro marked this pull request as ready for review September 3, 2026 06:34
@larryro
larryro merged commit e5748f9 into main Sep 3, 2026
23 checks passed
@larryro
larryro deleted the fix/org-lifecycle-integrity branch September 3, 2026 06:34
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.

1 participant