# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """What an upload is decided to be, from its bytes and never its name.""" from __future__ import annotations import pytest from signal_bot.media_sniff import ( AVIF, GIF, HEIC, HEIF, JPEG, KINDS, M4V, MOV, MP4, PNG, SVG, WEBM, WEBP, MediaKind, sniff, ) from signal_bot.pack import MEDIA_TYPES def _iso(brand: bytes) -> bytes: return b"\x00\x00\x00\x20ftyp" + brand + b"\x00\x00\x02\x00rest" @pytest.mark.parametrize( ("payload", "expected"), [ (b"\xff\xd8\xff\xe0JFIF", JPEG), (b"\x89PNG\r\n\x1a\n....", PNG), (b"GIF87a....", GIF), (b"GIF89a....", GIF), (b"RIFF\x00\x00\x00\x00WEBPVP8 ", WEBP), (b"\x1a\x45\xdf\xa3....", WEBM), (_iso(b"isom"), MP4), (_iso(b"mp42"), MP4), (_iso(b"qt "), MOV), (_iso(b"M4V "), M4V), (_iso(b"heic"), HEIC), (_iso(b"HEIX"), HEIC), (_iso(b"mif1"), HEIF), (_iso(b"avif"), AVIF), (b'', SVG), (b"", SVG), (b"\xef\xbb\xbf ", SVG), ], ) def test_every_allowlisted_format_is_recognised(payload: bytes, expected: MediaKind) -> None: assert sniff(payload) is expected @pytest.mark.parametrize( "payload", [ b"", b"just some text", b"RIFF\x00\x00\x00\x00WAVEfmt ", # RIFF, but not a picture b"RIFF", # truncated before the form type b"%PDF-1.7", b"\x00\x00\x00\x20ftyq" + b"isom", # "ftyq", not "ftyp" b"MZ\x90\x00", ], ) def test_anything_off_the_allowlist_is_refused(payload: bytes) -> None: assert sniff(payload) is None def test_a_jpeg_named_as_a_png_is_still_a_jpeg() -> None: """The filename is attacker-chosen and is never consulted.""" assert sniff(b"\xff\xd8\xff\xe0evil.png") is JPEG def test_every_kind_has_a_media_type_the_pack_knows() -> None: """The gap that takes startup down: ingested here, refused by pack_load. A file stored with a suffix MEDIA_TYPES does not carry uploads fine and then fails the *next* load, so this is the check that has to exist. """ for kind in KINDS: assert kind.suffix in MEDIA_TYPES, kind.suffix assert MEDIA_TYPES[kind.suffix] == kind.media_type def test_only_webm_and_svg_are_stored_unstripped() -> None: """kuhy's decision of 2026-08-31, pinned so it cannot spread silently.""" unstrippable = {kind.suffix for kind in KINDS if not kind.strippable} assert unstrippable == {".webm", ".svg"}