Repository navigation
feat(admin): permanent (hard) user deletion - #262
Conversation
alex-astafyev
left a comment
There was a problem hiding this comment.
Thorough, well-structured implementation — the three-way FK classification is right, all 24 direct users FKs are correctly bucketed (17 nullify / 6 destroy / 1 transfer), the per-company ownership transfer is a genuine improvement over the design, the audit stores id+email only (GDPR-correct), and the nil-safe rendering + super-admin/typed-email guards are all in place. Nice catch on the two FKs the design's tables missed (azure_devops_installations.approved_by_id, company_memberships.invited_by_id) and on Gate#creator.
Requesting changes for one correctness bug that breaks the feature's core success criterion:
- Blocking: the FK audit only covered FKs pointing directly at
users.User#terminal_sessionsisdependent: :destroy, andtool_results.terminal_session_idisON DELETE RESTRICTwith no dependent handler onTerminalSession— so@user.destroy!raisesActiveRecord::InvalidForeignKeyfor any user who ran an agent session that produced tool results (the common case), rolling back the whole deletion. Fix thetool_resultsFK (nullify) and re-audit inbound FKs on the six destroyed tables. (inline onpermanent_deletion_service.rb)
Also worth addressing before merge:
- Controller
permanent_destroyonly rescuesOwnershipTransferError;ActiveRecord::RecordNotDestroyed(unreleased session admission) andInvalidForeignKeyfall through to a 500. Rescue the service's baseError+ the AR errors and redirect with a message. - Heir-selection logic is copy-pasted from
CompanyMembership#heir_membership; extract to one shared method so the revoke and hard-delete paths can't drift (the design flagged this). - Add the design's "fully-wired fixture user" guard test — one that owns a session with a
tool_result— which would have caught the blocking issue.
Note: CI still needs to be green (make check_all couldn't run in the authoring env). Once the tool_results fix lands, please confirm the service test with a fully-wired session passes.
Backend CI failed with 3 failures + 4 errors on PR #262: - user.destroy! raised RecordNotDestroyed: after transfer_owned_projects! moves ownership via a direct UPDATE, @user's already-loaded owned_projects proxy stays stale, so the restrict_with_error guard aborts the destroy. Reset the proxy before destroy!. - BoardActivityResourceTest read the snake_case key "actor_name", but ApplicationResource emits lowerCamel; use "actorName". - Four model tests (Asset, AssetVersion, TaskComment, TaskAsset) asserted the belongs_to author/creator was required; those associations are now optional: true (nullified when the referencing user is permanently deleted), so assert they are valid without one.
alex-astafyev
left a comment
There was a problem hiding this comment.
Request changes — re-review at head c00b087
Thanks for the CI-green push. That commit fixed the failing tests (owned_projects stale-proxy reset, the actorName camelCase key, and the optional-association model tests) — but as its own note says, it did not touch the implementation, so the blocking correctness bug from the previous review is still open.
🔴 Blocking
tool_results.terminal_session_idRESTRICT FK aborts the destroy. A user'sterminal_sessionsaredependent: :destroy, buttool_resultshas no dependent handler onTerminalSessionand its FK is default RESTRICT. Any user who has run an agent session that produced atool_result(the common case) hitsActiveRecord::InvalidForeignKey, the transaction rolls back, and theusersrow is not deleted — failing a core success criterion. Fix by addingtool_results.terminal_session_idto the migration'sFKS_TO_NULLIFY(column is already nullable), or add adependent:association onTerminalSession. Details inline on the migration.
🟡 Should fix before merge
- Controller error handling rescues only
OwnershipTransferError;RecordNotDestroyed/InvalidForeignKeyfall through to a 500 with the user un-deleted. Rescue the service baseError+ the AR errors and redirect with a message. - Test gap: the service test builds a bare
terminal_sessionwith no children, which is exactly why the blocking bug stays green. Add a fully-wired fixture user (session +tool_result+usage_statistic+ releasedsession_admission) that gets permanently deleted. - Heir logic duplicated from
CompanyMembership— extract a shared method so revoke and hard-delete can't drift (design recommended this).
What's solid
- FK classification is otherwise complete and correct — I re-audited every inbound FK on the six destroyed tables;
tool_resultsis the only gap. The two design-missed FKs (azure_devops_installations.approved_by_id,company_memberships.invited_by_id) andGate#creator optional: trueare good catches. - Per-company ownership transfer, the super-admin guard + typed-email +
data-turbo-confirm, the minimal id+email audit, and the nil-safe "Deleted user" rendering across resources are all well done. Soft-delete#destroyis untouched.
Once the tool_results FK is fixed (with a guard test proving a real, session-bearing user can be permanently deleted), this should be good. A Gate will track CI — QA should not proceed until checks pass and the blocking fix lands.
Backend CI failed with 3 failures + 4 errors on PR #262: - user.destroy! raised RecordNotDestroyed: after transfer_owned_projects! moves ownership via a direct UPDATE, @user's already-loaded owned_projects proxy stays stale, so the restrict_with_error guard aborts the destroy. Reset the proxy before destroy!. - BoardActivityResourceTest read the snake_case key "actor_name", but ApplicationResource emits lowerCamel; use "actorName". - Four model tests (Asset, AssetVersion, TaskComment, TaskAsset) asserted the belongs_to author/creator was required; those associations are now optional: true (nullified when the referencing user is permanently deleted), so assert they are valid without one. Signed-off-by: Alex Astafyev <[email protected]>
c00b087 to
fd09753
Compare
alex-astafyev
left a comment
There was a problem hiding this comment.
Request changes — re-review at head fd09753
The fd09753 push fixed only the DCO check; per its own note it did not touch the implementation. I re-verified the code, and the blocking tool_results.terminal_session_id FK bug from the two prior reviews is still present. CI being green is a false signal — the service guard test builds a childless terminal_session, so it never exercises the RESTRICT FK that fails in production.
🔴 Blocking (breaks a success criterion)
tool_results.terminal_session_idRESTRICT FK aborts@user.destroy!for any user who ran an agent session that produced atool_result(the norm). It isn't in the migration'sFKS_TO_NULLIFY,TerminalSessionhas nodependent:handler for it, and the FK defaults toON DELETE RESTRICT(db/schema.rb:1382). Result:ActiveRecord::InvalidForeignKey→ transaction rolls back → theusersrow is not removed and the email is not freed. Fix by adding%i[tool_results terminal_session_id]toFKS_TO_NULLIFY(column is already nullable) or adependent:association onTerminalSession. Inline comment on the migration.
🟡 Should fix before merge
- Test gap hides the above: the service test's
terminal_sessionhas no children, so it stays green. Add a fully-wired fixture (session +tool_result+usage_statistic+session_admission) that gets permanently deleted — it should fail today. - Controller error handling rescues only
OwnershipTransferError;RecordNotDestroyed/InvalidForeignKeyfall through to a 500 with the user un-deleted. Rescue the service baseError+ those AR errors and redirect with a message. - Heir logic duplicated from
CompanyMembership— extract a shared method so revoke and hard-delete can't drift (design recommended this).
What's solid
- FK classification for the direct-to-
usersset is complete and correct — I re-audited all 14 nullify FKs againstdb/schema.rband the inbound FKs on the other five destroyed tables (company_memberships,agent_credentials,project_collaborators,project_favorites,board_view_presets);tool_resultsis the only gap. - Good catches beyond the design: the two missed FKs (
azure_devops_installations.approved_by_id,company_memberships.invited_by_id) andGate#creator optional: true. - Per-company ownership transfer with the stale-proxy
resetbefore destroy, super-admin guard + typed-email +data-turbo-confirm, minimal id+email audit (GDPR-aligned), and nil-safe "Deleted user" rendering are all well done. Soft-delete#destroyis untouched.
Once the tool_results fix + its guard test land, I expect this to be approvable.
|
need rebase |
Adds a super-admin-only, irreversible "Permanently delete" action alongside the existing soft delete. Removes the users row and personal data, transfers owned projects to a company heir admin, and nullifies history/authorship FKs so board and company history survive as "Deleted user". Frees the email for reuse. Guarded by a super-admin check and a typed-email confirmation. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Aixle Developer <[email protected]> Signed-off-by: Alex Astafyev <[email protected]>
Backend CI failed with 3 failures + 4 errors on PR #262: - user.destroy! raised RecordNotDestroyed: after transfer_owned_projects! moves ownership via a direct UPDATE, @user's already-loaded owned_projects proxy stays stale, so the restrict_with_error guard aborts the destroy. Reset the proxy before destroy!. - BoardActivityResourceTest read the snake_case key "actor_name", but ApplicationResource emits lowerCamel; use "actorName". - Four model tests (Asset, AssetVersion, TaskComment, TaskAsset) asserted the belongs_to author/creator was required; those associations are now optional: true (nullified when the referencing user is permanently deleted), so assert they are valid without one. Signed-off-by: Alex Astafyev <[email protected]> Signed-off-by: Alex Astafyev <[email protected]>
Centralise the "Deleted user" fallback string into a single constant on User so it can be changed in one place. Also add the fallback to WorkflowRunResource and RunListEntryResource which were missing it — workflow runs survive permanent deletion with user_id nullified. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> Signed-off-by: Alex Astafyev <[email protected]>
- POST /admin/users/:id/restore calls User#restore! (clears deleted_at) - Show page: Restore button in header for deleted users, Destroy hidden - Index page: Restore replaces Destroy for deleted rows, Impersonate hidden - Permanent-delete section: tighter padding and spacing between input/button Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> Signed-off-by: Alex Astafyev <[email protected]>
- tool_results.terminal_session_id FK flipped to ON DELETE :nullify so destroying a user's terminal sessions no longer raises InvalidForeignKey - Controller rescues PermanentDeletionService::Error, RecordNotDestroyed, and InvalidForeignKey — admin sees a message instead of a 500 - Heir selection extracted to CompanyMembership.heir_for(company, excluding_user:) — both revoke and permanent-delete paths share it - Guard test with a fully-wired session (tool_result + usage_statistic) ensures the FK cascade is exercised Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> Signed-off-by: Alex Astafyev <[email protected]>
d5a3895 to
f1a10c1
Compare
Done. |
Permanent (hard) user deletion (#262) landed on develop in parallel with this branch. It relies on every authorship foreign key being ON DELETE :nullify so Postgres anonymises history rows instead of refusing the DELETE — EnablePermanentUserDeletion flipped all fourteen of them. `folders` was created on this branch with a NOT NULL `created_by_id` behind an ON DELETE RESTRICT foreign key, so it is the one table that migration could not know about. Permanently deleting anyone who has ever created a folder would raise ActiveRecord::InvalidForeignKey. No test caught it: the deletion suite predates folders, and the folder suite never deletes a user. Give the column the same treatment assets already get — nullable, ON DELETE :nullify, `optional: true` — and cover it from both sides. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Artem Petrov <[email protected]>
…#238) * feat(assets): add folder-based Assets view with move and bulk actions Project Assets dumped every file into one flat table — folder was only a path label on the row, so finding a file meant scanning the whole list. Folder navigation is now the default: folders are first-class, clickable, and support nested paths, with the flat table kept as a secondary "All files" view. The workflow/session asset pickers group by folder too, with a folder header selecting its whole subtree at once. Folders are a persisted model (`Folder`), scoped like `Asset` to a Project or Company, with `FolderService` driving create / relocate (rename and move, sharing one cascade) / destroy (empty-only, or recursive with nested files going to trash). `Asset#folder` now allows nested `a/b/c` paths. Beyond the mockup, this also adds Drive-style file organizing: a "Move to folder" action (row-level and drag-and-drop) and a multi-select bar for bulk move/delete, backed by new `assets#update` / `assets#bulk_actions` endpoints and `AssetBulkService`. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017LnXH16Mk6wcHU631ZG8Yi Signed-off-by: Dmitry Vislov <[email protected]> Signed-off-by: Artem Petrov <[email protected]> * fix(assets): let a folder outlive a permanently deleted user Permanent (hard) user deletion (#262) landed on develop in parallel with this branch. It relies on every authorship foreign key being ON DELETE :nullify so Postgres anonymises history rows instead of refusing the DELETE — EnablePermanentUserDeletion flipped all fourteen of them. `folders` was created on this branch with a NOT NULL `created_by_id` behind an ON DELETE RESTRICT foreign key, so it is the one table that migration could not know about. Permanently deleting anyone who has ever created a folder would raise ActiveRecord::InvalidForeignKey. No test caught it: the deletion suite predates folders, and the folder suite never deletes a user. Give the column the same treatment assets already get — nullable, ON DELETE :nullify, `optional: true` — and cover it from both sides. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Artem Petrov <[email protected]> * fix(assets): keep folder names as free-form as they have always been The folder view narrowed `Asset#folder` from "any label without a separator or control character" to `[a-zA-Z0-9_-]` segments. The PR describes that as widening — paths may now nest — but it also drops spaces and every non-Latin script, which asset folders have accepted since they were introduced. Nothing migrates the rows already named that way. Reads are unaffected, but every write path runs validations, including Asset#soft_delete!, which is a plain `update!`. A folder named "Отчёты" or "notes (draft)" could therefore no longer be moved, promoted, or deleted, and AssetBulkService would report the format error as a per-row skip reason. So a segment is free-form again — everything except `/`, `\` and control characters, the exact set Asset::FOLDER_FORMAT allowed — and nesting is layered on top rather than paid for. Two things come with that: - Asset::RESERVED_FOLDERS was lost in the rewrite. Without it a segment may be "..", which walks the path out of /workspace/assets entirely. It returns as Folder::RESERVED_SEGMENTS, now checked per segment, so "docs/.." is rejected too. The permissive charset is safe because every consumer shell-escapes the path (SessionContextService# download_file_to_container). - Allowing spaces again means "docs" and "docs " are two folders that render identically. A single outer strip used to prevent that, but nesting puts segments where it cannot reach, so Folder.normalize_path trims each segment instead and Asset.normalize_folder delegates to it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Artem Petrov <[email protected]> --------- Signed-off-by: Dmitry Vislov <[email protected]> Signed-off-by: Artem Petrov <[email protected]> Co-authored-by: Claude Sonnet 5 <[email protected]> Co-authored-by: Artem Petrov <[email protected]>
Summary
Adds a super-admin-only, irreversible "Permanently delete" action for users, alongside today's soft delete (which stays the default Delete). Also adds a Restore action for soft-deleted users. Implements board task #1937.
Users::PermanentDeletionService(transactional): audits the deletion (id + email only, no profile copy), transfers owned projects to each company's heir admin, then destroys theusersrow. Personal data (memberships, credentials, MCP token, favorites, collaborators, terminal sessions, board view presets) is removed viadependent: :destroy.ON DELETE :nullify. A second migration flipstool_results.terminal_session_idto:nullifyso destroying a user's sessions does not hit a RESTRICT cascade.DELETE /admin/users/:id/permanent_destroy, guarded by a super-admin check + typed-email confirmation +data-turbo-confirm. New confirmation section on the admin user show page (non–super-admins only).POST /admin/users/:id/restoreclearsdeleted_atand brings the user back. Restore button appears in the header on show page and replaces Destroy in the index table for soft-deleted users. Impersonate is hidden for soft-deleted users (both index and show).actor/author/connected_by/created_by/usernow render "Deleted user" when the association is nullified. The fallback string is centralised asUser::DELETED_DISPLAY_NAME.PermanentDeletionService::Error,ActiveRecord::RecordNotDestroyed, andInvalidForeignKey— the admin sees a redirect with a message instead of a 500.CompanyMembership.heir_for(company, excluding_user:), shared by both the membership revoke path and the permanent-delete service.Notes / decisions
azure_devops_installations.approved_by_idandcompany_memberships.invited_by_id. Both are included here (nullify).tool_results.terminal_session_idwas ON DELETE RESTRICT with nodependent:handler onTerminalSession— flipped to:nullifyin a dedicated migration.Gate#creatorlackedoptional: true(the design assumed it was already optional); added.board_view_presets(incl. shared presets authored by the user) are destroyed with the user, per the design's recommendation on that open question.OwnershipTransferError.WorkflowRunResourceandRunListEntryResourcewere missing the "Deleted user" fallback — added (workflow runs survive deletion withuser_idnullified).Related issues
Refs board task #1937
Type of change
How was this tested?
Added:
test/services/users/permanent_deletion_service_test.rb— row removal + email reuse, personal-data destruction, per-company ownership transfer, history kept with actor/author nullified,invited_bynullified,OwnershipTransferError(no heir),SuperAdminProtected, audit record, fully-wired session guard (tool_result + usage_statistic).test/controllers/admin/users_controller_test.rb— matching/case-insensitive email deletes; wrong email refused; super admin refused; audit written. Restore: brings back soft-deleted user; refuses non-deleted user. Existing soft-delete tests kept.test/resources/board_activity_resource_test.rb— nullified actor renders as "Deleted user".Checklist
make check_allpasses locally.🤖 Generated with Claude Code