diff --git a/tests/core/test_mp4decrypt_track_key.py b/tests/core/test_mp4decrypt_track_key.py index 1a8b6096..89de71ad 100644 --- a/tests/core/test_mp4decrypt_track_key.py +++ b/tests/core/test_mp4decrypt_track_key.py @@ -1,6 +1,7 @@ from __future__ import annotations import io +import os import subprocess import sys from collections.abc import Callable @@ -185,6 +186,98 @@ def test_mp4decrypt_or_shaka(tmp_path: Path, output: bytes, calls: list[str]) -> 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) + 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() + if raises is subprocess.CalledProcessError: + 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.""" diff --git a/unshackle/core/drm/decrypters.py b/unshackle/core/drm/decrypters.py index 29538dbe..98dbaa2d 100644 --- a/unshackle/core/drm/decrypters.py +++ b/unshackle/core/drm/decrypters.py @@ -1,7 +1,7 @@ """Whole-file CENC decryption with mp4decrypt or shaka-packager, shared by Widevine, PlayReady and ClearKeyCENC.""" +import contextlib import logging -import shutil import subprocess from collections.abc import Callable from pathlib import Path @@ -79,7 +79,11 @@ def decrypt_cenc(drm: Any, path: Path, drm_type: str) -> None: def mp4decrypt(path: Path, key_args_for: Callable[[dict[int, UUID]], list[str]]) -> None: - """Decrypt ``path`` in place with mp4decrypt, taking the ``--key`` arguments from ``key_args_for(track_kids)``.""" + """Decrypt ``path`` in place with mp4decrypt, taking the ``--key`` arguments from ``key_args_for(track_kids)``. + + A failure keeps ``path`` as it is and removes the output. mp4decrypt exits 0 after it fails to + process a file and leaves a partial output, so this function also reads its stderr. + """ if not binaries.Mp4decrypt: raise coded(OSError("mp4decrypt executable not found but is required."), APIErrorCode.DRM_ERROR) @@ -87,18 +91,21 @@ def mp4decrypt(path: Path, key_args_for: Callable[[dict[int, UUID]], list[str]]) key_args = key_args_for(kidless_track_kids(read_top_level_box(path, b"moov") or b"")) cmd = [str(binaries.Mp4decrypt), "--show-progress", *key_args, str(path), str(output_path)] + output_path.unlink(missing_ok=True) try: - run_tool("mp4decrypt", cmd, "mp4decrypt") + p = run_tool("mp4decrypt", cmd, "mp4decrypt") + if b"failed to process" in p.stderr: + raise ToolFailed("mp4decrypt", p.returncode, cmd, p.stdout, p.stderr) + if not output_path.exists(): + raise RuntimeError(f"mp4decrypt failed: output file {output_path} was not created") + if output_path.stat().st_size == 0: + raise RuntimeError(f"mp4decrypt failed: output file {output_path} is empty") + output_path.replace(path) except ToolFailed as e: raise coded(e, APIErrorCode.DRM_ERROR) from None - - if not output_path.exists(): - raise RuntimeError(f"mp4decrypt failed: output file {output_path} was not created") - if output_path.stat().st_size == 0: - raise RuntimeError(f"mp4decrypt failed: output file {output_path} is empty") - - path.unlink() - shutil.move(output_path, path) + finally: + with contextlib.suppress(OSError): + output_path.unlink(missing_ok=True) def shaka_decrypt(path: Path, keys: str) -> None: