gabriel / musehub public
test_identity_push_validator_wire_integration.py python
229 lines 8.3 KB
Raw
sha256:383b9b15b1a7c18348bf797dbec252b8842199567b4b04371578fedd5f7891d4 merge: integrate push-ingest commit verification into dev Opus 5.5 minor ⚠ breaking 11 days ago
1 """TDD — musehub#230: IdentityPushValidator was never invoked by the real
2 wire_push_unpack_mpack pipeline -- I1/I2/I3 were enforced by nothing on an
3 actual push, despite push_validator.py's own docstring claiming otherwise
4 (the false claim #227's audit table also repeated).
5
6 This test exercises the real, live wire-push endpoint function end-to-end --
7 not IdentityPushValidator directly (tests/test_identity_push_validator.py
8 already covers that in isolation) -- with an identity-domain commit whose
9 committed state contains a real I1 violation (a 2-node cycle: alice spawns
10 bob, bob spawns alice). It must be rejected by the actual push pipeline,
11 not merely by calling the validator class in a unit test.
12
13 RED before the fix: the push succeeds; the cyclic relationship is persisted.
14 GREEN after: wire_push_unpack_mpack detects the identity domain, reconstructs
15 the full identities/relationships snapshot, runs IdentityPushValidator, and
16 rejects the push with ValueError (-> HTTP 422 at the route layer) before any
17 objects are committed.
18 """
19 from __future__ import annotations
20
21 import datetime
22 from unittest.mock import AsyncMock, MagicMock, patch
23
24 import pytest
25 from sqlalchemy.ext.asyncio import AsyncSession
26
27 from muse.core.ids import hash_snapshot
28 from muse.core.mpack import build_wire_mpack
29 from muse.core.types import blob_id
30 from muse.plugins.identity.records import (
31 IdentityRecord,
32 RelationshipRecord,
33 identity_path,
34 record_to_bytes,
35 relationship_path,
36 )
37 from musehub.core.genesis import compute_identity_id
38 from tests.commit_fixtures import with_reproducible_id
39 from musehub.db.musehub_repo_models import MusehubCommit
40 from musehub.services.musehub_repository import create_repo
41 from musehub.services.musehub_wire_push import wire_push_unpack_mpack
42
43 _OWNER = "gabriel"
44 _IDENTITY_ID = compute_identity_id(b"gabriel")
45
46
47 def _cid(seed: str) -> str:
48 return blob_id(f"identity-push-validator-wire-{seed}".encode())
49
50
51 def _now() -> datetime.datetime:
52 return datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)
53
54
55 def _raw_commit(label: str, snap_id: str) -> dict:
56 return with_reproducible_id({
57 "commit_id": "",
58 "branch": "main",
59 "message": f"commit {label[:12]}",
60 "author": _OWNER,
61 "committed_at": _now().isoformat(),
62 "parent_commit_id": None,
63 "parent2_commit_id": None,
64 "snapshot_id": snap_id,
65 "agent_id": "",
66 "model_id": "",
67 "toolchain_id": "",
68 "sem_ver_bump": "none",
69 "breaking_changes": [],
70 "signature": "",
71 "signer_key_id": "",
72 "signer_public_key": "",
73 "prompt_hash": "",
74 })
75
76
77 def _mock_backend(mpack_bytes: bytes) -> MagicMock:
78 backend = MagicMock()
79 backend.get_mpack = AsyncMock(return_value=mpack_bytes)
80 backend.put = AsyncMock(return_value=None)
81 backend.put_mpack = AsyncMock(return_value=None)
82 backend.quarantine_mpack = AsyncMock(return_value=None)
83 backend.presign_get = AsyncMock(return_value="")
84 backend.presign_mpack_get = AsyncMock(return_value="")
85 return backend
86
87
88 def _identity_record(handle: str, kind: str) -> IdentityRecord:
89 return {
90 "handle": handle,
91 "type": kind, # type: ignore[typeddict-item]
92 "pubkey": None,
93 "quorum": None,
94 "registered_at": _now().isoformat(),
95 "metadata": {},
96 }
97
98
99 def _spawns(frm: str, to: str, signer: str) -> RelationshipRecord:
100 return {
101 "from_handle": frm,
102 "to_handle": to,
103 "edge_type": "spawns",
104 "weight": None,
105 "authorized_by": [{"signer": signer, "signature": "sig", "signed_at": _now().isoformat()}],
106 }
107
108
109 async def _push_identity_commit(
110 db_session: AsyncSession,
111 *,
112 repo_name: str,
113 manifest: dict[str, bytes],
114 ) -> tuple[str, bytes]:
115 """Create an identity-domain repo and build the mpack for one commit
116 whose snapshot contains ``manifest`` (path -> file content). Returns
117 (repo_id, mpack_bytes); does not push -- caller drives wire_push_unpack_mpack
118 so it can assert on the raised exception or the resulting state."""
119 repo = await create_repo(
120 db_session,
121 name=repo_name,
122 owner=_OWNER,
123 owner_user_id=_IDENTITY_ID,
124 visibility="private",
125 domain="identity",
126 initialize=False,
127 )
128 await db_session.commit()
129
130 oid_manifest = {path: blob_id(content) for path, content in manifest.items()}
131 snap_id = hash_snapshot(oid_manifest, [])
132 record = _raw_commit(_cid(repo_name), snap_id)
133 commit_id = record["commit_id"]
134
135 mpack_bytes = build_wire_mpack({
136 "commits": [record],
137 "snapshots": [{
138 "snapshot_id": snap_id,
139 "parent_snapshot_id": None,
140 "delta_upsert": oid_manifest,
141 "delta_remove": [],
142 "directories": [],
143 }],
144 "blobs": [
145 {"object_id": oid, "content": manifest[path]}
146 for path, oid in oid_manifest.items()
147 ],
148 "tags": [],
149 })
150 return repo.repo_id, mpack_bytes, commit_id
151
152
153 @pytest.mark.asyncio
154 async def test_identity_cycle_is_rejected_by_the_real_wire_push_endpoint(
155 db_session: AsyncSession,
156 ) -> None:
157 """RED: a push introducing a 2-node identity cycle (alice spawns bob,
158 bob spawns alice -- an I1 violation) must be rejected by the live
159 wire_push_unpack_mpack pipeline, not silently accepted."""
160 manifest = {
161 identity_path("alice"): record_to_bytes(_identity_record("alice", "human")),
162 identity_path("bob"): record_to_bytes(_identity_record("bob", "agent")),
163 relationship_path("alice", "spawns", "bob"): record_to_bytes(_spawns("alice", "bob", "alice")),
164 relationship_path("bob", "spawns", "alice"): record_to_bytes(_spawns("bob", "alice", "bob")),
165 }
166 repo_id, mpack_bytes, commit_id = await _push_identity_commit(
167 db_session, repo_name="identity-cycle-repro", manifest=manifest
168 )
169 mpack_key = blob_id(mpack_bytes)
170 backend = _mock_backend(mpack_bytes)
171
172 with patch("musehub.services.musehub_wire.get_backend", return_value=backend), \
173 patch("musehub.services.musehub_wire_push.get_backend", return_value=backend), \
174 patch("musehub.storage.backends.get_backend", return_value=backend):
175 with pytest.raises(ValueError, match="I1"):
176 await wire_push_unpack_mpack(
177 db_session,
178 repo_id,
179 mpack_key,
180 pusher_id=_OWNER,
181 branch="main",
182 head_commit_id=commit_id,
183 commits_count=1,
184 blobs_count=4,
185 force=True,
186 )
187
188 stored = await db_session.get(MusehubCommit, commit_id)
189 assert stored is None, (
190 "a push containing an identity-graph cycle must be rejected outright -- "
191 "the commit must never be persisted"
192 )
193
194
195 @pytest.mark.asyncio
196 async def test_valid_identity_push_is_accepted_by_the_real_wire_push_endpoint(
197 db_session: AsyncSession,
198 ) -> None:
199 """GREEN control: a valid, acyclic, fully-authorized identity push must
200 still succeed -- the new validation must not reject legitimate pushes."""
201 manifest = {
202 identity_path("carol"): record_to_bytes(_identity_record("carol", "human")),
203 identity_path("dave"): record_to_bytes(_identity_record("dave", "agent")),
204 relationship_path("carol", "spawns", "dave"): record_to_bytes(_spawns("carol", "dave", "carol")),
205 }
206 repo_id, mpack_bytes, commit_id = await _push_identity_commit(
207 db_session, repo_name="identity-valid-push", manifest=manifest
208 )
209 mpack_key = blob_id(mpack_bytes)
210 backend = _mock_backend(mpack_bytes)
211
212 with patch("musehub.services.musehub_wire.get_backend", return_value=backend), \
213 patch("musehub.services.musehub_wire_push.get_backend", return_value=backend), \
214 patch("musehub.storage.backends.get_backend", return_value=backend):
215 await wire_push_unpack_mpack(
216 db_session,
217 repo_id,
218 mpack_key,
219 pusher_id=_OWNER,
220 branch="main",
221 head_commit_id=commit_id,
222 commits_count=1,
223 blobs_count=3,
224 force=True,
225 )
226 await db_session.flush()
227
228 stored = await db_session.get(MusehubCommit, commit_id)
229 assert stored is not None, "a valid identity push must be accepted and persisted"
File History 3 commits
sha256:383b9b15b1a7c18348bf797dbec252b8842199567b4b04371578fedd5f7891d4 merge: integrate push-ingest commit verification into dev Opus 5.5 minor ⚠ 11 days ago
sha256:a4d6b38221ff81ce17b43d47240f441c45140d63c575f98273c66c0df132c388 fix(push): verify commit records at ingest and reconcile du… Opus 5.5 minor ⚠ 11 days ago
sha256:066f0f58448cc0553bff3c845cbb8e1f7a6bdecf53fce6bc5c2ff5e0ddad3d71 feat: wire IdentityPushValidator into the real push pipelin… Sonnet 5 minor ⚠ 25 days ago