feat: per-IP rate limit and write bans

Apply sliding-window 2/s limits and BannedIP checks on write routes.
Also force SVG attachment disposition and claim burn-after-read in DB
before streaming, deleting the file via BackgroundTask after the response.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
肉末
2026-07-14 12:52:45 +08:00
parent f2a1f3a1d6
commit 175a4ad0d1
6 changed files with 197 additions and 19 deletions
+80
View File
@@ -119,3 +119,83 @@ def test_file_burn_after_download_not_metadata(client):
assert client.get(f"/api/items/{slug}/file").status_code == 404
assert client.get(f"/api/items/{slug}").status_code == 404
def test_svg_forced_attachment_disposition(client):
files = {"file": ("xss.svg", b"<svg xmlns='http://www.w3.org/2000/svg'></svg>", "image/svg+xml")}
r = client.post(
"/api/items/upload",
files=files,
data={"is_public": "true", "ttl": "24h"},
)
assert r.status_code == 200
slug = r.json()["slug"]
f = client.get(f"/api/items/{slug}/file")
assert f.status_code == 200
cd = f.headers.get("content-disposition", "")
assert "attachment" in cd
assert "inline" not in cd.split(";")[0]
def test_burn_claims_before_stream(client, monkeypatch):
"""burned=True is set before streaming, not only in the post-response BackgroundTask."""
import app.db as db_module
import app.api.public as public_api
from app.models import Item
from sqlalchemy import select
# Background only deletes bytes; claiming is done in the request handler.
monkeypatch.setattr(public_api, "_delete_file_path", lambda *_a, **_k: None)
files = {"file": ("once.txt", b"payload", "text/plain")}
r = client.post(
"/api/items/upload",
files=files,
data={"is_public": "true", "ttl": "never", "burn_after_read": "true"},
)
assert r.status_code == 200
slug = r.json()["slug"]
first = client.get(f"/api/items/{slug}/file")
assert first.status_code == 200
assert first.content == b"payload"
db = db_module.SessionLocal()
try:
item = db.scalar(select(Item).where(Item.slug == slug))
assert item is not None
assert item.burned is True
finally:
db.close()
assert client.get(f"/api/items/{slug}/file").status_code == 404
def test_rate_limit_third_request_in_same_second(client, monkeypatch):
import app.config as config_module
from app.services import rate_limit as rate_limit_module
monkeypatch.setattr(config_module.settings, "rate_limit_per_second", 2)
rate_limit_module.reset()
r1 = client.post("/api/items", json={"body": "one"})
r2 = client.post("/api/items", json={"body": "two"})
r3 = client.post("/api/items", json={"body": "three"})
assert r1.status_code == 200
assert r2.status_code == 200
assert r3.status_code == 429
def test_banned_ip_cannot_create(client):
import app.db as db_module
from app.models import BannedIP
db = db_module.SessionLocal()
try:
db.add(BannedIP(ip="testclient", reason="test"))
db.commit()
finally:
db.close()
r = client.post("/api/items", json={"body": "x"})
assert r.status_code == 403