Skip to content

The agent that grows with you

fix(webapp): every stored owner is read by one rule, so old Webapp chats open and adopt again

Tekniumc5270d2fbb58
diff --git a/gateway/owner_identity.py b/gateway/owner_identity.py
index 85f3d6be06e..bffdf405527 100644
--- a/gateway/owner_identity.py
+++ b/gateway/owner_identity.py
@@ -6,7 +6,10 @@ tab, a standalone dashboard's forwarded login or a phone signed in through the d
that same person: sign-in only decides whether a browser may open the Webapp at all, it never names a
second owner. So every authenticated non-native principal acts as :func:`host_owner_subject`, and
the login stamps older builds stored (``auth:v1:[provider, issuer, user]`` subjects, the
-``<provider>:<user>`` labels ``hermes serve`` stamped on Desktop rows) read as the owner's too.
+``<provider>:<user>`` labels ``hermes serve`` stamped on Desktop rows) read as the owner's too. A
+``local`` stamp names an OS user, so it matches this machine's account only. Every comparison of a
+stored owner with a caller goes through :func:`same_owner`, so the sidebar, the open, adoption and the
+room controls cannot disagree about who owns a row.
"""
from __future__ import annotations
@@ -34,11 +37,11 @@ def principal_subject(identity: dict) -> str:
return host_owner_subject() if _login_provider(provider) else subject
-# The interactive sign-ins Hermes bundles, plus the native grant a served Desktop presented
-# (``local:uid:<n>``); a plugin-registered dashboard provider counts too (:func:`_login_provider`).
-# ``session-token`` is the loopback Webapp's own credential and ``server-internal`` the PTY child a
-# signed-in dashboard spawns: both act for whoever opened that page, the owner.
-_BUNDLED_LOGINS = frozenset({'basic', 'nous', 'self-hosted', 'local', 'session-token', 'server-internal'})
+# The interactive sign-ins Hermes bundles; a plugin-registered dashboard provider counts too
+# (:func:`_login_provider`). ``session-token`` is the loopback Webapp's own credential and
+# ``server-internal`` the PTY child a signed-in dashboard spawns: both act for whoever opened that page,
+# the owner. ``local`` (a native grant) is not a sign-in: its stamp names an OS user (:func:`_owner_login`).
+_BUNDLED_LOGINS = frozenset({'basic', 'nous', 'self-hosted', 'session-token', 'server-internal'})
def _login_provider(provider: str) -> bool:
@@ -48,34 +51,48 @@ def _login_provider(provider: str) -> bool:
return any(p.name == provider for p in list_session_providers())
+def _owner_login(provider: str, user: str) -> bool:
+ """Whether a stored ``(provider, user)`` stamp names the host owner. A ``local`` stamp (the native
+ grant a served Desktop presented) names an OS user, so it is the owner's only when that user is this
+ machine's owner; any other OS user stays foreign. A sign-in stamp is the owner's."""
+ if provider == 'local':
+ return user.strip() == host_owner_subject()
+ return _login_provider(provider)
+
+
def _login_label(value: str) -> bool:
"""``<provider>:<user>`` for a dashboard sign-in: the label ``hermes serve`` stamped for a login
(session_transports). Any other prefix (``telegram:42``, ``uid:501``) names someone else, and a
``nous:`` stamp keeps its own rule (``legacy_account_label``: a Desktop row's account label)."""
provider, sep, user = value.partition(':')
- return bool(sep and user.strip()) and provider != 'nous' and _login_provider(provider)
+ return bool(sep and user.strip()) and provider != 'nous' and _owner_login(provider, user)
def _login_subject(value) -> bool:
"""An ``auth:v1:[provider, issuer, user]`` subject a sign-in stored (a provider is named)."""
from gateway.session_identity import parse_authenticated_subject
parts = parse_authenticated_subject(value)
- return parts is not None and bool(parts[2].strip()) and _login_provider(parts[0])
+ return parts is not None and bool(parts[2].strip()) and _owner_login(parts[0], parts[2])
def same_owner(stored, subject) -> bool:
- """Whether a stored owner subject (room owner, history binding) belongs to *subject*: equal, or a
- login subject a Webapp/dashboard sign-in stored while *subject* is the host owner."""
+ """THE owner rule: whether a stored owner stamp (a room owner, a history binding's subject, an
+ admission's principal, a routeless row's ``user_id``) belongs to *subject*. True when equal, when it
+ is the ``<provider>:<user>`` label of *subject*'s own login, or, while *subject* is the host owner,
+ when it is any sign-in stamp an older build stored (an ``auth:v1`` login subject or a served
+ dashboard's ``<provider>:<user>`` label). One-way: a non-owner subject never gains owner stamps.
+ Every identity comparison on a stored owner goes through here so readers cannot disagree."""
if stored == subject:
return True
- return subject == host_owner_subject() and _login_subject(stored)
-
-
-def owns_row_stamp(user_id, subject) -> bool:
- """Whether a routeless local row's ``user_id`` stamp names *subject*: :func:`same_owner`, the
- label of *subject*'s own login, or any ``<provider>:<user>`` login label a served dashboard
- stamped while *subject* is the host owner."""
+ if not isinstance(stored, str) or not stored or not subject:
+ return False
from hermes_state_mutation_binding import _login_label as label_of
- if same_owner(user_id, subject) or (user_id is not None and user_id == label_of(subject)):
+ if stored == label_of(subject):
return True
- return isinstance(user_id, str) and subject == host_owner_subject() and _login_label(user_id)
+ return subject == host_owner_subject() and (_login_subject(stored) or _login_label(stored))
+
+
+def owners_agree(first, second) -> bool:
+ """Whether two stored owner stamps name the same owner (:func:`same_owner` either way round), for
+ checks that compare one stored stamp with another rather than with a caller."""
+ return same_owner(first, second) or same_owner(second, first)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 1459f268846..b9e544c071f 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -215,8 +215,9 @@ class SessionAuthority:
require_history_access(self, actor, ref.session_id, capability)
from gateway.config import Platform
source = self.sessions[ref.session_id].source
+ from gateway.owner_identity import same_owner
if (source is not None and source.platform == Platform.LOCAL
- and source.user_id != actor.subject and 'session:operator' not in actor.capabilities):
+ and not same_owner(source.user_id, actor.subject) and 'session:operator' not in actor.capabilities):
raise RuntimeStoreError('permission_denied')
def _require_admission_open(self, *, queue_only=False):
@@ -709,7 +710,8 @@ class SessionAuthority:
if _kanban_card is not None:
payload['kanban_card_v1'] = _kanban_card
source = self.sessions[request.ref.session_id].source
- if source is not None and source.user_id != actor.subject:
+ from gateway.owner_identity import same_owner
+ if source is not None and not same_owner(source.user_id, actor.subject):
# Durable server authorization, not a client payload field. The original
# principal remains the admission/retry identity across owner restarts.
# Operator provenance is about who was authorized at this boundary, not
@@ -754,7 +756,8 @@ class SessionAuthority:
row = get_session_admission(self.db, admission_id=admission_id)
if row is None or row['target_session_id'] != ref.session_id:
raise RuntimeStoreError('not_found')
- if row['principal_id'] != actor.subject and 'session:control' not in actor.capabilities:
+ from gateway.owner_identity import same_owner
+ if not same_owner(row['principal_id'], actor.subject) and 'session:control' not in actor.capabilities:
raise RuntimeStoreError('permission_denied')
live = self.sessions[ref.session_id]
with live.event_stream.lock:
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 4d246d660fa..9e59421a422 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -773,7 +773,8 @@ async def deliver(connection, params):
def _require_same_delivery(record, actor, message, author, category):
"""A delivery id names one delivery: the same message, principal, author and category (the
mailbox writer's identity), whether its receipt is admission-backed or refused."""
- if (record['message'] != message or record['principal_id'] != actor.subject
+ from gateway.owner_identity import same_owner
+ if (record['message'] != message or not same_owner(record['principal_id'], actor.subject)
or record.get('author') != author
or record.get('notification_category', 'result') != category):
raise RuntimeStoreError('admission_conflict')
diff --git a/gateway/session_cron.py b/gateway/session_cron.py
index 0cc474d4539..46f174a923b 100644
--- a/gateway/session_cron.py
+++ b/gateway/session_cron.py
@@ -175,7 +175,8 @@ async def operation(authority, name, params, actor=None):
sid = local_identity(authority.profile_id, actor.subject, request_id)
from hermes_state_runtime import list_session_admissions
rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)
- row = next((r for r in rows if r['request_id'] == request_id and r['principal_id'] == actor.subject), None)
+ from gateway.owner_identity import same_owner
+ row = next((r for r in rows if r['request_id'] == request_id and same_owner(r['principal_id'], actor.subject)), None)
if row is None:
return {'status': 'missing', 'result': None}
state = await operation(authority, 'status', {'session_id': sid, 'admission_id': row['admission_id']}, actor)
@@ -216,7 +217,8 @@ async def operation(authority, name, params, actor=None):
ref = SessionRef(authority.profile_id, params['session_id'])
authority.authorize(actor, ref, 'session:submit')
row = get_session_admission(authority.db, admission_id=params['admission_id'])
- if row is None or row['target_session_id'] != ref.session_id or row['principal_id'] != actor.subject:
+ from gateway.owner_identity import same_owner
+ if row is None or row['target_session_id'] != ref.session_id or not same_owner(row['principal_id'], actor.subject):
raise RuntimeStoreError('permission_denied')
if name == 'cancel':
if row['status'] == 'queued':
diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.py
index 0f0b80d2082..579c4357c2e 100644
--- a/gateway/session_group_controls.py
+++ b/gateway/session_group_controls.py
@@ -341,7 +341,8 @@ def _read_bot_sessions(db, subject, operator):
# The named registry is not a recency window and canonical chats are hidden.
canonical = conn.execute(f'SELECT * FROM sessions WHERE title=? AND {_LOCAL_CHAT}',
('Bot Chat', LEGACY_PREFIX)).fetchone()
- if canonical and (canonical['user_id'] == subject or operator) and not canonical['archived']:
+ from gateway.owner_identity import same_owner
+ if canonical and (same_owner(canonical['user_id'], subject) or operator) and not canonical['archived']:
fields['canonical_session'] = summary(canonical)
# The newest conversation a picker shows: a hidden row (a Bot Chat, group member plumbing)
# never wins, as in the pre-unified roster's listing.
diff --git a/gateway/session_history_mount.py b/gateway/session_history_mount.py
index 187e4a27ca4..d3f481703d3 100644
--- a/gateway/session_history_mount.py
+++ b/gateway/session_history_mount.py
@@ -9,7 +9,6 @@ is keyed by no lane's route, so nothing route-keyed acts through it, and every c
(gateway/session_mutations.py), but only a leaf row deletes. Old local CLI/TUI/Desktop rows are not mounted
here: resume adopts them as writable conversations (gateway/session_local_migration.py).
"""
-import json
from hermes_state_runtime import RuntimeStoreError
@@ -20,11 +19,11 @@ _ROUTE_PREFIX = 'history:'
def _reader(authority, actor, sid):
"""The importer an import binding names, else the profile's owner: its native peer (the evidence
legacy adoption takes) or an operator. Knowing an old id is not ownership."""
- from hermes_state_mutation_binding import history_binding
+ from hermes_state_mutation_binding import binding_names, history_binding
with authority.db._read_ctx() as conn:
binding = history_binding(conn, sid)
if binding is not None:
- return binding == json.dumps([actor.profile_id, actor.subject], separators=(',', ':'))
+ return binding_names(binding, actor.profile_id, actor.subject)
return ('session:operator' in actor.capabilities
or getattr(authority, '_native_legacy_transports', {}).get(actor.transport_id) == actor)
diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.py
index 571fb75eed8..dc1b0aee250 100644
--- a/gateway/session_hosted_rpc.py
+++ b/gateway/session_hosted_rpc.py
@@ -12,6 +12,7 @@ import hashlib
import json
from gateway.hosted_room_driver import TaskIdentity
+from gateway.owner_identity import same_owner
from gateway.session_contract import SessionRef, Submission
from hermes_state_runtime import RuntimeStoreError, list_session_admissions
@@ -121,7 +122,7 @@ class HostedRoomAuthorityRPC:
rows = list_session_admissions(self.authority.db, session_id=self.ref.session_id, pending_only=False)
result = []
for row in rows:
- if row['principal_id'] != self.principal.subject or not row['request_id'].startswith('hosted:'):
+ if not same_owner(row['principal_id'], self.principal.subject) or not row['request_id'].startswith('hosted:'):
continue
try:
task, generation = json.loads(row['request_id'][7:])
diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.py
index da7755d0ef4..6c503edf05f 100644
--- a/gateway/session_hosted_service.py
+++ b/gateway/session_hosted_service.py
@@ -7,6 +7,7 @@ from pathlib import Path
from gateway.session_contract import Principal
from gateway.session_authorities import active_authority, all_authorities, owner_scope, serving_authorities
from gateway.session_hosted_controls import HostedControls
+from gateway.owner_identity import same_owner
from hermes_state_runtime import RuntimeStoreError, _epoch
from tui_gateway.hosted_room_service import HostedRoomService
@@ -113,7 +114,6 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):
if historical is None:
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, actor_subject))
return True
- from gateway.owner_identity import same_owner
if row is None or not same_owner(row[0], actor_subject):
raise RuntimeStoreError('permission_denied')
return True
@@ -214,7 +214,7 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):
if type(generation) is not int or generation < 1:
raise ValueError('invalid generation')
owner = self._owner(identity.room_id)
- if owner != row['principal_id']:
+ if not same_owner(owner, row['principal_id']):
raise ValueError('foreign owner')
room = self._room(identity.room_id)
task = next(t for t in list_tasks(self.db_path, room_id=identity.room_id)
diff --git a/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.py
index 12f0cb13cba..309619f0168 100644
--- a/gateway/session_hosted_transport.py
+++ b/gateway/session_hosted_transport.py
@@ -19,6 +19,7 @@ from gateway.hosted_room_driver import TaskIdentity
from gateway.session_contract import Principal
from gateway.session_authorities import owner_scope
from gateway.session_hosted_rpc import HostedRoomAuthorityRPC
+from gateway.owner_identity import same_owner
from hermes_state_runtime import RuntimeStoreError, _epoch
_BINDING = 'gateway.hosted.transport.v1:'
@@ -283,7 +284,7 @@ def _check_remote_hosted_admission(authority, ref, row):
binding = json.loads(stored[0])
identity, generation = json.loads(row['request_id'][7:])
if (not row['request_id'].startswith('hosted:')
- or row['principal_id'] != _principal(authority, binding).subject
+ or not same_owner(row['principal_id'], _principal(authority, binding).subject)
or ref.profile_id != authority.profile_id
or binding.get('target_home') != authority.profile_id):
raise ValueError('binding mismatch')
diff --git a/gateway/session_listing.py b/gateway/session_listing.py
index 68768336919..c67f41f3077 100644
--- a/gateway/session_listing.py
+++ b/gateway/session_listing.py
@@ -3,6 +3,7 @@ from hermes_state_local_migration import validate_legacy_row
from hermes_state_mutation_binding import authorize_history
from hermes_state_runtime import RuntimeStoreError
+from gateway.owner_identity import same_owner
from gateway.session_route_recovery import _messaging_platform, mountable
# Local labels (a cron run is a canonical local session whose last viewer is its own fire).
@@ -121,6 +122,6 @@ def _stored_closed(authority, actor, owner):
except (RuntimeStoreError, KeyError, TypeError):
return False
return (receipt.get('profile_id') == authority.profile_id
- and (receipt.get('principal_id') == actor.subject or 'session:operator' in actor.capabilities)
+ and (same_owner(receipt.get('principal_id'), actor.subject) or 'session:operator' in actor.capabilities)
and row is not None and row['ended_at'] is not None
and not list_session_admissions(authority.db, session_id=owner))
diff --git a/gateway/session_local_migration.py b/gateway/session_local_migration.py
index 1344e5753ed..99e0e2c7e25 100644
--- a/gateway/session_local_migration.py
+++ b/gateway/session_local_migration.py
@@ -35,7 +35,7 @@ def unbind_native_transport(authority, actor):
def require_history_claim(authority, conn, actor, sid):
"""Import receipts confer ownership; merely knowing an old ID does not."""
- from gateway.owner_identity import owns_row_stamp
+ from gateway.owner_identity import same_owner
from hermes_state_mutation_binding import BINDING_PREFIX, _owner_user
row = conn.execute('SELECT * FROM sessions WHERE id=?', (sid,)).fetchone()
if row is None or row['session_key'] or row['chat_id'] or row['origin_json']:
@@ -43,7 +43,7 @@ def require_history_claim(authority, conn, actor, sid):
if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (BINDING_PREFIX + sid,)).fetchone():
return # authorize_history checks the already committed importer identity.
own_profile = row['profile_name'] in (None, '', authority.db._own_profile_name() or 'default')
- if own_profile and _owner_user(row) and owns_row_stamp(row['user_id'], actor.subject):
+ if own_profile and _owner_user(row) and same_owner(row['user_id'], actor.subject):
return # Its owner (a login stamp is the machine owner's); authorize_history re-checks it.
if getattr(authority, '_native_legacy_transports', {}).get(actor.transport_id) != actor:
raise RuntimeStoreError('permission_denied')
diff --git a/gateway/session_operator.py b/gateway/session_operator.py
index 37e91ac50fd..0575e2c7248 100644
--- a/gateway/session_operator.py
+++ b/gateway/session_operator.py
@@ -5,6 +5,7 @@ It never claims unowned legacy history: that still requires the native migration
path. Only SessionAuthority.submit writes this envelope after authorization;
public submission parameters cannot supply it.
"""
+from gateway.owner_identity import same_owner
from hermes_state_runtime import RuntimeStoreError
# Fields ``SessionAuthority.submit`` commits for a local session's input; producers commit their own envelope.
@@ -31,7 +32,7 @@ def check_local_input(authority, ref, row, *, source=None):
raise RuntimeStoreError('permission_denied')
else:
source = source or authority.sessions[ref.session_id].source
- if row['principal_id'] != source.user_id:
+ if not same_owner(source.user_id, row['principal_id']): # the rule submit() stamped by
raise RuntimeStoreError('permission_denied')
if not {'text'} <= set(payload) <= allowed:
raise RuntimeStoreError('permission_denied')
diff --git a/gateway/session_worker_reservation.py b/gateway/session_worker_reservation.py
index 4d996ec261f..421bb891093 100644
--- a/gateway/session_worker_reservation.py
+++ b/gateway/session_worker_reservation.py
@@ -8,6 +8,7 @@ import secrets
import subprocess
from gateway.session_admission import admission_fingerprint
+from gateway.owner_identity import same_owner
from hermes_state_runtime import RuntimeStoreError, _admission, _epoch, _secret_digest, _session
# A venv launcher (uv's Windows python.exe, pip's exe shim) sits between the owner's
@@ -80,7 +81,7 @@ def reserve_admission_worker(authority, *, admission_id, process, principal_id,
admission = _admission(conn, admission_id)
if admission['status'] != 'started' or admission['owner_epoch'] != authority.epoch:
raise RuntimeStoreError('producer_not_started')
- if admission['principal_id'] != principal_id:
+ if not same_owner(admission['principal_id'], principal_id):
raise RuntimeStoreError('permission_denied')
owner, generation = admission['target_session_id'], admission['generation']
if _session(conn, owner)['runtime_generation'] != generation:
diff --git a/hermes_state_local_migration.py b/hermes_state_local_migration.py
index caac43ef386..d779abab2ba 100644
--- a/hermes_state_local_migration.py
+++ b/hermes_state_local_migration.py
@@ -30,13 +30,13 @@ def login_owned_by(row, subject):
Older ``hermes serve`` builds stamped the WS-upgrade login as ``<provider>:<user id>``
(tui_gateway/session_transports.py), and the gateway stored a Webapp login as its
``auth:v1:[...]`` subject. Hermes is single-user and sign-in is owner-only, so both name the
- machine owner: the host owner's subject adopts them (gateway.owner_identity.owns_row_stamp).
+ machine owner: the host owner's subject adopts them (gateway.owner_identity.same_owner).
"""
user_id = row.get('user_id')
if not isinstance(user_id, str) or not subject:
return False
- from gateway.owner_identity import owns_row_stamp
- return owns_row_stamp(user_id, subject)
+ from gateway.owner_identity import same_owner
+ return same_owner(user_id, subject)
def validate_legacy_row(db, row, *, subject=None):
@@ -48,8 +48,7 @@ def validate_legacy_row(db, row, *, subject=None):
user_id = row.get('user_id')
if (row['source'] not in LEGACY_LOCAL_SOURCES
or any(row.get(k) for k in ('session_key', 'chat_id', 'origin_json'))
- or (user_id and user_id != subject and not legacy_account_label(row)
- and not login_owned_by(row, subject))
+ or (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')
@@ -62,9 +61,9 @@ def bind_legacy_target(db, conn, receipt):
if row is None:
raise RuntimeStoreError('not_found')
validate_legacy_row(db, dict(row), subject=receipt['principal_id'])
- from hermes_state_mutation_binding import BINDING_PREFIX
+ from hermes_state_mutation_binding import BINDING_PREFIX, binding_names
imported = 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']]:
+ if imported and not binding_names(imported[0], receipt['profile_id'], receipt['principal_id']):
raise RuntimeStoreError('permission_denied')
from hermes_state_compression import _CHAIN_STEP_SQL
if conn.execute(_CHAIN_STEP_SQL, (target,)).fetchone() is not None:
diff --git a/hermes_state_mutation_binding.py b/hermes_state_mutation_binding.py
index d80d4597bd6..ab41538290c 100644
--- a/hermes_state_mutation_binding.py
+++ b/hermes_state_mutation_binding.py
@@ -35,15 +35,32 @@ def _login_label(subject):
return None if label.startswith('auth:') else label
-def _bound_to(saved, actor):
- """Whether a stored ``[profile_id, subject]`` binding names *actor*: same profile, and the same
- owner (a binding a Webapp login stored belongs to the machine owner, gateway.owner_identity)."""
+def binding_names(saved, profile_id, subject):
+ """Whether a stored ``[profile_id, subject]`` binding names *subject* in *profile_id*: same profile,
+ and the same owner (a binding a Webapp login stored belongs to the machine owner,
+ gateway.owner_identity.same_owner). Every reader of a binding asks this, never a string compare."""
try:
- profile_id, subject = json.loads(saved)
+ saved_profile, saved_subject = json.loads(saved)
except (TypeError, ValueError):
return False
from gateway.owner_identity import same_owner
- return profile_id == actor.profile_id and same_owner(subject, actor.subject)
+ return saved_profile == profile_id and same_owner(saved_subject, subject)
+
+
+def _bound_to(saved, actor):
+ return binding_names(saved, actor.profile_id, actor.subject)
+
+
+def _bindings_agree(first, second):
+ """Two stored bindings name the same owner (both absent agrees; one absent does not)."""
+ if first == second or first is None or second is None:
+ return first == second
+ try:
+ (first_profile, first_subject), (profile_id, subject) = json.loads(first), json.loads(second)
+ except (TypeError, ValueError):
+ return False
+ from gateway.owner_identity import owners_agree
+ return first_profile == profile_id and owners_agree(first_subject, subject)
def import_history_control(conn, actor, session_ids):
@@ -70,8 +87,8 @@ def authorize_history(conn, actor, session_id, *, claim=False):
return True
if row['source'] not in _history_sources():
return False
- from gateway.owner_identity import owns_row_stamp
- if _owner_user(row) and not owns_row_stamp(row['user_id'], actor.subject):
+ from gateway.owner_identity import same_owner
+ if _owner_user(row) and not same_owner(row['user_id'], actor.subject):
raise RuntimeStoreError('permission_denied')
if 'session:create' not in actor.capabilities:
raise RuntimeStoreError('permission_denied')
@@ -103,8 +120,10 @@ def same_history_owner(conn, anchor_id, session_id):
if row['session_key'] or row['chat_id'] or row['origin_json']:
return tuple(row)[1:4] == tuple(anchor)[1:4]
binding = history_binding(conn, session_id)
- if binding != history_binding(conn, anchor_id):
+ if not _bindings_agree(binding, history_binding(conn, anchor_id)):
return False
routeless_peer = row['source'] == anchor['source'] and not any(tuple(anchor)[2:5])
+ from gateway.owner_identity import owners_agree
return binding is not None or (
- (row['source'] in _history_sources() or routeless_peer) and _owner_user(row) in (None, '', anchor['user_id']))
+ (row['source'] in _history_sources() or routeless_peer)
+ and (_owner_user(row) in (None, '') or owners_agree(_owner_user(row), anchor['user_id'])))
diff --git a/tests/gateway/fixtures/hosted_auth_probe.py b/tests/gateway/fixtures/hosted_auth_probe.py
index 337ef9677c7..0336fda4448 100644
--- a/tests/gateway/fixtures/hosted_auth_probe.py
+++ b/tests/gateway/fixtures/hosted_auth_probe.py
@@ -213,8 +213,17 @@ def probe(tmp_path):
seen = await rpc(other, method, room_id=room)
assert 'result' in seen, seen
shared += 1
+ # The single-owner contract still refuses what would rewrite a room or replay input:
+ # creating over another tab's existing room id, and reusing a sent event id.
+ hijack = await rpc(other, 'groups.create', room_id=room, name='hijack', members=members)
+ assert 'error' in hijack, hijack
+ replay = await rpc(other, 'groups.send', room_id=room, event_id='own-input',
+ payload={'text': 'FORBIDDEN', 'thread_id': 'thread'})
+ assert 'error' in replay, replay
after = await rpc(other, 'groups.log', room_id=room)
assert after == before, (before, after)
+ named = await rpc(other, 'groups.state', room_id=room)
+ assert named['result']['room']['name'] == tab, named
state = await rpc(ws, 'groups.state', room_id=room)
assert state['result']['driver_status']['counts'].get('running') == 1, state
for tab, ws, _ in tabs:
@@ -256,6 +265,7 @@ def probe(tmp_path):
await async_wait_until(lambda: not removal.exists(), timeout=90,
what='the approved removal to run')
+ assert 'FORBIDDEN' not in json.dumps(model.requests)
return {'actors': oidc.logins, 'rooms': rooms, 'shared_views': shared, 'owner_stops': 2}
try:
diff --git a/tests/gateway/test_webapp_owner_identity.py b/tests/gateway/test_webapp_owner_identity.py
index a77917ca810..195445a2bb9 100644
--- a/tests/gateway/test_webapp_owner_identity.py
+++ b/tests/gateway/test_webapp_owner_identity.py
@@ -5,11 +5,13 @@ second owner. So a Webapp tab's Group Chats are native Desktop's (and the revers
older build stored under the tab's ``auth:v1`` login subject are still the owner's, while another OS
user's subject or a messaging identity stays foreign (gateway.owner_identity).
"""
+import json
from types import SimpleNamespace
import pytest
-from gateway.owner_identity import host_owner_subject, owns_row_stamp
+
+from gateway.owner_identity import host_owner_subject, same_owner
from hermes_state import SessionDB
from hermes_state_runtime import begin_runtime_epoch
@@ -69,10 +71,62 @@ async def test_a_room_an_older_build_stored_under_the_login_stays_the_owners(aut
assert (await _call(stranger, 'groups.list'))['rooms'] == []
+OWNER = host_owner_subject()
+WEBAPP_LOGIN = 'auth:v1:["basic","","admin"]'
+
+
@pytest.mark.parametrize('stamp, owned', [
- ('basic:admin', True), ('local:uid:1000', True), ('auth:v1:["self-hosted","https://idp","sub"]', True),
+ ('basic:admin', True), (f'local:{OWNER}', True), ('auth:v1:["self-hosted","https://idp","sub"]', True),
+ ('auth:v1:["local","","' + OWNER + '"]', True),
+ ('local:uid:999999', False), ('auth:v1:["local","","uid:999999"]', False),
('telegram:42', False), ('uid:999999', False), ('nous:account', False), ('auth:v1:["","","x"]', False),
])
-def test_only_sign_in_stamps_read_as_the_owners(stamp, owned):
- assert owns_row_stamp(stamp, host_owner_subject()) is owned
- assert owns_row_stamp(stamp, 'uid:999999') is (stamp == 'uid:999999')
+def test_only_sign_in_stamps_and_this_machines_account_read_as_the_owners(stamp, owned):
+ assert same_owner(stamp, OWNER) is owned
+ assert same_owner(stamp, 'uid:999999') is (stamp == 'uid:999999')
+
+
+def store(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ with SessionDB(tmp_path / 'state.db') as db:
+ yield SimpleNamespace(db=db, profile_id=str(tmp_path), sessions={}, _require_admission_open=lambda: None)
+
+
+def _bind(store, sid, subject, **row):
+ from hermes_state_mutation_binding import BINDING_PREFIX
+ store.db.create_session(sid, **row)
+ binding = json.dumps([store.profile_id, subject], separators=(',', ':'))
+ store.db._execute_write(lambda conn: conn.execute(
+ 'INSERT INTO state_meta(key,value) VALUES(?,?)', (BINDING_PREFIX + sid, binding)))
+
+
+def test_a_chat_a_webapp_tab_imported_before_the_upgrade_still_opens(store):
+ """The sidebar (authorize_history) and the open (mount_history) read a binding by one rule."""
+ from gateway.session_contract import Principal
+ from gateway.session_history_mount import mount_history
+ from hermes_state_mutation_binding import authorize_history
+ caps = frozenset({'session:create', 'session:read'})
+ owner, stranger = (Principal(s, store.profile_id, caps, 't') for s in (OWNER, 'uid:999999'))
+ _bind(store, 'imported-web', WEBAPP_LOGIN, source='webui')
+ with store.db._read_ctx() as conn:
+ assert authorize_history(conn, owner, 'imported-web') is True
+ assert mount_history(store, owner, 'imported-web') is True
+ store.sessions.clear()
+ assert mount_history(store, stranger, 'imported-web') is False
+
+
+def test_an_old_chat_a_webapp_tab_edited_is_adopted_by_the_owner(store):
+ from hermes_state_local_migration import bind_legacy_target
+ from hermes_state_runtime import RuntimeStoreError
+ _bind(store, 'legacy-web', WEBAPP_LOGIN, source='cli')
+
+ def adopt(subject):
+ receipt = {'legacy_session_id': 'legacy-web', 'session_id': 'legacy-web', 'principal_id': subject,
+ 'profile_id': store.profile_id, 'route': 'agent:main:local:dm:legacy-web',
+ 'entry': {'origin': {'platform': 'local', 'chat_id': 'legacy-web', 'user_id': subject}}}
+ store.db._execute_write(lambda conn: bind_legacy_target(store.db, conn, receipt))
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ adopt('uid:999999')
+ adopt(OWNER)
+ assert store.db.get_session('legacy-web')['user_id'] == OWNER