Commit Graph

59 Commits

Author SHA1 Message Date
Maciej Lisiewski
3b0a5e728d fix(dashboard-auth): logout revokes by access token and Basic skips the refresh replay cache
A session_ttl_seconds above the 30-day refresh TTL left a logout after day 30
with no refresh token to revoke, so a copied access token kept working; logout
now also hands the access-token cookie to revoke_access_session (Basic revokes
its sid). Basic refresh tokens stay valid after use, so a copied RT's cached
rotation could outlive a logout that presented the browser's newer RT; Basic
opts out of success caching via refresh_reuse_detection = False. Adds tests
that kill the forget() link, generation and read-before-write mutants.
2026-11-12 15:55:24 +01:00
Maciej Lisiewski
549bde85e4 fix(dashboard-auth): logout also ends cached refreshes and long-TTL tokens
Three gaps in the basic-auth logout from review:
- revocation lasted only the refresh TTL, so with session_ttl_seconds above
  30 days a logged-out access token worked again before it expired;
- the refresh replay cache kept handing a copied RT the rotated session for
  up to 30s after logout; logout now drops that login's cached rotations
  (following the rotation chain) and bars in-flight refreshes from caching;
- a worker skipped re-reading the revocation file when its mtime was
  unchanged (coarse-timestamp filesystems), missing another worker's logout
  and later overwriting it; the small file is now read every check.

Refs #77186
2026-11-12 15:55:24 +01:00
Maciej Lisiewski
02ba28abd3 fix(dashboard-auth): end basic-auth sessions on logout and credential change
The basic provider's tokens were signed only with the configured secret and
revoke_session() was a no-op, so a copied token outlived logout for its full
TTL (30d via refresh) and rotating the password while keeping an explicit
secret left every old session valid.

Tokens are now signed with a key derived from the secret plus the username and
a restart-stable form of the password (the plaintext when it is hashed
in-memory with a fresh salt each start), so a credential change ends all
sessions. Each login carries a sid that renewals keep; logout records it in
<hermes home>/dashboard_auth/basic-revoked-sessions.json (pruned past the
refresh TTL), which every process sharing the secret re-reads on change.

Fixes #77186
2026-11-12 15:55:24 +01:00
calvinnwq
2d05b3a208 fix(dashboard): refuse a Portal token with no scope claim as a dashboard session
The Nous provider accepted a Portal token for this agent without a scope
claim as a dashboard sign-in, with a warning. Every dashboard grant and
every peer pass writes the claim, so such a token was minted for some
other purpose; it now opens neither a dashboard session nor any peer
permission. Two test fixtures that minted Nous tokens without the claim
now carry the dashboard scope the Portal writes.

Raised by kshitijk4poor in review.
2026-11-11 17:29:14 +05:30
calvinnwq
3dbdf86402 feat(dashboard): let a peer pass reach the agent's API through /api/peer
Another Hermes agent can now call this agent's API server through the
dashboard with a short-lived pass minted for this one agent, instead of
holding its API_SERVER_KEY.

- /api/peer/<path> and /api/peer/p/<profile>/<path> forward to the gateway
  api_server on loopback with the key that listener checks. The key never
  leaves the machine and nothing new listens on the network.
- Each path needs a permission the pass carries: agents:message for what
  `hermes peer` uses (health, capabilities, sessions and session chat, runs,
  run events, stop), agents:control (which includes messaging) for the rest
  of the user-facing API. Unlisted paths are never forwarded: cron fire,
  platform event intake, RoomLink grants, /health/detailed.
- Passes are checked through a new provider capability (supports_peer_pass /
  verify_peer_pass), kept apart from verify_token, so a pass never authorises
  another provider's token routes such as /api/gateway/drain.
- The Nous provider no longer opens a dashboard session for a token whose
  scope lacks agent_dashboard:access. It did not look at scope before, which
  was safe only while every token minted for an agent granted the dashboard.
  A token with no scope claim is still accepted, like the other contract
  claims.
- Control actions are written to the dashboard-auth audit log (peer_control)
  with the pass holder, and the api_server records the holder as
  peer_principal in a job's origin, so jobs outlive passes attributably.
- /p/<profile>/ reads as the api_server reads it: hermes is the default
  profile unless a profile has that name, and an unknown profile gets the
  api_server's own 404 body, which `hermes peer` recognises.
- X-Hermes-Session-Key (the api_server's memory scope) passes only with
  agents:control. The api_server's replay and partial-turn response headers
  come back.
- A gateway that is asleep answers 503 with Retry-After; a request it dropped
  after receiving it answers 502 with no retry hint, since it may have run.
  Neither counts toward the dashboard's own health.
- The cron-fire listener lookup is split out so the peer route resolves the
  same listener, with the key the gateway loads (a usable API_SERVER_KEY
  over the configured key).
2026-11-11 17:29:14 +05:30
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
kshitijk4poor
b0eb36ba90 fix(dashboard-auth): another instance's agent_instance_id is a 401, not 503
The Nous provider's agent_instance_id cross-check raised ProviderError, so
a well-signed Portal token naming another instance answered the same
"Auth provider 'nous' unreachable" 503 as the foreign-aud case fixed by the
salvaged verify_jwt commit. It is a token this instance does not accept:
raise InvalidCodeError (verify_session -> None -> 401).

Adds a gate-level regression against a real local Portal JWKS and the real
gated web_server app: the user's live shape (Portal CLI token,
aud=hermes-cli:hermes-cli), another instance's aud, another instance's
agent_instance_id, and an unknown kid all get 401; a valid token is 200 and
an unreachable JWKS stays 503. 4 of 6 cases fail on origin/main (503).

Maps paul@letscubo.com -> paulyang-fm for the salvaged #107305 commit.
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
unsupportedpastels
01888fc206 fix(webapp): the gated Webapp accepts the deployment session token
On the gateway's Webapp behind the sign-in gate, a provider token worked
on its own (bearer header, socket ?token=) only when this listener gave
it to a native app's sign-in. The deployment session token
(HERMES_DASHBOARD_SESSION_TOKEN, literal or file:<path>) that the bundled
session-token provider vouches for was therefore refused with 401 /
close 4401, although the docs promise it authorizes the gated listener.

The bearer, peek_session and socket ?token= checks now call
access_token_works_alone: token_works_alone (looked up at call time) or
the token the registered session-token provider read at startup,
compared in constant time by the provider's matches_token, which its
verify_session also uses. With the provider not registered
(dashboard.session_token_auth enabled: false) the token is refused as on
main. token_works_alone and the refresh route are unchanged from main:
the deployment token has no refresh.
2026-11-05 18:26:06 -05:00
ethernet
2edfd0d369 feat(auth): the deployment session token authorizes the gated dashboard
A token-only deployment (nix/agenix: backend.sessionTokenFile ->
HERMES_DASHBOARD_SESSION_TOKEN=file:<path>) had no way to satisfy the
June-2026 fail-closed gate: gated mode demands a registered
DashboardAuthProvider, the interactive prompt then writes basic-auth
credentials the deployment never asked for, and the provisioned token
itself is rejected on every gated leg (REST 401, /api/ws 403) — the
desktop's 'HTTP reachable but the WebSocket fails' incident.

The bundled session_token plugin closes that: it registers whenever the
session token is provisioned (skippable via
dashboard.session_token_auth.enabled: false) and verify_session
constant-time-compares the presented credential against it. Both legs a
token-mode client uses — the REST bearer path and the /api/ws ?token=
upgrade — run through that seam, so one provisioned token authorizes both.

It is deliberately not an interactive login: a new interactive_login
capability flag keeps it off the login page, /api/auth/providers, the
auto-SSO redirect and the native provider chooser (a token-gated /login
now renders a note explaining the credential channel), while
supports_session stays True so the gate's verify loops consult it.

Rotation semantics are pinned by tests: a saved client copy from before a
secret redeploy must fail closed, not half-work.
2026-10-28 13:49:47 -04:00
Teknium
2a8413a52e fix(webapp): self-hosted sign-in admits whom it admitted on main, each as the machine owner
Maintainer ruling: an owner restriction on self-hosted OIDC adds no real protection, because
anyone the login provider lets in already gets the agent and terminal as you on main. Remove the
first-sign-in owner pin (owner_pin.py, dashboard-auth/self-hosted-owner.json) and the
dashboard.oauth.self_hosted.owner check; the self-hosted provider is back to main's code. Who may
sign in is decided by the login provider's app configuration, and the docs now say so.

The hosted-room daemon test signs in two different IdP accounts again (as on main); both act as
the owner and share one Group Chat list.
2026-10-27 17:32:49 -07:00
Teknium
8497ce9318 fix(webapp): a signed-in Webapp tab is the machine owner, the same identity native Desktop uses
Hermes is single-user (maintainer ruling): sign-in only gates whether a browser may open the
Webapp, it never creates a second identity. Every login (Webapp tab, loopback session token,
a dashboard login forwarded by a standalone backend, the dashboard's PTY child) now acts as the
host owner's OS subject (uid:<n> / sid:<sid>), on both routes:

- gateway route: AuthorityConnection and the REST session-mutation context build the principal
  through gateway.owner_identity.principal_subject.
- tui_gateway route: rows a login creates over hermes serve carry the owner subject instead of a
  <provider>:<user> label, so native Desktop and the TUI resume them.

Stored login stamps from older builds read as the owner's (read-time, nothing rewritten or
deleted): auth:v1 room owners and history bindings, and <provider>:<user> labels of a bundled or
registered dashboard sign-in on routeless local rows. Messaging ids (telegram:42), other OS users
(uid:N) and nous: stamps on non-Desktop rows stay foreign.

Owner-only sign-in: basic auth has one account and the Nous Portal refuses other accounts for the
registered agent client; self-hosted OIDC admitted every IdP account, so it now admits one:
dashboard.oauth.self_hosted.owner, or the first account to sign in, pinned in
dashboard-auth/self-hosted-owner.json.
2026-10-27 17:32:49 -07:00
unsupportedpastels
074d150fab fix(dashboard-auth): print the ignored basic-auth secret notice once on stderr
The error for a signing secret holding shell text only reached agent.log and
errors.log, so an operator watching the console of hermes serve or hermes
dashboard saw nothing and was only signed out on every restart. Print one line
on stderr the first time such a secret is ignored in a process. The line names
the setting and the fix but never the configured value.
2026-10-27 16:37:10 -04:00
unsupportedpastels
0323a30052 fix(dashboard-auth): treat a pasted openssl rand command as an unset basic-auth secret
The basic provider already ignores a signing secret holding $( or a backtick.
A secret that is the command itself (openssl rand -base64 32), a spaced
"$ (...)", or the web-dashboard.md placeholder
"<32+ random bytes; openssl rand -base64 32>" pasted as-is was still used as
a fixed, known key. Also match "openssl rand": base64 and hex output never
contains a space, so no generated secret can match it.
2026-10-27 16:37:10 -04:00
unsupportedpastels
50e14f7dd8 docs(dashboard): generate the basic-auth signing secret in the remote recipes
The remote-backend recipes in desktop.md and web-dashboard.md wrote the
HERMES_DASHBOARD_BASIC_AUTH_SECRET line inside a quoted heredoc, so .env got the
literal text $(openssl rand -base64 32) instead of a random secret. Write the
credentials with the quoted heredoc and append the secret with a real command
substitution, and tell readers how to spot and replace the literal line.

The basic provider now ignores a signing secret that still contains unexpanded
shell text ($( or a backtick), logs an error, and uses a random per-process key,
so the literal string is never used to sign or verify sessions.
2026-10-27 16:37:10 -04:00
unsupportedpastels
9ed6c20651 fix(dashboard-auth): give every password-provider session its own tokens
The password provider signed only the user, kind and whole-second expiry,
so two sign-ins in the same second got the same token pair. On the
Webapp's listener a browser login's tokens work only as its cookies, but
when a native app signed in with the password provider in the same second
as a browser login, the record of the app's pair matched the login's
tokens too: they worked on their own as a bearer token and on the refresh
route, and kept working after hermes webapp --sign-out and a restart.
Each minted session now carries a random jti, so every login, sign-in and
renewal gets its own pair; tokens still verify as before. Native apps stay
signed in across a sign-out, as before.

Rebuilt from ac1d76b459921bb371d30227e2d6dfba8224ae71 (#145108), with the
Webapp test rewritten for the contract that native apps stay signed in.
2026-10-26 18:15:25 -04:00
emozilla
53e551c58f fix(webapp): a running gateway's Webapp signs in with Web Access's own Portal client
The previous change kept the Webapp's Portal client in the Nous sign-in plugin's module. Plugin
discovery imports that bundled plugin under a module name of its own
(hermes_plugins.dashboard_auth__nous), so the gateway's import of plugins.dashboard_auth.nous was
a copy discovery never ran. In a real gateway the Webapp kept signing in with
HERMES_DASHBOARD_OAUTH_CLIENT_ID, and on a home with only Web Access's client the Webapp found no
sign-in provider and fell back to the private listener. A live run of the gateway's own start
showed both; the earlier tests imported the plugin directly and passed.

The listener's client and the plugin's provider swap now live in
hermes_cli.dashboard_auth.listener_client, one module that the plugin, however it was imported,
and the gateway share. The plugin offers its swap when discovery runs it, so a plugin that
plugins.disabled keeps from loading still gives the Webapp no Nous sign-in. The tests load the
plugin the way discovery does.
2026-10-25 03:22:38 -07:00
emozilla
d740c0f757 fix(webapp): Web Access signs the Webapp in with a Nous Portal client of its own
Web Access registered the Webapp's sign-in callback on the standalone dashboard's Portal client
(HERMES_DASHBOARD_OAUTH_CLIENT_ID), saved that id in .env, and `hermes dashboard register` called
back into Web Access so it would register again. If the Portal replaces a client's redirect URI on
update, turning on Web Access broke Nous sign-in on an existing `hermes dashboard` deployment.

Start now registers a client of Web Access's own (named webapp_<adjective>_<noun>) and keeps its
id, its Portal and the callback in webapp/sign-in-registration.json under the gateway home, user
only. It never sends the dashboard's client id and never writes .env. A second Start with the same
callback asks the Portal nothing; a moved callback updates Web Access's client only. While the
gateway serves the Webapp, the Nous sign-in provider uses that client, and a plugin reload keeps
it. The gateway's private listener and the standalone dashboard keep reading
HERMES_DASHBOARD_OAUTH_CLIENT_ID as on main, and a Webapp whose Nous sign-in was set up by hand
keeps the configured client. A home whose record came from an earlier build of Web Access names
the dashboard's client; its next Start registers a client of its own and leaves the dashboard's
alone. `hermes dashboard register` no longer touches Web Access's record.

The desktop guide said Start saves the client id in .env; it now says where the id lives.
2026-10-25 03:22:38 -07:00
Teknium
408cc0d12e Merge origin/main (#32: 36 commits to cf23a1a5cc) into feat/unified-gateway-runtime
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); no other main commit touches a conflicted file. Resolution: the branch side
of each file plus main's exact autofix (ruff 0.15.10, main's ruff.strict.toml, --fix
--unsafe-fixes). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
2026-10-09 10:24:04 -07:00
Maciej Lisiewski
aff64c3eeb ci: UP007, UP022, UP028, UP031, UP041 linter fixes 2026-10-09 17:31:52 +02:00
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
a5bd246865 Old pre-decomposition import paths are gone: plugin compat layer removed on schedule (#126164)
* refactor(plugins): remove the Sep 2026 decomposition compat layer on schedule

The PLUGIN-COMPAT layer (2776813df3 + d63e380324 + 0a5164cebe) kept pre-#102117 import paths
alive for external plugins until 2026-09-14. That window closed two weeks ago; since then the loader
has already been skipping plugins that use the old paths. This removes the layer itself:

- 328 appended `PLUGIN-COMPAT` blocks (lazy `__getattr__` pointer tables, re-exported third-party
  names, restored dead definitions) and the three re-export stub modules
  (gateway/startup_watchdog, hermes_cli/observability/relay_runtime, tools/environments/modal_utils)
- COMPAT_MANIFEST.md, compat_manifest.json, scripts/check_compat_pointers.py and its lint step
- the reporting surfaces: CLI banner notice, `hermes plugins compat`, the `hermes doctor` section,
  the post-update notice, the Desktop one-time dialog, the loader's pre-import skip and the
  `plugins.allow_deprecated_imports` escape hatch

An external plugin that still imports an old path now fails to load with its ImportError as the
reason in `hermes plugins list`, the same path as any broken plugin.

hermes_cli/plugin_compat.py stays as three inert stubs (compat_report, removal_in_effect,
summary_lines): an already-running pre-removal `hermes update` lazy-imports them after the checkout
swap (tests/compat/old_updater_surface.json).

In-tree fallout, both already dead: hermes_cli/setup.py::_check_espeak_ng (no callers; its
`shutil` came from a compat block) and gateway/config.py::SessionResetPolicy ("retained solely for
the scheduled plugin-compat window"). Two test_run_agent patches targeted the removed
`run_agent.handle_function_call` pointer; they now patch `model_tools.handle_function_call`, the
seam production reads, like every sibling test in that file.

* chore: retrigger CI (zero-job startup_failure phantom)

* test: drop resolution allowlist rows for the two deleted which() sites

hermes_cli/setup.py::_check_espeak_ng (dead) and tools/skillevaluator_scan.py::scanner_available
(a restored definition inside a PLUGIN-COMPAT block) no longer exist; the stale-row gate requires
their allowlist entries go with them.
2026-09-28 10:21:41 -07:00
teknium1
eec5bd6673 Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
4,048 upstream commits (Sep 16-23) composed onto the unified gateway runtime by six
per-domain conflict lanes (gateway, desktop/shared, cli/state, cron, bots/tui_gateway, ink).
Retired lanes stay retired (Desktop secondary pool + exit supervisor, deferred Bot Chat
pending queue, subprocess retry adoption); main's gateway.standalone, host-role claim,
clarify capability gate, config-read caches and idle gates ride on top.
2026-09-23 03:25:31 -07:00
beardthelion
07c1953ea1 fix(dashboard-auth): pin OIDC discovery to the configured issuer origin
_fetch_discovery followed redirects but only pinned the document's
self-asserted issuer field, so one cleartext or attacker-hosted hop
could serve a forged document claiming the configured issuer with
attacker jwks_uri and token_endpoint. Verify then accepted
attacker-signed ID tokens and the code exchange POSTed the client
secret to the attacker's token endpoint.

The resolved response.url must now share the configured issuer's
origin (scheme, host, port with default-port normalisation) before
the body is parsed. Same-origin canonicalisation redirects still
pass, and the issuer-field pin remains as the misconfig check it is.
2026-09-20 00:09:52 -07: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
d63e380324 compat(plugins): warn once per name when a plugin resolves an old import path; lint step restored in CI
Every PLUGIN-COMPAT __getattr__ now calls hermes_cli.plugin_compat.warn_once(facade, name, target) before
resolving, emitting a HermesPluginCompatWarning (FutureWarning) once per process per name: old path, new
path, removal target. Importing a facade for its live API stays silent; only resolving a moved name warns.
COMPAT_MANIFEST.md documents the warning and how to silence it during migration.

Verified the runtime never routes through a pointer: every entry point (run_agent, cli, hermes_cli.main,
gateway.run, tui_gateway.server, web_server, model_tools + tool discovery, hermes_state, cron.scheduler,
browser_tool, mcp_tool, kanban, auth) imports clean and `hermes doctor` runs end to end with the warning
promoted to an error.

Also restores the check_compat_pointers CI step to .github/workflows/lint.yml, which a0be177aac dropped
when the compat layer was regenerated (the lint script itself was present; the workflow step was not).

hermes_cli/plugin_compat.py, tests/test_plugin_compat_warning.py and the two-line insert per facade are
part of the compat layer and go away with it.
2026-09-04 00:15:16 -07:00
Teknium
2776813df3 compat(plugins): temporary import-path shims for external plugins — ONE commit, revert on schedule
The Sep 2026 decomposition (PR #102117) makes internal import paths a non-API: names now live in
the focused modules that define them. This commit is the ONLY thing keeping the old paths alive,
so external plugins have time to update. It is deliberately a single, unsquashed commit:

    git revert <this sha>

removes every shim, stub and manifest at once on the announced date. Nothing in-tree may depend on
these pointers: scripts/check_compat_pointers.py (wired into lint.yml) fails CI if it does.

What it adds (see COMPAT_MANIFEST.md, compat_manifest.json):
- 332 facade modules get one delimited `PLUGIN-COMPAT` block appended at the end of the file
- 1,172 moved names resolved lazily via a module `__getattr__` (PEP 562) — never a top-level import,
  so no import cycles; facades that already had `__getattr__` get a chained one
- 592 third-party/stdlib names the old modules used to expose, with their original import statements
- 266 public definitions that had been deleted as unused, restored byte-for-byte from the pre-decomposition
  tree (+40 private helpers and 16 imports pulled in only because a restored definition needs them)
- 3 deleted modules recreated as re-export stubs (gateway/startup_watchdog, hermes_cli/observability/
  relay_runtime, tools/environments/modal_utils)
- private names (`_x`) get no pointer: they were never API (3,792 skipped)

Verified: all 335 touched modules import under a fresh HERMES_HOME and every manifest name resolves;
the lint reports zero in-tree uses; ruff clean; targeted suites unchanged.
2026-09-03 17:13:22 -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
Teknium
2f44998353 fix(dashboard-auth): a non-JWT bearer is "not my token", not "provider unreachable" (#94558)
NousDashboardAuthProvider._verify_jwt (and the identical hunk in the
self-hosted OIDC provider) folded EVERY PyJWKClient failure into
ProviderError, which the gate translates to HTTP 503
{"detail":"Auth provider 'nous' unreachable"}. That branch fires for
jwt.DecodeError('Not enough segments') — i.e. the bearer is not a JWT at all
(an opaque peer key, a legacy token, garbage) — and for PyJWKSetError (JWKS
fetched fine, foreign kid). Neither involves reaching Portal, which is why
the hosted sjc agents in #94558 returned a fast, well-formed 503 that
survived token re-mint and instance restart while Portal was healthy.

Add one shared classifier, hermes_cli.dashboard_auth.classify_jwks_lookup_error:
only PyJWKClientConnectionError (transport) and an unexpected bare
PyJWKClientError stay ProviderError; DecodeError / PyJWKSetError /
InvalidTokenError become InvalidCodeError so verify_session() returns None
and the middleware proceeds to the next provider / refresh / 401 exactly as
the protocol documents. Both providers now use it.

Live repro (real NousDashboardAuthProvider against a local reachable JWKS
server; and the real gated web_server app): before — opaque bearer ->
ProviderError "JWKS lookup failed: DecodeError('Not enough segments')" ->
503 unreachable; after — verify_session() -> None, gated GET /api/auth/me
with the opaque bearer -> 401; a real JWT against an unreachable JWKS still
-> ProviderError (503).

This does not add /api/v1/message to the public-path allowlist (#94579):
that route has no verifier in this repo, so bypassing the gate would leave a
state-changing ingress fail-open. The correct fix is classification, which
also covers every other opaque-bearer surface.

Refs #94558
2026-09-02 01:15:58 -07:00
James Hodgkinson
eaa9582e38 fix(dashboard): set headers for Nous JWKS requests
The Nous PyJWKClient was constructed without explicit headers, while the
self_hosted provider already sends Accept + User-Agent. Without them the
Portal WAF can block the JWKS fetch, so the same failure mode remained for
the Nous dashboard-auth route. Mirror the self_hosted fix and add a
constructor-contract regression test.
2026-07-31 10:17:30 -04:00
James Hodgkinson
83cee29ff7 fix(dashboard): set headers for JWKS requests 2026-07-31 10:17:30 -04:00
Ben Barclay
53a75f147f feat(dashboard_auth): support confidential clients (client_secret) in self-hosted OIDC (#55344)
The self-hosted OIDC dashboard provider was public-client + PKCE only, with
two `# TODO(confidential-client)` seams. Authentik and Keycloak commonly
default a new OIDC client to *confidential*, whose token endpoint rejects an
unauthenticated exchange (`invalid_client`) — so a self-hoster who accepts
their IDP's default could not complete dashboard login without manually
flipping the client to public.

Add optional confidential-client support:

- New optional `client_secret` (env `HERMES_DASHBOARD_OIDC_CLIENT_SECRET`,
  or `dashboard.oauth.self_hosted.client_secret`; env-wins-config, empty
  treated as unset). It is a credential, so docs steer operators to the
  `.env` file; config.yaml is supported only for precedence symmetry.
- `_token_endpoint_auth()` selects `client_secret_basic` (HTTP Basic header)
  vs `client_secret_post` (form body) from the IDP's advertised
  `token_endpoint_auth_methods_supported`, defaulting to basic (the OIDC
  default) when absent. Applied to complete_login, refresh_session, and
  revoke_session (RFC 7009 §2.1).
- PKCE is sent in BOTH modes — the secret is client authentication layered
  on top, never a replacement (OAuth 2.1 / RFC 9700 keep PKCE mandatory).
- Basic header url-encodes client_id/secret before base64 per RFC 6749
  §2.3.1, so reserved chars (`:`, `@`, space) round-trip correctly.

Non-breaking: with no secret configured the provider is a pure public PKCE
client, byte-identical to prior behaviour (no Authorization header, no
client_secret in the body). The secret is never logged — register() reports
only a `confidential=<bool>` flag.

Tests: 16 new cases covering basic/post selection, default-when-absent,
public-unchanged contract, PKCE-preserved, reserved-char url-encoding,
blank-secret-is-public, refresh + revoke auth, no-secret-in-logs, and
env/config register wiring. Full dashboard-auth suite (nous provider,
middleware, gate, cookies, WS, 401-reauth, status endpoint) — 396 tests —
green, proving no existing auth path regressed.
2026-06-30 13:32:51 +10:00
Joey Kerper
f3d2dfbec6 fix(dashboard_auth): allow any http:// host in self-hosted OIDC redirect_uri (#55099)
The self-hosted OIDC dashboard login rejected any http:// redirect_uri
whose host was not localhost/127.0.0.1, surfacing "redirect_uri may only use http:// for localhost/127.0.0.1" before reaching the IDP. This broke self-hosted dashboards reached over plain HTTP (including LAN IPs, internal hostnames, and reverse proxies that terminate TLS upstream).

#38827 already dropped this check from the nous provider, but the generic self-hosted provider  copied the old localhost-only
branch and reintroduced the bug for HERMES_DASHBOARD_OIDC_ISSUER setups.

The IDP's own allowlist is authoritative on which redirect_uris are
permitted; this client-side _validate_redirect_uri is only a fast-fail for
obvious operator error and should not second-guess valid http:// deployments.

Fix: drop the localhost-only branch on the http scheme. Validation now enforces only that the scheme is http(s) and the path ends with
/auth/callback. Updated the docstring to explain the relaxed contract,
and added test_allows_http_with_arbitrary_host covering an internal
hostname and a LAN IP alongside the existing localhost case.
2026-06-30 09:45:11 +10:00
Ben Barclay
fbf748b282 fix(dashboard-auth): follow redirects on self-hosted OIDC discovery (#53399)
The self-hosted OIDC provider fetched the discovery document with a bare
httpx.get(). httpx defaults to follow_redirects=False (unlike curl -L or
the requests library), so when an IDP answers GET
/.well-known/openid-configuration with a 3xx — Authentik canonicalises the
.well-known path, and any IDP behind a reverse proxy doing an http→https
upgrade redirects too — the bare redirect (empty body) tripped the
status != 200 guard and raised 'OIDC discovery returned 302', which
routes.py maps to the provider_unreachable audit event and a 503. The
browser surfaced 'Auth provider self-hosted unreachable'.

The user's smoking gun (curl -o writing zero bytes from inside the
container) is exactly a redirect with no body — the same wall the code hit.

Add follow_redirects=True to the discovery GET only. It's safe: the
issuer-pin check and _require_https_or_loopback still validate the resolved
document and every endpoint, so a redirect can't smuggle in a bad issuer or
a cleartext endpoint. The token/revocation POSTs deliberately keep the
no-follow default (they carry an auth code / refresh token and the endpoint
is already the canonical absolute URL).

Existing discovery tests mocked httpx.get with a canned 200 and never
exercised a real 3xx. Add a regression test that runs a real loopback
server returning a 302 on the .well-known path — fails without the fix
(ProviderError: discovery returned 302), passes with it.
2026-06-27 14:14:51 +10:00
Nacho Avecilla
dbe734beff fix(dashboard-auth): exclude non-interactive providers from interactive login surfaces (#53239)
* Return None instead of erroring on drain login failure

* Fix login on drain

* Remove login for drained endpoints flow and clean the code

* chore: drop unrelated credits changes from this PR

* Remove extra comments that were not really necessary
2026-06-27 10:08:13 +10:00
Ben
2e322466b1 feat(dashboard-auth): drain shared-bearer-secret provider plugin
Task 2.0b: the concrete shared-bearer-secret auth provider, the FIRST consumer
of the generic token-auth capability (Task 2.0a). Implements decisions.md Q-A.

plugins/dashboard_auth/drain/ (bundled, discovered like dashboard_auth/basic):
- DrainSecretProvider: non-interactive provider, supports_token=True. Verifies
  an inbound Authorization bearer token against a per-agent shared secret with
  hmac.compare_digest (constant-time, no timing oracle) and, on a match,
  vouches for the caller as the "drain-control" principal scoped to "drain".
  The five interactive ABC methods raise NotImplementedError; verify_session
  returns None (stacks harmlessly in the cookie-verify loop).
- assess_secret_strength(): fail-closed entropy gate. Rejects secrets shorter
  than 43 url-safe-b64 chars (~256 bits), with < 16 distinct characters, or
  below 128 bits Shannon entropy — so a weak/structured/repeated secret can
  never be silently accepted. Enforced both at register() (friendly skip
  reason) and in __init__ (raises — defence in depth).
- register(ctx): no-op + skip reason when HERMES_DASHBOARD_DRAIN_SECRET is
  unset; rejects a weak secret fail-closed (drain endpoint stays gated). On a
  strong secret, registers the provider AND opts /api/gateway/drain into the
  generic token-auth seam via register_token_route().

Config: the secret is a CREDENTIAL → carried via HERMES_DASHBOARD_DRAIN_SECRET
(per-agent, provisioned by NAS at deploy). Behavioural knobs only
(dashboard.drain_auth.{scope,min_secret_chars}) live in config.yaml — added to
DEFAULT_CONFIG with the .env-is-for-secrets rationale documented inline.

Tests: tests/plugins/dashboard_auth/test_drain_provider.py — entropy gate
(strong pass; empty/short/repeated/few-distinct/custom-min reject), verify_token
(match → scoped principal, wrong/empty → None, custom scope), protocol
compliance, interactive-methods-raise, and register() (skip-no-secret,
fail-closed-weak-secret, strong-env-secret registers + route opt-in, config
scope + min_secret_chars). 21 new tests; drain + token-auth suites 44 passed.
Verified the plugin is discovered as dashboard_auth/drain alongside basic/nous.

Intentionally deferred:
- The begin/cancel-drain endpoint handler itself — Task 2.1.
- The dashboard→gateway control channel — Task 2.2.

Build status: dashboard-auth + drain-plugin suites green.
2026-06-26 00:47:19 -07:00