paste-bin/tests/test_paste_api.py
Jarian 985e070757 port: FastAPI rewrite built by the arch-llm spec pipeline
Spec-first port of the Flask app (still on main):
- schema.arch: signed arch-llm spec (single source of truth)
- paste_bin/: generated FastAPI backend, verified 51/51 frozen owner
  tests, 92.5% coverage (build r3, 2026-11-18)
- ui/: SPA + emitted OpenAPI contract (openapi.json + generated
  client.js); the app calls only window.PasteBinAPI
- 7 old bugs fixed (file raw 500, silent expiry, AVI-as-webp,
  stripped content, limiter leak, trusted mimetype, stale tmp)
- 62/62 live probe green; /health + JSON index added; JSON API

Full report on the wiki: 'FastAPI port (arch-llm pipeline)'.
2026-11-18 23:00:23 +00:00

339 lines
11 KiB
Python

# tests for module api (paste_bin/api.py)
# Owner test: at `api` verify time the app entrypoint is still a stub,
# so this mounts paste_router on its own app (no paste_bin.app import).
# The store is exercised through the router. STORE_FOLDER / UPLOAD_FOLDER
# are set only for the duration of the import (the api module builds its
# _store at import time) and restored afterwards so sibling test files
# are untouched.
import io
import os
import re
import tempfile
_TMP = tempfile.mkdtemp(prefix="paste_bin_owner_")
_prev_store = os.environ.get("STORE_FOLDER")
_prev_upload = os.environ.get("UPLOAD_FOLDER")
os.environ["STORE_FOLDER"] = os.path.join(_TMP, "store")
os.environ["UPLOAD_FOLDER"] = os.path.join(_TMP, "uploads")
from fastapi import FastAPI # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
from paste_bin.api import paste_router # noqa: E402
from paste_bin import api as api_mod # noqa: E402
from paste_bin.ratelimit import UploadRateLimiter # noqa: E402
if _prev_store is None:
del os.environ["STORE_FOLDER"]
else:
os.environ["STORE_FOLDER"] = _prev_store
if _prev_upload is None:
del os.environ["UPLOAD_FOLDER"]
else:
os.environ["UPLOAD_FOLDER"] = _prev_upload
app = FastAPI()
app.include_router(paste_router)
client = TestClient(app)
# The import-time limiter instance, captured before any fixture can swap it —
# used to assert the module-level construction contract (10/60, no inflation).
_IMPORT_TIME_LIMITER = api_mod._limiter
import pytest # noqa: E402
@pytest.fixture(autouse=True)
def _fresh_limiter_per_test():
# every POST to /pastes consumes a rate slot (the limiter runs first,
# even on requests that later 400). The suite makes more than 10 posts,
# so each test gets a fresh 10/60 limiter; the module-level instance is
# restored afterwards.
orig = api_mod._limiter
api_mod._limiter = UploadRateLimiter(max_attempts=10, window_seconds=60)
yield
api_mod._limiter = orig
PNG_BYTES = b"\x89PNG\r\n\x1a\n" + b"\x00" * 16
WEBP_BYTES = b"RIFF\x00\x00\x00\x00WEBP" + b"\x00" * 8
AVI_RIFF_BYTES = b"RIFF\x00\x00\x00\x00AVI " + b"\x00" * 8
def _post_text(content, title="t", expiry="1d"):
return client.post(
"/pastes",
data={"paste_type": "text", "title": title, "expiry": expiry, "content": content},
)
def _post_file(fname, data, paste_type, title="t", expiry="1d"):
return client.post(
"/pastes",
data={"paste_type": paste_type, "title": title, "expiry": expiry},
files={"file": (fname, io.BytesIO(data), "application/octet-stream")},
)
def _create_ok(r):
assert r.status_code == 201, r.text
return r.json()
# --- basic routes ---------------------------------------------------------
def test_routes_registered():
paths = app.openapi()["paths"]
assert "/pastes" in paths
assert "/pastes/{paste_id}" in paths
assert "/pastes/{paste_id}/raw" in paths
assert "/pastes/{paste_id}/download" in paths
assert "/health" in paths
assert "/" in paths
def test_index():
r = client.get("/")
assert r.status_code == 200
body = r.json()
assert body["service"] == "paste-bin"
assert "/pastes" in body["endpoints"]
assert "/health" in body["endpoints"]
def test_health():
r = client.get("/health")
assert r.status_code == 200
assert r.json() == {"status": "ok"}
def test_security_headers_present():
r = client.get("/health")
assert r.headers.get("X-Content-Type-Options") == "nosniff"
assert r.headers.get("X-Frame-Options") == "DENY"
assert r.headers.get("X-XSS-Protection") == "1; mode=block"
assert r.headers.get("Referrer-Policy") == "strict-origin-when-cross-origin"
assert "Content-Security-Policy" in r.headers
def test_module_limiter_uses_class_defaults():
# the IMPORT-TIME module-level limiter must be the pinned 10/60 contract —
# no config indirection, no inflated limits (the per-test fixture swaps
# api_mod._limiter, so assert on the captured import-time instance)
assert _IMPORT_TIME_LIMITER.max_attempts == 10
assert _IMPORT_TIME_LIMITER.window_seconds == 60
def test_head_supported_on_get_routes():
# Flask auto-added HEAD to GET routes; the port must keep that ability
# (FastAPI does not — 405 without explicit methods=['GET', 'HEAD'])
r = client.request("HEAD", "/health")
assert r.status_code == 200
assert r.content == b""
r = client.request("HEAD", "/pastes/ffffffffffffffff")
assert r.status_code == 404
# --- text pastes ----------------------------------------------------------
def test_text_paste_roundtrip():
r = _post_text("hello world", title="hi")
body = _create_ok(r)
pid = body["id"]
assert re.fullmatch(r"[a-f0-9]{16}", pid)
assert body["type"] == "text"
assert body["title"] == "hi"
assert body["view"] == f"/pastes/{pid}"
assert body["raw"] == f"/pastes/{pid}/raw"
assert body["download"] == f"/pastes/{pid}/download"
assert body["expires_at"] is not None
v = client.get(f"/pastes/{pid}")
assert v.status_code == 200
vb = v.json()
assert vb["type"] == "text"
assert vb["content"] == "hello world"
assert vb["filename"] is None
assert vb["mimetype"] is None
raw = client.get(f"/pastes/{pid}/raw")
assert raw.status_code == 200
assert raw.content == b"hello world"
assert raw.headers["content-type"].startswith("text/plain")
dl = client.get(f"/pastes/{pid}/download")
assert dl.status_code == 200
assert dl.content == b"hello world"
assert "attachment" in dl.headers.get("content-disposition", "")
def test_text_content_stored_verbatim():
payload = " leading spaces\n\ntrailing newline\n"
body = _create_ok(_post_text(payload))
raw = client.get(f"/pastes/{body['id']}/raw")
assert raw.status_code == 200
assert raw.content == payload.encode("utf-8")
def test_empty_content_400():
r = _post_text(" \n ")
assert r.status_code == 400
assert r.json()["error"] == "Content cannot be empty"
def test_invalid_expiry_400():
r = _post_text("x", expiry="2 weeks")
assert r.status_code == 400
assert r.json()["error"] == "Invalid expiry"
def test_invalid_paste_type_400():
r = client.post(
"/pastes",
data={"paste_type": "video", "title": "x", "expiry": "1d", "content": "c"},
)
assert r.status_code == 400
assert r.json()["error"] == "Invalid paste type"
def test_forever_paste_has_no_expiry():
body = _create_ok(_post_text("keep", expiry="forever"))
assert body["expires_at"] is None
v = client.get(f"/pastes/{body['id']}")
assert v.status_code == 200
assert v.json()["expires_at"] is None
# --- ids ------------------------------------------------------------------
def test_unknown_paste_id_404():
r = client.get("/pastes/" + "z" * 16)
assert r.status_code == 404
assert r.json()["error"] == "Paste not found"
def test_malformed_ids_404():
assert client.get("/pastes/abc").status_code == 404 # too short
assert client.get("/pastes/" + "g" * 16).status_code == 404 # not hex
def test_expired_paste_404_and_deleted():
body = _create_ok(_post_text("doomed", expiry="1h"))
pid = body["id"]
# whitebox: force the expiry into the past
meta = api_mod._store.load_meta(pid)
meta["expires_at"] = "2020-01-01T00:00:00+00:00"
api_mod._store.save_meta(pid, meta)
r = client.get(f"/pastes/{pid}")
assert r.status_code == 404
assert r.json()["error"] == "Paste not found"
assert api_mod._store.load_meta(pid) is None # deleted on view
# --- image uploads ---------------------------------------------------------
def test_svg_upload_rejected():
r = _post_file("evil.svg", b"<svg></svg>", "image")
assert r.status_code == 400
assert r.json()["error"] == "Invalid image format"
def test_fake_image_magic_rejected():
r = _post_file("fake.png", b"not a png at all", "image")
assert r.status_code == 400
assert r.json()["error"] == "File content does not match image type."
def test_riff_avi_rejected_as_webp():
# old bug: any RIFF container passed the webp check
r = _post_file("clip.webp", AVI_RIFF_BYTES, "image")
assert r.status_code == 400
assert r.json()["error"] == "File content does not match image type."
def test_valid_webp_accepted():
body = _create_ok(_post_file("anim.webp", WEBP_BYTES, "image"))
assert body["type"] == "image"
def test_image_paste_roundtrip():
body = _create_ok(_post_file("pic.png", PNG_BYTES, "image", title="pic"))
pid = body["id"]
assert body["type"] == "image"
v = client.get(f"/pastes/{pid}")
assert v.status_code == 200
vb = v.json()
assert vb["filename"] == "pic.png"
assert vb["mimetype"] == "image/png"
assert vb["content"] is None
raw = client.get(f"/pastes/{pid}/raw")
assert raw.status_code == 200
assert raw.content == PNG_BYTES
assert raw.headers["content-type"].split(";")[0].strip() == "image/png"
def test_no_file_for_image_400():
r = client.post("/pastes", data={"paste_type": "image", "title": "x", "expiry": "1d"})
assert r.status_code == 400
assert r.json()["error"] == "No file selected"
def test_empty_filename_400():
r = _post_file("...", b"x", "image")
assert r.status_code == 400
assert r.json()["error"] == "No file selected"
# --- file uploads -----------------------------------------------------------
def test_text_file_upload_stored_as_text():
code = "print('hi')\n"
body = _create_ok(_post_file("hello.py", code.encode(), "file"))
assert body["type"] == "text"
pid = body["id"]
v = client.get(f"/pastes/{pid}")
assert v.status_code == 200
vb = v.json()
assert vb["content"] == code
assert vb["filename"] == "hello.py"
raw = client.get(f"/pastes/{pid}/raw")
assert raw.status_code == 200
assert raw.content == code.encode()
def test_binary_file_upload_roundtrip():
data = bytes(range(256)) * 4
body = _create_ok(_post_file("blob.bin", data, "file"))
assert body["type"] == "file"
pid = body["id"]
v = client.get(f"/pastes/{pid}")
assert v.status_code == 200
assert v.json()["mimetype"] == "application/octet-stream"
# raw on a file-type paste (old bug: fell through to 500)
raw = client.get(f"/pastes/{pid}/raw")
assert raw.status_code == 200
assert raw.content == data
def test_upload_too_large_413():
big = b"A" * (20 * 1024 * 1024 + 1)
r = _post_file("big.bin", big, "file")
assert r.status_code == 413
assert r.json()["error"] == "File too large. Maximum size is 20 MB."
# --- rate limiting (must run last: resets the shared limiter) ---------------
def test_rate_limit_11th_upload_429():
# the autouse fixture provides a fresh 10/60 limiter for this test
for i in range(10):
r = _post_text(f"rl {i}", title=f"rl{i}")
assert r.status_code == 201, r.text
r = _post_text("rl 11", title="rl11")
assert r.status_code == 429
assert r.json()["error"] == "Too many uploads. Please wait."