gabriel / musehub public
test_doc_identity.py python
352 lines 19.7 KB
Raw
sha256:580949619fa19ce11fb2e0fd9ebd2e95707a8db352a8586382e0707b2a4a78a9 docs: follow Muse 0.2.2rc7 — shelf list --tag, shelf_size a… Opus 5.5 minor ⚠ breaking 1 day ago
1 """DOC_ID — /muse/identity contract (musehub#246, QA contract v2).
2
3 Every claim below was checked against muse 0.2.1rc20 (muse ``dev`` 5becda10) in a disposable
4 sandbox on 2026-11-07 (sandbox HOME, file keyring, unresolvable hub). The page's figure and sample
5 values are computed by muse's own functions (``ui_docs._ID_*``); these tests re-derive them from the
6 formulas the page documents, so a change to either the engine or the page fails here. Known product
7 defects stay documented as contract plus warning (#241 defect-preservation rule): each is pinned by a
8 strict xfail that flips when the defect is fixed, so the warning must be removed in the same change.
9
10 DOC_ID_01 (commands parse), _02 (anchors) and _03 (URL scheme) are the #242 checkers
11 (test_doc_inf_cli.py, test_doc_inf_registry.py, test_doc_inf_scheme.py). No database is used.
12 """
13
14 from __future__ import annotations
15
16 import base64
17 import hashlib
18 import html as html_lib
19 import importlib
20 import re
21 from datetime import datetime, timezone
22
23 import pytest
24 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
25 from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
26
27 from muse.core import hdkeys, msign
28 from muse.core.transport import SigningIdentity
29 from musehub.api.routes.musehub import ui_docs
30 from tests.docs_contract import registry_check as rc
31
32 pytestmark = pytest.mark.no_db
33
34 PAGE = rc.phase_path("identity")
35 MUSE_ISSUES = "https://staging.musehub.ai/gabriel/muse/issues/"
36
37 # Product tickets the page's known-defect warnings link to (filed under #246, assigned to gabriel).
38 _T_AGENT = "163" # agent key derivations disagree (KEY_FD vs keygen/register); agent keygen output
39 _T_RECOVER = "164" # recover restores rotation index 0 and no handle
40 _T_MPAY = "165" # sign payment vs hub MPay canonical message and output
41
42
43 def _h(n: str) -> int:
44 """The page's hash-to-index formula: int.from_bytes(sha256(name)[:4], "big") & 0x7FFFFFFF."""
45 return int.from_bytes(hashlib.sha256(n.encode()).digest()[:4], "big") & 0x7FFFFFFF
46
47
48 @pytest.fixture(scope="module")
49 def html(rendered: dict[str, str]) -> str:
50 return html_lib.unescape(rendered[PAGE])
51
52
53 @pytest.fixture(scope="module")
54 def text(html: str) -> str:
55 return " ".join(re.sub(r"<[^>]+>", "", html).split())
56
57
58 def _pre_after(html: str, label: str) -> str:
59 rest = html.split(label, 1)[1]
60 return re.sub(r"<[^>]+>", "", rest.split("<pre>", 1)[1].split("</pre>", 1)[0])
61
62
63 def _profile_routes() -> set[tuple[str, str]]:
64 """(method, full path) of the routes the profiles router mounts (prefix included, as main.py mounts it)."""
65 from musehub.api.routes.api.profiles import router
66
67 return {(m, r.path) for r in router.routes for m in getattr(r, "methods", ()) or ()}
68
69
70 def _pub(dk: object) -> bytes:
71 return hdkeys.dk_to_ed25519(dk).public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
72
73
74 # ── DOC_ID_04: MSign canonical message and header ──────────────────────────────
75
76 def test_doc_id_04_canonical_message_example_is_what_client_and_hub_sign(html: str) -> None:
77 """The page's example is byte-identical to muse's and the hub's canonical message."""
78 from musehub.auth.request_signing import build_canonical_message
79
80 shown = _pre_after(html, "example — GET /api/auth/keys/gabriel (no body)").strip()
81 client = msign.canonical_message("GET", "/api/auth/keys/gabriel", 1744000000, b"", host="staging.musehub.ai")
82 hub = build_canonical_message("GET", "/api/auth/keys/gabriel", 1744000000, b"", host="staging.musehub.ai")
83 assert shown.encode() == client == hub
84 assert shown.splitlines()[-1] == "sha256:" + hashlib.sha256(b"").hexdigest()
85 fmt = _pre_after(html, "canonical message (newline-separated, UTF-8)").strip().splitlines()
86 assert fmt == ["{algorithm}", "{METHOD}", "{host}", "{path_with_query}", "{unix_timestamp}",
87 "sha256:{hex(sha256(request_body))}"]
88
89
90 def test_doc_id_04_python_signing_sample_round_trips() -> None:
91 """build_msign_header / verify_msign_header as the page calls them; tampering any signed field fails."""
92 key = Ed25519PrivateKey.from_private_bytes(bytes(range(32)))
93 pk = base64.urlsafe_b64encode(key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)).rstrip(b"=").decode()
94 url = "https://staging.musehub.ai/api/auth/keys/gabriel"
95 header = msign.build_msign_header(SigningIdentity(handle="gabriel", private_key=key), "GET", url, b"")
96 assert re.fullmatch(r'MSign handle="gabriel" alg="ed25519" ts=\d+ sig="[A-Za-z0-9_-]{86}"', header)
97 assert msign.verify_msign_header(header, "GET", url, b"", pk) == (True, "ok")
98 for method, u, body in (("POST", url, b""), ("GET", url + "x", b""), ("GET", url, b"x"),
99 ("GET", url.replace("staging.", ""), b"")):
100 assert msign.verify_msign_header(header, method, u, body, pk)[0] is False
101 ts = int(header.split("ts=")[1].split()[0])
102 assert msign.verify_msign_header(header, "GET", url, b"", pk, now=ts + 30)[0] is True
103 assert msign.verify_msign_header(header, "GET", url, b"", pk, now=ts + 31)[0] is False
104 assert msign.verify_msign_header(header, "GET", url, b"", pk, now=ts - 31)[0] is False
105
106
107 # ── DOC_ID_05: MPay (ID-11) ────────────────────────────────────────────────────
108
109 def test_doc_id_05_mpay_routes_on_the_page_exist(html: str) -> None:
110 routes = _profile_routes()
111 assert ("POST", "/api/profiles/{handle}/mpay-claims") in routes
112 assert ("GET", "/api/profiles/{handle}/mpay-ledger") in routes
113 assert "/mpay/claim" not in html and "/mpay/ledger" not in html
114 assert "/api/profiles/alice/mpay-claims" in html and "/api/profiles/gabriel/mpay-ledger" in html
115
116
117 def test_doc_id_05_mpay_response_examples_use_the_wire_field_names(html: str) -> None:
118 from musehub.models.musehub import MPayClaimResponse, MPayLedgerResponse
119
120 resp = re.findall(r'"(\w+)":', _pre_after(html, "MPayClaimResponse — HTTP 201"))
121 assert resp == [f.alias or n for n, f in MPayClaimResponse.model_fields.items()]
122 ledger = _pre_after(html, "GET /api/profiles/gabriel/mpay-ledger — response")
123 top = [k for k in re.findall(r'^ "(\w+)":', ledger, re.M)]
124 assert top == [f.alias or n for n, f in MPayLedgerResponse.model_fields.items()]
125 for nonce in re.findall(r'"nonce(?:_hex|Hex)":\s*"([0-9a-f]+)"', html):
126 assert len(nonce) == 64
127
128
129 def test_doc_id_05_sign_payment_output_on_the_page_matches_the_cli() -> None:
130 """The page shows the 0.2.1rc20 output keys of `muse sign payment --json` (minus the envelope)."""
131 key = Ed25519PrivateKey.from_private_bytes(bytes(range(32)))
132 claim = msign.build_payment_claim(SigningIdentity("gabriel", key), "gabriel", "alice", 1_000_000, "nanoMUSE",
133 "a" * 64, "", ts=1744000000)
134 assert claim["canonical_message"] == f"MPAY\ngabriel\nalice\n1000000\nnanoMUSE\n{'a' * 64}\n\n1744000000"
135 assert {"from_handle", "to_handle", "amount_nano", "currency", "nonce_hex", "memo", "ts", "signature_b64",
136 "canonical_message"} <= set(claim)
137 assert "claim_request" not in claim # pinned: the known defect the page warns about
138
139
140 @pytest.mark.xfail(strict=True, reason=f"gabriel/muse#{_T_MPAY}: client signs 8 lines, hub verifies 5")
141 def test_doc_id_05_a_cli_signed_claim_verifies_on_the_hub() -> None:
142 """The documented flow: what `muse sign payment` signs must verify with the hub's MPay check."""
143 from muse.core.types import encode_pubkey, encode_sig
144 from musehub.services.musehub_mpay import verify_mpay_signature
145
146 key = Ed25519PrivateKey.from_private_bytes(bytes(range(32)))
147 claim = msign.build_payment_claim(SigningIdentity("gabriel", key), "gabriel", "alice", 1_000_000, "nanoMUSE",
148 "a" * 64, "", ts=1744000000)
149 sig = encode_sig("ed25519", base64.urlsafe_b64decode(claim["signature_b64"] + "=="))
150 pk = encode_pubkey("ed25519", key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))
151 assert verify_mpay_signature("gabriel", "alice", 1_000_000, "a" * 64, sig, pk) == (True, "")
152
153
154 # ── DOC_ID_07: V1 HD derivation figure ─────────────────────────────────────────
155
156 def test_doc_id_07_figure_paths_follow_the_documented_formulas() -> None:
157 purpose, ident = _h("muse"), _h("muse/identity")
158 assert (purpose, ident) == (1075233755, hdkeys.DOMAIN_IDENTITY)
159 hub, hub2 = _h("musehub.ai"), _h("staging.musehub.ai")
160 yours, agents = ui_docs._ID_YOURS, ui_docs._ID_AGENTS
161 vals = [[s.value for s in k.segments] for k in yours]
162 assert vals[0] == [f"{purpose}'", f"{ident}'", "0'", "0'", "0'", f"{hub}'", "0'"]
163 assert vals[1] == vals[0][:6] + ["1'"] and vals[2] == vals[0][:5] + [f"{hub2}'", "0'"]
164 assert [[s.changed for s in k.segments].count(True) for k in yours] == [0, 1, 1]
165 slot = _h("claude-code")
166 assert slot == hdkeys.agent_id_to_slot("claude-code")
167 assert [s.value for s in agents[0].segments] == [f"{purpose}'", f"{ident}'", "1'", f"{slot}'"]
168 assert agents[1].root == agents[2].root == "sub-seed"
169
170
171 def test_doc_id_07_figure_public_keys_are_muse_derivations() -> None:
172 from muse.core.keypair import derive_agent_identity_key
173 from muse.core.types import encode_pubkey
174
175 seed, hub = ui_docs._ID_SEED, hdkeys.hub_index("musehub.ai")
176 short = lambda raw: encode_pubkey("ed25519", raw)[:18] + "…" # noqa: E731
177 yours = ui_docs._ID_YOURS
178 assert yours[0].public_key == short(_pub(hdkeys.derive_identity_key(seed, hub=hub)))
179 assert yours[1].public_key == short(_pub(hdkeys.derive_identity_key(seed, hub=hub, index=1)))
180 assert yours[2].public_key == short(_pub(hdkeys.derive_identity_key(seed, hub=hdkeys.hub_index("staging.musehub.ai"))))
181 assert len({k.public_key for k in yours}) == 3
182 agent = derive_agent_identity_key(seed, "claude-code", hub).public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
183 assert ui_docs._ID_AGENTS[1].public_key == short(agent) # the key keygen --agent-id / register use
184 sub = hdkeys.derive_agent_sub_seed(seed, domain=hdkeys.DOMAIN_IDENTITY, agent_id=hdkeys.agent_id_to_slot("claude-code"))
185 from muse.core.slip010 import derive_path
186
187 node = derive_path(seed, f"m/1075233755'/{hdkeys.DOMAIN_IDENTITY}'/1'/{hdkeys.agent_id_to_slot('claude-code')}'")
188 assert bytes(sub) == bytes(node.private_bytes) + bytes(node.chain_code) # the sub-seed is that node
189
190
191 @pytest.mark.xfail(strict=True, reason=f"gabriel/muse#{_T_AGENT}: KEY_FD derives with entity type agent")
192 def test_doc_id_07_an_injected_sub_seed_signs_with_the_registered_agent_key() -> None:
193 """The page's injection sequence must yield the key `muse auth keygen --agent-id` registers."""
194 agents = ui_docs._ID_AGENTS
195 assert agents[2].public_key == agents[1].public_key
196
197
198 def test_doc_id_07_figure_renders_accessibly(html: str) -> None:
199 fig = html.split('id="hd-tree"', 1)[1].split("</figure>", 1)[0]
200 assert 'aria-labelledby="hd-tree-title"' in html and "One seed, isolated keys" in fig
201 changed = sum(s.changed for k in ui_docs._ID_YOURS + ui_docs._ID_AGENTS for s in k.segments)
202 assert fig.count('class="idfig__card') == 6 and fig.count("· differs") == changed == 5
203 assert "Known defect in muse 0.2.1rc20" in fig and "fixed public test seed" in fig
204 assert "<script" not in fig and "style=" not in fig
205
206
207 # ── DOC_ID_08: domain namespace ────────────────────────────────────────────────
208
209 def test_doc_id_08_domain_table_indices_and_registration(html: str) -> None:
210 from muse.cli.commands.domain_cmd import _SEED_REGISTRY
211
212 table = html.split('<a href="#domain-namespace">', 1)[1].split("</table>", 1)[0]
213 rows = re.findall(r"<code>(\d+)'</code></td><td>[^<]*· <code>(muse/[a-z]+)</code>", table)
214 assert len(rows) == 8
215 for idx, name in rows:
216 assert int(idx) == _h(name) == hdkeys.domain_index(name)
217 registered = {e["name"] if isinstance(e, dict) else e for e in _SEED_REGISTRY}
218 assert {n for _, n in rows} - registered == {"muse/mist"}
219 assert "Not registered in muse 0.2.1rc20" in table.split("muse/mist", 1)[1].split("</tr>", 1)[0]
220
221
222 # ── DOC_ID_09: sample outputs, roles, resolution ───────────────────────────────
223
224 def test_doc_id_09_sample_outputs_are_seven_level_and_computed(html: str) -> None:
225 ex = ui_docs._ID_EXAMPLES
226 hub = _h(ex["host"])
227 assert ex["hd_path"] == f"m/1075233755'/1660078172'/0'/0'/0'/{hub}'/0'"
228 assert ex["agent_label"] == f"m/1075233755'/1660078172'/1'/{_h('claude-code')}'/0'/{hub}'/0'"
229 assert re.fullmatch(r"sha256:[0-9a-f]{64}", ex["fingerprint"])
230 show = _pre_after(html, "output (envelope fields omitted)")
231 assert ex["hd_path"] in show and ex["fingerprint"] in show and ex["payments_path"] in show
232 assert "m/1075233755'/1660078172'/0'/0'/0'/0'\"" not in show # no stale six-level identity path
233 toml = _pre_after(html, 'code-label">~/.muse/identity.toml')
234 assert f'["{ex["host"]}"]' in toml and ex["agent_label"] in toml and "10003" not in toml
235
236
237 def test_doc_id_09_role_and_entity_constants(html: str) -> None:
238 roles = dict(re.findall(r"<td><code>(\d)'</code></td><td><code>(ROLE_[A-Z]+)</code>", html))
239 assert {k: getattr(hdkeys, v) for k, v in roles.items()} == {str(i): i for i in range(5)}
240 assert (hdkeys.ENTITY_HUMAN, hdkeys.ENTITY_AGENT, hdkeys.ENTITY_ORG) == (0, 1, 2)
241
242
243 def test_doc_id_09_python_imports_on_the_page_resolve(html: str) -> None:
244 """Every `from muse… / musehub… import …` in the page's code samples resolves (ID-4, ID-7)."""
245 code = " ".join(re.sub(r"<[^>]+>", "", c) for c in re.findall(r"<pre><code>(.*?)</code></pre>", html, re.S))
246 imports = re.findall(r"from ((?:muse|musehub)[\w.]*) import \(?([\w, \n]+?)\)?\s*(?:\n|#|$)", code)
247 assert imports
248 for module, names in imports:
249 mod = importlib.import_module(module)
250 for name in (n.strip() for n in names.split(",")):
251 if name:
252 assert hasattr(mod, name), f"{module}.{name}"
253
254
255 def test_doc_id_09_resolution_order_matches_get_signing_identity(html: str) -> None:
256 import inspect
257
258 from muse.cli.config import get_signing_identity
259
260 params = inspect.signature(get_signing_identity).parameters
261 assert "remote_url" in params and "hub" not in params
262 assert SigningIdentity._fields == ("handle", "private_key")
263 order = _pre_after(html, "resolution order")
264 assert "MUSE_AGENT_HD_SEED" not in html and "IdentityNotFound" not in html
265 assert order.index("MUSE_AGENT_KEY_FD") < order.index("[host#agent-id]") < order.index("[host]") < order.index("None")
266
267
268 # ── DOC_ID_10: attestations ────────────────────────────────────────────────────
269
270 def test_doc_id_10_claim_type_table_matches_the_registry(html: str) -> None:
271 from musehub.services.musehub_attestations import _CLAIM_TYPES
272
273 table = html.split('<a href="#attest-claim-types">', 1)[1].split("</table>", 1)[0]
274 rows = re.findall(r"<code>([a-z:-]+)</code></td>\s*<td>([^<]+)</td>\s*<td>(.*?)</td>", table, re.S)
275 assert len(rows) == len(_CLAIM_TYPES) == 17
276 for key, label, scopes in rows:
277 assert label.strip() == _CLAIM_TYPES[key]["label"]
278 assert re.findall(r"<code>(\w+)</code>", scopes) == _CLAIM_TYPES[key]["valid_scopes"]
279
280
281 def test_doc_id_10_attestation_id_formula_and_routes(html: str) -> None:
282 from musehub.core.genesis import compute_attestation_id
283
284 p = "\0".join(["gabriel", "claude-code", '{"type":"agent"}', "2026-11-07T09:00:00+00:00"]).encode()
285 expected = "sha256:" + hashlib.sha256(f"blob {len(p)}".encode() + b"\0" + p).hexdigest()
286 assert compute_attestation_id("gabriel", "claude-code", '{"type":"agent"}', "2026-11-07T09:00:00+00:00") == expected
287 assert 'hex(sha256("blob {len(p)}" NUL p))' in _pre_after(html, "attestation_id derivation")
288 routes = _profile_routes()
289 for route in (("GET", "/api/profiles/{handle}/attestations"), ("POST", "/api/profiles/{handle}/attestations"),
290 ("DELETE", "/api/profiles/{handle}/attestations/{attestation_id}"),
291 ("GET", "/api/profiles/attestation-types")):
292 assert route in routes
293 assert "MUSE-SIGN-V1" not in html
294
295
296 # ── DOC_ID_11: identity-graph samples execute as documented ────────────────────
297
298 def test_doc_id_11_validator_sample_and_messages(html: str) -> None:
299 from musehub.graph.push_validator import IdentityPushValidator
300
301 at, now = "2026-11-01T00:00:00+00:00", datetime(2026, 11, 7, tzinfo=timezone.utc)
302 result = IdentityPushValidator().validate(
303 identities=[{"handle": "gabriel", "type": "human", "quorum": None, "registered_at": at},
304 {"handle": "claude-code", "type": "agent", "quorum": None, "registered_at": at},
305 {"handle": "acme", "type": "org", "quorum": 2, "registered_at": at}],
306 relationships=[{"from_handle": "gabriel", "to_handle": "claude-code", "edge_type": "spawns",
307 "authorized_by": [{"signer": "gabriel", "signature": "ed25519:...", "signed_at": at}]}],
308 now=now)
309 assert result.valid and result.errors == []
310 assert re.fullmatch(r"I2 warning: 'acme' \(org\) has no path to any human root — orphaned for \d+ day\(s\), "
311 r"\d+ remaining before this becomes a hard error", result.warnings[0])
312 shown = re.search(r"result\.warnings → \[\"(I2 warning: 'acme' \(org\) has no path to any human root — orphaned "
313 r"for N day\(s\), M remaining before this becomes a hard error)\"\]", html)
314 assert shown
315
316
317 def test_doc_id_11_quorum_rejection_string_is_the_validator_output(text: str) -> None:
318 from musehub.graph.push_validator import IdentityPushValidator
319
320 at = "2026-11-01T00:00:00+00:00"
321 sig = lambda who: {"signer": who, "signature": "ed25519:x", "signed_at": at} # noqa: E731
322 join = lambda who, signers: {"from_handle": who, "to_handle": "graph-lab", "edge_type": "member_of", # noqa: E731
323 "authorized_by": [sig(s) for s in signers]}
324 result = IdentityPushValidator().validate(
325 identities=[{"handle": h, "type": t, "quorum": q, "registered_at": at} for h, t, q in
326 (("gabriel", "human", None), ("claude-code", "agent", None), ("musehub-org", "org", 1),
327 ("graph-lab", "org", 2), ("alice", "human", None))],
328 relationships=[join("gabriel", ["gabriel"]), join("claude-code", ["gabriel"]),
329 join("musehub-org", ["gabriel", "claude-code"]), join("alice", ["gabriel"])],
330 now=datetime(2026, 11, 7, tzinfo=timezone.utc))
331 detail = "push rejected: identity domain invariant violation(s): " + "; ".join(result.errors)
332 assert not result.valid and f'"detail": "{detail}"' in text
333
334
335 def test_doc_id_11_quorum_engine_sample_returns_true() -> None:
336 from decimal import Decimal
337
338 from musehub.graph.quorum import OrgSpec, QuorumEngine, VoteRecord
339
340 engine = QuorumEngine({"graph-lab": OrgSpec(handle="graph-lab", quorum=2,
341 member_weights={"gabriel": Decimal("1"), "claude-code": Decimal("1")})})
342 votes = [VoteRecord(voter_handle="gabriel", org_handle="graph-lab"),
343 VoteRecord(voter_handle="claude-code", org_handle="graph-lab")]
344 assert engine.is_quorum_met("graph-lab", votes) is True
345
346
347 # ── DOC_ID_12: known-defect warnings link real tickets ─────────────────────────
348
349 def test_doc_id_12_known_defect_warnings_link_their_tickets(html: str) -> None:
350 assert "__T_" not in html
351 for ticket in (_T_AGENT, _T_RECOVER, _T_MPAY):
352 assert f'href="{MUSE_ISSUES}{ticket}"' in html
File History 3 commits
sha256:580949619fa19ce11fb2e0fd9ebd2e95707a8db352a8586382e0707b2a4a78a9 docs: follow Muse 0.2.2rc7 — shelf list --tag, shelf_size a… Opus 5.5 minor ⚠ 1 day ago
sha256:634da27c5b4ea6e3cb5aa9cfb4e58dbf922b627caef67ffb0cb64bcaf70b7b9f Merge task/246-identity-qa-v2 (#246 Cryptographic Identity … Opus 5.5 minor ⚠ 9 days ago
sha256:2de1e96b7f547494958a8edace1860efc2c0de0933c4f00f777f2cc18abaf324 docs(identity): QA contract v2 for /muse/identity against m… Opus 5.5 minor ⚠ 9 days ago