"""Security-focused tests: signature validation, sanitisation, cookies, headers."""
from __future__ import annotations
import io
from fastapi.testclient import TestClient
from volumen.markdown import render
from volumen.password import (
BLOCK_R,
COST_N,
KEY_LENGTH,
PARALLEL_P,
hash_password,
needs_rehash,
verify_password,
)
from volumen.store import (
ALLOWED_IMAGE_EXTENSIONS,
detect_image_extension,
validate_image_signature,
)
# ---------------------------------------------------------------------------
# Image signature validation
# ---------------------------------------------------------------------------
class TestImageSignature:
def test_webp_magic_accepted(self) -> None:
# Minimal RIFF/WEBP header (12 bytes).
good = b"RIFF" + b"\x10\x00\x00\x00" + b"WEBP" + b"VP8 "
assert validate_image_signature(good, ".webp") is True
def test_webp_wrong_magic_rejected(self) -> None:
# RIFF but not WEBP at offset 8.
bad = b"RIFF" + b"\x10\x00\x00\x00" + b"WAVE" + b"VP8 "
assert validate_image_signature(bad, ".webp") is False
def test_webp_too_short_rejected(self) -> None:
assert validate_image_signature(b"RIFF", ".webp") is False
def test_avif_magic_accepted(self) -> None:
# ftyp box with size=0x18, brand=avif.
avif = b"\x00\x00\x00\x18ftyp" + b"avif" + b"\x00\x00\x00\x00" + b"avif" + b"mif1"
assert validate_image_signature(avif, ".avif") is True
def test_avif_alt_brand_accepted(self) -> None:
avif = b"\x00\x00\x00\x18ftyp" + b"avis" + b"\x00\x00\x00\x00" + b"avis" + b"mif1"
assert validate_image_signature(avif, ".avif") is True
def test_avif_wrong_brand_rejected(self) -> None:
avif = b"\x00\x00\x00\x18ftyp" + b"mp42" + b"\x00\x00\x00\x00" + b"mp42" + b"isom"
assert validate_image_signature(avif, ".avif") is False
def test_avif_too_short_rejected(self) -> None:
assert validate_image_signature(b"\x00\x00\x00\x18ftyp", ".avif") is False
def test_unknown_extension_rejected(self) -> None:
assert validate_image_signature(b"anything", ".png") is False
def test_detect_extension_webp(self) -> None:
data = b"RIFF" + b"\x00\x00\x00\x00" + b"WEBP"
assert detect_image_extension(data) == ".webp"
def test_detect_extension_avif(self) -> None:
data = b"\x00\x00\x00\x18ftypavif" + b"\x00" * 8
assert detect_image_extension(data) == ".avif"
def test_detect_extension_unknown(self) -> None:
assert detect_image_extension(b"random") is None
def test_allowed_extensions_match_policy(self) -> None:
assert ALLOWED_IMAGE_EXTENSIONS == (".webp", ".avif")
# ---------------------------------------------------------------------------
# Markdown XSS sanitisation
# ---------------------------------------------------------------------------
class TestMarkdownSanitisation:
def test_script_tag_stripped(self) -> None:
rendered = render("Hello world")
assert "