mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-28 20:05:10 +00:00
refactor(api): answer every API key question from one KeyPolicy
This commit is contained in:
@@ -14,6 +14,7 @@ import pytest
|
|||||||
import unshackle.core.cdm as cdm_mod
|
import unshackle.core.cdm as cdm_mod
|
||||||
from unshackle.commands.dl import dl
|
from unshackle.commands.dl import dl
|
||||||
from unshackle.core.api import handlers
|
from unshackle.core.api import handlers
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy
|
||||||
from unshackle.core.cdm.choice import choose_cdm, drm_system
|
from unshackle.core.cdm.choice import choose_cdm, drm_system
|
||||||
from unshackle.core.cdm.detect import is_playready_cdm
|
from unshackle.core.cdm.detect import is_playready_cdm
|
||||||
|
|
||||||
@@ -98,7 +99,8 @@ def answers(monkeypatch: pytest.MonkeyPatch, cdm: dict, profile: str | None, key
|
|||||||
"""What every ladder answers for one config row."""
|
"""What every ladder answers for one config row."""
|
||||||
monkeypatch.setattr(handlers.config, "cdm", cdm, raising=False)
|
monkeypatch.setattr(handlers.config, "cdm", cdm, raising=False)
|
||||||
user = {**TIER, **({"cdm": key_cdm} if key_cdm else {})}
|
user = {**TIER, **({"cdm": key_cdm} if key_cdm else {})}
|
||||||
view = handlers.key_cdm_config(user)
|
policy = KeyPolicy(user)
|
||||||
|
view = policy.cdm_config()
|
||||||
cmd = dl.__new__(dl)
|
cmd = dl.__new__(dl)
|
||||||
cmd.vaults = None
|
cmd.vaults = None
|
||||||
track = SimpleNamespace(drm_preference=None)
|
track = SimpleNamespace(drm_preference=None)
|
||||||
@@ -106,10 +108,10 @@ def answers(monkeypatch: pytest.MonkeyPatch, cdm: dict, profile: str | None, key
|
|||||||
"dl": each(LOCAL, lambda s: cmd.get_cdm("EXAMPLE", profile, drm=s)),
|
"dl": each(LOCAL, lambda s: cmd.get_cdm("EXAMPLE", profile, drm=s)),
|
||||||
"load": each(LOCAL, lambda s: handlers.load_full_cdm("EXAMPLE", profile, s, view)),
|
"load": each(LOCAL, lambda s: handlers.load_full_cdm("EXAMPLE", profile, s, view)),
|
||||||
"stub": each(LOCAL, lambda s: handlers.resolve_server_cdm("EXAMPLE", profile, s, view)),
|
"stub": each(LOCAL, lambda s: handlers.resolve_server_cdm("EXAMPLE", profile, s, view)),
|
||||||
"device": each(SERVER, lambda s: handlers.resolve_device_name(user, s, "EXAMPLE")),
|
"device": each(SERVER, lambda s: handlers.resolve_device_name(policy, s, "EXAMPLE")),
|
||||||
"settled": attempt(lambda: handlers.detect_cdm_type_for_service("EXAMPLE", view)),
|
"settled": attempt(lambda: handlers.detect_cdm_type_for_service("EXAMPLE", view)),
|
||||||
"both": attempt(lambda: choose_cdm(view.cdm, "EXAMPLE").both),
|
"both": attempt(lambda: choose_cdm(view.cdm, "EXAMPLE").both),
|
||||||
"candidates": each(SERVER, lambda s: handlers.server_drm_candidates("EXAMPLE", user, s, track)),
|
"candidates": each(SERVER, lambda s: handlers.server_drm_candidates("EXAMPLE", policy, s, track)),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import zlib
|
|||||||
|
|
||||||
import pytest
|
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.errors import APIError
|
||||||
from unshackle.core.api.handlers import load_client_cookies
|
from unshackle.core.api.handlers import load_client_cookies
|
||||||
from unshackle.core.remote_protocol import APIErrorCode
|
from unshackle.core.remote_protocol import APIErrorCode
|
||||||
@@ -59,7 +59,7 @@ def built_ctx(monkeypatch):
|
|||||||
seen["ctx"] = parent_ctx
|
seen["ctx"] = parent_ctx
|
||||||
return object()
|
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, "load_full_cdm", lambda *args: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||||
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
|
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import pytest
|
|||||||
import unshackle.commands.dl as dl_module
|
import unshackle.commands.dl as dl_module
|
||||||
from tests.remote.unit.test_remote_service_helpers import _sent_create_data
|
from tests.remote.unit.test_remote_service_helpers import _sent_create_data
|
||||||
from unshackle.core import mux_step
|
from unshackle.core import mux_step
|
||||||
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.api.handlers import validate_download_parameters
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.mux_step import hybrid_plan, hybrid_source_tracks, hybrid_step_error, missing_hybrid_error
|
from unshackle.core.mux_step import hybrid_plan, hybrid_source_tracks, hybrid_step_error, missing_hybrid_error
|
||||||
@@ -837,7 +837,7 @@ def test_a_remote_session_puts_the_flag_in_the_service_ctx(monkeypatch: pytest.M
|
|||||||
seen["ctx"] = parent_ctx
|
seen["ctx"] = parent_ctx
|
||||||
return object()
|
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, "load_full_cdm", lambda *args: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||||
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
|
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ def cli_search(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> click.Context
|
|||||||
|
|
||||||
def rest_handlers(monkeypatch: pytest.MonkeyPatch) -> tuple[Any, dict]:
|
def rest_handlers(monkeypatch: pytest.MonkeyPatch) -> tuple[Any, dict]:
|
||||||
"""The handlers module with the service, its config, CDM and proxy stubbed, and the context it builds."""
|
"""The handlers module with the service, its config, CDM and proxy stubbed, and the context it builds."""
|
||||||
from unshackle.core.api import handlers
|
from unshackle.core.api import handlers, key_policy
|
||||||
|
|
||||||
seen: dict = {}
|
seen: dict = {}
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ def rest_handlers(monkeypatch: pytest.MonkeyPatch) -> tuple[Any, dict]:
|
|||||||
seen["ctx"] = parent_ctx
|
seen["ctx"] = parent_ctx
|
||||||
return SimpleNamespace(authenticate=lambda cookies, credential: None)
|
return SimpleNamespace(authenticate=lambda cookies, credential: None)
|
||||||
|
|
||||||
monkeypatch.setattr(handlers, "load_service_config", lambda tag: {})
|
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
|
||||||
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, []))
|
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, []))
|
||||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
|
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import click
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import unshackle.commands.dl as dl_module
|
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.api.handlers import validate_download_parameters
|
||||||
from unshackle.core.services import Services
|
from unshackle.core.services import Services
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ def session_params(monkeypatch: pytest.MonkeyPatch, data: dict) -> dict:
|
|||||||
seen["params"] = parent_ctx.params
|
seen["params"] = parent_ctx.params
|
||||||
return object()
|
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, "load_full_cdm", lambda *args: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||||
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
|
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from pywidevine import DeviceTypes
|
|||||||
from pywidevine.pssh import PSSH
|
from pywidevine.pssh import PSSH
|
||||||
|
|
||||||
from tests.remote.sessions import session_entry
|
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.errors import APIError
|
||||||
from unshackle.core.api.input_bridge import InputBridge
|
from unshackle.core.api.input_bridge import InputBridge
|
||||||
from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call
|
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:
|
class Declares:
|
||||||
CLIENT_CONFIG = ("esn",)
|
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(
|
monkeypatch.setattr(
|
||||||
handlers,
|
handlers,
|
||||||
"served_context",
|
"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")
|
CLIENT_CONFIG = ("esn", "esn_map")
|
||||||
|
|
||||||
monkeypatch.setattr(
|
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, "load_full_cdm", lambda *a: server_device)
|
||||||
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm, config=obj.config))
|
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
|
monkeypatch: pytest.MonkeyPatch, fields: dict, forbidden: bool
|
||||||
) -> None:
|
) -> None:
|
||||||
"""A session that the client's device licenses reaches the server licence route only for the server vault."""
|
"""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:
|
with pytest.raises(APIError) as caught:
|
||||||
handlers.license_response({"mode": "server_cdm", "track_id": "none"}, session_entry(**fields), "sess", None)
|
handlers.license_response({"mode": "server_cdm", "track_id": "none"}, session_entry(**fields), "sess", None)
|
||||||
assert (caught.value.error_code is APIErrorCode.FORBIDDEN) is forbidden
|
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:
|
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."""
|
"""KeyPolicy.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
|
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", 600) is None
|
||||||
assert rate_limit_error("serve.tiers.bot", None) 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:
|
with pytest.MonkeyPatch().context() as m:
|
||||||
m.setitem(config.serve, "tiers", {"bot": {"rate_limit": "600"}})
|
m.setitem(config.serve, "tiers", {"bot": {"rate_limit": "600"}})
|
||||||
m.setitem(config.serve, "users", {"k": {"tier": "bot"}})
|
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:
|
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"}
|
return {"00" * 16: "key"}
|
||||||
|
|
||||||
monkeypatch.setattr(handlers, "get_validated_session", fake_get_session)
|
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, "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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: cdm_type)
|
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: cdm_type)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from types import SimpleNamespace
|
|||||||
|
|
||||||
import pytest
|
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.errors import APIError
|
||||||
from unshackle.core.remote_protocol import APIErrorCode
|
from unshackle.core.remote_protocol import APIErrorCode
|
||||||
from unshackle.core.utils import ip_info
|
from unshackle.core.utils import ip_info
|
||||||
@@ -111,17 +111,6 @@ def test_no_proxy_short_circuits(monkeypatch):
|
|||||||
assert providers == []
|
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):
|
def test_opted_in_country_code_resolves(monkeypatch):
|
||||||
patch_server_region(monkeypatch, "IN")
|
patch_server_region(monkeypatch, "IN")
|
||||||
provider = patch_providers(monkeypatch, "http://us.proxy:8080")
|
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):
|
def authenticate(self, cookies, credential):
|
||||||
seen["authenticated"] = True
|
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, "resolve_handler_proxy", fake_resolve)
|
||||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda service: 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):
|
def failed_check(*args):
|
||||||
raise ConnectionError("Proxy check failed: no IP lookup got through the proxy.")
|
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, "resolve_handler_proxy", lambda *args: ("http://127.0.0.1:9", []))
|
||||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||||
@@ -219,7 +208,8 @@ class TestDownloadGates:
|
|||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def cdm_gate_open(self, monkeypatch):
|
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):
|
def test_country_code_rejected_when_denied(self, monkeypatch):
|
||||||
with pytest.raises(APIError) as exc_info:
|
with pytest.raises(APIError) as exc_info:
|
||||||
|
|||||||
@@ -8,8 +8,9 @@ from types import SimpleNamespace
|
|||||||
|
|
||||||
import pytest
|
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.errors import APIError
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy
|
||||||
from unshackle.core.api.session_store import get_session_store
|
from unshackle.core.api.session_store import get_session_store
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.remote_protocol import AuthStatus
|
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):
|
def test_a_key_entry_replaces_the_whole_server_entry(server):
|
||||||
user = {"cdm": {"example": "own_pr"}}
|
user = KeyPolicy({"cdm": {"example": "own_pr"}})
|
||||||
assert handlers.key_cdm_config(user).cdm == {"OTHER": "x", "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.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):
|
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(KeyPolicy({"cdm": {"EXAMPLE": "own"}}), "playready", "EXAMPLE") == "own"
|
||||||
assert handlers.resolve_device_name({}, "playready", "EXAMPLE") == "shared_pr"
|
assert handlers.resolve_device_name(KeyPolicy({}), "playready", "EXAMPLE") == "shared_pr"
|
||||||
|
|
||||||
|
|
||||||
def test_a_session_keeps_the_user_config_it_was_created_with(server, monkeypatch):
|
def test_a_session_keeps_the_policy_it_was_created_with(server, monkeypatch):
|
||||||
session = SimpleNamespace(user_config={"cdm": {"EXAMPLE": "pinned"}})
|
pinned, reloaded = KeyPolicy({"cdm": {"EXAMPLE": "pinned"}}), KeyPolicy({"cdm": {"EXAMPLE": "reloaded"}})
|
||||||
monkeypatch.setattr(handlers, "serve_user_config", lambda key: {"cdm": {"EXAMPLE": "reloaded"}})
|
monkeypatch.setattr(handlers, "request_policy", lambda request: reloaded)
|
||||||
assert handlers.session_user_config(session, None)["cdm"]["EXAMPLE"] == "pinned"
|
assert handlers.session_policy(SimpleNamespace(policy=pinned), None) is pinned
|
||||||
assert handlers.session_user_config(SimpleNamespace(), None)["cdm"]["EXAMPLE"] == "reloaded"
|
assert handlers.session_policy(SimpleNamespace(), None) is reloaded
|
||||||
|
|
||||||
|
|
||||||
def test_the_key_block_beats_the_server_config_and_profile_sections(server, monkeypatch):
|
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"}}
|
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)))
|
monkeypatch.setattr(key_policy, "load_service_config", lambda service: json.loads(json.dumps(base)))
|
||||||
user = {"service_config": {"example": {"device_id": "key", "device_key": "key"}}}
|
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["device_id"] == merged["device_key"] == "key"
|
||||||
assert merged["p1"] == {"device_id": "key", "other": 1}
|
assert merged["p1"] == {"device_id": "key", "other": 1}
|
||||||
assert merged["urls"] == {"a": "b"}
|
assert merged["urls"] == {"a": "b"}
|
||||||
assert handlers.key_service_yaml("EXAMPLE", {})["device_id"] == "server"
|
assert KeyPolicy({}).service_yaml("EXAMPLE")["device_id"] == "server"
|
||||||
assert handlers.key_owns_identity(user, "EXAMPLE") and not handlers.key_owns_identity(user, "OTHER")
|
assert user.owns_identity("EXAMPLE") and not user.owns_identity("OTHER")
|
||||||
|
|
||||||
|
|
||||||
class _Service:
|
class _Service:
|
||||||
@@ -61,13 +62,13 @@ class _Service:
|
|||||||
|
|
||||||
|
|
||||||
def test_identity_keys_live_in_the_api_key_directory_and_never_reach_the_client(server):
|
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("keys/device1").set("keys")
|
||||||
cache.get("tokens").set("login")
|
cache.get("tokens").set("login")
|
||||||
|
|
||||||
assert set(handlers.collect_cache_files("_s")) == {"tokens"}
|
assert set(handlers.collect_cache_files("_s")) == {"tokens"}
|
||||||
assert list((server / "_identity").rglob("device1.json"))
|
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")
|
text = base64.b64encode(zlib.compress(b'{"data": "planted"}')).decode("ascii")
|
||||||
handlers.write_client_cache({"keys/device1": text}, "_s")
|
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):
|
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"}}}
|
own = KeyPolicy({"service_config": {"EXAMPLE": {"device_id": "key"}}})
|
||||||
assert handlers.keyed_cache("_accounts/EXAMPLE/p", _Service(), "EXAMPLE", "k", {}).route is None
|
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("_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
|
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):
|
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(
|
||||||
monkeypatch.setattr(handlers, "server_cdm_max_height", lambda request, service: None)
|
handlers, "request_policy", lambda request: KeyPolicy({"server_cdm": True, "cdm": {"EXAMPLE": "own"}})
|
||||||
monkeypatch.setattr(handlers, "serve_user_config", lambda key: {"cdm": {"EXAMPLE": "own"}})
|
)
|
||||||
with pytest.raises(APIError, match="its own"):
|
with pytest.raises(APIError, match="its own"):
|
||||||
handlers.enforce_download_gates({"service": "EXAMPLE"})
|
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):
|
def test_bad_key_config_is_refused_at_load(server, monkeypatch, user_cfg, problem):
|
||||||
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
|
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):
|
def test_a_known_device_passes_validation(server, monkeypatch):
|
||||||
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
|
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
|
||||||
monkeypatch.setattr(handlers, "device_system", lambda name, cfg: "playready")
|
monkeypatch.setattr(key_policy, "device_system", lambda name, cfg: "playready")
|
||||||
assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"playready": "dev"}}, "service_config": {}}) is None
|
assert KeyPolicy({"cdm": {"EXAMPLE": {"playready": "dev"}}, "service_config": {}}).entry_error("u") is None
|
||||||
assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"default": "dev"}}, "service_config": None}) is None
|
assert KeyPolicy({"cdm": {"EXAMPLE": {"default": "dev"}}, "service_config": None}).entry_error("u") is None
|
||||||
assert handlers.key_config_error("u", {"cdm": {"EXAMPLE": {"widevine": "dev"}}}) is not None
|
assert KeyPolicy({"cdm": {"EXAMPLE": {"widevine": "dev"}}}).entry_error("u") is not None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@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("keys/device1").set("identity")
|
||||||
self.cache.get("tokens").set("login")
|
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")
|
text = base64.b64encode(zlib.compress(b'{"data": "x"}')).decode("ascii")
|
||||||
monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
|
monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
|
||||||
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
|
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
|
||||||
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
|
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, "choose_session_cdm", lambda *args: (server_cdm, None))
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
|
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
|
||||||
monkeypatch.setattr(handlers, "create_service_instance", lambda *args, **kwargs: (Service(), None, None))
|
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())
|
session, sent_back = asyncio.run(run())
|
||||||
|
|
||||||
assert session.user_config is user
|
assert session.policy is user
|
||||||
assert sent_back == returned
|
assert sent_back == returned
|
||||||
|
|
||||||
|
|
||||||
def test_a_reload_checks_key_devices_against_the_new_config(server, monkeypatch):
|
def test_a_reload_checks_key_devices_against_the_new_config(server, monkeypatch):
|
||||||
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
|
monkeypatch.setattr(handlers.Services, "get_tags", staticmethod(lambda: ["EXAMPLE"]))
|
||||||
fresh = SimpleNamespace(remote_cdm=[{"name": "new_remote", "device_type": "PLAYREADY"}])
|
fresh = SimpleNamespace(remote_cdm=[{"name": "new_remote", "device_type": "PLAYREADY"}])
|
||||||
user = {"cdm": {"EXAMPLE": "new_remote"}}
|
user = KeyPolicy({"cdm": {"EXAMPLE": "new_remote"}})
|
||||||
assert handlers.key_config_error("u", user, fresh) is None
|
assert user.entry_error("u", fresh) is None
|
||||||
assert handlers.key_config_error("u", user) is not None
|
assert user.entry_error("u") is not None
|
||||||
|
|
||||||
|
|
||||||
def test_a_block_value_reaches_only_plain_values_of_other_sections(server, monkeypatch):
|
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"}
|
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}}
|
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["p1"] == {"device_id": "key", "headers": {"a": "b"}}
|
||||||
assert merged["device_key"] == {"nested": 1}
|
assert merged["device_key"] == {"nested": 1}
|
||||||
|
|
||||||
|
|
||||||
def test_a_removed_key_loses_its_identity_cache(server):
|
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", "gone", KeyPolicy(), 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", "kept", KeyPolicy(), True).get("keys/device1").set("keys")
|
||||||
handlers.drop_identity_cache({"gone"})
|
handlers.drop_identity_cache({"gone"})
|
||||||
assert not (server / "_identity" / handlers.key_namespace("gone")).exists()
|
assert not (server / "_identity" / handlers.key_namespace("gone")).exists()
|
||||||
assert (server / "_identity" / handlers.key_namespace("kept")).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 import remote_service
|
||||||
from unshackle.core.api import handlers
|
from unshackle.core.api import handlers
|
||||||
from unshackle.core.api.errors import APIError
|
from unshackle.core.api.errors import APIError
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.remote_protocol import APIErrorCode
|
from unshackle.core.remote_protocol import APIErrorCode
|
||||||
|
|
||||||
@@ -106,7 +107,7 @@ async def test_client_region_splits_the_pool(pool):
|
|||||||
def remote_config(monkeypatch):
|
def remote_config(monkeypatch):
|
||||||
monkeypatch.setattr(config, "remote_services", {"srv": {"url": "https://srv", "api_key": "k"}})
|
monkeypatch.setattr(config, "remote_services", {"srv": {"url": "https://srv", "api_key": "k"}})
|
||||||
monkeypatch.setattr(remote_service, "remote_service_list", lambda name: SERVICES)
|
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):
|
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):
|
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:
|
with pytest.raises(APIError) as e:
|
||||||
handlers.remote_server({"remote": "srv", "service": "EXAMPLE"})
|
handlers.remote_server({"remote": "srv", "service": "EXAMPLE"})
|
||||||
assert e.value.error_code == APIErrorCode.INVALID_SERVICE
|
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):
|
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"]}
|
fenced = {"tag": "EXAMPLE", "geofence": ["US", "ca"], "geoblock": ["us"]}
|
||||||
assert handlers.geofence_proxy({}, {"tag": "EXAMPLE", "geofence": ["US", "ca"]}) == {"proxy": "us"}
|
assert handlers.geofence_proxy({}, {"tag": "EXAMPLE", "geofence": ["US", "ca"]}) == {"proxy": "us"}
|
||||||
assert handlers.geofence_proxy({}, fenced) == {"proxy": "ca"}
|
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({"no_proxy": True}, fenced) == {}
|
||||||
assert handlers.geofence_proxy({}, INFO) == {}
|
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) == {}
|
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())
|
login = handlers.RemoteLogin("owner", "srv", "OTHER", "show", Remote())
|
||||||
monkeypatch.setattr(handlers, "_remote_logins", {login.id: login})
|
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"}
|
caller = {"key": "owner"}
|
||||||
monkeypatch.setattr(handlers, "caller_key", lambda request: caller["key"])
|
monkeypatch.setattr(handlers, "caller_key", lambda request: caller["key"])
|
||||||
got = []
|
got = []
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import zlib
|
|||||||
import click
|
import click
|
||||||
import pytest
|
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.api.stats import stats
|
||||||
from unshackle.core.cacher import Cacher
|
from unshackle.core.cacher import Cacher
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
@@ -59,7 +59,7 @@ def seen(tmp_path, monkeypatch):
|
|||||||
monkeypatch.setattr(config.directories, "cache", tmp_path)
|
monkeypatch.setattr(config.directories, "cache", tmp_path)
|
||||||
monkeypatch.setattr(stats, "mode", "remote_only")
|
monkeypatch.setattr(stats, "mode", "remote_only")
|
||||||
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag)
|
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_handler_proxy", lambda *args: (None, []))
|
||||||
monkeypatch.setattr(handlers, "resolve_server_account", lambda *args: None)
|
monkeypatch.setattr(handlers, "resolve_server_account", lambda *args: None)
|
||||||
monkeypatch.setattr(handlers, "load_full_cdm", 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, "get_validated_session", get_session)
|
||||||
monkeypatch.setattr(handlers, "require_authenticated", lambda s: None)
|
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:
|
with pytest.raises(handlers.APIError) as e:
|
||||||
await handlers.session_samples_handler("sid", "t", "1", b"")
|
await handlers.session_samples_handler("sid", "t", "1", b"")
|
||||||
assert e.value.error_code.value == "SERVICE_ERROR"
|
assert e.value.error_code.value == "SERVICE_ERROR"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import pytest
|
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.errors import APIError
|
||||||
|
|
||||||
|
|
||||||
@@ -71,7 +71,7 @@ def test_single_account_always_same(accounts):
|
|||||||
|
|
||||||
|
|
||||||
def test_client_managed_gets_nothing(monkeypatch, 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, "load_full_cdm", lambda *a: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
|
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
|
||||||
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
|
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"])
|
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"]}}
|
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_account_for(handlers.request_policy(Req("k1")), "EX") is False
|
||||||
assert handlers.server_accounts_allowed(Req("k2"), "EX") is True
|
assert handlers.server_account_for(handlers.request_policy(Req("k2")), "EX") is True
|
||||||
assert handlers.server_accounts_allowed(Req("k3"), "EX") is True
|
assert handlers.server_account_for(handlers.request_policy(Req("k2")), "OTHER") is False
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def test_rotation_per_region_pool(accounts):
|
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):
|
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, "load_full_cdm", lambda *a: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
|
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
|
||||||
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
|
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
|
"""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."""
|
not swap it for a stub of the other DRM system."""
|
||||||
seen = []
|
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, "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.Services, "load", staticmethod(lambda s: object()))
|
||||||
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
|
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
|
||||||
@@ -155,7 +151,7 @@ def _lang_option_module():
|
|||||||
|
|
||||||
|
|
||||||
def _create_with_real_ctx(monkeypatch, data):
|
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, "load_full_cdm", lambda *a: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
|
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
|
||||||
svc, _, _ = handlers.create_service_instance("OTHER", "t", data, None, [], None)
|
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):
|
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, "load_full_cdm", lambda *a: None)
|
||||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
|
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
|
||||||
svc, _, _ = handlers.create_service_instance("OTHER", "t", {}, None, [], "work")
|
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, "resolve_device_name", lambda *a, **k: "dev")
|
||||||
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
||||||
monkeypatch.setattr(handlers, "cache_to_vaults", lambda keys, 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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False)
|
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 {})
|
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):
|
def test_download_gate_uses_job_service(serve_users):
|
||||||
handlers.enforce_download_gates({"service": "EXAMPLE1"}, request("tier2key"))
|
handlers.enforce_download_gates({"service": "EXAMPLE1"}, request("tier2key"))
|
||||||
with pytest.raises(APIError):
|
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
|
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)
|
@pytest.mark.parametrize(("key", "allowed"), ENTITLEMENTS)
|
||||||
def test_download_gate_follows_entitlement(serve_users, key, allowed):
|
def test_download_gate_follows_entitlement(serve_users, key, allowed):
|
||||||
# A download job licenses with the server CDM, so submission obeys the same gate.
|
# 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"}
|
return {KID.hex: "c"}
|
||||||
|
|
||||||
monkeypatch.setattr(handlers, "get_validated_session", validated)
|
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, "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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine")
|
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"}
|
return {KID.hex: "v", CDM_KID.hex: "c"}
|
||||||
|
|
||||||
monkeypatch.setattr(handlers, "get_validated_session", validated)
|
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, "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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine")
|
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
|
return session
|
||||||
|
|
||||||
monkeypatch.setattr(handlers, "get_validated_session", validated)
|
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, "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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine")
|
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, "resolve_device_name", lambda *a, **k: "dev")
|
||||||
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
||||||
monkeypatch.setattr(handlers, "cache_to_vaults", lambda keys, 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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready")
|
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready")
|
||||||
monkeypatch.setattr(handlers, "drm_preference_name", lambda track: None)
|
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 tests.remote.sessions import session_entry
|
||||||
from unshackle.commands.dl import dl
|
from unshackle.commands.dl import dl
|
||||||
from unshackle.core import remote_channel
|
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.errors import APIError
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy
|
||||||
from unshackle.core.config import cdm_entry_names_device
|
from unshackle.core.config import cdm_entry_names_device
|
||||||
from unshackle.core.drm import Widevine
|
from unshackle.core.drm import Widevine
|
||||||
from unshackle.core.remote_protocol import APIErrorCode
|
from unshackle.core.remote_protocol import APIErrorCode
|
||||||
@@ -54,21 +55,6 @@ def video(height, width=None):
|
|||||||
return track
|
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(
|
@pytest.mark.parametrize(
|
||||||
("key", "data", "expected"),
|
("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):
|
def test_session_mode(key, data, expected, monkeypatch):
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: type("Svc", (), {}))
|
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):
|
def test_a_server_device_option_keeps_the_server_cdm_against_the_clients_choice(monkeypatch):
|
||||||
svc = type("Svc", (), {"SERVER_DEVICE_OPTIONS": ("server_side",)})
|
svc = type("Svc", (), {"SERVER_DEVICE_OPTIONS": ("server_side",)})
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: svc)
|
monkeypatch.setattr(handlers.Services, "load", lambda tag: svc)
|
||||||
data = {"cdm_type": "widevine", "server_cdm": False, "server_side": True}
|
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(KeyPolicy(USERS["flat"]), "EXAMPLE1", data) == (True, 1080)
|
||||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", {**data, "quality": [2160]}) == (False, 1080)
|
assert handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {**data, "quality": [2160]}) == (
|
||||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", {**data, "server_side": False}) == (False, None)
|
False,
|
||||||
assert handlers.choose_session_cdm(request("flat"), "EXAMPLE1", {**data, "server_side": "yes"}) == (True, 1080)
|
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}}
|
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
|
# 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, {}
|
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():
|
def test_above_the_cap_without_a_device_is_refused_at_create():
|
||||||
with pytest.raises(APIError) as ei:
|
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.error_code is APIErrorCode.SERVER_CDM_CAPPED
|
||||||
assert ei.value.details == {"reason": "server_cdm_max_height", "max_height": 1080}
|
assert ei.value.details == {"reason": "server_cdm_max_height", "max_height": 1080}
|
||||||
|
|
||||||
|
|
||||||
def test_bad_quality_is_invalid_input():
|
def test_bad_quality_is_invalid_input():
|
||||||
with pytest.raises(APIError) as ei:
|
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
|
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
|
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:
|
class _WV:
|
||||||
pssh = SimpleNamespace(dumps=lambda: "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
|
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():
|
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."""
|
"""-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)
|
session = session_entry(server_cdm_max_height=1080)
|
||||||
@@ -414,7 +388,6 @@ def licence_env(monkeypatch):
|
|||||||
raise refusal
|
raise refusal
|
||||||
return {KID.hex: "k"}
|
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, "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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "widevine")
|
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):
|
def no_server_device(*a, **k):
|
||||||
raise AssertionError("a client-device session must not load the server's device")
|
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, "load_full_cdm", no_server_device)
|
||||||
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm))
|
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm))
|
||||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: object)
|
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.api import session_store as store_mod
|
||||||
from unshackle.core.tracks import Tracks
|
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)
|
monkeypatch.setattr(store_mod.bus, "publish", lambda topic, data: None)
|
||||||
|
|
||||||
class StubService:
|
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)
|
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, "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, "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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready")
|
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.cdm.detect as detect_mod
|
||||||
import unshackle.core.drm as drm_mod
|
import unshackle.core.drm as drm_mod
|
||||||
from tests.remote.sessions import session_entry
|
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.errors import APIError
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy
|
||||||
from unshackle.core.cdm.choice import choose_cdm
|
from unshackle.core.cdm.choice import choose_cdm
|
||||||
|
|
||||||
pytestmark = pytest.mark.unit
|
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, "ensure_track_drm", lambda track, session=None, init_data=None: None)
|
||||||
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
monkeypatch.setattr(handlers, "check_vaults", lambda kids, name, **_: None)
|
||||||
monkeypatch.setattr(handlers, "cache_to_vaults", lambda keys, 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, "find_title_for_track", lambda tid, session: SimpleNamespace())
|
||||||
monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False)
|
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
|
# 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):
|
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."""
|
"""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.config, "cdm", {}, raising=False)
|
||||||
monkeypatch.setattr(
|
tier = KeyPolicy({"server_cdm": True, "devices": ["wv_dev"], "playready_devices": ["pr_dev"]})
|
||||||
handlers, "serve_user_config", lambda key: {"devices": ["wv_dev"], "playready_devices": ["pr_dev"]}
|
monkeypatch.setattr(handlers, "request_policy", lambda request: tier)
|
||||||
)
|
|
||||||
|
|
||||||
track = SimpleNamespace(id="vid", drm=[_pr_drm(), _wv_drm()])
|
track = SimpleNamespace(id="vid", drm=[_pr_drm(), _wv_drm()])
|
||||||
body = await _license(monkeypatch, track, {"drm_type": "playready"})
|
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 = []
|
asked: list = []
|
||||||
monkeypatch.setattr(handlers.config, "cdm", mapping, raising=False)
|
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(
|
monkeypatch.setattr(
|
||||||
handlers, "load_full_cdm", lambda service, profile, cdm_type, app_config=None: asked.append(cdm_type)
|
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 import handlers
|
||||||
from unshackle.core.api.errors import APIError
|
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"):
|
with pytest.raises(APIError, match="tunnel"):
|
||||||
handlers.enforce_download_gates({"service": "EXAMPLE", "proxy": "tunnel:abc"}, None)
|
handlers.enforce_download_gates({"service": "EXAMPLE", "proxy": "tunnel:abc"}, None)
|
||||||
|
|
||||||
|
|||||||
@@ -260,20 +260,6 @@ def test_download_rejects_path_profile_and_bad_output_dir(tmp_path, monkeypatch)
|
|||||||
assert validate_download_parameters({"output_dir": "a\x00b"})
|
assert validate_download_parameters({"output_dir": "a\x00b"})
|
||||||
|
|
||||||
|
|
||||||
def test_absent_key_keeps_server_devices(monkeypatch):
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from unshackle.core.api.handlers import config, serve_user_config
|
|
||||||
|
|
||||||
monkeypatch.setattr(
|
|
||||||
config,
|
|
||||||
"serve",
|
|
||||||
{"users": {"k1": {"devices": ["mine"]}}, "devices": [Path("/x/dev.wvd")], "playready_devices": []},
|
|
||||||
)
|
|
||||||
assert serve_user_config("k1") == {"devices": ["mine"]}
|
|
||||||
assert serve_user_config("admin-secret") == {"devices": ["dev"], "playready_devices": []}
|
|
||||||
|
|
||||||
|
|
||||||
def test_safe_inflate_rejects_non_str_via_isinstance():
|
def test_safe_inflate_rejects_non_str_via_isinstance():
|
||||||
# A non-string cache value must be caught before base64.b64decode raises a 500.
|
# A non-string cache value must be caught before base64.b64decode raises a 500.
|
||||||
# Mirror the guard used in session_create_handler.
|
# Mirror the guard used in session_create_handler.
|
||||||
|
|||||||
@@ -27,18 +27,15 @@ from unshackle.core.api.handlers import (
|
|||||||
dashboard_authentication,
|
dashboard_authentication,
|
||||||
dashboard_key,
|
dashboard_key,
|
||||||
drop_identity_cache,
|
drop_identity_cache,
|
||||||
key_config_error,
|
|
||||||
rate_limit_response,
|
rate_limit_response,
|
||||||
request_secret_key,
|
request_secret_key,
|
||||||
server_account_regions,
|
server_account_regions,
|
||||||
server_cdm_max_height_error,
|
|
||||||
validate_server_accounts,
|
validate_server_accounts,
|
||||||
)
|
)
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy, api_keys, rate_limit_error
|
||||||
from unshackle.core.api.stats import (
|
from unshackle.core.api.stats import (
|
||||||
cdm_log_middleware,
|
cdm_log_middleware,
|
||||||
key_id,
|
key_id,
|
||||||
key_rate_limit,
|
|
||||||
rate_limit_error,
|
|
||||||
ring,
|
ring,
|
||||||
stats,
|
stats,
|
||||||
stats_middleware,
|
stats_middleware,
|
||||||
@@ -173,22 +170,14 @@ def _prepare_serve(serve: dict, no_key: bool, app_config: Any = None) -> str | N
|
|||||||
raise ValueError(f"serve.tiers.{tier_name} must be a mapping of setting to value")
|
raise ValueError(f"serve.tiers.{tier_name} must be a mapping of setting to value")
|
||||||
if problem := rate_limit_error(f"serve.tiers.{tier_name}", tier_cfg.get("rate_limit")):
|
if problem := rate_limit_error(f"serve.tiers.{tier_name}", tier_cfg.get("rate_limit")):
|
||||||
raise ValueError(problem)
|
raise ValueError(problem)
|
||||||
for user_key, user_cfg in users.items() if isinstance(users, dict) else []:
|
for user_key in api_keys(serve):
|
||||||
user_services = user_cfg.get("services") if isinstance(user_cfg, dict) else None
|
policy = KeyPolicy.of(user_key, serve)
|
||||||
username = user_cfg.get("username", user_key[:8] + "...") if isinstance(user_cfg, dict) else user_key[:8]
|
username = policy.username or user_key[:8] + "..."
|
||||||
if user_services:
|
if user_services := (policy.entry or {}).get("services"):
|
||||||
log.info(f"User '{username}' restricted to services: {', '.join(user_services)}")
|
log.info(f"User '{username}' restricted to services: {', '.join(user_services)}")
|
||||||
tier = user_cfg.get("tier") if isinstance(user_cfg, dict) else None
|
if problem := policy.entry_error(f"serve.users.{username}", app_config):
|
||||||
if tier and tier not in tiers:
|
raise ValueError(problem)
|
||||||
raise ValueError(f"serve.users.{username}.tier: no such tier '{tier}' under serve.tiers")
|
limit = policy.rate_limit
|
||||||
if isinstance(user_cfg, dict):
|
|
||||||
if problem := rate_limit_error(f"serve.users.{username}", user_cfg.get("rate_limit")):
|
|
||||||
raise ValueError(problem)
|
|
||||||
if problem := server_cdm_max_height_error(f"serve.users.{username}", user_cfg.get("server_cdm_max_height")):
|
|
||||||
raise ValueError(problem)
|
|
||||||
if problem := key_config_error(f"serve.users.{username}", user_cfg, app_config):
|
|
||||||
raise ValueError(problem)
|
|
||||||
limit = key_rate_limit(user_key, serve)
|
|
||||||
if limit:
|
if limit:
|
||||||
log.info(f"User '{username}' rate limited to {limit} requests/hour")
|
log.info(f"User '{username}' rate limited to {limit} requests/hour")
|
||||||
return api_secret
|
return api_secret
|
||||||
|
|||||||
+112
-369
@@ -1,6 +1,5 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import base64
|
import base64
|
||||||
import copy
|
|
||||||
import functools
|
import functools
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -28,6 +27,7 @@ from unshackle.core import login
|
|||||||
from unshackle.core.api.compression import safe_inflate
|
from unshackle.core.api.compression import safe_inflate
|
||||||
from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception
|
from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception
|
||||||
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
|
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy, api_keys, is_whole_number, named_services
|
||||||
from unshackle.core.api.progress import track_log_label
|
from unshackle.core.api.progress import track_log_label
|
||||||
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload, sanitize_log
|
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload, sanitize_log
|
||||||
from unshackle.core.api.session_channel import status_message
|
from unshackle.core.api.session_channel import status_message
|
||||||
@@ -45,7 +45,7 @@ from unshackle.core.dl_options import (
|
|||||||
forwarded_dl_params,
|
forwarded_dl_params,
|
||||||
)
|
)
|
||||||
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids
|
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids
|
||||||
from unshackle.core.launch import load_service_config, served_context
|
from unshackle.core.launch import served_context
|
||||||
from unshackle.core.manifests.snapshot import capture
|
from unshackle.core.manifests.snapshot import capture
|
||||||
from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy
|
from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy
|
||||||
from unshackle.core.remote_protocol import (
|
from unshackle.core.remote_protocol import (
|
||||||
@@ -86,7 +86,7 @@ from unshackle.core.tunnel import (
|
|||||||
)
|
)
|
||||||
from unshackle.core.utilities import declared_kwargs
|
from unshackle.core.utilities import declared_kwargs
|
||||||
from unshackle.core.utils.click_types import QUALITY_LIST, SEASON_RANGE, VIDEO_CODEC_LIST, ContextData
|
from unshackle.core.utils.click_types import QUALITY_LIST, SEASON_RANGE, VIDEO_CODEC_LIST, ContextData
|
||||||
from unshackle.core.utils.collections import ci_get, merge_dict
|
from unshackle.core.utils.collections import ci_get
|
||||||
from unshackle.core.utils.hdr10plus import probed_tracks
|
from unshackle.core.utils.hdr10plus import probed_tracks
|
||||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text
|
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text
|
||||||
from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options
|
from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options
|
||||||
@@ -128,7 +128,7 @@ def load_full_cdm(service: str, profile: str | None, cdm_type: str | None = None
|
|||||||
for list_titles / list_tracks / search. :func:`choose_cdm` picks the device as for
|
for list_titles / list_tracks / search. :func:`choose_cdm` picks the device as for
|
||||||
``dl.get_cdm``, without the quality tiers (no track context yet). It falls back to the stub
|
``dl.get_cdm``, without the quality tiers (no track context yet). It falls back to the stub
|
||||||
if the configuration has no device, or if loading fails. ``app_config`` is an API key's
|
if the configuration has no device, or if loading fails. ``app_config`` is an API key's
|
||||||
view from :func:`key_cdm_config`; None reads the server's own ``cdm``.
|
view from :meth:`KeyPolicy.cdm_config`; None reads the server's own ``cdm``.
|
||||||
"""
|
"""
|
||||||
from unshackle.core.cdm import load_cdm
|
from unshackle.core.cdm import load_cdm
|
||||||
|
|
||||||
@@ -311,7 +311,7 @@ class RequestCache:
|
|||||||
normalized_service: str,
|
normalized_service: str,
|
||||||
request: web.Request | None,
|
request: web.Request | None,
|
||||||
client_login: bool,
|
client_login: bool,
|
||||||
user_config: dict[str, Any],
|
policy: KeyPolicy,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Give the service a new cache directory, seeded from the client's ``cache``.
|
"""Give the service a new cache directory, seeded from the client's ``cache``.
|
||||||
|
|
||||||
@@ -324,11 +324,11 @@ class RequestCache:
|
|||||||
api_key = caller_key(request)
|
api_key = caller_key(request)
|
||||||
if stats.mode != "remote_only":
|
if stats.mode != "remote_only":
|
||||||
tag = service_instance.cache.service_tag
|
tag = service_instance.cache.service_tag
|
||||||
service_instance.cache = keyed_cache(tag, service_instance, normalized_service, api_key, user_config)
|
service_instance.cache = keyed_cache(tag, service_instance, normalized_service, api_key, policy)
|
||||||
return
|
return
|
||||||
self.tag = f"_requests/{key_namespace(api_key)}/{uuid.uuid4()}/{normalized_service}"
|
self.tag = f"_requests/{key_namespace(api_key)}/{uuid.uuid4()}/{normalized_service}"
|
||||||
service_instance.cache = keyed_cache(
|
service_instance.cache = keyed_cache(
|
||||||
self.tag, service_instance, normalized_service, api_key, user_config, temporary=True
|
self.tag, service_instance, normalized_service, api_key, policy, temporary=True
|
||||||
)
|
)
|
||||||
cache_data = data.get("cache")
|
cache_data = data.get("cache")
|
||||||
if cache_data:
|
if cache_data:
|
||||||
@@ -372,7 +372,7 @@ def remote_server(data: dict[str, Any], request: web.Request | None = None) -> t
|
|||||||
return None
|
return None
|
||||||
service = data.get("service")
|
service = data.get("service")
|
||||||
info = find_remote_service(remote_list(name), str(service or ""))
|
info = find_remote_service(remote_list(name), str(service or ""))
|
||||||
allowed = get_allowed_services(request)
|
allowed = request_policy(request).services
|
||||||
if info is None or (allowed is not None and info["tag"] not in allowed):
|
if info is None or (allowed is not None and info["tag"] not in allowed):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
APIErrorCode.INVALID_SERVICE,
|
APIErrorCode.INVALID_SERVICE,
|
||||||
@@ -387,7 +387,7 @@ def geofence_proxy(data: dict[str, Any], info: dict, request: web.Request | None
|
|||||||
|
|
||||||
The remote counterpart of a local service's geofence auto-proxy, under the same ``server_proxy`` gate.
|
The remote counterpart of a local service's geofence auto-proxy, under the same ``server_proxy`` gate.
|
||||||
"""
|
"""
|
||||||
if data.get("proxy") or data.get("no_proxy") or not server_proxy_allowed(request):
|
if data.get("proxy") or data.get("no_proxy") or not request_policy(request).allows("server_proxy"):
|
||||||
return {}
|
return {}
|
||||||
blocked = {str(r).lower() for r in info.get("geoblock") or []}
|
blocked = {str(r).lower() for r in info.get("geoblock") or []}
|
||||||
fence = [str(r).lower() for r in info.get("geofence") or [] if r and str(r).lower() not in blocked]
|
fence = [str(r).lower() for r in info.get("geofence") or [] if r and str(r).lower() not in blocked]
|
||||||
@@ -483,7 +483,7 @@ _remote_logins: dict[str, RemoteLogin] = {}
|
|||||||
|
|
||||||
async def remote_logins_handler(request: web.Request) -> web.Response:
|
async def remote_logins_handler(request: web.Request) -> web.Response:
|
||||||
"""Answer the request for the caller's remote logins in progress, each with its prompt and notice."""
|
"""Answer the request for the caller's remote logins in progress, each with its prompt and notice."""
|
||||||
owner, admin = caller_key(request), is_admin(request)
|
owner, admin = caller_key(request), request_policy(request).admin
|
||||||
logins = [
|
logins = [
|
||||||
{
|
{
|
||||||
"id": login.id,
|
"id": login.id,
|
||||||
@@ -502,7 +502,7 @@ async def remote_logins_handler(request: web.Request) -> web.Response:
|
|||||||
async def remote_login_input_handler(login_id: str, data: dict[str, Any], request: web.Request) -> web.Response:
|
async def remote_login_input_handler(login_id: str, data: dict[str, Any], request: web.Request) -> web.Response:
|
||||||
"""Answer the prompt (an OTP, a PIN) a remote login a list call waits on is asking."""
|
"""Answer the prompt (an OTP, a PIN) a remote login a list call waits on is asking."""
|
||||||
login = _remote_logins.get(login_id)
|
login = _remote_logins.get(login_id)
|
||||||
if login is None or not (is_admin(request) or login.owner == caller_key(request)):
|
if login is None or not (request_policy(request).admin or login.owner == caller_key(request)):
|
||||||
raise APIError(APIErrorCode.NOT_FOUND, "Remote login not found", details={"login_id": login_id})
|
raise APIError(APIErrorCode.NOT_FOUND, "Remote login not found", details={"login_id": login_id})
|
||||||
response = data.get("response")
|
response = data.get("response")
|
||||||
if response is None:
|
if response is None:
|
||||||
@@ -711,17 +711,17 @@ def setup_list_service(
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
api_key = caller_key(request)
|
api_key = caller_key(request)
|
||||||
user_config = serve_user_config(api_key)
|
policy = request_policy(request)
|
||||||
service_config = key_service_yaml(normalized_service, user_config)
|
service_config = policy.service_yaml(normalized_service)
|
||||||
|
|
||||||
no_proxy = data.get("no_proxy", False)
|
no_proxy = data.get("no_proxy", False)
|
||||||
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
|
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
|
||||||
|
|
||||||
account = resolve_server_account(request, normalized_service, data.get("client_region"))
|
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
|
||||||
if account:
|
if account:
|
||||||
profile = None if account == "default" else account
|
profile = None if account == "default" else account
|
||||||
|
|
||||||
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type"), key_cdm_config(user_config))
|
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type"), policy.cdm_config())
|
||||||
cookies, credential = server_login_material(data, normalized_service, account, profile)
|
cookies, credential = server_login_material(data, normalized_service, account, profile)
|
||||||
|
|
||||||
parent_ctx = served_context(
|
parent_ctx = served_context(
|
||||||
@@ -734,10 +734,10 @@ def setup_list_service(
|
|||||||
|
|
||||||
if account:
|
if account:
|
||||||
account_tag = f"_accounts/{normalized_service}/{account}"
|
account_tag = f"_accounts/{normalized_service}/{account}"
|
||||||
service_instance.cache = keyed_cache(account_tag, service_instance, normalized_service, api_key, user_config)
|
service_instance.cache = keyed_cache(account_tag, service_instance, normalized_service, api_key, policy)
|
||||||
elif request_cache is not None:
|
elif request_cache is not None:
|
||||||
client_login = cookies is not None or credential is not None
|
client_login = cookies is not None or credential is not None
|
||||||
request_cache.attach(service_instance, data, normalized_service, request, client_login, user_config)
|
request_cache.attach(service_instance, data, normalized_service, request, client_login, policy)
|
||||||
service_instance._input_bridge = NoUserBridge()
|
service_instance._input_bridge = NoUserBridge()
|
||||||
service_instance.authenticate(cookies, credential)
|
service_instance.authenticate(cookies, credential)
|
||||||
return service_instance
|
return service_instance
|
||||||
@@ -763,15 +763,15 @@ def run_service_search(
|
|||||||
no_proxy = data.get("no_proxy", False)
|
no_proxy = data.get("no_proxy", False)
|
||||||
|
|
||||||
api_key = caller_key(request)
|
api_key = caller_key(request)
|
||||||
user_config = serve_user_config(api_key)
|
policy = request_policy(request)
|
||||||
service_config = key_service_yaml(normalized_service, user_config)
|
service_config = policy.service_yaml(normalized_service)
|
||||||
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
|
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
|
||||||
|
|
||||||
account = resolve_server_account(request, normalized_service, data.get("client_region"))
|
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
|
||||||
if account:
|
if account:
|
||||||
profile = None if account == "default" else account
|
profile = None if account == "default" else account
|
||||||
|
|
||||||
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type"), key_cdm_config(user_config))
|
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type"), policy.cdm_config())
|
||||||
service_module = Services.load(normalized_service)
|
service_module = Services.load(normalized_service)
|
||||||
anonymous = getattr(service_module, "ANONYMOUS_SEARCH", False)
|
anonymous = getattr(service_module, "ANONYMOUS_SEARCH", False)
|
||||||
cookies, credential = (
|
cookies, credential = (
|
||||||
@@ -799,10 +799,10 @@ def run_service_search(
|
|||||||
|
|
||||||
if account:
|
if account:
|
||||||
account_tag = f"_accounts/{normalized_service}/{account}"
|
account_tag = f"_accounts/{normalized_service}/{account}"
|
||||||
service_instance.cache = keyed_cache(account_tag, service_instance, normalized_service, api_key, user_config)
|
service_instance.cache = keyed_cache(account_tag, service_instance, normalized_service, api_key, policy)
|
||||||
elif request_cache is not None:
|
elif request_cache is not None:
|
||||||
client_login = cookies is not None or credential is not None
|
client_login = cookies is not None or credential is not None
|
||||||
request_cache.attach(service_instance, data, normalized_service, request, client_login, user_config)
|
request_cache.attach(service_instance, data, normalized_service, request, client_login, policy)
|
||||||
service_instance._input_bridge = NoUserBridge()
|
service_instance._input_bridge = NoUserBridge()
|
||||||
if not anonymous:
|
if not anonymous:
|
||||||
service_instance.authenticate(cookies, credential)
|
service_instance.authenticate(cookies, credential)
|
||||||
@@ -820,135 +820,24 @@ def run_service_search(
|
|||||||
return results
|
return results
|
||||||
|
|
||||||
|
|
||||||
def allowed_services_for_key(secret_key: str | None) -> list[str] | None:
|
def request_policy(request: web.Request | None) -> KeyPolicy:
|
||||||
"""Effective service allowlist for an API key: the global list intersected with the key's.
|
"""The calling API key's policy; a call with no request gets the policy of a key with no entry."""
|
||||||
|
return KeyPolicy.of(request_secret_key(request) if request else None)
|
||||||
Returns None when nothing restricts the services.
|
|
||||||
"""
|
|
||||||
global_allowed = config.serve.get("services")
|
|
||||||
global_set: set[str] | None = None
|
|
||||||
if global_allowed:
|
|
||||||
global_set = {Services.get_tag(s) for s in global_allowed}
|
|
||||||
|
|
||||||
key_set: set[str] | None = None
|
|
||||||
if secret_key:
|
|
||||||
users = config.serve.get("users", {})
|
|
||||||
user_config = users.get(secret_key, {})
|
|
||||||
if isinstance(user_config, dict) and user_config.get("services"):
|
|
||||||
key_set = {Services.get_tag(s) for s in user_config["services"]}
|
|
||||||
|
|
||||||
if global_set and key_set:
|
|
||||||
result = global_set & key_set
|
|
||||||
elif global_set:
|
|
||||||
result = global_set
|
|
||||||
elif key_set:
|
|
||||||
result = key_set
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return list(result)
|
|
||||||
|
|
||||||
|
|
||||||
def get_allowed_services(request: web.Request | None = None) -> list[str] | None:
|
|
||||||
"""The effective service allowlist for a request's API key, or None when unrestricted."""
|
|
||||||
return allowed_services_for_key(request_secret_key(request) if request else None)
|
|
||||||
|
|
||||||
|
|
||||||
def is_admin(request: web.Request | None) -> bool:
|
|
||||||
"""Whether the calling key is the admin secret (no ``users`` entry) or has ``admin: true``."""
|
|
||||||
if not request:
|
|
||||||
return True
|
|
||||||
user_config = (config.serve or {}).get("users", {}).get(request_secret_key(request))
|
|
||||||
return user_config is None or (isinstance(user_config, dict) and user_config.get("admin") is True)
|
|
||||||
|
|
||||||
|
|
||||||
def require_admin(request: web.Request | None) -> None:
|
def require_admin(request: web.Request | None) -> None:
|
||||||
"""FORBIDDEN unless the calling key is the admin secret or has ``admin: true`` in ``serve.users``."""
|
"""FORBIDDEN unless the calling key is the admin secret or has ``admin: true`` in ``serve.users``."""
|
||||||
if is_admin(request):
|
if request_policy(request).admin:
|
||||||
return
|
return
|
||||||
raise APIError(APIErrorCode.FORBIDDEN, "This API key may not run server maintenance.")
|
raise APIError(APIErrorCode.FORBIDDEN, "This API key may not run server maintenance.")
|
||||||
|
|
||||||
|
|
||||||
def serve_user_config(api_key: str) -> dict[str, Any]:
|
|
||||||
"""The ``serve.users`` entry for an API key.
|
|
||||||
|
|
||||||
An API key absent from ``serve.users`` (the admin secret, or any caller in no-key mode) keeps
|
|
||||||
full access, so it gets every CDM device the server loaded.
|
|
||||||
"""
|
|
||||||
user_config = ((config.serve or {}).get("users") or {}).get(api_key)
|
|
||||||
if isinstance(user_config, dict):
|
|
||||||
return user_config
|
|
||||||
serve_cfg = config.serve or {}
|
|
||||||
return {
|
|
||||||
kind: [d.stem if hasattr(d, "stem") else str(d) for d in (serve_cfg.get(kind) or [])]
|
|
||||||
for kind in ("devices", "playready_devices")
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class KeyCdmConfig:
|
|
||||||
"""The app config as one API key sees it: ``cdm`` is the key's map, every other setting is the server's."""
|
|
||||||
|
|
||||||
def __init__(self, cdm: dict[str, Any]) -> None:
|
|
||||||
self.cdm = cdm
|
|
||||||
|
|
||||||
def __getattr__(self, name: str) -> Any:
|
|
||||||
return getattr(config, name)
|
|
||||||
|
|
||||||
|
|
||||||
def own_cdm(user_config: dict[str, Any] | None) -> dict[str, Any]:
|
|
||||||
"""The API key's own ``cdm`` map; empty when it sets none."""
|
|
||||||
own = (user_config or {}).get("cdm")
|
|
||||||
return own if isinstance(own, dict) else {}
|
|
||||||
|
|
||||||
|
|
||||||
def key_cdm_config(user_config: dict[str, Any] | None) -> Any:
|
|
||||||
"""The config the CDM lookups read for an API key: ``config`` itself unless the key maps a device of its own.
|
|
||||||
|
|
||||||
Each service entry of the key's own ``cdm`` replaces the server's whole entry for that service.
|
|
||||||
"""
|
|
||||||
own = own_cdm(user_config)
|
|
||||||
if not own:
|
|
||||||
return config
|
|
||||||
tags = {str(tag).lower() for tag in own}
|
|
||||||
return KeyCdmConfig({**{t: e for t, e in (config.cdm or {}).items() if str(t).lower() not in tags}, **own})
|
|
||||||
|
|
||||||
|
|
||||||
def key_service_config(user_config: dict[str, Any] | None, service: str) -> dict[str, Any]:
|
|
||||||
"""The API key's own ``service_config`` block for ``service``; empty when it sets none."""
|
|
||||||
blocks = (user_config or {}).get("service_config")
|
|
||||||
block = ci_get(blocks, Services.get_tag(service)) if isinstance(blocks, dict) else None
|
|
||||||
return block if isinstance(block, dict) else {}
|
|
||||||
|
|
||||||
|
|
||||||
def key_owns_identity(user_config: dict[str, Any] | None, service: str) -> bool:
|
|
||||||
"""Whether the API key sets its own device or service config for ``service``."""
|
|
||||||
return bool(key_service_config(user_config, service)) or ci_get(own_cdm(user_config), service) is not None
|
|
||||||
|
|
||||||
|
|
||||||
def key_service_yaml(normalized_service: str, user_config: dict[str, Any] | None) -> dict:
|
|
||||||
""":func:`load_service_config` with the API key's own block merged over it.
|
|
||||||
|
|
||||||
A top-level section that sets one of the block's plain values (a profile section with its own identity) takes
|
|
||||||
the key's value too, so a client cannot pick the server's identity back through the profile it names.
|
|
||||||
"""
|
|
||||||
service_config = load_service_config(normalized_service)
|
|
||||||
block = key_service_config(user_config, normalized_service)
|
|
||||||
if block:
|
|
||||||
merge_dict(copy.deepcopy(block), service_config)
|
|
||||||
scalars = {key for key, value in block.items() if not isinstance(value, (dict, list))}
|
|
||||||
for name, section in service_config.items():
|
|
||||||
if isinstance(section, dict) and name not in block:
|
|
||||||
for key in scalars & section.keys():
|
|
||||||
section[key] = block[key]
|
|
||||||
return service_config
|
|
||||||
|
|
||||||
|
|
||||||
def keyed_cache(
|
def keyed_cache(
|
||||||
tag: str,
|
tag: str,
|
||||||
service_instance: Any,
|
service_instance: Any,
|
||||||
service: str,
|
service: str,
|
||||||
api_key: str,
|
api_key: str,
|
||||||
user_config: dict[str, Any],
|
policy: KeyPolicy,
|
||||||
temporary: bool = False,
|
temporary: bool = False,
|
||||||
client_identity: bool = False,
|
client_identity: bool = False,
|
||||||
) -> Cacher:
|
) -> Cacher:
|
||||||
@@ -959,7 +848,7 @@ def keyed_cache(
|
|||||||
receives an identity the server built and no other API key shares it.
|
receives an identity the server built and no other API key shares it.
|
||||||
"""
|
"""
|
||||||
prefixes = tuple(getattr(service_instance, "IDENTITY_CACHE", ()))
|
prefixes = tuple(getattr(service_instance, "IDENTITY_CACHE", ()))
|
||||||
owns = key_owns_identity(user_config, service)
|
owns = policy.owns_identity(service)
|
||||||
if owns and not prefixes:
|
if owns and not prefixes:
|
||||||
warn_no_identity_cache(service)
|
warn_no_identity_cache(service)
|
||||||
if prefixes and (owns or (temporary and not client_identity)):
|
if prefixes and (owns or (temporary and not client_identity)):
|
||||||
@@ -982,115 +871,6 @@ def drop_identity_cache(api_keys: Iterable[str]) -> None:
|
|||||||
SessionStore.cleanup_cache_dir(f"_identity/{key_namespace(api_key)}")
|
SessionStore.cleanup_cache_dir(f"_identity/{key_namespace(api_key)}")
|
||||||
|
|
||||||
|
|
||||||
def server_cdm_allowed(request: web.Request | None = None, service: str | None = None) -> bool:
|
|
||||||
"""Whether the calling API key may have the server operate the CDM licensing for ``service``."""
|
|
||||||
return key_grant_allows(request, service, "server_cdm")
|
|
||||||
|
|
||||||
|
|
||||||
def server_vault_allowed(request: web.Request | None = None, service: str | None = None) -> bool:
|
|
||||||
"""Whether the calling API key may read the server vault in a remote session its own device licenses."""
|
|
||||||
return key_grant_allows(request, service, "server_vault") or server_cdm_allowed(request, service)
|
|
||||||
|
|
||||||
|
|
||||||
def key_grant_allows(request: web.Request | None, service: str | None, name: str) -> bool:
|
|
||||||
"""Whether the calling API key holds the ``name`` grant for ``service``.
|
|
||||||
|
|
||||||
Configured API keys opt in with ``<name>: true`` for every service, or with a list of
|
|
||||||
service tags for only those. An API key absent from ``serve.users`` (the admin secret) keeps
|
|
||||||
full access.
|
|
||||||
"""
|
|
||||||
if not request:
|
|
||||||
return True
|
|
||||||
secret_key = request_secret_key(request)
|
|
||||||
user_config = config.serve.get("users", {}).get(secret_key)
|
|
||||||
if user_config is None:
|
|
||||||
return True
|
|
||||||
allowed = user_config.get(name, False)
|
|
||||||
if isinstance(allowed, str):
|
|
||||||
allowed = [allowed]
|
|
||||||
if isinstance(allowed, (list, tuple, set)):
|
|
||||||
return service is not None and Services.get_tag(service).upper() in {
|
|
||||||
Services.get_tag(s).upper() for s in allowed
|
|
||||||
}
|
|
||||||
return bool(allowed)
|
|
||||||
|
|
||||||
|
|
||||||
def is_whole_number(value: Any) -> bool:
|
|
||||||
"""True for a non-negative int that is not a bool."""
|
|
||||||
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
|
|
||||||
|
|
||||||
|
|
||||||
def server_cdm_max_height_error(where: str, value: Any) -> str | None:
|
|
||||||
"""Why *value* cannot serve as ``server_cdm_max_height``, or None when it can (unset included)."""
|
|
||||||
|
|
||||||
def bad(height: Any) -> bool:
|
|
||||||
return height is not None and not is_whole_number(height)
|
|
||||||
|
|
||||||
if isinstance(value, dict):
|
|
||||||
if any(bad(height) for height in value.values()):
|
|
||||||
return f"{where}.server_cdm_max_height values must be whole numbers of pixels, not {value!r}"
|
|
||||||
return None
|
|
||||||
if bad(value):
|
|
||||||
return (
|
|
||||||
f"{where}.server_cdm_max_height must be a whole number of pixels or a map of service to one, not {value!r}"
|
|
||||||
)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def key_config_error(where: str, user_cfg: dict[str, Any], app_config: Any = None) -> str | None:
|
|
||||||
"""Why the ``services``, ``cdm`` or ``service_config`` of one serve.users entry cannot work; None when it can.
|
|
||||||
|
|
||||||
Devices are looked up in ``app_config`` (a reload passes the new file). A tag that names no service the server
|
|
||||||
has is logged, not refused: a later services refresh can add it.
|
|
||||||
"""
|
|
||||||
app_config = app_config or config
|
|
||||||
if isinstance(user_cfg.get("services"), dict):
|
|
||||||
return f"{where}.services must be a list of service tags; per-service settings go under service_config"
|
|
||||||
cdm, service_config = user_cfg.get("cdm") or {}, user_cfg.get("service_config") or {}
|
|
||||||
for name, entries in (("cdm", cdm), ("service_config", service_config)):
|
|
||||||
if not isinstance(entries, dict):
|
|
||||||
return f"{where}.{name} must be a mapping of service tag to settings"
|
|
||||||
if any(str(tag).lower() == "default" for tag in entries):
|
|
||||||
return f"{where}.{name}.default: name each service tag; a key has no default entry"
|
|
||||||
for tag, entry in cdm.items():
|
|
||||||
named = {"default": entry} if isinstance(entry, str) else entry if isinstance(entry, dict) else {}
|
|
||||||
named = {str(system).lower(): device for system, device in named.items()}
|
|
||||||
if (
|
|
||||||
not named
|
|
||||||
or not set(named) <= {"widevine", "playready", "default"}
|
|
||||||
or not all(isinstance(device, str) for device in named.values())
|
|
||||||
):
|
|
||||||
return f"{where}.cdm.{tag} must be a device name or a widevine/playready/default mapping of device names"
|
|
||||||
for system, device in named.items():
|
|
||||||
found = device_system(device, app_config)
|
|
||||||
if found is None or system != "default" and found != system:
|
|
||||||
return f"{where}.cdm.{tag}: no {'CDM' if system == 'default' else system} device named '{device}'"
|
|
||||||
for tag, entry in service_config.items():
|
|
||||||
if not isinstance(entry, dict):
|
|
||||||
return f"{where}.service_config.{tag} must be a mapping of config key to value"
|
|
||||||
if not cdm and not service_config:
|
|
||||||
return None
|
|
||||||
known = {tag.lower() for tag in Services.get_tags()}
|
|
||||||
for tag in [*cdm, *service_config]:
|
|
||||||
if str(tag).lower() not in known:
|
|
||||||
log.warning(f"{where}: no service {tag} on this server")
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def server_cdm_max_height(request: web.Request | None, service: str | None) -> int | None:
|
|
||||||
"""The tallest video track the server CDM licenses live for this API key on ``service``; None for no cap.
|
|
||||||
|
|
||||||
The setting is one height, or a map of service tag to height where ``default`` covers a missing or null tag.
|
|
||||||
"""
|
|
||||||
if not request:
|
|
||||||
return None
|
|
||||||
cap = serve_user_config(request_secret_key(request) or "").get("server_cdm_max_height")
|
|
||||||
if isinstance(cap, dict):
|
|
||||||
own = ci_get(cap, Services.get_tag(service)) if service else None
|
|
||||||
cap = own if own is not None else ci_get(cap, "default")
|
|
||||||
return cap if is_whole_number(cap) else None
|
|
||||||
|
|
||||||
|
|
||||||
def capped_error(message: str, cap: int | None = None) -> APIError:
|
def capped_error(message: str, cap: int | None = None) -> APIError:
|
||||||
"""The SERVER_CDM_CAPPED refusal; a client reads ``details`` to license the track itself."""
|
"""The SERVER_CDM_CAPPED refusal; a client reads ``details`` to license the track itself."""
|
||||||
details = {"reason": "server_cdm_max_height", "max_height": cap} if cap is not None else {"reason": "client_device"}
|
details = {"reason": "server_cdm_max_height", "max_height": cap} if cap is not None else {"reason": "client_device"}
|
||||||
@@ -1114,7 +894,7 @@ def requested_height(quality: Any) -> int | None:
|
|||||||
return max(heights) if heights else None
|
return max(heights) if heights else None
|
||||||
|
|
||||||
|
|
||||||
def choose_session_cdm(request: web.Request | None, service: str, data: dict[str, Any]) -> tuple[bool, int | None]:
|
def choose_session_cdm(policy: KeyPolicy, service: str, data: dict[str, Any]) -> tuple[bool, int | None]:
|
||||||
"""``(server_cdm, max_height)`` for a new remote session.
|
"""``(server_cdm, max_height)`` for a new remote session.
|
||||||
|
|
||||||
The service picks its manifest from the CDM it sees, so it decides once, before any tracks.
|
The service picks its manifest from the CDM it sees, so it decides once, before any tracks.
|
||||||
@@ -1122,13 +902,13 @@ def choose_session_cdm(request: web.Request | None, service: str, data: dict[str
|
|||||||
one of the service's ``SERVER_DEVICE_OPTIONS``.
|
one of the service's ``SERVER_DEVICE_OPTIONS``.
|
||||||
When ``-q`` asks for more than the cap, the client's own device licenses, and a client with no device gets a refusal.
|
When ``-q`` asks for more than the cap, the client's own device licenses, and a client with no device gets a refusal.
|
||||||
"""
|
"""
|
||||||
if not server_cdm_allowed(request, service):
|
if not policy.allows("server_cdm", service):
|
||||||
return False, None
|
return False, None
|
||||||
if data.get("server_cdm") is False and data.get("cdm_type"):
|
if data.get("server_cdm") is False and data.get("cdm_type"):
|
||||||
server_device_options = getattr(Services.load(service), "SERVER_DEVICE_OPTIONS", ())
|
server_device_options = getattr(Services.load(service), "SERVER_DEVICE_OPTIONS", ())
|
||||||
if not any(service_options(data, server_device_options).values()):
|
if not any(service_options(data, server_device_options).values()):
|
||||||
return False, None
|
return False, None
|
||||||
cap = server_cdm_max_height(request, service)
|
cap = policy.max_height(service)
|
||||||
wanted = requested_height(data.get("quality"))
|
wanted = requested_height(data.get("quality"))
|
||||||
if cap is None or wanted is None or wanted <= cap:
|
if cap is None or wanted is None or wanted <= cap:
|
||||||
return True, cap
|
return True, cap
|
||||||
@@ -1292,25 +1072,14 @@ def next_server_profile(service: str, region: str | None) -> str | None:
|
|||||||
return pool[n % len(pool)]
|
return pool[n % len(pool)]
|
||||||
|
|
||||||
|
|
||||||
def server_accounts_allowed(request: web.Request | None = None, service: str | None = None) -> bool:
|
def resolve_server_account(policy: KeyPolicy, service: str, region: Any) -> str | None:
|
||||||
"""Whether the calling API key may authenticate ``service`` with one of the server's own accounts.
|
|
||||||
|
|
||||||
Same shape as ``server_cdm``: ``server_accounts: true`` on the ``serve.users`` entry for every
|
|
||||||
service, or a list of service tags. Off unless set. The admin secret (no ``users`` entry) keeps
|
|
||||||
full access. Combine with ``server_account_spec``: the server treats an API key without the
|
|
||||||
opt-in as a client-managed remote session for that service.
|
|
||||||
"""
|
|
||||||
return key_grant_allows(request, service, "server_accounts")
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_server_account(request: web.Request | None, service: str, region: Any) -> str | None:
|
|
||||||
"""Profile of the server account a search or list call runs on; None when the service is client-managed.
|
"""Profile of the server account a search or list call runs on; None when the service is client-managed.
|
||||||
|
|
||||||
Raises FORBIDDEN for an API key without the ``server_accounts`` opt-in.
|
Raises FORBIDDEN for an API key without the ``server_accounts`` opt-in.
|
||||||
"""
|
"""
|
||||||
if server_account_spec(service) is None:
|
if server_account_spec(service) is None:
|
||||||
return None
|
return None
|
||||||
if not server_accounts_allowed(request, service):
|
if not policy.allows("server_accounts", service):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
APIErrorCode.FORBIDDEN,
|
APIErrorCode.FORBIDDEN,
|
||||||
f"Your API key may not use the server's accounts for {service}.",
|
f"Your API key may not use the server's accounts for {service}.",
|
||||||
@@ -1319,27 +1088,9 @@ def resolve_server_account(request: web.Request | None, service: str, region: An
|
|||||||
return next_server_profile(service, region if isinstance(region, str) else None) or "default"
|
return next_server_profile(service, region if isinstance(region, str) else None) or "default"
|
||||||
|
|
||||||
|
|
||||||
def server_account_for(request: web.Request | None, service: str) -> bool:
|
def server_account_for(policy: KeyPolicy, service: str) -> bool:
|
||||||
"""True when this request's remote session for ``service`` should run on a server account."""
|
"""True when this API key's remote session for ``service`` should run on a server account."""
|
||||||
return server_account_spec(service) is not None and server_accounts_allowed(request, service)
|
return server_account_spec(service) is not None and policy.allows("server_accounts", service)
|
||||||
|
|
||||||
|
|
||||||
def server_proxy_allowed(request: web.Request | None = None) -> bool:
|
|
||||||
"""Whether the calling API key may use the server's own configured proxy providers.
|
|
||||||
|
|
||||||
Configured API keys opt in with ``server_proxy: true``, a real yaml boolean, so a
|
|
||||||
quoted ``"true"`` or ``"no"`` does not count. It is a plain bool, not a per-service
|
|
||||||
list, because a proxy is not tied to a service. No API key has implicit access: an
|
|
||||||
API key absent from ``serve.users`` gets none, and neither does a call without a
|
|
||||||
request, so a handler that does not pass ``request`` through fails closed.
|
|
||||||
"""
|
|
||||||
if not request:
|
|
||||||
return False
|
|
||||||
secret_key = request_secret_key(request)
|
|
||||||
user_config = (config.serve or {}).get("users", {}).get(secret_key)
|
|
||||||
if not isinstance(user_config, dict):
|
|
||||||
return False
|
|
||||||
return user_config.get("server_proxy") is True
|
|
||||||
|
|
||||||
|
|
||||||
JOB_EVENTS_ROUTE = "/api/download/jobs/{job_id}/events"
|
JOB_EVENTS_ROUTE = "/api/download/jobs/{job_id}/events"
|
||||||
@@ -1474,7 +1225,7 @@ def validate_service(service_tag: str, request: web.Request | None = None) -> st
|
|||||||
service_path = Services.get_path(normalized)
|
service_path = Services.get_path(normalized)
|
||||||
if not service_path.exists():
|
if not service_path.exists():
|
||||||
return None
|
return None
|
||||||
allowed = get_allowed_services(request)
|
allowed = request_policy(request).services
|
||||||
if allowed is not None and normalized not in allowed:
|
if allowed is not None and normalized not in allowed:
|
||||||
return None
|
return None
|
||||||
return normalized
|
return normalized
|
||||||
@@ -1931,18 +1682,19 @@ def enforce_download_gates(params: dict[str, Any], request: web.Request | None =
|
|||||||
must set a quality at or under it, no ``best_available`` and no HYBRID range, as a job has no client device
|
must set a quality at or under it, no ``best_available`` and no HYBRID range, as a job has no client device
|
||||||
to fall back to. Pass the job's merged parameters, so the gate sees the values the job runs with.
|
to fall back to. Pass the job's merged parameters, so the gate sees the values the job runs with.
|
||||||
"""
|
"""
|
||||||
if not server_cdm_allowed(request, params.get("service")):
|
policy = request_policy(request)
|
||||||
|
if not policy.allows("server_cdm", params.get("service")):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
APIErrorCode.FORBIDDEN,
|
APIErrorCode.FORBIDDEN,
|
||||||
"Download jobs license with the server CDM, which is not enabled for this API key on this service",
|
"Download jobs license with the server CDM, which is not enabled for this API key on this service",
|
||||||
)
|
)
|
||||||
service = params.get("service")
|
service = params.get("service")
|
||||||
if service and key_owns_identity(serve_user_config(caller_key(request)), service):
|
if service and policy.owns_identity(service):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
APIErrorCode.FORBIDDEN,
|
APIErrorCode.FORBIDDEN,
|
||||||
"Download jobs run on the server's own device config, and this API key has its own for this service",
|
"Download jobs run on the server's own device config, and this API key has its own for this service",
|
||||||
)
|
)
|
||||||
cap = server_cdm_max_height(request, params.get("service"))
|
cap = policy.max_height(params.get("service"))
|
||||||
if cap is not None:
|
if cap is not None:
|
||||||
serve_defaults = config.serve or {}
|
serve_defaults = config.serve or {}
|
||||||
|
|
||||||
@@ -1970,7 +1722,7 @@ def enforce_download_gates(params: dict[str, Any], request: web.Request | None =
|
|||||||
"A download job cannot use a tunnel: proxy, because a tunnel belongs to one --remote client run.",
|
"A download job cannot use a tunnel: proxy, because a tunnel belongs to one --remote client run.",
|
||||||
)
|
)
|
||||||
|
|
||||||
if not server_proxy_allowed(request):
|
if not policy.allows("server_proxy"):
|
||||||
resolve_handler_proxy(params, params.get("service") or "", request)
|
resolve_handler_proxy(params, params.get("service") or "", request)
|
||||||
if params.get("proxy_download"):
|
if params.get("proxy_download"):
|
||||||
# the download proxy is gated like the main one: a full URI or nothing, never a server provider
|
# the download proxy is gated like the main one: a full URI or nothing, never a server provider
|
||||||
@@ -2028,7 +1780,10 @@ async def enqueue_job(
|
|||||||
manager = get_download_manager()
|
manager = get_download_manager()
|
||||||
await manager.start_workers()
|
await manager.start_workers()
|
||||||
job = manager.create_job(
|
job = manager.create_job(
|
||||||
service, title_id, owner_key=caller_key(request), **{**params, "server_proxy": server_proxy_allowed(request)}
|
service,
|
||||||
|
title_id,
|
||||||
|
owner_key=caller_key(request),
|
||||||
|
**{**params, "server_proxy": request_policy(request).allows("server_proxy")},
|
||||||
)
|
)
|
||||||
return web.json_response(
|
return web.json_response(
|
||||||
{"job_id": job.job_id, "status": job.status.value, "created_time": job.created_time.isoformat()}, status=202
|
{"job_id": job.job_id, "status": job.status.value, "created_time": job.created_time.isoformat()}, status=202
|
||||||
@@ -2288,11 +2043,7 @@ def configured_service_tags() -> list[str]:
|
|||||||
installed service. An API key with no ``services`` list does not widen the union, and a malformed entry is skipped.
|
installed service. An API key with no ``services`` list does not widen the union, and a malformed entry is skipped.
|
||||||
"""
|
"""
|
||||||
tags = Services.get_tags()
|
tags = Services.get_tags()
|
||||||
allowed = allowed_services_for_key(None)
|
allowed = named_services()
|
||||||
if allowed is None:
|
|
||||||
users = config.serve.get("users")
|
|
||||||
lists = [u.get("services") for u in users.values() if isinstance(u, dict)] if isinstance(users, dict) else []
|
|
||||||
allowed = [Services.get_tag(s) for lst in lists if isinstance(lst, list) for s in lst if isinstance(s, str)]
|
|
||||||
if not allowed:
|
if not allowed:
|
||||||
return tags
|
return tags
|
||||||
named = set(allowed)
|
named = set(allowed)
|
||||||
@@ -2418,26 +2169,26 @@ async def dashboard_keys_handler(request: web.Request) -> web.Response:
|
|||||||
bucket except ``anonymous`` has a row to attribute it to. Without the dashboard key's own
|
bucket except ``anonymous`` has a row to attribute it to. Without the dashboard key's own
|
||||||
row, a dashboard would render its own polling as traffic from an unknown caller.
|
row, a dashboard would render its own polling as traffic from an unknown caller.
|
||||||
"""
|
"""
|
||||||
from unshackle.core.api.stats import key_id, key_rate_limit, key_tier, mask_key, stats
|
from unshackle.core.api.stats import key_id, mask_key, stats
|
||||||
|
|
||||||
users = config.serve.get("users") or {}
|
|
||||||
api_secret = str(config.serve.get("api_secret") or "")
|
api_secret = str(config.serve.get("api_secret") or "")
|
||||||
dashboard = dashboard_key() or ""
|
dashboard = dashboard_key() or ""
|
||||||
|
|
||||||
def row(secret_key: str, role: str) -> dict[str, Any]:
|
def row(secret_key: str, role: str) -> dict[str, Any]:
|
||||||
entry = stats.keys.get(key_id(secret_key))
|
entry = stats.keys.get(key_id(secret_key))
|
||||||
api_access = role != "dashboard" or secret_key in users
|
policy = KeyPolicy.of(secret_key)
|
||||||
|
api_access = role != "dashboard" or policy.configured
|
||||||
return {
|
return {
|
||||||
"id": key_id(secret_key),
|
"id": key_id(secret_key),
|
||||||
"role": role,
|
"role": role,
|
||||||
"label": mask_key(secret_key),
|
"label": mask_key(secret_key),
|
||||||
"services": allowed_services_for_key(secret_key) if api_access else [],
|
"services": policy.services if api_access else [],
|
||||||
"server_cdm": user_grant(secret_key, "server_cdm") if api_access else False,
|
"server_cdm": policy.grant("server_cdm") if api_access else False,
|
||||||
"server_cdm_max_height": serve_user_config(secret_key).get("server_cdm_max_height") if api_access else None,
|
"server_cdm_max_height": policy.max_height_setting if api_access else None,
|
||||||
"server_accounts": user_grant(secret_key, "server_accounts") if api_access else False,
|
"server_accounts": policy.grant("server_accounts") if api_access else False,
|
||||||
"server_proxy": user_grant(secret_key, "server_proxy") is True if api_access else False,
|
"server_proxy": policy.grant("server_proxy") if api_access else False,
|
||||||
"tier": key_tier(secret_key),
|
"tier": policy.tier,
|
||||||
"rate_limit": key_rate_limit(secret_key),
|
"rate_limit": policy.rate_limit,
|
||||||
"window_used": entry.window_used if entry else 0,
|
"window_used": entry.window_used if entry else 0,
|
||||||
"requests": entry.requests if entry else 0,
|
"requests": entry.requests if entry else 0,
|
||||||
"rejected": entry.rejected if entry else 0,
|
"rejected": entry.rejected if entry else 0,
|
||||||
@@ -2451,24 +2202,13 @@ async def dashboard_keys_handler(request: web.Request) -> web.Response:
|
|||||||
return "dashboard"
|
return "dashboard"
|
||||||
return "admin" if secret_key == api_secret else "user"
|
return "admin" if secret_key == api_secret else "user"
|
||||||
|
|
||||||
keys = [str(k) for k in users]
|
keys = api_keys()
|
||||||
for extra in (api_secret, dashboard):
|
for extra in (api_secret, dashboard):
|
||||||
if extra and extra not in keys:
|
if extra and extra not in keys:
|
||||||
keys.append(extra)
|
keys.append(extra)
|
||||||
return web.json_response([row(k, role_of(k)) for k in keys])
|
return web.json_response([row(k, role_of(k)) for k in keys])
|
||||||
|
|
||||||
|
|
||||||
def user_grant(secret_key: str, name: str) -> Any:
|
|
||||||
"""A per-key grant as configured: False, True, or the list of service tags it covers.
|
|
||||||
|
|
||||||
An API key with no ``serve.users`` entry keeps implicit access, matching the resolvers.
|
|
||||||
"""
|
|
||||||
user_config = (config.serve.get("users") or {}).get(secret_key)
|
|
||||||
if not isinstance(user_config, dict):
|
|
||||||
return name != "server_proxy"
|
|
||||||
return user_config.get(name, False)
|
|
||||||
|
|
||||||
|
|
||||||
async def dashboard_services_handler(request: web.Request) -> web.Response:
|
async def dashboard_services_handler(request: web.Request) -> web.Response:
|
||||||
"""Every service configured on this server, or every installed one with ``?all=1``, and its load state."""
|
"""Every service configured on this server, or every installed one with ``?all=1``, and its load state."""
|
||||||
from unshackle.core import services as services_module
|
from unshackle.core import services as services_module
|
||||||
@@ -2949,7 +2689,7 @@ def redact_config(value: Any) -> Any:
|
|||||||
async def profiles_handler(request: web.Request | None = None) -> web.Response:
|
async def profiles_handler(request: web.Request | None = None) -> web.Response:
|
||||||
"""Answer the request for the credential profiles."""
|
"""Answer the request for the credential profiles."""
|
||||||
try:
|
try:
|
||||||
allowed = get_allowed_services(request)
|
allowed = request_policy(request).services
|
||||||
profiles: dict[str, list[str]] = {}
|
profiles: dict[str, list[str]] = {}
|
||||||
for service, creds in (config.credentials or {}).items():
|
for service, creds in (config.credentials or {}).items():
|
||||||
# a plain (non-dict) credential is unnamed; that service is omitted entirely
|
# a plain (non-dict) credential is unnamed; that service is omitted entirely
|
||||||
@@ -2977,7 +2717,8 @@ async def server_config_handler(request: web.Request | None = None) -> web.Respo
|
|||||||
try:
|
try:
|
||||||
manager = get_download_manager()
|
manager = get_download_manager()
|
||||||
serve_cfg = config.serve or {}
|
serve_cfg = config.serve or {}
|
||||||
allowed = get_allowed_services(request)
|
policy = request_policy(request)
|
||||||
|
allowed = policy.services
|
||||||
service_tags = Services.get_tags()
|
service_tags = Services.get_tags()
|
||||||
if allowed is not None:
|
if allowed is not None:
|
||||||
service_tags = [t for t in service_tags if t in allowed]
|
service_tags = [t for t in service_tags if t in allowed]
|
||||||
@@ -2995,7 +2736,7 @@ async def server_config_handler(request: web.Request | None = None) -> web.Respo
|
|||||||
"server_accounts": {
|
"server_accounts": {
|
||||||
tag: server_account_regions(tag)
|
tag: server_account_regions(tag)
|
||||||
for tag in (serve_cfg.get("server_accounts") or {})
|
for tag in (serve_cfg.get("server_accounts") or {})
|
||||||
if server_accounts_allowed(request, tag)
|
if policy.allows("server_accounts", tag)
|
||||||
}
|
}
|
||||||
or None,
|
or None,
|
||||||
},
|
},
|
||||||
@@ -3004,7 +2745,7 @@ async def server_config_handler(request: web.Request | None = None) -> web.Respo
|
|||||||
"remote_services": list(config.remote_services or {}),
|
"remote_services": list(config.remote_services or {}),
|
||||||
}
|
}
|
||||||
# Server-local absolute paths are useless to a remote client and name the host layout.
|
# Server-local absolute paths are useless to a remote client and name the host layout.
|
||||||
if is_admin(request):
|
if policy.admin:
|
||||||
payload["directories"] = {
|
payload["directories"] = {
|
||||||
"downloads": str(config.directories.downloads),
|
"downloads": str(config.directories.downloads),
|
||||||
"temp": str(config.directories.temp),
|
"temp": str(config.directories.temp),
|
||||||
@@ -3037,7 +2778,7 @@ async def download_history_handler(data: dict[str, Any], request: web.Request |
|
|||||||
if limit < 1:
|
if limit < 1:
|
||||||
raise APIError(APIErrorCode.INVALID_PARAMETERS, "limit must be >= 1", details={"limit": limit_raw})
|
raise APIError(APIErrorCode.INVALID_PARAMETERS, "limit must be >= 1", details={"limit": limit_raw})
|
||||||
|
|
||||||
allowed = get_allowed_services(request)
|
allowed = request_policy(request).services
|
||||||
if allowed is None:
|
if allowed is None:
|
||||||
history = await asyncio.to_thread(
|
history = await asyncio.to_thread(
|
||||||
read_job_history, limit=limit, service=data.get("service"), owner=owner_id(caller_key(request))
|
read_job_history, limit=limit, service=data.get("service"), owner=owner_id(caller_key(request))
|
||||||
@@ -3064,7 +2805,7 @@ async def delete_history_handler(job_id: str, request: web.Request | None = None
|
|||||||
from unshackle.core.api.download_manager import delete_job_history, owner_id
|
from unshackle.core.api.download_manager import delete_job_history, owner_id
|
||||||
|
|
||||||
try:
|
try:
|
||||||
allowed = get_allowed_services(request)
|
allowed = request_policy(request).services
|
||||||
allowed_upper = {a.upper() for a in allowed} if allowed is not None else None
|
allowed_upper = {a.upper() for a in allowed} if allowed is not None else None
|
||||||
if not delete_job_history(job_id, allowed=allowed_upper, owner=owner_id(caller_key(request))):
|
if not delete_job_history(job_id, allowed=allowed_upper, owner=owner_id(caller_key(request))):
|
||||||
raise APIError(APIErrorCode.NOT_FOUND, "History entry not found", details={"job_id": job_id})
|
raise APIError(APIErrorCode.NOT_FOUND, "History entry not found", details={"job_id": job_id})
|
||||||
@@ -3267,11 +3008,11 @@ def create_service_instance(
|
|||||||
server_cdm: bool = False,
|
server_cdm: bool = False,
|
||||||
client_device: bool = False,
|
client_device: bool = False,
|
||||||
input_bridge: InputBridge | None = None,
|
input_bridge: InputBridge | None = None,
|
||||||
user_config: dict[str, Any] | None = None,
|
policy: KeyPolicy | None = None,
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""Make a service instance and resolve its credentials and cookies.
|
"""Make a service instance and resolve its credentials and cookies.
|
||||||
|
|
||||||
``user_config`` is the calling API key's serve.users entry: its own ``cdm`` and ``service_config`` apply.
|
``policy`` is the calling API key's: its own ``cdm`` and ``service_config`` apply.
|
||||||
|
|
||||||
With ``client_device`` the service sees a stand-in for the client's device, which relays CDM calls
|
With ``client_device`` the service sees a stand-in for the client's device, which relays CDM calls
|
||||||
through ``input_bridge`` when the client can answer them, and a config holding the client's own identity.
|
through ``input_bridge`` when the client can answer them, and a config holding the client's own identity.
|
||||||
@@ -3283,9 +3024,10 @@ def create_service_instance(
|
|||||||
"""
|
"""
|
||||||
from unshackle.core.tracks import Video
|
from unshackle.core.tracks import Video
|
||||||
|
|
||||||
server_config = service_config = key_service_yaml(normalized_service, user_config)
|
policy = policy or KeyPolicy.of(None)
|
||||||
|
server_config = service_config = policy.service_yaml(normalized_service)
|
||||||
service_module = Services.load(normalized_service)
|
service_module = Services.load(normalized_service)
|
||||||
key_config = key_cdm_config(user_config)
|
key_config = policy.cdm_config()
|
||||||
cdm: Any
|
cdm: Any
|
||||||
client_identity = False
|
client_identity = False
|
||||||
if client_device:
|
if client_device:
|
||||||
@@ -3388,11 +3130,11 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
|||||||
|
|
||||||
session_id = str(uuid_mod.uuid4())
|
session_id = str(uuid_mod.uuid4())
|
||||||
api_key = caller_key(request)
|
api_key = caller_key(request)
|
||||||
user_config = serve_user_config(api_key)
|
policy = request_policy(request)
|
||||||
session_cache_dir = f"_sessions/{api_key_namespace(request)}/{session_id}/{normalized_service}"
|
session_cache_dir = f"_sessions/{api_key_namespace(request)}/{session_id}/{normalized_service}"
|
||||||
session_cache_tag: str | None = session_cache_dir
|
session_cache_tag: str | None = session_cache_dir
|
||||||
|
|
||||||
server_account = server_account_for(request, normalized_service)
|
server_account = server_account_for(policy, normalized_service)
|
||||||
if server_account:
|
if server_account:
|
||||||
region = data.get("proxy_region") or data.get("client_region")
|
region = data.get("proxy_region") or data.get("client_region")
|
||||||
if region is not None and not (isinstance(region, str) and re.fullmatch(r"[A-Za-z]{2}", region)):
|
if region is not None and not (isinstance(region, str) and re.fullmatch(r"[A-Za-z]{2}", region)):
|
||||||
@@ -3402,7 +3144,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
|||||||
profile = next_server_profile(normalized_service, region)
|
profile = next_server_profile(normalized_service, region)
|
||||||
log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}")
|
log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}")
|
||||||
|
|
||||||
use_server_cdm, max_height = choose_session_cdm(request, normalized_service, data)
|
use_server_cdm, max_height = choose_session_cdm(policy, normalized_service, data)
|
||||||
# an old client without cdm_relay keeps the server's device outside a capped session
|
# an old client without cdm_relay keeps the server's device outside a capped session
|
||||||
client_device = (
|
client_device = (
|
||||||
not use_server_cdm
|
not use_server_cdm
|
||||||
@@ -3426,7 +3168,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
|||||||
server_cdm=use_server_cdm,
|
server_cdm=use_server_cdm,
|
||||||
client_device=client_device,
|
client_device=client_device,
|
||||||
input_bridge=bridge,
|
input_bridge=bridge,
|
||||||
user_config=user_config,
|
policy=policy,
|
||||||
)
|
)
|
||||||
|
|
||||||
service_instance, cookies, credential = await asyncio.to_thread(build_service)
|
service_instance, cookies, credential = await asyncio.to_thread(build_service)
|
||||||
@@ -3444,7 +3186,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
|||||||
service_instance,
|
service_instance,
|
||||||
normalized_service,
|
normalized_service,
|
||||||
api_key,
|
api_key,
|
||||||
user_config,
|
policy,
|
||||||
temporary=not server_account,
|
temporary=not server_account,
|
||||||
client_identity=client_device and not server_device,
|
client_identity=client_device and not server_device,
|
||||||
)
|
)
|
||||||
@@ -3465,10 +3207,10 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
|||||||
creator_ip=request.remote if request else None,
|
creator_ip=request.remote if request else None,
|
||||||
server_account=(profile or "default") if server_account else None,
|
server_account=(profile or "default") if server_account else None,
|
||||||
cache_tag=session_cache_tag,
|
cache_tag=session_cache_tag,
|
||||||
user_config=user_config,
|
policy=policy,
|
||||||
server_cdm=use_server_cdm,
|
server_cdm=use_server_cdm,
|
||||||
server_cdm_max_height=max_height,
|
server_cdm_max_height=max_height,
|
||||||
server_vault=client_device and server_vault_allowed(request, normalized_service),
|
server_vault=client_device and policy.allows("server_vault", normalized_service),
|
||||||
server_device=server_device,
|
server_device=server_device,
|
||||||
client_auth=not server_account
|
client_auth=not server_account
|
||||||
and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)),
|
and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)),
|
||||||
@@ -3597,13 +3339,13 @@ def cookie_values(cookies: list[dict[str, Any]]) -> dict[str, str]:
|
|||||||
return {c["name"]: c["value"] for c in cookies}
|
return {c["name"]: c["value"] for c in cookies}
|
||||||
|
|
||||||
|
|
||||||
def session_user_config(session: Any, request: web.Request | None) -> dict[str, Any]:
|
def session_policy(session: Any, request: web.Request | None) -> KeyPolicy:
|
||||||
"""The serve.users entry a remote session was created with, so a reload cannot change it for that session.
|
"""The API key policy a remote session was created with, so a reload cannot change it for that session.
|
||||||
|
|
||||||
An API key with no ``cdm`` entry of its own for the service still follows the server's ``cdm`` after a reload.
|
An API key with no ``cdm`` entry of its own for the service still follows the server's ``cdm`` after a reload.
|
||||||
"""
|
"""
|
||||||
pinned = getattr(session, "user_config", None)
|
pinned = getattr(session, "policy", None)
|
||||||
return pinned if isinstance(pinned, dict) else serve_user_config(caller_key(request))
|
return pinned if isinstance(pinned, KeyPolicy) else request_policy(request)
|
||||||
|
|
||||||
|
|
||||||
def client_owns_login(session: SessionEntry) -> bool:
|
def client_owns_login(session: SessionEntry) -> bool:
|
||||||
@@ -3683,10 +3425,10 @@ async def session_tracks_handler(
|
|||||||
|
|
||||||
session_headers, session_cookies = client_session_auth(session)
|
session_headers, session_cookies = client_session_auth(session)
|
||||||
|
|
||||||
user_cfg = session_user_config(session, request)
|
policy = session_policy(session, request)
|
||||||
app_config = key_cdm_config(user_cfg)
|
app_config = policy.cdm_config()
|
||||||
has_wv = bool(user_cfg.get("devices"))
|
has_wv = bool(policy.devices("devices"))
|
||||||
has_pr = bool(user_cfg.get("playready_devices"))
|
has_pr = bool(policy.devices("playready_devices"))
|
||||||
|
|
||||||
service_tag = session.service_tag
|
service_tag = session.service_tag
|
||||||
config_cdm_type = detect_cdm_type_for_service(service_tag, app_config)
|
config_cdm_type = detect_cdm_type_for_service(service_tag, app_config)
|
||||||
@@ -4022,12 +3764,13 @@ def resolve_handler_proxy(
|
|||||||
proxy_param = data.get("proxy")
|
proxy_param = data.get("proxy")
|
||||||
no_proxy = data.get("no_proxy", False)
|
no_proxy = data.get("no_proxy", False)
|
||||||
proxy_providers: list = []
|
proxy_providers: list = []
|
||||||
allowed = server_proxy_allowed(request)
|
policy = request_policy(request)
|
||||||
|
allowed = policy.allows("server_proxy")
|
||||||
|
|
||||||
if (
|
if (
|
||||||
proxy_param
|
proxy_param
|
||||||
and re.match(r"^(https?://|socks|controld://|tunnel:)", str(proxy_param))
|
and re.match(r"^(https?://|socks|controld://|tunnel:)", str(proxy_param))
|
||||||
and server_account_for(request, normalized_service)
|
and server_account_for(policy, normalized_service)
|
||||||
):
|
):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
APIErrorCode.FORBIDDEN,
|
APIErrorCode.FORBIDDEN,
|
||||||
@@ -4035,7 +3778,7 @@ def resolve_handler_proxy(
|
|||||||
details={"service": normalized_service},
|
details={"service": normalized_service},
|
||||||
)
|
)
|
||||||
|
|
||||||
if isinstance(proxy_param, str) and not no_proxy and not (allowed or is_admin(request)):
|
if isinstance(proxy_param, str) and not no_proxy and not (allowed or policy.admin):
|
||||||
refusal = local_proxy_refusal(proxy_param)
|
refusal = local_proxy_refusal(proxy_param)
|
||||||
if refusal:
|
if refusal:
|
||||||
raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": normalized_service})
|
raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": normalized_service})
|
||||||
@@ -4256,23 +3999,23 @@ def ensure_track_drm(track: Any, session: Any = None, init_data: bytes | None =
|
|||||||
log.warning(f"ISM DRM extraction failed for {track.id}: {e!r}")
|
log.warning(f"ISM DRM extraction failed for {track.id}: {e!r}")
|
||||||
|
|
||||||
|
|
||||||
def resolve_device_name(user_config: dict, drm_type: str, service_tag: str = "") -> str:
|
def resolve_device_name(policy: KeyPolicy, drm_type: str, service_tag: str = "") -> str:
|
||||||
"""Get the CDM device name, checking the service's cdm mapping first.
|
"""Get the CDM device name, checking the service's cdm mapping first.
|
||||||
|
|
||||||
Resolution order:
|
Resolution order:
|
||||||
1. the key's own ``cdm`` entry for the service, else ``config.cdm[service_tag]``
|
1. the key's own ``cdm`` entry for the service, else ``config.cdm[service_tag]``
|
||||||
2. serve.users.{key}.devices / playready_devices (user device list)
|
2. the key's ``devices`` / ``playready_devices``
|
||||||
"""
|
"""
|
||||||
cdm_name = choose_cdm(key_cdm_config(user_config).cdm, service_tag, drm=drm_type, view="licence").name
|
cdm_name = choose_cdm(policy.cdm_config().cdm, service_tag, drm=drm_type, view="licence").name
|
||||||
if cdm_name:
|
if cdm_name:
|
||||||
return cdm_name
|
return cdm_name
|
||||||
|
|
||||||
if drm_type == "playready":
|
if drm_type == "playready":
|
||||||
device_name = (user_config.get("playready_devices") or [None])[0]
|
device_name = next(iter(policy.devices("playready_devices")), None)
|
||||||
if not device_name:
|
if not device_name:
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "No PlayReady device configured for this API key")
|
raise APIError(APIErrorCode.INVALID_INPUT, "No PlayReady device configured for this API key")
|
||||||
else:
|
else:
|
||||||
device_name = (user_config.get("devices") or [None])[0]
|
device_name = next(iter(policy.devices("devices")), None)
|
||||||
if not device_name:
|
if not device_name:
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "No Widevine device configured for this API key")
|
raise APIError(APIErrorCode.INVALID_INPUT, "No Widevine device configured for this API key")
|
||||||
return device_name
|
return device_name
|
||||||
@@ -4286,7 +4029,7 @@ def vault_candidates(client_drm_type: str) -> list[str]:
|
|||||||
|
|
||||||
def server_drm_candidates(
|
def server_drm_candidates(
|
||||||
service_tag: str,
|
service_tag: str,
|
||||||
user_config: dict,
|
policy: KeyPolicy,
|
||||||
client_drm_type: str,
|
client_drm_type: str,
|
||||||
track: Any,
|
track: Any,
|
||||||
warn: Callable[[str], None] = log.warning,
|
warn: Callable[[str], None] = log.warning,
|
||||||
@@ -4298,13 +4041,13 @@ def server_drm_candidates(
|
|||||||
system, so the route never plans a licence that fails on the wrong device type. The
|
system, so the route never plans a licence that fails on the wrong device type. The
|
||||||
track's own drm_preference moves its system to the front when the server has it.
|
track's own drm_preference moves its system to the front when the server has it.
|
||||||
"""
|
"""
|
||||||
app_config = key_cdm_config(user_config)
|
app_config = policy.cdm_config()
|
||||||
server_type = detect_cdm_type_for_service(service_tag, app_config)
|
server_type = detect_cdm_type_for_service(service_tag, app_config)
|
||||||
first = server_type or (client_drm_type if client_drm_type in ("widevine", "playready") else "widevine")
|
first = server_type or (client_drm_type if client_drm_type in ("widevine", "playready") else "widevine")
|
||||||
candidates: list[str] = []
|
candidates: list[str] = []
|
||||||
for drm_type in (first, *(system for system in ("widevine", "playready") if system != first)):
|
for drm_type in (first, *(system for system in ("widevine", "playready") if system != first)):
|
||||||
try:
|
try:
|
||||||
device_name = resolve_device_name(user_config, drm_type, service_tag)
|
device_name = resolve_device_name(policy, drm_type, service_tag)
|
||||||
except APIError:
|
except APIError:
|
||||||
continue
|
continue
|
||||||
if device_system(device_name, app_config) in (None, drm_type):
|
if device_system(device_name, app_config) in (None, drm_type):
|
||||||
@@ -4515,7 +4258,7 @@ def handle_single_server_cdm(
|
|||||||
vault_only: bool = False,
|
vault_only: bool = False,
|
||||||
shared: dict[str, Any] | None = None,
|
shared: dict[str, Any] | None = None,
|
||||||
track_kid: uuid.UUID | None = None,
|
track_kid: uuid.UUID | None = None,
|
||||||
user_config: dict[str, Any] | None = None,
|
policy: KeyPolicy | None = None,
|
||||||
) -> dict[str, str]:
|
) -> dict[str, str]:
|
||||||
"""Do the single-track server_cdm licensing with the DRM class get_content_keys() flow.
|
"""Do the single-track server_cdm licensing with the DRM class get_content_keys() flow.
|
||||||
|
|
||||||
@@ -4552,8 +4295,8 @@ def handle_single_server_cdm(
|
|||||||
return vault_keys
|
return vault_keys
|
||||||
raise refusal or APIError(APIErrorCode.NO_CONTENT, "The server vault holds no content key for this track")
|
raise refusal or APIError(APIErrorCode.NO_CONTENT, "The server vault holds no content key for this track")
|
||||||
|
|
||||||
if user_config is None:
|
if policy is None:
|
||||||
user_config = serve_user_config(caller_key(request))
|
policy = request_policy(request)
|
||||||
|
|
||||||
if drm_type == "playready":
|
if drm_type == "playready":
|
||||||
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
|
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
|
||||||
@@ -4568,7 +4311,7 @@ def handle_single_server_cdm(
|
|||||||
pr_drm.absorb(*siblings)
|
pr_drm.absorb(*siblings)
|
||||||
|
|
||||||
# Gate on the caller's CDM device first: no device, no keys from the vault or CDM.
|
# Gate on the caller's CDM device first: no device, no keys from the vault or CDM.
|
||||||
device_name = resolve_device_name(user_config, drm_type, service_name)
|
device_name = resolve_device_name(policy, drm_type, service_name)
|
||||||
|
|
||||||
if track_kid and (vault_keys := from_vaults(pr_drm.kids)):
|
if track_kid and (vault_keys := from_vaults(pr_drm.kids)):
|
||||||
return vault_keys
|
return vault_keys
|
||||||
@@ -4597,7 +4340,7 @@ def handle_single_server_cdm(
|
|||||||
|
|
||||||
# Gate on the caller's CDM device first so a caller with no device cannot
|
# Gate on the caller's CDM device first so a caller with no device cannot
|
||||||
# harvest server-side keys from the vault fallback below.
|
# harvest server-side keys from the vault fallback below.
|
||||||
device_name = resolve_device_name(user_config, drm_type, service_name)
|
device_name = resolve_device_name(policy, drm_type, service_name)
|
||||||
|
|
||||||
if vault_keys := from_vaults(wv_drm.kids):
|
if vault_keys := from_vaults(wv_drm.kids):
|
||||||
return vault_keys
|
return vault_keys
|
||||||
@@ -4764,7 +4507,7 @@ async def session_samples_handler(
|
|||||||
details={"track_id": track_id, "session_id": session_id},
|
details={"track_id": track_id, "session_id": session_id},
|
||||||
)
|
)
|
||||||
service = session.service_instance
|
service = session.service_instance
|
||||||
if not server_cdm_allowed(request, session.service_tag):
|
if not request_policy(request).allows("server_cdm", session.service_tag):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
APIErrorCode.FORBIDDEN, f"This API key may not decrypt {session.service_tag} samples on the server"
|
APIErrorCode.FORBIDDEN, f"This API key may not decrypt {session.service_tag} samples on the server"
|
||||||
)
|
)
|
||||||
@@ -4825,7 +4568,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
|||||||
# a session the client's device licenses reaches the server vault only; its live licences stay client-side
|
# a session the client's device licenses reaches the server vault only; its live licences stay client-side
|
||||||
vault_only = not session.server_cdm
|
vault_only = not session.server_cdm
|
||||||
if mode == "server_cdm" and not (
|
if mode == "server_cdm" and not (
|
||||||
session.server_vault if vault_only else server_cdm_allowed(request, session.service_tag)
|
session.server_vault if vault_only else request_policy(request).allows("server_cdm", session.service_tag)
|
||||||
):
|
):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
APIErrorCode.FORBIDDEN,
|
APIErrorCode.FORBIDDEN,
|
||||||
@@ -4833,7 +4576,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
|||||||
)
|
)
|
||||||
|
|
||||||
if mode == "server_cdm" and track_ids:
|
if mode == "server_cdm" and track_ids:
|
||||||
user_config = session_user_config(session, request)
|
policy = session_policy(session, request)
|
||||||
service = session.service_instance
|
service = session.service_instance
|
||||||
service_tag = session.service_tag
|
service_tag = session.service_tag
|
||||||
|
|
||||||
@@ -4905,7 +4648,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
|||||||
vault_only=vault_only,
|
vault_only=vault_only,
|
||||||
shared=shared,
|
shared=shared,
|
||||||
track_kid=track_kid,
|
track_kid=track_kid,
|
||||||
user_config=user_config,
|
policy=policy,
|
||||||
)
|
)
|
||||||
if keys:
|
if keys:
|
||||||
keys_by_pssh[cache_key] = {**keys_by_pssh[cache_key], **keys}
|
keys_by_pssh[cache_key] = {**keys_by_pssh[cache_key], **keys}
|
||||||
@@ -4938,7 +4681,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
|||||||
candidates = (
|
candidates = (
|
||||||
vault_candidates(drm_type)
|
vault_candidates(drm_type)
|
||||||
if vault_only
|
if vault_only
|
||||||
else server_drm_candidates(service_tag, user_config, drm_type, track, warn)
|
else server_drm_candidates(service_tag, policy, drm_type, track, warn)
|
||||||
)
|
)
|
||||||
|
|
||||||
probed: uuid.UUID | None = None
|
probed: uuid.UUID | None = None
|
||||||
@@ -5018,11 +4761,11 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
|||||||
if mode == "server_cdm":
|
if mode == "server_cdm":
|
||||||
# The server's config.cdm mapping decides the DRM system, as in the batch path.
|
# The server's config.cdm mapping decides the DRM system, as in the batch path.
|
||||||
# The client only knows its own local device, which the server never uses here.
|
# The client only knows its own local device, which the server never uses here.
|
||||||
user_config = session_user_config(session, request)
|
policy = session_policy(session, request)
|
||||||
candidates = (
|
candidates = (
|
||||||
vault_candidates(drm_type)
|
vault_candidates(drm_type)
|
||||||
if vault_only
|
if vault_only
|
||||||
else server_drm_candidates(session.service_tag, user_config, drm_type, track)
|
else server_drm_candidates(session.service_tag, policy, drm_type, track)
|
||||||
)
|
)
|
||||||
picked = pick_server_pssh(track, candidates)
|
picked = pick_server_pssh(track, candidates)
|
||||||
if not picked:
|
if not picked:
|
||||||
@@ -5054,7 +4797,7 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
|||||||
live_licence_refusal(session, track),
|
live_licence_refusal(session, track),
|
||||||
vault_only=vault_only,
|
vault_only=vault_only,
|
||||||
track_kid=asked_kid,
|
track_kid=asked_kid,
|
||||||
user_config=user_config,
|
policy=policy,
|
||||||
)
|
)
|
||||||
log.info(f"Server CDM resolved {len(keys)} key(s) for track {track_log_label(track)}")
|
log.info(f"Server CDM resolved {len(keys)} key(s) for track {track_log_label(track)}")
|
||||||
note_served_keys(session, keys, key_sources)
|
note_served_keys(session, keys, key_sources)
|
||||||
@@ -5266,7 +5009,7 @@ def shared_key_client(request: web.Request) -> str | None:
|
|||||||
|
|
||||||
Only a shared key reads the header, so a client that talks to the server directly cannot use it to pass a limit.
|
Only a shared key reads the header, so a client that talks to the server directly cannot use it to pass a limit.
|
||||||
"""
|
"""
|
||||||
if serve_user_config(request_secret_key(request) or "").get("shared") is not True:
|
if not request_policy(request).shared:
|
||||||
return None
|
return None
|
||||||
return request.headers.get("X-Client-Id", "")[:64] or None
|
return request.headers.get("X-Client-Id", "")[:64] or None
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,308 @@
|
|||||||
|
"""What one API key may do on this server, read from its ``serve.users`` entry."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import logging
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Literal
|
||||||
|
|
||||||
|
from unshackle.core.cdm.loader import device_system
|
||||||
|
from unshackle.core.config import config
|
||||||
|
from unshackle.core.launch import load_service_config
|
||||||
|
from unshackle.core.services import Services
|
||||||
|
from unshackle.core.utils.collections import ci_get, merge_dict
|
||||||
|
|
||||||
|
log = logging.getLogger("api")
|
||||||
|
|
||||||
|
Grant = Literal["server_cdm", "server_vault", "server_accounts", "server_proxy"]
|
||||||
|
|
||||||
|
|
||||||
|
def _serve(serve: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
|
return (config.serve if serve is None else serve) or {}
|
||||||
|
|
||||||
|
|
||||||
|
def users_table(serve: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
"""The ``serve.users`` mapping of ``serve`` (the live config when None); empty when it is not a mapping."""
|
||||||
|
users = _serve(serve).get("users")
|
||||||
|
return users if isinstance(users, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def api_keys(serve: dict[str, Any] | None = None) -> list[str]:
|
||||||
|
"""Every API key that has a ``serve.users`` entry."""
|
||||||
|
return [str(key) for key in users_table(serve)]
|
||||||
|
|
||||||
|
|
||||||
|
def named_services(serve: dict[str, Any] | None = None) -> list[str]:
|
||||||
|
"""The service tags the config names: ``serve.services``, else every key's ``services`` list together.
|
||||||
|
|
||||||
|
An API key with no ``services`` list adds nothing, and the function skips a malformed entry.
|
||||||
|
"""
|
||||||
|
serve = _serve(serve)
|
||||||
|
if serve.get("services"):
|
||||||
|
return list({Services.get_tag(s) for s in serve["services"]})
|
||||||
|
lists = [entry.get("services") for entry in users_table(serve).values() if isinstance(entry, dict)]
|
||||||
|
return [Services.get_tag(s) for names in lists if isinstance(names, list) for s in names if isinstance(s, str)]
|
||||||
|
|
||||||
|
|
||||||
|
def is_whole_number(value: Any) -> bool:
|
||||||
|
"""True for a non-negative int that is not a bool."""
|
||||||
|
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
|
||||||
|
|
||||||
|
|
||||||
|
def rate_limit_error(where: str, value: Any) -> str | None:
|
||||||
|
"""Why *value* cannot serve as a rate limit, or None when it can. Unset is fine.
|
||||||
|
|
||||||
|
:attr:`KeyPolicy.rate_limit` reads anything else as "no limit", so a mistyped value would silently remove the cap.
|
||||||
|
"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||||
|
return f"{where}.rate_limit must be a positive whole number of requests per hour, not {value!r}"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class KeyCdmConfig:
|
||||||
|
"""The app config as one API key sees it: ``cdm`` is the key's map, every other setting is the server's."""
|
||||||
|
|
||||||
|
def __init__(self, cdm: dict[str, Any]) -> None:
|
||||||
|
self.cdm = cdm
|
||||||
|
|
||||||
|
def __getattr__(self, name: str) -> Any:
|
||||||
|
return getattr(config, name)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class KeyPolicy:
|
||||||
|
"""What one API key may do, built from its ``serve.users`` entry and the ``serve`` block around it.
|
||||||
|
|
||||||
|
``entry`` is None for an API key with no entry: the ``api_secret``, any caller in no-key mode, and a call with
|
||||||
|
no request. Such an API key is admin and holds every grant except ``server_proxy``, which only an entry gives.
|
||||||
|
"""
|
||||||
|
|
||||||
|
entry: dict[str, Any] | None = None
|
||||||
|
serve: dict[str, Any] = field(default_factory=dict, repr=False)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def of(cls, api_key: str | None, serve: dict[str, Any] | None = None) -> KeyPolicy:
|
||||||
|
"""The policy of ``api_key`` in ``serve`` (the live config when None); a malformed entry grants nothing."""
|
||||||
|
serve = _serve(serve)
|
||||||
|
table = users_table(serve)
|
||||||
|
if not api_key or api_key not in table:
|
||||||
|
return cls(None, serve)
|
||||||
|
entry = table[api_key]
|
||||||
|
return cls(entry if isinstance(entry, dict) else {}, serve)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _entry(self) -> dict[str, Any]:
|
||||||
|
return self.entry or {}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def configured(self) -> bool:
|
||||||
|
"""Whether the API key has a ``serve.users`` entry."""
|
||||||
|
return self.entry is not None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def admin(self) -> bool:
|
||||||
|
"""Whether the API key may run server maintenance and see admin-only fields."""
|
||||||
|
return not self.configured or self._entry.get("admin") is True
|
||||||
|
|
||||||
|
@property
|
||||||
|
def services(self) -> list[str] | None:
|
||||||
|
"""The services the API key may use: ``serve.services`` and its own ``services`` together; None for all."""
|
||||||
|
sets = [
|
||||||
|
{Services.get_tag(s) for s in names}
|
||||||
|
for names in (self.serve.get("services"), self._entry.get("services"))
|
||||||
|
if names
|
||||||
|
]
|
||||||
|
return list(set.intersection(*sets)) if sets else None
|
||||||
|
|
||||||
|
def grant(self, name: Grant) -> bool | list[str]:
|
||||||
|
"""The ``name`` setting as enforced: True for every service, False, or the service tags it covers.
|
||||||
|
|
||||||
|
``server_proxy`` is a plain bool that only a real yaml ``true`` on an entry sets.
|
||||||
|
"""
|
||||||
|
if name == "server_proxy":
|
||||||
|
return self.configured and self._entry.get(name) is True
|
||||||
|
if not self.configured:
|
||||||
|
return True
|
||||||
|
value = self._entry.get(name, False)
|
||||||
|
if isinstance(value, str):
|
||||||
|
return [value]
|
||||||
|
if isinstance(value, (list, tuple, set)):
|
||||||
|
return list(value)
|
||||||
|
return bool(value)
|
||||||
|
|
||||||
|
def allows(self, name: Grant, service: str | None = None) -> bool:
|
||||||
|
"""Whether the API key holds ``name`` for ``service``; ``server_cdm`` gives ``server_vault`` too."""
|
||||||
|
if name == "server_vault" and self.allows("server_cdm", service):
|
||||||
|
return True
|
||||||
|
value = self.grant(name)
|
||||||
|
if isinstance(value, list):
|
||||||
|
return service is not None and Services.get_tag(service).upper() in {
|
||||||
|
Services.get_tag(s).upper() for s in value
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def max_height_setting(self) -> Any:
|
||||||
|
"""``server_cdm_max_height`` as configured: one height, a map of service tag to height, or None."""
|
||||||
|
return self._entry.get("server_cdm_max_height")
|
||||||
|
|
||||||
|
def max_height(self, service: str | None) -> int | None:
|
||||||
|
"""The tallest video track the server CDM licenses live for ``service``; None for no cap.
|
||||||
|
|
||||||
|
In a map, ``default`` covers a missing or null tag.
|
||||||
|
"""
|
||||||
|
cap = self.max_height_setting
|
||||||
|
if isinstance(cap, dict):
|
||||||
|
own = ci_get(cap, Services.get_tag(service)) if service else None
|
||||||
|
cap = own if own is not None else ci_get(cap, "default")
|
||||||
|
return cap if is_whole_number(cap) else None
|
||||||
|
|
||||||
|
def devices(self, kind: Literal["devices", "playready_devices"]) -> list[str]:
|
||||||
|
"""The API key's device names of ``kind``; every device the server loaded for an API key with no entry."""
|
||||||
|
if self.configured:
|
||||||
|
return list(self._entry.get(kind) or [])
|
||||||
|
return [d.stem if hasattr(d, "stem") else str(d) for d in (self.serve.get(kind) or [])]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _own_cdm(self) -> dict[str, Any]:
|
||||||
|
own = self._entry.get("cdm")
|
||||||
|
return own if isinstance(own, dict) else {}
|
||||||
|
|
||||||
|
def cdm_config(self) -> Any:
|
||||||
|
"""The config the CDM lookups read: ``config`` itself unless the API key maps a device of its own.
|
||||||
|
|
||||||
|
Each service entry of the key's own ``cdm`` replaces the server's whole entry for that service.
|
||||||
|
"""
|
||||||
|
own = self._own_cdm
|
||||||
|
if not own:
|
||||||
|
return config
|
||||||
|
tags = {str(tag).lower() for tag in own}
|
||||||
|
return KeyCdmConfig({**{t: e for t, e in (config.cdm or {}).items() if str(t).lower() not in tags}, **own})
|
||||||
|
|
||||||
|
def service_config(self, service: str) -> dict[str, Any]:
|
||||||
|
"""The key's own ``service_config`` block for ``service``; empty when it sets none."""
|
||||||
|
blocks = self._entry.get("service_config")
|
||||||
|
block = ci_get(blocks, Services.get_tag(service)) if isinstance(blocks, dict) else None
|
||||||
|
return block if isinstance(block, dict) else {}
|
||||||
|
|
||||||
|
def owns_identity(self, service: str) -> bool:
|
||||||
|
"""Whether the API key sets its own device or service config for ``service``."""
|
||||||
|
return bool(self.service_config(service)) or ci_get(self._own_cdm, service) is not None
|
||||||
|
|
||||||
|
def service_yaml(self, service: str) -> dict:
|
||||||
|
""":func:`load_service_config` with the key's own block merged over it.
|
||||||
|
|
||||||
|
A top-level section that sets one of the block's plain values (a profile section with its own identity) takes
|
||||||
|
the key's value too, so a client cannot pick the server's identity back through the profile it names.
|
||||||
|
"""
|
||||||
|
service_config = load_service_config(service)
|
||||||
|
block = self.service_config(service)
|
||||||
|
if block:
|
||||||
|
merge_dict(copy.deepcopy(block), service_config)
|
||||||
|
scalars = {key for key, value in block.items() if not isinstance(value, (dict, list))}
|
||||||
|
for name, section in service_config.items():
|
||||||
|
if isinstance(section, dict) and name not in block:
|
||||||
|
for key in scalars & section.keys():
|
||||||
|
section[key] = block[key]
|
||||||
|
return service_config
|
||||||
|
|
||||||
|
@property
|
||||||
|
def username(self) -> str | None:
|
||||||
|
"""The entry's ``username``, when it sets one."""
|
||||||
|
name = self._entry.get("username")
|
||||||
|
return str(name) if name else None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def shared(self) -> bool:
|
||||||
|
"""Whether a gateway shares the API key, so its ``X-Client-Id`` header names the person behind each call."""
|
||||||
|
return self._entry.get("shared") is True
|
||||||
|
|
||||||
|
@property
|
||||||
|
def tier(self) -> str | None:
|
||||||
|
"""The tier name the entry references."""
|
||||||
|
tier = self._entry.get("tier")
|
||||||
|
return str(tier) if tier else None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def rate_limit(self) -> int | None:
|
||||||
|
"""Requests per hour: the entry's own ``rate_limit``, else its tier's, else None for no limit."""
|
||||||
|
own = self._entry.get("rate_limit")
|
||||||
|
if isinstance(own, int) and own > 0:
|
||||||
|
return own
|
||||||
|
tiers = self.serve.get("tiers")
|
||||||
|
tier = tiers.get(self._entry["tier"]) if isinstance(tiers, dict) and self._entry.get("tier") else None
|
||||||
|
limit = tier.get("rate_limit") if isinstance(tier, dict) else None
|
||||||
|
return limit if isinstance(limit, int) and limit > 0 else None
|
||||||
|
|
||||||
|
def entry_error(self, where: str, app_config: Any = None) -> str | None:
|
||||||
|
"""Why the entry cannot work, or None when it can; serve runs it on load and on reload.
|
||||||
|
|
||||||
|
Devices are looked up in ``app_config`` (a reload passes the new file).
|
||||||
|
"""
|
||||||
|
entry = self._entry
|
||||||
|
tier = entry.get("tier")
|
||||||
|
if tier and tier not in (self.serve.get("tiers") or {}):
|
||||||
|
return f"{where}.tier: no such tier '{tier}' under serve.tiers"
|
||||||
|
return (
|
||||||
|
rate_limit_error(where, entry.get("rate_limit"))
|
||||||
|
or _max_height_error(where, entry.get("server_cdm_max_height"))
|
||||||
|
or _identity_error(where, entry, app_config or config)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _max_height_error(where: str, value: Any) -> str | None:
|
||||||
|
"""Why *value* cannot serve as ``server_cdm_max_height``, or None when it can (unset included)."""
|
||||||
|
|
||||||
|
def bad(height: Any) -> bool:
|
||||||
|
return height is not None and not is_whole_number(height)
|
||||||
|
|
||||||
|
if isinstance(value, dict):
|
||||||
|
if any(bad(height) for height in value.values()):
|
||||||
|
return f"{where}.server_cdm_max_height values must be whole numbers of pixels, not {value!r}"
|
||||||
|
return None
|
||||||
|
if bad(value):
|
||||||
|
return (
|
||||||
|
f"{where}.server_cdm_max_height must be a whole number of pixels or a map of service to one, not {value!r}"
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _identity_error(where: str, entry: dict[str, Any], app_config: Any) -> str | None:
|
||||||
|
"""Why the ``services``, ``cdm`` or ``service_config`` of an entry cannot work; None when it can.
|
||||||
|
|
||||||
|
A tag that names no service the server has is logged, not refused: a later services refresh can add it.
|
||||||
|
"""
|
||||||
|
if isinstance(entry.get("services"), dict):
|
||||||
|
return f"{where}.services must be a list of service tags; per-service settings go under service_config"
|
||||||
|
cdm, service_config = entry.get("cdm") or {}, entry.get("service_config") or {}
|
||||||
|
for name, entries in (("cdm", cdm), ("service_config", service_config)):
|
||||||
|
if not isinstance(entries, dict):
|
||||||
|
return f"{where}.{name} must be a mapping of service tag to settings"
|
||||||
|
if any(str(tag).lower() == "default" for tag in entries):
|
||||||
|
return f"{where}.{name}.default: name each service tag; a key has no default entry"
|
||||||
|
for tag, value in cdm.items():
|
||||||
|
named = {"default": value} if isinstance(value, str) else value if isinstance(value, dict) else {}
|
||||||
|
named = {str(system).lower(): device for system, device in named.items()}
|
||||||
|
if (
|
||||||
|
not named
|
||||||
|
or not set(named) <= {"widevine", "playready", "default"}
|
||||||
|
or not all(isinstance(device, str) for device in named.values())
|
||||||
|
):
|
||||||
|
return f"{where}.cdm.{tag} must be a device name or a widevine/playready/default mapping of device names"
|
||||||
|
for system, device in named.items():
|
||||||
|
found = device_system(device, app_config)
|
||||||
|
if found is None or system != "default" and found != system:
|
||||||
|
return f"{where}.cdm.{tag}: no {'CDM' if system == 'default' else system} device named '{device}'"
|
||||||
|
for tag, value in service_config.items():
|
||||||
|
if not isinstance(value, dict):
|
||||||
|
return f"{where}.service_config.{tag} must be a mapping of config key to value"
|
||||||
|
if not cdm and not service_config:
|
||||||
|
return None
|
||||||
|
known = {tag.lower() for tag in Services.get_tags()}
|
||||||
|
for tag in [*cdm, *service_config]:
|
||||||
|
if str(tag).lower() not in known:
|
||||||
|
log.warning(f"{where}: no service {tag} on this server")
|
||||||
|
return None
|
||||||
@@ -41,9 +41,7 @@ from unshackle.core.api.handlers import (
|
|||||||
download_job_events_handler,
|
download_job_events_handler,
|
||||||
download_job_input_handler,
|
download_job_input_handler,
|
||||||
env_check_handler,
|
env_check_handler,
|
||||||
get_allowed_services,
|
|
||||||
get_download_job_handler,
|
get_download_job_handler,
|
||||||
is_admin,
|
|
||||||
list_download_jobs_handler,
|
list_download_jobs_handler,
|
||||||
list_titles_handler,
|
list_titles_handler,
|
||||||
list_tracks_handler,
|
list_tracks_handler,
|
||||||
@@ -53,10 +51,10 @@ from unshackle.core.api.handlers import (
|
|||||||
remote_login_input_handler,
|
remote_login_input_handler,
|
||||||
remote_logins_handler,
|
remote_logins_handler,
|
||||||
remote_services_info,
|
remote_services_info,
|
||||||
|
request_policy,
|
||||||
retry_download_job_handler,
|
retry_download_job_handler,
|
||||||
search_handler,
|
search_handler,
|
||||||
server_account_regions,
|
server_account_regions,
|
||||||
server_accounts_allowed,
|
|
||||||
server_config_handler,
|
server_config_handler,
|
||||||
session_bad_key_handler,
|
session_bad_key_handler,
|
||||||
session_channel_handler,
|
session_channel_handler,
|
||||||
@@ -568,7 +566,8 @@ async def services(request: web.Request) -> web.Response:
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
service_tags = Services.get_tags()
|
service_tags = Services.get_tags()
|
||||||
allowed = get_allowed_services(request)
|
policy = request_policy(request)
|
||||||
|
allowed = policy.services
|
||||||
if allowed is not None:
|
if allowed is not None:
|
||||||
service_tags = [t for t in service_tags if t in allowed]
|
service_tags = [t for t in service_tags if t in allowed]
|
||||||
if remote := request.query.get("remote"):
|
if remote := request.query.get("remote"):
|
||||||
@@ -581,7 +580,7 @@ async def services(request: web.Request) -> web.Response:
|
|||||||
service_data: dict[str, Any] = {**catalogue[tag]}
|
service_data: dict[str, Any] = {**catalogue[tag]}
|
||||||
if tag in services_module.PENDING:
|
if tag in services_module.PENDING:
|
||||||
service_data["pending_update"] = True
|
service_data["pending_update"] = True
|
||||||
if server_accounts_allowed(request, tag) and (server_accounts := server_account_regions(tag)) is not None:
|
if policy.allows("server_accounts", tag) and (server_accounts := server_account_regions(tag)) is not None:
|
||||||
service_data["server_accounts"] = server_accounts
|
service_data["server_accounts"] = server_accounts
|
||||||
|
|
||||||
services_info.append(service_data)
|
services_info.append(service_data)
|
||||||
@@ -589,7 +588,7 @@ async def services(request: web.Request) -> web.Response:
|
|||||||
# an import error names services outside the caller's allowlist
|
# an import error names services outside the caller's allowlist
|
||||||
load_errors = (
|
load_errors = (
|
||||||
[redact_path(re.sub(r" \([^()]*\)$", "", err)) for err in services_module.LOAD_ERRORS]
|
[redact_path(re.sub(r" \([^()]*\)$", "", err)) for err in services_module.LOAD_ERRORS]
|
||||||
if is_admin(request)
|
if policy.admin
|
||||||
else []
|
else []
|
||||||
)
|
)
|
||||||
return web.json_response({"services": services_info, "load_errors": load_errors})
|
return web.json_response({"services": services_info, "load_errors": load_errors})
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import uuid
|
|||||||
from collections import Counter, deque
|
from collections import Counter, deque
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
from unshackle.core.api.events import bus
|
from unshackle.core.api.events import bus
|
||||||
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
|
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
|
||||||
@@ -25,6 +25,9 @@ from unshackle.core.config import config
|
|||||||
from unshackle.core.remote_protocol import AuthStatus
|
from unshackle.core.remote_protocol import AuthStatus
|
||||||
from unshackle.core.tracks import Track, Tracks
|
from unshackle.core.tracks import Track, Tracks
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy
|
||||||
|
|
||||||
log = logging.getLogger("api.session")
|
log = logging.getLogger("api.session")
|
||||||
|
|
||||||
DRAIN_WARNING = "This server restarts for an update after the open downloads finish; this download continues"
|
DRAIN_WARNING = "This server restarts for an update after the open downloads finish; this download continues"
|
||||||
@@ -56,7 +59,7 @@ class SessionEntry:
|
|||||||
server_vault: bool = False # a session the client's device licenses may still take keys from the server vault
|
server_vault: bool = False # a session the client's device licenses may still take keys from the server vault
|
||||||
server_device: bool = False # its service runs on the server's lent device, so keys come only from a vault
|
server_device: bool = False # its service runs on the server's lent device, so keys come only from a vault
|
||||||
client_auth: bool = False # the login is the client's: it succeeded without a server account
|
client_auth: bool = False # the login is the client's: it succeeded without a server account
|
||||||
user_config: dict[str, Any] | None = None # the serve.users entry the session was created with
|
policy: KeyPolicy | None = field(default=None, repr=False) # the API key policy the session was created with
|
||||||
input_bridge: InputBridge | None = None
|
input_bridge: InputBridge | None = None
|
||||||
log_buffer: Any | None = None # SessionLogBuffer mirroring the service's self.log
|
log_buffer: Any | None = None # SessionLogBuffer mirroring the service's self.log
|
||||||
channel: SessionChannel = field(default_factory=SessionChannel, repr=False, compare=False)
|
channel: SessionChannel = field(default_factory=SessionChannel, repr=False, compare=False)
|
||||||
@@ -190,7 +193,7 @@ class SessionStore:
|
|||||||
creator_ip: str | None = None,
|
creator_ip: str | None = None,
|
||||||
server_account: str | None = None,
|
server_account: str | None = None,
|
||||||
cache_tag: str | None = None,
|
cache_tag: str | None = None,
|
||||||
user_config: dict[str, Any] | None = None,
|
policy: KeyPolicy | None = None,
|
||||||
server_cdm: bool = False,
|
server_cdm: bool = False,
|
||||||
server_cdm_max_height: int | None = None,
|
server_cdm_max_height: int | None = None,
|
||||||
server_vault: bool = False,
|
server_vault: bool = False,
|
||||||
@@ -227,7 +230,7 @@ class SessionStore:
|
|||||||
creator_ip=creator_ip,
|
creator_ip=creator_ip,
|
||||||
server_account=server_account,
|
server_account=server_account,
|
||||||
cache_tag=cache_tag,
|
cache_tag=cache_tag,
|
||||||
user_config=user_config,
|
policy=policy,
|
||||||
server_cdm=server_cdm,
|
server_cdm=server_cdm,
|
||||||
server_cdm_max_height=server_cdm_max_height,
|
server_cdm_max_height=server_cdm_max_height,
|
||||||
server_vault=server_vault,
|
server_vault=server_vault,
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from aiohttp import web
|
|||||||
|
|
||||||
from unshackle.core import __code_hash__, __version__
|
from unshackle.core import __code_hash__, __version__
|
||||||
from unshackle.core.api.events import bus
|
from unshackle.core.api.events import bus
|
||||||
|
from unshackle.core.api.key_policy import KeyPolicy, api_keys
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.utils.redact import redact_secrets
|
from unshackle.core.utils.redact import redact_secrets
|
||||||
|
|
||||||
@@ -36,16 +37,6 @@ CDM_SESSION_ID_LIMIT = 64
|
|||||||
CDM_DEVICE_LIMIT = 255
|
CDM_DEVICE_LIMIT = 255
|
||||||
|
|
||||||
|
|
||||||
def _users() -> dict[str, Any]:
|
|
||||||
users = (config.serve or {}).get("users")
|
|
||||||
return users if isinstance(users, dict) else {}
|
|
||||||
|
|
||||||
|
|
||||||
def _user_config(key: str | None) -> dict[str, Any] | None:
|
|
||||||
user = _users().get(key) if key else None
|
|
||||||
return user if isinstance(user, dict) else None
|
|
||||||
|
|
||||||
|
|
||||||
def configured_key(key: str | None) -> str | None:
|
def configured_key(key: str | None) -> str | None:
|
||||||
"""``key`` when the config knows it (a user API key, the master secret or the dashboard API key), else None.
|
"""``key`` when the config knows it (a user API key, the master secret or the dashboard API key), else None.
|
||||||
|
|
||||||
@@ -56,7 +47,7 @@ def configured_key(key: str | None) -> str | None:
|
|||||||
return None
|
return None
|
||||||
serve = config.serve or {}
|
serve = config.serve or {}
|
||||||
dashboard = serve.get("dashboard")
|
dashboard = serve.get("dashboard")
|
||||||
known = {str(k) for k in _users()} | {str(serve.get("api_secret") or "")}
|
known = set(api_keys()) | {str(serve.get("api_secret") or "")}
|
||||||
if isinstance(dashboard, dict) and dashboard.get("key"):
|
if isinstance(dashboard, dict) and dashboard.get("key"):
|
||||||
known.add(str(dashboard["key"]))
|
known.add(str(dashboard["key"]))
|
||||||
return key if key in known else None
|
return key if key in known else None
|
||||||
@@ -66,10 +57,7 @@ def mask_key(key: str | None) -> str:
|
|||||||
"""A display label for an API key: its configured username, else a truncated prefix."""
|
"""A display label for an API key: its configured username, else a truncated prefix."""
|
||||||
if not key:
|
if not key:
|
||||||
return "anonymous"
|
return "anonymous"
|
||||||
user = _user_config(key)
|
return KeyPolicy.of(key).username or key[:4] + "…"
|
||||||
if user and user.get("username"):
|
|
||||||
return str(user["username"])
|
|
||||||
return key[:4] + "…"
|
|
||||||
|
|
||||||
|
|
||||||
def key_id(key: str | None) -> str:
|
def key_id(key: str | None) -> str:
|
||||||
@@ -80,47 +68,6 @@ def key_id(key: str | None) -> str:
|
|||||||
return hashlib.sha256(key.encode()).hexdigest()[:12]
|
return hashlib.sha256(key.encode()).hexdigest()[:12]
|
||||||
|
|
||||||
|
|
||||||
def key_tier(key: str | None) -> str | None:
|
|
||||||
"""The tier name an API key references, when it names one that exists."""
|
|
||||||
user = _user_config(key)
|
|
||||||
tier = user.get("tier") if user else None
|
|
||||||
return str(tier) if tier else None
|
|
||||||
|
|
||||||
|
|
||||||
def key_rate_limit(key: str | None, serve: dict[str, Any] | None = None) -> int | None:
|
|
||||||
"""Requests per hour allowed for a key: its own override, else its tier's, else unlimited.
|
|
||||||
|
|
||||||
``serve`` reads a config block that is not yet the live one, as the reload validator does.
|
|
||||||
"""
|
|
||||||
if serve is None:
|
|
||||||
serve = config.serve or {}
|
|
||||||
users = serve.get("users")
|
|
||||||
user = users.get(key) if isinstance(users, dict) and key else None
|
|
||||||
if not isinstance(user, dict):
|
|
||||||
return None
|
|
||||||
own = user.get("rate_limit")
|
|
||||||
if isinstance(own, int) and own > 0:
|
|
||||||
return own
|
|
||||||
tiers = serve.get("tiers")
|
|
||||||
tier = tiers.get(user.get("tier")) if isinstance(tiers, dict) and user.get("tier") else None
|
|
||||||
limit = tier.get("rate_limit") if isinstance(tier, dict) else None
|
|
||||||
return limit if isinstance(limit, int) and limit > 0 else None
|
|
||||||
|
|
||||||
|
|
||||||
def rate_limit_error(where: str, value: Any) -> str | None:
|
|
||||||
"""Why *value* cannot serve as a rate limit, or None when it can. Unset is fine.
|
|
||||||
|
|
||||||
``key_rate_limit`` reads anything else as "no limit", so a mistyped value would silently
|
|
||||||
remove the cap the operator wrote down. It lives beside the reader so the two rules cannot
|
|
||||||
drift apart.
|
|
||||||
"""
|
|
||||||
if value is None:
|
|
||||||
return None
|
|
||||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
||||||
return f"{where}.rate_limit must be a positive whole number of requests per hour, not {value!r}"
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class KeyStats:
|
class KeyStats:
|
||||||
"""Per-key counters and the current rate-limit window."""
|
"""Per-key counters and the current rate-limit window."""
|
||||||
@@ -170,7 +117,7 @@ class ServerStats:
|
|||||||
|
|
||||||
A fixed window, not a sliding one: cheap, and an operator cap does not need the precision.
|
A fixed window, not a sliding one: cheap, and an operator cap does not need the precision.
|
||||||
"""
|
"""
|
||||||
limit = key_rate_limit(key)
|
limit = KeyPolicy.of(key).rate_limit
|
||||||
if limit is None:
|
if limit is None:
|
||||||
return None
|
return None
|
||||||
entry = self.key_stats(key)
|
entry = self.key_stats(key)
|
||||||
@@ -185,7 +132,7 @@ class ServerStats:
|
|||||||
|
|
||||||
def rate_limit_headers(self, key: str) -> dict[str, str]:
|
def rate_limit_headers(self, key: str) -> dict[str, str]:
|
||||||
"""The ``X-RateLimit-*`` headers for ``key``'s current window; none for an API key with no limit."""
|
"""The ``X-RateLimit-*`` headers for ``key``'s current window; none for an API key with no limit."""
|
||||||
limit = key_rate_limit(key)
|
limit = KeyPolicy.of(key).rate_limit
|
||||||
if limit is None:
|
if limit is None:
|
||||||
return {}
|
return {}
|
||||||
entry = self.key_stats(key)
|
entry = self.key_stats(key)
|
||||||
|
|||||||
Reference in New Issue
Block a user