test_mist_validator_parity.py
python
sha256:73ca10052303079a3f5a97a247e6d768dc4c3342ff276038175661004487cc40
Merge branch 'task/mist-validator-parity' into dev
Sonnet 5.5
minor
⚠ breaking
4 days ago
| 1 | """Every mist write path applies the create-time field rules. |
| 2 | |
| 3 | ``POST /api/mists`` rejects unsafe filenames, bad tag lists and unknown |
| 4 | visibility values. ``PATCH /api/mists/{id}`` and the MCP ``muse_mist_create`` / |
| 5 | ``muse_mist_update`` tools must reject the same values and store nothing. The |
| 6 | rules live once (``musehub.models.mists.validate_mist_fields``) and are applied by |
| 7 | the request models, the MCP tools before any side effect, and the service layer. |
| 8 | """ |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import secrets |
| 12 | from collections.abc import AsyncGenerator |
| 13 | |
| 14 | import pytest |
| 15 | from httpx import AsyncClient |
| 16 | from sqlalchemy import func, select |
| 17 | from sqlalchemy.ext.asyncio import AsyncSession |
| 18 | |
| 19 | from musehub.auth.request_signing import MSignContext, optional_signed_request, require_signed_request |
| 20 | from musehub.core.genesis import compute_identity_id |
| 21 | from musehub.db.musehub_identity_models import MusehubIdentity |
| 22 | from musehub.db.musehub_repo_models import MusehubMist, MusehubRepo |
| 23 | from musehub.main import app |
| 24 | from musehub.mcp.write_tools.mists import execute_create_mist, execute_update_mist |
| 25 | |
| 26 | OWNER = "carol" |
| 27 | |
| 28 | BAD_FILENAMES = [ |
| 29 | "../escape.py", |
| 30 | "dir/name.py", |
| 31 | "dir\\name.py", |
| 32 | "red\x1b[31m.py", |
| 33 | "bell\x07.py", |
| 34 | "nul\x00.py", |
| 35 | "", |
| 36 | ] |
| 37 | BAD_TAG_LISTS = [ |
| 38 | [f"t{i}" for i in range(11)], |
| 39 | ["x" * 65], |
| 40 | ["<b>bold</b>"], |
| 41 | ["a&b"], |
| 42 | ['quo"te'], |
| 43 | ["nul\x00"], |
| 44 | ] |
| 45 | BAD_VISIBILITY = ["friends", "PUBLIC", ""] |
| 46 | |
| 47 | |
| 48 | def validate_mist_fields(**kwargs: object) -> None: |
| 49 | from musehub.models.mists import validate_mist_fields as _shared |
| 50 | |
| 51 | _shared(**kwargs) # type: ignore[arg-type] |
| 52 | |
| 53 | |
| 54 | def _as(handle: str | None) -> None: |
| 55 | if handle is None: |
| 56 | app.dependency_overrides.pop(require_signed_request, None) |
| 57 | app.dependency_overrides.pop(optional_signed_request, None) |
| 58 | return |
| 59 | ctx = MSignContext(handle=handle, identity_id=compute_identity_id(handle.encode()), is_agent=False, is_admin=False) |
| 60 | app.dependency_overrides[require_signed_request] = lambda: ctx |
| 61 | app.dependency_overrides[optional_signed_request] = lambda: ctx |
| 62 | |
| 63 | |
| 64 | @pytest.fixture |
| 65 | async def owner(db_session: AsyncSession) -> AsyncGenerator[None, None]: |
| 66 | db_session.add( |
| 67 | MusehubIdentity( |
| 68 | identity_id=compute_identity_id(OWNER.encode()), handle=OWNER, display_name=OWNER, identity_type="human" |
| 69 | ) |
| 70 | ) |
| 71 | await db_session.commit() |
| 72 | _as(OWNER) |
| 73 | yield |
| 74 | _as(None) |
| 75 | |
| 76 | |
| 77 | async def _new_mist() -> str: |
| 78 | r = await execute_create_mist(filename="note.py", content=f"x = 1 # {secrets.token_hex(16)}", actor=OWNER) |
| 79 | assert r.ok, r |
| 80 | return str(r.data["mist_id"]) |
| 81 | |
| 82 | |
| 83 | async def _row(db: AsyncSession, mist_id: str) -> MusehubMist: |
| 84 | db.expire_all() |
| 85 | return (await db.execute(select(MusehubMist).where(MusehubMist.mist_id == mist_id))).scalar_one() |
| 86 | |
| 87 | |
| 88 | async def _counts(db: AsyncSession) -> tuple[int, int]: |
| 89 | db.expire_all() |
| 90 | mists = (await db.execute(select(func.count()).select_from(MusehubMist))).scalar_one() |
| 91 | repos = (await db.execute(select(func.count()).select_from(MusehubRepo))).scalar_one() |
| 92 | return int(mists), int(repos) |
| 93 | |
| 94 | |
| 95 | # --- the shared rule set --------------------------------------------------- |
| 96 | |
| 97 | |
| 98 | @pytest.mark.parametrize("bad", BAD_FILENAMES) |
| 99 | def test_shared_rules_reject_each_unsafe_filename(bad: str) -> None: |
| 100 | with pytest.raises(ValueError): |
| 101 | validate_mist_fields(filename=bad) |
| 102 | |
| 103 | |
| 104 | @pytest.mark.parametrize("bad", BAD_TAG_LISTS) |
| 105 | def test_shared_rules_reject_each_bad_tag_list(bad: list[str]) -> None: |
| 106 | with pytest.raises(ValueError): |
| 107 | validate_mist_fields(tags=bad) |
| 108 | |
| 109 | |
| 110 | @pytest.mark.parametrize("bad", BAD_VISIBILITY) |
| 111 | def test_shared_rules_reject_unknown_visibility(bad: str) -> None: |
| 112 | with pytest.raises(ValueError): |
| 113 | validate_mist_fields(visibility=bad) |
| 114 | |
| 115 | |
| 116 | def test_shared_rules_accept_valid_values_and_skip_none() -> None: |
| 117 | validate_mist_fields() |
| 118 | validate_mist_fields(filename="ok-name_1.py", tags=["a", "b" * 64], visibility="secret") |
| 119 | validate_mist_fields(tags=[f"t{i}" for i in range(10)], visibility="public") |
| 120 | |
| 121 | |
| 122 | # --- REST PATCH ------------------------------------------------------------ |
| 123 | |
| 124 | |
| 125 | @pytest.mark.parametrize("bad", [b for b in BAD_FILENAMES if b]) |
| 126 | async def test_patch_rejects_unsafe_filename_and_stores_nothing(client: AsyncClient, db_session: AsyncSession, owner: None, bad: str) -> None: |
| 127 | mid = await _new_mist() |
| 128 | resp = await client.patch(f"/api/mists/{mid}", json={"filename": bad}) |
| 129 | assert resp.status_code == 422, resp.text |
| 130 | assert (await _row(db_session, mid)).filename == "note.py" |
| 131 | |
| 132 | |
| 133 | @pytest.mark.parametrize("bad", BAD_TAG_LISTS) |
| 134 | async def test_patch_rejects_bad_tags_and_stores_nothing(client: AsyncClient, db_session: AsyncSession, owner: None, bad: list[str]) -> None: |
| 135 | mid = await _new_mist() |
| 136 | resp = await client.patch(f"/api/mists/{mid}", json={"tags": bad}) |
| 137 | assert resp.status_code == 422, resp.text |
| 138 | assert list((await _row(db_session, mid)).tags or []) == [] |
| 139 | |
| 140 | |
| 141 | async def test_patch_accepts_valid_filename_and_tags(client: AsyncClient, db_session: AsyncSession, owner: None) -> None: |
| 142 | mid = await _new_mist() |
| 143 | resp = await client.patch(f"/api/mists/{mid}", json={"filename": "renamed.py", "tags": ["a", "b"], "visibility": "secret"}) |
| 144 | assert resp.status_code == 200, resp.text |
| 145 | row = await _row(db_session, mid) |
| 146 | assert (row.filename, list(row.tags), row.visibility) == ("renamed.py", ["a", "b"], "secret") |
| 147 | |
| 148 | |
| 149 | # --- MCP muse_mist_update -------------------------------------------------- |
| 150 | |
| 151 | |
| 152 | @pytest.mark.parametrize("bad", [b for b in BAD_FILENAMES if b]) |
| 153 | async def test_mcp_update_rejects_unsafe_filename(db_session: AsyncSession, owner: None, bad: str) -> None: |
| 154 | mid = await _new_mist() |
| 155 | r = await execute_update_mist(mist_id=mid, actor=OWNER, filename=bad) |
| 156 | assert (r.ok, r.error_code) == (False, "invalid_args"), r |
| 157 | assert (await _row(db_session, mid)).filename == "note.py" |
| 158 | |
| 159 | |
| 160 | @pytest.mark.parametrize("bad", BAD_TAG_LISTS) |
| 161 | async def test_mcp_update_rejects_bad_tags(db_session: AsyncSession, owner: None, bad: list[str]) -> None: |
| 162 | mid = await _new_mist() |
| 163 | r = await execute_update_mist(mist_id=mid, actor=OWNER, tags=bad) |
| 164 | assert (r.ok, r.error_code) == (False, "invalid_args"), r |
| 165 | assert list((await _row(db_session, mid)).tags or []) == [] |
| 166 | |
| 167 | |
| 168 | @pytest.mark.parametrize("bad", BAD_VISIBILITY) |
| 169 | async def test_mcp_update_rejects_unknown_visibility(db_session: AsyncSession, owner: None, bad: str) -> None: |
| 170 | mid = await _new_mist() |
| 171 | r = await execute_update_mist(mist_id=mid, actor=OWNER, visibility=bad) |
| 172 | assert (r.ok, r.error_code) == (False, "invalid_args"), r |
| 173 | assert (await _row(db_session, mid)).visibility == "public" |
| 174 | |
| 175 | |
| 176 | async def test_mcp_update_accepts_valid_values(db_session: AsyncSession, owner: None) -> None: |
| 177 | mid = await _new_mist() |
| 178 | r = await execute_update_mist(mist_id=mid, actor=OWNER, filename="renamed.py", tags=["a"], visibility="secret") |
| 179 | assert r.ok, r |
| 180 | row = await _row(db_session, mid) |
| 181 | assert (row.filename, list(row.tags), row.visibility) == ("renamed.py", ["a"], "secret") |
| 182 | |
| 183 | |
| 184 | # --- MCP muse_mist_create -------------------------------------------------- |
| 185 | |
| 186 | |
| 187 | @pytest.mark.parametrize( |
| 188 | "kwargs", |
| 189 | [{"filename": "../x.py"}, {"filename": "a\x1b[31m.py"}, {"tags": [f"t{i}" for i in range(11)]}, {"tags": ["<i>"]}, {"visibility": "friends"}], |
| 190 | ) |
| 191 | async def test_mcp_create_rejects_unsafe_values_and_creates_nothing(db_session: AsyncSession, owner: None, kwargs: dict[str, object]) -> None: |
| 192 | before = await _counts(db_session) |
| 193 | args: dict[str, object] = {"filename": "note.py", "content": f"y = 2 # {secrets.token_hex(16)}", "actor": OWNER} |
| 194 | args.update(kwargs) |
| 195 | r = await execute_create_mist(**args) # type: ignore[arg-type] |
| 196 | assert (r.ok, r.error_code) == (False, "invalid_args"), r |
| 197 | assert await _counts(db_session) == before |
File History
2 commits
sha256:73ca10052303079a3f5a97a247e6d768dc4c3342ff276038175661004487cc40
Merge branch 'task/mist-validator-parity' into dev
Sonnet 5.5
minor
⚠
4 days ago
sha256:951821801a6c8638659a92fae2606899bf1a689ce30e7d488f795c0b0a34391f
fix(mists): every write path applies the create-time field rules
Sonnet 5.5
minor
⚠
4 days ago