Repository navigation
fix(platform): complete organization removal and member credential paths - #3240
Merged
Merged
Conversation
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.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 theorg.cleanup_filesjob, 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, theeditorrole listed aseditor, and four dead helpers removed.Builds on #3162 (single serializable deletion transaction + closed plugin door) — nothing there is re-implemented.
Findings fixed
deleteOrganizationnow cascades over every org-keyed app table (catalog-driven, child-first), writesapp.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 underorgObjectPrefix, removes the config tree, then clears the tombstone.beforeCreateOrganization/beforeUpdateOrganizationrefuse a retiring slug; the onboarding step reads that refusal as "taken".setCredentialPassworddecides 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).createMember(POST/users/members, the settings UI's door) writes the member row throughmembers/service.addMemberin one serializable tx:add_memberaudit row +memberrealtime hint;MemberServiceErrorcodes mapped on the users route.revokePasskeyForMember/resetTwoFactorForMembertake the caller'sTransactionSql, audit in the same tx; both routes wrap intransactSerializablelike their siblings.listUserOrganizationsderives its role set fromMEMBER_ROLES; aneditormembership lists aseditor.core/organizations/resolve_org_slug.ts(+ test),listMissingScaffoldDomains+dirHasSeedableEntries,GET /api/app/organizations/has-any+hasAnyOrganization, the three Convex-eraBetterAuth*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 0bunx oxlint --type-aware— exit 0bunx 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 excepttest: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-existingcron-parserconfiguration hint only)run-itest.sh, fix(platform): pass the corpus scope rows as one jsonb parameter #3222'saa3d1d7a9cherry-picked temporarily and dropped afterwards):[itest] 471/473 checks passed across 133/133 lanes, noRUN 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 0bunx oxlint --type-aware— exit 0bunx 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 totalbun run knip:check— exit 0 (one pre-existing configuration hint,cron-parser … Remove from ignoreDependencies, identical on main)run-itest.sh, with fix(platform): pass the corpus scope rows as one jsonb parameter #3222'saa3d1d7a9cherry-picked temporarily and dropped afterwards):[itest] 471/473 checks passed across 133/133 lanes. The two failures —webdav re-homeandknowledge: 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=1the 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=falsea freed slug can be taken again and the new organization starts with an empty corpusa retiring slug is refused until its teardown has run, then reusable — status=400 … created=0 healed=truecheckAccountAuthzHardening(one credential row after repeated resets;/users/memberswritesadd_member+memberhint, refusesDUPLICATE_MEMBER).Review round 1 (adversarial PR review) — addressed
removeOrgSubtreeis 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 inteardown.test.ts: a symlinked org dir makes the job fail, leaves the link and its target alone, invalidates nothing and writes no DELETE. (commit214c9eb1c)app_realtime.outboxis org-keyed but lives outside theappschema 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). (commitsb2803426d,20b8456af)forcedResetCredentialPassword(update by(user, provider)) is exported and pinned: statement shape, reuse refusal, missing-credential 404. (commitf3ba177ed)backend/MIGRATION.mdorganizations row records 0079, the catalog cascade, the teardown job and the tombstoned-slug refusal. (commit25c587033)Notes for the reviewer
origin/main(3997f6a) before the round-1 push: CLEAN — no rebase, no force-push; five commits added on top of the reviewed head.0079_organization_tombstones.sql) and only creates a table.audit_logs,audit_chain_heads,audit_integrity_progress(retention-governed ledger; theorganization_deletedrow is written inside the same transaction) andorganization_tombstones(written after the cascade).automation_project_bindings → projectsis the schema's only non-cascading FK between org-keyed tables; the child-first order covers it (proved on Postgres).… 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."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;createMembernow routes through the sameaddMemberservice function, so there is one instrumented concept.