Skip to content

The agent that grows with you

fix(dashboard): forward mutations as the dashboard's authenticated principal

liuhao10240bba83b868c0
diff --git a/gateway/control_socket.py b/gateway/control_socket.py
index a35e92ff100..385f43ace63 100644
--- a/gateway/control_socket.py
+++ b/gateway/control_socket.py
@@ -330,11 +330,18 @@ class GatewayControlServer:
raise PermissionError("invalid bootstrap envelope")
params = request.get("params")
if (not isinstance(params, dict) or not {"profile_id", "instance_id", "purpose"} <= set(params)
- or set(params) - {"profile_id", "instance_id", "purpose", "scope"}):
+ or set(params) - {"profile_id", "instance_id", "purpose", "scope", "subject"}):
raise PermissionError("invalid bootstrap parameters")
if params["instance_id"] != self.ticket_store.instance_id:
raise PermissionError("stale runtime instance")
- ticket = self.ticket_store.mint(profile_id=params["profile_id"], subject=peer_subject,
+ # A verified same-user peer may name the principal it acts for (a standalone dashboard
+ # forwarding a mutation for its authenticated user, #138915): the socket's peer gate
+ # stays the trust boundary — the forwarded subject only relabels who that same peer is,
+ # it never admits a less-verified caller. Anything shaped wrong fails closed.
+ subject = params.get("subject", peer_subject)
+ if not isinstance(subject, str) or not subject or len(subject) > 256:
+ raise PermissionError("invalid bootstrap subject")
+ ticket = self.ticket_store.mint(profile_id=params["profile_id"], subject=subject,
purpose=params["purpose"], scope=params.get("scope", "profile"))
return {"ticket": ticket, "expires_in_seconds": 30,
"instance_id": self.ticket_store.instance_id,
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.py
index 2bc7852e8c4..9c1964fc5aa 100644
--- a/hermes_cli/gateway_client.py
+++ b/hermes_cli/gateway_client.py
@@ -149,14 +149,16 @@ class GatewayClient:
self.pending.pop(rid, None)
-def _session_ticket(home: Path, endpoint, *, purpose="interactive", scope=None) -> str:
+def _session_ticket(home: Path, endpoint, *, purpose="interactive", scope=None, subject=None) -> str:
from hermes_cli.gateway_runtime import control_home_for
from hermes_cli.gateway_runtime_discovery import connect_private, _identify_response
# A served secondary's ticket is minted by the multiplexer's socket, bound to the secondary.
home = control_home_for(home, endpoint)
+ # ``subject`` names the principal a same-user caller acts for (the standalone dashboard's
+ # authenticated user) instead of the socket UID; the owner's peer gate stays the boundary.
request = json.dumps({"protocol": 1, "id": 1, "verb": "session-ticket", "params": {
"profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id, "purpose": purpose,
- **({"scope": scope} if scope else {}),
+ **({"scope": scope} if scope else {}), **({"subject": subject} if subject else {}),
}}).encode() + b"\n"
if os.name == "nt":
from gateway.runtime_bootstrap_windows import query_runtime_control
@@ -184,9 +186,11 @@ def _session_ticket(home: Path, endpoint, *, purpose="interactive", scope=None)
@asynccontextmanager
-async def connect_gateway(endpoint=None):
+async def connect_gateway(endpoint=None, subject=None):
"""Attach to this home's owner. ``endpoint``: an already-discovered ready owner to dial as-is
- (maintenance that must never start a gateway); default ensures one, starting it if needed."""
+ (maintenance that must never start a gateway); default ensures one, starting it if needed.
+ ``subject``: mint the ticket for this principal (the caller's authenticated dashboard user)
+ rather than the socket identity; only a peer the owner already trusts may name one."""
from websockets.asyncio.client import connect
from hermes_constants import get_hermes_home
from hermes_cli.gateway_runtime import attachable, ensure_gateway_runtime
@@ -195,7 +199,8 @@ async def connect_gateway(endpoint=None):
remote = "" if endpoint is not None else os.environ.get("HERMES_TUI_GATEWAY_URL", "").strip()
protocols = None
if endpoint is not None:
- ticket = await asyncio.to_thread(_session_ticket, get_hermes_home().resolve(), endpoint)
+ ticket = await asyncio.to_thread(_session_ticket, get_hermes_home().resolve(), endpoint,
+ subject=subject)
url, protocols = gateway_ws_target(endpoint, ticket)
elif remote:
parsed = urlsplit(remote)
diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.py
index a8ac92ebe85..0a4d07970d4 100644
--- a/hermes_cli/web_server_sessions.py
+++ b/hermes_cli/web_server_sessions.py
@@ -185,7 +185,7 @@ def _mutate_offline_store(profile, actor, params):
return _with_session_maintenance(profile, run)
-async def _mutate_via_gateway_owner(profile, params):
+async def _mutate_via_gateway_owner(profile, actor, params):
"""Forward a standalone dashboard mutation to the live gateway owner.
While a gateway serves the same home, a separately launched ``hermes
@@ -194,6 +194,11 @@ async def _mutate_via_gateway_owner(profile, params):
dies on a bare 409 (#138915). The owner exposes the same revision-fenced
verb over the control socket; with no discoverable owner (or a dial that
died under us) return None so the caller falls back to the offline store.
+
+ The ticket is minted for the dashboard's authenticated principal, not the
+ socket UID: ``authorize_history`` compares the actor subject against the
+ row's stored owner, so a cold row owned by a dashboard account only takes
+ the mutation when the forward acts as that account.
"""
from hermes_cli.gateway_client import GatewayClientError, connect_gateway
from hermes_cli.gateway_runtime import discover_gateway_endpoint
@@ -213,7 +218,7 @@ async def _mutate_via_gateway_owner(profile, params):
if params.get('expected_generation') is not None:
call['expected_generation'] = params['expected_generation']
try:
- async with connect_gateway(endpoint=endpoint) as client:
+ async with connect_gateway(endpoint=endpoint, subject=actor.subject) as client:
return await client.rpc('session.mutate', **call)
except GatewayClientError:
raise
@@ -252,7 +257,7 @@ async def _mutate_session_request(request, profile, session_id, *, request_id,
if authority is None:
# A live gateway owner answers first; only an owner-less home takes
# the offline store (whose reservation loses to that same owner).
- result = await _mutate_via_gateway_owner(profile, params)
+ result = await _mutate_via_gateway_owner(profile, actor, params)
if result is None:
result = await asyncio.to_thread(_mutate_offline_store, profile, actor, params)
else:
diff --git a/tests/gateway/test_control_socket_forwarded_subject.py b/tests/gateway/test_control_socket_forwarded_subject.py
new file mode 100644
index 00000000000..9cc6731fe4e
--- /dev/null
+++ b/tests/gateway/test_control_socket_forwarded_subject.py
@@ -0,0 +1,104 @@
+"""A forwarded mutation acts as the dashboard's authenticated principal, not the socket UID (#138915).
+
+The standalone dashboard's owner-forward mints its ticket over the private control socket, whose
+POSIX/pipe peer gate trusts the same user. The minted grant must carry the dashboard's
+authenticated subject when one is named — ``authorize_history`` compares that subject against a
+cold row's stored owner — while an unverified peer, or a malformed subject, still fails closed.
+"""
+
+import json
+
+from gateway.control_socket import GatewayControlServer
+from gateway.runtime_bootstrap import TicketStore
+
+FORWARDED = 'auth:v1:["basic","","wweic"]'
+
+
+def _server(tmp_path):
+ server = GatewayControlServer(tmp_path)
+ server.ticket_store = TicketStore("inst-1", frozenset({str(tmp_path)}))
+ return server
+
+
+def _mint_line(profile, subject=None, *, with_subject=True):
+ params = {
+ "profile_id": str(profile),
+ "instance_id": "inst-1",
+ "purpose": "interactive",
+ }
+ if with_subject:
+ params["subject"] = subject
+ return json.dumps(
+ {"protocol": 1, "id": 7, "verb": "session-ticket", "params": params}
+ ).encode()
+
+
+def test_a_verified_peer_mints_for_the_named_dashboard_principal(tmp_path):
+ server = _server(tmp_path)
+ response = json.loads(
+ server.handle_request_line(
+ _mint_line(tmp_path, FORWARDED), peer_subject="uid:501"
+ )
+ )
+ assert response["ok"] is True
+ grant = server.ticket_store.redeem(
+ response["result"]["ticket"], profile_id=None, purpose="interactive"
+ )
+ assert grant["subject"] == FORWARDED
+ # authorize_history's capability gate: the forwarded actor must still carry it.
+ assert "session:create" in grant["capabilities"]
+
+
+def test_an_unverified_peer_cannot_name_a_principal(tmp_path):
+ response = json.loads(
+ _server(tmp_path).handle_request_line(
+ _mint_line(tmp_path, FORWARDED), peer_subject=None
+ )
+ )
+ assert response["ok"] is False
+ assert "authenticated runtime bootstrap unavailable" in response["error"]
+
+
+def test_a_malformed_forwarded_subject_fails_closed(tmp_path):
+ for bad in ("", "x" * 257, 501, None):
+ response = json.loads(
+ _server(tmp_path).handle_request_line(
+ _mint_line(tmp_path, bad), peer_subject="uid:501"
+ )
+ )
+ assert response["ok"] is False, bad
+ assert "invalid bootstrap subject" in response["error"]
+
+
+def test_a_forwarded_subject_matching_the_row_owner_takes_the_mutation(tmp_path):
+ """The reviewer-repro shape: a stored ``desktop`` row owned by a dashboard account is
+ deletable by a forwarded actor acting as that account, and refused for any other."""
+ from gateway.session_contract import Principal
+ from hermes_state import SessionDB
+ from hermes_state_mutation_binding import authorize_history
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ db.create_session("cold-desktop", source="desktop", user_id=FORWARDED)
+ same = Principal(
+ FORWARDED,
+ str(tmp_path),
+ frozenset({"session:read", "session:create"}),
+ "native-http:x",
+ )
+ other = Principal(
+ 'auth:v1:["basic","","someone-else"]',
+ str(tmp_path),
+ frozenset({"session:read", "session:create"}),
+ "native-http:y",
+ )
+ with db._read_ctx() as conn:
+ assert authorize_history(conn, same, "cold-desktop") is True
+ try:
+ authorize_history(conn, other, "cold-desktop")
+ except Exception as exc:
+ assert getattr(exc, "reason", None) == "permission_denied"
+ else:
+ raise AssertionError("a foreign principal must not take the mutation")
+ finally:
+ db.close()
diff --git a/tests/hermes_cli/test_web_server_session_owner_forward.py b/tests/hermes_cli/test_web_server_session_owner_forward.py
index 9bd02f7fdeb..d7747b5f8a0 100644
--- a/tests/hermes_cli/test_web_server_session_owner_forward.py
+++ b/tests/hermes_cli/test_web_server_session_owner_forward.py
@@ -45,8 +45,9 @@ async def test_standalone_mutation_forwards_to_the_live_owner(tmp_path, monkeypa
return {'session_id': params['session_id'], 'operation': 'delete', 'revision': 1}
@asynccontextmanager
- async def fake_connect(endpoint=None):
+ async def fake_connect(endpoint=None, subject=None):
calls['endpoint'] = endpoint
+ calls['subject'] = subject
yield FakeClient()
offline = []
@@ -63,6 +64,9 @@ async def test_standalone_mutation_forwards_to_the_live_owner(tmp_path, monkeypa
# Discovery resolved the selected home's owner; the offline store never opened.
assert seen['home'] == tmp_path.resolve()
assert calls['endpoint'] == 'owner-endpoint'
+ # The ticket names the dashboard's authenticated principal — the socket UID would be
+ # refused by authorize_history on any row that stores an owner.
+ assert calls['subject'] == 'auth:v1:["oidc","https://idp.example","user-a"]'
method, params = calls['rpc']
assert method == 'session.mutate'
assert params == {'session_id': 'session-1', 'request_id': 'req-1', 'expected_revision': 0,
@@ -103,7 +107,7 @@ async def test_owner_dial_failure_falls_back_to_the_offline_store(tmp_path, monk
_discover(monkeypatch, 'owner-endpoint')
@asynccontextmanager
- async def dying_connect(endpoint=None):
+ async def dying_connect(endpoint=None, subject=None):
raise FileNotFoundError('owner control socket vanished')
yield # pragma: no cover
@@ -130,7 +134,7 @@ async def test_owner_refusal_maps_to_the_matching_http_status(tmp_path, monkeypa
_discover(monkeypatch, 'owner-endpoint')
@asynccontextmanager
- async def refusing_connect(endpoint=None):
+ async def refusing_connect(endpoint=None, subject=None):
class Refuser:
async def rpc(self, method, **params):
raise GatewayClientError('permission_denied')