Dateien als Clip-Art "file": gestreamter Upload mit Größengrenze, Kontingent pro Benutzer und Mindestreserve an freiem Speicher. Download immer als Anhang mit sandbox-CSP, Vorschau nur für geprüfte JPEG/PNG/GIF/WebP. Ablauf nach 1/7/30 Tagen oder nie; der Aufräumjob löscht abgelaufene und verwaiste Dateien. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
458 lines
15 KiB
Python
458 lines
15 KiB
Python
import asyncio
|
|
import os
|
|
import time
|
|
from datetime import timedelta
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app.config import get_settings
|
|
from app.models import Clip, StoredFile, utcnow
|
|
from app.services import files as file_service
|
|
from tests.conftest import login
|
|
from tests.test_ws import connect
|
|
|
|
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
|
|
JPEG = b"\xff\xd8\xff\xe0" + b"\x00" * 64
|
|
WEBP = b"RIFF\x00\x00\x00\x00WEBPVP8 " + b"\x00" * 32
|
|
|
|
|
|
@pytest.fixture
|
|
def anna(client, make_user):
|
|
make_user("anna")
|
|
login(client, "anna")
|
|
return client
|
|
|
|
|
|
@pytest.fixture
|
|
def bert(client, make_user):
|
|
make_user("bert")
|
|
with TestClient(client.app, base_url="https://testserver") as other:
|
|
login(other, "bert")
|
|
yield other
|
|
|
|
|
|
@pytest.fixture
|
|
def limits(monkeypatch):
|
|
"""Set file limits via environment, like in production."""
|
|
|
|
def _set(**values):
|
|
for key, value in values.items():
|
|
monkeypatch.setenv(key.upper(), str(value))
|
|
get_settings.cache_clear()
|
|
|
|
return _set
|
|
|
|
|
|
def upload(c, data=b"hello file", name="note.txt", status=201, headers=None, **params):
|
|
response = c.post(
|
|
"/api/files",
|
|
params={"name": name, **params},
|
|
content=data,
|
|
headers={"Content-Type": "text/plain", **(headers or {})},
|
|
)
|
|
assert response.status_code == status, response.text
|
|
return response.json()
|
|
|
|
|
|
def stored_files():
|
|
root = get_settings().files_dir
|
|
return sorted(p for p in root.glob("*/*") if p.is_file()) if root.exists() else []
|
|
|
|
|
|
# --- Upload and download --------------------------------------------------------
|
|
|
|
|
|
def test_upload_creates_file_clip(anna):
|
|
clip = upload(anna, b"hello file", "Notiz.txt", title=" Wichtig ")
|
|
|
|
assert clip["kind"] == "file"
|
|
assert clip["content"] == "Notiz.txt"
|
|
assert clip["title"] == "Wichtig"
|
|
assert clip["language"] is None
|
|
assert clip["file"]["name"] == "Notiz.txt"
|
|
assert clip["file"]["size"] == 10
|
|
assert clip["file"]["content_type"] == "text/plain"
|
|
assert clip["file"]["previewable"] is False
|
|
assert len(stored_files()) == 1
|
|
# The original name never reaches the file system
|
|
assert stored_files()[0].name != "Notiz.txt"
|
|
|
|
|
|
def test_download_is_an_attachment(anna):
|
|
clip = upload(
|
|
anna, b"<html><script>alert(1)</script>", "page.html", headers={"Content-Type": "text/html"}
|
|
)
|
|
|
|
response = anna.get(f"/api/files/{clip['id']}")
|
|
assert response.status_code == 200
|
|
assert response.content == b"<html><script>alert(1)</script>"
|
|
assert response.headers["content-disposition"].startswith("attachment;")
|
|
assert response.headers["content-security-policy"] == "default-src 'none'; sandbox"
|
|
assert response.headers["x-content-type-options"] == "nosniff"
|
|
assert response.headers["cache-control"] == "private, no-cache"
|
|
|
|
|
|
def test_inline_request_is_ignored_for_non_images(anna):
|
|
clip = upload(anna, b"<svg onload='x'/>", "x.svg", headers={"Content-Type": "image/svg+xml"})
|
|
|
|
assert clip["file"]["previewable"] is False
|
|
response = anna.get(f"/api/files/{clip['id']}", params={"inline": 1})
|
|
assert response.headers["content-disposition"].startswith("attachment;")
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("data", "content_type"),
|
|
[
|
|
(PNG, "image/png"),
|
|
(JPEG, "image/jpeg"),
|
|
(WEBP, "image/webp"),
|
|
(b"GIF89a" + PNG, "image/gif"),
|
|
],
|
|
)
|
|
def test_real_images_are_previewable(anna, data, content_type):
|
|
# Type comes from the content, not from what the client claims
|
|
clip = upload(anna, data, "bild", headers={"Content-Type": "application/octet-stream"})
|
|
|
|
assert clip["file"]["previewable"] is True
|
|
assert clip["file"]["content_type"] == content_type
|
|
response = anna.get(f"/api/files/{clip['id']}", params={"inline": 1})
|
|
assert response.headers["content-disposition"].startswith("inline;")
|
|
assert response.headers["content-type"] == content_type
|
|
|
|
|
|
def test_fake_image_is_not_previewable(anna):
|
|
clip = upload(anna, b"<html>", "fake.png", headers={"Content-Type": "image/png"})
|
|
assert clip["file"]["previewable"] is False
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("raw", "expected"),
|
|
[
|
|
("../../etc/passwd", "passwd"),
|
|
("C:\\Users\\x\\bericht.pdf", "bericht.pdf"),
|
|
("a\r\nX-Evil: 1.txt", "aX-Evil: 1.txt"),
|
|
(" .. ", "datei"),
|
|
("Größe.txt", "Größe.txt"),
|
|
],
|
|
)
|
|
def test_file_names_are_sanitized(anna, raw, expected):
|
|
assert upload(anna, name=raw)["file"]["name"] == expected
|
|
|
|
|
|
def test_long_names_keep_their_extension():
|
|
name = file_service.sanitize_name("x" * 400 + ".tar.gz")
|
|
assert len(name) == 255
|
|
assert name.endswith(".gz")
|
|
|
|
|
|
def test_content_disposition_cannot_break_out():
|
|
header = file_service.content_disposition('a"b\\c ä.txt')
|
|
assert header == "attachment; filename=\"a_b_c _.txt\"; filename*=UTF-8''a%22b%5Cc%20%C3%A4.txt"
|
|
|
|
|
|
def test_download_header_with_umlauts(anna):
|
|
clip = upload(anna, name="Bericht März.pdf")
|
|
disposition = anna.get(f"/api/files/{clip['id']}").headers["content-disposition"]
|
|
assert "filename*=UTF-8''Bericht%20M%C3%A4rz.pdf" in disposition
|
|
|
|
|
|
def test_content_type_is_sanitized(anna):
|
|
clip = upload(anna, headers={"Content-Type": "Text/Plain; charset=utf-8"})
|
|
assert clip["file"]["content_type"] == "text/plain"
|
|
clip = upload(anna, headers={"Content-Type": "bad type\r\nX: y"})
|
|
assert clip["file"]["content_type"] == "application/octet-stream"
|
|
|
|
|
|
def test_upload_larger_than_request_limit(anna):
|
|
data = os.urandom(1024 * 1024 + 4096) # above the general 1 MiB request limit
|
|
|
|
clip = upload(anna, data, "random.bin")
|
|
assert anna.get(f"/api/files/{clip['id']}").content == data
|
|
# The general limit still applies everywhere else
|
|
assert anna.post("/api/clips", content=b"x" * len(data)).status_code == 413
|
|
|
|
|
|
def test_search_finds_file_names(anna):
|
|
clip = upload(anna, name="steuer-2026.pdf")
|
|
upload(anna, name="urlaub.jpg")
|
|
|
|
items = anna.get("/api/clips", params={"q": "STEUER"}).json()["items"]
|
|
assert [c["id"] for c in items] == [clip["id"]]
|
|
|
|
|
|
def test_upload_into_project(anna):
|
|
project = anna.post("/api/projects", json={"name": "Docs"}).json()
|
|
clip = upload(anna, project_id=project["id"])
|
|
assert clip["project_id"] == project["id"]
|
|
assert anna.get("/api/projects").json()[0]["clip_count"] == 1
|
|
|
|
|
|
# --- Limits ---------------------------------------------------------------------
|
|
|
|
|
|
def test_empty_file_is_rejected(anna):
|
|
assert upload(anna, b"", status=400)["detail"] == "Die Datei ist leer."
|
|
|
|
|
|
def test_file_size_limit(anna, limits):
|
|
limits(file_max_bytes=10)
|
|
upload(anna, b"x" * 10)
|
|
|
|
detail = upload(anna, b"x" * 11, status=413)["detail"]
|
|
assert detail == "Die Datei ist zu groß (höchstens 10 B)."
|
|
assert len(stored_files()) == 1
|
|
|
|
|
|
def test_quota_per_user(anna, bert, limits):
|
|
limits(file_quota_bytes=2048)
|
|
upload(anna, b"x" * 1500)
|
|
|
|
detail = upload(anna, b"x" * 1000, status=413)["detail"]
|
|
assert detail == "Nicht genug Speicherplatz: noch 548 B von 2 KB frei."
|
|
# Quota is per user
|
|
upload(bert, b"x" * 1500)
|
|
|
|
|
|
def test_minimum_free_disk_space(anna, limits, monkeypatch):
|
|
limits(file_min_free_bytes=1000)
|
|
monkeypatch.setattr(file_service.shutil, "disk_usage", lambda _path: SimpleNamespace(free=1500))
|
|
|
|
upload(anna, b"x" * 500)
|
|
response = anna.post("/api/files", params={"name": "a"}, content=b"x" * 501)
|
|
assert response.status_code == 507
|
|
|
|
|
|
def test_content_length_is_required(anna):
|
|
def body():
|
|
yield b"chunk"
|
|
|
|
response = anna.post("/api/files", params={"name": "a"}, content=body())
|
|
assert response.status_code == 411
|
|
|
|
|
|
@pytest.mark.parametrize("days", [-1, 2, 365])
|
|
def test_invalid_expiry(anna, days):
|
|
upload(anna, expires_days=days, status=400)
|
|
|
|
|
|
def test_foreign_or_unknown_project(anna, bert):
|
|
project = anna.post("/api/projects", json={"name": "Docs"}).json()
|
|
upload(bert, project_id=project["id"], status=404)
|
|
upload(anna, project_id=999, status=404)
|
|
assert stored_files() == []
|
|
|
|
|
|
def test_upload_requires_login_and_csrf(anna, client):
|
|
del anna.headers["X-CSRF-Token"]
|
|
upload(anna, status=403)
|
|
anna.cookies.clear()
|
|
upload(anna, status=401)
|
|
assert stored_files() == []
|
|
|
|
|
|
def _chunks(*parts, fail=False):
|
|
async def gen():
|
|
for part in parts:
|
|
yield part
|
|
if fail:
|
|
raise ConnectionError("client gone")
|
|
|
|
return gen()
|
|
|
|
|
|
def test_aborted_upload_leaves_nothing_behind(db, make_user):
|
|
user = make_user("anna")
|
|
with pytest.raises(ConnectionError):
|
|
asyncio.run(
|
|
file_service.store_upload(db, user.id, _chunks(b"half", fail=True), name="a", size=8)
|
|
)
|
|
with pytest.raises(file_service.FileRejected, match="unterbrochen"):
|
|
asyncio.run(file_service.store_upload(db, user.id, _chunks(b"half"), name="a", size=8))
|
|
with pytest.raises(file_service.FileRejected, match="größer als angekündigt"):
|
|
asyncio.run(
|
|
file_service.store_upload(db, user.id, _chunks(b"too", b"long"), name="a", size=4)
|
|
)
|
|
|
|
assert stored_files() == []
|
|
assert db.query(StoredFile).count() == 0
|
|
assert db.query(Clip).count() == 0
|
|
|
|
|
|
# --- File clips -----------------------------------------------------------------
|
|
|
|
|
|
def test_file_clip_metadata_can_change(anna):
|
|
clip = upload(anna)
|
|
project = anna.post("/api/projects", json={"name": "Docs"}).json()
|
|
|
|
response = anna.patch(
|
|
f"/api/clips/{clip['id']}",
|
|
json={"title": "Neu", "pinned": True, "project_id": project["id"]},
|
|
)
|
|
assert response.status_code == 200
|
|
assert response.json()["file"]["name"] == "note.txt"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"changes", [{"content": "other.txt"}, {"kind": "text"}, {"language": "python"}]
|
|
)
|
|
def test_file_clip_content_is_fixed(anna, changes):
|
|
clip = upload(anna)
|
|
response = anna.patch(f"/api/clips/{clip['id']}", json=changes)
|
|
assert response.status_code == 400
|
|
|
|
|
|
def test_files_cannot_be_created_or_faked_as_clips(anna):
|
|
assert anna.post("/api/clips", json={"content": "x", "kind": "file"}).status_code == 400
|
|
text = anna.post("/api/clips", json={"content": "x"}).json()
|
|
assert anna.patch(f"/api/clips/{text['id']}", json={"kind": "file"}).status_code == 400
|
|
|
|
|
|
def test_deleting_clip_removes_file(anna):
|
|
clip = upload(anna)
|
|
assert len(stored_files()) == 1
|
|
|
|
assert anna.delete(f"/api/clips/{clip['id']}").status_code == 204
|
|
assert stored_files() == []
|
|
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
|
|
|
|
|
|
def test_missing_file_on_disk_is_404(anna):
|
|
clip = upload(anna)
|
|
stored_files()[0].unlink()
|
|
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
|
|
|
|
|
|
def test_usage(anna, bert, limits):
|
|
limits(file_quota_bytes=5000, file_max_bytes=1000)
|
|
upload(anna, b"x" * 300)
|
|
upload(anna, b"x" * 200)
|
|
upload(bert, b"x" * 999)
|
|
|
|
assert anna.get("/api/files/usage").json() == {
|
|
"used_bytes": 500,
|
|
"quota_bytes": 5000,
|
|
"max_file_bytes": 1000,
|
|
}
|
|
|
|
|
|
# --- Expiry ---------------------------------------------------------------------
|
|
|
|
|
|
def test_default_expiry_is_seven_days(anna):
|
|
expires = upload(anna)["file"]["expires_at"]
|
|
assert expires[:10] == (utcnow() + timedelta(days=7)).date().isoformat()
|
|
assert upload(anna, expires_days=0)["file"]["expires_at"] is None
|
|
|
|
|
|
def test_change_expiry(anna):
|
|
clip = upload(anna, expires_days=1)
|
|
|
|
response = anna.patch(f"/api/files/{clip['id']}", json={"expires_days": 0})
|
|
assert response.status_code == 200
|
|
assert response.json()["file"]["expires_at"] is None
|
|
assert response.json()["version"] == clip["version"] + 1
|
|
assert response.json()["updated_at"] == clip["updated_at"]
|
|
|
|
text = anna.post("/api/clips", json={"content": "x"}).json()
|
|
assert anna.patch(f"/api/files/{text['id']}", json={"expires_days": 0}).status_code == 400
|
|
|
|
|
|
def _expire(db, clip_id):
|
|
stored = db.query(StoredFile).filter_by(clip_id=clip_id).one()
|
|
stored.expires_at = utcnow() - timedelta(minutes=1)
|
|
db.commit()
|
|
|
|
|
|
def test_expired_file_cannot_be_downloaded(anna, db):
|
|
clip = upload(anna)
|
|
_expire(db, clip["id"])
|
|
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
|
|
|
|
|
|
def test_cleanup_deletes_expired_files(anna, db):
|
|
old = upload(anna, b"old", "old.txt")
|
|
keep = upload(anna, b"keep", "keep.txt", expires_days=0)
|
|
_expire(db, old["id"])
|
|
user_id = db.query(Clip).filter_by(id=old["id"]).one().user_id
|
|
|
|
assert file_service.delete_expired(db) == [(user_id, old["id"])]
|
|
|
|
ids = [c["id"] for c in anna.get("/api/clips").json()["items"]]
|
|
assert ids == [keep["id"]]
|
|
assert len(stored_files()) == 1
|
|
assert file_service.delete_expired(db) == []
|
|
|
|
|
|
def test_cleanup_removes_orphans_and_stale_uploads(anna, db):
|
|
upload(anna)
|
|
files_dir = get_settings().files_dir
|
|
known = stored_files()[0]
|
|
old = time.time() - 7 * 3600
|
|
|
|
orphan_old = files_dir / "99" / "deadbeef"
|
|
orphan_new = files_dir / "99" / "cafebabe"
|
|
stale_part = files_dir / "tmp" / "x.part"
|
|
fresh_part = files_dir / "tmp" / "y.part"
|
|
for path in (orphan_old, orphan_new, stale_part, fresh_part):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_bytes(b"x")
|
|
for path in (orphan_old, stale_part, known):
|
|
os.utime(path, (old, old))
|
|
|
|
assert file_service.remove_orphans(db) == 2
|
|
assert {p.name for p in stored_files()} == {known.name, "cafebabe", "y.part"}
|
|
|
|
|
|
def test_deleted_user_leaves_only_orphans(client, anna, db, make_user):
|
|
from app.models import Role, User
|
|
|
|
upload(anna)
|
|
make_user("root", role=Role.ADMIN)
|
|
with TestClient(client.app, base_url="https://testserver") as admin:
|
|
login(admin, "root")
|
|
anna_id = db.query(User).filter_by(username="anna").one().id
|
|
admin.delete(f"/api/admin/users/{anna_id}")
|
|
|
|
db.expire_all()
|
|
assert db.query(StoredFile).count() == 0
|
|
path = stored_files()[0]
|
|
os.utime(path, (time.time() - 7200, time.time() - 7200))
|
|
assert file_service.remove_orphans(db) == 1
|
|
|
|
|
|
# --- Data separation ------------------------------------------------------------
|
|
|
|
|
|
def test_files_of_other_users_are_invisible(anna, bert):
|
|
clip = upload(anna, b"secret")
|
|
url = f"/api/files/{clip['id']}"
|
|
|
|
assert bert.get(url).status_code == 404
|
|
assert bert.get(url, params={"inline": 1}).status_code == 404
|
|
assert bert.patch(url, json={"expires_days": 0}).status_code == 404
|
|
assert bert.delete(f"/api/clips/{clip['id']}").status_code == 404
|
|
assert bert.get("/api/files/usage").json()["used_bytes"] == 0
|
|
assert anna.get(url).content == b"secret"
|
|
assert len(stored_files()) == 1
|
|
|
|
|
|
# --- Live sync ------------------------------------------------------------------
|
|
|
|
|
|
def test_upload_is_broadcast(anna):
|
|
with connect(anna) as ws:
|
|
ws.receive_json()
|
|
clip = upload(anna, name="live.txt")
|
|
event = ws.receive_json()
|
|
assert event["type"] == "clip.created"
|
|
assert event["data"]["id"] == clip["id"]
|
|
assert event["data"]["file"]["name"] == "live.txt"
|
|
|
|
anna.patch(f"/api/files/{clip['id']}", json={"expires_days": 30})
|
|
event = ws.receive_json()
|
|
assert event["type"] == "clip.updated"
|
|
assert event["data"]["file"]["expires_at"] is not None
|