gabriel / musehub public
test_security_r1_repo_authz.py python
293 lines 13.5 KB
Raw
sha256:89c7a8268be75aeb33144acf863ad3ebefe7fd3bdfd679faa768199fd789b376 merge: REST wire wave — #296 #297 #298 #299 (Tier A review … Opus 5.5 minor ⚠ breaking 1 day ago
1 """Private-repository read authorization (security R1, C1 and related paths).
2
3 Authentication alone must never grant read access to a private repo. These
4 tests drive every read surface that previously checked only ``claims is None``
5 (or nothing at all) with four callers against a private repo:
6
7 anonymous → denied (401/404, never 200)
8 unrelated user → 404 (no existence leak)
9 pending invitee → 404 (invite not accepted)
10 read collaborator→ allowed
11 owner → allowed
12
13 and confirm public repos stay readable by everyone. Denials are asserted on
14 status codes only; private content never appears in assertions.
15 """
16 from __future__ import annotations
17
18 from collections.abc import AsyncGenerator
19 from datetime import datetime, timezone
20
21 import pytest
22 import pytest_asyncio
23 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
24 from httpx import ASGITransport, AsyncClient
25 from sqlalchemy.ext.asyncio import AsyncSession
26
27 from muse.core.types import blob_id, encode_pubkey, public_key_fingerprint
28 from musehub.auth.request_signing import MSignContext, optional_signed_request, require_signed_request
29 from musehub.core.genesis import compute_collaborator_id, compute_identity_id
30 from musehub.db.database import get_db
31 from musehub.db.musehub_collaborator_models import MusehubCollaborator
32 from musehub.db.musehub_identity_models import MusehubIdentity
33 from musehub.db.musehub_repo_models import MusehubObject, MusehubObjectRef, MusehubRepo
34 from musehub.main import app
35 from musehub.mcp.resources import read_resource
36 from musehub.mcp.write_tools.collaborators import execute_list_collaborators
37 from musehub.mcp.write_tools.proposals import execute_list_simulations
38 from musehub.services.musehub_repository import create_repo
39
40 OWNER = "r1-owner"
41 STRANGER = "r1-stranger"
42 PENDING = "r1-pending"
43 READER = "r1-reader"
44
45
46 def _ctx(handle: str, *, scope: list[str] | None = None, is_agent: bool = False) -> MSignContext:
47 return MSignContext(
48 handle=handle, identity_id=compute_identity_id(handle.encode()),
49 is_agent=is_agent, is_admin=False, scope=scope,
50 )
51
52
53 @pytest_asyncio.fixture
54 async def world(db_session: AsyncSession) -> AsyncGenerator[dict[str, MusehubRepo], None]:
55 for h in (OWNER, STRANGER, PENDING, READER):
56 db_session.add(MusehubIdentity(
57 identity_id=compute_identity_id(h.encode()), handle=h, display_name=h, identity_type="human",
58 ))
59 await db_session.commit()
60 private = await create_repo(db_session, name="r1-private", owner=OWNER,
61 owner_user_id=compute_identity_id(OWNER.encode()),
62 visibility="private", initialize=False)
63 public = await create_repo(db_session, name="r1-public", owner=OWNER,
64 owner_user_id=compute_identity_id(OWNER.encode()),
65 visibility="public", initialize=False)
66 await db_session.commit()
67 for handle, accepted in ((PENDING, False), (READER, True)):
68 row = MusehubCollaborator(
69 id=compute_collaborator_id(private.repo_id, compute_identity_id(handle.encode()),
70 datetime.now(timezone.utc).isoformat()),
71 repo_id=private.repo_id, identity_handle=handle, permission="read",
72 )
73 db_session.add(row)
74 await db_session.flush()
75 if accepted:
76 row.accepted_at = row.invited_at
77 await db_session.commit()
78 yield {"private": private, "public": public}
79
80
81 async def _get(db_session: AsyncSession, path: str, who: str | None) -> int:
82 async def _db() -> AsyncGenerator[AsyncSession, None]:
83 yield db_session
84 app.dependency_overrides[get_db] = _db
85 if who is None:
86 app.dependency_overrides[optional_signed_request] = lambda: None
87 else:
88 app.dependency_overrides[require_signed_request] = lambda: _ctx(who)
89 app.dependency_overrides[optional_signed_request] = lambda: _ctx(who)
90 try:
91 async with AsyncClient(transport=ASGITransport(app=app), base_url="https://localhost:1337") as c:
92 return (await c.get(path)).status_code
93 finally:
94 for dep in (get_db, optional_signed_request, require_signed_request):
95 app.dependency_overrides.pop(dep, None)
96
97
98 # Every path below previously served a private repo to any authenticated caller
99 # (or, for labels / object CDN, to anyone at all).
100 REST = [
101 "/api/repos/{id}",
102 "/api/repos/{id}/issues",
103 "/api/repos/{id}/labels",
104 "/api/repos/{id}/proposals",
105 "/api/repos/{id}/releases",
106 "/api/repos/{id}/snapshots",
107 "/api/repos/{id}/collaborators",
108 ]
109 UI = ["/{owner}/{slug}", "/{owner}/{slug}/commits"]
110 WIRE = ["/{owner}/{slug}/version-tags"]
111
112
113 def _paths(repo: MusehubRepo) -> list[str]:
114 return ([p.format(id=repo.repo_id) for p in REST]
115 + [p.format(owner=repo.owner, slug=repo.slug) for p in UI + WIRE])
116
117
118 @pytest.mark.asyncio
119 async def test_private_repo_denied_to_unrelated_and_pending(db_session: AsyncSession, world) -> None:
120 for path in _paths(world["private"]):
121 for who in (STRANGER, PENDING):
122 code = await _get(db_session, path, who)
123 assert code == 404, f"{who} GET {path} -> {code}"
124
125
126 @pytest.mark.asyncio
127 async def test_private_repo_denied_to_anonymous(db_session: AsyncSession, world) -> None:
128 for path in _paths(world["private"]):
129 code = await _get(db_session, path, None)
130 assert code in (401, 404), f"anonymous GET {path} -> {code}"
131
132
133 @pytest.mark.asyncio
134 async def test_private_repo_allowed_to_owner_and_collaborator(db_session: AsyncSession, world) -> None:
135 for path in _paths(world["private"]):
136 for who in (OWNER, READER):
137 code = await _get(db_session, path, who)
138 assert code == 200, f"{who} GET {path} -> {code}"
139
140
141 @pytest.mark.asyncio
142 async def test_public_repo_readable_by_everyone(db_session: AsyncSession, world) -> None:
143 for path in _paths(world["public"]):
144 if path.endswith("/collaborators") or path.endswith("/version-tags"):
145 continue # authenticated-only endpoints by design
146 for who in (None, STRANGER):
147 code = await _get(db_session, path, who)
148 assert code == 200, f"{who or 'anonymous'} GET {path} -> {code}"
149
150
151 # ── content-addressed object CDN ─────────────────────────────────────────────
152
153 async def _store_object(db_session: AsyncSession, repo: MusehubRepo | None, data: bytes) -> str:
154 object_id = blob_id(data) # the typed object ID the CDN verifies (musehub#299)
155 db_session.add(MusehubObject(object_id=object_id, path="f.bin", size_bytes=len(data), content_cache=data))
156 await db_session.flush()
157 if repo is not None:
158 db_session.add(MusehubObjectRef(repo_id=repo.repo_id, object_id=object_id))
159 await db_session.commit()
160 return object_id
161
162
163 async def _get_object(db_session: AsyncSession, object_id: str, who: str | None) -> tuple[int, str]:
164 async def _db() -> AsyncGenerator[AsyncSession, None]:
165 yield db_session
166 app.dependency_overrides[get_db] = _db
167 app.dependency_overrides[optional_signed_request] = (lambda: None) if who is None else (lambda: _ctx(who))
168 try:
169 async with AsyncClient(transport=ASGITransport(app=app), base_url="https://localhost:1337") as c:
170 r = await c.get(f"/o/{object_id}")
171 return r.status_code, r.headers.get("cache-control", "")
172 finally:
173 app.dependency_overrides.pop(get_db, None)
174 app.dependency_overrides.pop(optional_signed_request, None)
175
176
177 @pytest.mark.asyncio
178 async def test_object_cdn_private_object_access(db_session: AsyncSession, world) -> None:
179 oid = await _store_object(db_session, world["private"], b"r1 private object bytes")
180 for who in (None, STRANGER, PENDING):
181 code, _ = await _get_object(db_session, oid, who)
182 assert code == 404, f"{who or 'anonymous'} -> {code}"
183 for who in (OWNER, READER):
184 code, cc = await _get_object(db_session, oid, who)
185 assert code == 200, f"{who} -> {code}"
186 assert "no-store" in cc and "public" not in cc
187
188
189 @pytest.mark.asyncio
190 async def test_object_cdn_public_object_cached_publicly(db_session: AsyncSession, world) -> None:
191 oid = await _store_object(db_session, world["public"], b"r1 public object bytes")
192 code, cc = await _get_object(db_session, oid, None)
193 assert code == 200 and cc.startswith("public")
194
195
196 @pytest.mark.asyncio
197 async def test_object_cdn_unreferenced_object_denied(db_session: AsyncSession, world) -> None:
198 oid = await _store_object(db_session, None, b"r1 orphan object bytes")
199 code, _ = await _get_object(db_session, oid, OWNER)
200 assert code == 404
201
202
203 # ── MCP ──────────────────────────────────────────────────────────────────────
204
205 @pytest.mark.asyncio
206 async def test_mcp_resource_private_repo(db_session: AsyncSession, world) -> None:
207 uri = f"musehub://repos/{OWNER}/r1-private"
208 denied = await read_resource(uri, user_id=STRANGER)
209 assert "error" in denied
210 allowed = await read_resource(uri, user_id=READER)
211 assert "error" not in allowed
212
213
214 @pytest.mark.asyncio
215 async def test_mcp_tools_private_repo(db_session: AsyncSession, world) -> None:
216 repo_id = world["private"].repo_id
217 for fn in (execute_list_collaborators, execute_list_simulations):
218 kwargs = {"repo_id": repo_id, "actor": STRANGER}
219 if fn is execute_list_simulations:
220 kwargs["proposal_id"] = "sha256:" + "0" * 64
221 result = await fn(**kwargs)
222 assert not result.ok and result.error_code == "repo_not_found", fn.__name__
223 ok = await execute_list_collaborators(repo_id=repo_id, actor=OWNER)
224 assert ok.ok
225
226
227 # ── webhook delivery history ─────────────────────────────────────────────────
228
229 @pytest.mark.asyncio
230 async def test_webhook_deliveries_owner_only(db_session: AsyncSession, world) -> None:
231 for repo in (world["private"], world["public"]):
232 path = f"/api/repos/{repo.repo_id}/webhooks/sha256:{'0' * 64}/deliveries"
233 assert await _get(db_session, path, STRANGER) == 403
234 assert await _get(db_session, path, READER) in (403, 404)
235 assert await _get(db_session, path, OWNER) == 404 # authorized; webhook does not exist
236
237
238 # ── agent delegation bounds ──────────────────────────────────────────────────
239
240 def _agent_body(handle: str, *, scope: list[str], expires_at: str | None = None) -> dict[str, object]:
241 raw = Ed25519PrivateKey.generate().public_key().public_bytes_raw()
242 body: dict[str, object] = {
243 "handle": handle, "public_key_b64": encode_pubkey("ed25519", raw),
244 "fingerprint": public_key_fingerprint(raw), "algorithm": "ed25519", "scope": scope,
245 }
246 if expires_at is not None:
247 body["expires_at"] = expires_at
248 return body
249
250
251 async def _post_agent(db_session: AsyncSession, caller: MSignContext, body: dict[str, object]) -> int:
252 async def _db() -> AsyncGenerator[AsyncSession, None]:
253 yield db_session
254 app.dependency_overrides[get_db] = _db
255 app.dependency_overrides[require_signed_request] = lambda: caller
256 try:
257 async with AsyncClient(transport=ASGITransport(app=app), base_url="https://localhost:1337") as c:
258 return (await c.post("/api/identities/agent", json=body)).status_code
259 finally:
260 app.dependency_overrides.pop(get_db, None)
261 app.dependency_overrides.pop(require_signed_request, None)
262
263
264 @pytest.mark.asyncio
265 async def test_agent_cannot_grant_scope_beyond_its_own(db_session: AsyncSession) -> None:
266 parent = "r1-scoped-agent"
267 db_session.add(MusehubIdentity(identity_id=compute_identity_id(parent.encode()), handle=parent,
268 display_name=parent, identity_type="agent", scope=["issue:write"]))
269 await db_session.commit()
270 caller = _ctx(parent, scope=["issue:write"], is_agent=True)
271 assert await _post_agent(db_session, caller, _agent_body("r1-child-wide", scope=["issue:write", "repo:write"])) == 403
272 assert await _post_agent(db_session, caller, _agent_body("r1-child-ok", scope=["issue:write"])) == 201
273
274
275 @pytest.mark.asyncio
276 async def test_expiring_agent_cannot_grant_longer_life(db_session: AsyncSession) -> None:
277 parent = "r1-expiring-agent"
278 db_session.add(MusehubIdentity(identity_id=compute_identity_id(parent.encode()), handle=parent,
279 display_name=parent, identity_type="agent", scope=[],
280 expires_at=datetime(2030, 1, 1, tzinfo=timezone.utc)))
281 await db_session.commit()
282 caller = _ctx(parent, scope=[], is_agent=True)
283 assert await _post_agent(db_session, caller, _agent_body("r1-child-forever", scope=[])) == 403
284 assert await _post_agent(db_session, caller, _agent_body("r1-child-later", scope=[], expires_at="2031-01-01T00:00:00Z")) == 403
285 assert await _post_agent(db_session, caller, _agent_body("r1-child-sooner", scope=[], expires_at="2029-01-01T00:00:00Z")) == 201
286
287
288 @pytest.mark.asyncio
289 async def test_human_can_still_provision_agents(db_session: AsyncSession) -> None:
290 db_session.add(MusehubIdentity(identity_id=compute_identity_id(OWNER.encode()), handle=OWNER,
291 display_name=OWNER, identity_type="human"))
292 await db_session.commit()
293 assert await _post_agent(db_session, _ctx(OWNER), _agent_body("r1-human-child", scope=["issue:write"])) == 201
File History 4 commits
sha256:89c7a8268be75aeb33144acf863ad3ebefe7fd3bdfd679faa768199fd789b376 merge: REST wire wave — #296 #297 #298 #299 (Tier A review … Opus 5.5 minor ⚠ 1 day ago
sha256:22ee032c7cb1c6d27f318812c88dd8c2ba76fc8ee54551be7742fe75a1558202 fix(wire): GET /o/{id} verifies the typed blob ID and refus… Opus 5.5 patch 2 days ago
sha256:4defb0407ee7fe26b1addb8df5cf3d31dae4ebf1ab92eeca1c05348b9d4c8458 merge: integrate R1 into the publishable #114 line (private… Opus 5.5 minor ⚠ 12 days ago
sha256:83227647a82e1733a20b0b6d225df3d153769630d3c710d255e0c1b8aab8ae61 Co-Authored-By: Claude Opus 5.5 <[email protected]> Opus 5.5 minor ⚠ 13 days ago