mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
refactor(api): answer every API key question from one KeyPolicy
This commit is contained in:
@@ -9,7 +9,7 @@ import click
|
||||
import pytest
|
||||
|
||||
import unshackle.commands.dl as dl_module
|
||||
from unshackle.core.api import download_manager, handlers
|
||||
from unshackle.core.api import download_manager, handlers, key_policy
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.services import Services
|
||||
|
||||
@@ -57,7 +57,7 @@ def session_params(monkeypatch: pytest.MonkeyPatch, data: dict) -> dict:
|
||||
seen["params"] = parent_ctx.params
|
||||
return object()
|
||||
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda service: {})
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
|
||||
|
||||
@@ -15,7 +15,7 @@ from pywidevine import DeviceTypes
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
from tests.remote.sessions import session_entry
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.input_bridge import InputBridge
|
||||
from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call
|
||||
@@ -170,7 +170,7 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
|
||||
class Declares:
|
||||
CLIENT_CONFIG = ("esn",)
|
||||
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda tag: {"esn": "SERVER"})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {"esn": "SERVER"})
|
||||
monkeypatch.setattr(
|
||||
handlers,
|
||||
"served_context",
|
||||
@@ -331,7 +331,7 @@ def test_a_lent_device_gives_the_service_the_server_config_back(monkeypatch: pyt
|
||||
CLIENT_CONFIG = ("esn", "esn_map")
|
||||
|
||||
monkeypatch.setattr(
|
||||
handlers, "load_service_config", lambda tag: {"esn": "SERVER", "esn_map": {7000: "s"}, "other": 1}
|
||||
key_policy, "load_service_config", lambda tag: {"esn": "SERVER", "esn_map": {7000: "s"}, "other": 1}
|
||||
)
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: server_device)
|
||||
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm, config=obj.config))
|
||||
@@ -474,7 +474,6 @@ def test_the_server_licence_route_follows_the_licensing_mode(
|
||||
monkeypatch: pytest.MonkeyPatch, fields: dict, forbidden: bool
|
||||
) -> None:
|
||||
"""A session that the client's device licenses reaches the server licence route only for the server vault."""
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, service: True)
|
||||
with pytest.raises(APIError) as caught:
|
||||
handlers.license_response({"mode": "server_cdm", "track_id": "none"}, session_entry(**fields), "sess", None)
|
||||
assert (caught.value.error_code is APIErrorCode.FORBIDDEN) is forbidden
|
||||
|
||||
@@ -531,8 +531,8 @@ async def test_health_vault_checks_are_told_apart_by_name(aiohttp_server, monkey
|
||||
|
||||
|
||||
def test_rate_limit_value_must_be_a_positive_whole_number() -> None:
|
||||
"""key_rate_limit reads anything else as unlimited, so it has to be caught at startup."""
|
||||
from unshackle.core.api.stats import key_rate_limit, rate_limit_error
|
||||
"""KeyPolicy.rate_limit reads anything else as unlimited, so it has to be caught at startup."""
|
||||
from unshackle.core.api.key_policy import KeyPolicy, rate_limit_error
|
||||
|
||||
assert rate_limit_error("serve.tiers.bot", 600) is None
|
||||
assert rate_limit_error("serve.tiers.bot", None) is None
|
||||
@@ -542,7 +542,7 @@ def test_rate_limit_value_must_be_a_positive_whole_number() -> None:
|
||||
with pytest.MonkeyPatch().context() as m:
|
||||
m.setitem(config.serve, "tiers", {"bot": {"rate_limit": "600"}})
|
||||
m.setitem(config.serve, "users", {"k": {"tier": "bot"}})
|
||||
assert key_rate_limit("k") is None
|
||||
assert KeyPolicy.of("k").rate_limit is None
|
||||
|
||||
|
||||
async def test_dashboard_key_gets_its_own_row(aiohttp_client, dashboard_cfg) -> None:
|
||||
|
||||
@@ -64,7 +64,6 @@ async def _run_batch(monkeypatch, tracks, cdm_type, calls):
|
||||
return {"00" * 16: "key"}
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", fake_get_session)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", lambda track, session=None, init_data=None: None)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: cdm_type)
|
||||
|
||||
@@ -5,7 +5,7 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.utils import ip_info
|
||||
@@ -111,17 +111,6 @@ def test_no_proxy_short_circuits(monkeypatch):
|
||||
assert providers == []
|
||||
|
||||
|
||||
def test_server_proxy_allowed_entitlements():
|
||||
assert handlers.server_proxy_allowed(request("proxykey")) is True
|
||||
assert handlers.server_proxy_allowed(request("plainkey")) is False
|
||||
# yaml string "true" is not the boolean opt-in
|
||||
assert handlers.server_proxy_allowed(request("strkey")) is False
|
||||
# no implicit admin access: a key absent from serve.users is denied
|
||||
assert handlers.server_proxy_allowed(request("adminsecret")) is False
|
||||
# no request (an internal call, or a handler that dropped it) fails closed
|
||||
assert handlers.server_proxy_allowed(None) is False
|
||||
|
||||
|
||||
def test_opted_in_country_code_resolves(monkeypatch):
|
||||
patch_server_region(monkeypatch, "IN")
|
||||
provider = patch_providers(monkeypatch, "http://us.proxy:8080")
|
||||
@@ -182,7 +171,7 @@ def test_setup_list_service_threads_request(monkeypatch):
|
||||
def authenticate(self, cookies, credential):
|
||||
seen["authenticated"] = True
|
||||
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda service: {})
|
||||
monkeypatch.setattr(handlers, "resolve_handler_proxy", fake_resolve)
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||
@@ -200,7 +189,7 @@ def test_search_reports_failed_proxy_check_as_invalid_proxy(monkeypatch):
|
||||
def failed_check(*args):
|
||||
raise ConnectionError("Proxy check failed: no IP lookup got through the proxy.")
|
||||
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda service: {})
|
||||
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: ("http://127.0.0.1:9", []))
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||
@@ -219,7 +208,8 @@ class TestDownloadGates:
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def cdm_gate_open(self, monkeypatch):
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request=None, service=None: True)
|
||||
users = {key: {**entry, "server_cdm": True} for key, entry in USERS.items()}
|
||||
monkeypatch.setattr(handlers.config, "serve", {"users": users}, raising=False)
|
||||
|
||||
def test_country_code_rejected_when_denied(self, monkeypatch):
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
|
||||
@@ -8,8 +8,9 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
from unshackle.core.api.session_store import get_session_store
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.remote_protocol import AuthStatus
|
||||
@@ -24,36 +25,36 @@ def server(monkeypatch, tmp_path):
|
||||
|
||||
|
||||
def test_a_key_entry_replaces_the_whole_server_entry(server):
|
||||
user = {"cdm": {"example": "own_pr"}}
|
||||
assert handlers.key_cdm_config(user).cdm == {"OTHER": "x", "example": "own_pr"}
|
||||
user = KeyPolicy({"cdm": {"example": "own_pr"}})
|
||||
assert user.cdm_config().cdm == {"OTHER": "x", "example": "own_pr"}
|
||||
assert handlers.resolve_device_name(user, "widevine", "EXAMPLE") == "own_pr"
|
||||
assert handlers.key_cdm_config({}) is config
|
||||
assert KeyPolicy({}).cdm_config() is config
|
||||
|
||||
|
||||
def test_licence_device_comes_from_the_key_entry(server):
|
||||
assert handlers.resolve_device_name({"cdm": {"EXAMPLE": "own"}}, "playready", "EXAMPLE") == "own"
|
||||
assert handlers.resolve_device_name({}, "playready", "EXAMPLE") == "shared_pr"
|
||||
assert handlers.resolve_device_name(KeyPolicy({"cdm": {"EXAMPLE": "own"}}), "playready", "EXAMPLE") == "own"
|
||||
assert handlers.resolve_device_name(KeyPolicy({}), "playready", "EXAMPLE") == "shared_pr"
|
||||
|
||||
|
||||
def test_a_session_keeps_the_user_config_it_was_created_with(server, monkeypatch):
|
||||
session = SimpleNamespace(user_config={"cdm": {"EXAMPLE": "pinned"}})
|
||||
monkeypatch.setattr(handlers, "serve_user_config", lambda key: {"cdm": {"EXAMPLE": "reloaded"}})
|
||||
assert handlers.session_user_config(session, None)["cdm"]["EXAMPLE"] == "pinned"
|
||||
assert handlers.session_user_config(SimpleNamespace(), None)["cdm"]["EXAMPLE"] == "reloaded"
|
||||
def test_a_session_keeps_the_policy_it_was_created_with(server, monkeypatch):
|
||||
pinned, reloaded = KeyPolicy({"cdm": {"EXAMPLE": "pinned"}}), KeyPolicy({"cdm": {"EXAMPLE": "reloaded"}})
|
||||
monkeypatch.setattr(handlers, "request_policy", lambda request: reloaded)
|
||||
assert handlers.session_policy(SimpleNamespace(policy=pinned), None) is pinned
|
||||
assert handlers.session_policy(SimpleNamespace(), None) is reloaded
|
||||
|
||||
|
||||
def test_the_key_block_beats_the_server_config_and_profile_sections(server, monkeypatch):
|
||||
base = {"device_id": "server", "device_key": "server", "p1": {"device_id": "p1", "other": 1}, "urls": {"a": "b"}}
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda service: json.loads(json.dumps(base)))
|
||||
user = {"service_config": {"example": {"device_id": "key", "device_key": "key"}}}
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda service: json.loads(json.dumps(base)))
|
||||
user = KeyPolicy({"service_config": {"example": {"device_id": "key", "device_key": "key"}}})
|
||||
|
||||
merged = handlers.key_service_yaml("EXAMPLE", user)
|
||||
merged = user.service_yaml("EXAMPLE")
|
||||
|
||||
assert merged["device_id"] == merged["device_key"] == "key"
|
||||
assert merged["p1"] == {"device_id": "key", "other": 1}
|
||||
assert merged["urls"] == {"a": "b"}
|
||||
assert handlers.key_service_yaml("EXAMPLE", {})["device_id"] == "server"
|
||||
assert handlers.key_owns_identity(user, "EXAMPLE") and not handlers.key_owns_identity(user, "OTHER")
|
||||
assert KeyPolicy({}).service_yaml("EXAMPLE")["device_id"] == "server"
|
||||
assert user.owns_identity("EXAMPLE") and not user.owns_identity("OTHER")
|
||||
|
||||
|
||||
class _Service:
|
||||
@@ -61,13 +62,13 @@ class _Service:
|
||||
|
||||
|
||||
def test_identity_keys_live_in_the_api_key_directory_and_never_reach_the_client(server):
|
||||
cache = handlers.keyed_cache("_s", _Service(), "EXAMPLE", "k", {}, temporary=True)
|
||||
cache = handlers.keyed_cache("_s", _Service(), "EXAMPLE", "k", KeyPolicy(), temporary=True)
|
||||
cache.get("keys/device1").set("keys")
|
||||
cache.get("tokens").set("login")
|
||||
|
||||
assert set(handlers.collect_cache_files("_s")) == {"tokens"}
|
||||
assert list((server / "_identity").rglob("device1.json"))
|
||||
assert handlers.keyed_cache("_t", _Service(), "EXAMPLE", "k", {}, True).get("keys/device1").data == "keys"
|
||||
assert handlers.keyed_cache("_t", _Service(), "EXAMPLE", "k", KeyPolicy(), True).get("keys/device1").data == "keys"
|
||||
|
||||
text = base64.b64encode(zlib.compress(b'{"data": "planted"}')).decode("ascii")
|
||||
handlers.write_client_cache({"keys/device1": text}, "_s")
|
||||
@@ -75,16 +76,16 @@ def test_identity_keys_live_in_the_api_key_directory_and_never_reach_the_client(
|
||||
|
||||
|
||||
def test_a_lasting_cache_keeps_identity_keys_apart_only_for_a_key_with_its_own_identity(server):
|
||||
own = {"service_config": {"EXAMPLE": {"device_id": "key"}}}
|
||||
assert handlers.keyed_cache("_accounts/EXAMPLE/p", _Service(), "EXAMPLE", "k", {}).route is None
|
||||
own = KeyPolicy({"service_config": {"EXAMPLE": {"device_id": "key"}}})
|
||||
assert handlers.keyed_cache("_accounts/EXAMPLE/p", _Service(), "EXAMPLE", "k", KeyPolicy()).route is None
|
||||
assert handlers.keyed_cache("_accounts/EXAMPLE/p", _Service(), "EXAMPLE", "k", own).route is not None
|
||||
assert handlers.keyed_cache("_s", object(), "EXAMPLE", "k", own, temporary=True).route is None
|
||||
|
||||
|
||||
def test_a_job_is_refused_for_a_key_with_its_own_identity(server, monkeypatch):
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, service: True)
|
||||
monkeypatch.setattr(handlers, "server_cdm_max_height", lambda request, service: None)
|
||||
monkeypatch.setattr(handlers, "serve_user_config", lambda key: {"cdm": {"EXAMPLE": "own"}})
|
||||
monkeypatch.setattr(
|
||||
handlers, "request_policy", lambda request: KeyPolicy({"server_cdm": True, "cdm": {"EXAMPLE": "own"}})
|
||||
)
|
||||
with pytest.raises(APIError, match="its own"):
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE"})
|
||||
|
||||
@@ -103,15 +104,15 @@ def test_a_job_is_refused_for_a_key_with_its_own_identity(server, monkeypatch):
|
||||
)
|
||||
def test_bad_key_config_is_refused_at_load(server, monkeypatch, user_cfg, problem):
|
||||
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
|
||||
assert problem in handlers.key_config_error("serve.users.u", user_cfg)
|
||||
assert problem in KeyPolicy(user_cfg).entry_error("serve.users.u")
|
||||
|
||||
|
||||
def test_a_known_device_passes_validation(server, monkeypatch):
|
||||
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
|
||||
monkeypatch.setattr(handlers, "device_system", lambda name, cfg: "playready")
|
||||
assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"playready": "dev"}}, "service_config": {}}) is None
|
||||
assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"default": "dev"}}, "service_config": None}) is None
|
||||
assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"widevine": "dev"}}}) is not None
|
||||
monkeypatch.setattr(key_policy, "device_system", lambda name, cfg: "playready")
|
||||
assert KeyPolicy({"cdm": {"EXAMPLE": {"playready": "dev"}}, "service_config": {}}).entry_error("u") is None
|
||||
assert KeyPolicy({"cdm": {"EXAMPLE": {"default": "dev"}}, "service_config": None}).entry_error("u") is None
|
||||
assert KeyPolicy({"cdm": {"EXAMPLE": {"widevine": "dev"}}}).entry_error("u") is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -133,12 +134,12 @@ def test_a_session_keeps_identity_keys_from_the_client_unless_the_identity_is_th
|
||||
self.cache.get("keys/device1").set("identity")
|
||||
self.cache.get("tokens").set("login")
|
||||
|
||||
user = {"service_config": {"EXAMPLE": {"device_id": "key"}}} if own else {}
|
||||
user = KeyPolicy({"service_config": {"EXAMPLE": {"device_id": "key"}}} if own else {})
|
||||
text = base64.b64encode(zlib.compress(b'{"data": "x"}')).decode("ascii")
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
|
||||
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
|
||||
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
|
||||
monkeypatch.setattr(handlers, "serve_user_config", lambda key: user)
|
||||
monkeypatch.setattr(handlers, "request_policy", lambda request: user)
|
||||
monkeypatch.setattr(handlers, "choose_session_cdm", lambda *args: (server_cdm, None))
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
|
||||
monkeypatch.setattr(handlers, "create_service_instance", lambda *args, **kwargs: (Service(), None, None))
|
||||
@@ -158,32 +159,32 @@ def test_a_session_keeps_identity_keys_from_the_client_unless_the_identity_is_th
|
||||
|
||||
session, sent_back = asyncio.run(run())
|
||||
|
||||
assert session.user_config is user
|
||||
assert session.policy is user
|
||||
assert sent_back == returned
|
||||
|
||||
|
||||
def test_a_reload_checks_key_devices_against_the_new_config(server, monkeypatch):
|
||||
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
|
||||
fresh = SimpleNamespace(remote_cdm=[{"name": "new_remote", "device_type": "PLAYREADY"}])
|
||||
user = {"cdm": {"EXAMPLE": "new_remote"}}
|
||||
assert handlers.key_config_error("u", user, fresh) is None
|
||||
assert handlers.key_config_error("u", user) is not None
|
||||
user = KeyPolicy({"cdm": {"EXAMPLE": "new_remote"}})
|
||||
assert user.entry_error("u", fresh) is None
|
||||
assert user.entry_error("u") is not None
|
||||
|
||||
|
||||
def test_a_block_value_reaches_only_plain_values_of_other_sections(server, monkeypatch):
|
||||
base = {"p1": {"device_id": "p1", "headers": {"a": "b"}}, "device_key": "server"}
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda service: json.loads(json.dumps(base)))
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda service: json.loads(json.dumps(base)))
|
||||
block = {"device_id": "key", "headers": {"c": "d"}, "device_key": {"nested": 1}}
|
||||
|
||||
merged = handlers.key_service_yaml("EXAMPLE", {"service_config": {"EXAMPLE": block}})
|
||||
merged = KeyPolicy({"service_config": {"EXAMPLE": block}}).service_yaml("EXAMPLE")
|
||||
|
||||
assert merged["p1"] == {"device_id": "key", "headers": {"a": "b"}}
|
||||
assert merged["device_key"] == {"nested": 1}
|
||||
|
||||
|
||||
def test_a_removed_key_loses_its_identity_cache(server):
|
||||
handlers.keyed_cache("_s", _Service(), "EXAMPLE", "gone", {}, True).get("keys/device1").set("keys")
|
||||
handlers.keyed_cache("_s", _Service(), "EXAMPLE", "kept", {}, True).get("keys/device1").set("keys")
|
||||
handlers.keyed_cache("_s", _Service(), "EXAMPLE", "gone", KeyPolicy(), True).get("keys/device1").set("keys")
|
||||
handlers.keyed_cache("_s", _Service(), "EXAMPLE", "kept", KeyPolicy(), True).get("keys/device1").set("keys")
|
||||
handlers.drop_identity_cache({"gone"})
|
||||
assert not (server / "_identity" / handlers.key_namespace("gone")).exists()
|
||||
assert (server / "_identity" / handlers.key_namespace("kept")).exists()
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""What an API key may do, answered by its KeyPolicy from a plain serve.users entry."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api.key_policy import KeyPolicy, api_keys, named_services
|
||||
from unshackle.core.services import Services
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
GRANTS = ("server_cdm", "server_vault", "server_accounts")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def tags(monkeypatch):
|
||||
monkeypatch.setattr(Services, "get_tag", staticmethod(lambda tag: tag.upper()))
|
||||
|
||||
|
||||
def test_a_key_with_no_entry_holds_every_grant_but_the_server_proxy():
|
||||
absent = KeyPolicy.of("api-secret", {"users": {"other": {}}})
|
||||
assert absent == KeyPolicy.of(None, {"users": {"other": {}}}) == KeyPolicy(None, {"users": {"other": {}}})
|
||||
assert not absent.configured and absent.admin
|
||||
assert all(absent.allows(name, "EXAMPLE") and absent.grant(name) is True for name in GRANTS)
|
||||
assert absent.allows("server_proxy") is absent.grant("server_proxy") is False
|
||||
assert absent.max_height("EXAMPLE") is None and absent.rate_limit is None
|
||||
|
||||
|
||||
def test_a_call_with_no_request_gets_the_policy_of_a_key_with_no_entry():
|
||||
from unshackle.core.api.handlers import request_policy
|
||||
|
||||
assert request_policy(None) == KeyPolicy.of(None)
|
||||
assert request_policy(None).entry is None
|
||||
|
||||
|
||||
def test_the_policy_repr_holds_no_other_api_key():
|
||||
assert "secret" not in repr(KeyPolicy({}, {"api_secret": "secret", "users": {"other-secret": {}}}))
|
||||
|
||||
|
||||
def test_an_empty_entry_holds_no_grant():
|
||||
policy = KeyPolicy({})
|
||||
assert policy.configured and not policy.admin
|
||||
assert not any(policy.allows(name, "EXAMPLE") for name in (*GRANTS, "server_proxy"))
|
||||
assert policy.grant("server_cdm") is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["true", 1, "yes"])
|
||||
def test_only_a_real_true_grants_the_server_proxy(value):
|
||||
assert KeyPolicy({"server_proxy": True}).allows("server_proxy") is True
|
||||
assert KeyPolicy({"server_proxy": value}).allows("server_proxy") is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", GRANTS)
|
||||
@pytest.mark.parametrize(
|
||||
("setting", "service", "allowed"),
|
||||
[
|
||||
(True, "EXAMPLE", True),
|
||||
(True, None, True),
|
||||
(["example"], "EXAMPLE", True),
|
||||
(["EXAMPLE"], "OTHER", False),
|
||||
(["EXAMPLE"], None, False),
|
||||
("example", "EXAMPLE", True),
|
||||
("EXAMPLE", "OTHER", False),
|
||||
(False, "EXAMPLE", False),
|
||||
],
|
||||
)
|
||||
def test_a_grant_covers_every_service_or_the_listed_tags(name, setting, service, allowed):
|
||||
assert KeyPolicy({name: setting}).allows(name, service) is allowed
|
||||
|
||||
|
||||
def test_the_server_cdm_grant_gives_the_server_vault():
|
||||
assert KeyPolicy({"server_cdm": ["EXAMPLE"]}).allows("server_vault", "EXAMPLE")
|
||||
assert not KeyPolicy({"server_cdm": ["EXAMPLE"]}).allows("server_vault", "OTHER")
|
||||
assert KeyPolicy({"server_vault": ["OTHER"]}).allows("server_vault", "OTHER")
|
||||
|
||||
|
||||
def test_the_dashboard_view_shows_the_grant_enforcement_reads():
|
||||
policy = KeyPolicy({"server_cdm": "example", "server_accounts": 1, "server_proxy": "true"})
|
||||
assert policy.grant("server_cdm") == ["example"]
|
||||
assert policy.grant("server_accounts") is True
|
||||
assert policy.grant("server_proxy") is False
|
||||
|
||||
|
||||
def test_admin_needs_a_real_true():
|
||||
assert KeyPolicy({"admin": True}).admin
|
||||
assert not KeyPolicy({"admin": "true"}).admin
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("serve", "entry", "services"),
|
||||
[
|
||||
({}, {}, None),
|
||||
({"services": ["example", "OTHER"]}, {}, {"EXAMPLE", "OTHER"}),
|
||||
({}, {"services": ["example"]}, {"EXAMPLE"}),
|
||||
({"services": ["EXAMPLE", "OTHER"]}, {"services": ["other", "THIRD"]}, {"OTHER"}),
|
||||
],
|
||||
)
|
||||
def test_the_services_are_the_global_list_and_the_keys_list_together(serve, entry, services):
|
||||
allowed = KeyPolicy(entry, serve).services
|
||||
assert (set(allowed) if allowed is not None else None) == services
|
||||
|
||||
|
||||
def test_the_named_services_are_the_global_list_else_every_keys_list():
|
||||
users = {"a": {"services": ["example"]}, "b": {"services": ["OTHER", 7]}, "c": {}, "d": "bad"}
|
||||
assert sorted(named_services({"users": users})) == ["EXAMPLE", "OTHER"]
|
||||
assert named_services({"services": ["third"], "users": users}) == ["THIRD"]
|
||||
assert named_services({"users": ["not", "a", "mapping"]}) == []
|
||||
assert api_keys({"users": users}) == ["a", "b", "c", "d"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("setting", "service", "cap"),
|
||||
[
|
||||
(1080, "EXAMPLE1", 1080),
|
||||
({"example1": 720, "default": 1080}, "EXAMPLE1", 720),
|
||||
({"example1": 720, "default": 1080}, "EXAMPLE2", 1080),
|
||||
({"EXAMPLE1": 1080}, "EXAMPLE2", None),
|
||||
({"EXAMPLE1": None, "default": 1080}, "EXAMPLE1", 1080),
|
||||
(None, "EXAMPLE1", None),
|
||||
(True, "EXAMPLE1", None),
|
||||
],
|
||||
)
|
||||
def test_the_height_cap_per_service(setting, service, cap):
|
||||
assert KeyPolicy({"server_cdm_max_height": setting}).max_height(service) == cap
|
||||
|
||||
|
||||
def test_a_key_with_no_entry_gets_every_server_device():
|
||||
serve = {"users": {"k1": {"devices": ["mine"]}}, "devices": [Path("/x/dev.wvd")], "playready_devices": []}
|
||||
assert KeyPolicy.of("k1", serve).devices("devices") == ["mine"]
|
||||
assert KeyPolicy.of("k1", serve).devices("playready_devices") == []
|
||||
assert KeyPolicy.of("admin-secret", serve).devices("devices") == ["dev"]
|
||||
|
||||
|
||||
def test_a_malformed_entry_grants_nothing():
|
||||
policy = KeyPolicy.of("k", {"users": {"k": ["not", "a", "mapping"]}})
|
||||
assert policy.configured and not policy.admin and not policy.allows("server_cdm", "EXAMPLE")
|
||||
|
||||
|
||||
def test_the_rate_limit_is_the_keys_own_else_its_tiers():
|
||||
tiers = {"bot": {"rate_limit": 600}}
|
||||
assert KeyPolicy({"tier": "bot"}, {"tiers": tiers}).rate_limit == 600
|
||||
assert KeyPolicy({"tier": "bot", "rate_limit": 5}, {"tiers": tiers}).rate_limit == 5
|
||||
assert KeyPolicy({"tier": "bot"}, {"tiers": {"bot": {"rate_limit": "600"}}}).rate_limit is None
|
||||
assert KeyPolicy({"tier": "bot"}).tier == "bot"
|
||||
|
||||
|
||||
def test_shared_and_username():
|
||||
assert KeyPolicy({"shared": True, "username": "tier1"}).shared
|
||||
assert not KeyPolicy({"shared": "true"}).shared
|
||||
assert KeyPolicy({"username": "tier1"}).username == "tier1"
|
||||
assert KeyPolicy({}).username is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("entry", "problem"),
|
||||
[
|
||||
({"tier": "gone"}, "serve.users.u.tier: no such tier 'gone'"),
|
||||
({"rate_limit": -1}, "serve.users.u.rate_limit"),
|
||||
({"server_cdm_max_height": "1080"}, "serve.users.u.server_cdm_max_height must be"),
|
||||
({"server_cdm_max_height": {"EXAMPLE": -1}}, "server_cdm_max_height values"),
|
||||
({"services": {"EXAMPLE": {}}}, "list of service tags"),
|
||||
],
|
||||
)
|
||||
def test_the_entry_check_names_the_first_problem(entry, problem):
|
||||
assert problem in KeyPolicy(entry, {"tiers": {"bot": {}}}).entry_error("serve.users.u")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [None, 1080, {"EXAMPLE1": 720, "default": None}])
|
||||
def test_the_entry_check_accepts_a_good_height_cap(value):
|
||||
assert KeyPolicy({"server_cdm_max_height": value, "tier": "bot"}, {"tiers": {"bot": {}}}).entry_error("u") is None
|
||||
@@ -8,6 +8,7 @@ import pytest
|
||||
from unshackle.core import remote_service
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
|
||||
@@ -106,7 +107,7 @@ async def test_client_region_splits_the_pool(pool):
|
||||
def remote_config(monkeypatch):
|
||||
monkeypatch.setattr(config, "remote_services", {"srv": {"url": "https://srv", "api_key": "k"}})
|
||||
monkeypatch.setattr(remote_service, "remote_service_list", lambda name: SERVICES)
|
||||
monkeypatch.setattr(handlers, "get_allowed_services", lambda request=None: None)
|
||||
monkeypatch.setattr(handlers, "request_policy", lambda request=None: KeyPolicy())
|
||||
|
||||
|
||||
def test_remote_server_resolves_case_and_aliases(remote_config):
|
||||
@@ -130,7 +131,7 @@ def test_remote_server_rejects(remote_config, data, code):
|
||||
|
||||
|
||||
def test_remote_server_applies_the_allowlist_and_reports_an_unreachable_server(remote_config, monkeypatch):
|
||||
monkeypatch.setattr(handlers, "get_allowed_services", lambda request=None: ["OTHER"])
|
||||
monkeypatch.setattr(handlers, "request_policy", lambda request=None: KeyPolicy({"services": ["OTHER"]}))
|
||||
with pytest.raises(APIError) as e:
|
||||
handlers.remote_server({"remote": "srv", "service": "EXAMPLE"})
|
||||
assert e.value.error_code == APIErrorCode.INVALID_SERVICE
|
||||
@@ -197,7 +198,7 @@ def test_an_unreachable_server_list_logs_one_warning(monkeypatch, caplog):
|
||||
|
||||
|
||||
def test_a_geofenced_remote_service_gets_its_first_allowed_region_as_proxy(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "server_proxy_allowed", lambda request=None: True)
|
||||
monkeypatch.setattr(handlers, "request_policy", lambda request=None: KeyPolicy({"server_proxy": True}))
|
||||
fenced = {"tag": "EXAMPLE", "geofence": ["US", "ca"], "geoblock": ["us"]}
|
||||
assert handlers.geofence_proxy({}, {"tag": "EXAMPLE", "geofence": ["US", "ca"]}) == {"proxy": "us"}
|
||||
assert handlers.geofence_proxy({}, fenced) == {"proxy": "ca"}
|
||||
@@ -205,7 +206,7 @@ def test_a_geofenced_remote_service_gets_its_first_allowed_region_as_proxy(monke
|
||||
assert handlers.geofence_proxy({"no_proxy": True}, fenced) == {}
|
||||
assert handlers.geofence_proxy({}, INFO) == {}
|
||||
|
||||
monkeypatch.setattr(handlers, "server_proxy_allowed", lambda request=None: False)
|
||||
monkeypatch.setattr(handlers, "request_policy", lambda request=None: KeyPolicy({}))
|
||||
assert handlers.geofence_proxy({}, fenced) == {}
|
||||
|
||||
|
||||
@@ -251,7 +252,7 @@ async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch):
|
||||
|
||||
login = handlers.RemoteLogin("owner", "srv", "OTHER", "show", Remote())
|
||||
monkeypatch.setattr(handlers, "_remote_logins", {login.id: login})
|
||||
monkeypatch.setattr(handlers, "is_admin", lambda request: False)
|
||||
monkeypatch.setattr(handlers, "request_policy", lambda request: KeyPolicy({}))
|
||||
caller = {"key": "owner"}
|
||||
monkeypatch.setattr(handlers, "caller_key", lambda request: caller["key"])
|
||||
got = []
|
||||
|
||||
@@ -13,7 +13,7 @@ import zlib
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api.stats import stats
|
||||
from unshackle.core.cacher import Cacher
|
||||
from unshackle.core.config import config
|
||||
@@ -59,7 +59,7 @@ def seen(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(config.directories, "cache", tmp_path)
|
||||
monkeypatch.setattr(stats, "mode", "remote_only")
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag)
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda service: {})
|
||||
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
|
||||
monkeypatch.setattr(handlers, "resolve_server_account", lambda *args: None)
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||
@@ -222,7 +222,6 @@ async def test_samples_answers_a_service_exit_in_decrypts_samples(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", get_session)
|
||||
monkeypatch.setattr(handlers, "require_authenticated", lambda s: None)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
with pytest.raises(handlers.APIError) as e:
|
||||
await handlers.session_samples_handler("sid", "t", "1", b"")
|
||||
assert e.value.error_code.value == "SERVICE_ERROR"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ def test_single_account_always_same(accounts):
|
||||
|
||||
|
||||
def test_client_managed_gets_nothing(monkeypatch, accounts):
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
|
||||
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
|
||||
@@ -86,13 +86,9 @@ def test_per_key_gate(accounts, monkeypatch):
|
||||
|
||||
monkeypatch.setattr(handlers, "request_secret_key", lambda r: r.headers["X-Secret-Key"])
|
||||
handlers.config.serve["users"] = {"k1": {}, "k2": {"server_accounts": True}, "k3": {"server_accounts": ["EX"]}}
|
||||
assert handlers.server_accounts_allowed(Req("k1"), "EX") is False
|
||||
assert handlers.server_accounts_allowed(Req("k2"), "EX") is True
|
||||
assert handlers.server_accounts_allowed(Req("k3"), "EX") is True
|
||||
assert handlers.server_accounts_allowed(Req("k3"), "SINGLE") is False
|
||||
assert handlers.server_accounts_allowed(Req("admin"), "EX") is True
|
||||
assert handlers.server_account_for(Req("k1"), "EX") is False
|
||||
assert handlers.server_account_for(Req("k2"), "OTHER") is False
|
||||
assert handlers.server_account_for(handlers.request_policy(Req("k1")), "EX") is False
|
||||
assert handlers.server_account_for(handlers.request_policy(Req("k2")), "EX") is True
|
||||
assert handlers.server_account_for(handlers.request_policy(Req("k2")), "OTHER") is False
|
||||
|
||||
|
||||
def test_rotation_per_region_pool(accounts):
|
||||
@@ -101,7 +97,7 @@ def test_rotation_per_region_pool(accounts):
|
||||
|
||||
|
||||
def test_server_account_ignores_client_credentials(monkeypatch, accounts):
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
|
||||
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
|
||||
@@ -125,7 +121,7 @@ def test_server_cdm_ignores_client_cdm_type(monkeypatch):
|
||||
"""A server_cdm tier licenses with the server's own device, so the client's CDM type must
|
||||
not swap it for a stub of the other DRM system."""
|
||||
seen = []
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda s, p, t=None, app_config=None: seen.append(t))
|
||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
|
||||
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
|
||||
@@ -155,7 +151,7 @@ def _lang_option_module():
|
||||
|
||||
|
||||
def _create_with_real_ctx(monkeypatch, data):
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
|
||||
svc, _, _ = handlers.create_service_instance("OTHER", "t", data, None, [], None)
|
||||
@@ -230,7 +226,7 @@ def test_malformed_dl_params_are_ignored(monkeypatch, dl_params):
|
||||
|
||||
|
||||
def test_profile_reaches_the_parent_ctx_params(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
|
||||
svc, _, _ = handlers.create_service_instance("OTHER", "t", {}, None, [], "work")
|
||||
|
||||
@@ -61,7 +61,6 @@ def env(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "resolve_device_name", lambda *a, **k: "dev")
|
||||
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
||||
monkeypatch.setattr(handlers, "cache_to_vaults", lambda keys, name, **_: None)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False)
|
||||
|
||||
|
||||
@@ -36,22 +36,6 @@ def request(key):
|
||||
return SimpleNamespace(headers={"X-Secret-Key": key} if key else {})
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("key", "allowed"), ENTITLEMENTS)
|
||||
def test_server_cdm_allowed(serve_users, key, allowed):
|
||||
assert handlers.server_cdm_allowed(request(key)) is allowed
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("service", "allowed"), [("EXAMPLE1", True), ("EXAMPLE2", False), (None, False)])
|
||||
def test_server_cdm_service_list(serve_users, service, allowed):
|
||||
assert handlers.server_cdm_allowed(request("tier2key"), service) is allowed
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("service", "allowed"), [("EXAMPLE1", True), ("EXAMPLE2", False)])
|
||||
def test_server_cdm_bare_tag(serve_users, service, allowed):
|
||||
# A bare tag gates one service. It must not read as a truthy value that opens every service.
|
||||
assert handlers.server_cdm_allowed(request("tier2strkey"), service) is allowed
|
||||
|
||||
|
||||
def test_download_gate_uses_job_service(serve_users):
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE1"}, request("tier2key"))
|
||||
with pytest.raises(APIError):
|
||||
@@ -87,10 +71,6 @@ async def test_retry_gate_uses_job_service(serve_users, monkeypatch, service, al
|
||||
assert ei.value.error_code == APIErrorCode.FORBIDDEN
|
||||
|
||||
|
||||
def test_no_request_allows(serve_users):
|
||||
assert handlers.server_cdm_allowed(None) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("key", "allowed"), ENTITLEMENTS)
|
||||
def test_download_gate_follows_entitlement(serve_users, key, allowed):
|
||||
# A download job licenses with the server CDM, so submission obeys the same gate.
|
||||
|
||||
@@ -140,7 +140,6 @@ async def test_batch_reports_vault_keys_from_the_init_segment_pssh(monkeypatch):
|
||||
return {KID.hex: "c"}
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", validated)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", lambda track, session=None, init_data=None: None)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine")
|
||||
@@ -188,7 +187,6 @@ async def test_batch_asks_again_when_a_cached_vault_answer_lacks_the_track_kid(m
|
||||
return {KID.hex: "v", CDM_KID.hex: "c"}
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", validated)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", lambda track, session=None, init_data=None: None)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine")
|
||||
@@ -334,7 +332,6 @@ async def test_a_stripe_cipher_track_is_clear_and_never_licensed(monkeypatch):
|
||||
return session
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", validated)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", lambda track, session=None, init_data=None: None)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine")
|
||||
|
||||
@@ -87,7 +87,6 @@ def server_env(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "resolve_device_name", lambda *a, **k: "dev")
|
||||
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
||||
monkeypatch.setattr(handlers, "cache_to_vaults", lambda keys, name, **_: None)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready")
|
||||
monkeypatch.setattr(handlers, "drm_preference_name", lambda track: None)
|
||||
|
||||
@@ -17,8 +17,9 @@ from tests.remote.key_source import CAPPED, PR_DEVICE, MemoryKeySource, one_titl
|
||||
from tests.remote.sessions import session_entry
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core import remote_channel
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
from unshackle.core.config import cdm_entry_names_device
|
||||
from unshackle.core.drm import Widevine
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
@@ -54,21 +55,6 @@ def video(height, width=None):
|
||||
return track
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("key", "service", "cap"),
|
||||
[
|
||||
("flat", "EXAMPLE1", 1080),
|
||||
("mapped", "EXAMPLE1", 720),
|
||||
("mapped", "EXAMPLE2", 1080),
|
||||
("partial", "EXAMPLE2", None),
|
||||
("open", "EXAMPLE1", None),
|
||||
("admin", "EXAMPLE1", None),
|
||||
],
|
||||
)
|
||||
def test_cap_per_key_and_service(key, service, cap):
|
||||
assert handlers.server_cdm_max_height(request(key), service) == cap
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("key", "data", "expected"),
|
||||
[
|
||||
@@ -87,35 +73,44 @@ def test_cap_per_key_and_service(key, service, cap):
|
||||
)
|
||||
def test_session_mode(key, data, expected, monkeypatch):
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: type("Svc", (), {}))
|
||||
assert handlers.choose_session_cdm(request(key), "EXAMPLE1", data) == expected
|
||||
assert handlers.choose_session_cdm(KeyPolicy(USERS[key]), "EXAMPLE1", data) == expected
|
||||
|
||||
|
||||
def test_a_server_device_option_keeps_the_server_cdm_against_the_clients_choice(monkeypatch):
|
||||
svc = type("Svc", (), {"SERVER_DEVICE_OPTIONS": ("server_side",)})
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: svc)
|
||||
data = {"cdm_type": "widevine", "server_cdm": False, "server_side": True}
|
||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", data) == (True, 1080)
|
||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", {**data, "quality": [2160]}) == (False, 1080)
|
||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", {**data, "server_side": False}) == (False, None)
|
||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", {**data, "server_side": "yes"}) == (True, 1080)
|
||||
assert handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", data) == (True, 1080)
|
||||
assert handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {**data, "quality": [2160]}) == (
|
||||
False,
|
||||
1080,
|
||||
)
|
||||
assert handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {**data, "server_side": False}) == (
|
||||
False,
|
||||
None,
|
||||
)
|
||||
assert handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {**data, "server_side": "yes"}) == (
|
||||
True,
|
||||
1080,
|
||||
)
|
||||
|
||||
nested = {"cdm_type": "widevine", "server_cdm": False, "service_params": {"server_side": True}}
|
||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", nested) == (True, 1080)
|
||||
assert handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", nested) == (True, 1080)
|
||||
# with service_params present a flat key is a dl value, as it is when the service is built
|
||||
nested["server_side"], nested["service_params"] = True, {}
|
||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", nested) == (False, None)
|
||||
assert handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", nested) == (False, None)
|
||||
|
||||
|
||||
def test_above_the_cap_without_a_device_is_refused_at_create():
|
||||
with pytest.raises(APIError) as ei:
|
||||
handlers.choose_session_cdm(request("flat"), "EXAMPLE1", {"quality": [2160]})
|
||||
handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {"quality": [2160]})
|
||||
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
|
||||
assert ei.value.details == {"reason": "server_cdm_max_height", "max_height": 1080}
|
||||
|
||||
|
||||
def test_bad_quality_is_invalid_input():
|
||||
with pytest.raises(APIError) as ei:
|
||||
handlers.choose_session_cdm(request("flat"), "EXAMPLE1", {"quality": ["best"]})
|
||||
handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {"quality": ["best"]})
|
||||
assert ei.value.error_code is APIErrorCode.INVALID_INPUT
|
||||
|
||||
|
||||
@@ -183,21 +178,6 @@ def test_download_jobs_stay_inside_the_cap(quality, allowed):
|
||||
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "ok"),
|
||||
[
|
||||
(None, True),
|
||||
(1080, True),
|
||||
({"EXAMPLE1": 720, "default": None}, True),
|
||||
(True, False),
|
||||
("1080", False),
|
||||
(-1, False),
|
||||
],
|
||||
)
|
||||
def test_config_shape(value, ok):
|
||||
assert (handlers.server_cdm_max_height_error("serve.users.x", value) is None) is ok
|
||||
|
||||
|
||||
class _WV:
|
||||
pssh = SimpleNamespace(dumps=lambda: "WV")
|
||||
|
||||
@@ -259,12 +239,6 @@ def test_a_server_vault_miss_without_the_local_drm_system_fails_at_once():
|
||||
assert "-q" not in ei.value.message
|
||||
|
||||
|
||||
def test_a_null_service_in_the_cap_map_falls_through_to_the_default(monkeypatch):
|
||||
users = {"k": {"server_cdm": True, "server_cdm_max_height": {"EXAMPLE1": None, "default": 1080}}}
|
||||
monkeypatch.setattr(handlers.config, "serve", {"users": users}, raising=False)
|
||||
assert handlers.server_cdm_max_height(request("k"), "EXAMPLE1") == 1080
|
||||
|
||||
|
||||
def test_an_ultrawide_track_is_measured_as_the_smallest_quality_that_selects_it():
|
||||
"""-q matches a height or a 16:9 width, so a track passes the cap when either one is inside it."""
|
||||
session = session_entry(server_cdm_max_height=1080)
|
||||
@@ -414,7 +388,6 @@ def licence_env(monkeypatch):
|
||||
raise refusal
|
||||
return {KID.hex: "k"}
|
||||
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", lambda track, session=None, init_data=None: None)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine")
|
||||
@@ -478,7 +451,7 @@ def test_a_client_device_session_builds_the_service_on_a_stub_of_that_device(mon
|
||||
def no_server_device(*a, **k):
|
||||
raise AssertionError("a client-device session must not load the server's device")
|
||||
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda tag: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", no_server_device)
|
||||
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm))
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: object)
|
||||
@@ -497,7 +470,6 @@ def test_the_tracks_response_echoes_the_session_choice(monkeypatch):
|
||||
from unshackle.core.api import session_store as store_mod
|
||||
from unshackle.core.tracks import Tracks
|
||||
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(store_mod.bus, "publish", lambda topic, data: None)
|
||||
|
||||
class StubService:
|
||||
|
||||
@@ -142,7 +142,6 @@ async def test_batch_shares_full_bundle_per_pssh(monkeypatch):
|
||||
return dict(bundle_a) if pssh_str == pssh_a else dict(bundle_b)
|
||||
|
||||
monkeypatch.setattr(handlers, "get_validated_session", fake_get_session)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", lambda track, session=None, init_data=None: None)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready")
|
||||
|
||||
@@ -21,8 +21,9 @@ import unshackle.core.cdm as cdm_mod
|
||||
import unshackle.core.cdm.detect as detect_mod
|
||||
import unshackle.core.drm as drm_mod
|
||||
from tests.remote.sessions import session_entry
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
from unshackle.core.cdm.choice import choose_cdm
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
@@ -92,7 +93,6 @@ def env(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", lambda track, session=None, init_data=None: None)
|
||||
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
||||
monkeypatch.setattr(handlers, "cache_to_vaults", lambda keys, name, **_: None)
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, tag: True)
|
||||
monkeypatch.setattr(handlers, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||
monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False)
|
||||
# the device name says what the device is, in place of the .wvd / .prd file on disk
|
||||
@@ -138,9 +138,8 @@ async def test_playready_only_track_licenses_with_widevine_server(env, monkeypat
|
||||
async def test_client_type_decides_without_server_mapping(env, monkeypatch):
|
||||
"""No config.cdm entry for the service: the tier's devices answer in the client's order."""
|
||||
monkeypatch.setattr(handlers.config, "cdm", {}, raising=False)
|
||||
monkeypatch.setattr(
|
||||
handlers, "serve_user_config", lambda key: {"devices": ["wv_dev"], "playready_devices": ["pr_dev"]}
|
||||
)
|
||||
tier = KeyPolicy({"server_cdm": True, "devices": ["wv_dev"], "playready_devices": ["pr_dev"]})
|
||||
monkeypatch.setattr(handlers, "request_policy", lambda request: tier)
|
||||
|
||||
track = SimpleNamespace(id="vid", drm=[_pr_drm(), _wv_drm()])
|
||||
body = await _license(monkeypatch, track, {"drm_type": "playready"})
|
||||
@@ -237,7 +236,7 @@ def test_the_server_device_follows_the_client_only_when_both_systems_are_mapped(
|
||||
):
|
||||
asked: list = []
|
||||
monkeypatch.setattr(handlers.config, "cdm", mapping, raising=False)
|
||||
monkeypatch.setattr(handlers, "load_service_config", lambda tag: {})
|
||||
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
|
||||
monkeypatch.setattr(
|
||||
handlers, "load_full_cdm", lambda service, profile, cdm_type, app_config=None: asked.append(cdm_type)
|
||||
)
|
||||
|
||||
@@ -507,8 +507,6 @@ def test_a_download_job_refuses_a_tunnel_proxy(monkeypatch: pytest.MonkeyPatch)
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api.errors import APIError
|
||||
|
||||
monkeypatch.setattr(handlers, "server_cdm_allowed", lambda request, service: True)
|
||||
monkeypatch.setattr(handlers, "server_cdm_max_height", lambda request, service: None)
|
||||
with pytest.raises(APIError, match="tunnel"):
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE", "proxy": "tunnel:abc"}, None)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user