Skip to content

fix: browser-e2e 2026-09-08 bug tranche — device approval crash, readiness hang, OAuth flow resume, blank-username deletion + 5 more - #180

Merged
voidvec merged 14 commits into
masterfrom
fix/browser-e2e-bugfix-tranche
Sep 10, 2026
Merged

voidvec merged 14 commits into
masterfrom
fix/browser-e2e-bugfix-tranche

Conversation

@voidvec

@voidvec voidvec commented Sep 9, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes the bug list from the 2026-09-08 full browser E2E pass (report in docs-local/browser-e2e/2026-09-08-test-report.md, 74 steps / 69 pass). Every touched behavior was re-verified end-to-end against real frontends + backend; the previously blocked device-flow scenario (C3) now passes its full closure.

P0

  • A-2 [CRITICAL] server crash on device approval — DeviceCodeService moved the same callback into both Mapper::findOne lambdas (findByUserCode, markApproved, dead findByDeviceCodeHash); the loser held an empty std::function → bad_function_call escaped the event loop and killed the process on every approval miss. Fixed with the shared-callback pattern (same as createDeviceCode in f1f418b), DB faults now distinguishable from "code not found" (DB_CONNECTION_ERROR vs VALIDATION_DEVICE_CODE_INVALID), dead function removed, and the admin approve leg gets its first integration coverage (invalid-code-survives + approve→redeem closure).
  • U-3 anonymous OAuth flow never resumed after login — /oauth2/authorize bounces anonymous users to /login with the OAuth params flattened (no redirect); login used to land on the dashboard and the relying party never got its code. LoginPage now rebuilds the authorize URL from those params (whitelisted keys, PKCE triple + nonce preserved) for both password and MFA branches.
  • U-2 one-click self-deletion for blank-username accounts — registration promised auto-generated usernames but stored NULL; profile.username === '' made the Danger Zone confirm guard match empty input. Backend now generates user_<8 hex> (both registration paths, collision retry), V030 backfills existing NULL rows, and the frontend guard rejects empty confirm input outright.

P1

  • A-1 /health/ready hung forever when Redis was configured but unreachable (Drogon queues the PING and never fires its callbacks on connect failure) — 2s one-shot timeout guard answering 503 degraded/timeout; the admin dashboard decouples stats from readiness (allSettled + timeouts + 503 bodies accepted) so the cards always render.
  • U-6 MFA lockout from redirect_uri drift (localhost in .env vs 127.0.0.1 in the seed; the MFA verify leg strictly validates) — seed + dev configs register both loopback spellings; a fresh clone no longer reproduces. Error-code mapping intentionally unchanged (ADR-0007 mandates the unified AUTH_INVALID_CREDENTIALS anti-enumeration contract).
  • U-1 zombie session after password change — the SPA now drops local state and lands on /login?pw_changed=1 with a notice; the guest guard restores the session before bouncing.

P2

  • U-4 CallbackPage no longer burns one-time codes of externally-initiated flows (only redeems with its own stashed PKCE verifier; otherwise shows a "return to your app" notice).
  • U-5 MFA setup renders the backend's otpauth_uri as a QR code (qrcode.vue; size gate passes without a baseline raise).
  • M-1 for/id + aria-labels on the security/login inputs; M-3 passkey failures classified instead of "network connection failed"; M-4 run_server.bat forward-slash if exist fix.

Not fixed, with evidence

  • M-2 by design per ADR-0007 (anti-enumeration). M-5 pagination UI exists (48 < perPage 50). M-7 roles-save banner already present (UserDetailPage.vue:107). M-6 "Revoke All for User" is a filter-bar button gated on a typed user_id filter, not a dropdown entry — works as designed (screenshot evidence), noted for discoverability.

Test plan

  • Backend full_test: 585/591 green; the 6 failures are Redis-repository contract tests that require a live Redis (unavailable on this workstation; covered by CI's Redis service). New integration tests included and green.
  • Frontends: test:unit, lint (0 errors), build, Playwright mock e2e (user 126/126 incl. new authorize-resume / external-flow / password-change / danger-zone / QR cases; admin 190 passed + 6 skipped), check-ui-sync, size gate — all green.
  • Live acceptance (docs-local/browser-e2e/2026-09-09-fix-acceptance.md): device flow 3/3 (invalid code no crash, admin approve, device_code→token), /health/ready answers 503 in 2.0s with Redis unreachable (was: infinite hang), portal scenarios p1 8/8 · p2 9/9 · p3 7/7 · p4 4/4, admin p1 7/7, tokens/C2 5/5, MFA lifecycle passes with zero manual DB surgery.
  • Error codes synced at all five points (spec, catalog test, SDKs where applicable) — no error codes added or changed in this PR.

…eService

A-2 from the 2026-09-08 browser E2E report: POST /oauth2/device/approve
killed the whole server. Root cause was NOT the respondError helper —
DeviceCodeService moved the same std::function callback into BOTH
Mapper::findOne lambdas (findByUserCode, markApproved and the dead
findByDeviceCodeHash). Whichever lambda lost the move race held an empty
std::function; calling it raised bad_function_call inside the DB IO
thread, escaping every handler-level catch and terminating the event
loop. createDeviceCode got the sharedCb pattern in f1f418b; the other
three functions were missed.

- findByUserCode/markApproved: move the callback once into a shared_ptr,
  every lambda captures it by value; each Mapper construction gets its
  own try/catch that answers the callback (db-operations.md)
- findByUserCode now reports (ok, row): UnexpectedRows (0 rows / too
  many) is a miss (ok=true, nullptr) while real DB faults log and
  report ok=false; the controller maps DB faults to DB_CONNECTION_ERROR
  instead of masquerading as VALIDATION_DEVICE_CODE_INVALID
- markApproved failures likewise surface as DB_CONNECTION_ERROR (the
  user_code was already validated at that point)
- drop findByDeviceCodeHash (zero callers since the B5 refactor)
- integration coverage for the admin leg: unknown user_code -> 400 AND
  the server stays alive (the exact crash path), plus the full
  seed -> approve -> device_code redemption closure (browser-e2e C3,
  previously untestable)
…dis outages

A-1 from the 2026-09-08 browser E2E report. Drogon's Redis client with no
ready connection queues the PING (both callbacks attached) in its task
buffer and, on connect failure, only schedules a reconnect — the queued
callbacks never fire. With dev configs' redis timeout of -1, /health/ready
hung forever whenever Redis was configured but unreachable, which made
K8s readiness probes time out and left the admin dashboard skeletonized
(Promise.all chained stats to the hanging probe; axios has no timeout).

- HealthController: one-shot 2s runAfter guard around the Redis PING;
  first answer wins (atomic responded flag), timeout answers 503
  degraded with redis:"timeout" — same health-body contract as the
  existing disconnected branch
- DashboardPage: allSettled + 8s timeouts; stats render independently of
  readiness; a failed probe only degrades the health card (503 bodies
  are accepted so the card can show WHICH component is down)
…ning codes

User-portal fixes from the 2026-09-08 browser E2E report:

- U-3: /oauth2/authorize bounces anonymous users to /login with the OAuth
  params flattened on the query (no `redirect` param); a successful login
  dumped the user on the dashboard and the relying party never got its
  code. LoginPage now rebuilds /oauth2/authorize from a whitelisted set of
  those params (PKCE triple and nonce included) and navigates with a full
  page load — for both the password and the MFA branches
- U-1: changing a password revokes every token server-side, but the SPA
  kept its optimistic authenticated state and the guest guard bounced the
  user off /login into a dashboard of 401s. changePassword now clears
  local session state and lands on /login?pw_changed=1 with a notice;
  the guest guard restores the session before deciding to bounce
- U-4: CallbackPage redeemed any ?code it received, burning the one-time
  code of flows initiated by external apps (PKCE is force-enabled, so a
  redemption without OUR verifier always failed anyway). It now only
  redeems when the stashed verifier proves this SPA initiated the flow,
  and otherwise shows an "authorization complete, return to your app"
  notice
- U-5: render the backend-provided otpauth_uri as a QR code (qrcode.vue)
  next to the manual key the setup panel previously showed alone
- U-2 frontend backstop: the Danger Zone confirm guard rejects an EMPTY
  confirm input regardless of the profile username ('' === '' used to
  enable one-click self-deletion for blank-username accounts)
- M-1: wire for/id (and aria-labels for the inline inputs) on the
  security page password/MFA/passkey fields and the login MFA input
- M-3: passkey failures are classified (already-registered vs generic
  registration failure) instead of masquerading as "network connection
  failed" via the no-response error branch
- e2e: authorize-resume (password + MFA + plain-login negative),
  external-flow callback (never touches the token endpoint), password
  change redirect, danger-zone empty/wrong/correct, QR rendering
…NULL rows

U-2 (backend half) from the 2026-09-08 browser E2E report: the
registration form promises "leave the username blank and one is
generated", but both registration paths stored NULL (email-first). Every
such account read username '' in the account center (Drogon maps NULL
columns to the type default), which blanked the Danger Zone hint and
defeated its confirm guard.

- identity AuthService::registerUser: blank username -> "user_<8
  lowercase hex>" from the injected crypto provider (charset-valid for
  Rule.h USERNAME_PATTERN); a generated name colliding with an existing
  one retries with a fresh name (<=3) instead of surfacing
  VALIDATION_USERNAME_TAKEN to a user who never typed a username
- legacy fallback AuthService: same generation (hashToken of a secure
  token, lowercased) and the same retry on the users_username_key
  constraint
- V030: backfill the same shape for existing NULL rows (md5(id||random)
  keeps every row distinct; a unique collision would abort the migration
  loudly rather than silently leaving NULLs)
- RegistrationWithoutUsernameTest: the contract flips from
  "username IS NULL" to "matches ^user_[0-9a-f]{8}$" via the real
  POST /api/register path
… path fix

- U-6 from the 2026-09-08 browser E2E report: the user portal's .env
  sends VITE_REDIRECT_URI=http://localhost:5173/callback while the
  vue-client seed registered only 127.0.0.1 hosts. The MFA verify leg
  strictly validates redirect_uri, so the drift locked out every
  MFA-enabled user with a misleading "incorrect username or password".
  The seed and the dev configs now register BOTH loopback spellings
  (5173 and 8080); a fresh clone no longer reproduces the lockout.
  Production/CI/bench configs are untouched
- M-4: run_server.bat inherits forward-slash values from paths.env
  (apps/server); cmd's `if exist` reports the exe as missing for such
  paths. Normalize EXE_PATH and the run directory to backslashes, the
  same fix build.bat applies to its copy paths
@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.

@voidvec

voidvec commented Sep 9, 2026

Copy link
Copy Markdown
Owner Author

Code review — 27 files (+937/−170), verified against the branch head (fe13dc0d)

Reviewed all 27 changed files, plus repo-wide checks for the same crash pattern and for each claim in the description. The root-cause work is solid: the DeviceCodeService fix matches both requirements in .claude/rules/db-operations.md (per-Mapper construction try/catch, and every catch answering the callback), findByDeviceCodeHash was confirmed to have zero callers before removal, and the U-2/U-3 analysis holds up.

10 findings: 3 Major, 6 Minor, 1 Info. The three Majors are worth fixing before merge — two are introduced by this PR's new code, one is a fix that does not take effect.


[Major] 1. Reference cycle leaks every registration attempt, including the HTTP response callback

Where: libs/identity/src/AuthService.cc:322-325 (and the inner capture at :344), libs/drogon/src/AuthService.cc:232-235 (and :309)

attemptCreate is a shared_ptr<std::function<void()>>, and the lambda stored into it captures attemptCreate by value → function object → capture table → the same shared_ptr is an unreachable cycle. Once registerUser returns, the local shared_ptr dies but the cycle keeps the refcount at 1 forever, so the whole captured set — sharedCb (which holds the controller's response callback, and through it the request/connection state), currentUser, attempts, passwordHash, email, crypto/userRepo — is never freed.

Risk: /api/register is an unauthenticated public endpoint, so this is attacker-reachable unbounded growth.

The DB callbacks also hold copies of attemptCreate, but those release when the query completes; the cycle survives independently of them.

// before: by-value self-capture -> cycle
*attemptCreate = [sharedCb, ..., attemptCreate]() { /* ... */ };

// after: weak_ptr breaks the cycle
auto attemptCreate = std::make_shared<std::function<void()>>();
std::weak_ptr<std::function<void()>> weakSelf = attemptCreate;
*attemptCreate = [sharedCb, ..., weakSelf]() {
    auto self = weakSelf.lock();
    if (!self) return;
    /* ... */ (*self)();   // on retry
};

Alternatively drop the self-referential shared_ptr entirely in favour of a named helper plus an explicit retry counter — clearer, and no cycle to reason about.

[Major] 2. generateUsername ignores secureRandomBytes' return value — reads uninitialized stack on RNG failure

Where: libs/identity/src/AuthService.cc:67-72

unsigned char raw[4];
crypto.secureRandomBytes(raw, sizeof(raw));   // returns bool; leaves the buffer untouched on failure
return "user_" + bytesToHex(raw, sizeof(raw));

This repo already has the rule written down and a prior review number attached to it: libs/identity/src/mfa/TotpUtils.cc:121-125 ("secureRandomBytes leaves the buffer untouched on failure … Callers treat "" as failure", PR #157 review MAJOR 5). The new generator is the one place in libs/identity that reads the buffer unconditionally.

Two follow-ons:

  • The surrounding try/catch (const std::exception &) at :312-320 and :357-365 can never fire — this port does not throw — so the error handling is misplaced rather than merely thin.
  • The comments claim both generators are identical. On the legacy side that is not true in failure behaviour: libs/drogon/include/fulla/drogon/utils/CryptoUtils.h:175-189 is fail-closed (falls back to fresh UUIDs). Only the identity side reads garbage.
if (!crypto.secureRandomBytes(raw, sizeof(raw)))
    throw std::runtime_error("secureRandomBytes failed");   // existing catch maps INTERNAL_ERROR

[Major] 3. The U-1 "restore the session before bouncing" guest guard never actually waits

Where: frontends/user/src/stores/auth.ts:23,31-34,118-120 + frontends/user/src/router/index.ts:95,105-113

restoreSession() sets sessionRestored = true synchronously, before await tryRestoreSession(). And the store body first runs at useAuthStore() inside the guard itself (router/index.ts:95), where the init block at :118-120 fires restoreSession() without awaiting it. So by the time the new if (!auth.sessionRestored) await auth.restoreSession() line executes, the flag is already true, the await is skipped, and auth.isAuthenticated is still the optimistic tokenPresent from :22 (!!getAccessToken() || !!getRefreshToken()), which is true whenever a refresh token merely exists. The exact state the finding describes — refresh token revoked server-side → zombie dashboard of 401s — still bounces.

The primary U-1 scenario is fixed, because logoutLocal() clears the tokens before the full page load, so there is no refresh token and no in-flight restore. So the code is fine for the regression test; it just does not do what the new comment and the PR description say.

Fix: cache the in-flight promise and have restoreSession() return it idempotently, then await it unconditionally in the guard and only set sessionRestored on completion.

let restorePromise: Promise<boolean> | null = null
function restoreSession(): Promise<boolean> {
  if (restorePromise) return restorePromise
  restorePromise = doRestore().then(ok => { sessionRestored.value = true; return ok })
  return restorePromise
}

[Minor] 4. markApproved collapses "row missing" into "DB fault", unlike its sibling

DeviceCodeService.cc:158 sends every DrogonDbException from the find leg to DeviceAuthController.cc:444 as DB_CONNECTION_ERROR. findByUserCode was given the UnexpectedRows distinction in this PR; markApproved was not, so a row reclaimed between find and update reports an infrastructure error where the protocol-level miss is accurate. Worth the same dynamic_cast<const UnexpectedRows *> split for symmetry.

[Minor] 5. /health/ready timeout guard: two loose ends

HealthController.cc:146-149 registers the timer unconditionally, so the happy path also pins answer → sharedCb → the response object for the full 2s. Consider keeping the returned timer id and cancelling it on the first real answer. Separately, the catch (...) at :151-159 answers through (*sharedCb) directly, bypassing the responded CAS — the single-answer invariant only holds because execCommandAsync/runAfter are not expected to throw after queueing. Routing that branch through the same CAS would make the guard self-evident. Also: 2.0 is hardcoded, while the trigger was dev configs' redis timeout: -1; making the budget configurable would fix the cause, not just the symptom.

[Minor] 6. U-4's predicate is not bound to state, so a stale verifier can still burn an external code

authService.ts:28-30 tests only for the presence of pkce_code_verifier, but the key is written solely in the MFA branch (:54) and removed only on success (:99). An MFA login that fails before the token exchange leaves a verifier behind, and the next externally-initiated landing on /callback is then misclassified as "ours" and redeemed with the wrong verifier — the original bug, narrowed rather than closed. Suggest storing the verifier paired with state and comparing against route.query.state. Also, the doc comment at :13 ("the authorize redirect is the only place this key is written") has drifted from the code.

[Minor] 7. RegistrationWithoutUsernameTest lost its email assertion and gained a silent skip

  • The old test asserted the persisted email equals the canonical form; the new one only uses lower(email) as a lookup key (:91) and asserts on username. email_lc is selected and never checked. The comment on the change states the reason — the wired identity path stores the email verbatim while the legacy path normalizes — which means this PR discovered a real inconsistency and then removed the only assertion covering it, without a tracking issue.
  • :61-64 returns CHECK(true) when the server is unreachable, so "server did not start" reports green. Combined with the file moving from a DB-only contract test to one that needs a live server, the net coverage here is swapped rather than added.

[Minor] 8. New device-approve tests leave no teardown

DeviceAuthEndpointHttpTest.cc:150 inserts p1-test-pub-device (idempotent, fine) and :164 seeds APRVTS01; the redemption then issues tokens for user 1. Nothing is deleted, so row-count-sensitive assertions elsewhere inherit the residue. A DELETE for the seeded device_code_hash and the client at the end of the happy-path test would keep it self-contained.

[Minor] 9. changePassword navigates with window.location.href, bypassing the router

SecurityPage.vue:296-298. In U-3 the full-page load is necessary because the target is a backend endpoint; here it is not — logoutLocal() has already cleared state, so router.replace({ path: '/login', query: { pw_changed: '1' } }) would keep the SPA base prefix and the locale, and avoid a reload. Minor, but the two hardcoded /login strings are a latent break under a non-root BASE_URL.

[Info] 10. Config surface and a new runtime dependency

  • Both apps/server/config/config.json and config.dev.json gained four loopback redirect URIs. config.json is also staged as the CI/runtime config (scripts/backend/build.sh:165), so a dev-only reproduction fix now widens the default callback allow-list. If config.json is intended as the shipped default, config.dev.json + the seed alone would contain U-6.
  • qrcode.vue@3.11.0 is a new third-party runtime dependency riding in a bugfix PR. The choice is reasonable (MIT, peerDependencies: vue ^3, renders the backend's otpauth_uri client-side), but it deserves its own dependency review rather than slipping through a bug tranche.

Checked and cleared (the things most likely to be doubted)

  • + vs %20 on the resumed authorize URL. URLSearchParams.toString() encodes the space in scope=openid profile as +. Verified against the pinned drogon/1.9.13 sources: lib/src/Utilities.cc urlDecode maps case '+': result += ' ' with no opt-out in any of the three overloads, and the query-string block of HttpRequestImpl::parseParameters decodes both key and value before any content-type check, so getParameters()["scope"] yields openid profile. The project's own SCOPE_PATTERN (Rule.h:23, alphanumerics/colons/spaces) would hard-400 an undecoded +, which corroborates it. No change needed. Note for future work that req->getQuery() still returns the raw + — only the parameter accessors decode.
  • Charset agreement. bytesToHex uses "0123456789abcdef", so the identity generator really does match the test's ^user_[0-9a-f]{8}$, and USERNAME_PATTERN = ^[a-zA-Z0-9_]{1,100}$ accepts user_<8hex>.
  • Schema assumptions in the new tests. expires_at is BIGINT (V014) so the epoch-seconds literal is right; user_code VARCHAR(8) matches the 8-char APRVTS01; V030 is the next free number after V029.
  • The registration contract the new test depends on. username really is optional on /api/register — RuleSet::registerUser validates it only when non-empty, and ADD_METHOD_TO at SessionController.h:83 attaches no validation filter to that route — so the 2xx expectation is sound.
  • Has the crash pattern been left elsewhere? I scanned for a callback std::move'd into two lambdas of one call across libs/ and apps/: 6 proximity hits (SessionController.cc:1854, TokenEndpointController.cc:843, IdentityService.cc:63/73, TokenService.cc:211/436, RedisTokenRepository.cc:203). All are sequential moves where the inner lambda is constructed inside the outer body and only one branch runs — not this bug. Since the compiler cannot prevent a regression, an arch-guard rule flagging two = std::move(callback) captures within one statement would be a cheap permanent fix.

Not a blocker but worth a follow-up issue: findings 7 and 8 both concern test hygiene introduced here, and finding 6 has a protocol-level argument behind it (RFC 7636 §4.6 binds the verifier to the request, so state should be the correlation key).

… entry

The override was declared against a top-level "vue_client.secret" path that
exists in no config file, so ConfigManager::getJsonPointer returned nullptr and
applyEnvOverrides silently skipped it — the env var never reached the runtime
config, while configuration-guide.md documented the plugin path as the target.

Repointed at plugins[name=OAuth2Plugin].config.clients.vue-client.secret, using
the same by-name lookup as the sibling redirect_uri override. tests/test_main.cc
had a hand-rolled injection for the same variable, which is why the existing
EnvConfigTest passed and masked the gap; the new regression test drives
ConfigManager::load directly.
Five tracked files leaked the author's machine layout (a real username in
C:\Users\..., a VS install path, and two stale repo roots predating the
directory refactor). Replaced with relative paths and portable expansions.

Verified: parse_ctest.py --selftest still passes against the rewritten fixtures.
apps/server/AGENTS.md forbids credentials in tracked config; every other prod
value already uses an OVERRIDE_VIA_FULLA_* sentinel except this one, which sat
at "123456". vue-client is a PUBLIC client, so per RFC 8252 it authenticates
with authorization code + PKCE and carries no secret at all — removing the field
is the correct fix, not a substitution.

No runtime impact: the config "clients" block is only consumed by the memory
backend branch in OAuth2Plugin, and prod runs storage_type=postgres, where
client credentials come from the database.
Regenerated with api_diff.py --update-baseline --force. Two entries land here:

- ConfigTypes.h: the vue-client secret override path, flagged breaking only
  because the tool diffs declaration line-by-line. The symbol, its type and the
  EnvOverride layout are unchanged — this is data in an inline table, not an
  API surface change, so no major bump.
- DeviceCodeService.h: leftover drift from 881772a, which landed the shared-
  callback device-approval fix without refreshing the baseline. Ratified here to
  unblock the gate; it was not revisited in this commit.
- M1: the registerUser retry no longer routes through a std::function
  that captures its own shared_ptr (an unreachable reference cycle that
  leaked the HTTP response callback on an unauthenticated endpoint). The
  attempt is now a plain free function with an explicit retry counter —
  plain recursion, no self-referential capture in either AuthService.
- M2: generateUsername (identity) checks secureRandomBytes' return value
  and throws on failure — the buffer is left untouched on failure, so an
  unchecked read drew from uninitialized stack (same contract TotpUtils
  documents for its PR #157 review finding). Legacy side was already
  fail-closed via its UUID fallback; the parity comment is corrected.
- M4: markApproved reports (dbOk, found); UnexpectedRows on the find leg
  is a protocol-level miss (row reclaimed between lookup and update),
  reported as VALIDATION_DEVICE_CODE_INVALID instead of DB_CONNECTION_ERROR
  — symmetric with findByUserCode.
- M5: the readiness Redis guard now cancels its timer on the first real
  answer (TimerId + invalidateTimer via runInLoop; no-op if already
  fired) and the not-configured branch answers through the same CAS, so
  the single-answer invariant is structural. Dev configs enable Drogon's
  native 2s redis command timeout (timeout: -1 disabled it — the A-1
  root cause); the in-controller guard remains as the backstop for
  operator configs.
- M7: the identity registration/login paths now canonicalize emails,
  matching the legacy path (registration stored mixed case verbatim and
  lookup was exact-match, so mixed-case registrants could only log in
  with their exact-case email). V031 lowercases existing rows; the
  registration integration test re-asserts canonical storage.
- M8: the device-approve happy-path test deletes its seeded
  oauth2_device_codes row.
- M3: restoreSession() caches its in-flight promise and flips the
  sessionRestored flag only on completion; both router guard branches
  await it unconditionally and decide on the LIVE isAuthenticated —
  the previous flag check raced the store-init restore and never
  actually waited, so a revoked refresh token still bounced users into
  the zombie dashboard. The cached result is deliberately not trusted
  (it can predate a logout).
- M6: the stashed PKCE verifier is now stored as { state, verifier } and
  correlates with the callback's state (RFC 7636 §4.6). A stash left by
  an abandoned MFA login can no longer qualify an externally-initiated
  /callback landing; the stale stash is consumed on any redemption
  attempt. hasStashedVerifier() is replaced by hasVerifierForState();
  the drifted doc comment is rewritten.
- M9: changePassword navigates with router.replace instead of a full
  page load — logoutLocal() already cleared the state, so the SPA keeps
  its base prefix and locale; the e2e no longer needs the seeded-token
  resurrection workaround.
@voidvec

voidvec commented Sep 9, 2026

Copy link
Copy Markdown
Owner Author

Review response — all 10 findings addressed (commits 78cc8d0 + 934bd9d)

Thanks for the thorough review. Every Major and Minor is fixed; responses below. Everything was re-verified on freshly built binaries (the first "green" run after the fixes turned out to be against a stale test binary — a pipe-masking | tail swallowed the cmake failure; caught it via binary timestamps and re-ran everything for real).

Majors

1 (capture cycle) — Fixed with your suggested alternative shape: the retry attempt is now a plain free function (attemptRegistrationInsert) with an explicit attempts counter, called recursively from the create continuation. No self-referential shared_ptr exists at all in either AuthService, so there is no cycle to reason about and every capture is a strong, hop-surviving copy. (For the record: a weak_ptr patch inside the original lambda structure died on C3493 — the inner lambda can't name attemptCreate once the outer stops capturing it — which forced the cleaner restructure.)

2 (unchecked secureRandomBytes) — Identity's generateUsername now throws on RNG failure (registration → INTERNAL_ERROR, fail-closed). The parity comment is corrected: legacy is fail-closed via its fresh-UUID fallback, identity via the throw. The surrounding try/catch sites are now reachable.

3 (guest guard never waits) — restoreSession() now caches its in-flight promise and flips sessionRestored only on completion; both guard branches await auth.restoreSession() unconditionally and decide on the live isAuthenticated, never the cached result (which can predate a logout). The store-init restore and the guard now join the same promise instead of racing.

Minors

4 — markApproved reports (dbOk, found); UnexpectedRows on the find leg maps to VALIDATION_DEVICE_CODE_INVALID ("no longer pending"), other faults to DB_CONNECTION_ERROR. Symmetric with findByUserCode.

5 — All three sub-points: the winner now cancels the pending timer (TimerId + invalidateTimer via runInLoop, no-op if already fired); the not-configured catch answers through the same CAS; and the root cause is addressed directly — both dev configs now set the redis client timeout: 2.0, enabling Drogon's own per-command timeout that timeout: -1 had disabled. The in-controller 2s guard stays as a backstop for operator configs that leave -1; I left it hardcoded rather than adding a custom config key (new config surface needs the configuration-guide + baseline ceremony for marginal value — the operator-facing knob already exists as the standard redis timeout field).

6 — The stash is now { state, verifier } JSON; hasVerifierForState(state) (replacing hasStashedVerifier()) and exchangeCode(code, state) both require the state to match the callback landing (RFC 7636 §4.6 correlation), and the stash is consumed on any redemption attempt so an abandoned login can't qualify a later landing. Drifted doc comment rewritten. New e2e case: stale verifier + state mismatch → external-flow notice, zero token-endpoint calls.

7 — Confirmed as a real inconsistency and fixed rather than tracked: the identity path did NEITHER registration-normalization NOR login-identifier normalization while the legacy path does both. Both identity paths now canonicalize (mirroring legacy), V031 lowercases existing rows (case-variant collisions abort the migration loudly by design), and the test re-asserts canonical email equality. On the silent skip: the serverReachable() guard is the repo-wide convention for the HTTP integration tests (e.g. DEVICEAUTH_SKIP_GUARD in the same suite) — kept for consistency; the coverage swap is real but the pre-V030 DB-shape test it replaced was asserting a contract that no longer exists by design.

8 — The happy-path test now deletes its seeded oauth2_device_codes row. The client (p1-test-pub-device) is intentionally kept: it's the shared fixture the DeviceCodeRaceConditionTest re-creates idempotently, and deleting it would FK-fail against the redeemed tokens anyway — token residue matches the existing device-code tests.

9 — changePassword uses router.replace({ path: '/login', query: { pw_changed: '1' } }); the e2e dropped its seeded-token workaround (SPA navigation can't resurrect it).

Info 10

  • config.json scope: kept, deliberately. On Windows build.bat stages config.json as the local dev runtime config — it is the exact surface where U-6 reproduced — and the file already ships loopback dev callbacks (127.0.0.1:5173/8080); both host spellings are loopback, and production has its own untouched config.prod.json. Happy to move the addition to config.dev.json+seed only if you consider config.json shipped-default surface.
  • qrcode.vue: agreed it deserves standalone dependency review; it's MIT, peer-depends on vue ^3, renders the backend's own otpauth_uri client-side, and passes the size gate without a baseline raise. Say the word and I'll split it into its own PR / swap for an inline generator.

Follow-up

The arch-guard idea from your closing note is registered as #183 (flag two = std::move(callback) captures within one call). The M-6 discoverability finding is #182, M-8 dialog unification is #181.

Re-verification on the fresh build: Registration + both device-approve integration tests, full OAuth2Tests (59k assertions) and EndpointTests_OutOfProcess green; live checks confirmed mixed-case registration now stores canonical email with case-variant duplicates rejected 409, and /health/ready answers 503 degraded in 2.0s with Redis unreachable; browser acceptance re-ran green across the affected scenarios (p1 8/8, p2 9/9, p3 7/7, p4 4/4, admin p1 7/7, device flow 3/3, Redis-down dashboard 2/2).

V030 backfills generated usernames for NULL rows; V031 lowercases
emails to the canonical form (PR #180 review M7). Both verified
against a live database before baselining.
…tures

markApproved now reports (dbOk, found) and findByUserCode (ok, row) —
flagged breaking only because the tool diffs declaration lines. These
are Adapter-layer internal service callbacks (fulla::drogon::services);
the SDK surface is generated from OpenAPI and unaffected, so no major
bump (same rationale as the env-override ratification).
Three unit tests against the refactored registerUser path: generated-
name collision retry (first create reports USERNAME_TAKEN, the retry
must succeed with a fresh name), RNG-unavailable fail-closed (INTERNAL
_ERROR, no account created), and email canonicalization on both
registration and login (PR #180 review M7). Restores the identity
library's ratchet headroom consumed by the new code paths.
@voidvec
voidvec merged commit 8b4dbcc into master Sep 10, 2026
12 checks passed
voidvec added a commit that referenced this pull request Sep 10, 2026
- M1: the registerUser retry no longer routes through a std::function
  that captures its own shared_ptr (an unreachable reference cycle that
  leaked the HTTP response callback on an unauthenticated endpoint). The
  attempt is now a plain free function with an explicit retry counter —
  plain recursion, no self-referential capture in either AuthService.
- M2: generateUsername (identity) checks secureRandomBytes' return value
  and throws on failure — the buffer is left untouched on failure, so an
  unchecked read drew from uninitialized stack (same contract TotpUtils
  documents for its PR #157 review finding). Legacy side was already
  fail-closed via its UUID fallback; the parity comment is corrected.
- M4: markApproved reports (dbOk, found); UnexpectedRows on the find leg
  is a protocol-level miss (row reclaimed between lookup and update),
  reported as VALIDATION_DEVICE_CODE_INVALID instead of DB_CONNECTION_ERROR
  — symmetric with findByUserCode.
- M5: the readiness Redis guard now cancels its timer on the first real
  answer (TimerId + invalidateTimer via runInLoop; no-op if already
  fired) and the not-configured branch answers through the same CAS, so
  the single-answer invariant is structural. Dev configs enable Drogon's
  native 2s redis command timeout (timeout: -1 disabled it — the A-1
  root cause); the in-controller guard remains as the backstop for
  operator configs.
- M7: the identity registration/login paths now canonicalize emails,
  matching the legacy path (registration stored mixed case verbatim and
  lookup was exact-match, so mixed-case registrants could only log in
  with their exact-case email). V031 lowercases existing rows; the
  registration integration test re-asserts canonical storage.
- M8: the device-approve happy-path test deletes its seeded
  oauth2_device_codes row.
voidvec added a commit that referenced this pull request Sep 10, 2026
- M3: restoreSession() caches its in-flight promise and flips the
  sessionRestored flag only on completion; both router guard branches
  await it unconditionally and decide on the LIVE isAuthenticated —
  the previous flag check raced the store-init restore and never
  actually waited, so a revoked refresh token still bounced users into
  the zombie dashboard. The cached result is deliberately not trusted
  (it can predate a logout).
- M6: the stashed PKCE verifier is now stored as { state, verifier } and
  correlates with the callback's state (RFC 7636 §4.6). A stash left by
  an abandoned MFA login can no longer qualify an externally-initiated
  /callback landing; the stale stash is consumed on any redemption
  attempt. hasStashedVerifier() is replaced by hasVerifierForState();
  the drifted doc comment is rewritten.
- M9: changePassword navigates with router.replace instead of a full
  page load — logoutLocal() already cleared the state, so the SPA keeps
  its base prefix and locale; the e2e no longer needs the seeded-token
  resurrection workaround.
voidvec added a commit that referenced this pull request Sep 10, 2026
V030 backfills generated usernames for NULL rows; V031 lowercases
emails to the canonical form (PR #180 review M7). Both verified
against a live database before baselining.
wangrh0909 pushed a commit that referenced this pull request Sep 10, 2026
… and hooks

Consolidates the recurring lessons from the 2026-08/09 engineering sessions
(previously only in AI-session memory) into versioned, tool-agnostic assets:

- skills: ci-gate-sync (sync-point policies for error codes/endpoints/
  migrations/headers), ci-failure-triage (cross-compiler WERROR blind spots,
  flake taxonomy), release-engineering (six-point + ~15 version carriers,
  tag recovery, PyPI first publish), pr-workflow (rebase-merge repair,
  rebase value-loss audit, PAT permission boundary), local-env-runbook
  (Windows/WSL/Docker/Mimosa/multi-session rules), test-methodology (two
  test layers, mock injection seam, Playwright pitfalls), and
  benchmark-methodology (wrk Lua model, A/B discipline, measurement-artifact
  taxonomy).
- rules (path-scoped): sync-points (8-point error-code and 5-point endpoint
  hard checklists), frontend-contract (verified frontend/backend contract
  facts), async-cpp-gotchas (traps beyond db-operations: Session::insert
  no-overwrite, callback double-move, ::drogon:: shadowing).
- commands: /preflight (local gate sweep before pushing), /ci-triage
  (failure classification workflow).
- hooks: local-gates.sh (wired to the git-commit PreToolUse hook, replacing
  the broken full-ctest gate), port-guard.sh, redis-watchdog.ps1.

Provenance (source retrospectives): ci-gate-sync/rules.sync-points from PR
#115/#141/#149/#157/#179/#180 CI post-mortems; release-engineering from the
v1.0.0-v1.1.0 release runs; test-methodology from the coverage push
(48.5%->57.2%) and PR #140/#156 e2e work; benchmark-methodology from the
four-product comparison campaign; local-env-runbook from environment
incident records. AGENTS.md indexes the new rules and skills.
@voidvec voidvec mentioned this pull request Sep 10, 2026
voidvec added a commit that referenced this pull request Sep 10, 2026
Six-point version sync (Version.cmake, root CMakeLists, conanfile, both
frontend package.json/locks, openapi.yaml, pyproject) plus the doc/helm/
sdk-guide/package carriers. CHANGELOG [1.1.1] finalized from the
Unreleased section with the browser-e2e bugfix tranche (PR #180) and the
V030/V031 migration upgrade note (V031 fails fast on case-variant
duplicate emails).
@voidvec
voidvec deleted the fix/browser-e2e-bugfix-tranche branch September 20, 2026 12:43
wangrh0909 pushed a commit that referenced this pull request Sep 27, 2026
Static guard against the A-2 crash pattern (PR #180): one std::function
callback init-capture-moved into BOTH sibling lambdas of a single call
expression -- the two lambda objects are constructed unconditionally,
the loser holds an empty std::function, and its branch aborts when run.
Review-only vigilance failed once already (sibling functions missed a
month after the first fix), so the pattern is now CI-enforced.

The rule flags two `x = std::move(x)` captures only when they are direct
arguments of the SAME call expression with disjoint lambda regions.
Nested serial chains (TokenEndpointController's revoke chains), mutually
exclusive branches (SessionController if/else, SocialLinkService
provider arms), and direct-argument moves are legal shapes and produce
zero findings on the current tree (386 files scanned). Blind spots
(brace-init-list siblings, wrapped-call siblings, cross-statement
captures) are documented in the header; closing them needs a real AST.

Wired as a static-checks step (selftest + tree scan) next to arch-guard;
carriers synced: ci-cd-guide pipeline overview, db-operations.md combo
rule pointer, async-cpp-gotchas.md double-move bullet pointer,
local-gates.sh preflight gate.

Fixes #183
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