"""The server spends its own proxy subscriptions only for a key that opts in.""" import asyncio from datetime import UTC from types import SimpleNamespace import pytest from tests.remote.sessions import stub_service_build from unshackle.core.api import api_proxy, handlers, job_admission, key_policy from unshackle.core.api.errors import APIError from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.utils import ip_info pytestmark = pytest.mark.unit USERS = { "plainkey": {"username": "plain"}, "proxykey": {"username": "proxy", "server_proxy": True}, "strkey": {"username": "str", "server_proxy": "true"}, } @pytest.fixture(autouse=True) def serve_users(monkeypatch): monkeypatch.setattr(handlers.config, "serve", {"users": USERS}, raising=False) monkeypatch.setattr(handlers, "request_secret_key", lambda request: request.headers.get("X-Secret-Key")) def request(key): return SimpleNamespace(headers={"X-Secret-Key": key} if key else {}) def patch_server_region(monkeypatch, region): monkeypatch.setattr(ip_info, "get_ip_info", lambda session=None, cached=False: region and {"country": region}) @pytest.mark.parametrize( ("key", "grant"), [ ("plainkey", api_proxy.ProxyGrant(owner="plainkey")), ("proxykey", api_proxy.ProxyGrant(server_proxy=True, local_proxy=True, owner="proxykey")), ("strkey", api_proxy.ProxyGrant(owner="strkey")), ("adminkey", api_proxy.ProxyGrant(local_proxy=True, owner="adminkey")), ], ) def test_the_proxy_grant_comes_from_the_key_policy(key, grant): """Only a real yaml true grants server_proxy; a key with no entry is admin and may send a local proxy URI.""" assert handlers.proxy_grant(request(key)) == grant def test_a_list_launch_threads_the_request(monkeypatch): """A regression that stops passing the request through would re-open the proxy gate.""" seen = {} def fake_resolve(data, service, request=None): seen["request"] = request return None, [] class FakeService: def authenticate(self, cookies, credential): seen["authenticated"] = True monkeypatch.setattr(key_policy, "load_service_config", lambda service: {}) monkeypatch.setattr(handlers, "resolve_handler_proxy", fake_resolve) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers, "instantiate_service", lambda *args: FakeService()) monkeypatch.setattr("unshackle.core.login.get_cookie_jar", lambda service, profile: None) monkeypatch.setattr("unshackle.core.login.get_credentials", lambda service, profile: None) req = request("plainkey") handlers.launch_served(handlers.LIST, {}, "EXAMPLE", "some-title", None, req) assert seen["request"] is req assert seen["authenticated"] def test_search_reports_failed_proxy_check_as_invalid_proxy(monkeypatch): def failed_check(*args): raise ConnectionError("Proxy check failed: no IP lookup got through the proxy.") monkeypatch.setattr(key_policy, "load_service_config", lambda service: {}) monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: ("http://127.0.0.1:9", [])) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers, "instantiate_service", failed_check) monkeypatch.setattr("unshackle.core.login.get_cookie_jar", lambda service, profile: None) monkeypatch.setattr("unshackle.core.login.get_credentials", lambda service, profile: None) with pytest.raises(APIError) as exc_info: handlers.run_service_search({}, "EXAMPLE", "query", request("plainkey")) assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY assert exc_info.value.retryable is False class TestDownloadGates: """/api/download submissions and retries obey the same proxy policy as sessions.""" @pytest.fixture(autouse=True) def cdm_gate_open(self, monkeypatch): users = {key: {**entry, "server_cdm": True} for key, entry in USERS.items()} monkeypatch.setattr(handlers.config, "serve", {"users": users}, raising=False) def test_country_code_rejected_when_denied(self, monkeypatch): with pytest.raises(APIError) as exc_info: job_admission.enforce_download_gates({"service": "EXAMPLE", "proxy": "us"}, request("plainkey")) assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY def test_no_proxy_param_passes_when_denied(self): job_admission.enforce_download_gates({"service": "EXAMPLE"}, request("plainkey")) def test_country_code_passes_when_opted_in(self, monkeypatch): # The gate must not even try to resolve for an opted-in key: dl resolves at run time, # exactly as before the gate existed. monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: pytest.fail("providers loaded")) job_admission.enforce_download_gates({"service": "EXAMPLE", "proxy": "us"}, request("proxykey")) def test_region_mismatch_rejected_at_submit(self, monkeypatch): """A queued job reaches the same region verdict, at submission.""" patch_server_region(monkeypatch, "IN") with pytest.raises(APIError) as exc_info: job_admission.enforce_download_gates({"service": "EXAMPLE", "client_region": "gb"}, request("plainkey")) assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY def test_download_proxy_on_local_network_refused(self): with pytest.raises(APIError) as exc_info: job_admission.enforce_download_gates( {"service": "EXAMPLE", "proxy_download": "http://127.0.0.1:9"}, request("plainkey") ) assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY class TestDownloadEnforcement: """The server_proxy stamp survives from submission to the dl construction.""" @pytest.fixture def created_params(self, monkeypatch): """Drive download_handler with the job machinery faked out; capture create_job params.""" import asyncio from datetime import datetime from unshackle.core.api import download_manager as dm created = {} class FakeManager: async def start_workers(self): pass def create_job(self, service, title_id, owner_key=None, **params): created.update(params) return SimpleNamespace( job_id="job1", status=SimpleNamespace(value="queued"), created_time=datetime.now(UTC) ) monkeypatch.setattr(dm, "get_download_manager", lambda: FakeManager()) monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: "EXAMPLE") monkeypatch.setattr(job_admission, "enforce_download_gates", lambda params, request=None: None) monkeypatch.setattr(handlers.Services, "load", lambda service: SimpleNamespace()) def run(body, req): response = asyncio.run(handlers.download_handler(body, req)) assert response.status == 202 return created return run def test_client_sent_stamp_is_overwritten(self, created_params): created = created_params({"service": "EXAMPLE", "title_id": "t1", "server_proxy": True}, request("plainkey")) assert created["server_proxy"] is False def test_opted_in_key_is_stamped_true(self, created_params): created = created_params({"service": "EXAMPLE", "title_id": "t1"}, request("proxykey")) assert created["server_proxy"] is True @pytest.mark.parametrize(("key", "stamp"), [("plainkey", False), ("proxykey", True), ("adminkey", True)]) def test_the_local_proxy_stamp_records_the_key_at_submit(self, created_params, key, stamp): """A key removed by a reload before the job starts reads as admin then, so the stamp keeps the submit view.""" created = created_params({"service": "EXAMPLE", "title_id": "t1", "local_proxy": True}, request(key)) assert created["local_proxy"] is stamp @pytest.mark.parametrize(("params", "expected"), [({}, []), ({"server_proxy": True}, ["server"])]) def test_perform_download_maps_stamp_to_dl_providers(self, monkeypatch, tmp_path, params, expected): """An unstamped or denied job hands dl an empty provider list; a stamped one gets the server's list.""" from unshackle.commands import dl as dl_module from unshackle.core.api import download_manager as dm seen = {} class Stop(Exception): pass class FakeDl: cli = dl_module.dl.cli def __init__(self, **kwargs): seen.update(kwargs) raise Stop monkeypatch.setattr(dl_module, "dl", FakeDl) monkeypatch.setattr("unshackle.core.services.Services.get_path", staticmethod(lambda service: tmp_path)) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: ["server"]) with pytest.raises(Stop): dm.perform_download("job1", "EXAMPLE", "t1", dict(params)) assert seen["proxy_providers"] == expected def test_session_create_builds_service_off_the_event_loop(monkeypatch): import asyncio import json import logging import threading seen: dict = {} class RecordingBuffer(handlers.SessionLogBuffer): def __init__(self): super().__init__() seen["buffer"] = self def failed_check(*args, **kwargs): seen["thread"] = threading.get_ident() logging.getLogger("SlowProxySvc").warning("checking proxy") raise ConnectionError("Proxy check failed: no IP lookup got through the proxy.") monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service) monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: ("http://127.0.0.1:9", [])) monkeypatch.setattr(handlers, "server_account_for", lambda *args: False) monkeypatch.setattr(handlers.Services, "load", lambda service: type("SlowProxySvc", (), {})) monkeypatch.setattr(handlers, "SessionLogBuffer", RecordingBuffer) stub_service_build(monkeypatch, failed_check) response = asyncio.run(handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t"})) assert seen["thread"] != threading.get_ident() assert [r["message"] for r in seen["buffer"].since(0)] == ["checking proxy"] assert json.loads(response.body)["error_code"] == "INVALID_PROXY" def test_a_job_refused_at_start_never_runs_the_worker(monkeypatch): from datetime import datetime from unshackle.core.api.download_manager import DownloadJob, DownloadQueueManager, JobStatus async def never(job): raise AssertionError("the worker ran") manager = DownloadQueueManager() monkeypatch.setattr(manager, "run_download_async", never) job = DownloadJob( "job1", JobStatus.DOWNLOADING, datetime.now(), "EXAMPLE", "t1", {"proxy": "http://10.0.0.7:3128"}, owner_key="plainkey", ) with pytest.raises(APIError): asyncio.run(manager.execute_download(job)) assert job.status is JobStatus.FAILED assert job.error_code == "INVALID_PROXY"