Commit Graph

19 Commits

Author SHA1 Message Date
kshitijk4poor
af5c2014a8 refactor(dashboard-auth): collapse verify_jwt's identical except arms
Final-head review fold:

- verify_jwt: the expired / bad-signature / not-yet-valid arms existed only
  because the catch-all used to raise ProviderError; all now raise the same
  InvalidCodeError, so one InvalidTokenError arm covers them (PyJWT's own
  message names the failure; the clock-skew test matches it). The aud/iss
  arm's diagnostic re-decode runs only after the signature verified, so its
  try/except-pass guarded nothing.
- Docstrings: ProviderError also covers a malformed JWKS and a provider-wide
  contract failure (oauth_contract_version); the refresh comment no longer
  assumes Portal's rotate-on-use refresh tokens.
- Cookie tests use the __Host- names the server sets over HTTPS, so they
  keep exercising verify/refresh once bare names stop being read there
  (#136772); the access-token-only case asserts the session-expired reason
  rather than any 401.
2026-11-07 16:04:30 +05:30
kshitijk4poor
b182c16aee fix(dashboard-auth): log drift only for verified aud/iss mismatches
Round-2 review: the drift WARNING fired on every InvalidTokenError. PyJWT
checks the algorithm before the signature, so a forged token naming the
published kid with another alg reached that branch unauthenticated and
logged attacker-chosen iss/aud of any length.

Warn only on InvalidAudienceError / InvalidIssuerError, which PyJWT raises
after the signature verified (a real IdP-signed token: a foreign client's,
or config drift), with the echoed unverified values capped at 128 chars.
Other claim failures stay a plain InvalidCodeError, unlogged.

Tests: a forged-alg token with the published kid is a 401 with no drift
line (fails against the previous shape), and a gate-level cookie+RT case
where Portal's rotated token does not verify here is a signed-out 401.
2026-11-07 16:04:30 +05:30
kshitijk4poor
f6c8b95fda refactor(dashboard-auth): one refresh-boundary mapping, keep drift visible
Folds the pre-arm review of the salvaged stack:

- Map a grant's "minted token is not ours" InvalidCodeError to
  RefreshExpiredError once, in JwtOAuthProvider.refresh_session, instead of
  a copy in each provider's _grant (the auth-code path already raises
  InvalidCodeError -> 400, so the copies only mattered for refresh).
- A wrong aud/iss is also what config drift looks like (wrong client_id or
  portal URL). Now that it is a 401 instead of a 503, nothing logged it:
  verify_jwt logs the token's and the configured iss/aud at WARNING. The
  diagnostics tests assert that log through verify_session instead of
  calling _claims_for/_verify_id_token directly.
- oauth_contract_version mismatch deliberately stays a 503 (every token
  Portal mints would fail it); say so beside the check.
- Fix the now-stale InvalidCodeError and classify_jwks_lookup_error
  docstrings and trim per-branch comments that restated the rule.
- Tests: fold the gate-level cases into test_opaque_bearer_not_unreachable.py
  with one JWKS-server helper and one gated-app helper (three server copies
  -> one), add a cookie-path case, close the server socket.
2026-11-07 16:04:30 +05:30
paul.yang
3fe7d20c88 fix(dashboard-auth): verify-stage token denials trigger re-login, not a misleading 503
verify_jwt raised ProviderError for every decode-time rejection except
expiry, so a token minted for a different client on the same IdP (e.g. the
Hermes Desktop app reusing one session across two same-issuer gateways)
surfaced as '503 Auth provider self-hosted unreachable' — the IdP was
reachable and had answered; the token was simply not ours (audience
mismatch). Operators only saw the real reason in errors.log.

Denials are now InvalidCodeError end-to-end:
- verify_jwt: wrong audience/issuer, bad signature, missing claims ->
  InvalidCodeError (diagnostic iss/aud still appended). verify_session
  returns None per protocol -> middleware refreshes / re-logins.
- JwtOAuthProvider grants (self-hosted + nous) map a verify-stage
  InvalidCodeError to the caller's bad_request_exc (InvalidCodeError for
  the auth-code path, RefreshExpiredError for refresh) so the middleware
  refresh scan rejects the provider instead of crashing on an uncaught
  InvalidCodeError.
- JWKS transport failures stay ProviderError (503) — unreachable means
  unreachable.
2026-11-07 16:04:30 +05:30
Teknium
65bec86e37 Merge origin/main (#27: 19 commits to 517b5e10fe) into feat/unified-gateway-runtime
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 12:09:24 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
86e81c4470 Merge origin/main (#22: 4 commits to 8a33891bdd) into feat/unified-gateway-runtime
Conflict: tui_gateway/server.py (f3ef9db683 voice-turn reasoning leak). The branch moved
_runtime_model_config/_persist_live_session_runtime to tui_gateway/agent_factory.py; main's
session_runtime_view edits ported there, and kept in place for _live_session_identity and
_session_info.
2026-10-07 18:11:16 -07:00
Teknium
8a33891bdd revert: dashboard-auth token exchange breaks on gzip IdP responses (partial revert of #133938)
Reverts the plugins/dashboard_auth half of ca38caeea0.

_request_limited_response streamed the body via iter_bytes() (already
gzip-decoded by httpx) and rebuilt an httpx.Response with the ORIGINAL
headers, Content-Encoding: gzip included, so .json() tried to gunzip
plaintext. Every Nous Portal dashboard login failed with
503 "Provider unreachable: Portal token endpoint unreachable: Error -3
while decompressing data: incorrect header check". Self-hosted OIDC
discovery/token/revocation used the same helper.

The urllib half (gateway health probe, ElevenLabs voices) is kept:
urllib does not decode Content-Encoding, and c061068b26 builds on its
_read_dashboard_json_response helper.
2026-10-07 17:52:08 -07:00
Teknium
1e500ebce2 Merge origin/main (#16: 4,465 commits to 9dcab1e440) into feat/unified-gateway-runtime
99 conflicted files resolved in nine area lanes (Desktop composer, Desktop renderer/shared
client, Electron main, Ink, tui_gateway, gateway, state, CLI/config, cron/tools/CI). The
unified runtime's architecture wins where it deliberately replaced a mechanism (pool,
fallback lanes, claim poller, renderer queue); every orthogonal main change is kept, ported
into the <stem>_<topic> sibling that now owns relocated code.

Notable ports and repairs in this merge:
- tui_gateway/server.py relocated regions: atomic _attach_built_agent (#49852), slash ranking
  registry names, minted-key helpers methods_session.py calls, request_overrides, service tier.
- gateway/run_turn*.py: i18n accessors for the removed reply constants, first-contact
  internal/DM rule, rotated-compression persist, fast-mode tiers, prompt-pin rehydration.
- webhook: route_from_chat_id decodes main's opaque webhook:v2 chat ids (old ids still read).
- ws.py: main's per-connection dispatch queue with authority-first dispatch inside it.
- state: schema event for runtime revision renumbered to 31; worker mirrors updated for
  main's message uid/merge fields, on_contended lease arg, compression columns.
- config: branch's bot_chat_delivery_timeout removal renumbered v47 -> v50.
- Electron: primary-profile pin, redirect header scoping, remote fetchJsonForBackend, SSH
  teardown on profile delete, held-update dial gate restored (lost in earlier merges).
- Desktop: canonical clarify.request mapped to main's questions[] card; replay truncation vs
  snapshot_required; periodic secondary prune tick restored; DELETE already_absent restored.
- cron/tools: diagnostic category on cron failure notices restored; owner_holds_delivery
  ported onto the authority; admitted receipts can no longer be cancelled locally.
2026-10-06 14:24:24 -07:00
Austin Pickett
ca38caeea0 fix(dashboard+auth): cap HTTP JSON response body reads
Dashboard-side urllib readers (gateway health probe, ElevenLabs voices)
and self-hosted OIDC httpx readers (discovery, token exchange, revocation)
buffered remote response bodies with no size bound — a hostile or
compromised upstream could exhaust memory. Both halves now read with a
1 MiB hard cap: a shared _read_dashboard_json_response for urllib JSON
reads and a streaming _request_limited_response for IdP endpoints that
prechecks Content-Length and caps the chunked body regardless.

Adapted from #54809 and #55122 (credit @ooiuuii) to current main, where
the token exchange lives in plugins/dashboard_auth/_shared.py and the
health probe in hermes_cli/web_server_gateway.py.

Fixes #54808, Fixes #55121
2026-10-06 12:28:55 -04:00
Austin Pickett
c5cb0f597b fix(dashboard-auth): clock-skew leeway for JWT verification; classify not-yet-valid tokens as validation failures
Both dashboard-auth JWT verification paths (self-hosted OIDC ID token and the
Nous Portal access token, via the shared verify_jwt) called PyJWT jwt.decode
with the default leeway=0 while requiring iat. Any host whose clock lags the
issuer's — unsynced containers/VMs, NTP jitter — failed login with
ImmatureSignatureError, and the failure was folded into ProviderError, i.e.
HTTP 503 'provider unreachable', discarding already-rotated refresh tokens
and forcing unrecoverable re-logins.

- verify_jwt gains leeway (default 60s, RFC 7519 §4.1.4-4.1.6) and classifies
  ImmatureSignatureError as InvalidCodeError (validation failure -> 401 /
  refresh) instead of ProviderError/503.
- New parse_leeway helper: fail-closed parsing (unparseable / negative / NaN /
  inf -> 0, never widens the window); 0 honours strict mode.
- Self-hosted OIDC: id_token_leeway kwarg + dashboard.oauth.self_hosted.id_token_leeway.
- Nous: token_leeway kwarg + dashboard.oauth.token_leeway.
- No new env vars (config.yaml-only knobs).

Fixes #47815
2026-10-06 11:14:28 -04:00
Teknium
6b8a6d4c35 fix: isolate authenticated gateway owners by provider and issuer 2026-09-10 05:17:39 -07:00
Teknium
5bb155d568 fix: a forged JWT bearer is an invalid token, not an auth-provider outage
verify_jwt folded jwt.InvalidSignatureError into the generic InvalidTokenError branch and
raised ProviderError, so the gated API answered a tampered/foreign-key OIDC bearer with
HTTP 503 "Auth provider 'self-hosted' unreachable" (cookies retained, no fall-through to
the next provider) while the IDP was healthy. Live remote-bind probe on 127.0.0.2 showed it.
Signature failure now maps to InvalidCodeError -> verify_session None -> 401
session_expired, same as an expired token. Genuine iss/aud drift keeps its diagnostic 503.
2026-09-09 05:42:05 -07:00
Teknium
e83816a4d1 review-fix(comments): restore lost #NNNN rationale comments across non-test source (mechanical sweep, condensed, code unchanged)
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.
2026-09-03 09:44:26 -07:00
Teknium
a1f0e6e657 refactor(plugins/kanban,dashboard_auth): compact docstrings/comments (WHY retained), document JwtOAuthProvider hook contract 2026-09-02 22:54:41 -07:00
Teknium
d20d37e5e0 refactor(plugins/dashboard_auth): JwtOAuthProvider base (complete/refresh/verify + JWKS client) and NonInteractiveMixin in _shared; nous/self_hosted/basic/drain become thin subclasses 2026-09-02 22:45:15 -07:00
Teknium
eccfcb5f8e refactor(plugins/hermes-achievements,dashboard_auth): unify snapshot/scan_meta/result builders, drop dead evaluate_boolean + import shims, compact module docstrings, AST-neutral layout 2026-09-02 21:43:13 -07:00
Teknium
e986577dca refactor(plugins/kanban,dashboard_auth): split update_task/bulk_update into phase helpers, dict-driven orchestration writes; unify provider register() via _shared.register_provider/SkipRegistration 2026-09-02 21:09:26 -07:00
Teknium
238260e6aa refactor(plugins/dashboard_auth): shared session/JWT/config helpers in _shared; compact basic/drain/nous/self_hosted 2026-09-02 13:30:10 -07:00