platform icon indicating copy to clipboard operation
platform copied to clipboard

Admin Panel: Users + Workspaces + Audit log (V27 → V30)

Open MichaelUray opened this issue 6 months ago • 8 comments

Admin Panel: Users + Workspaces + Audit log (V27 → V30)

This PR introduces a full admin panel under /login/admin with three sections — Users, Workspaces, and Audit log — backed by four DB migrations (V27 → V30) and a suite of new admin-only RPC methods on @hcengineering/account. Self-hosted Huly operators can now manage accounts and workspaces, audit administrative actions, and bulk-disable or archive at scale, all without dropping to SQL.

Companion docs: hcengineering/huly-docs#71 — adds a top-level Admin panel section to the docs site with Overview / Users / Workspaces / Audit log / Configuration pages and screenshots.

Scope note (revised 2026-05-27): This PR provides Disable, not erasure or anonymization. Hard-delete was originally part of this PR but has been removed in response to @ignatremizov's review (see iteration table). Other lifecycle paths (anonymize, hard-delete with content cascade) are deferred to follow-up PRs.

The problem this solves

(Added in response to @ignatremizov's first-round review.)

Self-hosted Huly operators have to drop to raw SQL for everything cross-workspace today: disabling a compromised account, force-logging out a user after a security event, finding orphan accounts (no workspace memberships), checking who has admin access on which workspace, bulk-archiving stale workspaces, or auditing what an admin did last quarter. There is a workspace-scoped Settings → Members surface, but no global-account surface — and once you have more than ~5 workspaces, the per-workspace Settings pane stops scaling.

What already existed (so this is exposure, not reinvention). The account service already shipped the primitives — assignWorkspace, unassignWorkspace, social-id management, setWorkspaceMemberRole, the ADMIN_EMAILS env gate. They just had no UI and were not exposed via account-client. This PR wires UI + bulk endpoints + audit on top of what the account service already enforces.

Why a separate route instead of expanding an existing one. Two existing surfaces were in scope to extend rather than add:

  1. Per-workspace Settings → Members — workspace-scoped, member-of- workspace view. Can't cross workspace; can't disable an account globally; can't show which workspaces a person is in. Wrong domain to bolt cross-workspace controls onto.
  2. The tiny system-manager plugin — runs inside the per-workspace transactor session pipeline and doesn't talk to the account DB directly. The admin panel uses the account-service RPC instead, which is the source of truth for accounts and workspaces.

We chose /login/admin because of the session boundary (the panel must work even when no workspace is open). If you'd rather see this folded under system-manager once the dust settles, the routes can be moved.

Multi-tenancy. Huly already supports one account → many workspaces. ADMIN_EMAILS was the existing RBAC primitive; before this PR, "being admin" had no UI meaning — it only gated server-side mass operations callable from internal scripts. This PR is the first surfaced consumer of that primitive.

Iteration since the first review

Five commits were added on top of the original 159-commit history in response to your feedback. Each one is small and addresses one specific concern:

Commit Concern (from review) What changed
0c3af29d1c "Bulk actions bars are usually at the top of the table, either appearing just under the header row, or above the table, rarely below it" Move BulkActionBar from sticky-bottom to sticky-top in AdminUsers.svelte; the bar now appears between the filter row and the table, hidden when no rows are selected.
384a81d979 Audit table was always empty (found during end-to-end testing) AdminAudit.svelte was calling getAccountClient(null).listAuditAdmin() — explicitly passing no token. Server-side assertAdmin consequently always returned Forbidden. Fix: use the default token (getAccountClient()) so the existing admin claim travels with the call, like every other admin-panel RPC.
ab2589361e Two UX papercuts surfaced during the Playwright sweep (a) Audit log to-date parsed as UTC midnight 00:00:00.000, which excluded every event logged "today" — the default "Last 3 days" preset hid the freshly-created disable / delete entries until the admin manually picked a Custom range. Anchor to to end-of-day (23:59:59.999) inside the listAuditAdmin params builder. (b) Drawer offered the Disable button on the admin's own row; the server guard cannot_self_disable caught it, but only after the admin had clicked through. Surface isSelf client-side by decoding the JWT payload locally — no extra RPC — and grey out the button with an explanatory label. The server guard still enforces as the security primitive; this is purely a UX preview of the impossible action.
086b7f9530 Reviewer @ignatremizov flagged that hard-delete cannot ship as proven safe without a cross-reference audit + sole-owner workspace guard Hard-delete UI and RPC removed entirely from this PR. DeleteAccountConfirm.svelte deleted; deleteAccount function, postgres impl, mongo impl, AccountDB.deleteAccount interface method, 'deleteAccount' from AccountMethods union, 'delete_account' from AdminAuditAction, the client-binding in account-client, and the delete_account entry in the audit-action dropdown all removed. deleteAccount.test.ts deleted. Static grep verifies zero stragglers. Disable remains as the only account-state action in this PR. If hard-delete returns, it will be a separate smaller PR with a full content/reference audit, a sole-owner workspace guard, and an impact preview before confirmation.
08472f43e8 Operational ergonomics — admin had to manually navigate from the user drawer to the corresponding workspace V5a: each workspace-membership row in the user drawer now exposes an Open ↗ link to /workbench/<wsUrl> in a new tab. Workspace-root link only; an Employee deep-link via per-workspace Ref<Employee> lookup is deferred to a future enrichment.
2869af32ba Audit-log UX papercut — switching the date-range preset to Custom range cleared the From/To inputs and forced the admin to re-enter both V7: switching to Custom range now retains the From/To values from the previously-active preset; only on a cold-start with both inputs empty does the dialog fall back to a 3-day window.
cb8c4a2409 Audit-log timestamps were ambiguous between local time and UTC V8: each timestamp cell exposes a two-line title tooltip on hover — Local time: ... (<TZ>, UTC<offset>) and UTC: .... Extracted tzTooltip helper into its own module with 5 unit tests covering the Intl-unavailable degraded path.
1d61952b93 Denied admin actions had no audit trace V13: cannot_self_disable and last_admin (for Disable) now write an admin_action_denied audit row before throwing. Rate-limited per (actor, reason, method) in a 1-hour window. Pre-auth Forbidden writes no row. Instrumentation lives in disableAccountInternal (Step 5a), disableAccount is refactored to delegate to it (Step 5b, eliminates 50 lines of duplicate body), and bulkSetDisabled adds a pre-bulkLoop self-audit because bulkLoop short-circuits self-targets before the per-target call runs (Step 5c). 7 unit tests cover the decision matrix. Audit-action dropdown gains admin_action_denied.

Identities / Employee / Contact mapping

You asked about Employee / canonical contacts / HR integration. Where this PR sits today:

  • Subject of the panel: the global account.uuid plus its email-typed social_id. Person / Employee / Contact / HR records are workspace-internal and untouched.
  • Per-workspace Employee bridge: lives in the workspace's transactor DB, not the account DB. The admin panel is a global- account view and does not enumerate Employee rows.
  • Guest / client-contact accounts: show up the same way as User+ accounts (each has a global account row + email social-id). The drawer's role picker and the table's role chip reflect what's in global_account.workspace_members.role for that workspace.
  • GitHub OIDC-linked accounts: one global account row with an additional github-typed social-id. The drawer surfaces this in the Identities section but does not link out to the IdP — deferred.

If the value would be there, the drawer can be extended in a follow-up to add a "in workspace X, you're Employee Y" back-link. Not in this PR.

Status: Implementation complete, deployed and live-verified on our self-hosted Huly v0.7.423 instance (CockroachDB backend) for ~8 days. All admin-targeted test suites pass — 568 + 7 + 5 = 580 of 584 (the 4 pre-existing failures are in postgres-real.test.ts, which requires a live CockroachDB and fails identically at upstream/develop merge-base).

159 + 5 = 164 commits, intentionally not squashed — the original history is grouped into 6 logical phases, the new 5 commits are review-driven and each addresses one concern. Reviewers who prefer to read chronologically can follow the per-phase ranges below.

Per-phase commit ranges

Phase Range Focus
1a — Foundations 394e3db143 … efe42d1617 (~110 commits) V27 migration (account disable + token version + last activity + admin_audit_log table). New collections + service operations: listAccountsAdmin, getAccountDetails, disableAccount / enableAccount, setWorkspaceMemberRole, removeWorkspaceMember, triggerPasswordReset, addToWorkspace, bulkSetDisabled, bulkSendPasswordReset, bulkAddToWorkspace, bulkRemoveFromWorkspace. Force-logout hook (AccountDisabled Tx → client-side store). Admin-only RBAC via assertAdmin. UI: AdminShell, AdminUsers + drawer, AdminWorkspaces + drawer, MassActionConfirm, FilterPresetMenu, ColumnFilterPopup. V28 migration to relax admin_audit_log.target_account NOT NULL + 5 query-tuning indexes.
1c — Polish + tests c5da4d170c … d80a9710d0 (~10 commits) decodeFilterParam extract with strict base64 + recursive prototype-pollution rejection + 32-level depth cap (15 tests). Shared csvEscape/csvLine in @hcengineering/account-client (9 tests). mergeColumnFilters + DEBOUNCE_MS extract (5 tests). A11y basics — html lang, <th scope="col">, drawer close aria-label. Audit empty state component. AdminAudit render cap (200 rows). 10s → 30s throttle on workspace stats poll.
1d — Audit infrastructure 9e03bc3948 … d97b80f8c0 (~4 commits) Per-token CSV rate-limit (5/min, SHA-256-keyed in-memory TokenBucketLimiter, 4 tests). AUDIT_RETENTION_DAYS env-driven daily prune cron with Mongo auto-disable. V29/V30 migration: batch_id UUID NULL column + partial index WHERE batch_id IS NOT NULL, split into two migrations because CockroachDB rejects partial-index DDL on a same-tx-added column. Bulk-action service calls stamp one UUID across all their audit rows; UI groups consecutive same-batch rows under a non-interactive header.
1e — Visual design pass 4da2f06f8e … cff6e8a19e (~6 commits) Members icon prefix on Users stats row. Tabular-nums + truncate-with-tooltip on Last-activity column. Audit Details JSON collapse-by-default. GlobalSearch empty-state with query echo (later removed). Workspaces stats two-band layout (counts vs capacity). V29/V30 migration split (CockroachDB partial-index-on-new-column constraint).
Audit log redesign a267d3d2f4 … 9461de3092 (~5 commits) Removed UUID-typing filter inputs in favor of admin name/email substring + target name/url substring + actions multi-select dropdown. Sortable column headers with arrow indicator only on active sort. Per-column filter icons that scroll-and-focus the relevant top-bar input. Date-range preset dropdown (1d / 2d / 3d / 1w / 2w / 1m / Custom; default Last 3 days).
Final UX cleanup 83b9cdeedb … 60e4d27e1d (9 commits) CSV token moved from URL to Authorization header (admin UI side; legacy server fallback retained — see Security). enableAccountInternal extracted (drops N redundant assertAdmin per bulk-enable). Workspaces selection-bar count vs Mass Archive count clarified. Orphan-as-clickable-pill with row badge. All stat pills toggleable as filters. "Add workspace" primary button on Workspaces. Export CSV moved next to Presets in the filter row, regular kind. Three-button preset trio collapsed into a single Presets dropdown. postgres.test.ts mock SELECT projection updated to match V25–V27 column additions.
Review iteration 0c3af29d1c … 1d61952b93 (8 commits) Bulk-bar position; audit-listing token bug; audit date inclusive end-of-day + self-disable UI guard; hard-delete REMOVED from this PR per safety review; V5a workspace-root backlink; V7 audit Custom-range prefill; V8 timezone tooltip; V13 admin_action_denied audit. Detail in the table above.

Database migrations

Migration DDL Purpose
V27 disabled_at, token_version, last_activity_at on account + admin_audit_log table Foundation for disable / force-logout / audit
V28 admin_audit_log.target_account NULLABLE + 5 query indexes Workspace-level audit entries + admin-panel query perf
V29 admin_audit_log.batch_id UUID NULL Bulk-action correlation
V30 partial index on admin_audit_log(batch_id) WHERE batch_id IS NOT NULL Small-footprint index (single-action rows dominate)

All migrations are forward-only with IF NOT EXISTS guards. Rollback is "leave the schema, redeploy the previous account pod" — no down- migrations.

Security posture

  • decodeFilterParam: strict base64 + JSON-object + recursive __proto__/constructor/prototype rejection + 32-level depth cap. Returns 400 Bad Request with a structured reason; never silently accepts malformed input.
  • LIKE wildcards (%, _, \) escaped on every user-supplied substring filter (Users search, audit substring filters) with explicit ESCAPE '\' clauses.
  • CSV-export rate-limit: 5/min per SHA-256(token). Token is hashed before entering the limiter Map so a leaked heap dump / APM sample doesn't expose a usable admin Bearer.
  • CSV export: the admin UI now uses fetch + Authorization: Bearer + blob download instead of window.open(url-with-token). The server retains the legacy ?token=… query-string fallback for one release with a deprecation warning log, so any out-of-band scripts that bookmarked the URL keep working. Removing the legacy fallback is in the deferred list.
  • assertAdmin gates every admin-only RPC. Single-source-of-truth: ADMIN_EMAILS env. Force-logout when an active admin is disabled mid-session.

Tests

Pass: 575 / 579 across the admin-targeted suites (4 failures in postgres-real.test.ts are infra-bound, identical at upstream/develop merge-base).

Suite Result
server/account (all) 575 / 579 — 4 failures in postgres-real.test.ts are pre-existing CockroachDB-required integration tests, identical at upstream/develop merge-base
server/account-service rateLimiter 4 / 4
server/account adminActionDenied.test.ts 7 / 7 (self-disable + last_admin audit-write paths, rate-limit dedup by key, bulk method tag, pre-auth Forbidden no-audit) — new in iteration
plugins/login-resources tzTooltip.test.ts 5 / 5 (Local time / UTC line format, Intl-unavailable fallback, DST/non-DST) — new in iteration
server/account listAuditAdmin.test.ts 5 / 5
foundations/core/packages/account-client csv + listAccountsAdmin 47 / 47
plugins/login-resources (mutex, columnFilters, signupTokenGuard) 12 / 12

Total new tests added by this PR: ~125 (decodeFilterParam, csv, columnFilters, rateLimiter, pruneAuditOlderThan, escapeLike, bulkActions, listAccountsAdmin, listAuditAdmin, getAccountDetails, assertAdmin, adminActionDenied, tzTooltip).

Reviews completed before this PR

  1. Per-task implementation review — every task in Plans 1c/1d/1e passed spec-compliance review + code-quality review before integration.
  2. Independent full-codebase code review — found and we fixed: LIKE wildcard escape, bulk-enable redundant validation, CSV CRLF + BOM, 429 charset, token-in-URL.
  3. Playwright UI/UX walkthrough (original) — found and we fixed: status filter sending wrong field shape, double Popup host, stuck sort arrow, orphan-mapper drop, header/body alignment, audit filter UX, ~6 more.
  4. Three rounds of user-feedback fixes during deployment.
  5. Pre-PR test review — caught the stale postgres.test.ts mock that hadn't been updated for the V25–V27 SELECT projection additions (fixed in b90bbbcc30).
  6. End-to-end Playwright sweep of the full panel (new) — exercised T1 stat-pill filters → T9 Workspaces table. Caught the audit-token bug (Forbidden on every audit reload), the audit-date end-of-day cutoff, and the self-disable/self-delete UX gap; all three fixed in 384a81d979 and ab2589361e.

Deliberately deferred (tracked, not blocking this PR)

  • Reverse-batch CTA — design stub for a future iteration. Six open product/security questions; what's the inverse of archive_workspace in 6 months? Reset_password has no inverse. Doing this wrong is worse than not doing it.
  • Remove legacy ?token=… query-string fallback on the CSV export route once one release has shipped with the new Authorization-header flow. Currently emits a deprecation warning when hit.
  • Streaming-loop catch-all on /admin/export/accounts.csv: if listAccountsAdmin or ctx.res.write throws after the 200 header has been sent, the request fails mid-stream without a structured error envelope. Pre-existing behaviour, not introduced here, but worth hardening alongside the legacy-token-fallback removal.
  • Trigram index for audit ILIKE substring filters — only matters at

    100k row scale.

  • Unbatched audit DELETE in retention prune — only matters at >10M row scale.
  • Three duplicate workspace-picker popups (~464 LOC overlap, AddTo / BulkPick / AddMember) — refactor candidate, not a feature.
  • Pre-existing Huly icon-API drift (fill/inline/disabled props rejected by 6 icon components) — 39 console warnings per page load, upstream-side cleanup more appropriate than admin-panel side.
  • Drawer back-link to per-workspace Employee row (in response to the identities question above).

Live deployment evidence

Deployed and live-verified on a self-hosted Huly v0.7.423 instance with the CockroachDB backend and OIDC SSO. The following behaviours have been exercised end-to-end on a 12-user / 14-workspace test dataset: 5 clickable stat pills with per-pill filter state, drawer reactive refetch on row swap, outside-click + Escape drawer dismiss, Workspaces per-row selection + selection-driven Mass Archive, batch_id row grouping in the audit log, date-range presets, CSV export with Authorization header, CSV rate-limit 429 response, and self-disable UI guard on the admin's own row (Disable button greyed with explanatory label when the caller is the target).

Screenshots in hcengineering/huly-docs#71 (src/assets/screenshots/huly/admin-panel/).

Notes for upstream reviewers

  • CommunityDB.ts (CockroachDB) backend only — Mongo collection stubs throw "not implemented" with a meaningful error. The audit retention cron auto-disables itself on Mongo to avoid log spam.
  • English-only UI strings so far; getEmbeddedLabel everywhere so i18n is a future drop-in.
  • No new dependencies added to package.json (uses existing Huly primitives: @hcengineering/ui Button / ButtonMenu / Dropdown / CheckBox, @hcengineering/platform getEmbeddedLabel, postgres.js Sql template tag).
  • Sign-off + DCO compliant; single author across all 164 commits.
  • Squash-merge is fine if you prefer a single commit on develop. We've kept the granular history as documentation, not because we insist on preserving it.

MichaelUray avatar May 25 '26 13:05 MichaelUray

Connected to Huly®: UBERF-16473

huly-github-staging avatar May 25 '26 13:05 huly-github-staging

Share some screenshots, would be interesting to see. But also I think this PR is too big

ignatremizov avatar May 25 '26 15:05 ignatremizov

@ignatremizov thanks for taking a look! Both points well taken.

Screenshots — the companion docs PR hcengineering/huly-docs#71 already carries 14 anonymized captures (1700×1000) of every panel state. The most informative ones at a glance:

Sidebar sidebar
Users — landing users-default
Users — drawer users-drawer
Users — bulk bar users-bulk
Workspaces workspaces-default
Workspaces — mass archive workspaces-mass
Audit log audit-default
Audit — filters audit-filters

Full set (14 PNGs) in src/assets/screenshots/huly/admin-panel/.

PR size — fair, ~159 commits. Happy to split if that makes review easier. My suggested cut, each PR independently deployable, each on its own branch, in this order so later PRs can build on the earlier migrations:

Split PR Phases from the table What's in it LOC est.
PR-A — Foundations + Users tab 1a + 1c V27 + V28 migrations, `assertAdmin` RBAC, force-logout, AdminShell + AdminUsers + drawer + mass actions, Export CSV (still with `?token=` URL), `decodeFilterParam` hardening largest
PR-B — Workspaces tab + Audit log infra 1d + Visual pass AdminWorkspaces + drawer, V29 + V30 migrations (`batch_id` + partial index), audit table + retention cron + CSV rate-limit, `batch_id` row grouping medium
PR-C — Audit redesign + final UX cleanup Audit redesign + Final UX substring/date-preset audit filters, sort headers, CSV moved to `Authorization` header, Presets dropdown collapse, selection-bar clarifications small

If you'd prefer a different split (e.g. extract V27–V30 as a backend-only PR first, then UI), just say so — happy to land it however gets the review through.

Either way I'll keep the current PR open until you tell me to close + repost, so review work here isn't lost.

MichaelUray avatar May 25 '26 22:05 MichaelUray

Thanks for the detailed reply @MichaelUray

It's up to the maintainers how they want the review PRs - kept as is or split.

My two cents, for UX, bulk actions bars are usually at the top of the table, either appearing just under the header row, or above the table, rarely below it

Also check the identities management of users when connected with GitHub, and how it interfaces with canonical contacts/ employee and the new beta HR management areas. User can mean a lot of things - also guest users or client contacts that could be added to the workspace.

Would be good to add in your PR body what problem this solves - it sounded like you manage multiple workspaces and would avoid SQL for mass user management across those workspaces, which is fair. I'm new to the codebase so I'm not sure how well Huly supports multi tenancy, sounds like an admin of workspaces primitive existed but wasn't adequately exposed for controls?

I think it might be better expanding existing user/person management surfaces rather than creating new ones, but again, it's just a question of UX and long-term maintance.

ignatremizov avatar May 25 '26 23:05 ignatremizov

@ignatremizov — thank you again for taking the time on the first review. Every one of the three points you raised has produced a concrete change in the code now. Walkthrough below.

1. Bulk-action bar position

You wrote:

bulk actions bars are usually at the top of the table, either appearing just under the header row, or above the table, rarely below it

Fully agreed once you pointed it out — the original "sticky bottom" came from wanting to avoid a layout shift on first selection, but that's a worse trade than the convention break. Moved to a sticky-top position directly above the table, between the filter row and the header row, hidden when no rows are selected. Commit 0c3af29d1c.

Bulk action bar in its new top position above the user table

2. Identities — Employee / Contact / HR / Guest / GitHub

You raised the broader concern of how this panel relates to canonical Person / Employee / Contact records, the beta HR area, guest accounts, and GitHub-linked identities. Here is exactly where the panel sits today and where it deliberately does not reach:

Concept Storage Touched by this PR?
Global account.uuid + primary social_id (email) account DB (global_account.account, global_account.social_id) Yes — this is the subject of the panel.
huly-typed and oidc-typed social IDs account DB Surfaced read-only in the drawer's Identities section.
github-typed social ID account DB Surfaced read-only as an additional row. No back-link to the IdP yet; tracked as a follow-up.
contact:class:Employee (per workspace) workspace transactor DB Not touched. Lives in a different DB; the panel is global-account-scoped.
contact:class:Person, HR mixins, HR-beta records workspace transactor DB Not touched.
workspace_members.role (per workspace) account DB Read + edited via the drawer's role picker.

So a single human can appear as: (a) one global account, (b) zero-to-N Employees (one per workspace they joined), (c) one Person/Contact entry per workspace, (d) optional GitHub identity. The admin panel currently surfaces (a) and the role part of workspace_members. It does not yet draw a back-link from the drawer to the per-workspace Employee row — fair smell, tracked as a follow-up rather than landed in this PR, because the right shape (full mini-card vs. just a "in workspace X you're Employee Y" line) is the kind of decision worth a quick design pass.

Guest accounts and external client contacts appear in the table the same way as User+ accounts (each carries a global account row + an email social ID). The role chip in the table and the role picker in the drawer reflect what's in global_account.workspace_members.role for the workspace in question, including GUEST / READONLYGUEST.

3. PR body — what problem this solves

That was the gap. The PR body now opens with a "The problem this solves" section that states the operator pain (every cross-workspace administrative task today routes through raw SQL), then a "What already existed" subsection that maps each new piece of UI to the existing account-service primitive it wraps (assignWorkspace, unassignWorkspace, setWorkspaceMemberRole, social-id management, ADMIN_EMAILS-gated mass operations), and finally a "Why a separate route" subsection explaining why neither Settings → Members (workspace-scoped) nor the small system-manager plugin (per-workspace transactor session) was the right host for cross-workspace account management.

Your specific suggestion — "it might be better expanding existing user/person management surfaces rather than creating new ones" — got an explicit answer there too: the two existing surfaces we evaluated were Settings → Members (wrong domain — workspace-scoped, can't cross-workspace) and system-manager (wrong session boundary — runs inside per-workspace transactor; the admin panel needs to work even when no workspace is open). If you'd rather see the routes folded under system-manager once the dust settles, the URLs can be moved without restructuring the data path; the panel talks to the account-service RPC, not the transactor, which is the property that drove the separate-route decision.

Two additional things I owed back to the review

While verifying the above with an end-to-end Playwright sweep of the panel, two more bugs surfaced. Both fixed in this iteration:

  • Audit log was always empty under password-auth. AdminAudit.svelte was calling getAccountClient(null).listAuditAdmin() — explicitly passing no token — and the server-side assertAdmin was therefore always returning Forbidden. Fixed in 384a81d979 by using the default token like every other admin RPC. The audit log was unusable before this commit; reviewers checking on dev or any password-auth instance would not have seen rows.
  • Audit log date-cutoff at midnight excluded today's events. The yyyy-mm-dd to input parsed as UTC midnight 00:00:00.000, so the default "Last 3 days" preset hid every entry from today. Anchored to to end-of-day (23:59:59.999) in ab2589361e.

Hard-delete account (operator gap reported separately)

Came up in parallel testing as the missing companion to Disable. Added behind a typed-DELETE confirm dialog with the full irreversible cascade enumerated up front — account row, password, workspace memberships, mailbox secrets, integration secrets, billing subscriptions, per-workspace permission grants. Social IDs are kept but marked un-verified so historical createdBy / modifiedBy references stay readable.

Delete account confirmation dialog with typed DELETE input and consequences list

Server-side guards (cannot_self_delete, last_admin, Forbidden) refuse the call before the cascade fires. A follow-up Codex review of the delete commit caught a real release blocker — V19 subscription and V24 workspace_permissions rows have FK to account(uuid) with no ON DELETE CASCADE, so the final DELETE FROM account would have hit a constraint violation for any account that owned a billing row or a per-workspace permission grant. Fixed by clearing both tables in the same transaction. Seven Jest tests cover admin-token, self-delete, AccountNotFound, last-admin, success cascade + audit insert, and OIDC-only target. All green.

In the drawer, both Disable and Delete are greyed out when opened on the calling admin's own row so the destructive paths are unreachable client-side. Server guards still enforce as the security primitive — this is a UX layer that surfaces the "you can't do this" earlier than the typed-confirm step.

Drawer with Disable and Delete greyed out on the admin's own account

Bulk delete is intentionally not offered. Hard-delete is irreversible and the bulk-bar pattern (one click + one dialog) is too easy to misfire on a destructive operation. For fleet cleanup: Disable first, then delete one row at a time.

The new delete_account entries surface in the Audit log alongside the existing actions:

Audit log filtered showing delete_account rows

Status

5 new commits since the original PR head, all on feat/admin-user-management. 12/12 Jest tests pass on the new + existing admin suites; full npm run build for the docs site is green. Deployed and live-verified for ~8 days on our self-hosted v0.7.423 + CockroachDB instance.

Companion docs PR hcengineering/huly-docs#71 is updated to match, including the three new sections (Danger zone — Delete account, Self-block, delete_account in Audit) and 17 anonymized screenshots.

Thanks again — the review was load-bearing for the iteration; happy to keep going on anything else.

MichaelUray avatar May 26 '26 05:05 MichaelUray

Is hard delete safe? How would it affect Tracker issues assigned/created by the user? Chats? Cards? Documents? Do they disappear in the delete cascade, or render with an error/empty user slot?

Usually suspend is the only option available in most services due to data integrity... Hard delete may introduce unintended consequences.

I've seen only GitHub on hard delete just re-assign user repos/comments to "@ghost" when an account has been hard deleted, which is somewhat elegant but loses auditability. Suspend/soft-delete is usually just much safer.

ignatremizov avatar May 26 '26 07:05 ignatremizov

This is a fair concern. I re-checked the delete path and agree it should not ship in this PR.

I'm removing the hard-delete UI and RPC from #10883. Disable remains as the only account-state action in this PR. It's reversible — it preserves the account / person / social-id anchors, blocks login via the disabled_at flag, and doesn't touch authored workspace content.

If hard-delete comes back, I'll do it as a separate, smaller PR with an explicit content/reference audit, sole-owner workspace guard, and an impact preview before confirmation. I also want to separate that from a privacy-oriented anonymization path, since deleting authored project content is not the same problem as removing personal identifiers.

The structural removal commit is 086b7f9530 — DeleteAccountConfirm.svelte deleted, deleteAccount RPC + DB cascade + types-union entries + client binding + delete_account from the audit-action dropdown all removed; deleteAccount.test.ts deleted. Static grep against the working tree shows zero deleteAccount / delete_account / DeleteAccountConfirm / cannot_self_delete references outside lib/ and *.d.ts output. Disable's existing cannot_self_disable + last_admin guards stay as before.

Four additional commits layered on top while this branch was up for review (V5a workspace-root link in the drawer, V7 audit Custom-range pre-fill, V8 audit timestamp timezone tooltip, V13 admin_action_denied audit event for the surviving Disable / last_admin denials). The PR body's iteration table has the per-commit detail.

Thanks for catching this before it shipped as default-on — the answer to "is hard-delete safe?" was "we haven't proven it yet," and shipping with that assumption would have been wrong.

MichaelUray avatar May 27 '26 14:05 MichaelUray

Cool, yeah it's good to not include it. I'd also suggest to update PR body to remove that block about hard delete.

Edit: I see removed already 👍

ignatremizov avatar May 27 '26 14:05 ignatremizov