The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): a login-stamped desktop row belongs to that login only
Teknium57011297574f
diff --git a/gateway/session_identity.py b/gateway/session_identity.pyindex 3e809051040..f462f6f1201 100644--- a/gateway/session_identity.py+++ b/gateway/session_identity.py@@ -274,6 +274,24 @@ def resolve_identity(return identity+AUTH_SUBJECT_PREFIX = 'auth:v1:'+++def parse_authenticated_subject(subject):+ """``(provider, issuer, user)`` of an :func:`authenticated_subject` login form+ ``auth:v1:[provider, issuer, user]``, else None. The one parser for that format: callers+ apply their own policy (which logins may be forwarded, which map to a label) to the result."""+ if not isinstance(subject, str) or not subject.startswith(AUTH_SUBJECT_PREFIX):+ return None+ try:+ parts = json.loads(subject[len(AUTH_SUBJECT_PREFIX):])+ except ValueError:+ return None+ if not (isinstance(parts, list) and len(parts) == 3 and all(isinstance(p, str) for p in parts)):+ return None+ return tuple(parts)++def authenticated_subject(identity):"""Keep private native receipts stable; namespace every dashboard identity.@@ -285,6 +303,6 @@ def authenticated_subject(identity):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(+ return AUTH_SUBJECT_PREFIX + json.dumps([identity.get('provider') or '', identity.get('issuer') or '', subject],separators=(',', ':'), ensure_ascii=True)diff --git a/gateway/session_listing.py b/gateway/session_listing.pyindex 45b4103dc7d..231252f608f 100644--- a/gateway/session_listing.py+++ b/gateway/session_listing.py@@ -34,7 +34,7 @@ def stored_picker_sessions(authority, actor, *, limit, include_hidden=False):breakcontinuetry:- validate_legacy_row(db, tip)+ validate_legacy_row(db, tip, subject=actor.subject)with db._read_ctx() as conn:if not authorize_history(conn, actor, sid):continuediff --git a/gateway/session_local_migration.py b/gateway/session_local_migration.pyindex 31513443521..87c1e2844b8 100644--- a/gateway/session_local_migration.py+++ b/gateway/session_local_migration.py@@ -137,7 +137,7 @@ def adopt_legacy_session(authority, actor, row):or not {'session:read', 'session:create'} <= actor.capabilities):raise RuntimeStoreError('not_found')from hermes_state_local_migration import LEGACY_CREATION_SOURCES, validate_legacy_row- validate_legacy_row(authority.db, row)+ validate_legacy_row(authority.db, row, subject=actor.subject)authority._require_admission_open()from gateway.run import _load_gateway_config, _resolve_gateway_modelfrom gateway.session_policy import build_policy, bind_launch_keydiff --git a/hermes_state_local_migration.py b/hermes_state_local_migration.pyindex 8bbcfd7c1b8..c4dce7fa374 100644--- a/hermes_state_local_migration.py+++ b/hermes_state_local_migration.py@@ -18,31 +18,36 @@ LEGACY_CREATION_SOURCES = {'desktop': 'gui'}def legacy_account_label(row):- # main's Desktop stamped the signed-in Nous account on its chats, and a served remote backend- # stamps the WS-upgrade login the same way ("<provider>:<user id>"; tui_gateway/session_transports).- # Either is a creation-time label, not a route or an authenticated owner, so neither blocks- # adoption of an otherwise unrouted Desktop row. A prefix naming a messaging platform is- # different: it is that platform's real foreign identity, so only that stays an owner.+ # main's Desktop stamped the signed-in Nous account on its chats. That is a label, not a route or+ # an authenticated owner, so it does not block adoption of an otherwise unrouted Desktop row.user_id = row.get('user_id')- if row['source'] != 'desktop' or not isinstance(user_id, str) or ':' not in user_id:+ return row['source'] == 'desktop' and isinstance(user_id, str) and user_id.startswith('nous:')+++def login_owned_by(row, subject):+ """Whether *subject* is the login a served remote backend stamped on this Desktop row.++ ``hermes serve`` stamps the WS-upgrade login as ``<provider>:<user id>``+ (tui_gateway/session_transports.py). Unlike the Nous label that stamp IS an owner: once a+ login's dashboard writes reach the gateway as that login, reading it as no-owner let login bob+ rename, claim and delete alice's chats (#140183 review F1). So it adopts only for the caller+ whose authenticated subject spells exactly that label (``_login_label``: issuer-less logins+ only); every other caller, the host's own native peer included, still meets a foreign owner.+ """+ user_id = row.get('user_id')+ if row['source'] != 'desktop' or not isinstance(user_id, str) or not subject:return False- provider, _ = user_id.split(':', 1)- if provider == 'nous':- return True- from gateway.config import Platform- try:- platform = Platform(provider)- except ValueError:- return True # a login provider (basic auth, OIDC, ...) labels its user; no platform identity- return platform in (Platform.LOCAL, Platform.API_SERVER)+ from hermes_state_mutation_binding import _login_label+ return _login_label(subject) == user_id-def validate_legacy_row(db, row):+def validate_legacy_row(db, row, *, subject=None):# Unrouted old local history only. Existing identity, foreign profile,# API, messaging, delegate and canonical rows require their own authority.+ # ``subject``: the adopting caller, whose own login stamp is not a foreign identity.if (row['source'] not in LEGACY_LOCAL_SOURCESor any(row.get(k) for k in ('session_key', 'chat_id', 'origin_json'))- or (row.get('user_id') and not legacy_account_label(row))+ or (row.get('user_id') and not legacy_account_label(row) and not login_owned_by(row, subject))or row.get('profile_name') not in (None, '', db._own_profile_name() or 'default')):raise RuntimeStoreError('not_found')@@ -54,7 +59,7 @@ def bind_legacy_target(db, conn, receipt):row = conn.execute('SELECT * FROM sessions WHERE id=?', (target,)).fetchone()if row is None:raise RuntimeStoreError('not_found')- validate_legacy_row(db, dict(row))+ validate_legacy_row(db, dict(row), subject=receipt['principal_id'])from hermes_state_mutation_binding import BINDING_PREFIXimported = conn.execute('SELECT value FROM state_meta WHERE key=?', (BINDING_PREFIX + target,)).fetchone()if imported and json.loads(imported[0]) != [receipt['profile_id'], receipt['principal_id']]:diff --git a/hermes_state_mutation_binding.py b/hermes_state_mutation_binding.pyindex a2329bfc575..07b964d3b7c 100644--- a/hermes_state_mutation_binding.py+++ b/hermes_state_mutation_binding.py@@ -19,6 +19,22 @@ def _owner_user(row):return None if legacy_account_label(dict(row)) else row['user_id']+def _login_label(subject):+ """The ``<provider>:<user>`` label Desktop stamps on its rows (tui_gateway/session_transports.py) when it+ names exactly the dashboard subject ``auth:v1:[provider, "", user]`` (gateway/session_identity.py).+ Only an issuer-less login maps: the label drops the issuer, so an issuer-bearing subject must not claim it."""+ from gateway.session_identity import parse_authenticated_subject+ parts = parse_authenticated_subject(subject)+ if parts is None:+ return None+ provider, issuer, user = parts+ if issuer or ':' in provider or not provider.strip() or not user.strip():+ return None+ label = f'{provider.strip()}:{user.strip()}'+ # Never yield something that reads as a subject itself (a provider named ``auth`` + user ``v1:[...]``).+ return None if label.startswith('auth:') else label++def import_history_control(conn, actor, session_ids):binding = json.dumps([actor.profile_id, actor.subject], separators=(',', ':'))for sid in session_ids:@@ -43,7 +59,7 @@ def authorize_history(conn, actor, session_id, *, claim=False):return Trueif row['source'] not in _history_sources():return False- if _owner_user(row) and row['user_id'] != actor.subject:+ if _owner_user(row) and row['user_id'] not in (actor.subject, _login_label(actor.subject)):raise RuntimeStoreError('permission_denied')if 'session:create' not in actor.capabilities:raise RuntimeStoreError('permission_denied')diff --git a/tests/gateway/test_legacy_desktop_source.py b/tests/gateway/test_legacy_desktop_source.pyindex 3ae2aac259a..f256e6a1cfe 100644--- a/tests/gateway/test_legacy_desktop_source.py+++ b/tests/gateway/test_legacy_desktop_source.py@@ -1,14 +1,25 @@"""Every old local row the native resume adopts also takes a sidebar edit (#106742).The resume adopts main's ``desktop`` chats (including those stamped with the signed-in Nous-account or with a served remote backend's login label) and ``oneshot``/``tool`` CLI runs, but-``authorize_history`` (pin/archive/hide/rename) only knew ``cli``/``tui``/``gui``, so the same-rows answered ``permission_denied`` on every sidebar edit.+account) and ``oneshot``/``tool`` CLI runs, but ``authorize_history`` (pin/archive/hide/rename)+only knew ``cli``/``tui``/``gui``, so the same rows answered ``permission_denied`` on every+sidebar edit. A served remote backend's login label (``basic:alice``) is that login's ownership,+not a label: only the same login adopts and edits it (#139818; #140183 review F1)."""+import json++import pytest+from gateway.session_contract import Principalfrom hermes_state import SessionDBfrom hermes_state_local_migration import validate_legacy_rowfrom hermes_state_mutation_binding import authorize_history, same_history_owner+from hermes_state_runtime import RuntimeStoreError+++def _login(user, issuer=''):+ """The subject a dashboard login (or its forwarded ticket) carries: ``authenticated_subject``."""+ return 'auth:v1:' + json.dumps(['basic', issuer, user], separators=(',', ':'))def test_rows_the_resume_adopts_take_sidebar_edits(tmp_path):@@ -16,15 +27,12 @@ def test_rows_the_resume_adopts_take_sidebar_edits(tmp_path):try:for sid, source, user_id in (('old-desktop', 'desktop', None), ('old-oneshot', 'oneshot', None),('old-desktop-nous', 'desktop', 'nous:account'),- ('old-desktop-remote', 'desktop', 'basic:hermes'),- ('old-desktop-oidc', 'desktop', 'oidc:alice'),('old-desktop-foreign', 'desktop', 'telegram:42'),('old-cli-nous', 'cli', 'nous:account'), ('api-row', 'api_server', None)):db.create_session(sid, source=source, user_id=user_id)actor = Principal('uid:1', str(tmp_path), frozenset({'session:read', 'session:create'}), 'native-http:x')with db._read_ctx() as conn:- for sid in ('old-desktop', 'old-oneshot', 'old-desktop-nous', 'old-desktop-remote',- 'old-desktop-oidc'):+ for sid in ('old-desktop', 'old-oneshot', 'old-desktop-nous'):validate_legacy_row(db, db.get_session(sid)) # the resume adopts it ...assert authorize_history(conn, actor, sid) is True, sid # ... so it takes an edit.assert same_history_owner(conn, 'old-desktop', 'old-desktop-nous') is True@@ -39,3 +47,39 @@ def test_rows_the_resume_adopts_take_sidebar_edits(tmp_path):assert authorize_history(conn, actor, 'api-row') is Falsefinally:db.close()+++def test_a_login_labelled_desktop_row_belongs_to_that_login_only(tmp_path):+ """#140183 review F1: reading ``basic:alice`` as a no-owner label let login bob rename, claim+ and delete alice's chats once dashboard writes reach the gateway as the dashboard login. The+ label is alice's ownership: alice adopts and edits it, bob and the host's own UID do not."""+ db = SessionDB(db_path=tmp_path / 'state.db')+ try:+ db.create_session('alice-row', source='desktop', user_id='basic:alice')+ db.create_session('oidc-row', source='desktop', user_id='oidc:alice')+ caps = frozenset({'session:read', 'session:create'})+ alice, bob = (Principal(_login(u), str(tmp_path), caps, 'native-http:x') for u in ('alice', 'bob'))+ issuer_alice = Principal(_login('alice', 'https://idp.example'), str(tmp_path), caps, 'native-http:x')+ host = Principal('uid:1', str(tmp_path), caps, 'native-http:x')+ row = db.get_session('alice-row')+ validate_legacy_row(db, row, subject=alice.subject)+ for stranger in (bob, issuer_alice, host):+ with pytest.raises(RuntimeStoreError, match='not_found'):+ validate_legacy_row(db, row, subject=stranger.subject)+ with pytest.raises(RuntimeStoreError, match='not_found'):+ validate_legacy_row(db, row) # no caller named: never adoptable+ with db._read_ctx() as conn:+ assert authorize_history(conn, alice, 'alice-row') is True+ for stranger in (bob, issuer_alice, host):+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ authorize_history(conn, stranger, 'alice-row', claim=True)+ # A login label the caller's subject cannot spell (another provider) stays foreign.+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ authorize_history(conn, alice, 'oidc-row')+ # Not an anonymous chain member either: a no-owner anchor does not reach it.+ assert same_history_owner(conn, 'alice-row', 'alice-row') is True+ db.create_session('plain', source='desktop')+ with db._read_ctx() as conn:+ assert same_history_owner(conn, 'plain', 'alice-row') is False+ finally:+ db.close()diff --git a/tests/gateway/test_legacy_session_migration.py b/tests/gateway/test_legacy_session_migration.pyindex 75c12727388..29959170465 100644--- a/tests/gateway/test_legacy_session_migration.py+++ b/tests/gateway/test_legacy_session_migration.py@@ -1,4 +1,5 @@"""Pre-authority rows never grant ownership to the first remote claimant."""+import jsonfrom pathlib import Pathfrom types import SimpleNamespace@@ -180,8 +181,8 @@ async def test_upgraded_oneshot_and_tool_history_resumes_by_id_and_title_but_staasync def test_upgraded_desktop_history_resumes_by_id(tmp_path, monkeypatch):"""main's Desktop stored its chats with ``source='desktop'``. After the upgrade the native owneradopts them by id like ``gui`` history, including the ones stamped with the signed-in Nous- account or with a served remote backend's login label (``hermes serve`` basic auth). Any other- identity still needs its own authority."""+ account. A served remote backend's login stamp (``hermes serve`` basic auth) adopts for that same+ login only. Any other identity still needs its own authority."""from gateway import runfrom gateway.config import GatewayConfigfrom gateway.session import SessionStore@@ -211,9 +212,23 @@ async def test_upgraded_desktop_history_resumes_by_id(tmp_path, monkeypatch):stamped = await native.dispatch({'id': 2, 'method': 'session.resume', 'params': {'session_id': 'old-desktop-account'}})assert stamped.get('result', {}).get('session_id') == 'old-desktop-account', stampedassert [m['content'] for m in stamped['result']['messages']] == ['OLD-DESKTOP-ACCOUNT']- # A served remote backend stamped its basic-auth principal on the row at creation; that login- # is a label, so the local native owner adopts the row once its hosting serve is gone (#139818).- remote = await native.dispatch({'id': 4, 'method': 'session.resume', 'params': {'session_id': 'old-desktop-remote'}})+ # A served remote backend stamped its basic-auth login on the row at creation (#139818). That+ # stamp is the login's ownership, not a label (#140183 review F1): another login and the host's+ # own native peer are refused without a write; the same login adopts it once its serve is gone.+ caps = ['session:create', 'session:read', 'session:submit', 'session:control', 'session:approve',+ 'session:respond']++ def login(user):+ subject = 'auth:v1:' + json.dumps(['basic', '', user], separators=(',', ':'))+ return AuthorityConnection(authority, object(), {'provider': 'local', 'user_id': subject,+ 'profile_id': str(tmp_path), 'instance_id': 'first', 'capabilities': caps})+ for stranger in (login('bob'), native):+ refused = await stranger.dispatch({'id': 4, 'method': 'session.resume',+ 'params': {'session_id': 'old-desktop-remote'}})+ assert refused.get('error', {}).get('message') == 'not_found', refused+ assert db.get_session('old-desktop-remote')['user_id'] == 'basic:hermes'+ remote = await login('hermes').dispatch({'id': 5, 'method': 'session.resume',+ 'params': {'session_id': 'old-desktop-remote'}})assert remote.get('result', {}).get('session_id') == 'old-desktop-remote', remoteassert [m['content'] for m in remote['result']['messages']] == ['OLD-DESKTOP-REMOTE']# Any other identity, or a Nous stamp on a non-Desktop row, still needs its own authority.