Repository navigation
fix: browser-e2e 2026-09-08 bug tranche — device approval crash, readiness hang, OAuth flow resume, blank-username deletion + 5 more - #180
Conversation
…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
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Code review — 27 files (+937/−170), verified against the branch head (
|
… 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.
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 Majors1 (capture cycle) — Fixed with your suggested alternative shape: the retry attempt is now a plain free function ( 2 (unchecked secureRandomBytes) — Identity's 3 (guest guard never waits) — Minors4 — 5 — All three sub-points: the winner now cancels the pending timer ( 6 — The stash is now 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 8 — The happy-path test now deletes its seeded 9 — Info 10
Follow-upThe arch-guard idea from your closing note is registered as #183 (flag two Re-verification on the fresh build: Registration + both device-approve integration tests, full |
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.
- 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.
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.
… 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.
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).
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
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
DeviceCodeServicemoved the same callback into bothMapper::findOnelambdas (findByUserCode,markApproved, deadfindByDeviceCodeHash); the loser held an emptystd::function→bad_function_callescaped the event loop and killed the process on every approval miss. Fixed with the shared-callback pattern (same ascreateDeviceCodein f1f418b), DB faults now distinguishable from "code not found" (DB_CONNECTION_ERRORvsVALIDATION_DEVICE_CODE_INVALID), dead function removed, and the admin approve leg gets its first integration coverage (invalid-code-survives + approve→redeem closure)./oauth2/authorizebounces anonymous users to/loginwith the OAuth params flattened (noredirect); 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.profile.username === ''made the Danger Zone confirm guard match empty input. Backend now generatesuser_<8 hex>(both registration paths, collision retry), V030 backfills existing NULL rows, and the frontend guard rejects empty confirm input outright.P1
/health/readyhung 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 503degraded/timeout; the admin dashboard decouples stats from readiness (allSettled + timeouts + 503 bodies accepted) so the cards always render.localhostin.envvs127.0.0.1in 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 unifiedAUTH_INVALID_CREDENTIALSanti-enumeration contract)./login?pw_changed=1with a notice; the guest guard restores the session before bouncing.P2
otpauth_urias a QR code (qrcode.vue; size gate passes without a baseline raise).if existfix.Not fixed, with evidence
UserDetailPage.vue:107). M-6 "Revoke All for User" is a filter-bar button gated on a typeduser_idfilter, not a dropdown entry — works as designed (screenshot evidence), noted for discoverability.Test plan
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.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./health/readyanswers 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.