"""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 " None: rendered = render('') assert "onerror" not in rendered.lower() assert "alert" not in rendered.lower() def test_javascript_url_sanitised(self) -> None: rendered = render("[click me](javascript:alert(1))") assert "javascript:" not in rendered.lower() def test_data_image_url_kept(self) -> None: rendered = render("![alt](data:image/webp;base64,UklGRg==)") assert " None: rendered = render('![alt](url "caption")') assert "
" in rendered assert "caption" in rendered # --------------------------------------------------------------------------- # Password hashing policy # --------------------------------------------------------------------------- class TestPasswordPolicy: def test_strong_hash_passes(self) -> None: encoded = hash_password("a-strong-password") assert verify_password("a-strong-password", encoded) is True def test_weak_params_rejected(self) -> None: encoded = f"scrypt$8$1$1${'A' * 24}${'B' * 32}" assert verify_password("anything", encoded) is False def test_needs_rehash_for_strong_hash(self) -> None: encoded = hash_password("a-strong-password") assert needs_rehash(encoded) is False def test_needs_rehash_for_weak_hash(self) -> None: encoded = f"scrypt$8$1$1${'A' * 24}${'B' * 32}" assert needs_rehash(encoded) is True def test_needs_rehash_for_malformed(self) -> None: assert needs_rehash("not-a-hash") is True def test_module_constants_match_policy(self) -> None: # Policy floor equals current implementation. assert COST_N >= 16384 assert BLOCK_R >= 8 assert PARALLEL_P >= 1 assert KEY_LENGTH >= 32 # --------------------------------------------------------------------------- # HTTP security headers and CSP # --------------------------------------------------------------------------- class TestSecurityHeaders: def test_global_security_headers_present(self, client: TestClient) -> None: response = client.get("/api/volumen/site") assert response.headers.get("x-content-type-options") == "nosniff" assert response.headers.get("x-frame-options") == "DENY" assert response.headers.get("referrer-policy") == "strict-origin-when-cross-origin" assert "permissions-policy" in response.headers def test_csp_on_public_routes(self, client: TestClient) -> None: response = client.get("/api/volumen/site") csp = response.headers.get("content-security-policy", "") assert "default-src 'self'" in csp # Public routes have script-src but without nonce (nonce is admin-only) assert "script-src 'self'" in csp assert "nonce-" not in csp def test_admin_route_has_csp_with_nonce(self, admin_client: TestClient) -> None: response = admin_client.get("/admin/login") csp = response.headers.get("content-security-policy", "") assert "default-src 'self'" in csp assert "'unsafe-inline'" not in csp assert "nonce-" in csp def test_admin_csp_has_no_duplicate_directives(self, admin_client: TestClient) -> None: # Regression: nonce-augmented script-src / style-src used to be # appended after the base ones, so the same directive name appeared # twice. Browsers use the FIRST occurrence and silently drop the # nonce, breaking all admin JS. Verify each directive is unique. response = admin_client.get("/admin/login") csp = response.headers.get("content-security-policy", "") directives = [d.strip().split(maxsplit=1)[0] for d in csp.split(";")] assert len(directives) == len(set(directives)), ( f"Duplicate CSP directives: {[d for d in directives if directives.count(d) > 1]}" ) # And specifically: only one script-src, only one style-src. assert directives.count("script-src") == 1 assert directives.count("style-src") == 1 def test_admin_csp_nonce_appears_in_rendered_html(self, admin_client: TestClient) -> None: # Regression: nonce used to be set AFTER call_next, so templates # rendered with an empty csp_nonce and the matching