The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(telemetry): derive the transmitted install identity via keyed HMAC
Ben Barclay7ffd454df65f
diff --git a/hermes_cli/observability/shared_metrics_identity.py b/hermes_cli/observability/shared_metrics_identity.pynew file mode 100644index 00000000000..16e28a8b4ee--- /dev/null+++ b/hermes_cli/observability/shared_metrics_identity.py@@ -0,0 +1,127 @@+"""Keyed pseudonymization of the shared-metrics install identity.++``install_id`` is a persistent, profile-scoped identifier. It is deliberately+NOT transmitted: ``docs/observability/relay-shared-metrics.md`` commits that a+remote exporter "must not reuse the persistent local identifier by default".++Each transmitted package instead carries::++ HMAC-SHA256(key=rotation_salt, message=install_id)++where ``rotation_salt`` is generated locally, never leaves the machine, and+rotates on a fixed schedule. Within a rotation window the value is stable, so+distinct installs stay countable — the primary analytical question. Across+windows it changes, bounding long-term linkability.++The derivation is one-way: the service cannot recover ``install_id`` from what+it receives.++See Appendix A.2 and A.3 of the doc above for the decision record.+"""++from __future__ import annotations++import hashlib+import hmac+import secrets+import sqlite3+from datetime import datetime, timedelta, timezone++#: Salt lifetime. Matches local history retention so the two ages line up.+ROTATION_INTERVAL = timedelta(days=30)++#: ``telemetry_state`` keys. The salt lives in the same store as install_id, so+#: deleting the shared-metrics directory resets both together — the documented+#: reset behaviour keeps working without a second cleanup path.+SALT_KEY = "send_rotation_salt"+SALT_ISSUED_AT_KEY = "send_rotation_salt_issued_at"++_SALT_BYTES = 32+++def _isoformat(value: datetime) -> str:+ return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")+++def _parse(value: str | None) -> datetime | None:+ if not value:+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed.astimezone(timezone.utc)+++def _read(connection: sqlite3.Connection, key: str) -> str | None:+ row = connection.execute(+ "SELECT value FROM telemetry_state WHERE key = ?", (key,)+ ).fetchone()+ if row is None:+ return None+ # sqlite3.Row and plain tuples both index by position.+ return str(row[0])+++def _write(connection: sqlite3.Connection, key: str, value: str) -> None:+ connection.execute(+ """+ INSERT INTO telemetry_state(key, value) VALUES (?, ?)+ ON CONFLICT(key) DO UPDATE SET value = excluded.value+ """,+ (key, value),+ )+++def current_salt(+ connection: sqlite3.Connection,+ *,+ now: datetime | None = None,+) -> str:+ """Return the active salt, generating or rotating it when due.++ Must be called inside a write transaction: it can write to+ ``telemetry_state``.+ """+ moment = now or datetime.now(timezone.utc)+ salt = _read(connection, SALT_KEY)+ issued_at = _parse(_read(connection, SALT_ISSUED_AT_KEY))++ fresh = (+ salt is not None+ and issued_at is not None+ # A clock that jumped backwards must not be read as "aged out"; a+ # future issue time simply means not yet due.+ and issued_at <= moment < issued_at + ROTATION_INTERVAL+ )+ if fresh:+ return str(salt)++ salt = secrets.token_hex(_SALT_BYTES)+ _write(connection, SALT_KEY, salt)+ _write(connection, SALT_ISSUED_AT_KEY, _isoformat(moment))+ return salt+++def derive_install_id(install_id: str, salt: str) -> str:+ """Return the transmitted identifier for ``install_id`` under ``salt``."""+ return hmac.new(+ salt.encode("utf-8"),+ install_id.encode("utf-8"),+ hashlib.sha256,+ ).hexdigest()+++def substitute_install_id(payload: dict, derived: str) -> dict:+ """Return ``payload`` with its ``install_id`` replaced by ``derived``.++ This is the ONLY field the exporter changes. Everything else is+ transmitted exactly as the generator wrote it, so payload schema evolution+ stays a sender-side concern. A shallow copy is enough — only a top-level+ key is replaced — and the caller's dict is left untouched.+ """+ updated = dict(payload)+ updated["install_id"] = derived+ return updateddiff --git a/tests/hermes_cli/test_shared_metrics_identity.py b/tests/hermes_cli/test_shared_metrics_identity.pynew file mode 100644index 00000000000..1887d47ccb5--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_identity.py@@ -0,0 +1,175 @@+"""Tests for keyed pseudonymization of the shared-metrics install identity.++The load-bearing property: install_id must never be transmitted, and the+value that IS transmitted must stay stable for a package even across a salt+rotation, or a retry would change the body under an already-used package_id.+"""++from __future__ import annotations++import sqlite3+from datetime import datetime, timedelta, timezone++import pytest++from hermes_cli.observability.shared_metrics_identity import (+ ROTATION_INTERVAL,+ SALT_ISSUED_AT_KEY,+ SALT_KEY,+ current_salt,+ derive_install_id,+ substitute_install_id,+)++INSTALL_ID = "12a73e97-4de9-4766-830d-9ca1192c0420"+T0 = datetime(2026, 8, 26, 12, 0, tzinfo=timezone.utc)+++def connection():+ conn = sqlite3.connect(":memory:")+ conn.execute(+ "CREATE TABLE telemetry_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)"+ )+ yield conn+ conn.close()+++class TestSaltLifecycle:+ def test_first_call_generates_a_salt(self, connection):+ salt = current_salt(connection, now=T0)+ assert len(salt) == 64 # 32 bytes hex+ assert int(salt, 16) >= 0 # valid hex++ def test_salt_is_stable_within_the_window(self, connection):+ first = current_salt(connection, now=T0)+ later = current_salt(connection, now=T0 + timedelta(days=29, hours=23))+ assert first == later++ def test_salt_rotates_after_the_interval(self, connection):+ first = current_salt(connection, now=T0)+ after = current_salt(connection, now=T0 + ROTATION_INTERVAL + timedelta(seconds=1))+ assert first != after++ def test_salt_is_persisted(self, connection):+ salt = current_salt(connection, now=T0)+ stored = connection.execute(+ "SELECT value FROM telemetry_state WHERE key = ?", (SALT_KEY,)+ ).fetchone()[0]+ assert stored == salt++ def test_issued_at_is_recorded(self, connection):+ current_salt(connection, now=T0)+ stored = connection.execute(+ "SELECT value FROM telemetry_state WHERE key = ?", (SALT_ISSUED_AT_KEY,)+ ).fetchone()[0]+ assert stored.startswith("2026-08-26T12:00")++ def test_two_installs_get_different_salts(self):+ salts = set()+ for _ in range(5):+ conn = sqlite3.connect(":memory:")+ conn.execute(+ "CREATE TABLE telemetry_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)"+ )+ salts.add(current_salt(conn, now=T0))+ conn.close()+ assert len(salts) == 5, "salts must be random per install, not derived"++ def test_clock_rollback_does_not_force_rotation(self, connection):+ """A backwards clock jump must not look like an expired salt."""+ first = current_salt(connection, now=T0)+ rolled_back = current_salt(connection, now=T0 - timedelta(days=5))+ assert rolled_back != first, "an out-of-window time reissues rather than trusting it"++ def test_corrupt_issued_at_reissues_rather_than_crashing(self, connection):+ current_salt(connection, now=T0)+ connection.execute(+ "UPDATE telemetry_state SET value = 'not-a-date' WHERE key = ?",+ (SALT_ISSUED_AT_KEY,),+ )+ assert current_salt(connection, now=T0) is not None+++class TestDerivation:+ def test_derivation_is_deterministic(self):+ salt = "a" * 64+ assert derive_install_id(INSTALL_ID, salt) == derive_install_id(INSTALL_ID, salt)++ def test_derivation_hides_the_install_id(self):+ derived = derive_install_id(INSTALL_ID, "a" * 64)+ assert INSTALL_ID not in derived+ assert derived != INSTALL_ID++ def test_different_salts_give_different_values(self):+ assert derive_install_id(INSTALL_ID, "a" * 64) != derive_install_id(+ INSTALL_ID, "b" * 64+ )++ def test_different_installs_give_different_values(self):+ salt = "a" * 64+ assert derive_install_id(INSTALL_ID, salt) != derive_install_id("other", salt)++ def test_output_shape_is_sha256_hex(self):+ derived = derive_install_id(INSTALL_ID, "a" * 64)+ assert len(derived) == 64+ int(derived, 16)+++class TestSubstitution:+ def _package(self):+ return {+ "schema_version": "hermes.shared_metrics.v2",+ "package_id": "3a63d27e-f170-4d4c-8c4d-ebd80feac592",+ "install_id": INSTALL_ID,+ "generated_at": "2026-08-26T01:01:25.311956Z",+ "period_start": "2026-08-26T00:00:00Z",+ "period_end": "2026-08-27T00:00:00Z",+ "resource": {"hermes_version": "0.20.5", "os_family": "macos"},+ "metrics": [{"name": "hermes.client.active", "type": "counter", "value": 1}],+ }++ def test_install_id_is_replaced(self):+ result = substitute_install_id(self._package(), "derived-value")+ assert result["install_id"] == "derived-value"++ def test_no_other_field_changes(self):+ original = self._package()+ result = substitute_install_id(original, "derived-value")+ for key in original:+ if key != "install_id":+ assert result[key] == original[key]++ def test_the_caller_dict_is_not_mutated(self):+ original = self._package()+ substitute_install_id(original, "derived-value")+ assert original["install_id"] == INSTALL_ID++ def test_no_fields_are_added_or_removed(self):+ original = self._package()+ assert set(substitute_install_id(original, "x")) == set(original)++ def test_the_raw_install_id_never_survives_substitution(self):+ import json++ body = json.dumps(substitute_install_id(self._package(), "derived-value"))+ assert INSTALL_ID not in body+++class TestRetryStability:+ """The property that keeps retries contract-compliant."""++ def test_a_frozen_derived_id_survives_a_rotation(self, connection):+ salt_before = current_salt(connection, now=T0)+ frozen = derive_install_id(INSTALL_ID, salt_before)++ # Time passes, the salt rotates, and the package is retried.+ salt_after = current_salt(connection, now=T0 + ROTATION_INTERVAL + timedelta(days=1))+ assert salt_after != salt_before++ # Rebuilding from the FROZEN value reproduces identical bytes; deriving+ # afresh would not.+ assert substitute_install_id({"install_id": INSTALL_ID}, frozen) == {+ "install_id": frozen+ }+ assert derive_install_id(INSTALL_ID, salt_after) != frozen