"""Tests for ContentSizeLimitMiddleware (checklist 2.3 — body size cap).""" from __future__ import annotations import pytest from httpx import AsyncClient from musehub.middleware.content_size import API_MAX_BYTES, PUSH_MAX_BYTES async def test_api_request_within_limit_passes( client: AsyncClient, ) -> None: """A body under 10 MB on an API route must not be rejected by the middleware.""" small_body = b"x" * 1024 # 1 KB resp = await client.post( "/api/repos", content=small_body, headers={"Content-Type": "application/json", "Content-Length": str(len(small_body))}, ) # May be 422 (invalid JSON) or 401 (auth required) — not 413 assert resp.status_code != 413 async def test_api_request_over_limit_returns_413( client: AsyncClient, ) -> None: """Content-Length over 10 MB on a non-push route must return 413.""" over_limit = API_MAX_BYTES + 1 resp = await client.post( "/api/repos", headers={"Content-Length": str(over_limit)}, content=b"", # actual body irrelevant — Content-Length header drives the check ) assert resp.status_code == 413 assert "too large" in resp.json()["detail"].lower() async def test_push_mpack_presign_under_push_limit_not_rejected( client: AsyncClient, ) -> None: """Content-Length under 500 MB on push/mpack-presign must not be rejected.""" import json body = json.dumps({"mpack_key": "sha256:" + "a" * 64, "size_bytes": 1024}).encode() # No auth → will get 401, but that's AFTER the size check — must not be 413 resp = await client.post( "/gabriel/my-repo/push/mpack-presign", content=body, headers={"Content-Type": "application/json"}, ) assert resp.status_code != 413 async def test_push_mpack_presign_over_api_limit_but_under_push_limit_allowed( client: AsyncClient, ) -> None: """A 20 MB Content-Length on push/mpack-presign must NOT return 413 (push limit is 500 MB).""" over_api_limit = API_MAX_BYTES * 2 # 20 MB — over API limit but under push limit resp = await client.post( "/gabriel/my-repo/push/mpack-presign", headers={"Content-Length": str(over_api_limit)}, content=b"", ) # Should get 401 (no auth) or 422 (bad body) — not 413 assert resp.status_code != 413 async def test_push_mpack_presign_path_uses_push_limit( client: AsyncClient, ) -> None: """/{owner}/{slug}/push/mpack-presign must use the 500 MB limit, not 10 MB.""" over_api_limit = API_MAX_BYTES + 1 resp = await client.post( "/gabriel/my-repo/push/mpack-presign", headers={"Content-Length": str(over_api_limit)}, content=b"", ) assert resp.status_code != 413 def test_limits_are_correct_values() -> None: assert API_MAX_BYTES == 10 * 1024 * 1024 assert PUSH_MAX_BYTES == 500 * 1024 * 1024