from __future__ import annotations import io import os import subprocess import sys from collections.abc import Callable from pathlib import Path from typing import Any from uuid import UUID import pytest from tests.core.test_kid_windows import A, B, box, clear_audio, encv, moof, movie, sinf from tests.core.test_zero_kid_fallback import _playready, _widevine from tests.test_segment_decrypt import read_argv from unshackle.core import binaries from unshackle.core.api.errors import categorize_exception from unshackle.core.config import config from unshackle.core.drm import ClearKeyCENC from unshackle.core.drm import decrypters as decrypters_module from unshackle.core.drm.decrypters import mp4decrypt_or_shaka from unshackle.core.drm.key_args import shaka_noise, track_key_args from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use from unshackle.core.drm.verify import kidless_track_kids from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.tracks.segment_store import decrypted KEY = "b5df2ae3f63b8dda9049d6e41422e075" OTHER_KEY = "11" * 16 POSIX_STUBS = pytest.mark.skipif(sys.platform == "win32", reason="the decrypter stubs are shell scripts") def two_sinf(kid: UUID, piff_first: bool) -> bytes: """A sample entry with a PIFF and a CENC sinf for the same KID.""" return box(b"encv", bytes(78), sinf(kid, piff_first), sinf(kid, not piff_first)) def track_zero(entry: bytes) -> bytes: """A movie whose tkhd carries track_ID 0.""" data = movie(entry) tkhd = data.index(b"tkhd") return data[: tkhd + 16] + bytes(4) + data[tkhd + 20 :] @pytest.mark.parametrize( ("init", "kids"), [ pytest.param(movie(two_sinf(A, piff_first=True)), {1: A}, id="piff-then-cenc"), pytest.param(movie(encv(A, piff=True)), {1: A}, id="piff-only"), pytest.param(movie(two_sinf(A, piff_first=False)), {}, id="cenc-then-piff"), pytest.param(movie(encv(A)), {}, id="cenc-only"), pytest.param(clear_audio(), {}, id="clear"), pytest.param(track_zero(two_sinf(A, piff_first=True)), {}, id="track-id-0"), pytest.param(b"\x00\x00\x00\x01moov\x00\x00", {}, id="truncated-large-size"), pytest.param(movie(two_sinf(A, piff_first=True))[:-20], {}, id="cut-short"), ], ) def test_kidless_track_kids(init: bytes, kids: dict[int, UUID]) -> None: assert kidless_track_kids(init) == kids def test_kidless_track_kids_survives_deep_nesting() -> None: nested = b"" for _ in range(3000): nested = box(b"trak", nested) assert kidless_track_kids(nested) == {} def test_track_key_needs_the_track_kid() -> None: assert track_key_args({A: KEY, B: OTHER_KEY}, {2: A}) == ["--key", f"2:{KEY}"] assert track_key_args({B: OTHER_KEY}, {2: A}) == [] DRMS: list[Any] = [ pytest.param(lambda: _widevine(A), id="widevine"), pytest.param(lambda: _playready(A), id="playready"), pytest.param(lambda: ClearKeyCENC(kids=[A]), id="clearkey"), ] def write_movie(path: Path, entry: bytes, fragment: bytes = b"") -> Path: path.write_bytes(movie(entry) + fragment + box(b"mdat", bytes(16))) return path @POSIX_STUBS @pytest.mark.parametrize("make", DRMS) def test_whole_file_decrypt_keys_a_piff_first_track_by_id( tmp_path: Path, stub_mp4decrypt: Path, make: Callable[[], Any] ) -> None: path = write_movie(tmp_path / "track.mp4", two_sinf(A, piff_first=True)) drm = make() drm.content_keys[A] = KEY drm.decrypt_with_mp4decrypt(path) assert f"1:{KEY}" in read_argv(stub_mp4decrypt)[0] @POSIX_STUBS @pytest.mark.parametrize("make", DRMS) def test_decrypt_falls_back_to_shaka_on_a_passthrough( tmp_path: Path, stub_mp4decrypt: Path, monkeypatch: pytest.MonkeyPatch, make: Callable[[], Any] ) -> None: path = write_movie(tmp_path / "track.mp4", two_sinf(A, piff_first=True), moof(1, 0)) drm = make() drm.content_keys[B] = OTHER_KEY shaka: list[Path] = [] monkeypatch.setattr(type(drm), "decrypt_with_shaka_packager", lambda self, p: shaka.append(p)) monkeypatch.setattr(config, "decryption", "mp4decrypt", raising=False) drm.decrypt(path) assert shaka == [path] @POSIX_STUBS def test_segment_decrypter_keys_from_the_init_segment(tmp_path: Path, stub_mp4decrypt: Path) -> None: drm = _widevine(A) drm.content_keys[A] = KEY decrypter = SegmentDecrypter(drm, movie(two_sinf(A, piff_first=True)), tmp_path, workers=1) decrypter.pool.shutdown() assert f"1:{KEY}" in decrypter.key_args @POSIX_STUBS @pytest.mark.parametrize( ("output", "stderr", "raises"), [ pytest.param( b"partial", "ERROR: failed to process the file (-10)\n", subprocess.CalledProcessError, id="exit-0-error" ), pytest.param(None, "", RuntimeError, id="exit-0-no-output"), pytest.param(b"", "", RuntimeError, id="exit-0-empty-output"), ], ) def test_a_failed_segment_decrypt_keeps_the_segment( tmp_path: Path, mp4decrypt_writes: Callable[[bytes | None, int, str], None], output: bytes | None, stderr: str, raises: type[BaseException], ) -> None: mp4decrypt_writes(output, 0, stderr) drm = _widevine(A) drm.content_keys[A] = KEY # the path holds a keyword that categorize_exception reads as a rate limit segment_dir = tmp_path / "segments-429" segment_dir.mkdir() segment = segment_dir / "000.mp4" segment.write_bytes(b"segment-0") (segment_dir / "000.clear.!dev").write_bytes(b"stale") decrypter = SegmentDecrypter(drm, movie(encv(A)), tmp_path / "work", workers=1) decrypter.submit(segment, decrypted(segment)) with pytest.raises(raises) as caught: decrypter.finish() assert segment.read_bytes() == b"segment-0" assert list(segment_dir.iterdir()) == [segment] assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR @pytest.mark.parametrize(("key_kid", "usable"), [(A, True), (B, False)], ids=["track-kid-keyed", "other-kid-only"]) def test_segment_decrypt_needs_a_key_for_a_kidless_track( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, key_kid: UUID, usable: bool ) -> None: monkeypatch.setattr(config, "decrypt_segments", True, raising=False) monkeypatch.setattr(binaries, "Mp4decrypt", tmp_path / "mp4decrypt") drm = _widevine(A) drm.content_keys[key_kid] = KEY assert can_use(drm, "mp4decrypt", movie(two_sinf(A, piff_first=True))) is usable assert can_use(drm, "mp4decrypt", movie(encv(A))) is usable def test_segment_decrypt_waits_for_a_key_to_every_kid_the_drm_names( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr(config, "decrypt_segments", True, raising=False) monkeypatch.setattr(binaries, "Mp4decrypt", tmp_path / "mp4decrypt") drm = _widevine(A, B) drm.content_keys[A] = KEY assert can_use(drm, "mp4decrypt", movie(encv(A))) is False class StubDRM: """Records which decrypter ran; mp4decrypt writes ``mp4decrypt_output`` over the file.""" def __init__(self, mp4decrypt_output: bytes) -> None: self.output = mp4decrypt_output self.calls: list[str] = [] def decrypt_with_mp4decrypt(self, path: Path) -> None: self.calls.append("mp4decrypt") path.write_bytes(self.output) def decrypt_with_shaka_packager(self, path: Path) -> None: self.calls.append("shaka") ENCRYPTED = movie(encv(A)) + moof(1, 0) @pytest.mark.parametrize( ("output", "calls"), [ pytest.param(ENCRYPTED, ["mp4decrypt", "shaka"], id="copied-through"), pytest.param(movie(encv(A)) + moof(1, 1000), ["mp4decrypt"], id="stale-encrypted-moov"), pytest.param(movie(box(b"avc1", bytes(78))) + moof(1, 1000), ["mp4decrypt"], id="decrypted"), pytest.param(b"not an mp4", ["mp4decrypt"], id="unreadable"), ], ) def test_mp4decrypt_or_shaka(tmp_path: Path, output: bytes, calls: list[str]) -> None: drm = StubDRM(output) path = tmp_path / "track.mp4" path.write_bytes(ENCRYPTED) mp4decrypt_or_shaka(drm, path) assert drm.calls == calls @pytest.fixture def mp4decrypt_writes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Callable[[bytes | None, int, str], None]: """An mp4decrypt that writes ``output`` (nothing for ``None``), prints ``stderr`` and exits with ``code``.""" def install(output: bytes | None, code: int, stderr: str) -> None: script = tmp_path / "mp4decrypt" write = "" if output is None else f"open(sys.argv[-1], 'wb').write({output!r})\n" script.write_text( f"#!/usr/bin/env python3\nimport sys\n{write}sys.stderr.write({stderr!r})\nsys.exit({code})\n" ) script.chmod(0o755) monkeypatch.setattr(binaries, "Mp4decrypt", script) return install def mp4decrypt_track(tmp_path: Path) -> tuple[Path, bytes, Any]: """An encrypted track, its bytes and a Widevine DRM that holds its key.""" path = write_movie(tmp_path / "track.mp4", encv(A)) drm = _widevine(A) drm.content_keys[A] = KEY return path, path.read_bytes(), drm @POSIX_STUBS def test_mp4decrypt_replaces_the_input_with_its_output( tmp_path: Path, mp4decrypt_writes: Callable[[bytes | None, int, str], None] ) -> None: mp4decrypt_writes(b"decrypted", 0, "") path, original, drm = mp4decrypt_track(tmp_path) backup = tmp_path / "track.mp4.enc" os.link(path, backup) drm.decrypt_with_mp4decrypt(path) assert path.read_bytes() == b"decrypted" assert backup.read_bytes() == original assert not (tmp_path / "track_decrypted.mp4").exists() @POSIX_STUBS @pytest.mark.parametrize( ("output", "code", "stderr", "raises"), [ pytest.param(None, 0, "", RuntimeError, id="exit-0-no-output"), pytest.param(b"", 0, "", RuntimeError, id="exit-0-empty-output"), pytest.param( b"partial", 0, "ERROR: failed to process the file (-10)\n", subprocess.CalledProcessError, id="exit-0-error" ), pytest.param(b"partial", 1, "", subprocess.CalledProcessError, id="non-zero-exit"), ], ) def test_a_failed_mp4decrypt_keeps_the_input( tmp_path: Path, mp4decrypt_writes: Callable[[bytes | None, int, str], None], output: bytes | None, code: int, stderr: str, raises: type[BaseException], ) -> None: mp4decrypt_writes(output, code, stderr) # the path holds a keyword that categorize_exception reads as a rate limit tmp_path = tmp_path / "work-429" tmp_path.mkdir() path, original, drm = mp4decrypt_track(tmp_path) stray = tmp_path / "track_decrypted.mp4" stray.write_bytes(b"stale") with pytest.raises(raises) as caught: drm.decrypt_with_mp4decrypt(path) assert path.read_bytes() == original assert not stray.exists() assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR @POSIX_STUBS def test_a_failed_swap_keeps_the_input( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mp4decrypt_writes: Callable[[bytes | None, int, str], None] ) -> None: def refuse(self: Path, target: Path) -> None: raise PermissionError(target) mp4decrypt_writes(b"decrypted", 0, "") path, original, drm = mp4decrypt_track(tmp_path) monkeypatch.setattr(Path, "replace", refuse) with pytest.raises(PermissionError): drm.decrypt_with_mp4decrypt(path) assert path.read_bytes() == original assert not (tmp_path / "track_decrypted.mp4").exists() @pytest.fixture def stub_packager(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Callable[[int], None]: """A shaka-packager that writes its output, logs an ERROR line and exits with the code given.""" def install(code: int) -> None: script = tmp_path / "packager" script.write_text( "#!/usr/bin/env python3\n" "import sys\n" "output = sys.argv[1].split('output=')[1].split(',')[0]\n" "open(output, 'wb').write(b'decrypted')\n" "sys.stderr.write('[1103/153702:ERROR:box_definitions.cc(641)] Not implemented reached\\n')\n" f"sys.exit({code})\n" ) script.chmod(0o755) monkeypatch.setattr(binaries, "ShakaPackager", script) return install @POSIX_STUBS @pytest.mark.parametrize("make", DRMS) def test_shaka_error_line_with_exit_0_is_a_decrypt( tmp_path: Path, stub_packager: Callable[[int], None], make: Callable[[], Any] ) -> None: stub_packager(0) path = tmp_path / "track.mp4" path.write_bytes(b"encrypted") drm = make() drm.content_keys[A] = KEY drm.decrypt_with_shaka_packager(path) assert path.read_bytes() == b"decrypted" @POSIX_STUBS @pytest.mark.parametrize("make", DRMS) def test_shaka_non_zero_exit_raises( tmp_path: Path, stub_packager: Callable[[int], None], make: Callable[[], Any] ) -> None: stub_packager(2) path = tmp_path / "track.mp4" path.write_bytes(b"encrypted") drm = make() drm.content_keys[A] = KEY with pytest.raises(subprocess.CalledProcessError): drm.decrypt_with_shaka_packager(path) class FakePackager: """A shaka-packager Popen that records its argv, prints ``log`` and exits with ``code``.""" code = 0 log = "" argv: list[str] = [] def __init__(self, cmd: list[Any], **kwargs: Any) -> None: FakePackager.argv = [str(c) for c in cmd] self.stderr = io.StringIO(FakePackager.log) self.returncode = FakePackager.code def wait(self) -> int: return self.returncode @pytest.fixture def fake_packager(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: """Route shaka-packager to ``FakePackager``.""" FakePackager.code, FakePackager.log = 0, "" monkeypatch.setattr(decrypters_module.subprocess, "Popen", FakePackager) monkeypatch.setattr(binaries, "ShakaPackager", Path("packager")) monkeypatch.setattr(config.directories, "temp", tmp_path) def shaka_run(tmp_path: Path, make: Callable[[], Any], raises: type[BaseException]) -> BaseException: """Decrypt a one-key track of ``make()`` through ``FakePackager`` and return the ``raises`` it raised.""" path = tmp_path / "track.mp4" path.write_bytes(b"encrypted") drm = make() drm.content_keys[A] = KEY with pytest.raises(raises) as caught: drm.decrypt_with_shaka_packager(path) assert path.read_bytes() == b"encrypted" return caught.value @pytest.mark.parametrize("make", DRMS) @pytest.mark.usefixtures("fake_packager") def test_every_drm_passes_the_fake_clock(tmp_path: Path, make: Callable[[], Any]) -> None: shaka_run(tmp_path, make, FileNotFoundError) assert "--use_fake_clock_for_muxer" in FakePackager.argv @pytest.mark.usefixtures("fake_packager") def test_clearkey_gives_no_zero_kid_fallback(tmp_path: Path) -> None: shaka_run(tmp_path, lambda: ClearKeyCENC(kids=[A]), FileNotFoundError) assert FakePackager.argv[FakePackager.argv.index("--keys") + 1] == f"label=0:key_id={A.hex}:key={KEY}" @pytest.mark.usefixtures("fake_packager") @pytest.mark.parametrize("make", DRMS) def test_a_shaka_failure_names_the_reason_and_keeps_the_key(tmp_path: Path, make: Callable[[], Any]) -> None: FakePackager.code = 2 FakePackager.log = ( "I1103 15:37:02 demuxer.cc(89)] Demuxer::Run()\n[1103/153702:ERROR:main.cc(1)] Packaging Error: 5\n" ) error = shaka_run(tmp_path, make, subprocess.CalledProcessError) assert str(error).startswith("shaka-packager failed (exit 2): Packaging Error: 5; command: ") assert KEY in str(error) and "Demuxer" not in str(error) assert categorize_exception(error).error_code == APIErrorCode.DRM_ERROR @pytest.mark.usefixtures("fake_packager") @pytest.mark.parametrize("make", DRMS) def test_a_skipped_shaka_stream_keeps_the_input(tmp_path: Path, make: Callable[[], Any]) -> None: FakePackager.log = ( "[1128/120000:INFO:mp4_muxer.cc(1)] Skip stream 'track_decrypted.mp4' which does not contain any sample.\n" ) path = tmp_path / "track.mp4" path.write_bytes(b"encrypted") stray = tmp_path / "track_decrypted.mp4" stray.write_bytes(b"stale") drm = make() drm.content_keys[A] = KEY drm.decrypt_with_shaka_packager(path) assert path.read_bytes() == b"encrypted" assert not stray.exists() @pytest.mark.usefixtures("fake_packager") def test_a_shaka_ctrl_c_exit_is_a_keyboard_interrupt(tmp_path: Path) -> None: FakePackager.code = 0xC000013A shaka_run(tmp_path, lambda: _widevine(A), KeyboardInterrupt) @pytest.mark.parametrize( ("line", "noise"), [ pytest.param( "I1103 21:41:56.557273 16212 packager_main.cc:591] Excluding 'pssh' boxes", True, id="glog-info" ), pytest.param("I0503 01:02:03.000000 1 demuxer.cc:105] Demuxer::Run()", True, id="glog-info-early-month"), pytest.param("W1103 21:41:56.000000 1 x.cc:1] warning", True, id="glog-warning"), pytest.param( "[1103/214121:WARNING:track_run_iterator.cc(699)] Seeing non-zero composition offset", True, id="warning" ), pytest.param("[1103/153402:INFO:demuxer.cc(170)] Initialize Demuxer", True, id="info"), pytest.param("[1103/153402:ERROR:box_definitions.cc(641)] Not implemented reached", False, id="error"), pytest.param("E1103 21:41:56.000000 1 x.cc:1] failed", False, id="glog-error"), pytest.param("Packaging completed successfully.", False, id="plain"), ], ) def test_shaka_noise(line: str, noise: bool) -> None: assert shaka_noise(line) is noise