Skip to content

fix(auth,admin): #53 #54 #56 #58 #59 #60 — soft-delete contract enforcement + user-admin hardening - #62

Merged
voidvec merged 8 commits into
masterfrom
fix/issues-53-60-useradmin-social-hardening
Aug 16, 2026
Merged

voidvec merged 8 commits into
masterfrom
fix/issues-53-60-useradmin-social-hardening

Conversation

@voidvec

@voidvec voidvec commented Aug 16, 2026

Copy link
Copy Markdown
Owner

Summary

Hardening batch for the PR #52 user-management review residue plus the #54 soft-delete contract bypass. All six issues verified at HEAD a9a1bf8 before 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 — no deleted_at filter, and its error callback faked success (username="user") for users it couldn't even read.
  • Three social upserts used ON CONFLICT (username) DO UPDATE — they didn't just resurrect soft-deleted rows; they could adopt an ACTIVE row registered by someone else (victim registers gh_alice locally; a GitHub user named alice gets the victim's id back from the upsert, a attacker_subject→victim_id mapping, and tokens issued as the victim). All three now DO NOTHING — fail closed.
  • MfaController::verifyLogin fallback completed logins for soft-deleted users holding an outstanding mfa_token (TOCTOU between factors). Wired + fallback paths now also reject locked users (parity with the password path).
  • All five UserSelfServiceController lookups filtered; deleteAccount now actually sets deleted_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 old optional conflated "no mapping" with DB errors, sending outages into the account-CREATION branch.

oauth2_subject_mappings rows are intentionally kept on soft-delete (reversibility); login/consent are rejected through the filters above.

#53 [High] — SIGABRT via unguarded JSON coercions

updateUser/createUser called asString()/asBool() inside async DB callbacks; a wrong-typed field threw Json::LogicError into 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 execSqlAsync calls with empty success AND error callbacks inside catch(...){}. Now chained (access→refresh), awaited before the response, every failure LOG_ERRORed, dual-keyed, and the 200 body reports tokens_revoked (false + warning + audit outcome partial on 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 → JSON null; PUT org_id: null → setOrgIdToNull(); wrong types → 400. Admin UI sends null on clear (was '', silently skipped).

#60 [Low] — review residue

  1. createUser reports roles_assigned / roles_failed (+warning) instead of a silent permission-less 201.
  2. Last-active-admin guard: delete/disable/lock/demote/self-delete-via-/api/me of the only active admin → 409 VALIDATION_RESOURCE_CONFLICT. Accepted TOCTOU race documented. (Subagent review caught the /api/me bypass and a test-ordering regression; both addressed.)
  3. openapi.yaml PUT body drift — full field set + new responses across five operations; runtime OpenAPI descriptions synced.
  4. Misleading "defense-in-depth" comment on the userinfo openid check rewritten — it is the SOLE enforcement (registry deliberately excludes userinfo).
  5. Mapper-construction try/catch hygiene across every function this PR touches (13 bare constructions in UserAdminService alone).

Test-infra fix (found by the full pipeline)

The endpoint-suite admin reset docker-exec'd into ANY container named *postgres* — an unrelated ory-bench-postgres on 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)

  • Wrong-typed optional fields on user create/update: 200-silent-skip → 400.
  • org_id serializes as null (was 0) when unset; explicit null clears it.
  • DELETE /users/{id} 200 body adds tokens_revoked (bool).
  • POST /users 201 body adds roles_assigned / roles_failed / conditional warning.
  • Last-admin lockout operations: 200 → 409 (delete/disable/lock/demote/self-delete).
  • Social login for soft-deleted or locked users: tokens → 401 generic auth error (no status enumeration).
  • Social upsert on username conflict: silent adoption → login failure (fail closed).
  • MFA verify for deleted/locked users: completion → rejection.
  • /api/me endpoints for deleted users: data → 404 (token already revoked → 401 first).
  • /api/me DELETE now soft-deletes (sets deleted_at) in addition to anonymizing.

api-diff baseline

Ratified with --force in a reviewed commit (precedent a9a1bf8): the LookupCallback signature change is BREAKING per the guard but every consumer is in-tree — not an external-SDK surface.

Verification

  • Backend full_test.bat 8/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.
  • Admin frontend: build + 168 e2e passed (6 skipped as designed; mock brought to parity, several pre-existing environment-dependent e2e defects fixed — each verified failing at HEAD via git stash).
  • User frontend: build + 96 e2e + 21 unit tests passed (2 skipped: GitHub button requires compiled-in VITE_GITHUB_CLIENT_ID).
  • api-diff passes against the ratified baseline.

Open decisions (not in this PR)

  • D1: oauth2_subject_mappings lifecycle on soft-delete — keep + reject (current, reversible) vs delete mapping (allows identity re-registration). Recommendation: keep.
  • D2: users_username_key global unique constraint vs partial index on deleted_at IS NULL (username reuse after delete). Currently soft-deleted usernames are permanently taken.

…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.
@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.

…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

voidvec commented Aug 16, 2026

Copy link
Copy Markdown
Owner Author

Review round 2 complete — all findings from the subagent PR review addressed in 09d6ba7:

  • [MAJOR-1] fixed: the social default-role grant inserted user_roles with only user_id (role_id is NOT NULL, no default) — every constraint violation was swallowed by the best-effort callbacks, so every GitHub-created account had ZERO roles. Both sites now resolve the user role id first and insert both columns; failures LOG_ERROR. New repo-level test asserts a created linked user actually HAS the user role.
  • [MINOR-3] fixed: failFind seam + HTTP test proving a RepositoryError 5xx's AND does not create an account (the old contract sent DB outages down the account-creation branch).
  • [MINOR-4] fixed: dead nameToId map removed; comment no longer claims request-order output.
  • [MINOR-2] documented in code: the fallback-vs-wired error-code divergence on username conflict (401 vs 500) — both fail closed, nothing leaked, conflict reason LOG_ERROR'd server-side.
  • [NOTE-5/6] accepted as-is (guard fails safe; MFA 401-vs-404 is defense-in-depth with the token already revoked).

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).
@voidvec
voidvec merged commit e5548ec into master Aug 16, 2026
8 checks passed
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.
@voidvec
voidvec deleted the fix/issues-53-60-useradmin-social-hardening branch August 22, 2026 12:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment