gabriel / musehub public
test_attestation_caller_auth.py python
176 lines 9.7 KB
Raw
sha256:937f09c8180451ccab720bc1939dbb181055322af23ac2b0e4ccc91ae376b22a fix(profiles): bind attestations and MPay claims to the aut… Opus 5.5 minor ⚠ breaking 8 days ago
1 """Attestations and MPay claims are bound to the MSign-authenticated caller.
2
3 - Issue (``POST /api/profiles/{handle}/attestations``) and MPay claims (``POST …/mpay-claims``) require MSign; the
4 attester / sender must be the caller, and the supplied public key must be one of the caller's active registered keys.
5 - Revoke (``DELETE …/attestations/{id}?revoker=``) requires MSign; the revoker must be the caller and the attester.
6 - The MCP tools take the caller from the authenticated session, never from tool arguments.
7 Existing signature, claim-type and scope validation is unchanged.
8 """
9 from __future__ import annotations
10
11 import secrets
12 from collections.abc import AsyncGenerator
13 from datetime import datetime, timezone
14 from unittest.mock import AsyncMock, MagicMock, patch
15
16 import pytest
17 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
18 from httpx import AsyncClient
19 from muse.core.types import encode_pubkey, encode_sig
20 from sqlalchemy import text
21 from sqlalchemy.ext.asyncio import AsyncSession
22
23 from musehub.auth.request_signing import MSignContext, optional_signed_request, require_signed_request
24 from musehub.core.genesis import compute_identity_id
25 from musehub.crypto.keys import key_fingerprint
26 from musehub.db.musehub_auth_models import MusehubAuthKey
27 from musehub.db.musehub_identity_models import MusehubIdentity
28 from musehub.main import app
29
30 CLAIM = '{"type":"collab"}'
31
32
33 def _keypair() -> tuple[Ed25519PrivateKey, str]:
34 priv = Ed25519PrivateKey.generate()
35 return priv, encode_pubkey("ed25519", priv.public_key().public_bytes_raw())
36
37
38 def _attest(priv: Ed25519PrivateKey, pub: str, attester: str, subject: str) -> dict[str, str]:
39 ts = datetime.now(tz=timezone.utc).isoformat()
40 sig = encode_sig("ed25519", priv.sign("\n".join(["ATTEST", attester, subject, CLAIM, ts]).encode()))
41 return {"attester": attester, "subject": subject, "claim": CLAIM, "signature": sig,
42 "attester_public_key": pub, "issued_at": ts, "scope": "identity"}
43
44
45 def _mpay(priv: Ed25519PrivateKey, pub: str, sender: str, recipient: str) -> dict[str, object]:
46 nonce = secrets.token_hex(32)
47 sig = encode_sig("ed25519", priv.sign(f"MPAY\n{sender}\n{recipient}\n1000\n{nonce}".encode()))
48 return {"sender": sender, "recipient": recipient, "amount_nano": 1000, "nonce_hex": nonce,
49 "signature": sig, "sender_public_key": pub}
50
51
52 def _as(handle: str | None) -> None:
53 if handle is None:
54 app.dependency_overrides.pop(require_signed_request, None)
55 app.dependency_overrides.pop(optional_signed_request, None)
56 return
57 ctx = MSignContext(handle=handle, identity_id=compute_identity_id(handle.encode()), is_agent=False, is_admin=False)
58 app.dependency_overrides[require_signed_request] = lambda: ctx
59 app.dependency_overrides[optional_signed_request] = lambda: ctx
60
61
62 @pytest.fixture
63 async def keys(db_session: AsyncSession) -> AsyncGenerator[dict[str, tuple[Ed25519PrivateKey, str]], None]:
64 """alice and bob are registered identities, each with one active registered key."""
65 out: dict[str, tuple[Ed25519PrivateKey, str]] = {}
66 for h in ("alice", "bob"):
67 iid = compute_identity_id(h.encode())
68 db_session.add(MusehubIdentity(identity_id=iid, handle=h, display_name=h, identity_type="human"))
69 await db_session.flush() # the key row references the identity
70 priv, pub = _keypair()
71 raw = priv.public_key().public_bytes_raw()
72 db_session.add(MusehubAuthKey(key_id=f"key-{h}", identity_id=iid, public_key_b64=pub.split(":", 1)[1],
73 fingerprint=key_fingerprint(raw), algorithm="ed25519", label="test"))
74 out[h] = (priv, pub)
75 await db_session.commit()
76 yield out
77 _as(None)
78
79
80 async def _count(db: AsyncSession, table: str) -> int:
81 return int((await db.execute(text(f"SELECT count(*) FROM {table}"))).scalar_one())
82
83
84 async def test_unauthenticated_issue_revoke_and_mpay_are_rejected(client: AsyncClient, db_session: AsyncSession, keys: dict) -> None:
85 _as(None)
86 priv, pub = keys["alice"]
87 assert (await client.post("/api/profiles/bob/attestations", json=_attest(priv, pub, "alice", "bob"))).status_code == 401
88 assert (await client.delete("/api/profiles/bob/attestations/sha256:" + "0" * 64, params={"revoker": "alice"})).status_code == 401
89 assert (await client.post("/api/profiles/bob/mpay-claims", json=_mpay(priv, pub, "alice", "bob"))).status_code == 401
90 assert await _count(db_session, "musehub_attestations") == 0
91 assert await _count(db_session, "musehub_mpay_claims") == 0
92
93
94 async def test_attesting_as_another_identity_is_refused(client: AsyncClient, db_session: AsyncSession, keys: dict) -> None:
95 priv, pub = keys["bob"] # a valid signature by bob's own registered key, submitted by alice
96 _as("alice")
97 r = await client.post("/api/profiles/alice/attestations", json=_attest(priv, pub, "bob", "alice"))
98 assert r.status_code == 403, r.text
99 assert await _count(db_session, "musehub_attestations") == 0
100
101
102 async def test_unregistered_or_revoked_key_is_refused(client: AsyncClient, db_session: AsyncSession, keys: dict) -> None:
103 _as("alice")
104 priv, pub = _keypair() # valid signature, but not a key registered to alice
105 assert (await client.post("/api/profiles/bob/attestations", json=_attest(priv, pub, "alice", "bob"))).status_code == 403
106 await db_session.execute(text("UPDATE musehub_auth_keys SET revoked_at = now() WHERE key_id = 'key-alice'"))
107 await db_session.commit()
108 priv, pub = keys["alice"]
109 assert (await client.post("/api/profiles/bob/attestations", json=_attest(priv, pub, "alice", "bob"))).status_code == 403
110 assert await _count(db_session, "musehub_attestations") == 0
111
112
113 async def test_own_registered_key_issues_and_lists(client: AsyncClient, keys: dict) -> None:
114 priv, pub = keys["alice"]
115 _as("alice")
116 r = await client.post("/api/profiles/bob/attestations", json=_attest(priv, pub, "alice", "bob"))
117 assert r.status_code == 201, r.text
118 listed = await client.get("/api/profiles/bob/attestations")
119 assert r.json()["attestationId"] in [a["attestationId"] for a in listed.json()["attestations"]]
120
121
122 async def test_revoke_requires_the_authenticated_attester(client: AsyncClient, db_session: AsyncSession, keys: dict) -> None:
123 priv, pub = keys["alice"]
124 _as("alice")
125 aid = (await client.post("/api/profiles/bob/attestations", json=_attest(priv, pub, "alice", "bob"))).json()["attestationId"]
126 url = f"/api/profiles/bob/attestations/{aid}"
127 _as("bob")
128 assert (await client.delete(url, params={"revoker": "alice"})).status_code == 403 # claims to be the attester
129 assert (await client.delete(url, params={"revoker": "bob"})).status_code == 403 # is not the attester
130 _as("alice")
131 assert (await client.delete(url, params={"revoker": "bob"})).status_code == 403 # revoker must be the caller
132 still = (await db_session.execute(text("SELECT revoked_at FROM musehub_attestations WHERE attestation_id = :a"), {"a": aid})).scalar_one()
133 assert still is None
134 ok = await client.delete(url, params={"revoker": "alice"})
135 assert ok.status_code == 200 and ok.json()["revokedAt"] is not None
136
137
138 async def test_mpay_sender_must_be_the_caller_with_a_registered_key(client: AsyncClient, db_session: AsyncSession, keys: dict) -> None:
139 _as("alice")
140 bpriv, bpub = keys["bob"]
141 assert (await client.post("/api/profiles/alice/mpay-claims", json=_mpay(bpriv, bpub, "bob", "alice"))).status_code == 403
142 priv, pub = _keypair()
143 assert (await client.post("/api/profiles/bob/mpay-claims", json=_mpay(priv, pub, "alice", "bob"))).status_code == 403
144 assert await _count(db_session, "musehub_mpay_claims") == 0
145 priv, pub = keys["alice"]
146 assert (await client.post("/api/profiles/bob/mpay-claims", json=_mpay(priv, pub, "alice", "bob"))).status_code == 201
147
148
149 async def test_mcp_tools_refuse_a_caller_other_than_the_named_party() -> None:
150 from musehub.services.musehub_mcp_executor import (
151 execute_issue_attestation, execute_record_mpay_claim, execute_revoke_attestation)
152 priv, pub = _keypair()
153 a = _attest(priv, pub, "bob", "alice")
154 m = _mpay(priv, pub, "bob", "alice")
155 with patch("musehub.services.musehub_mcp_executor._check_db_available", return_value=None):
156 r1 = await execute_issue_attestation(attester="bob", subject="alice", claim=CLAIM, issued_at_iso=a["issued_at"],
157 signature=a["signature"], attester_public_key=pub, caller="alice")
158 r2 = await execute_revoke_attestation(attestation_id="sha256:" + "0" * 64, revoker="bob", caller="alice")
159 r3 = await execute_record_mpay_claim(sender="bob", recipient="alice", amount_nano=1000, nonce_hex=m["nonce_hex"],
160 signature=m["signature"], sender_public_key=pub, caller="alice")
161 r4 = await execute_revoke_attestation(attestation_id="sha256:" + "0" * 64, revoker="bob", caller="")
162 assert [(r.ok, r.error_code) for r in (r1, r2, r3, r4)] == [(False, "forbidden")] * 4
163
164
165 @pytest.mark.parametrize("tool,executor", [
166 ("musehub_issue_attestation", "execute_issue_attestation"),
167 ("musehub_revoke_attestation", "execute_revoke_attestation"),
168 ("musehub_record_mpay_claim", "execute_record_mpay_claim"),
169 ])
170 async def test_mcp_dispatcher_passes_the_authenticated_user_as_caller(tool: str, executor: str) -> None:
171 from musehub.mcp.dispatcher import dispatch_tool
172 done = MagicMock(ok=True, data={}, error_code=None, error_message=None, hint=None)
173 with patch(f"musehub.services.musehub_mcp_executor.{executor}", new=AsyncMock(return_value=done)) as exe:
174 await dispatch_tool(name=tool, arguments={"attester": "mallory", "revoker": "mallory", "sender": "mallory"},
175 user_id="gabriel", session_context=None)
176 assert exe.call_args.kwargs["caller"] == "gabriel"
File History 1 commit
sha256:937f09c8180451ccab720bc1939dbb181055322af23ac2b0e4ccc91ae376b22a fix(profiles): bind attestations and MPay claims to the aut… Opus 5.5 minor ⚠ 8 days ago