- import ZIP: odczyt czlonka nigdy nie rozpakowuje ponad zadeklarowany rozmiar + 1 (zf.read() rozpakowywal calosc i dopiero przycinal: 300 KB -> 600 MB pamieci) - naglowek SKILL.md: daty zostaja tekstem, wartosci spoza JSON (binary, set, NaN) = odrzucenie zamiast bledu 500 przy zapisie do JSONB - trasy /skills i /agents czytaja cialo JSON strumieniowo z limitem 14 MB; metadata i model_policy maks. 8 KB - ekran zgody: roznica wersji obejmuje licencje, metadata, model_policy i narzedzia agenta - nazwy skilli i agentow w naglowku strony poza tlumaczeniem interfejsu - testy: bomba z falszywym rozmiarem, limit strumienia na poziomie ASGI (TestClient czyta cale cialo, wiec dawny test byl zielony z konstrukcji), ponowne sprawdzenie przypiec agenta przy zatwierdzeniu; wszystkie zweryfikowane mutacja Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016uwxqJbh3fPYdfdLG3MU6f
189 lines
8.0 KiB
Python
189 lines
8.0 KiB
Python
"""The skills HTTP surface, DB-free: the routes exist under /api/v1, and what the router itself
|
|
decides — the streamed 10 MB ceiling on an import, base64 files, the ZIP response — reaches the
|
|
service the way the service expects. The rules behind the routes are `test_skills_unit.py`'s."""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import types
|
|
import uuid
|
|
|
|
import pytest
|
|
from fastapi.routing import APIRoute
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app import deps
|
|
from app.db import get_db
|
|
from app.main import app
|
|
from app.services import skills as service
|
|
from app.routers.skills import MAX_JSON_BODY_BYTES
|
|
from app.services.skill_pack import MAX_PACK_BYTES
|
|
|
|
API = "/api/v1"
|
|
SKILL_ID = uuid.uuid4()
|
|
|
|
|
|
def test_every_skills_route_is_registered_under_the_api_prefix():
|
|
bound = {(m, r.path) for r in app.routes if isinstance(r, APIRoute) for m in r.methods}
|
|
for method, path in [
|
|
("GET", "/skills"), ("POST", "/skills"), ("GET", "/skills/{skill_id}"),
|
|
("POST", "/skills/{skill_id}/versions"), ("GET", "/skills/{skill_id}/versions/{n}"),
|
|
("POST", "/skills/{skill_id}/archive"), ("POST", "/skills/{skill_id}/publish"),
|
|
("GET", "/skills/{skill_id}/export"), ("POST", "/skills/import"),
|
|
]:
|
|
assert (method, API + path) in bound, (method, path)
|
|
|
|
|
|
class _Db:
|
|
def commit(self):
|
|
pass
|
|
|
|
|
|
@pytest.fixture
|
|
def api(monkeypatch):
|
|
"""`calls` records what reached the service; nothing touches a database."""
|
|
calls: dict = {}
|
|
user = types.SimpleNamespace(id=uuid.uuid4(), is_admin=False)
|
|
app.dependency_overrides[get_db] = _Db
|
|
app.dependency_overrides[deps.get_current_user] = lambda: user
|
|
|
|
def fake(name, result):
|
|
def _f(db, actor, *args, **kwargs):
|
|
calls[name] = (args, kwargs)
|
|
return result
|
|
monkeypatch.setattr(service, name, _f)
|
|
|
|
fake("import_skills", {"status": "imported", "skills": [], "ignored": []})
|
|
fake("new_version", {"n": 2})
|
|
fake("export_skill", ("nda-v3.zip", b"PK\x05\x06" + bytes(18)))
|
|
try:
|
|
yield types.SimpleNamespace(client=TestClient(app), calls=calls)
|
|
finally:
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
def test_import_passes_the_raw_body_and_its_name_to_the_service(api):
|
|
r = api.client.post(f"{API}/skills/import?filename=nda.zip&add_version=true", content=b"PK-bytes",
|
|
headers={"Content-Type": "application/zip"})
|
|
assert r.status_code == 200, r.text
|
|
args, kwargs = api.calls["import_skills"]
|
|
assert args == (b"PK-bytes", "nda.zip") and kwargs["add_version"] is True
|
|
|
|
|
|
@pytest.mark.parametrize("chunked", [False, True])
|
|
def test_an_import_over_10_mb_is_refused_before_the_service(api, chunked):
|
|
big = b"x" * (MAX_PACK_BYTES + 1)
|
|
# A generator body goes out chunked, with no Content-Length: only the streamed count catches it.
|
|
content = (big[i:i + 65536] for i in range(0, len(big), 65536)) if chunked else big
|
|
r = api.client.post(f"{API}/skills/import", content=content,
|
|
headers={"Content-Type": "application/zip"})
|
|
assert r.status_code == 422 and r.json()["code"] == "pack_too_large"
|
|
assert "import_skills" not in api.calls
|
|
|
|
|
|
@pytest.mark.parametrize("path, cap", [
|
|
("/skills/import", MAX_PACK_BYTES), # zip_body
|
|
(f"/skills/{SKILL_ID}/versions", MAX_JSON_BODY_BYTES), # CappedBodyRoute
|
|
])
|
|
def test_an_oversized_body_stops_being_read_at_the_cap(api, path, cap):
|
|
"""Not only refused: reading STOPS at the cap. Buffering the whole body first and measuring it
|
|
afterwards answers the same 422, so the result alone cannot tell the two apart. ASGI-level,
|
|
because TestClient reads the whole request body before the app sees a byte."""
|
|
import asyncio
|
|
chunk, received, status = b"x" * 65536, [0], []
|
|
ctype = b"application/zip" if path.endswith("import") else b"application/json"
|
|
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "POST",
|
|
"scheme": "http", "path": f"{API}{path}", "raw_path": f"{API}{path}".encode(),
|
|
"root_path": "", "query_string": b"", "server": ("testserver", 80),
|
|
"client": ("127.0.0.1", 1), "headers": [(b"host", b"testserver"), (b"content-type", ctype)]}
|
|
|
|
async def receive():
|
|
received[0] += len(chunk)
|
|
return {"type": "http.request", "body": chunk, "more_body": received[0] < 10 * cap}
|
|
|
|
async def send(message):
|
|
if message["type"] == "http.response.start":
|
|
status.append(message["status"])
|
|
|
|
asyncio.run(app(scope, receive, send))
|
|
assert status == [422]
|
|
assert received[0] < cap + 4 * len(chunk), received[0]
|
|
|
|
|
|
@pytest.mark.parametrize("field", ["metadata", "model_policy"])
|
|
def test_free_form_json_over_8_kb_is_a_422(api, field):
|
|
path = f"/skills/{SKILL_ID}/versions" if field == "metadata" else f"/agents/{SKILL_ID}/versions"
|
|
r = api.client.post(f"{API}{path}", json={field: {"x": "y" * 9000}})
|
|
assert r.status_code == 422
|
|
|
|
|
|
def test_a_new_version_decodes_files_and_leaves_absent_fields_none(api):
|
|
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions",
|
|
json={"body": "# v2", "files": {"a.txt": base64.b64encode(b"hi").decode()}})
|
|
assert r.status_code == 201, r.text
|
|
(skill_id, fields), _ = api.calls["new_version"]
|
|
assert skill_id == SKILL_ID
|
|
assert fields["files"] == {"a.txt": b"hi"} and fields["body"] == "# v2"
|
|
assert fields["description"] is None and fields["metadata"] is None # None = carry over
|
|
|
|
|
|
@pytest.mark.parametrize("files", [
|
|
{"a.txt": "not base64!"},
|
|
["a.txt"],
|
|
{"a.txt": base64.b64encode(b"x" * (MAX_PACK_BYTES // 2 + 1)).decode(),
|
|
"b.txt": base64.b64encode(b"x" * (MAX_PACK_BYTES // 2 + 1)).decode()},
|
|
])
|
|
def test_bad_or_oversized_files_are_a_422(api, files):
|
|
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"files": files})
|
|
assert r.status_code == 422
|
|
assert "new_version" not in api.calls
|
|
|
|
|
|
def test_export_answers_a_zip_attachment(api):
|
|
r = api.client.get(f"{API}/skills/{SKILL_ID}/export?n=3")
|
|
assert r.status_code == 200
|
|
assert r.headers["content-type"] == "application/zip"
|
|
assert r.headers["content-disposition"] == 'attachment; filename="nda-v3.zip"'
|
|
assert api.calls["export_skill"][0] == (SKILL_ID, 3)
|
|
|
|
|
|
def test_every_agent_and_publish_request_route_is_registered_under_the_api_prefix():
|
|
bound = {(m, r.path) for r in app.routes if isinstance(r, APIRoute) for m in r.methods}
|
|
for method, path in [
|
|
("GET", "/agents"), ("POST", "/agents"), ("GET", "/agents/{agent_id}"),
|
|
("POST", "/agents/{agent_id}/versions"), ("POST", "/agents/{agent_id}/archive"),
|
|
("POST", "/agents/{agent_id}/publish"), ("GET", "/agents/{agent_id}/export"),
|
|
("POST", "/agents/import"), ("GET", "/admin/publish-requests"),
|
|
("POST", "/admin/publish-requests/{request_id}/approve"),
|
|
("POST", "/admin/publish-requests/{request_id}/decline"),
|
|
]:
|
|
assert (method, API + path) in bound, (method, path)
|
|
|
|
|
|
def _calls(dependant):
|
|
for d in dependant.dependencies:
|
|
yield d.call
|
|
yield from _calls(d)
|
|
|
|
|
|
def test_every_publish_request_route_depends_on_require_administrator():
|
|
routes = [r for r in app.routes
|
|
if isinstance(r, APIRoute) and r.path.startswith(API + "/admin/publish-requests")]
|
|
assert len(routes) == 3
|
|
for r in routes:
|
|
assert deps.require_administrator in set(_calls(r.dependant)), r.path
|
|
|
|
|
|
def test_a_non_administrator_is_refused_the_publish_queue(api):
|
|
r = api.client.get(f"{API}/admin/publish-requests")
|
|
assert r.status_code == 403
|
|
|
|
|
|
def test_a_new_agent_version_passes_pins_and_leaves_absent_fields_none(api, monkeypatch):
|
|
pin = uuid.uuid4()
|
|
seen = {}
|
|
monkeypatch.setattr(service, "new_agent_version",
|
|
lambda db, actor, agent_id, fields, ip: seen.update(fields) or {"n": 2})
|
|
r = api.client.post(f"{API}/agents/{SKILL_ID}/versions", json={"skill_version_ids": [str(pin)]})
|
|
assert r.status_code == 201, r.text
|
|
assert seen["skill_version_ids"] == [pin] and seen["instructions"] is None
|