gabriel / musehub public
test_rest_gaps_312.py python
213 lines 10.7 KB
Raw
sha256:8157b0df0e2312254edef68f882db2e510f21a94655f46def61a00abc850c106 Merge branch 'task/wave-hub-rest-310-312' into dev Opus 5.5 minor ⚠ breaking 1 day ago
1 """musehub#312: the REST operations /muse/api used to document are real, with one way to do each.
2
3 - ``GET /api/user``: the signed caller's own identity (401 anonymous).
4 - ``DELETE /api/repos/{repo_id}/releases/{tag}``: owner or admin collaborator; the assets go with the release and a
5 ``release`` webhook with ``action: "deleted"`` is emitted.
6 - ``GET``/``PUT /api/repos/{repo_id}/topics``: read and idempotently replace a repository's topics; ``POST`` is gone.
7 - Repository metadata (description, visibility, domain) is updated through ``PATCH /api/repos/{repo_id}/settings``,
8 the one update route; there is no second ``PATCH /api/repos/{repo_id}``.
9 """
10 from __future__ import annotations
11
12 from collections.abc import Iterator
13 from datetime import datetime, timezone
14
15 import pytest
16 from httpx import AsyncClient
17 from sqlalchemy import func, select
18 from sqlalchemy.ext.asyncio import AsyncSession
19
20 from musehub.auth.request_signing import MSignContext, optional_signed_request, require_signed_request
21 from musehub.core.genesis import compute_collaborator_id, compute_identity_id
22 from musehub.db.musehub_collaborator_models import MusehubCollaborator
23 from musehub.db.musehub_identity_models import MusehubIdentity
24 from musehub.db.musehub_release_models import MusehubReleaseAsset
25 from musehub.main import app
26 from musehub.services import musehub_releases
27 from musehub.types.json_types import StrDict
28 from tests.factories import create_repo
29
30
31 @pytest.fixture
32 def signed_as() -> Iterator:
33 """Sign every request of the test as the given handle (the auth dependencies are overridden)."""
34
35 def _as(handle: str, *, agent: bool = False, scope: list[str] | None = None) -> None:
36 ctx = MSignContext(handle=handle, identity_id=compute_identity_id(handle.encode()), is_agent=agent,
37 is_admin=False, scope=scope)
38 app.dependency_overrides[require_signed_request] = lambda: ctx
39 app.dependency_overrides[optional_signed_request] = lambda: ctx
40
41 yield _as
42 app.dependency_overrides.pop(require_signed_request, None)
43 app.dependency_overrides.pop(optional_signed_request, None)
44
45
46 async def _collaborator(db: AsyncSession, repo_id: str, handle: str, permission: str) -> None:
47 row = MusehubCollaborator(
48 id=compute_collaborator_id(repo_id, compute_identity_id(handle.encode()), datetime.now(timezone.utc).isoformat()),
49 repo_id=repo_id, identity_handle=handle, permission=permission)
50 db.add(row)
51 await db.flush()
52 row.accepted_at = row.invited_at
53 await db.commit()
54
55
56 # ── GET /api/user ───────────────────────────────────────────────────────────
57
58
59 async def test_current_user_requires_a_signature(client: AsyncClient) -> None:
60 resp = await client.get("/api/user")
61 assert resp.status_code == 401
62 assert "MSign" in resp.headers.get("www-authenticate", "")
63
64
65 async def test_current_user_is_the_signed_human(client: AsyncClient, auth_headers: StrDict) -> None:
66 resp = await client.get("/api/user", headers=auth_headers)
67 assert resp.status_code == 200, resp.text
68 body = resp.json()
69 assert body["handle"] == "testuser"
70 assert body["displayName"] == "Test User"
71 assert body["kind"] == "human"
72 assert body["identityId"] == compute_identity_id(b"testuser")
73 assert body["createdAt"]
74 assert body["scope"] is None
75 assert "email" not in body and "_" not in "".join(body)
76
77
78 async def test_current_user_reports_an_agent_and_its_scope(
79 client: AsyncClient, db_session: AsyncSession, signed_as
80 ) -> None:
81 db_session.add(MusehubIdentity(identity_id=compute_identity_id(b"bot-312"), handle="bot-312",
82 identity_type="agent", display_name="Bot", scope=["repo:read"]))
83 await db_session.commit()
84 signed_as("bot-312", agent=True, scope=["repo:read"])
85 body = (await client.get("/api/user")).json()
86 assert (body["handle"], body["kind"], body["scope"]) == ("bot-312", "agent", ["repo:read"])
87
88
89 # ── DELETE /api/repos/{repo_id}/releases/{tag} ──────────────────────────────
90
91
92 async def _release_with_asset(db: AsyncSession, repo_id: str, tag: str) -> str:
93 rel = await musehub_releases.create_release(db, repo_id=repo_id, tag=tag, title=tag, commit_id=None)
94 await musehub_releases.attach_asset(db, release_id=rel.release_id, repo_id=repo_id, name="a.mid",
95 download_url="https://cdn.example/a.mid")
96 await db.commit()
97 return rel.release_id
98
99
100 async def _assets(db: AsyncSession, release_id: str) -> int:
101 return (await db.execute(select(func.count()).select_from(MusehubReleaseAsset)
102 .where(MusehubReleaseAsset.release_id == release_id))).scalar_one()
103
104
105 async def test_owner_deletes_a_release_and_its_assets(
106 client: AsyncClient, db_session: AsyncSession, signed_as, monkeypatch: pytest.MonkeyPatch
107 ) -> None:
108 events: list[tuple] = []
109 monkeypatch.setattr("musehub.services.musehub_webhook_dispatcher.emit_event",
110 lambda *a: events.append(a))
111 repo = await create_repo(db_session, owner="relowner", slug="rel-del-312", visibility="public")
112 rid = str(repo.repo_id)
113 release_id = await _release_with_asset(db_session, rid, "v1.0.0")
114 assert await _assets(db_session, release_id) == 1
115 signed_as("relowner")
116
117 resp = await client.delete(f"/api/repos/{rid}/releases/v1.0.0")
118 assert resp.status_code == 204, resp.text
119 assert (await client.get(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 404
120 assert await _assets(db_session, release_id) == 0
121 assert events == [(rid, "release", {"repoId": rid, "action": "deleted", "tag": "v1.0.0", "releaseId": release_id})]
122
123 again = await client.delete(f"/api/repos/{rid}/releases/v1.0.0")
124 assert again.status_code == 404
125
126
127 async def test_admin_collaborator_may_delete_a_write_collaborator_may_not(
128 client: AsyncClient, db_session: AsyncSession, signed_as
129 ) -> None:
130 repo = await create_repo(db_session, owner="relowner", slug="rel-perm-312", visibility="public")
131 rid = str(repo.repo_id)
132 await _release_with_asset(db_session, rid, "v1.0.0")
133 await _collaborator(db_session, rid, "writer-312", "write")
134 await _collaborator(db_session, rid, "admin-312", "admin")
135
136 signed_as("writer-312")
137 assert (await client.delete(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 403
138 signed_as("stranger-312")
139 assert (await client.delete(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 403
140 signed_as("admin-312")
141 assert (await client.delete(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 204
142
143
144 async def test_release_delete_hides_a_private_repo_and_needs_release_write(
145 client: AsyncClient, db_session: AsyncSession, signed_as
146 ) -> None:
147 repo = await create_repo(db_session, owner="relowner", slug="rel-priv-312", visibility="private")
148 rid = str(repo.repo_id)
149 await _release_with_asset(db_session, rid, "v1.0.0")
150 assert (await client.delete(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 401
151 signed_as("stranger-312")
152 assert (await client.delete(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 404
153 signed_as("relowner", agent=True, scope=["repo:read"])
154 assert (await client.delete(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 403
155 signed_as("relowner", agent=True, scope=["release:write"]) # a scoped caller also needs repo read on a private repo
156 assert (await client.delete(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 404
157 signed_as("relowner", agent=True, scope=["repo:read", "release:write"])
158 assert (await client.delete(f"/api/repos/{rid}/releases/v1.0.0")).status_code == 204
159
160
161 # ── GET / PUT /api/repos/{repo_id}/topics ───────────────────────────────────
162
163
164 async def test_repo_topics_read_and_idempotent_replace(
165 client: AsyncClient, db_session: AsyncSession, auth_headers: StrDict
166 ) -> None:
167 repo = await create_repo(db_session, owner="testuser", slug="topics-312", visibility="public", tags=["old"])
168 rid = str(repo.repo_id)
169 assert (await client.get(f"/api/repos/{rid}/topics")).json() == {"repoId": rid, "topics": ["old"]}
170
171 for _ in range(2):
172 put = await client.put(f"/api/repos/{rid}/topics", json={"topics": ["Jazz", "piano", "jazz"]}, headers=auth_headers)
173 assert put.status_code == 200, put.text
174 assert put.json() == {"repoId": rid, "topics": ["jazz", "piano"]}
175 assert (await client.get(f"/api/repos/{rid}/topics")).json()["topics"] == ["jazz", "piano"]
176
177 bad = await client.put(f"/api/repos/{rid}/topics", json={"topics": ["BAD SLUG!"]}, headers=auth_headers)
178 assert bad.status_code == 422
179 gone = await client.post(f"/api/repos/{rid}/topics", json={"topics": ["x"]}, headers=auth_headers)
180 assert gone.status_code == 405
181
182
183 async def test_repo_topics_of_a_private_repo_are_hidden(
184 client: AsyncClient, db_session: AsyncSession, signed_as
185 ) -> None:
186 repo = await create_repo(db_session, owner="topicowner", slug="topics-priv-312", visibility="private", tags=["x"])
187 rid = str(repo.repo_id)
188 assert (await client.get(f"/api/repos/{rid}/topics")).status_code == 401
189 signed_as("stranger-312")
190 assert (await client.get(f"/api/repos/{rid}/topics")).status_code == 404
191 signed_as("topicowner")
192 assert (await client.get(f"/api/repos/{rid}/topics")).json()["topics"] == ["x"]
193 assert (await client.get("/api/repos/sha256:" + "0" * 64 + "/topics")).status_code == 404
194
195
196 # ── Repo update: one route ──────────────────────────────────────────────────
197
198
199 async def test_repo_metadata_is_updated_through_the_settings_route_only(
200 client: AsyncClient, db_session: AsyncSession, auth_headers: StrDict
201 ) -> None:
202 repo = await create_repo(db_session, owner="testuser", slug="patch-312", visibility="public")
203 rid = str(repo.repo_id)
204 resp = await client.patch(f"/api/repos/{rid}/settings",
205 json={"description": "new words", "visibility": "private", "domainId": "midi"},
206 headers=auth_headers)
207 assert resp.status_code == 200, resp.text
208 meta = (await client.get(f"/api/repos/{rid}", headers=auth_headers)).json()
209 assert (meta["description"], meta["visibility"], meta["domainId"]) == ("new words", "private", "midi")
210
211 bad = await client.patch(f"/api/repos/{rid}/settings", json={"visibility": "internal"}, headers=auth_headers)
212 assert bad.status_code == 422
213 assert (await client.patch(f"/api/repos/{rid}", json={"description": "x"}, headers=auth_headers)).status_code == 405
File History 2 commits
sha256:8157b0df0e2312254edef68f882db2e510f21a94655f46def61a00abc850c106 Merge branch 'task/wave-hub-rest-310-312' into dev Opus 5.5 minor ⚠ 1 day ago
sha256:157f2b8f3de428f54183520d5e16e7b0627b03322fc6a68f44a4d40b58e887b1 feat(rest): current user, release delete, repo topics GET/P… Opus 5.5 minor ⚠ 1 day ago