Skip to content

The agent that grows with you

refactor(gateway): parse the auth:v1 login subject in one place

Tekniumcdfc0a535496
diff --git a/gateway/control_socket.py b/gateway/control_socket.py
index a12734a9fb8..9a229844df7 100644
--- a/gateway/control_socket.py
+++ b/gateway/control_socket.py
@@ -133,13 +133,8 @@ def _structured_login_subject(value: str) -> bool:
``auth:v1:[provider, issuer, user]`` (gateway.session_identity) — the only identity
a same-user peer may forward a ticket for. Bare labels (``admin``, ``uid:501``) fail:
they can collide with another stored owner representation."""
- if not value.startswith('auth:v1:'):
- return False
- try:
- parts = json.loads(value[len('auth:v1:'):])
- except ValueError:
- return False
- return isinstance(parts, list) and len(parts) == 3 and all(isinstance(p, str) for p in parts)
+ from gateway.session_identity import parse_authenticated_subject
+ return parse_authenticated_subject(value) is not None
def launch_supervisor(identity: dict[str, Any]) -> Optional[str]:
diff --git a/gateway/session_identity.py b/gateway/session_identity.py
index 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/hermes_state_mutation_binding.py b/hermes_state_mutation_binding.py
index c7c7048b2a4..07b964d3b7c 100644
--- a/hermes_state_mutation_binding.py
+++ b/hermes_state_mutation_binding.py
@@ -23,13 +23,9 @@ 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."""
- if not isinstance(subject, str) or not subject.startswith('auth:v1:'):
- return None
- try:
- parts = json.loads(subject[len('auth:v1:'):])
- except ValueError:
- return None
- if not (isinstance(parts, list) and len(parts) == 3 and all(isinstance(p, str) for p in parts)):
+ 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():
diff --git a/tests/hermes_state/test_history_login_label.py b/tests/hermes_state/test_history_login_label.py
index 4bdd3880e5a..1378325c4d8 100644
--- a/tests/hermes_state/test_history_login_label.py
+++ b/tests/hermes_state/test_history_login_label.py
@@ -78,3 +78,31 @@ def test_an_issuer_bearing_login_cannot_touch_the_labelled_row(db):
def test_an_unowned_row_still_admits_any_local_actor(db):
db.create_session("unowned-row", source="desktop")
assert _auth(db, LOGIN, "unowned-row") is True
+
+
+def test_one_parser_reads_the_login_subject_for_every_caller():
+ """``authenticated_subject``'s format is parsed in one place: the control socket's
+ forwarded-subject gate and the login label both use its checked result."""
+ from gateway.control_socket import _structured_login_subject
+ from gateway.session_identity import authenticated_subject, parse_authenticated_subject
+
+ subject = authenticated_subject({'provider': 'basic', 'issuer': '', 'user_id': 'e2e'})
+ assert parse_authenticated_subject(subject) == ('basic', '', 'e2e')
+ for bad in ('uid:501', 'auth:v1:"basic"', 'auth:v1:[1,2,3]', 'auth:v1:["a","b"]', 'auth:v1:[', None, 7):
+ assert parse_authenticated_subject(bad) is None
+ assert _login_label(bad) is None
+ if isinstance(bad, str):
+ assert _structured_login_subject(bad) is False
+ assert _structured_login_subject(subject) is True
+
+
+def test_a_forwarded_bob_cannot_mutate_a_row_bound_to_alice(db):
+ """F1 guard: a dashboard login ``bob`` (forwarded ``auth:v1:["basic","",bob]``) is refused on
+ a Desktop row stamped ``basic:alice``, cannot claim it, and alice still owns it afterwards."""
+ alice, bob = 'auth:v1:["basic","","alice"]', 'auth:v1:["basic","","bob"]'
+ db.create_session("alice-row", source="desktop", user_id="basic:alice")
+ with db._read_ctx() as conn:
+ with pytest.raises(Exception) as raised:
+ authorize_history(conn, _actor(bob, db.db_path.parent), "alice-row", claim=True)
+ assert getattr(raised.value, "reason", None) == "permission_denied"
+ assert authorize_history(conn, _actor(alice, db.db_path.parent), "alice-row") is True