fix(drm): send a bridged licence key to the server vault only after its decode check decodes it

This commit is contained in:
imSp4rky
2026-12-01 21:42:36 -07:00
parent cefd5295ac
commit 1288a8e9b7
3 changed files with 42 additions and 18 deletions
+1 -1
View File
@@ -1275,7 +1275,7 @@ A slow answer arrives as a [slow response](#slow-responses).
### `POST /api/session/{session_id}/keys` ### `POST /api/session/{session_id}/keys`
Store the content keys that the client proved on a track and that the server did not serve to this remote session. The server stores a content key only for a KID that a track of the remote session names and that no local server vault holds a content key for. It never stores a pair flagged bad, and it never removes a flag. The server answers when its local vaults hold the pairs, and sends them to its other vaults after the answer. The client sends each key of a licence when the licence returns, and each vault key after its decode check passes. Store the content keys that the client proved on a track and that the server did not serve to this remote session. The server stores a content key only for a KID that a track of the remote session names and that no local server vault holds a content key for. It never stores a pair flagged bad, and it never removes a flag. The server answers when its local vaults hold the pairs, and sends them to its other vaults after the answer. The client sends each key of a licence when the licence returns, and each vault key after its decode check passes. A licence key of a FairPlay-only track that the client licensed through the bridge goes only after its decode check passes, so a client without FFmpeg does not send it.
```json ```json
{ "track_id": "<track_id>", "keys": { "<kid_hex>": "<key_hex>" } } { "track_id": "<track_id>", "keys": { "<kid_hex>": "<key_hex>" } }
+23 -7
View File
@@ -127,6 +127,9 @@ def decrypt(
track: Any = "track", track: Any = "track",
flagged: dict | None = None, flagged: dict | None = None,
licence: Any = None, licence: Any = None,
bridged: bool = False,
decrypting: bool = True,
unnamed: dict | None = None,
) -> list: ) -> list:
"""Decrypt a track that holds a licence key, a vault key and a null key; return what reached the server vault.""" """Decrypt a track that holds a licence key, a vault key and a null key; return what reached the server vault."""
monkeypatch.setattr(key_resolution.binaries, "FFMPEG", ffmpeg) monkeypatch.setattr(key_resolution.binaries, "FFMPEG", ffmpeg)
@@ -146,21 +149,34 @@ def decrypt(
vaults.flag_bad_key(kid, key) vaults.flag_bad_key(kid, key)
path = tmp_path / "video.mp4" path = tmp_path / "video.mp4"
path.write_bytes(b"cipher") path.write_bytes(b"cipher")
content_keys = {LICENSED: KEY, VAULTED: OTHER_KEY, NULL: "0" * 32, **(flagged or {})} named = {LICENSED: KEY, VAULTED: OTHER_KEY, NULL: "0" * 32, **(flagged or {})}
drm = SimpleNamespace(content_keys=content_keys, decrypt=lambda path: None) content_keys = {**named, **(unnamed or {})}
drm = SimpleNamespace(content_keys=content_keys, kids=list(named), bridged=bridged, decrypt=lambda path: None)
try: try:
keys.decrypt_verified(drm, path, licence, LICENSED, track=track) keys.decrypt_verified(drm, path, licence, LICENSED, decrypting, track=track)
finally: finally:
keys.wait_vault_writes() keys.wait_vault_writes()
return pushed return pushed
def test_a_passed_decode_sends_the_licence_keys_and_the_checked_vault_keys(tmp_path, monkeypatch) -> None: @pytest.mark.parametrize("bridged", [False, True], ids=["licence", "bridged-licence"])
assert decrypt(tmp_path, monkeypatch, "ffmpeg") == [({LICENSED: KEY, VAULTED: OTHER_KEY}, "track")] def test_a_passed_decode_sends_the_licence_keys_and_the_checked_vault_keys(tmp_path, monkeypatch, bridged) -> None:
pushed = decrypt(tmp_path, monkeypatch, "ffmpeg", bridged=bridged)
assert pushed == [({LICENSED: KEY, VAULTED: OTHER_KEY}, "track")]
def test_without_ffmpeg_a_vault_key_is_not_sent(tmp_path, monkeypatch) -> None: @pytest.mark.parametrize("decrypting", [True, False], ids=["decrypt", "decrypted-in-place"])
assert decrypt(tmp_path, monkeypatch, None) == [({LICENSED: KEY}, "track")] @pytest.mark.parametrize("bridged", [False, True], ids=["licence", "bridged-licence"])
def test_without_ffmpeg_no_vault_key_and_no_bridged_licence_key_is_sent(
tmp_path, monkeypatch, bridged, decrypting
) -> None:
pushed = decrypt(tmp_path, monkeypatch, None, bridged=bridged, decrypting=decrypting)
assert pushed == ([] if bridged else [({LICENSED: KEY}, "track")])
def test_a_bridged_licence_key_the_check_did_not_decode_is_not_sent(tmp_path, monkeypatch) -> None:
pushed = decrypt(tmp_path, monkeypatch, "ffmpeg", bridged=True, unnamed={UNNAMED: KEY})
assert pushed == [({LICENSED: KEY, VAULTED: OTHER_KEY}, "track")]
def test_a_failed_decode_sends_nothing(tmp_path, monkeypatch) -> None: def test_a_failed_decode_sends_nothing(tmp_path, monkeypatch) -> None:
+18 -10
View File
@@ -156,7 +156,8 @@ class ContentKeyResolver:
failure can only flag and raise; the next run skips the flagged pair. failure can only flag and raise; the next run skips the flagged pair.
After a decrypt that passes, the server key source's vault gets the proven content keys of After a decrypt that passes, the server key source's vault gets the proven content keys of
``track``: each licence key, and each vault key the decode check passed. ``track``: each licence key, and each vault key the decode check passed. A bridged track sends only
the licence keys that the decode check decoded.
Before the decrypt, each KID the DRM names without a content key is licensed when the file Before the decrypt, each KID the DRM names without a content key is licensed when the file
uses it, or when the file cannot be mapped, because ``_prepare_drm`` licensed only for the track's KID. uses it, or when the file cannot be mapped, because ``_prepare_drm`` licensed only for the track's KID.
@@ -239,11 +240,16 @@ class ContentKeyResolver:
windows = kid_map.windows if kid_map else {} windows = kid_map.windows if kid_map else {}
video = kid_map.video if kid_map else None video = kid_map.video if kid_map else None
def proven(passed: dict[UUID, KeySource]) -> dict[UUID | str, str]: def proven(passed: dict[UUID, KeySource], decoded: set[UUID]) -> dict[UUID | str, str]:
"""The licence keys and the vault keys in ``passed``, without null keys; a flagged pair never gets here.""" """The licence keys and the vault keys in ``passed``, without null keys; a flagged pair never gets here.
A bridged DRM's licence key counts only when its KID is in ``decoded``.
"""
sourced = vault_kids() sourced = vault_kids()
return { return {
kid: key for kid, key in keys.items() if (kid in passed or kid not in sourced) and not is_null_key(key) kid: key
for kid, key in keys.items()
if (kid in passed or (kid in decoded if bridged else kid not in sourced)) and not is_null_key(key)
} }
def window_decodes(start: float, end: float) -> bool: def window_decodes(start: float, end: float) -> bool:
@@ -256,14 +262,15 @@ class ContentKeyResolver:
return {kid: vault for kid, vault in kids.items() if kid in windows} return {kid: vault for kid, vault in kids.items() if kid in windows}
return kids return kids
def refuse_bad_licence_keys() -> None: def refuse_bad_licence_keys() -> set[UUID]:
"""Stop a bridged track whose licence content key does not decode, and flag the pair like a bad vault key. """Stop a bridged track whose licence content key does not decode, and flag the pair like a bad vault key.
A multi-DRM licence server can issue a PlayReady or Widevine content key that is not the FairPlay one. A multi-DRM licence server can issue a PlayReady or Widevine content key that is not the FairPlay one.
The flag goes through the vault writer, after the licence's own write of the pair. The flag goes through the vault writer, after the licence's own write of the pair. Returns the KIDs that
the check decoded.
""" """
if not (bridged and binaries.FFMPEG and path.exists()): if not (bridged and binaries.FFMPEG and path.exists()):
return return set()
sourced = vault_kids() sourced = vault_kids()
licensed = judged_kids({kid: None for kid in real_kids(drm) if kid in keys and kid not in sourced}) licensed = judged_kids({kid: None for kid in real_kids(drm) if kid in keys and kid not in sourced})
if bad := failed_kids(licensed): if bad := failed_kids(licensed):
@@ -273,6 +280,7 @@ class ContentKeyResolver:
raise ValueError( raise ValueError(
f"The licence content key of KID {kid.hex} does not decrypt track {getattr(track, 'id', path.name)}" f"The licence content key of KID {kid.hex} does not decrypt track {getattr(track, 'id', path.name)}"
) )
return set(licensed)
def failed_kids(kids: dict[UUID, Any]) -> set[UUID]: def failed_kids(kids: dict[UUID, Any]) -> set[UUID]:
"""The vault KIDs whose content key did not decode. """The vault KIDs whose content key did not decode.
@@ -311,12 +319,12 @@ class ContentKeyResolver:
checked = bool(kids and binaries.FFMPEG and path.exists()) checked = bool(kids and binaries.FFMPEG and path.exists())
failed = failed_kids(kids) if checked else set() failed = failed_kids(kids) if checked else set()
if not failed: if not failed:
refuse_bad_licence_keys() decoded = refuse_bad_licence_keys()
passed = kids if checked else {} passed = kids if checked else {}
self._flush_vault_writes([partial(self.vaults.proven, dict(keys), passed)]) self._flush_vault_writes([partial(self.vaults.proven, dict(keys), passed)])
server_vault = self.source.server_vault if self.source and track is not None else None server_vault = self.source.server_vault if self.source and track is not None else None
if server_vault is not None: if server_vault is not None and (sent := proven(passed, decoded)):
self._flush_vault_writes([partial(server_vault.add_keys, self.tag, proven(passed), track)]) self._flush_vault_writes([partial(server_vault.add_keys, self.tag, sent, track)])
return return
bad = {kid: drop(kid) for kid in {*failed, *stale}} bad = {kid: drop(kid) for kid in {*failed, *stale}}
for kid, key in bad.items(): for kid, key in bad.items():