hermes_state_mutation_binding.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """Control-only ownership for unbound legacy history; never an execution policy."""
  2. import json
  3. from hermes_state_runtime import RuntimeStoreError
  4. BINDING_PREFIX = 'gateway.history_control.v1.'
  5. def _history_row(row):
  6. """Local surfaces' unrouted rows are owner history: every row the native resume adopts
  7. (``legacy_history_row``: old ``desktop`` chats, ``oneshot``/``tool`` CLI runs and phone apps'
  8. self-labelled chats too) plus imports. A row resume can adopt must also take a sidebar edit
  9. (pin/archive/hide/rename)."""
  10. from hermes_state_local_migration import legacy_history_row
  11. return row['source'] == 'import' or legacy_history_row(dict(row))
  12. def _owner_user(row):
  13. """The row's owner identity; main's Desktop Nous-account label is not one (see validate_legacy_row)."""
  14. from hermes_state_local_migration import legacy_account_label
  15. return None if legacy_account_label(dict(row)) else row['user_id']
  16. def _login_label(subject):
  17. """The ``<provider>:<user>`` label Desktop stamps on its rows (tui_gateway/session_transports.py) when it
  18. names exactly the dashboard subject ``auth:v1:[provider, "", user]`` (gateway/session_identity.py).
  19. Only an issuer-less login maps: the label drops the issuer, so an issuer-bearing subject must not claim it."""
  20. from gateway.session_identity import parse_authenticated_subject
  21. parts = parse_authenticated_subject(subject)
  22. if parts is None:
  23. return None
  24. provider, issuer, user = parts
  25. if issuer or ':' in provider or not provider.strip() or not user.strip():
  26. return None
  27. label = f'{provider.strip()}:{user.strip()}'
  28. # Never yield something that reads as a subject itself (a provider named ``auth`` + user ``v1:[...]``).
  29. return None if label.startswith('auth:') else label
  30. def binding_names(saved, profile_id, subject):
  31. """Whether a stored ``[profile_id, subject]`` binding names *subject* in *profile_id*: same profile,
  32. and the same owner (a binding a Webapp login stored belongs to the machine owner,
  33. gateway.owner_identity.same_owner). Every reader of a binding asks this, never a string compare."""
  34. try:
  35. saved_profile, saved_subject = json.loads(saved)
  36. except (TypeError, ValueError):
  37. return False
  38. from gateway.owner_identity import same_owner
  39. return saved_profile == profile_id and same_owner(saved_subject, subject)
  40. def _bound_to(saved, actor):
  41. return binding_names(saved, actor.profile_id, actor.subject)
  42. def _bindings_agree(first, second):
  43. """Two stored bindings name the same owner (both absent agrees; one absent does not)."""
  44. if first == second or first is None or second is None:
  45. return first == second
  46. try:
  47. (first_profile, first_subject), (profile_id, subject) = json.loads(first), json.loads(second)
  48. except (TypeError, ValueError):
  49. return False
  50. from gateway.owner_identity import owners_agree
  51. return first_profile == profile_id and owners_agree(first_subject, subject)
  52. def import_history_control(conn, actor, session_ids):
  53. binding = json.dumps([actor.profile_id, actor.subject], separators=(',', ':'))
  54. for sid in session_ids:
  55. if conn.execute('SELECT 1 FROM sessions WHERE id=?', (sid,)).fetchone() is None:
  56. conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (BINDING_PREFIX + sid, binding))
  57. def authorize_history(conn, actor, session_id, *, claim=False):
  58. row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
  59. if row is None:
  60. return False
  61. # Import intentionally strips routes. Never reinterpret a cold native/API
  62. # transcript as imported history, even if stale import metadata exists.
  63. if row['session_key'] or row['chat_id'] or row['origin_json']:
  64. return False
  65. key = BINDING_PREFIX + session_id
  66. binding = json.dumps([actor.profile_id, actor.subject], separators=(',', ':'))
  67. saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
  68. if saved is not None:
  69. if not _bound_to(saved[0], actor):
  70. raise RuntimeStoreError('permission_denied')
  71. return True
  72. if not _history_row(row):
  73. return False
  74. from gateway.owner_identity import same_owner
  75. if _owner_user(row) and not same_owner(row['user_id'], actor.subject):
  76. raise RuntimeStoreError('permission_denied')
  77. if 'session:create' not in actor.capabilities:
  78. raise RuntimeStoreError('permission_denied')
  79. if claim:
  80. conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, binding))
  81. return True
  82. def history_binding(conn, session_id):
  83. saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (BINDING_PREFIX + session_id,)).fetchone()
  84. return saved[0] if saved else None
  85. def same_history_owner(conn, anchor_id, session_id):
  86. """Whether chain member ``session_id`` is history the authorizer of ``anchor_id`` controls.
  87. A real compression continuation copies its parent's route columns, so a routed member must
  88. carry the anchor's exact (user_id, session_key, chat_id). A routeless member needs the
  89. anchor's exact import binding; unbound, it must also pass :func:`authorize_history`'s local
  90. rule (local source, no foreign user_id) — e.g. the pre-adoption ancestors of an adopted
  91. legacy CLI conversation — or share an unbound routeless anchor's source (an old cron run's or
  92. subagent's own compression chain, mounted as one chat). A bound (imported) anchor therefore
  93. never reaches unbound rows.
  94. """
  95. columns = 'SELECT source,user_id,session_key,chat_id,origin_json FROM sessions WHERE id=?'
  96. anchor, row = (conn.execute(columns, (sid,)).fetchone() for sid in (anchor_id, session_id))
  97. if anchor is None or row is None:
  98. return False
  99. if row['session_key'] or row['chat_id'] or row['origin_json']:
  100. return tuple(row)[1:4] == tuple(anchor)[1:4]
  101. binding = history_binding(conn, session_id)
  102. if not _bindings_agree(binding, history_binding(conn, anchor_id)):
  103. return False
  104. routeless_peer = row['source'] == anchor['source'] and not any(tuple(anchor)[2:5])
  105. from gateway.owner_identity import owners_agree
  106. return binding is not None or (
  107. (_history_row(row) or routeless_peer)
  108. and (_owner_user(row) in (None, '') or owners_agree(_owner_user(row), anchor['user_id'])))