Skip to content

The agent that grows with you

fix: authorize cold history mutations without execution rebinding

Teknium529fb127b42a
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index f36757d6096..bd893fdc045 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -18,6 +18,7 @@ async def mutate_session(authority, actor, ref, params):
operation = params['operation']
if not isinstance(operation, str):
raise RuntimeStoreError('invalid_params')
+ cold_history = False
if operation == 'import':
if actor.profile_id != authority.profile_id or ref.profile_id != authority.profile_id:
raise RuntimeStoreError('profile_mismatch')
@@ -32,7 +33,12 @@ async def mutate_session(authority, actor, ref, params):
# A receipt authorizes only its original principal's exact retry; the
# transaction still verifies the entire digest and current epoch.
if not has_mutation_receipt(authority.db, actor.subject, ref.session_id, params['request_id']):
- authority.authorize(actor, ref, 'session:control')
+ if ref.session_id not in authority.sessions:
+ from hermes_state_mutation_binding import authorize_history
+ with authority.db._read_ctx() as conn:
+ cold_history = authorize_history(conn, actor, ref.session_id)
+ if not cold_history:
+ authority.authorize(actor, ref, 'session:control')
authority._require_admission_open()
live = authority.sessions.get(ref.session_id)
@@ -58,10 +64,16 @@ async def mutate_session(authority, actor, ref, params):
if operation in _RUNTIME_ACTIONS:
live_guard([ref.session_id])
raise RuntimeStoreError('runtime_coordination_required')
+ def authorize_write(conn):
+ from hermes_state_mutation_binding import authorize_history
+ if not authorize_history(conn, actor, ref.session_id, claim=True):
+ raise RuntimeStoreError('permission_denied')
+
result = mutate_runtime_session(authority.db, epoch=authority.epoch,
principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],
expected_revision=params['expected_revision'], expected_generation=params.get('expected_generation'),
- operation=operation, payload=params['payload'], _live_guard=live_guard)
+ operation=operation, payload=params['payload'], _live_guard=live_guard,
+ _authorize_write=authorize_write if cold_history else None)
if operation == 'delete':
# Repeat local retirement on an exact retry too: publication may have
# failed after the transaction committed. Never repeat the event.
diff --git a/hermes_state_mutation_binding.py b/hermes_state_mutation_binding.py
new file mode 100644
index 00000000000..441ccbd476d
--- /dev/null
+++ b/hermes_state_mutation_binding.py
@@ -0,0 +1,27 @@
+"""Control-only ownership for unbound legacy history; never an execution policy."""
+import json
+from hermes_state_runtime import RuntimeStoreError
+
+BINDING_PREFIX = 'gateway.history_control.v1.'
+
+
+def authorize_history(conn, actor, session_id, *, claim=False):
+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
+ if row is None or row['source'] not in {'cli', 'tui', 'gui', 'import'}:
+ return False
+ # Import intentionally strips routes. Never reinterpret a cold native/API
+ # transcript or another user's owned local conversation as imported history.
+ if row['session_key'] or row['chat_id'] or row['origin_json']:
+ return False
+ if row['user_id'] and row['user_id'] != actor.subject:
+ raise RuntimeStoreError('permission_denied')
+ if 'session:create' not in actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ key = BINDING_PREFIX + session_id
+ binding = json.dumps([actor.profile_id, actor.subject], separators=(',', ':'))
+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
+ if saved is not None and saved[0] != binding:
+ raise RuntimeStoreError('permission_denied')
+ if claim and saved is None:
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, binding))
+ return True
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 7a7493ee56a..4a241a546f4 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -174,7 +174,7 @@ def recover_session_inputs(db, *, epoch: int) -> int:
def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str,
request_id: str, expected_revision: int,
operation: str, payload: dict, expected_generation: int | None = None,
- _live_guard=None) -> dict:
+ _live_guard=None, _authorize_write=None) -> dict:
"""Commit a closed metadata edit and its retry receipt in the same transaction.
Caller authorizes the principal and resolves the canonical session. These
@@ -220,6 +220,8 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str
from hermes_state_mutation_guards import delete_targets
targets = delete_targets(conn, session_id) if operation == 'delete' else [session_id]
_live_guard(targets)
+ if _authorize_write is not None:
+ _authorize_write(conn)
affected, projection = apply_action(db, conn, session_id, operation, payload)
conn.executemany('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',
[(target,) for target in affected])
diff --git a/tests/gateway/test_session_mutation_cold.py b/tests/gateway/test_session_mutation_cold.py
new file mode 100644
index 00000000000..41d1fdd77cf
--- /dev/null
+++ b/tests/gateway/test_session_mutation_cold.py
@@ -0,0 +1,29 @@
+"""Cold history authorization does not manufacture an execution route."""
+import asyncio
+import httpx
+import pytest
+from tests.gateway.test_native_http_auth import daemon, ticket, headers
+from tests.gateway.test_session_mutation_retirement import create
+
+
+def test_cold_import_mutation_binds_owner_across_restart(tmp_path):
+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:
+ # Native creation remains independently authorized while cold history binds.
+ asyncio.run(create(home, descriptor))
+ response = client.post('/api/sessions/import', headers=headers(ticket(home, descriptor)), json={
+ 'request_id': 'import', 'expected_revision': 0, 'sessions': [
+ {'id': 'cold', 'source': 'cli', 'messages': [{'role': 'user', 'content': 'history'}]}]})
+ assert response.status_code == 200, response.text
+ snapshot = client.get('/api/sessions/cold/mutation-snapshot', headers=headers(ticket(home, descriptor)))
+ assert snapshot.status_code == 200, snapshot.text
+ body = {'request_id': 'edit', 'expected_revision': snapshot.json()['runtime_revision'], 'title': 'Cold history'}
+ edited = client.patch('/api/sessions/cold', headers=headers(ticket(home, descriptor)), json=body)
+ assert edited.status_code == 200, edited.text
+ stale = client.patch('/api/sessions/cold', headers=headers(ticket(home, descriptor)), json=body | {'request_id': 'competitor', 'title': 'stale'})
+ assert stale.status_code == 409 and 'revision_conflict' in stale.text
+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:
+ assert client.patch('/api/sessions/cold', headers=headers(ticket(home, descriptor)), json=body).json() == edited.json()
+ assert client.get('/api/sessions/cold/mutation-snapshot', headers=headers(ticket(home, descriptor))).status_code == 200
+ denied = client.patch('/api/sessions/cold', headers={'Authorization': 'Bearer normal-http-owner'}, json=body | {'request_id': 'foreign'})
+ assert denied.status_code == 403, denied.text