Repository navigation
fix(public-links): an expired visitor session asks for the email again, never the operator /login (#3406) - #3411
Conversation
…n, never the operator /login (#3406) A visitor who verified their email on /chat/:token and came back after the 24 h session expired was sent to the operator /login and stayed locked out. The page's history and intro 401s went through the global axios interceptor, and the 401 verdict treated /chat/ as an operator page. An operator previewing their own link was signed out of the platform the same way, because their JWT rides every bare-axios request. The 401 verdict (utils/platformSession.js): - /chat/:token and /canvas/s/:token never navigate. They end the platform session in place (new verdict `logout-in-place`) only when the stored token is the one that failed and the platform rejected it: a `WWW-Authenticate: Bearer` challenge on /chat/, any 401 on the canvas. A bare 401 is the link's own session. A blanket ignore would leave the ws-ticket retry 401ing every 5 s on a dead token. - /m ends a dead token in place on a Bearer-challenged 401, so the PWA shows its own inline login. - main.js judges a 401 against the address being loaded until the first navigation settles (`pathForVerdict`), because `currentRoute` reads "/" (START_LOCATION) until then. PublicChat.vue: - One reaction, `endPublicSession()`, handles a 401 from history, intro, session clear, send and Stop. It shows the verify card with the existing "Session expired. Please verify your email again." and removes only this tab's key. The transcript reloads after the visitor verifies again. - An unsent message goes back into the input. - Stop sends `session_token` as a query parameter on email links. Before, it sent none, so Stop there always 401'd. Canvas (added at pick time): an authorized share's own "Sign in" card is no longer pre-empted. Login.vue honours `?redirect=` for in-app paths only (utils/safeRedirect.js), on every non-SSO success path. Tests: the verdict and reaction executed; PublicChat and Login mounted through their real call sites; a real-router first-navigation test; a route table guard (any route open without requiresAuth must be classified); and a backend test driving the handlers to pin which 401s carry the challenge. Mutation: each fix site reverted from a scratch copy turns a named test red (39 frontend, 2 backend), e.g. "a history 401 clears the stored session and shows the verify card with the reason", "the second victim: an operator's LIVE token rides the request, and the 401 is the link's", "during the FIRST navigation it is the address being loaded". Fixes #3406 Co-Authored-By: Claude Opus 5.5 <[email protected]>
AndriiPasternak31
left a comment
There was a problem hiding this comment.
Approving. The fix does what the issue asks without changing the dashboard: the Bearer check changes the verdict only on /chat/ and /m, and an operator page still logs out on any 401. There's one should-fix below, on Stop.
Reviewed at a9303ff33. The 5 specs in the PR: 112 passed. Full vitest: 5114 passed. test_3406_bearer_challenge_contract.py: 4 passed, and adding a Bearer header to terminate's expired-session 401 turns it red. The branch merges cleanly with dev and with #3412, which also touches PublicChat.vue.
What I verified
-
Every 401 for a dead platform credential carries the challenge.
get_current_user(dependencies.py:634-638) covers:- an expired or pre-restart JWT;
- a malformed or revoked token;
- a deleted or suspended user;
- a bad MCP key.
The missing-token path,
/api/tokenand/api/auth/validatecarry it too. The bare 401s that remain never judge the platform JWT: link sessions, file download tokens, OTP, webhooks and the canvas sign-in. nginx.conf passes the header through, and the calls are same-origin, so CORS exposure doesn't matter. -
?redirect=can't leave the origin.//evil.com,/\evil.com,\\evil.com,javascript:, absolute URLs, and an embedded tab or newline all fall back to/. Some inputs pass the guard:/%2F%2F…,/%5C…,/..//evil.com, slash lookalikes and/@evil.com. Pushed through a realcreateWebHistoryrouter, every one of them stays on the origin. -
pathForVerdict. In vue-router 5.3.1,currentRoutestarts as the exactSTART_LOCATIONobject, and there is no router base. The #2791 Workspace veto holds on a first load. -
Mutations. 14 of 15 went red. They included dropping the chat discriminator, the
/marm, the draft restore, Stop'ssession_tokenand the//check, and makinglogout-in-placenavigate. The one that stayed green is theheaders.getbranch, which is redundant because axios lower-cases header names.
Should fix
- On an email link, the agent's own 401 from Stop ends a valid visitor session.
PublicChat.vue:940reads any 401 there as an expired session.- But terminate re-raises whatever the agent answers (public.py:1010, chat_execution_service.py:2691-2694). The agent's auth middleware (agent_server/middleware/auth.py:85) answers a bare 401 when the agent-auth secret is wrong.
- The visitor's session is then removed, they get "Session expired. Please verify your email again.", and the turn isn't cancelled.
- Evidence: I drove the route with a valid session and made the agent call raise
ChatDispatchError(401); it returned a bare 401 with no header. A copy of your mounted spec with terminate answering 401{"detail":"Unauthorized"}ends withstored: null, card: true. - The comment on that branch already says this for open links ("a 401 there is the agent's own status").
- Either fix is fine with me: map an agent 401 to 502 in the terminate route, or have the client end the session only on the two session
detailstrings.
Nits
loginRedirect.spec.js:132("someone already signed in goes straight there") mounts Login withisAuthenticatedtrue. The app never reaches that state: the guard at router/index.js:451-454 sends a signed-in visitor from/loginto/first. Checked through the real router,/login?redirect=/canvas/s/abclands on/. It's minor, since the canvas card only shows to signed-out viewers, butadmin-login.md:99claims it.endPublicSession(PublicChat.vue:486-487) compares storage with the session in memory, not the one the failed request carried. Say the visitor re-verified as S2 while a request with the old S1 was still in flight; when its 401 lands, it removes S2. I found this from the code only, and it's unlikely given the email round trip.- Wording.
- The summary says the session ends only on a 401 with
WWW-Authenticate: Bearer, but on/canvas/s/any 401 on the stored token ends it. That behaviour is correct; the summary just doesn't say it. architecture/workspace.mdlistslogout-in-placefor/chat/and/canvas/s/and leaves out/m.- The CSO report says 4 new specs; there are 3 new and 2 extended.
public-agent-links.mdcitescancelTurn()at :907; it's at :911.
- The summary says the session ends only on a 401 with
Not checked: anything in a browser or on a live stack, and the enterprise submodule's routes.
…orable secret value is a named 422 (#3325) (#3417) Fixes #3325 — independent fix, one of ten small bug fixes in the trinity-pm `chain-easy-1008` run. Base is `dev`. **Draft until the operator merges.** ## What - `src/backend/services/credential_encryption.py::decrypt`: every malformed envelope shape raises `ValueError`, as the function promises — JSON that is not an object (`[]`, `null`), and a non-string nonce or ciphertext. Importing such a `.credentials.enc` now returns **400** instead of a 500 with a stack trace in the log. The envelope format and every successful decrypt are unchanged. - `src/backend/services/secret_settings.py::encrypt_secret_setting`: the key is checked first, in its own `try`, and only that check can raise `MissingEncryptionKeyError`. A value that cannot be encoded (for example a lone surrogate) raises the new `SecretSettingValueError(ValueError)`. Its message names the setting, never the value. - `src/backend/error_handlers.py` + `src/backend/main.py`: one app-level handler maps `SecretSettingValueError` to **422**. `src/backend/routers/settings/credentials.py`: three pass-through lines in the routes whose catch-all would have turned it into a 500 (Anthropic, GitHub PAT, `PUT /slack`). - Tests: the three strict-xfail markers in `test_ec_credential_crypto_edges.py` are removed; new `tests/unit/test_3325_credential_error_types.py` (registered in `tests/registry.json`) asserts no value in the message or the exception chain, a missing key reported before a bad value, `PUT /api/settings/api-keys/anthropic` → 422, and that `main.py` registers the handler. ## Rulings carried (orchestrator, on the operator's behalf — plan file) - TD-1: one app-level handler plus the three pass-through lines — as recommended. - TD-2: a `.credentials.enc` that decrypts correctly but whose contents are not an object is deferred — as recommended; forging one needs the platform key. - TD-3: 422, matching the existing 422 for refused cleartext writes — as recommended. ## Review + security `/review` reading pass (claude-fable-5-1, report-only): **MERGEABLE**, no critical findings. The secret cannot leave through the new error: it is raised after the `except` block, so `__context__` is cleared, not merely hidden; the handler returns only the message; nothing logs it; audit rows are written only after a successful write. The only residual carrier is traceback frame locals, which nothing in the backend renders. The handler is keyed on the subclass, so no other `ValueError` is swallowed or relabelled. `/cso --diff`: no findings. Evidence sweep (claude-opus-5-5): **GREEN**. 23 unit files import the touched modules; the 16 most direct ran shuffled (seed 12345), one file per process, all passed. All 7 tests in the new file ran, 0 skipped. With both service files taken from `dev`, exactly the three formerly-xfail tests fail (8 cases). Seven less direct files are left to CI and named in the review file. `git merge-tree` against `dev` f6bedcd is clean. ## Tests Targeted counts above. Not run here: the full unit island (CI). ## Before merge - Startup auto-import (`lifecycle.py`) on a malformed envelope now lands in its `ValueError` retry arm: it retries without a warning per attempt and ends in the same "failed" result, with the existing error log after the last attempt. - Enterprise callers of `decrypt` get `ValueError` where they got `AttributeError` / `TypeError` on a malformed envelope. Two catch broadly, three propagate as before; no change needed there. - The new test file has a module-level `importorskip` for `sqlalchemy` and `cryptography`: it skips silently where those are missing. They are present on the engineer and in CI. - Ten open PRs share `tests/registry.json` or `src/backend/main.py` with this branch (#3412, #3411, #3407, #3304, #3271, #3256, #2984, #2956, #2713, #2709). A test-merge of this head against each adds no conflict beyond what that PR already has with `dev`. ## Handoffs (not in this diff) - TD-2 above: the decrypted-but-not-an-object case can still 500 on import. - `PUT /api/settings/slack` saves the client ID before a later secret write fails (partial update, pre-existing). - The GitHub PAT, Resend and Gemini routes are covered by the app-level handler but not exercised by the new route test. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…L is refused, not stored (#3323) (#3420) Fixes #3323 — independent fix, one of ten small bug fixes in the trinity-pm `chain-easy-1008` run. Base is `dev`. **Draft until the operator merges.** ## What - `src/backend/utils/url_validation.py::reject_embedded_credentials`: strips its input and treats a leading `//` as already having a host, the same rule `strip_url_credentials` uses. `//<token>@github.com/o/r` is now refused like the `https://` form, including with leading whitespace or mixed case. All three write paths that store a skills-library URL go through this one function (`routers/skills.py` create and update, legacy adoption in `services/skill_service.py`), so the token is no longer saved in plaintext to `skill_sources.url` or the audit details. - If `urlparse` refuses an input that starts with `//`, the function falls back to the module's existing userinfo regex instead of raising, so this fix adds no new 500. - Tests: the D3 strict-xfail marker is removed; four more refused shapes and a four-case "must not raise / must not over-reach" test are added. ## Rulings carried (orchestrator, on the operator's behalf — plan file) - TD-1: the fallback applies only to inputs starting with `//`; the bare `ValueError` for every other malformed input is #3322's and is unchanged (D4 stays a strict xfail) — as recommended. - TD-2: keep the username/password check; `//@host` carries no secret and is not refused — as recommended. - TD-3, TD-4: deferred, see Handoffs — as recommended. ## Review + security `/review` reading pass (claude-fable-5-1, report-only): **MERGEABLE**, zero critical, five informational. The pre-fix and post-fix modules were executed side by side over forty inputs: nothing that was refused before now passes, credential-free inputs are unchanged, the fallback regex is anchored and linear. `/cso --diff`: no findings. Fixed after review: - `546f329a` — the `tests/registry.json` descriptions no longer call #3323 a strict xfail. - `a75a5e04` — the reject stub in `test_ent183_skill_packages.py` mirrors the fixed `//` rule. It is deliberately stricter than production on a malformed bracket (`//[oops/x` raises). Evidence sweep after the fix (claude-opus-5-5): **GREEN**. 28 unit files import the module; the 14 most direct ran shuffled (seed 12345), one file per process. Three did not come back clean, none because of this branch: - `test_ent236_skills_lifecycle.py::TestNonRepoDirectoryRecovers::test_real_repo_still_pulls` and `test_skill_service_user_agent.py` (collection error) fail the same way on `dev` f6bedcd in the engineer's environment. - `test_ent237_skill_sources.py` hit the 240 s per-file limit at about 72 % with no failure printed — left to CI. `git merge-tree` against `dev` f6bedcd is clean. ## Tests 895 passed across the 11 files that completed cleanly. Not run here: the 14 less direct importer files, `test_ent237_skill_sources.py` to completion, and the full unit island (CI). ## Before merge - Ten open PRs share `tests/registry.json` with this branch (#3417, #3412, #3411, #3407, #3304, #3271, #3256, #2984, #2956, #2709). A test-merge of this head against each adds no conflict beyond what that PR already has with `dev`. - One stale docstring remains at `tests/unit/test_ec_url_validation_properties.py:36` (still calls D3 a strict xfail). ## Handoffs (not in this diff) - TD-3 (P3): shapes that still pass both reject and strip — `/\t/tok@`, `/\n/tok@`, `///tok@`, `https:/tok@` (`urlparse` removes tab and newline after the check). Fixing it needs the same change in `strip_url_credentials` and cases in both test families. - TD-4: a property test that reject and strip always agree over the shared `test_2052` corpus; it needs exceptions for empty userinfo. - #3322 (bare `ValueError` / `UnicodeError` → 500) is the sibling issue in the same file and is untouched. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…t the database (#3385) (#3421) Fixes #3385 — one of ten small bug fixes in the trinity-pm `chain-easy-1008` run. **Stacked on #3414** (the fix for #3314): base is `feature/3314-queue-fingerprint-falsy`, because both issues edit `_clamp_ingested_item` and the fingerprint helpers. Merge #3414 first, then retarget this to `dev`. **Draft until the operator merges.** ## What - `src/backend/services/operator_queue_service.py`: new `OPERATOR_QUEUE_TYPE_MAX = 64` and `_bounded_type`. An agent-written `type` longer than 64 characters is shortened with the existing `…[truncated]` marker at ingest (`_clamp_ingested_item`); the ask is never refused or lost. `_comparable_type` applies the same bound, so a shortened row does not read as a rewrite (#2915) and a row stored before this fix at full length still compares equal. - `src/backend/db/operator_queue.py::_insert_values`: `_DB_BELT_TYPE_MAX_BYTES = 1024`; above it the insert raises `ValueError`, like the id / title / question / context belts. All three create paths go through it. - Docs: five lines in `architecture/api-endpoints.md`, `feature-flows/operating-room.md` and `requirements/security.md` that list the clamp and belt fields now name `type`. - Tests in `tests/unit/test_1632_operator_queue_caps.py`: an oversized type is shortened with the marker; every platform-emitted type and every type `ask_operator` accepts is unchanged; the belt rejects an oversized type and passes 64 four-byte characters; `test_3385_clamped_type_is_not_a_rewrite` (clamped row vs raw entry, legacy full-length row, a real rewrite inside the first 52 characters). ## Rulings carried (orchestrator, on the operator's behalf — plan file) - T1: a fixed constant, no environment variable — as recommended. - T2: 64 characters — as recommended. The longest type the platform emits is `workspace_problem_report`, 24. - T3: the DB belt raises, like its siblings — as recommended. - Orchestrator: stacked on #3314 instead of branching from `dev`, so the two fixes do not hand the operator a conflict in the same two functions. ## Review + security `/review` reading pass (claude-fable-5-1, report-only, against the stacked base): **MERGEABLE**, zero critical. Census of every literal `type` the platform and the enterprise submodule pass to the insert paths: longest is 24 characters, none is altered. Every truncated value ends in the marker, which no set member can match, so truncation cannot move a value into or out of a set that decides control flow (`_BUDGETED_ALERT_TYPES` and neighbours). The new `ValueError` is reachable only from the file sync loop, which quarantines it under its existing handler. `/cso --diff`: no findings; the error text carries the constant, never the value. Fixed after review: `eab91c10` — I1, the five doc lines. Noted, not changed: I2, a non-string `type` over 1 KiB now raises the named `ValueError` where the base failed at the bind — same quarantine outcome. Evidence sweep after the fix (claude-opus-5-5): **GREEN**. 13 operator-queue files ran shuffled (seed 12345), one file per process: 836 passed, 7 xfailed. With both production files taken from the #3314 branch, the two `TestClampType` cases, the belt test and the clamped-row fingerprint case go red. `git merge-tree` against `dev` f6bedcd is clean; the base branch has not moved (`923b1edc`). ## Tests Counts above. Not run here: `test_ent815_queue_walk`, `test_ent815_broad_list_agent_scope`, `test_ent751_gate_entries` (2–4 minutes each; they ran green on the #3314 base in that PR's sweep) and the full unit island. ## Before merge - **This PR's checks are weaker than a dev-based PR's:** a PR whose base is a feature branch runs a reduced CI set and `backend-unit-test` does not run. The first full run happens when it retargets to `dev` after #3414 merges — read that run before merging. - Accepted trade-off: an agent that rewrites an oversized type only after character 52 is not detected as a change. Titles and questions already behave this way. - Thirteen open PRs share a file with this branch (mostly `tests/registry.json` and `docs/memory/architecture/api-endpoints.md`; #3256 also `db/operator_queue.py` and the three docs). A test-merge of this head against each of #3420, #3417, #3412, #3411, #3407, #3304, #3271, #3256, #2984, #2956, #2713 and #2709 adds no conflict beyond what that PR already has with `dev`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Summary
/chat/:tokenlink has expired now gets the verify card with the existing red "Session expired. Please verify your email again." instead of the operator/login. That holds wherever the 401 lands: page load, send, New and Stop. A message that was being sent goes back into the input, and the conversation reloads once the visitor verifies again.WWW-Authenticate: Bearer(emitted byget_current_userand the missing-token path; the link-session 401s are bare). On/chat/,/canvas/s/and/mit does so in place, with a new verdictlogout-in-place, and never navigates./login.Login.vuenow honours?redirect=for in-app paths only (utils/safeRedirect.js), so signing in returns to the canvas.Fixed on the way, same bug class:
session_token, so it always 401'd and landed on/login. It now sends it as the route's query parameter.main.jsjudged a first-load 401 against/, becauserouter.currentRoutereadsSTART_LOCATIONuntil the first navigation settles.pathForVerdictuses the address being loaded until then. A Workspace client lost bug(session): main app and Workspace disagree about the platform session — two credential sources, no cross-tab sync, three 401 logout paths; a stale Workspace tab logs a fresh re-login out #2791's veto on a first load the same way; that is fixed too./mwith a dead token now drops to the mobile login, instead of a signed-in-looking shell whose panels all fail while the ws ticket retries every 5 s.Changes
src/frontend/src/utils/platformSession.js/chat/,/canvas/s/and/m;logout-in-place;isBearerChallenge(fails towardfalse);pathForVerdictsrc/frontend/src/main.jspathForVerdict(router, START_LOCATION, window.location.pathname)src/frontend/src/views/PublicChat.vueendPublicSession(), for a link-session 401 from history, intro, New, send and Stop; removes only this tab's stored session; Stop sendssession_tokensrc/frontend/src/views/Login.vue,src/frontend/src/utils/safeRedirect.js?redirect=on every non-SSO success path, bounded to in-app pathstests/registry.jsonworkspace-session-signout,public-agent-links,agent-canvas,admin-login),architecture/workspace.md, user docs (public-links,agent-canvas), two learnings fragments, the/cso --diffreportNo backend product code, no DB migrations, no dependency or Docker changes.
Test plan
Frontend specs pass:
cd src/frontend && npx vitest run tests/unit/platformSessionVerdict.spec.js tests/unit/platformSessionSync.spec.js tests/unit/publicLinkSessionExpiry.spec.js tests/unit/loginRedirect.spec.js tests/unit/publicSurfaceRoutes.spec.js.PublicChatandLoginare mounted (jsdom) and driven through their real call sites. The first-navigation case runs a realvue-router.publicSurfaceRoutesfails when a route that is open withoutrequiresAuthis not classified by the verdict.Backend contract test passes:
cd tests && pytest unit/test_3406_bearer_challenge_contract.py -v(4 passed). It drives the handlers to pin which 401s carry the Bearer challenge.Mutation: each fix site, reverted from a scratch copy, turns a named test red (39 frontend mutations, 2 backend). All files were restored byte-identical.
Full host vitest run is green except 3 failures outside this diff, all from the host environment: two specs need
@vue/compiler-sfc, which isn't installed there, and one comes from a local DOMPurify version drift./cso --diff: 0 critical, 0 high. One medium (the new 401 discriminator didn't state its failure direction) is fixed in-branch. Report:docs/security-reports/cso-diff-2026-10-08-3406-public-link-401.md.Eyeball on localhost at
a9303ff33: all 7 steps PASS./login.POST …/terminate?session_token=…returns 200./chat/: one ws-ticket 401, no retry loop.?redirect=round trip back to the canvas, and the dead-token variant./mwith a dead token shows the mobile login.The test agent has open access off, so the expiry steps verified with the owner's email.
Follow-up
?redirect=. The SSO success path inLogin.vuestill lands on/, because the IdP round trip drops the query. Signing in to an authorized canvas share through SSO therefore ends on the dashboard. It will be filed as its own issue after this merges.Known and accepted:
/loginat first load is now ignored there instead of cleared. The existing/login → /guard and the dashboard's own 401 clear it one hop later.Fixes #3406
🤖 Generated with Claude Code