Initial Commit: Status Testing
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped

This commit is contained in:
marco.morath committed 2026-11-25 18:46:04 +01:00
1 parent 1eff675f05
commit 42dd1f2d4a
286 files changed
+64800 -369

No files matched your search

+322
View File
@@ -0,0 +1,322 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Typprüfung, Bildverarbeitung, Einbettungen und Ablage (ohne Datenbank)."""
from __future__ import annotations
import io
import os
import time
import zipfile
from pathlib import Path
import pytest
from surveybox.media import embeds, sniff, storage
# ---------------------------------------------------------------------------
# Typprüfung
# ---------------------------------------------------------------------------
def _write(tmp_path: Path, name: str, data: bytes) -> Path:
path = tmp_path / name
path.write_bytes(data)
return path
@pytest.mark.parametrize(
("data", "name", "key"),
[
(b"\xff\xd8\xff\xe0" + b"0" * 20, "a.jpg", "jpeg"),
(b"\x89PNG\r\n\x1a\n" + b"0" * 20, "a.png", "png"),
(b"RIFF\x00\x00\x00\x00WEBPVP8 ", "a.webp", "webp"),
(b"\x00\x00\x00\x18ftypisom" + b"0" * 20, "a.mp4", "mp4"),
(b"\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01webm", "a.webm", "webm"),
(b"%PDF-1.7\n", "a.pdf", "pdf"),
(b"WEBVTT\n\n00:00.000 --> 00:01.000\nHallo\n", "a.vtt", "vtt"),
("Name;Ort\nÄrger;Köln\n".encode(), "liste.csv", "csv"),
(b"einfacher Text\n", "notiz", "txt"),
],
)
def test_detects_by_content(tmp_path: Path, data: bytes, name: str, key: str) -> None:
detected = sniff.detect_file(_write(tmp_path, name, data), name)
assert detected is not None
assert detected.key == key
def test_rejects_unknown_and_disguised(tmp_path: Path) -> None:
exe = _write(tmp_path, "bild.jpg", b"MZ\x90\x00" + b"\x00" * 50)
assert sniff.detect_file(exe, "bild.jpg") is None
mov = _write(tmp_path, "film.mp4", b"\x00\x00\x00\x14ftypqt " + b"0" * 20)
assert sniff.detect_file(mov, "film.mp4") is None
html = _write(tmp_path, "x.png", b"<html><script>alert(1)</script>")
assert sniff.detect_file(html, "x.png").key == "txt" # type: ignore[union-attr]
def _zip(tmp_path: Path, name: str, files: dict[str, bytes]) -> Path:
path = tmp_path / name
with zipfile.ZipFile(path, "w") as archive:
for inner, content in files.items():
archive.writestr(inner, content)
return path
def test_office_formats_from_archive(tmp_path: Path) -> None:
docx = _zip(tmp_path, "a.docx", {"[Content_Types].xml": b"<x/>", "word/document.xml": b""})
assert sniff.detect_file(docx).key == "docx" # type: ignore[union-attr]
ods = _zip(tmp_path, "a.ods", {"mimetype": b"application/vnd.oasis.opendocument.spreadsheet"})
assert sniff.detect_file(ods).key == "ods" # type: ignore[union-attr]
plain = _zip(tmp_path, "a.zip", {"readme.txt": b"hi"})
assert sniff.detect_file(plain).key == "zip" # type: ignore[union-attr]
def test_safe_filename() -> None:
assert sniff.safe_filename("C:\\Users\\x\\Bericht 2026.PDF", "pdf") == "Bericht 2026.pdf"
assert sniff.safe_filename('../../etc/pa"ss\x00wd', "txt") == "passwd.txt"
assert sniff.safe_filename("", "png") == "datei.png"
# ---------------------------------------------------------------------------
# Bilder
# ---------------------------------------------------------------------------
PIL = pytest.importorskip("PIL")
def _jpeg_with_gps(path: Path, size: tuple[int, int] = (3000, 2000)) -> None:
from PIL import Image
img = Image.new("RGB", size, (200, 30, 30))
exif = Image.Exif()
exif[0x010F] = "Kamerahersteller"
exif[0x0112] = 6 # um 90° gedreht
exif[0x8825] = {1: "N", 2: (47.0, 54.0, 0.0)}
img.save(path, "JPEG", exif=exif)
def test_image_is_rotated_resized_and_stripped(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
source = tmp_path / "foto.jpg"
_jpeg_with_gps(source)
full, thumb = tmp_path / "full", tmp_path / "thumb"
result = images.process(source, full, thumb)
# Ausrichtung angewandt (hochkant), auf 2560 begrenzt
assert (result.width, result.height) == (1707, 2560)
with Image.open(full) as out:
assert out.format == "WEBP"
assert not out.getexif()
assert "exif" not in out.info
with Image.open(thumb) as small:
assert max(small.size) == 640
def test_image_rejects_garbage_and_bombs(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
junk = _write(tmp_path, "x.png", b"\x89PNG\r\n\x1a\n" + os.urandom(200))
with pytest.raises(images.ImageError):
images.process(junk, tmp_path / "f", tmp_path / "t")
gif = tmp_path / "a.gif"
Image.new("RGB", (10, 10)).save(gif, "GIF")
with pytest.raises(images.ImageError):
images.process(gif, tmp_path / "f", tmp_path / "t")
bomb = tmp_path / "bomb.png"
Image.new("1", (9000, 9000)).save(bomb, "PNG")
with pytest.raises(images.ImageError):
images.process(bomb, tmp_path / "f", tmp_path / "t")
def test_transparent_png_keeps_alpha(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
source = tmp_path / "logo.png"
Image.new("RGBA", (100, 50), (0, 0, 0, 0)).save(source, "PNG")
images.process(source, tmp_path / "f", tmp_path / "t")
with Image.open(tmp_path / "f") as out:
assert out.mode == "RGBA"
# ---------------------------------------------------------------------------
# Externe Videos
# ---------------------------------------------------------------------------
ALL = embeds.EmbedPolicy(youtube=True, vimeo=True, peertube_hosts=("video.example.org",))
@pytest.mark.parametrize(
("url", "provider", "video"),
[
("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=10", "youtube", "dQw4w9WgXcQ"),
("https://youtu.be/dQw4w9WgXcQ?si=abc", "youtube", "dQw4w9WgXcQ"),
("https://www.youtube.com/shorts/dQw4w9WgXcQ", "youtube", "dQw4w9WgXcQ"),
("https://vimeo.com/76979871", "vimeo", "76979871"),
("https://player.vimeo.com/video/76979871?h=abc123def", "vimeo", "76979871"),
("https://video.example.org/w/9c9de5e8-0a1e-484a-b099-e80766180a6d", "peertube",
"9c9de5e8-0a1e-484a-b099-e80766180a6d"),
("https://video.example.org/videos/watch/kkGMgK9ZtnKfYAgnEtQxbv", "peertube",
"kkGMgK9ZtnKfYAgnEtQxbv"),
],
)
def test_parse_video_urls(url: str, provider: str, video: str) -> None:
embed = embeds.parse_url(url, ALL)
assert (embed.provider, embed.video) == (provider, video)
assert embeds.from_config(embed.to_config()) == embed
@pytest.mark.parametrize(
"url",
[
"javascript:alert(1)",
"https://www.youtube.com/watch?v=short",
"https://www.youtube.com/watch?v=dQw4w9WgXcQ\"><script>",
"https://evil.example/w/9c9de5e8-0a1e-484a-b099-e80766180a6d",
"https://vimeo.com/abc",
],
)
def test_rejects_bad_video_urls(url: str) -> None:
with pytest.raises(embeds.EmbedError):
embeds.parse_url(url, ALL)
def test_disabled_provider_and_player_urls() -> None:
with pytest.raises(embeds.EmbedError) as exc:
embeds.parse_url("https://youtu.be/dQw4w9WgXcQ", embeds.EmbedPolicy())
assert exc.value.code == "embed_provider_disabled"
yt = embeds.parse_url("https://youtu.be/dQw4w9WgXcQ", ALL)
assert embeds.player_url(yt).startswith("https://www.youtube-nocookie.com/embed/")
vimeo = embeds.parse_url("https://vimeo.com/76979871", ALL)
assert "dnt=1" in embeds.player_url(vimeo)
assert ALL.frame_sources() == [
"https://www.youtube-nocookie.com",
"https://player.vimeo.com",
"https://video.example.org",
]
# Manipulierte Konfiguration wird verworfen
assert embeds.from_config({"provider": "peertube", "video": "abcdefgh", "host": "a b"}) is None
def test_clean_host() -> None:
assert embeds.clean_host("https://Video.Example.org/") == "video.example.org"
assert embeds.clean_host("localhost") is None
assert embeds.clean_host("exa mple.org") is None
# ---------------------------------------------------------------------------
# Ablage
# ---------------------------------------------------------------------------
def test_receive_commit_and_sweep(tmp_path: Path) -> None:
root, tmp = tmp_path / "media", tmp_path / "tmp"
temp = storage.temp_path(tmp)
assert storage.receive(io.BytesIO(b"x" * 100), temp, 1000) == 100
key = storage.commit(root, temp)
assert storage.path_for(root, key).read_bytes() == b"x" * 100
big = storage.temp_path(tmp)
with pytest.raises(storage.TooLarge):
storage.receive(io.BytesIO(b"x" * 2000), big, 1000)
assert not big.exists()
with pytest.raises(ValueError):
storage.path_for(root, "../../etc/passwd")
orphan = storage.commit(root, _write(tmp, "o", b"o"))
# Frische verwaiste Dateien bleiben (Sicherungen), alte verschwinden
assert storage.sweep(root, {key}) == 0
old = time.time() - 2 * storage.ORPHAN_MIN_AGE
os.utime(storage.path_for(root, orphan), (old, old))
assert storage.sweep(root, {key}) == 1
assert set(storage.stored_keys(root)) == {key}
def test_backup_manifest_store_and_restore(tmp_path: Path) -> None:
from surveybox import backup
media, backups = tmp_path / "media", tmp_path / "backups"
store = backups / "media"
first = storage.commit(media, _write(tmp_path, "a", b"erste"))
second = storage.commit(media, _write(tmp_path, "b", b"zweite"))
(backups / "daily").mkdir(parents=True)
dump_old = backups / "daily" / "surveybox-daily-20260101T000000Z.dump"
dump_old.write_bytes(b"x")
assert backup.backup_media(media, store, dump_old) == 2
# Eine Datei verschwindet, eine neue kommt hinzu
storage.path_for(media, first).unlink()
third = storage.commit(media, _write(tmp_path, "c", b"dritte"))
dump_new = backups / "daily" / "surveybox-daily-20260102T000000Z.dump"
dump_new.write_bytes(b"x")
backup.backup_media(media, store, dump_new)
assert set(backup.read_manifest(backup.manifest_for(dump_new))) == {second, third}
# Alte Sicherung zurückspielen: die gelöschte Datei kommt wieder
assert backup.restore_media(media, store, dump_old) == 1
assert storage.path_for(media, first).read_bytes() == b"erste"
# Alte Sicherung weg: ihre Datei wird im Speicher nicht mehr gebraucht
dump_old.unlink()
backup.manifest_for(dump_old).unlink()
assert backup.prune_media_store(backups, store) == 1
assert set(storage.stored_keys(store)) == {second, third}
OWN = embeds.EmbedPolicy(
custom=(
embeds.Source("media.example.org", "mediacms", True),
embeds.Source("nas.example.org:5001", "file", False),
embeds.Source("192.168.10.5", "iframe", True),
)
)
def test_own_sources() -> None:
cms = embeds.parse_url("https://media.example.org/view?m=AbCdEf123", OWN)
assert embeds.player_url(cms) == "https://media.example.org/embed?m=AbCdEf123"
assert embeds.needs_consent(cms, OWN)
nas = embeds.parse_url("https://nas.example.org:5001/videos/Einweisung 2026.mp4", OWN)
assert nas.provider == "file"
assert embeds.player_url(nas) == "https://nas.example.org:5001/videos/Einweisung%202026.mp4"
assert not embeds.needs_consent(nas, OWN)
assert embeds.from_config(nas.to_config()) == nas
page = embeds.parse_url("https://192.168.10.5/player?id=7", OWN)
assert page.provider == "iframe"
assert embeds.csp_sources([cms, nas, page]) == (
["https://192.168.10.5", "https://media.example.org"],
["https://nas.example.org:5001"],
)
@pytest.mark.parametrize(
"url",
[
"http://nas.example.org:5001/a.mp4", # kein HTTPS
"https://nas.example.org/a.mp4", # falscher Port
"https://user:pw@nas.example.org:5001/a.mp4",
"https://media.example.org/view?m=x",
"https://other.example.org/a.mp4",
],
)
def test_own_sources_reject(url: str) -> None:
with pytest.raises(embeds.EmbedError):
embeds.parse_url(url, OWN)
def test_own_source_config_is_rechecked() -> None:
forged = {"provider": "file", "host": "nas.example.org:5001",
"url": "https://evil.example/x.mp4"}
assert embeds.from_config(forged) is None
quoted = embeds.from_config({"provider": "iframe", "host": "192.168.10.5",
"url": 'https://192.168.10.5/a"onload="x'})
assert quoted is not None and '"' not in embeds.player_url(quoted)
assert embeds.clean_source_host("NAS.example.org:5001") == "nas.example.org:5001"
assert embeds.clean_source_host("nas:99999") is None