The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): self-hosted sign-in admits whom it admitted on main, each as the machine owner
Teknium2a8413a52ef8
diff --git a/plugins/dashboard_auth/self_hosted/__init__.py b/plugins/dashboard_auth/self_hosted/__init__.pyindex 8cd4fbe79ca..f65a24ec348 100644--- a/plugins/dashboard_auth/self_hosted/__init__.py+++ b/plugins/dashboard_auth/self_hosted/__init__.py@@ -21,7 +21,7 @@ from typing import Any, Dict, Optionalimport httpx-from hermes_cli.dashboard_auth import InvalidCodeError, LoginStart, ProviderError, Session+from hermes_cli.dashboard_auth import LoginStart, ProviderError, Sessionfrom plugins.dashboard_auth._shared import (DEFAULT_TOKEN_LEEWAY_SECONDS,JSON_HEADERS,@@ -89,7 +89,7 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):def __init__(self, *, issuer: str, client_id: str, scopes: str = _DEFAULT_SCOPES, client_secret: str = "",- id_token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS, owner: str = "",+ id_token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS,) -> None:if not issuer:raise ValueError("issuer is required")@@ -107,7 +107,6 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):# Empty/whitespace secret ⇒ public client, so a provisioned-but-blank secret# can't flip us into a broken confidential mode.self._client_secret = (client_secret or "").strip()- self._owner = (owner or "").strip()# Discovery + JWKS resolve lazily so registration never hits the network# (the IDP may be down at boot; fail per-request instead).self._discovery: dict[str, Any] | None = None@@ -184,12 +183,7 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):"OIDC token response missing id_token — ensure the 'openid' ""scope is configured and the client is allowed to receive an ""ID token."))- try:- claims = self._owner_claims(id_token)- except InvalidCodeError as exc:- if bad_request_exc is InvalidCodeError:- raise- raise bad_request_exc(str(exc)) from exc # a refresh for another account just ends+ claims = self._verify_id_token(id_token)# Prefer a freshly-issued RT, else keep the previous (some IDPs don't rotate).return self._session(id_token, refresh_token_from(payload, previous_refresh_token), claims)@@ -273,17 +267,7 @@ class SelfHostedOIDCProvider(JwtOAuthProvider):id_token, self._get_jwks_client(), algorithms=list(_ALLOWED_ID_TOKEN_ALGS),audience=self._client_id, issuer=issuer, label="ID token", leeway=self._id_token_leeway)- def _owner_claims(self, id_token: str) -> dict[str, Any]:- """Verified claims of the machine owner's IdP account only. Hermes is single-user: a signed-in- Webapp tab acts as the owner (gateway.owner_identity), so any other account of the same IdP- must not sign in at all. ``dashboard.oauth.self_hosted.owner`` names the owner's ``sub``;- unset, the first account that signs in is pinned as the owner (``owner_pin``)."""- claims = self._verify_id_token(id_token)- from plugins.dashboard_auth.self_hosted.owner_pin import require_owner- require_owner(self._issuer, str(claims.get("sub", "")), self._owner)- return claims-- _claims_for = _owner_claims+ _claims_for = _verify_id_tokendef _session(self, id_token: str, refresh_token: str, claims: dict[str, Any]) -> Session:"""Map verified OIDC claims onto a Session. The verified ID token is stored in@@ -330,9 +314,7 @@ def _settings() -> dict:# Credential: canonical home is the env var / ~/.hermes/.env. Empty ⇒ public client."client_secret": setting("HERMES_DASHBOARD_OIDC_CLIENT_SECRET", "client_secret"),# Clock-skew tolerance for ID-token exp/nbf/iat (config.yaml only; default 60s, 0 = strict).- "id_token_leeway": parse_leeway(oidc_cfg.get("id_token_leeway")),- # The owner's ``sub`` (config.yaml only): the one IdP account that may sign in.- "owner": str(oidc_cfg.get("owner") or "")}+ "id_token_leeway": parse_leeway(oidc_cfg.get("id_token_leeway"))}def register(ctx) -> None:diff --git a/plugins/dashboard_auth/self_hosted/owner_pin.py b/plugins/dashboard_auth/self_hosted/owner_pin.pydeleted file mode 100644index 915ed33c14f..00000000000--- a/plugins/dashboard_auth/self_hosted/owner_pin.py+++ /dev/null@@ -1,50 +0,0 @@-"""Self-hosted OIDC sign-in is owner-only: one IdP account, the machine owner's.--Hermes is single-user, and a signed-in Webapp tab acts as the machine owner (gateway.owner_identity).-An OIDC provider can hold many accounts, so the sign-in admits exactly one: the ``sub`` named by-``dashboard.oauth.self_hosted.owner``, or, when that is unset, the first account that signs in, whose-``[issuer, sub]`` is pinned in ``dashboard-auth/self-hosted-owner.json`` under the Hermes root home.-Any other account is refused like an invalid token (the callback reports a failed sign-in).-"""-from __future__ import annotations--import json-import logging-import os-import threading--from hermes_cli.dashboard_auth import InvalidCodeError--logger = logging.getLogger(__name__)-_lock = threading.Lock()---def _pin_path():- from hermes_constants import get_process_hermes_home- return get_process_hermes_home() / "dashboard-auth" / "self-hosted-owner.json"---def require_owner(issuer: str, sub: str, configured: str) -> None:- """Raise :class:`InvalidCodeError` unless *sub* is the owner's account."""- if not sub:- raise InvalidCodeError("ID token names no account")- if configured:- if sub != configured:- raise InvalidCodeError("this account is not the owner of this Hermes")- return- path = _pin_path()- with _lock:- try:- pinned = json.loads(path.read_text(encoding="utf-8-sig"))- except FileNotFoundError:- pinned = None- if pinned is None:- path.parent.mkdir(parents=True, exist_ok=True)- fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)- with os.fdopen(fd, "w", encoding="utf-8") as handle:- json.dump([issuer, sub], handle)- logger.warning("dashboard-auth-self-hosted: pinned the first account to sign in as this Hermes's "- "owner (%s); set dashboard.oauth.self_hosted.owner to choose it", path)- return- if pinned != [issuer, sub]:- raise InvalidCodeError("this account is not the owner of this Hermes")diff --git a/tests/gateway/fixtures/hosted_auth_probe.py b/tests/gateway/fixtures/hosted_auth_probe.pyindex 0336fda4448..0bf18771ff6 100644--- a/tests/gateway/fixtures/hosted_auth_probe.py+++ b/tests/gateway/fixtures/hosted_auth_probe.py@@ -1,7 +1,8 @@"""Loopback OIDC/model boundaries; daemon, auth, tickets and room controls are real.-Hermes is single-user: every signed-in Webapp tab is the machine owner, so two tabs share one-Group Chat list and either may stop or approve, while a second IdP account cannot sign in at all.+Hermes is single-user: every signed-in Webapp tab is the machine owner, whichever IdP account it+signed in with, so two tabs share one Group Chat list and either may stop or approve. Who may sign in+is the login provider's app configuration, not Hermes's."""import asyncioimport base64@@ -24,7 +25,7 @@ from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpcfrom tests.waiting import async_wait_until-#: Two signed-in Webapp tabs of the same owner account (Hermes is single-user).+#: Two signed-in Webapp tabs, each acting as the machine owner (Hermes is single-user).TABS = ('tab1', 'tab2')@@ -53,7 +54,7 @@ class OIDC(BaseHTTPRequestHandler):params = {k: v[0] for k, v in parse_qs(url.query).items()}assert params['client_id'] == 'room-fixture'assert params['code_challenge_method'] == 'S256'- assert params['subject'] in ('alice', 'mallory')+ assert params['subject'] in ('alice', 'bob')code = secrets.token_urlsafe(24)self.server.codes[code] = paramsself.send_response(302)@@ -120,7 +121,7 @@ class Model(BaseHTTPRequestHandler):pass-def callback(client, issuer, actor):+def login(client, issuer, actor):response = client.get('/auth/login', params={'provider': 'self-hosted'})assert response.status_code == 302, response.textauthorize = response.headers['location']@@ -129,11 +130,7 @@ def callback(client, issuer, actor):assert response.status_code == 302, response.text# public_url enables the gate; route its callback to the owned loopback listener.redirect = urlsplit(response.headers['location'])- return client.get(redirect.path + '?' + redirect.query)---def login(client, issuer, actor):- response = callback(client, issuer, actor)+ response = client.get(redirect.path + '?' + redirect.query)assert response.status_code == 302, response.textidentity = client.get('/api/auth/me')assert identity.status_code == 200, identity.text@@ -276,11 +273,9 @@ def probe(tmp_path):for credential in ('', 'Bearer invalid'):rejected = clients[0].post('/api/auth/ws-ticket', headers={'Authorization': credential})assert rejected.status_code == 401, rejected.text- tickets = [login(clients[0], oidc.issuer, 'alice')]- # Owner-only sign-in: another account of the same IdP is refused, not a second owner.- refused = callback(clients[1], oidc.issuer, 'mallory')- assert refused.status_code != 302 and 'not the owner' in refused.text, refused.text- tickets.append(login(clients[1], oidc.issuer, 'alice'))+ # A second IdP account is admitted like on main and acts as the same machine owner.+ tickets = [login(client, oidc.issuer, actor)+ for client, actor in zip(clients, ('alice', 'bob'))]return asyncio.run(exercise(desc, tickets))finally:model.release.set()diff --git a/tests/gateway/test_hosted_room_auth_daemon.py b/tests/gateway/test_hosted_room_auth_daemon.pyindex a2c6b5aa52d..e7ebeaec43e 100644--- a/tests/gateway/test_hosted_room_auth_daemon.py+++ b/tests/gateway/test_hosted_room_auth_daemon.py@@ -4,8 +4,8 @@ from tests.gateway.fixtures.hosted_auth_probe import probedef test_every_signed_in_tab_shares_the_owners_hosted_rooms(tmp_path):receipt = probe(tmp_path)- # The second account's token exchange happened, then its sign-in was refused.- assert receipt['actors'] == ['alice', 'mallory', 'alice']+ # Two different IdP accounts signed in; both act as the owner and share one room list.+ assert receipt['actors'] == ['alice', 'bob']assert receipt['rooms'] == ['tab1-room', 'tab2-room']assert receipt['shared_views'] == 4assert receipt['owner_stops'] == 2diff --git a/tests/plugins/dashboard_auth/test_self_hosted_owner_only.py b/tests/plugins/dashboard_auth/test_self_hosted_owner_only.pydeleted file mode 100644index cc9575b080e..00000000000--- a/tests/plugins/dashboard_auth/test_self_hosted_owner_only.py+++ /dev/null@@ -1,27 +0,0 @@-"""Self-hosted OIDC sign-in admits one account, the machine owner's (the Webapp is single-user)."""-import pytest--from hermes_cli.dashboard_auth import InvalidCodeError-from plugins.dashboard_auth.self_hosted import owner_pin---def pin_file(tmp_path, monkeypatch):- path = tmp_path / "dashboard-auth" / "self-hosted-owner.json"- monkeypatch.setattr(owner_pin, "_pin_path", lambda: path)- return path---def test_the_configured_owner_is_the_only_account_that_signs_in(pin_file):- owner_pin.require_owner("https://idp", "owner-sub", "owner-sub")- with pytest.raises(InvalidCodeError):- owner_pin.require_owner("https://idp", "colleague-sub", "owner-sub")- assert not pin_file.exists()---def test_unconfigured_the_first_account_is_pinned_and_no_other_signs_in(pin_file):- owner_pin.require_owner("https://idp", "first-sub", "")- owner_pin.require_owner("https://idp", "first-sub", "")- for issuer, sub in (("https://idp", "second-sub"), ("https://other-idp", "first-sub")):- with pytest.raises(InvalidCodeError):- owner_pin.require_owner(issuer, sub, "")diff --git a/website/docs/user-guide/features/web-dashboard.md b/website/docs/user-guide/features/web-dashboard.mdindex db8f8ce1869..b181aee88c1 100644--- a/website/docs/user-guide/features/web-dashboard.md+++ b/website/docs/user-guide/features/web-dashboard.md@@ -883,7 +883,6 @@ dashboard:client_id: hermes-dashboard # requiredscopes: "openid profile email" # optional (this is the default)id_token_leeway: 60 # optional; seconds of clock-skew tolerance- owner: "<your sub claim>" # optional; the one account that may sign in```**Environment variables** — operator overrides (env wins over `config.yaml` when set non-empty; an empty value is treated as unset):@@ -898,7 +897,7 @@ In your IDP, register a **public** application/client with the authorization-cod#### What it verifies-Hermes is single-user, so this sign-in admits exactly one IdP account: the machine owner's. Name it with `dashboard.oauth.self_hosted.owner` (the account's `sub` claim). Unset, the first account that signs in is pinned as the owner in `dashboard-auth/self-hosted-owner.json` under your Hermes home (delete that file to choose again), and every other account of the IdP gets a failed sign-in. A signed-in browser acts as you on this machine: it sees and resumes the same chats and Group Chats as native Desktop.+Every account that can sign in acts as you, the machine owner. With a self-hosted login provider, restrict the app to your own account in the provider (for example Okta app assignment, Microsoft Entra "Assignment required", or a Google Workspace app limited to you); otherwise anyone your provider admits gets full access, as before.The provider verifies the OpenID Connect **ID token** (RS256/ES256) against the discovered `jwks_uri`, with the `iss` and `aud` claims pinned to your configured `issuer` and `client_id`. The time claims (`exp`/`nbf`/`iat`) are verified with a 60-second clock-skew leeway (RFC 7519 §4.1.4-4.1.6), so a dashboard host whose clock lags the IDP's doesn't fail login; tune it with `dashboard.oauth.self_hosted.id_token_leeway` in `config.yaml` (any value below `60` tightens it, `0` restores strict verification, and an invalid value fails closed to `0`). Standard OIDC claims map onto the dashboard session: