The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: isolate authenticated gateway owners by provider and issuer
Teknium6b8a6d4c3581
diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex d4422f8c2d9..5b40cafae9f 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -20,7 +20,8 @@ class AuthorityConnection:if (not identity.get('user_id')or identity.get('instance_id', authority.instance_id) != authority.instance_id):capabilities = frozenset()- self.actor = Principal(str(identity.get('user_id') or 'unbound'),+ from gateway.session_identity import authenticated_subject+ self.actor = Principal(authenticated_subject(identity),identity.get('profile_id', authority.profile_id),capabilities, uuid.uuid4().hex)self.subscriptions = {}diff --git a/gateway/session_identity.py b/gateway/session_identity.pynew file mode 100644index 00000000000..3a0d30622d1--- /dev/null+++ b/gateway/session_identity.py@@ -0,0 +1,18 @@+"""Stable owner keys from server-authenticated identity, never RPC parameters."""+import json+++def authenticated_subject(identity):+ """Keep private native receipts stable; namespace every dashboard identity.++ Only the private bootstrap stamps profile/instance/capabilities. A dashboard+ provider named 'local' (or a subject resembling a UID) is not native provenance.+ Historical remote bare-subject receipts cannot be assigned to a first caller.+ """+ subject = str(identity.get('user_id') or 'unbound')+ if (identity.get('provider') == 'local' and identity.get('profile_id')+ and identity.get('instance_id') and 'capabilities' in identity):+ return subject+ return 'auth:v1:' + json.dumps(+ [identity.get('provider') or '', identity.get('issuer') or '', subject],+ separators=(',', ':'), ensure_ascii=True)diff --git a/hermes_cli/dashboard_auth/base.py b/hermes_cli/dashboard_auth/base.pyindex 681d555d331..c7e60b03590 100644--- a/hermes_cli/dashboard_auth/base.py+++ b/hermes_cli/dashboard_auth/base.py@@ -18,6 +18,7 @@ class Session:expires_at: int # unix seconds; the access_token's exp claimaccess_token: strrefresh_token: str+ issuer: str = "" # Verified issuer; empty for non-federated providers.@dataclass(frozen=True)diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.pyindex 553938f9ec8..403022a5f15 100644--- a/hermes_cli/dashboard_auth/routes.py+++ b/hermes_cli/dashboard_auth/routes.py@@ -459,7 +459,7 @@ async def api_auth_ws_ticket(request: Request):``Authorization`` on the upgrade); one ticket per WS."""sess = _require_session(request)from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDS, mint_ticket- ticket = mint_ticket(user_id=sess.user_id, provider=sess.provider)+ ticket = mint_ticket(user_id=sess.user_id, provider=sess.provider, issuer=sess.issuer)_audit(request, AuditEvent.WS_TICKET_MINTED, provider=sess.provider, user_id=sess.user_id)return {"ticket": ticket, "ttl_seconds": TTL_SECONDS}diff --git a/hermes_cli/dashboard_auth/ws_tickets.py b/hermes_cli/dashboard_auth/ws_tickets.pyindex aef1456b84e..313d3e76933 100644--- a/hermes_cli/dashboard_auth/ws_tickets.py+++ b/hermes_cli/dashboard_auth/ws_tickets.py@@ -33,11 +33,13 @@ class TicketInvalid(Exception):"""Ticket missing, expired, or already consumed."""-def mint_ticket(*, user_id: str, provider: str) -> str:+def mint_ticket(*, user_id: str, provider: str, issuer: str = "") -> str:"""One-shot base64url ticket (32 random bytes) bound to this identity; ``consume_ticket``hands the ``info`` dict back to the WS handler."""ticket = secrets.token_urlsafe(32)info = {"user_id": user_id, "provider": provider, "minted_at": int(time.time())}+ if issuer:+ info["issuer"] = issuerwith _lock:_tickets[ticket] = (int(time.time()) + TTL_SECONDS, info)_gc_expired_locked()diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex 047bc867afb..999165c259c 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -248,10 +248,12 @@ def _ws_auth_reason(ws: "WebSocket") -> tuple[Optional[str], str]:# Server-minted {user_id, provider} stamped onto the WS object is the# sole identity authority downstream (gateway transport / controller# registration); a client can never supply it through RPC params.- # Only the two identity fields are carried — bookkeeping such as+ # Only identity fields are carried — bookkeeping such as# ``minted_at`` is not part of the identity contract.ws._hermes_auth_identity = {"user_id": info.get("user_id"), "provider": info.get("provider")}+ if info.get("issuer"):+ ws._hermes_auth_identity["issuer"] = info["issuer"]internal = ws.query_params.get("internal", "")if internal:diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.pyindex 41e729cc32a..694b978a1f9 100644--- a/hermes_cli/web_server_sessions.py+++ b/hermes_cli/web_server_sessions.py@@ -79,7 +79,9 @@ def _session_mutation_context(request, profile):if native is not None:subject = native['subject']elif session is not None:- subject = session.user_id+ from gateway.session_identity import authenticated_subject+ subject = authenticated_subject({"user_id": session.user_id,+ "provider": session.provider, "issuer": session.issuer})elif not getattr(request.app.state, 'auth_required', False) and _has_valid_session_token(request):subject = 'dashboard-token'else:diff --git a/plugins/dashboard_auth/_shared.py b/plugins/dashboard_auth/_shared.pyindex 7d2e6859799..0c80431a9db 100644--- a/plugins/dashboard_auth/_shared.py+++ b/plugins/dashboard_auth/_shared.py@@ -174,7 +174,8 @@ def session_from_claims(raise ProviderError(f"{label} missing 'sub' (user_id) claim")return Session(user_id=user_id, email=email, display_name=display_name, org_id=org_id, provider=provider,- expires_at=int(claims["exp"]), access_token=access_token, refresh_token=refresh_token)+ expires_at=int(claims["exp"]), access_token=access_token, refresh_token=refresh_token,+ issuer=str(claims.get("iss") or ""))# ---- JWT verification ----diff --git a/tests/gateway/test_authenticated_session_identity.py b/tests/gateway/test_authenticated_session_identity.pynew file mode 100644index 00000000000..2f22eddd058--- /dev/null+++ b/tests/gateway/test_authenticated_session_identity.py@@ -0,0 +1,164 @@+"""Verified dashboard identities must own separate durable authority receipts."""+import json+import threading+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from types import SimpleNamespace++import jwt+import pytest+from cryptography.hazmat.primitives.asymmetric import rsa+from starlette.requests import Request+from starlette.websockets import WebSocket+++def oidc():+ from plugins.dashboard_auth.self_hosted import SelfHostedOIDCProvider+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(key.public_key()))+ jwk.update(kid='test-key', use='sig', alg='RS256')++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ realm = self.path.removesuffix('/.well-known/openid-configuration')+ body = {'keys': [jwk]} if self.path.endswith('/jwks') else {+ 'issuer': issuer + realm, 'jwks_uri': issuer + '/jwks',+ 'authorization_endpoint': issuer + '/authorize', 'token_endpoint': issuer + '/token'}+ raw = json.dumps(body).encode()+ self.send_response(200)+ self.send_header('Content-Type', 'application/json')+ self.send_header('Content-Length', str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)++ server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)+ issuer = f'http://127.0.0.1:{server.server_port}'+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ def login(subject, realm=''):+ provider = SelfHostedOIDCProvider(issuer=issuer + realm, client_id='fixture-client')+ token = jwt.encode({'iss': issuer + realm, 'sub': subject, 'aud': 'fixture-client',+ 'iat': int(time.time()), 'exp': int(time.time()) + 600}, key, algorithm='RS256',+ headers={'kid': 'test-key'})+ return provider.verify_session(access_token=token)++ try:+ yield login+ finally:+ server.shutdown()+ server.server_close()+ thread.join(5)+++def connection(authority, session, monkeypatch):+ from hermes_cli import web_server as web+ from hermes_cli.dashboard_auth.routes import api_auth_ws_ticket+ from hermes_cli.web_server_chat import _ws_auth_reason+ from gateway.session_controls import AuthorityConnection+ # Exercise the production ticket endpoint and upgrade stamp, not a made-up Principal.+ monkeypatch.setattr(web.app.state, 'auth_required', True, raising=False)+ request = Request({'type': 'http', 'app': web.app, 'state': {'session': session},+ 'headers': [], 'method': 'POST', 'path': '/api/auth/ws-ticket'})+ return request, api_auth_ws_ticket, _ws_auth_reason, AuthorityConnection, WebSocket+++async def test_bundled_provider_issuer_subject_owns_durable_receipts(tmp_path, monkeypatch, oidc):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_local import create_local_session+ from gateway.session_contract import Principal+ from hermes_cli.web_server_sessions import _session_mutation_context+ from hermes_state_runtime import RuntimeStoreError+ from plugins.dashboard_auth.basic import BasicAuthProvider, hash_password++ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False)+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='first')++ async def actor(session):+ request, endpoint, auth, factory, ws_type = connection(authority, session, monkeypatch)+ monkeypatch.setattr(request.app.state, 'session_authority', authority, raising=False)+ ticket = (await endpoint(request))['ticket']+ ws = ws_type({'type': 'websocket', 'path': '/api/ws', 'headers': [],+ 'query_string': ('ticket=' + ticket).encode(), 'client': ('127.0.0.1', 1)},+ None, None)+ assert auth(ws)[0] is None+ result = factory(authority, object(), ws._hermes_auth_identity).actor+ # HTTP mutation must use precisely the WS ownership/retry key.+ monkeypatch.setattr('hermes_state._default_db_path', lambda: authority.db.db_path)+ assert _session_mutation_context(request, None)[1].subject == result.subject+ return result++ oauth = oidc('user-a')+ basic = BasicAuthProvider(username='user-a', password_hash=hash_password('fixture-password'), secret=b'fixture-secret-32-characters-long')+ password = basic.complete_password_login(username='user-a', password='fixture-password')+ owner, other, same_sub = await actor(oauth), await actor(oidc('user-b')), await actor(password)+ params = {'request_id': 'same-request', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'fixture', 'toolsets': []}+ ref = create_local_session(authority, owner, params)+ from gateway.session_mutations import mutate_session+ edit = dict(session_id=ref.session_id, request_id='oauth-rename', expected_revision=0,+ operation='rename', payload={'title': 'OAuth owned'})+ receipt = await mutate_session(authority, owner, ref, edit)+ for foreign in (other, same_sub):+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await authority.resolve(foreign, ref)+ assert create_local_session(authority, foreign, params) != ref+ # Same provider name under a different verified issuer is a different authority.+ foreign_issuer = await actor(oidc('user-a', '/other'))+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await authority.resolve(foreign_issuer, ref)+ from tui_gateway.methods_browser_control import _principal_digest+ assert _principal_digest({'provider': oauth.provider, 'issuer': oauth.issuer, 'user_id': oauth.user_id}) != _principal_digest(+ {'provider': oauth.provider, 'issuer': oauth.issuer + '/other', 'user_id': oauth.user_id})+ runner.adapters = {}+ cold = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='second')+ reconnect = await actor(oidc('user-a'))+ assert create_local_session(cold, reconnect, params) == ref+ assert await mutate_session(cold, reconnect, ref, edit) == receipt+ assert (await cold.resolve(reconnect, ref)).ref == ref+ # Pre-cutover remote records have no issuer provenance: never adopt on first request.+ old = create_local_session(cold, Principal('user-a', owner.profile_id, owner.capabilities, 'old'),+ {**params, 'request_id': 'old-ambiguous'})+ for current in (reconnect, same_sub):+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await cold.resolve(current, old)+++async def test_private_native_subject_preserves_existing_creation_and_mutation_retries(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from gateway.session_mutations import mutate_session+ from hermes_state_runtime import RuntimeStoreError++ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False)+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='first')+ caps = frozenset({'session:create', 'session:read', 'session:control'})+ old = Principal('uid:1000', 'fixture', caps, 'old')+ params = {'request_id': 'original', 'source': 'cli', 'cwd': str(tmp_path), 'model': 'fixture', 'toolsets': []}+ ref = create_local_session(authority, old, params)+ native = AuthorityConnection(authority, object(), {'provider': 'local', 'user_id': old.subject,+ 'profile_id': 'fixture', 'instance_id': 'first', 'capabilities': caps}).actor+ assert native.subject == old.subject+ assert create_local_session(authority, native, params) == ref+ edit = dict(session_id=ref.session_id, request_id='rename', expected_revision=0, operation='rename', payload={'title': 'Native preserved'})+ result = await mutate_session(authority, old, ref, edit)+ assert await mutate_session(authority, native, ref, edit) == result+ remote = AuthorityConnection(authority, object(), {'provider': 'local', 'user_id': old.subject}).actor+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await authority.resolve(remote, ref)diff --git a/tui_gateway/methods_browser_control.py b/tui_gateway/methods_browser_control.pyindex 4c82d1b45cf..90ef0b570ad 100644--- a/tui_gateway/methods_browser_control.py+++ b/tui_gateway/methods_browser_control.py@@ -49,7 +49,8 @@ def _is_authenticated_identity(identity: object) -> bool:def _principal_digest(identity: dict) -> str:"""Server-derived principal id: stable per user, unspoofable without the minted identity."""- raw = f"{identity.get('provider')}\x00{identity.get('user_id')}"+ from gateway.session_identity import authenticated_subject+ raw = authenticated_subject(identity)return f"principal:dashboard:{hashlib.sha256(raw.encode('utf-8')).hexdigest()[:32]}"diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex 9a1f6f0fbaa..98080755f0d 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -26,6 +26,23 @@ The SQLite database stores:- Timestamps (started_at, ended_at)- Parent session ID (for compression-triggered session splitting)+### Authenticated gateway session ownership++Sessions created through the canonical gateway are owned by the authenticated+identity, not its display name. Dashboard identities include the auth provider,+verified OAuth issuer (when present), and subject. A password account and an OAuth+account with the same subject do not share ownership; changing OAuth issuers also+changes the owner. HTTP session mutations and WebSocket controls use the same key.+Reconnects and daemon restarts retain creation and mutation retry receipts for the+same identity. Private native bootstrap identities keep their existing owner keys+and session IDs.++Older remote sessions whose receipts contain only a bare subject cannot establish+which provider owned them. They remain stored but are not automatically assigned to+the first authenticated account requesting them. This is not a change to the+personal dashboard's general operator permissions or a guarantee of isolation for+all historical messaging sessions.+### What Counts Toward ContextHermes stores session history so it can resume conversations, but it does not