Repository navigation
fix(auth,admin): #53 #54 #56 #58 #59 #60 — soft-delete contract enforcement + user-admin hardening - #62
Merged
Conversation
…service paths Soft-deleted users could obtain fresh tokens via GitHub social login (the V024 "can no longer log in" contract bypass), complete MFA verification, and keep using /api/me self-service endpoints. - ISocialAccountRepository::findLinkedUser: optional<SocialAccountLookup> -> explicit four-state SocialLinkStatus (Linked / NoMapping / AccountUnavailable / RepositoryError). The old contract conflated "no mapping" with DB errors (a DB outage sent the flow into account CREATION) and could not express "linked user is dead" at all. - PostgresSocialAccountRepository: findBy (not findOne) so zero-rows and DB exceptions are distinct; users lookup filters deleted_at IS NULL and rejects locked users (parity with the password path); the error callback no longer FAKES a success (old code returned username="user" and issued tokens for a user it could not read). - All three social upserts (GitHubController::createNewLinkedUser, PostgresSocialAccountRepository::createLinkedUser, PostgresIdentityRepository::createUserForExternalLogin) switch from ON CONFLICT (username) DO UPDATE to DO NOTHING — fail closed. DO UPDATE "adopted" whatever row held the username: soft-deleted rows got resurrected, and an ACTIVE row registered locally (e.g. victim's gh_alice) was silently taken over by a GitHub user named alice (the upsert returned the victim's id -> attacker_subject->victim_id mapping -> tokens issued as the victim). Empty RETURNING is checked BEFORE indexing (Result::operator[](0) on empty is UB). - GitHubController::linkExistingUser (fallback path): the user fetch result was previously ignored ((void)users) and tokens were issued unconditionally; now filters deleted_at and rejects locked users with the password path's generic AUTH_INVALID_CREDENTIALS. - MfaController: all fallback lookups filter deleted_at; verifyLogin (both paths) additionally rejects locked users — completing a login for a user soft-deleted/locked between first and second factor was a token minting bypass (TOCTOU). - UserSelfServiceController: all lookups filter deleted_at (deleted user -> 404, never data); deleteAccount now sets deleted_at (it previously only anonymized, leaving a live row — V024 gap), revokes tokens on both keys, and 409s when the caller is the last active admin. - PostgresIdentityRepository::getInternalUserId resolves the mapping against a live users row (split query) so the consent->code->token chain cannot mint tokens for a deleted user. - oauth2_subject_mappings rows are intentionally KEPT on soft-delete (reversibility); login/consent are rejected through the filters above. Atomic commit: the interface change and every in-tree consumer (GitHubAuthService, Fake, Postgres impl, tests) move together.
#53 (High): updateUser/createUser performed unguarded jsoncpp coercions (asString/asBool) inside async DB callbacks — a wrong-typed field threw Json::LogicError into the Drogon event loop and aborted the process (SIGABRT). Both endpoints now type-validate every provided field up front and answer 400. This also removes the old silent-skip- on-type-mismatch behavior (#59-3): a malformed request never looks like a successful update. Defense-in-depth: the updateUser callback body is wrapped so no future coercion can escape. #56 (Medium): deleteUser's token revocation was two fire-and-forget execSqlAsync calls with EMPTY success AND error callbacks inside catch(...){} — a failed revocation left a soft-deleted user's refresh token rotatable forever with zero output. The two UPDATEs are now chained (access -> refresh) and the response waits for both; every error path LOG_ERRORs. Dual key: password-flow tokens store the public sub in user_id, GitHub-flow tokens store the internal id — the old single-key revocation missed every social-issued token. The 200 body now reports tokens_revoked (false + warning + audit outcome "partial" on failure — soft-delete itself already succeeded, so 500 would be a lie and unretryable). #58 (Medium): user search used case-sensitive LIKE while the e2e mock matched case-insensitively (prod/CI divergence) and the comment claimed lowercasing that didn't exist. Now lower(col) LIKE lower(q) via Criteria's colName slot (parameterized API use, not raw SQL); ASCII-only fold with the mandatory unsigned-char cast; comment fixed. #59 (Medium): org_id NULL serialized as 0 (getValueOfOrgId default — a nonexistent org), could never be cleared (no setOrgIdToNull path, the frontend's '' was silently skipped). getUser now uses the nullable accessor (JSON null when unset); PUT accepts int (set) / JSON null (clear, -> setOrgIdToNull) / anything else 400. #60-1 (Low): createUser answered 201 "success" even when role assignment failed (permission-less user, admin none the wiser). The 201 body now reports roles_assigned / roles_failed (+ warning + LOG_ERROR when failures occurred). #60-2 (Low): last-active-admin guard. Deleting/disabling/locking the only other active admin, demoting them via /roles, or self-deleting via /api/me locked out the management plane. Shared isLastActiveAdmin helper (three Mapper queries, JOIN-forbidden; "active" = not deleted AND not locked, NULL locked_until = unlocked) guards all five paths with VALIDATION_RESOURCE_CONFLICT 409. Known accepted TOCTOU race between two concurrent last-admin operations documented in the header. #60-5 + audit residue: every Mapper construction in UserAdminService.cc now sits in its own try/catch invoking the error callback (db-operations rule; the old code left 13 constructions bare). Existing DisableEnable test adapted: promotes a throwaway second admin (RAII cleanup) since the seeded admin now correctly 409s. HttpTestClient: loginAsUserTokens — generalized password login for an arbitrary user returning the full token JSON (refresh-token revocation tests need the refresh token).
Get-PostgresContainer / get_postgres_container matched any container
whose name contains "postgres". On a machine running an unrelated
postgres container (here: ory-bench-postgres), the admin-account reset
docker-exec'd into the WRONG database ("role oauth2_user does not
exist"), silently failing. The password-change endpoint test (Test 17)
can only restore the seeded admin/admin credential via this DB reset
(the API restore path is structurally unusable: its restore token
requests scope=openid only -> 403 on /api/me/password, and the seeded
password 'admin' violates the >=8-char policy), so every subsequent
admin test 401'd (52/55 failures in EndpointTests_OutOfProcess).
Detection now matches only containers named like this project's compose
service (oauth2-postgres); no match falls through to the local-psql
branch, which is the correct path for a native-Windows Postgres.
UserDetailPage: clearing the Organization field now sends org_id: null (the API's explicit clear via setOrgIdToNull) instead of '' — the old value was silently skipped by the backend's isInt guard, making "clear" a no-op that still answered 200. mock-api parity with the hardened backend (#53/#56/#59): - PUT /users/:id is stateful: applies known fields so a subsequent GET reflects the update, rejects wrong-typed fields with 400, and treats org_id: null as a clear. - users list route pattern '**/api/admin/users*' matches query strings (?page=&per_page=) — the old exact pattern fell through to the vite proxy, so 11 users-page cases only passed with a live backend on 5555 (pre-existing flakiness; verified failing via git stash). - delete response includes tokens_revoked (#56 contract). Pre-existing e2e defects fixed along the way (all verified failing at HEAD via git stash, unrelated to the API changes): - users.spec create-user test clicked a page-level button occluded by the modal overlay (strict-mode/timeout flake). - user-detail toggle-email-verified used a non-strict checkbox locator (3 checkboxes on the page -> strict mode violation). - spec-level route overrides '**/api/admin/users' missed query strings. - user-frontend GitHub-login cases now skip (not fail) when VITE_GITHUB_CLIENT_ID is not compiled in for the dev server.
#60-4) openapi.yaml (#60 item 3 — the PUT body documented only email/ email_verified while the implementation accepts six fields): - PUT /users/{id}: full field set (username, email, email_verified, mfa_enabled, locked, org_id nullable) + 400/409 responses. - DELETE /users/{id}: tokens_revoked reporting in the 200 body, 400 self-delete, 409 last-admin. - disable / roles PUT: 409 last-admin responses. - POST /users: 201 body documents roles_assigned/roles_failed/warning. - GET detail: org_id is a nullable integer (null = no org, never 0). UserAdminController's runtime OpenAPI descriptions updated to match. #60 item 4 — misleading security comments: TokenEndpointController's userinfo check was described as "defense-in-depth ... even if the filter gate is bypassed", but the ResourceScopeRegistry deliberately EXCLUDES /oauth2/userinfo, making the handler check the SOLE enforcement — the old comment invited a future maintainer to delete it. Both the handler comment and the registry header now state the exclusion and its reason (401-vs-403 split is handler-exclusive). api-diff baseline ratified (--force, reviewed commit; precedent a9a1bf8): the ISocialAccountRepository::LookupCallback signature change is classified BREAKING by the guard, but every consumer is in-tree (GitHubAuthService, FakeSocialAccountRepository, both Postgres repos, tests) — it is not an external-SDK surface. Additive: UserAdminService.h isLastActiveAdmin declaration, SocialLinkStatus enum, Fake test seams.
Design passed an adversarial subagent review (PASS-WITH-CONDITIONS; all conditions adopted — including the active-row takeover escalation of the upsert defect); the implementation plan passed a second review after adding the api-diff baseline-ratification step and the shared isLastActiveAdmin declaration site.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…d unset) Subagent review of PR #62 found the social-account default-role grant inserted user_roles with ONLY user_id set: role_id is NOT NULL with no default, so every grant raised a constraint violation that the best-effort callbacks swallowed silently — every account created via GitHub login had ZERO roles (the exact permission-less-user class issue #60-1 called out for createUser). Pre-existing, but squarely in this PR's theme and smaller to fix than to file. - PostgresSocialAccountRepository::createLinkedUser and GitHubController::createNewLinkedUser now resolve the 'user' role id first (split query) and insert BOTH columns; the best-effort failure paths LOG_ERROR instead of staying silent. - assignUserRoles: removed the dead nameToId map; the comment no longer claims request-order output (completion order — treat as a set). - FakeSocialAccountRepository: failFind seam + RepositoryError HTTP test (a DB outage must 5xx and must NOT create an account — the old optional contract sent outages down the creation branch). - Repo-level assertion that a created linked user actually HAS the 'user' role. Also MINOR-2 from review (401-on-conflict fallback vs 500 wired path) is documented in code as a known, fail-closed divergence — both leak nothing and the conflict reason is server-side LOG_ERROR'd. All 498 in-process test cases pass (57645 assertions).
Owner
Author
|
Review round 2 complete — all findings from the subagent PR review addressed in 09d6ba7:
Re-verified after the fixes: all 498 in-process test cases (57,645 assertions) and the full 8/8 backend pipeline (DB reset → build → ctest → server → 59 OAuth2 endpoint tests → 55 admin endpoint tests → shutdown) pass. |
Decision D3 (user-approved): the hardening batch's contract-visible changes (new 400/409 validation semantics, org_id nullability, tokens_revoked / roles_assigned reporting, last-admin guard) are backward-compatible functional changes — MINOR bump. The one C++ header BREAKING (ISocialAccountRepository::LookupCallback) was ratified with --force earlier as a non-public surface; the remaining additive drift (failFind test seam) is ratified here (additions need no version bump). Release tag v1.2.0 + git-cliff changelog follow the release process after merge (tags/pushes are manual-gated per .claude/settings.json).
wangrh0909
approved these changes
Aug 16, 2026
voidvec
added a commit
that referenced
this pull request
Aug 16, 2026
…d unset) Subagent review of PR #62 found the social-account default-role grant inserted user_roles with ONLY user_id set: role_id is NOT NULL with no default, so every grant raised a constraint violation that the best-effort callbacks swallowed silently — every account created via GitHub login had ZERO roles (the exact permission-less-user class issue #60-1 called out for createUser). Pre-existing, but squarely in this PR's theme and smaller to fix than to file. - PostgresSocialAccountRepository::createLinkedUser and GitHubController::createNewLinkedUser now resolve the 'user' role id first (split query) and insert BOTH columns; the best-effort failure paths LOG_ERROR instead of staying silent. - assignUserRoles: removed the dead nameToId map; the comment no longer claims request-order output (completion order — treat as a set). - FakeSocialAccountRepository: failFind seam + RepositoryError HTTP test (a DB outage must 5xx and must NOT create an account — the old optional contract sent outages down the creation branch). - Repo-level assertion that a created linked user actually HAS the 'user' role. Also MINOR-2 from review (401-on-conflict fallback vs 500 wired path) is documented in code as a known, fail-closed divergence — both leak nothing and the conflict reason is server-side LOG_ERROR'd. All 498 in-process test cases pass (57645 assertions).
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Hardening batch for the PR #52 user-management review residue plus the #54 soft-delete contract bypass. All six issues verified at HEAD
a9a1bf8before fixing; design + implementation plan were subagent-reviewed before implementation (.zcode/plans/issues-53-60-*.md).Fixes #53, Fixes #56, Fixes #58, Fixes #59, Fixes #60. For #54 this lands the execution half (deleted/locked filtering + rejection everywhere); the mapping-lifecycle semantics decision is deliberately left open (see Open decisions below).
#54 [High] — soft-delete contract bypass (broader than filed)
The issue reported GitHub social login issuing tokens for soft-deleted users. Audit found the production WITH_SOCIAL path equally affected, plus three more bypasses, and one escalation:
PostgresSocialAccountRepository::findLinkedUser— nodeleted_atfilter, and its error callback faked success (username="user") for users it couldn't even read.ON CONFLICT (username) DO UPDATE— they didn't just resurrect soft-deleted rows; they could adopt an ACTIVE row registered by someone else (victim registersgh_alicelocally; a GitHub user namedalicegets the victim's id back from the upsert, aattacker_subject→victim_idmapping, and tokens issued as the victim). All three nowDO NOTHING— fail closed.MfaController::verifyLoginfallback completed logins for soft-deleted users holding an outstandingmfa_token(TOCTOU between factors). Wired + fallback paths now also reject locked users (parity with the password path).UserSelfServiceControllerlookups filtered;deleteAccountnow actually setsdeleted_at(it previously only anonymized, leaving a live row) and revokes tokens on both keys (password-flow tokens store the public sub; GitHub-flow tokens store the internal id — the old single-key revocation missed every social-issued token).getInternalUserId(feeds consent→code→token) now resolves the mapping against a live users row.findLinkedUser's callback is an explicit four-state enum (Linked/NoMapping/AccountUnavailable/RepositoryError): the oldoptionalconflated "no mapping" with DB errors, sending outages into the account-CREATION branch.oauth2_subject_mappingsrows are intentionally kept on soft-delete (reversibility); login/consent are rejected through the filters above.#53 [High] — SIGABRT via unguarded JSON coercions
updateUser/createUsercalledasString()/asBool()inside async DB callbacks; a wrong-typed field threwJson::LogicErrorinto the event loop. Both now type-validate up front (400) — which also eliminates the old silent-skip-on-type-mismatch that answered 200 "success" (#59-3). Defense-in-depth wrapper around the callback body.#56 [Medium] — fire-and-forget token revocation
Two
execSqlAsynccalls with empty success AND error callbacks insidecatch(...){}. Now chained (access→refresh), awaited before the response, every failureLOG_ERRORed, dual-keyed, and the 200 body reportstokens_revoked(false + warning + audit outcomepartialon failure — the soft-delete already succeeded, so 500 would be a lie and unretryable).#58 [Medium] — case-sensitive search vs case-insensitive mock
lower(col) LIKE lower(q)via Criteria's colName slot (parameterized API use, not raw SQL; ASCII-only fold with the mandatory unsigned-char cast). Comment no longer claims lowercasing that didn't exist.#59 [Medium] — org_id nullability
NULL serialized as
0(nonexistent org); could never be cleared. Nullable accessor → JSONnull;PUT org_id: null→setOrgIdToNull(); wrong types → 400. Admin UI sendsnullon clear (was'', silently skipped).#60 [Low] — review residue
createUserreportsroles_assigned/roles_failed(+warning) instead of a silent permission-less 201.VALIDATION_RESOURCE_CONFLICT. Accepted TOCTOU race documented. (Subagent review caught the/api/mebypass and a test-ordering regression; both addressed.)openidcheck rewritten — it is the SOLE enforcement (registry deliberately excludes userinfo).Test-infra fix (found by the full pipeline)
The endpoint-suite admin reset docker-exec'd into ANY container named
*postgres*— an unrelatedory-bench-postgreson this machine broke 52/55 admin tests via a failed password restore (the API restore path is structurally unusable: openid-only restore token → 403, and the seeded 5-char password violates the ≥8 policy). Detection now matches only this project's compose service name; no match falls back to local psql.Behavior changes (contract-visible)
null(was0) when unset; explicit null clears it.tokens_revoked(bool).roles_assigned/roles_failed/ conditionalwarning.api-diff baseline
Ratified with
--forcein a reviewed commit (precedent a9a1bf8): theLookupCallbacksignature change is BREAKING per the guard but every consumer is in-tree — not an external-SDK surface.Verification
full_test.bat8/8 PASS (DB reset → build → 462 ctest cases → server → 59 OAuth2 endpoint tests → 55 admin endpoint tests → shutdown), including 21 new test cases: type-mismatch 400s, org null semantics, case-insensitive search, role reporting, durable refresh-token revocation after delete, deleted-user /api/me no-leak, last-admin 409 matrix, repo-level soft-delete/lock/fail-closed-upsert against real Postgres, and HTTP-level social rejection via the mock fixture.git stash).VITE_GITHUB_CLIENT_ID).Open decisions (not in this PR)
oauth2_subject_mappingslifecycle on soft-delete — keep + reject (current, reversible) vs delete mapping (allows identity re-registration). Recommendation: keep.users_username_keyglobal unique constraint vs partial index ondeleted_at IS NULL(username reuse after delete). Currently soft-deleted usernames are permanently taken.