Skip to content

feat(admin): user management CRUD — pagination, search/filter, createUser, expanded updateUser - #52

Merged
voidvec merged 10 commits into
masterfrom
feat/user-management-crud-v2
Aug 14, 2026
Merged

voidvec merged 10 commits into
masterfrom
feat/user-management-crud-v2

Conversation

@voidvec

@voidvec voidvec commented Aug 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

A2 user-management补全 (全栈) + Phase 2 deleteUser soft-delete.

Backend

Change Detail
listUsers pagination page, per_page, q (username/email LIKE), role (JOIN-free fan-out), locked (derived from locked_until). Real total via Mapper::count. Response: {page, per_page, total, total_pages, users}
createUser (POST) PBKDF2-SHA256 hash + default role + audit. 201 on success; 409 on duplicate username/email (constraint-name matching)
updateUser expanded username, mfa_enabled, locked, org_id (was email + email_verified only)
deleteUser (DELETE) V024 migration adds deleted_at; soft-delete sets timestamp + audit. All user queries filter deleted_at IS NULL
AuthorizationFilter Persists userId/scope/clientId for admin audit logging
OpenAPI POST + DELETE endpoints with schemas

Frontend

  • UsersPage: pagination, search/filter, Create + Delete buttons with confirm
  • UserDetailPage: Info tab expanded (username, mfa, locked, org_id editable)
  • mock-api: pagination, POST create, DELETE handler

Verification

  • ✅ Full 8-step backend test: 452/452 ctest pass, all endpoint tests pass
  • ✅ Frontend: npm run build + npm run test:unit pass
  • ✅ api-diff / arch-guard / migration-check: all pass

…User, expanded updateUser (#A2)

Backend:
- listUsers: real pagination (page/per_page, total count via Mapper::count),
  search (q on username/email), filters (role via JOIN-free fan-out,
  locked derived from locked_until)
- createUser (POST /api/admin/users): PBKDF2 hash + default role assignment +
  audit log (user_create); 201 Created response
- updateUser: expanded to username, mfa_enabled, locked, org_id
  (was email + email_verified only)
- AuthorizationFilter: persist userId/scope/clientId onto request attributes
  (was only done by OAuth2AuthFilter) so admin handlers can identify the actor
- OpenAPI: added POST /api/admin/users + query params on GET list

Frontend:
- UsersPage: pagination controls, search bar, role/locked filters,
  Create User modal (username/password/email/roles)
- UserDetailPage: Info tab expanded — username, mfa_enabled, locked,
  org_id now editable (was email + email_verified only)
- mock-api: paginated GET handler + POST create mock with duplicate detection
- e2e: create-user, search-filter, duplicate-username test cases

Tests:
- AdminUserApiHttpTest: 7 new cases (create success/dup/missing, pagination,
  search, expanded update, locked filter)

Stacked on PR #49 (feat/resource-scope-authorization-43); rebase to master
after #49 merges.
…User/updateUser

Code review (PR #51): the previous generic 'unique'/'duplicate' substring
match always reported VALIDATION_USERNAME_TAKEN even for duplicate emails.
Now matches constraint names (users_username_key / idx_users_email_unique)
like AuthService and PostgresIdentityRepository already do.
…minUserId, unique suffix

- DuplicateUsername test: VALIDATION_USERNAME_TAKEN maps to HTTP 409 (not 400)
- findAdminUserId: use ?q=admin search to find admin user across pages (admin
  user is at id=513, not page 1 of default per_page=50)
- uniqueSuffix: use 9-digit modulo to avoid collisions across rapid re-runs
- mock-api: POST duplicate returns 409 to match backend

All 16 AdminUser tests pass with local PostgreSQL (7 new + 9 existing).
…are endpoint scripts

- OpenApi fingerprint: add POST /api/admin/users entry
- route_manifest.txt golden: add POST /api/admin/users
- test-admin-endpoints.ps1/.sh: use ?q= search for admin/test user lookup
  (list endpoint is now paginated, admin user not always on page 1)
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

…end)

Backend:
- V024: add deleted_at column to users table
- deleteUser (DELETE /api/admin/users/{userId}): soft-delete + audit
- All user queries filter deleted_at IS NULL
- OpenAPI: DELETE endpoint

Frontend: UsersPage Delete button with confirm; mock-api DELETE handler
Tests: delete soft-delete integration test + baseline updates
Security: mock-api credential-looking values replaced with process.env pattern
Full-test ORM regen output — required for CI builds that don't run
the ORM regeneration step. Adds deleted_at accessors to Users.h/.cc.
… non-public-surface)

The dirtyFlag_ array size changed [17]→[18] because V024 added the
deleted_at column. This is an internal ORM-generated field, not part
of the SDK public API surface. Used --force per the tool's guidance
for verified non-public-surface changes.
@voidvec

voidvec commented Aug 14, 2026

Copy link
Copy Markdown
Owner Author

PR #52 Review — user-management CRUD (pagination, search/filter, createUser, expanded updateUser, soft-delete)

Verdict: Request changes — 1 critical + 1 high functional issue must be fixed before merge.

🔴 Critical

1. Soft-delete does not block login (security/correctness)
The PR states a soft-deleted user "can no longer log in," but AuthService::authenticate
(libs/drogon/src/AuthService.cc:35-43) looks up the user by username/email with no
deleted_at IS NULL filter
, and a codebase-wide grep shows no other path (token
issuance, userinfo, refresh) filters soft-deleted users. A soft-deleted user can therefore
still authenticate via the password grant and obtain a valid access token — the soft-delete
is ineffective for its stated purpose.
Fix: add Criteria(Users::Cols::_deleted_at, CompareOperator::IsNull) to every
authentication/authorization user lookup (login, token introspection, refresh, self-service
verify). This is the single most important change.

🟠 High (functional)

2. getUser omits org_id — the edit UI is broken
The detail GET (UserAdminService.cc, getUser()) returns
id, username, email, email_verified, mfa_enabled, failed_login_count, locked, locked_until, created_at, roles but not org_id. The PR's UserDetailPage.vue displays and edits
org_id (reads resp.data.org_id), yet since it is never returned:

  • the field always renders empty, and
  • the save-diff guard editOrgId !== (user.org_id ?? '') never triggers, so an org_id
    change can never be detected/sent.
    Fix: add json["org_id"] = row.getValueOfOrgId(); in getUser() (and ideally in
    userRowToListJson if lists should show it).

🟡 Medium

3. Case-sensitive LIKE vs case-insensitive mock
listUsers builds username/email LIKE 'q%' (PostgreSQL VARCHAR, case-sensitive), while
the frontend mock (mock-api.ts) does toLowerCase().startsWith. So an admin searching
"Admin" won't find the seeded "admin" in prod, but e2e (mock) would match — prod/CI
divergence and a real UX gap. Emails are normalized to lowercase on create, but q is not
lowercased, so uppercase email search also misses.
Fix: use ILIKE (or lower(col) LIKE lower('q%')) for both columns; also escape
%/_ in q (they are currently interpreted as LIKE wildcards).

4. Silent partial failure on role assignment in createUser
The user row is inserted and 201 returned even when the user_roles inserts fail; the
user then has no role → no permissions, with no error surfaced to the caller.
Fix: at minimum log a warning and/or include a flag in the response; consider failing
the create (or rolling back) if role assignment is essential.

5. Unvalidated org_id / locked type coercion
(*jsonBody)["org_id"].asInt() (createUser ~line 1818; updateUser ~line 2015) and
["locked"].asBool() throw Json::LogicError on non-conforming input (e.g. string). These
run inside async DB callbacks, so the exception is uncaught → 500 / crash.
Fix: guard with isConvertibleTo(Json::intValue) / isBool() before coercion.

6. No self / last-admin delete guard
An admin can delete their own account or all admins via DELETE /api/admin/users/{userId},
causing lockout/DoS.
Fix: reject self-deletion and last-admin deletion (or require a second factor).

🟢 Low / suggestions

  1. Migration index idx_users_deleted_at is low-value for the dominant deleted_at IS NULL
    scan; prefer a partial index CREATE INDEX ... ON users(deleted_at) WHERE deleted_at IS NULL.
  2. createUser has no password-strength policy (only non-empty check). Consider a minimum
    length/complexity rule for admin-created accounts.
  3. Re-creating a soft-deleted username/email is blocked by UNIQUE constraints (identity reuse
    prevention). Confirm this is intended and document it.
  4. The createUser 201 user object lacks roles/org_id (only userRowToListJson);
    enrich for client convenience.
  5. q containing %/_ is treated as a LIKE wildcard — escape these characters.

✅ Strengths

  • Backward-compatible migration (ADD COLUMN IF NOT EXISTS, nullable deleted_at).
  • Audit logging wired for create/update/delete via the principal persisted by
    AuthorizationFilter (userId/scope/clientId).
  • Real pagination (count + paginate) with JOIN-free role fan-out.
  • Correct UNIQUE-violation disambiguation by constraint name (users_username_key vs
    idx_users_email_unique), matching AuthService/PostgresIdentityRepository.
  • PBKDF2 hashing (PasswordHasher::hash) is consistent with PasswordHasher::verify
    (the salt column is correctly unused for PBKDF2), so newly created users authenticate.
  • Comprehensive tests: 7 new integration cases + e2e + mock-api fixes + baseline updates;
    full 8-step backend pipeline green (452/452 ctest).

Line references are on head branch feat/user-management-crud-v2.

1 similar comment
@voidvec

voidvec commented Aug 14, 2026

Copy link
Copy Markdown
Owner Author

PR #52 Review — user-management CRUD (pagination, search/filter, createUser, expanded updateUser, soft-delete)

Verdict: Request changes — 1 critical + 1 high functional issue must be fixed before merge.

🔴 Critical

1. Soft-delete does not block login (security/correctness)
The PR states a soft-deleted user "can no longer log in," but AuthService::authenticate
(libs/drogon/src/AuthService.cc:35-43) looks up the user by username/email with no
deleted_at IS NULL filter
, and a codebase-wide grep shows no other path (token
issuance, userinfo, refresh) filters soft-deleted users. A soft-deleted user can therefore
still authenticate via the password grant and obtain a valid access token — the soft-delete
is ineffective for its stated purpose.
Fix: add Criteria(Users::Cols::_deleted_at, CompareOperator::IsNull) to every
authentication/authorization user lookup (login, token introspection, refresh, self-service
verify). This is the single most important change.

🟠 High (functional)

2. getUser omits org_id — the edit UI is broken
The detail GET (UserAdminService.cc, getUser()) returns
id, username, email, email_verified, mfa_enabled, failed_login_count, locked, locked_until, created_at, roles but not org_id. The PR's UserDetailPage.vue displays and edits
org_id (reads resp.data.org_id), yet since it is never returned:

  • the field always renders empty, and
  • the save-diff guard editOrgId !== (user.org_id ?? '') never triggers, so an org_id
    change can never be detected/sent.
    Fix: add json["org_id"] = row.getValueOfOrgId(); in getUser() (and ideally in
    userRowToListJson if lists should show it).

🟡 Medium

3. Case-sensitive LIKE vs case-insensitive mock
listUsers builds username/email LIKE 'q%' (PostgreSQL VARCHAR, case-sensitive), while
the frontend mock (mock-api.ts) does toLowerCase().startsWith. So an admin searching
"Admin" won't find the seeded "admin" in prod, but e2e (mock) would match — prod/CI
divergence and a real UX gap. Emails are normalized to lowercase on create, but q is not
lowercased, so uppercase email search also misses.
Fix: use ILIKE (or lower(col) LIKE lower('q%')) for both columns; also escape
%/_ in q (they are currently interpreted as LIKE wildcards).

4. Silent partial failure on role assignment in createUser
The user row is inserted and 201 returned even when the user_roles inserts fail; the
user then has no role → no permissions, with no error surfaced to the caller.
Fix: at minimum log a warning and/or include a flag in the response; consider failing
the create (or rolling back) if role assignment is essential.

5. Unvalidated org_id / locked type coercion
(*jsonBody)["org_id"].asInt() (createUser ~line 1818; updateUser ~line 2015) and
["locked"].asBool() throw Json::LogicError on non-conforming input (e.g. string). These
run inside async DB callbacks, so the exception is uncaught → 500 / crash.
Fix: guard with isConvertibleTo(Json::intValue) / isBool() before coercion.

6. No self / last-admin delete guard
An admin can delete their own account or all admins via DELETE /api/admin/users/{userId},
causing lockout/DoS.
Fix: reject self-deletion and last-admin deletion (or require a second factor).

🟢 Low / suggestions

  1. Migration index idx_users_deleted_at is low-value for the dominant deleted_at IS NULL
    scan; prefer a partial index CREATE INDEX ... ON users(deleted_at) WHERE deleted_at IS NULL.
  2. createUser has no password-strength policy (only non-empty check). Consider a minimum
    length/complexity rule for admin-created accounts.
  3. Re-creating a soft-deleted username/email is blocked by UNIQUE constraints (identity reuse
    prevention). Confirm this is intended and document it.
  4. The createUser 201 user object lacks roles/org_id (only userRowToListJson);
    enrich for client convenience.
  5. q containing %/_ is treated as a LIKE wildcard — escape these characters.

✅ Strengths

  • Backward-compatible migration (ADD COLUMN IF NOT EXISTS, nullable deleted_at).
  • Audit logging wired for create/update/delete via the principal persisted by
    AuthorizationFilter (userId/scope/clientId).
  • Real pagination (count + paginate) with JOIN-free role fan-out.
  • Correct UNIQUE-violation disambiguation by constraint name (users_username_key vs
    idx_users_email_unique), matching AuthService/PostgresIdentityRepository.
  • PBKDF2 hashing (PasswordHasher::hash) is consistent with PasswordHasher::verify
    (the salt column is correctly unused for PBKDF2), so newly created users authenticate.
  • Comprehensive tests: 7 new integration cases + e2e + mock-api fixes + baseline updates;
    full 8-step backend pipeline green (452/452 ctest).

Line references are on head branch feat/user-management-crud-v2.

… fixes

Critical #1: soft-deleted users can no longer log in
- PostgresIdentityRepository: add deleted_at IS NULL filter to
  findByEmail, findByUsername, findById, findByPublicSub, getUserInfoWithRoles,
  getRoles(subject) — blocks login, userinfo, and token-issuance role resolution
- deleteUser: revoke all access + refresh tokens for the deleted user
  (introspection/refresh copy subject from token rows, never query users)

High #2: getUser now returns org_id in the response JSON

Medium #3: listUsers search escapes LIKE wildcards (%/_) in query param q

Medium #5: createUser/updateUser guard org_id/locked type coercion
  with isInt()/isBool() to prevent uncaught Json::LogicError in async callbacks

Medium #6: deleteUser rejects self-deletion (admin cannot delete own account)
@voidvec
voidvec merged commit 4979bad into master Aug 14, 2026
8 checks passed
voidvec added a commit that referenced this pull request Aug 14, 2026
…1 delivery

Restores the memory-verdict updates lost when the working tree was
switched to feat/user-management-crud-v2 (the previous edits were never
committed), and syncs all tracking docs with the newly delivered work:

Memory verdict (⚠️ → ✅, re-applied across 4 docs):
- SDK embedding scope measured 2026-08-13: third-party-host-smoke
  (pure SDK) peak working set 2.5 MB / private 0.6 MB / binary 12 MB;
  full-stack-host-smoke (SDK+Drogon) also 2.5 MB peak
- 50-120MB claim conservatively MET — actual SDK logic layer far below
- docker stats 2.4GB is a different scope (container: pools + shared
  libs + page cache), not comparable to the SDK claim

Newly delivered work synced:
- A2 user management CRUD — IMPLEMENTED (PR #52): pagination, search,
  createUser, updateUser expansion, deleteUser soft-delete (V024)
- D1 Backchannel Logout — BACKEND DELIVERED (PR #50): notifier +
  logout_token JWT + admin API + discovery + unit tests D1-D6;
  frontend blocked by Mimosa false-positive, integration tests pending
- Phase 2 completion raised ~25% → ~45%; Phase 0 raised ~85% → ~90%
- IAM audit: user mgmt + backchannel logout rows updated to delivered
- next-phase plan: completed-tiers table extended, A2/B1 sections
  marked delivered, dependency graph + risk matrix + decision items
  updated (decisions 1-3 now resolved)
voidvec added a commit that referenced this pull request Aug 15, 2026
…1 delivery

Restores the memory-verdict updates lost when the working tree was
switched to feat/user-management-crud-v2 (the previous edits were never
committed), and syncs all tracking docs with the newly delivered work:

Memory verdict (⚠️ → ✅, re-applied across 4 docs):
- SDK embedding scope measured 2026-08-13: third-party-host-smoke
  (pure SDK) peak working set 2.5 MB / private 0.6 MB / binary 12 MB;
  full-stack-host-smoke (SDK+Drogon) also 2.5 MB peak
- 50-120MB claim conservatively MET — actual SDK logic layer far below
- docker stats 2.4GB is a different scope (container: pools + shared
  libs + page cache), not comparable to the SDK claim

Newly delivered work synced:
- A2 user management CRUD — IMPLEMENTED (PR #52): pagination, search,
  createUser, updateUser expansion, deleteUser soft-delete (V024)
- D1 Backchannel Logout — BACKEND DELIVERED (PR #50): notifier +
  logout_token JWT + admin API + discovery + unit tests D1-D6;
  frontend blocked by Mimosa false-positive, integration tests pending
- Phase 2 completion raised ~25% → ~45%; Phase 0 raised ~85% → ~90%
- IAM audit: user mgmt + backchannel logout rows updated to delivered
- next-phase plan: completed-tiers table extended, A2/B1 sections
  marked delivered, dependency graph + risk matrix + decision items
  updated (decisions 1-3 now resolved)
wangrh0909 pushed a commit that referenced this pull request Aug 16, 2026
…1 delivery

Restores the memory-verdict updates lost when the working tree was
switched to feat/user-management-crud-v2 (the previous edits were never
committed), and syncs all tracking docs with the newly delivered work:

Memory verdict (⚠️ → ✅, re-applied across 4 docs):
- SDK embedding scope measured 2026-08-13: third-party-host-smoke
  (pure SDK) peak working set 2.5 MB / private 0.6 MB / binary 12 MB;
  full-stack-host-smoke (SDK+Drogon) also 2.5 MB peak
- 50-120MB claim conservatively MET — actual SDK logic layer far below
- docker stats 2.4GB is a different scope (container: pools + shared
  libs + page cache), not comparable to the SDK claim

Newly delivered work synced:
- A2 user management CRUD — IMPLEMENTED (PR #52): pagination, search,
  createUser, updateUser expansion, deleteUser soft-delete (V024)
- D1 Backchannel Logout — BACKEND DELIVERED (PR #50): notifier +
  logout_token JWT + admin API + discovery + unit tests D1-D6;
  frontend blocked by Mimosa false-positive, integration tests pending
- Phase 2 completion raised ~25% → ~45%; Phase 0 raised ~85% → ~90%
- IAM audit: user mgmt + backchannel logout rows updated to delivered
- next-phase plan: completed-tiers table extended, A2/B1 sections
  marked delivered, dependency graph + risk matrix + decision items
  updated (decisions 1-3 now resolved)
voidvec added a commit that referenced this pull request Aug 17, 2026
CHANGELOG for v1.2.0 (61 commits since v1.1.0): #43 resource-scope
authorization model, A2 user-management CRUD (PR #52), B1 back-channel
logout backend (PR #50), A1 OpenAPI spec governance M0 + breaking-change
gates (PR #63), benchmark M2-M4 load-bearing verdicts (PR #48), and the
#53-#60 user-admin hardening batch (PR #62).

Per the release SOP (docs/backend/versioning-and-release.md §11.1):
draft via `git cliff --unreleased --tag v1.2.0 --prepend`, then
hand-curated (themed sections, security-hardening migrations, noise
removed). Version SSoT already bumped to 1.2.0 in e5548ec; api-diff and
the new spec-governance gate verified OK on the release ref.
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