Skip to content

fix(platform): complete organization removal and member credential paths - #3240

Merged
larryro merged 13 commits into
mainfrom
fix/org-lifecycle-integrity
Sep 6, 2026
Merged

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

Conversation

@larryro

@larryro larryro commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The org-core slice of the backend fix campaign (organizations / members / users). The headline is organization deletion: it used to remove four app tables by hand and the config tree, leaving 91 org-keyed app tables, the slug-keyed knowledge corpus and the blob prefix behind — and the freed slug was reusable at once, so a new organization with the same slug read the deleted tenant's documents. Deletion now cascades over every org_id-bearing app table read from the catalog (child before parent along the schema's own FKs; the governance ledger is the deliberate survivor), writes a slug tombstone, and hands the slug-keyed remains (corpus, blobs, config tree) to the org.cleanup_files job, which clears the tombstone last; the slug hooks refuse a tombstoned slug (and re-enqueue the job so a stale tombstone heals). Around it: one credential account row per user on admin password resets, audit + realtime hint for members created from the settings UI, transactional passkey revoke / 2FA reset, the editor role listed as editor, and four dead helpers removed.

Builds on #3162 (single serializable deletion transaction + closed plugin door) — nothing there is re-implemented.

Findings fixed

  • org-core-1 — deleteOrganization now cascades over every org-keyed app table (catalog-driven, child-first), writes app.organization_tombstones (migration 0079), and the cleanup job purges the org's corpus on its own knowledge pool (documents, chunks, semantic cache, website memberships + orphaned domains), deletes the blobs under orgObjectPrefix, removes the config tree, then clears the tombstone. beforeCreateOrganization / beforeUpdateOrganization refuse a retiring slug; the onboarding step reads that refusal as "taken".
  • org-core-2 — setCredentialPassword decides create-or-update inside the caller's transaction (folding duplicate rows an earlier release left behind); both admin doors use it and the forced first-login reset updates by (user, provider).
  • org-core-4 — createMember (POST /users/members, the settings UI's door) writes the member row through members/service.addMember in one serializable tx: add_member audit row + member realtime hint; MemberServiceError codes mapped on the users route.
  • org-core-9 — revokePasskeyForMember / resetTwoFactorForMember take the caller's TransactionSql, audit in the same tx; both routes wrap in transactSerializable like their siblings.
  • org-core-10 — listUserOrganizations derives its role set from MEMBER_ROLES; an editor membership lists as editor.
  • org-core-5 / 6 / 7 / 8 — dead code removed: core/organizations/resolve_org_slug.ts (+ test), listMissingScaffoldDomains + dirHasSeedableEntries, GET /api/app/organizations/has-any + hasAnyOrganization, the three Convex-era BetterAuth* types.

Skipped

None. (org-core-3 was not in the assigned list.)

Tests & gates observed (round 1, after the review commits)

  • bunx tsc --noEmit — exit 0
  • bunx oxlint --type-aware — exit 0
  • bunx vitest --run --project server teardown.test.ts service.test.ts credential.test.ts — Test Files 3 passed (3) / Tests 24 passed (24)
  • bun run check — Tasks: 39 successful, 40 total: every task green except test:ui, where 6 tests in 5 unrelated files (sidebar-nav, workflow-settings, settings-rail, connectors-settings, data-residency-settings) timed out at ~5 s under CPU load; rerun alone: Test Files 5 passed (5) / Tests 49 passed (49). Server suite inside check: Tests 73215 passed (73215).
  • bun run knip:check — exit 0 (the pre-existing cron-parser configuration hint only)
  • Real-Postgres integration proof (run-itest.sh, fix(platform): pass the corpus scope rows as one jsonb parameter #3222's aa3d1d7a9 cherry-picked temporarily and dropped afterwards): [itest] 471/473 checks passed across 133/133 lanes, no RUN TRUNCATED; the same two known-red lanes as before (webdav re-home — pre-campaign; knowledge: corpus scope drift … drifted=null — the cherry-picked fix(platform): pass the corpus scope rows as one jsonb parameter #3222's lane), nothing from this branch. Lifecycle checks all PASS, now including the outbox: org delete cascades over every org-keyed app table and keeps only the governance ledger — tables=91 survivors=none audit=1 outboxB=1; the teardown job removes the slug-keyed corpus, blobs and tree, then clears the tombstone — tombstoneCleared=true … dirA=false; a freed slug can be taken again …; a retiring slug is refused until its teardown has run, then reusable — status=400 … healed=true; credential reset: repeated resets keep ONE credential row …; users/members (the settings door) … audits=2 hints=2.

Tests & gates observed (initial)

  • bunx tsc --noEmit — exit 0
  • bunx oxlint --type-aware — exit 0
  • bunx vitest --run --project server — Test Files 497 passed (497) / Tests 5997 passed (5997)
  • bunx vitest --run --config vitest.ui.config.ts …/workspace-step.test.tsx — Test Files 1 passed (1) / Tests 6 passed (6)
  • bun run check — exit 0, Tasks: 40 successful, 40 total
  • bun run knip:check — exit 0 (one pre-existing configuration hint, cron-parser … Remove from ignoreDependencies, identical on main)
  • Real-Postgres integration proof (run-itest.sh, with fix(platform): pass the corpus scope rows as one jsonb parameter #3222's aa3d1d7a9 cherry-picked temporarily and dropped afterwards): [itest] 471/473 checks passed across 133/133 lanes. The two failures — webdav re-home and knowledge: corpus scope drift — reproduce in every sibling campaign log and are not from this branch (webdav is the known pre-campaign red; the drift lane belongs to the cherry-picked PR). New lane checks, all PASS:
    • org delete cascades over every org-keyed app table and keeps only the governance ledger — tables=91 survivors=none audit=1
    • the teardown job removes the slug-keyed corpus, blobs and tree, then clears the tombstone — tombstoneCleared=true documents=0 memberships=0 soleDomain=0 sharedDomain=1 membershipsB=1 blobs=0 dirA=false
    • a freed slug can be taken again and the new organization starts with an empty corpus
    • a retiring slug is refused until its teardown has run, then reusable — status=400 … created=0 healed=true
    • plus the org-core-2 / org-core-4 probes in checkAccountAuthzHardening (one credential row after repeated resets; /users/members writes add_member + member hint, refuses DUPLICATE_MEMBER).

Review round 1 (adversarial PR review) — addressed

  • Blocking — fail-closed config-tree step. removeOrgSubtree is non-fatal by contract (a symlinked org dir, a tripped traversal guard or a failed rename logs and returns, because the scaffolder must go on to seed). The teardown job trusted that return and cleared the tombstone anyway, so a tree the remover refused to delete stayed on disk while the slug became claimable again. The job now checks that <TALE_CONFIG_DIR>/<slug> answers ENOENT after the removal and throws otherwise — the tombstone stands and pg-boss retries (corpus + blob steps before it are idempotent). Unit case in teardown.test.ts: a symlinked org dir makes the job fail, leaves the link and its target alone, invalidates nothing and writes no DELETE. (commit 214c9eb1c)
  • Non-blocking — realtime outbox. app_realtime.outbox is org-keyed but lives outside the app schema the catalog walk lists; deletion now clears it in the same transaction (unit pin + real-Postgres survivors probe; the probe seeds one hint per organization so A's must go and B's must stay). (commits b2803426d, 20b8456af)
  • Non-blocking — forced reset test. forcedResetCredentialPassword (update by (user, provider)) is exported and pinned: statement shape, reuse refusal, missing-credential 404. (commit f3ba177ed)
  • Non-blocking — migration ledger. backend/MIGRATION.md organizations row records 0079, the catalog cascade, the teardown job and the tombstoned-slug refusal. (commit 25c587033)

Notes for the reviewer

  • Merge-tree check against origin/main (3997f6a) before the round-1 push: CLEAN — no rebase, no force-push; five commits added on top of the reviewed head.
  • Migration renumbered 0077 → 0079 (coordinator assignment; 0077 is fix(platform): close conversation send, dedupe and scoping gaps #3225's, 0078 is the files branch). Re-check the number at merge time; the file is new (0079_organization_tombstones.sql) and only creates a table.
  • The cascade is catalog-driven on purpose: a hand-kept table list is exactly what leaked 87 tables. Excluded by name: audit_logs, audit_chain_heads, audit_integrity_progress (retention-governed ledger; the organization_deleted row is written inside the same transaction) and organization_tombstones (written after the cascade). automation_project_bindings → projects is the schema's only non-cascading FK between org-keyed tables; the child-first order covers it (proved on Postgres).
  • The tombstone is the only new user-visible behaviour: taking a slug whose teardown is still running answers 400 … is still being removed. Try again in a few minutes. (English backend literal like the sibling slug messages; the onboarding step maps it to the existing "name taken" copy, so no locale keys were added). The refusal re-enqueues the teardown (dedup key), so a tombstone whose job exhausted its retries is healed by the next claim rather than blocking the slug forever.
  • Better Auth owns "account", so org-core-2 is a transactional setter + lazy dedupe rather than a unique index on that table.
  • POST /api/app/members (the harness's primitive) is kept; createMember now routes through the same addMember service function, so there is one instrumented concept.

Four leftovers from the 0.4 port had no caller anywhere in the repo:

- core/organizations/resolve_org_slug.ts, a deprecated re-export of
  orgSlugFromId imported only by its own test (org-core-5)
- listMissingScaffoldDomains + its only helper dirHasSeedableEntries in
  core/organizations/scaffold.ts — the provisioning-status banner they
  served never landed in 0.5 (org-core-6)
- GET /api/app/organizations/has-any + hasAnyOrganization; the app and
  the integration harness probe /users/has-any (org-core-7)
- the Convex-adapter shapes BetterAuthOrganization, BetterAuthSession and
  BetterAuthCreateResult in core/members/types.ts (org-core-8)

Verified with rg over services/, tools/, packages/, configs/ and docs/.
listUserOrganizations kept its own role set (owner, admin, developer,
member) and normalized everything else to 'member', so an 'editor'
membership answered 'editor' on /members/me and 'member' on
/organizations — one row, two roles, and the org list panel showed
editors as plain members. 'editor' is assignable on both member-creation
routes and is in every other vocabulary (members/service MEMBER_ROLES,
the shared memberRoleLiterals, even the 0.4 origin of this list), so the
omission was a port regression.

The set is now derived from MEMBER_ROLES instead of being a second
hand-written copy; 'disabled' is still excluded before the lookup and an
off-vocabulary role still reads as 'member'. Regression test added.

Finding: org-core-10.
revokePasskeyForMember and resetTwoFactorForMember took the bare pool:
their multi-table mutations ran as autocommit statements (passkey +
sessions; twoFactor row + user flag + grace + attempts + sessions) and
the audit row was written in a separate sql.begin afterwards. A failure
mid-sequence left a half-reset factor (twoFactor row gone while
twoFactorEnabled stayed true) or a security action with no row in the
governance ledger. Every sibling mutation route already wrapped its
service call in transactSerializable.

Both functions now take the caller's TransactionSql and write the audit
row through it; the two routes wrap them in transactSerializable like
their siblings. A recording-tx test pins the statement set, the guard
order, the target binding and that an audit failure surfaces after the
writes were issued on the same tx (so the rollback covers them).

Finding: org-core-9.
POST /users/members (createMember — the door the settings UI uses)
added the member row through auth.api.addMember and recorded nothing
else: no add_member audit row and no 'member' realtime hint, so the
members table did not refresh live and the governance ledger had no
trace of who added whom. The fully instrumented copy of the same concept
— members/service.ts addMember (audit + hint in the caller's tx) — was
reached only by the integration harness through POST /members. No
Better Auth member hook was configured, so the plugin API bought
nothing.

createMember now writes the member row through addMember inside one
serializable transaction (for a new user, together with the forced
password-change anchor); its own duplicate check is gone because
addMember refuses DUPLICATE_MEMBER in the same transaction that would
insert. The users route maps MemberServiceError like UserServiceError so
those codes reach the dialog unchanged, and passes the actor's email for
the audit row. Regression test pins the statement set for both branches.

Finding: org-core-4.
…esets

setMemberPassword and resetOwnerCredentials wrote the credential with
INSERT INTO "account" … ON CONFLICT DO NOTHING followed by an UPDATE.
Better Auth owns the account table and declares no unique key on
(userId, providerId), so the INSERT's only conflict target was its fresh
uuid primary key: every admin reset of a member who already had a
password added a second credential row. The user's mandatory forced
first-login change (forcedResetCredentialPassword) then updated ONE row
by id, leaving the other with the admin-set temporary password, and
sign-in picks whichever credential row comes first — the temporary
password could keep working, or the new one be rejected.

The app is not allowed to add a constraint to a Better Auth table (the
migration contract), so the rule lives in one setter instead:
setCredentialPassword decides create-or-update inside the caller's
serializable transaction with the rows locked, and folds duplicate rows
an earlier release left behind into the newest one. Both doors use it,
and both now run credential write + session sweep + rotation anchor (+
audit) as one transaction. The forced reset updates by (user, provider)
so no second row can survive with an old password.

Finding: org-core-2.
Extend checkAccountAuthzHardening with the real-Postgres proofs for the
two users-domain fixes: a repeated admin password reset leaves exactly
one credential account row and only the newest password signs in
(org-core-2); POST /users/members — the settings UI's door — adds a new
and an existing user with an add_member audit row and a member realtime
hint each, and refuses a duplicate with DUPLICATE_MEMBER (org-core-4).
deleteOrganization removed four app tables by hand (user_preferences,
memories, the two SSO team-sync tables) plus Better Auth's rows, and the
org.cleanup_files job removed only the config tree. Every other org-keyed
app table — projects, tasks, documents, conversations, automations,
credentials, usage, … (91 tables today) — kept its rows forever with no
path to remove them, and the two stores keyed by the SLUG rather than the
id, the knowledge corpus (org_slug) and the object-store blobs
(<prefix>/<slug>/<uuid>), were never touched. Because the slug became
reusable the moment the organization row was gone, a new organization
taking it was routed by getKnowledgePoolForOrg(slug) onto the deleted
tenant's documents — a cross-tenant read.

The deletion transaction now cascades over every app-schema table with an
org_id column, read from the catalog (so a table added later is covered
the day its migration lands) and ordered child-before-parent along the
schema's own foreign keys; the governance ledger is the one deliberate
survivor. It then writes a slug tombstone (migration 0079,
app.organization_tombstones) before enqueueing the cleanup job. The job
is now the second half of the teardown: purge the org's corpus on its own
knowledge pool (documents, chunks, semantic cache, website memberships,
and the domains nobody else holds), delete the blobs under the org's key
prefix in its resolved store, remove the config tree, and clear the
tombstone LAST — every step idempotent, so a retry resumes with the slug
still reserved. The organization create/update slug hooks refuse a slug
whose tombstone stands (and re-enqueue the job, so a tombstone that
outlived its retries heals on the next claim); the onboarding step reads
that refusal as "taken". orgObjectPrefix is the one place the blob
namespace is spelled, shared by buildObjectKey and the teardown.

Migration renumbered from 0077 to the coordinator-assigned 0079 (0077 is
taken by the conversations branch); re-check at merge time.

Tests: the recording-tx contract pins the catalog cascade order and the
tombstone as the last write; unit tests cover the child-first ordering,
the corpus purge statements, and the job body's order, refusal and
retry-safety; the real-Postgres lane seeds org-keyed rows with a
non-cascading FK, corpus rows (one website shared with another org) and
a blob, then proves zero survivors across the catalog, the job clearing
the tombstone with corpus/blobs/tree gone and the shared domain kept,
slug reuse with an empty corpus, and the retiring-slug refusal healing
itself.

Finding: org-core-1.
…ives

`removeOrgSubtree` is non-fatal by contract: a symlinked org dir, a tripped
traversal guard or a failed rename logs and returns, because its other
caller (the scaffolder) must go on to seed. The teardown job trusted that
return and cleared the slug tombstone anyway, so a tree the remover refused
to delete stayed on disk while the slug became claimable again — the next
organization taking the slug would inherit the old tenant's config files.

The job now checks that `<TALE_CONFIG_DIR>/<slug>` answers ENOENT after the
removal and throws otherwise, so the tombstone stands and pg-boss retries;
the corpus and blob steps before it are idempotent. Unit case: a symlinked
org dir makes the job fail, leaves the link and its target alone, and writes
no DELETE. (PR #3240 review, blocking.)
The catalog-driven cascade walks every `app.*` table with an `org_id`
column; the realtime hint outbox lives in `app_realtime` and was never
listed, so a deleted organization's hints outlived it until the retention
sweep. The deletion now removes them in the same transaction; the unit pin
and the real-Postgres survivors probe cover the table. (PR #3240 review,
non-blocking.)
`forcedResetCredentialPassword` changed from updating the one row id it read
to updating by (user, provider) so a duplicated credential row cannot keep
the old admin-set password — the change carried no test. Export it and pin
the statement shape, the reuse refusal and the missing-credential 404.
(PR #3240 review, non-blocking.)
The organizations row names migration 0079, the catalog-driven cascade, the
slug-keyed teardown job and the tombstoned-slug refusal. (PR #3240 review,
non-blocking.)
The survivors probe counted app_realtime.outbox rows for the deleted
organization without ever seeding one, so it could not fail. Seed one hint
per organization before the deletion: A's must be gone with the cascade,
B's must survive it. (PR #3240 review follow-up, org-core-1.)
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