Skip to content

feat(admin): permanent (hard) user deletion - #262

Merged
artempartos merged 5 commits into
developfrom
task-1937
Sep 17, 2026
Merged

artempartos merged 5 commits into
developfrom
task-1937

Conversation

@aixle-com

@aixle-com aixle-com Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

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 the users row. Personal data (memberships, credentials, MCP token, favorites, collaborators, terminal sessions, board view presets) is removed via dependent: :destroy.
  • FK reclassification migrations: makes 8 history/authorship columns nullable and flips 14 user-referencing FKs to ON DELETE :nullify. A second migration flips tool_results.terminal_session_id to :nullify so destroying a user's sessions does not hit a RESTRICT cascade.
  • Controller/route/UI: new 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).
  • Restore action: new POST /admin/users/:id/restore clears deleted_at and 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).
  • Nil-safe rendering: resources that read actor/author/connected_by/created_by/user now render "Deleted user" when the association is nullified. The fallback string is centralised as User::DELETED_DISPLAY_NAME.
  • Error handling: controller rescues PermanentDeletionService::Error, ActiveRecord::RecordNotDestroyed, and InvalidForeignKey — the admin sees a redirect with a message instead of a 500.
  • Heir selection deduplicated: extracted to CompanyMembership.heir_for(company, excluding_user:), shared by both the membership revoke path and the permanent-delete service.

Notes / decisions

  • The tech design's FK tables missed two user FKs that would have blocked the destroy — azure_devops_installations.approved_by_id and company_memberships.invited_by_id. Both are included here (nullify).
  • tool_results.terminal_session_id was ON DELETE RESTRICT with no dependent: handler on TerminalSession — flipped to :nullify in a dedicated migration.
  • Gate#creator lacked optional: 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.
  • Super admins cannot be permanently deleted; a sole project owner with no heir admin is refused with OwnershipTransferError.
  • WorkflowRunResource and RunListEntryResource were missing the "Deleted user" fallback — added (workflow runs survive deletion with user_id nullified).
  • Soft-deleted users: Destroy button hidden (show + index), replaced with Restore; Impersonate hidden.

Related issues

Refs board task #1937

Type of change

  • New feature

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_by nullified, 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

  • I added/updated tests where it makes sense.
  • make check_all passes locally.

🤖 Generated with Claude Code

@alex-astafyev alex-astafyev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_sessions is dependent: :destroy, and tool_results.terminal_session_id is ON DELETE RESTRICT with no dependent handler on TerminalSession — so @user.destroy! raises ActiveRecord::InvalidForeignKey for any user who ran an agent session that produced tool results (the common case), rolling back the whole deletion. Fix the tool_results FK (nullify) and re-audit inbound FKs on the six destroyed tables. (inline on permanent_deletion_service.rb)

Also worth addressing before merge:

  • Controller permanent_destroy only rescues OwnershipTransferError; ActiveRecord::RecordNotDestroyed (unreleased session admission) and InvalidForeignKey fall through to a 500. Rescue the service's base Error + 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.

aixle-com Bot pushed a commit that referenced this pull request Sep 15, 2026
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 alex-astafyev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_id RESTRICT FK aborts the destroy. A user's terminal_sessions are dependent: :destroy, but tool_results has no dependent handler on TerminalSession and its FK is default RESTRICT. Any user who has run an agent session that produced a tool_result (the common case) hits ActiveRecord::InvalidForeignKey, the transaction rolls back, and the users row is not deleted — failing a core success criterion. Fix by adding tool_results.terminal_session_id to the migration's FKS_TO_NULLIFY (column is already nullable), or add a dependent: association on TerminalSession. Details inline on the migration.

🟡 Should fix before merge

  • Controller error handling rescues only OwnershipTransferError; RecordNotDestroyed / InvalidForeignKey fall through to a 500 with the user un-deleted. Rescue the service base Error + the AR errors and redirect with a message.
  • Test gap: the service test builds a bare terminal_session with no children, which is exactly why the blocking bug stays green. Add a fully-wired fixture user (session + tool_result + usage_statistic + released session_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_results is the only gap. The two design-missed FKs (azure_devops_installations.approved_by_id, company_memberships.invited_by_id) and Gate#creator optional: true are 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 #destroy is 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.

aixle-com Bot pushed a commit that referenced this pull request Sep 15, 2026
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]>

@alex-astafyev alex-astafyev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_id RESTRICT FK aborts @user.destroy! for any user who ran an agent session that produced a tool_result (the norm). It isn't in the migration's FKS_TO_NULLIFY, TerminalSession has no dependent: handler for it, and the FK defaults to ON DELETE RESTRICT (db/schema.rb:1382). Result: ActiveRecord::InvalidForeignKey → transaction rolls back → the users row is not removed and the email is not freed. Fix by adding %i[tool_results terminal_session_id] to FKS_TO_NULLIFY (column is already nullable) or a dependent: association on TerminalSession. Inline comment on the migration.

🟡 Should fix before merge

  • Test gap hides the above: the service test's terminal_session has 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 / InvalidForeignKey fall through to a 500 with the user un-deleted. Rescue the service base Error + 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-users set is complete and correct — I re-audited all 14 nullify FKs against db/schema.rb and the inbound FKs on the other five destroyed tables (company_memberships, agent_credentials, project_collaborators, project_favorites, board_view_presets); tool_results is the only gap.
  • Good catches beyond the design: the two missed FKs (azure_devops_installations.approved_by_id, company_memberships.invited_by_id) and Gate#creator optional: true.
  • Per-company ownership transfer with the stale-proxy reset before 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 #destroy is untouched.

Once the tool_results fix + its guard test land, I expect this to be approvable.

@alex-astafyev
alex-astafyev marked this pull request as draft September 15, 2026 13:50
@alex-astafyev
alex-astafyev marked this pull request as ready for review September 16, 2026 08:10
@artempartos

Copy link
Copy Markdown
Contributor

need rebase

Aixle Developer and others added 5 commits September 17, 2026 13:02
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]>
@alex-astafyev

Copy link
Copy Markdown
Collaborator

need rebase

Done.

@artempartos
artempartos merged commit 5436da7 into develop Sep 17, 2026
7 checks passed
artempartos added a commit that referenced this pull request Sep 17, 2026
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]>
artempartos added a commit that referenced this pull request Sep 17, 2026
…#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]>
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.

2 participants