From fef68988233f160ac8e0c9fb605526f13a055eb6 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Wed, 2 Dec 2026 20:04:07 -0700 Subject: [PATCH] refactor(api): decide the proxy of an API request in one api_proxy module --- tests/remote/unit/test_api_proxy.py | 294 ++++++++++++++++++ .../remote/unit/test_handler_proxy_policy.py | 261 +--------------- tests/remote/unit/test_process_exit.py | 2 +- tests/remote/unit/test_remote_relay.py | 22 +- unshackle/core/api/api_proxy.py | 263 ++++++++++++++++ unshackle/core/api/download_manager.py | 9 +- unshackle/core/api/handlers.py | 188 ++--------- unshackle/core/api/job_admission.py | 46 +-- 8 files changed, 617 insertions(+), 468 deletions(-) create mode 100644 tests/remote/unit/test_api_proxy.py create mode 100644 unshackle/core/api/api_proxy.py diff --git a/tests/remote/unit/test_api_proxy.py b/tests/remote/unit/test_api_proxy.py new file mode 100644 index 00000000..a809e74e --- /dev/null +++ b/tests/remote/unit/test_api_proxy.py @@ -0,0 +1,294 @@ +"""The one proxy decision of an API request: grant, host check, tunnel, providers, region and the job recheck.""" + +import socket +from types import SimpleNamespace + +import pytest + +from unshackle.core.api import api_proxy +from unshackle.core.api.api_proxy import ProxyGrant, admit, decide, geofence_proxy, job_providers, recheck +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 + +PLAIN = ProxyGrant() +ADMIN = ProxyGrant(local_proxy=True) +SERVER_PROXY = ProxyGrant(server_proxy=True, local_proxy=True) + + +def answer(address): + """A resolver that answers every host name with ``address``.""" + return lambda host: {address} + + +def no_answer(host): + raise socket.gaierror("no answer") + + +def refusal(grant, proxy=None, client_region=None, no_proxy=False, resolver=no_answer, service="EXAMPLE"): + with pytest.raises(APIError) as exc_info: + decide(grant, service, proxy, client_region, no_proxy, resolver) + return exc_info.value + + +@pytest.fixture +def server_region(monkeypatch): + def set_region(region): + monkeypatch.setattr(ip_info, "get_ip_info", lambda session=None, cached=False: region and {"country": region}) + + return set_region + + +@pytest.fixture +def providers(monkeypatch): + """Give the server one provider that answers every country code with the proxy given.""" + + def set_proxy(proxy): + provider = SimpleNamespace(get_proxy=lambda query: proxy) + monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: [provider]) + return provider + + return set_proxy + + +@pytest.fixture +def no_providers(monkeypatch): + monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: pytest.fail("providers loaded")) + + +def test_region_mismatch_is_refused_without_naming_the_server_region(server_region): + server_region("IN") + error = refusal(PLAIN, client_region="ca") + assert error.error_code == APIErrorCode.INVALID_PROXY + assert "IN" not in error.message + assert error.details == {"service": "EXAMPLE"} + + +@pytest.mark.usefixtures("example_service") +def test_a_geoblocked_client_region_is_refused(monkeypatch, server_region): + server_region("CA") + monkeypatch.setattr(api_proxy.Services.load("EXAMPLE"), "GEOBLOCK", ("GB",), raising=False) + error = refusal(PLAIN, client_region="gb") + assert error.error_code == APIErrorCode.GEOFENCE + assert error.details == {"service": "EXAMPLE"} + + +@pytest.mark.parametrize(("region", "service"), [("CA", "EXAMPLE"), ("CA", "NOTHERE"), (None, "EXAMPLE")]) +def test_a_matching_unknown_or_relayed_region_needs_no_proxy(server_region, region, service): + """A relayed tag that this server does not install skips the local geoblock.""" + server_region(region) + assert decide(PLAIN, service, client_region="ca") == (None, []) + + +def test_a_full_uri_on_a_public_host_passes_without_server_proxy(server_region, no_providers): + server_region("IN") + assert decide(PLAIN, "EXAMPLE", "socks5://user:pass@host:1080", resolver=answer("8.8.8.8")) == ( + "socks5://user:pass@host:1080", + [], + ) + + +@pytest.mark.parametrize("proxy", ["us", "nordvpn:us"]) +def test_a_country_code_is_refused_without_server_proxy(server_region, no_providers, proxy): + server_region("IN") + error = refusal(PLAIN, proxy) + assert error.error_code == APIErrorCode.INVALID_PROXY + assert "nordvpn" not in error.message.lower() + assert error.details == {"service": "EXAMPLE"} + + +def test_no_proxy_skips_the_checks_and_loads_no_providers(no_providers): + assert decide(SERVER_PROXY, "EXAMPLE", "us", "ca", no_proxy=True) == ("us", []) + assert decide(PLAIN, "EXAMPLE", "http://127.0.0.1:8080", no_proxy=True) == ("http://127.0.0.1:8080", []) + + +def test_server_proxy_resolves_a_country_code(server_region, providers): + server_region("IN") + provider = providers("http://us.proxy:8080") + assert decide(SERVER_PROXY, "EXAMPLE", "us") == ("http://us.proxy:8080", [provider]) + + +def test_server_proxy_auto_proxies_a_client_in_another_region(server_region, providers): + server_region("IN") + provider = providers("http://ca.proxy:8080") + assert decide(SERVER_PROXY, "EXAMPLE", client_region="ca") == ("http://ca.proxy:8080", [provider]) + + +@pytest.mark.parametrize("grant", [PLAIN, ADMIN]) +def test_a_key_without_server_proxy_gets_no_auto_proxy(server_region, providers, grant): + server_region("IN") + providers("http://ca.proxy:8080") + assert refusal(grant, client_region="ca").error_code == APIErrorCode.INVALID_PROXY + + +@pytest.mark.parametrize("grant", [PLAIN, SERVER_PROXY]) +def test_no_client_region_never_refuses(server_region, monkeypatch, grant): + """An out-of-date client that reports no region is unknown and never blocked.""" + server_region("IN") + monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: []) + assert decide(grant, "EXAMPLE") == (None, []) + + +@pytest.mark.parametrize("grant", [PLAIN, SERVER_PROXY]) +def test_a_client_region_that_is_no_string_is_refused(providers, grant): + providers("http://ca.proxy:8080") + assert refusal(grant, client_region=1).error_code == APIErrorCode.INVALID_INPUT + + +@pytest.mark.parametrize("client_region", ["localhost:8080", "ftp://127.0.0.1:21", "United States"]) +def test_a_client_region_that_is_no_region_code_gets_no_proxy(server_region, monkeypatch, client_region): + server_region("IN") + monkeypatch.setattr( + api_proxy, "initialize_proxy_providers", lambda **_: [SimpleNamespace(get_proxy=lambda q: None)] + ) + assert decide(SERVER_PROXY, "EXAMPLE", client_region=client_region).proxy is None + + +@pytest.mark.parametrize( + "proxy", + [ + "http://127.0.0.1:8080", + "http://localhost:3128", + "socks5://user:pass@10.0.0.5:1080", + "https://[::1]:8443", + "http://169.254.169.254", + "socks5h://192.168.1.1:1080", + "http://198.18.0.1:8080", + "http://[2002:7f00:1::]:8080", + "http://foo.localhost:8080", + "http://127.0.0.1:8080\\@example.com", + "http://%31%32%37.0.0.1:8080", + ], +) +def test_a_local_proxy_uri_is_refused_without_server_proxy(proxy): + error = refusal(PLAIN, proxy, resolver=answer("8.8.8.8")) + assert error.error_code == APIErrorCode.INVALID_PROXY + assert "pass" not in error.message + + +@pytest.mark.parametrize("grant", [SERVER_PROXY, ADMIN]) +def test_a_local_proxy_uri_passes_with_the_local_proxy_grant(monkeypatch, grant): + monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: []) + assert decide(grant, "EXAMPLE", "http://127.0.0.1:8080").proxy == "http://127.0.0.1:8080" + + +@pytest.mark.parametrize("grant", [PLAIN, SERVER_PROXY]) +@pytest.mark.parametrize("proxy", ["127.0.0.1:8080", "localhost:3128", "ftp://127.0.0.1:21"]) +def test_a_proxy_without_an_http_or_socks_scheme_is_refused(monkeypatch, grant, proxy): + monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: []) + assert refusal(grant, proxy).error_code == APIErrorCode.INVALID_PROXY + + +def test_a_host_name_with_a_private_address_is_refused(): + assert refusal(PLAIN, "http://proxy.lan:3128", resolver=answer("10.0.0.7")).error_code == APIErrorCode.INVALID_PROXY + + +def test_a_proxy_host_that_does_not_resolve_is_refused(): + """A name that fails at check time can answer a local address when the client connects, so it is refused.""" + error = refusal(PLAIN, "http://unresolvable.invalid:3128") + assert error.error_code == APIErrorCode.INVALID_PROXY + assert error.message == "Proxy host unresolvable.invalid does not resolve" + + +def test_the_loopback_uris_the_server_builds_pass_without_server_proxy(monkeypatch): + """The check reads the client's value, so the loopback URIs that tunnel: and controld:// become pass.""" + monkeypatch.setattr(api_proxy, "tunnel_proxy", lambda tunnel_id, owner: owner and "http://u:p@127.0.0.1:5000") + assert decide(ProxyGrant(owner="key"), "EXAMPLE", "tunnel:t1").proxy == "http://u:p@127.0.0.1:5000" + + monkeypatch.setattr(api_proxy, "resolve_proxy", lambda proxy, providers: "http://127.0.0.1:5001") + assert decide(PLAIN, "EXAMPLE", "controld://resolver@dns.controld.com").proxy == "http://127.0.0.1:5001" + + +def test_a_tunnel_that_the_caller_does_not_own_is_refused(monkeypatch): + monkeypatch.setattr(api_proxy, "tunnel_proxy", lambda tunnel_id, owner: None) + assert refusal(ProxyGrant(owner="other"), "tunnel:t1").message.startswith("The tunnel for this proxy is not open") + + +@pytest.mark.parametrize("proxy", ["http://203.0.113.9:8080", "tunnel:t1", "controld://resolver@dns.controld.com"]) +def test_a_server_account_service_refuses_a_proxy_uri(proxy): + with pytest.raises(APIError) as exc_info: + decide(PLAIN, "EXAMPLE", proxy, server_account=lambda: True) + assert exc_info.value.error_code == APIErrorCode.FORBIDDEN + + +def test_the_server_account_is_asked_only_for_a_proxy_uri(providers): + providers("http://us.proxy:8080") + assert decide(SERVER_PROXY, "EXAMPLE", "us", server_account=lambda: pytest.fail("asked")).proxy == ( + "http://us.proxy:8080" + ) + + +class TestAdmit: + """A download job: the same checks for the proxy and the download proxy, tunnel: refused.""" + + def test_a_country_code_is_refused_without_server_proxy(self, no_providers): + for params in ({"proxy": "us"}, {"proxy_download": "nordvpn:us"}): + with pytest.raises(APIError) as exc_info: + admit(PLAIN, "EXAMPLE", params) + assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY + + def test_server_proxy_leaves_the_proxy_to_dl(self, no_providers): + admit(SERVER_PROXY, "EXAMPLE", {"proxy": "us", "proxy_download": "http://127.0.0.1:9", "client_region": "gb"}) + + def test_the_region_check_runs_at_submit(self, server_region): + server_region("IN") + with pytest.raises(APIError) as exc_info: + admit(PLAIN, "EXAMPLE", {"client_region": "gb"}) + assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY + + def test_the_download_proxy_gets_the_host_check_but_no_region_check(self, server_region): + server_region("CA") + admit(PLAIN, "EXAMPLE", {"proxy_download": "http://proxy.example:3128"}, answer("8.8.8.8")) + with pytest.raises(APIError) as exc_info: + admit(PLAIN, "EXAMPLE", {"proxy_download": "http://proxy.example:3128"}, answer("10.0.0.7")) + assert exc_info.value.message == "Proxy host proxy.example is not a public address" + + @pytest.mark.parametrize("key", ["proxy", "proxy_download"]) + @pytest.mark.parametrize("grant", [PLAIN, SERVER_PROXY]) + def test_a_tunnel_is_refused(self, grant, key): + with pytest.raises(APIError, match="tunnel"): + admit(grant, "EXAMPLE", {key: "tunnel:t1"}) + + def test_a_download_proxy_that_is_no_string_is_refused(self): + with pytest.raises(APIError) as exc_info: + admit(SERVER_PROXY, "EXAMPLE", {"proxy_download": 1}) + assert exc_info.value.error_code == APIErrorCode.INVALID_INPUT + + +@pytest.mark.parametrize(("stamp", "refused"), [(False, True), (True, False), (None, True)]) +@pytest.mark.parametrize("field", ["proxy", "proxy_download"]) +def test_a_job_checks_its_proxy_again_when_it_starts(field, stamp, refused): + """A host that answered public at submit and answers private at start stops a job not stamped local_proxy.""" + params = {field: "http://rebind.example:3128", "local_proxy": stamp} + recheck("EXAMPLE", params, answer("8.8.8.8")) + recheck("EXAMPLE", {**params, "no_proxy": True}, answer("127.0.0.1")) + if not refused: + recheck("EXAMPLE", params, answer("127.0.0.1")) + return + with pytest.raises(APIError) as exc_info: + recheck("EXAMPLE", params, answer("127.0.0.1")) + assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY + assert exc_info.value.message == "Proxy host rebind.example is not a public address" + + +@pytest.mark.parametrize(("stamp", "expected"), [(None, []), (False, []), ("true", []), (True, ["server"])]) +def test_only_the_server_proxy_stamp_gives_a_job_the_server_providers(monkeypatch, stamp, expected): + monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: ["server"]) + assert job_providers({"server_proxy": stamp}) == expected + + +def test_the_job_stamps_carry_the_grant(): + assert SERVER_PROXY.stamps() == {"server_proxy": True, "local_proxy": True} + assert PLAIN.stamps() == {"server_proxy": False, "local_proxy": False} + + +def test_a_geofenced_remote_service_gets_its_first_allowed_region_as_proxy(): + fenced = {"tag": "EXAMPLE", "geofence": ["US", "ca"], "geoblock": ["us"]} + assert geofence_proxy(SERVER_PROXY, {}, {"tag": "EXAMPLE", "geofence": ["US", "ca"]}) == {"proxy": "us"} + assert geofence_proxy(SERVER_PROXY, {}, fenced) == {"proxy": "ca"} + assert geofence_proxy(SERVER_PROXY, {"proxy": "gb"}, fenced) == {} + assert geofence_proxy(SERVER_PROXY, {"no_proxy": True}, fenced) == {} + assert geofence_proxy(SERVER_PROXY, {}, {"tag": "EXAMPLE"}) == {} + assert geofence_proxy(ADMIN, {}, fenced) == {} diff --git a/tests/remote/unit/test_handler_proxy_policy.py b/tests/remote/unit/test_handler_proxy_policy.py index 557884ed..003a6fc1 100644 --- a/tests/remote/unit/test_handler_proxy_policy.py +++ b/tests/remote/unit/test_handler_proxy_policy.py @@ -7,7 +7,7 @@ from types import SimpleNamespace import pytest from tests.remote.sessions import stub_service_build -from unshackle.core.api import handlers, job_admission, key_policy +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 @@ -35,136 +35,18 @@ def patch_server_region(monkeypatch, region): monkeypatch.setattr(ip_info, "get_ip_info", lambda session=None, cached=False: region and {"country": region}) -def answer(monkeypatch, address): - """Make every proxy host name resolve to ``address``.""" - monkeypatch.setattr(handlers.socket, "getaddrinfo", lambda host, port: [(2, 1, 6, "", (address, 0))]) - - -def patch_providers(monkeypatch, proxy): - """Give the server one provider that answers every country code with ``proxy``.""" - provider = SimpleNamespace(get_proxy=lambda query: proxy) - monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: [provider]) - return provider - - -def test_region_mismatch_raises(monkeypatch): - patch_server_region(monkeypatch, "IN") - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"client_region": "ca"}, "EXAMPLE", request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - assert "IN" not in exc_info.value.message - # The details must not leak the server region either. - assert exc_info.value.details == {"service": "EXAMPLE"} - - -@pytest.mark.usefixtures("example_service") -def test_geoblocked_client_region_raises(monkeypatch): - patch_server_region(monkeypatch, "CA") - service_class = handlers.Services.load("EXAMPLE") - monkeypatch.setattr(service_class, "GEOBLOCK", ("GB",), raising=False) - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"client_region": "gb"}, "EXAMPLE", request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.GEOFENCE - assert exc_info.value.details == {"service": "EXAMPLE"} - - -def test_region_match_no_proxy(monkeypatch): - patch_server_region(monkeypatch, "CA") - assert handlers.resolve_handler_proxy({"client_region": "ca"}, "EXAMPLE", request("plainkey")) == (None, []) - - -def test_relayed_tag_not_installed_here_skips_the_local_geoblock(monkeypatch): - patch_server_region(monkeypatch, "CA") - assert handlers.resolve_handler_proxy({"client_region": "ca"}, "NOTHERE", request("plainkey")) == (None, []) - - -def test_region_unknown_no_error(monkeypatch): - patch_server_region(monkeypatch, None) - assert handlers.resolve_handler_proxy({"client_region": "ca"}, "EXAMPLE", request("plainkey")) == (None, []) - - -def test_direct_uri_passes_through(monkeypatch): - patch_server_region(monkeypatch, "IN") - answer(monkeypatch, "8.8.8.8") - proxy, providers = handlers.resolve_handler_proxy( - {"proxy": "socks5://user:pass@host:1080"}, "EXAMPLE", request("plainkey") - ) - assert proxy == "socks5://user:pass@host:1080" - assert providers == [] - - -def test_country_code_rejected(monkeypatch): - patch_server_region(monkeypatch, "IN") - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"proxy": "us"}, "EXAMPLE", request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - assert "us" not in exc_info.value.details.values() - - -def test_provider_country_rejected(monkeypatch): - patch_server_region(monkeypatch, "IN") - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"proxy": "nordvpn:us"}, "EXAMPLE", request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - assert "nordvpn" not in exc_info.value.message.lower() - assert exc_info.value.details == {"service": "EXAMPLE"} - - -def test_no_proxy_short_circuits(monkeypatch): - """no_proxy skips resolution and never loads providers, even with a proxy param set.""" - monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: pytest.fail("providers loaded")) - _, providers = handlers.resolve_handler_proxy( - {"proxy": "us", "no_proxy": True, "client_region": "ca"}, "EXAMPLE", request("proxykey") - ) - assert providers == [] - - -def test_opted_in_country_code_resolves(monkeypatch): - patch_server_region(monkeypatch, "IN") - provider = patch_providers(monkeypatch, "http://us.proxy:8080") - proxy, providers = handlers.resolve_handler_proxy({"proxy": "us"}, "EXAMPLE", request("proxykey")) - assert proxy == "http://us.proxy:8080" - assert providers == [provider] - - -def test_opted_in_region_mismatch_auto_proxies(monkeypatch): - patch_server_region(monkeypatch, "IN") - patch_providers(monkeypatch, "http://ca.proxy:8080") - proxy, providers = handlers.resolve_handler_proxy({"client_region": "ca"}, "EXAMPLE", request("proxykey")) - assert proxy == "http://ca.proxy:8080" - assert providers - - -def test_absent_key_denied(monkeypatch): - patch_server_region(monkeypatch, "IN") - patch_providers(monkeypatch, "http://ca.proxy:8080") - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"client_region": "ca"}, "EXAMPLE", request("adminsecret")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - - -def test_user_without_server_proxy_denied(monkeypatch): - patch_server_region(monkeypatch, "IN") - patch_providers(monkeypatch, "http://ca.proxy:8080") - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"client_region": "ca"}, "EXAMPLE", request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - - -def test_no_region_sent_proceeds(monkeypatch): - """An out-of-date client that reports no region is unknown and never blocked.""" - patch_server_region(monkeypatch, "IN") - monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: []) - assert handlers.resolve_handler_proxy({}, "EXAMPLE", request("plainkey")) == (None, []) - assert handlers.resolve_handler_proxy({}, "EXAMPLE", request("proxykey")) == (None, []) - - -@pytest.mark.parametrize("key", ["plainkey", "proxykey"]) -def test_non_string_client_region_rejected(monkeypatch, key): - patch_providers(monkeypatch, "http://ca.proxy:8080") - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"client_region": 1}, "EXAMPLE", request(key)) - assert exc_info.value.error_code == APIErrorCode.INVALID_INPUT +@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): @@ -224,24 +106,13 @@ class TestDownloadGates: job_admission.enforce_download_gates({"service": "EXAMPLE", "proxy": "us"}, request("plainkey")) assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - def test_provider_country_rejected_when_denied(self, monkeypatch): - with pytest.raises(APIError) as exc_info: - job_admission.enforce_download_gates({"service": "EXAMPLE", "proxy": "nordvpn:us"}, request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - - def test_full_uri_passes_when_denied(self, monkeypatch): - answer(monkeypatch, "8.8.8.8") - job_admission.enforce_download_gates( - {"service": "EXAMPLE", "proxy": "socks5://user:pass@host:1080"}, request("plainkey") - ) - 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(handlers, "initialize_proxy_providers", lambda **_: pytest.fail("providers loaded")) + 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): @@ -330,7 +201,7 @@ class TestDownloadEnforcement: 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("unshackle.core.proxies.resolve.initialize_proxy_providers", lambda **_: ["server"]) + monkeypatch.setattr(api_proxy, "initialize_proxy_providers", lambda **_: ["server"]) with pytest.raises(Stop): dm.perform_download("job1", "EXAMPLE", "t1", dict(params)) @@ -369,88 +240,6 @@ def test_session_create_builds_service_off_the_event_loop(monkeypatch): assert json.loads(response.body)["error_code"] == "INVALID_PROXY" -@pytest.mark.parametrize( - "proxy", - [ - "http://127.0.0.1:8080", - "http://localhost:3128", - "socks5://user:pass@10.0.0.5:1080", - "https://[::1]:8443", - "http://169.254.169.254", - "socks5h://192.168.1.1:1080", - "http://198.18.0.1:8080", - "http://[2002:7f00:1::]:8080", - "http://foo.localhost:8080", - "http://127.0.0.1:8080\\@example.com", - "http://%31%32%37.0.0.1:8080", - ], -) -def test_local_proxy_uri_refused_without_server_proxy(proxy): - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"proxy": proxy}, "EXAMPLE", request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - assert "pass" not in exc_info.value.message # credentials never echo back - - -@pytest.mark.parametrize("key", ["proxykey", "adminkey"]) # adminkey has no serve.users entry -def test_local_proxy_uri_allowed_with_server_proxy_or_admin(monkeypatch, key): - monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: []) - proxy, _ = handlers.resolve_handler_proxy({"proxy": "http://127.0.0.1:8080"}, "EXAMPLE", request(key)) - assert proxy == "http://127.0.0.1:8080" - - -@pytest.mark.parametrize("key", ["plainkey", "proxykey"]) -@pytest.mark.parametrize("proxy", ["127.0.0.1:8080", "localhost:3128", "ftp://127.0.0.1:21"]) -def test_a_proxy_without_an_http_or_socks_scheme_is_refused(monkeypatch, key, proxy): - monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: []) - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"proxy": proxy}, "EXAMPLE", request(key)) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - - -@pytest.mark.parametrize("client_region", ["localhost:8080", "ftp://127.0.0.1:21", "United States"]) -def test_a_client_region_that_is_no_region_code_gets_no_proxy(monkeypatch, client_region): - patch_server_region(monkeypatch, "IN") - monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: [SimpleNamespace(get_proxy=lambda q: None)]) - proxy, _ = handlers.resolve_handler_proxy({"client_region": client_region}, "EXAMPLE", request("proxykey")) - assert proxy is None - - -def test_hostname_resolving_to_a_private_address_refused(monkeypatch): - answer(monkeypatch, "10.0.0.7") - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"proxy": "http://proxy.lan:3128"}, "EXAMPLE", request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - - -def test_a_proxy_host_that_does_not_resolve_is_refused(): - """A name that fails at check time can answer a local address when the client connects, so it is refused.""" - with pytest.raises(APIError) as exc_info: - handlers.resolve_handler_proxy({"proxy": "http://unresolvable.invalid:3128"}, "EXAMPLE", request("plainkey")) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - assert exc_info.value.message == "Proxy host unresolvable.invalid does not resolve" - - -@pytest.mark.parametrize(("stamp", "refused"), [(False, True), (True, False), (None, True)]) -@pytest.mark.parametrize("field", ["proxy", "proxy_download"]) -def test_a_job_checks_its_proxy_again_when_it_starts(monkeypatch, field, stamp, refused): - """A host that answered public at submit and answers private at start stops a job not stamped local_proxy.""" - params = {field: "http://rebind.example:3128", "local_proxy": stamp} - answer(monkeypatch, "8.8.8.8") - job_admission.check_job_start("EXAMPLE", params) - job_admission.check_job_start("EXAMPLE", {**params, "no_proxy": True}) - - answer(monkeypatch, "127.0.0.1") - job_admission.check_job_start("EXAMPLE", {**params, "no_proxy": True}) - if not refused: - job_admission.check_job_start("EXAMPLE", params) - return - with pytest.raises(APIError) as exc_info: - job_admission.check_job_start("EXAMPLE", params) - assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY - assert exc_info.value.message == "Proxy host rebind.example is not a public address" - - def test_a_job_refused_at_start_never_runs_the_worker(monkeypatch): from datetime import datetime @@ -459,7 +248,6 @@ def test_a_job_refused_at_start_never_runs_the_worker(monkeypatch): async def never(job): raise AssertionError("the worker ran") - answer(monkeypatch, "10.0.0.7") manager = DownloadQueueManager() monkeypatch.setattr(manager, "run_download_async", never) job = DownloadJob( @@ -468,27 +256,10 @@ def test_a_job_refused_at_start_never_runs_the_worker(monkeypatch): datetime.now(), "EXAMPLE", "t1", - {"proxy": "http://rebind.example:3128"}, + {"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" - - -def test_local_proxy_uri_ignored_under_no_proxy(): - handlers.resolve_handler_proxy({"proxy": "http://127.0.0.1:8080", "no_proxy": True}, "EXAMPLE", request("plainkey")) - - -def test_server_built_loopback_proxies_pass_without_server_proxy(monkeypatch): - """The check reads the client's value, so the loopback URIs the server builds for tunnel: and controld:// pass.""" - monkeypatch.setattr(handlers, "tunnel_proxy", lambda tunnel_id, key: "http://u:p@127.0.0.1:5000") - proxy, _ = handlers.resolve_handler_proxy({"proxy": "tunnel:abc"}, "EXAMPLE", request("plainkey")) - assert proxy == "http://u:p@127.0.0.1:5000" - - monkeypatch.setattr(handlers, "resolve_proxy", lambda proxy, providers: "http://127.0.0.1:5001") - proxy, _ = handlers.resolve_handler_proxy( - {"proxy": "controld://abc@dns.controld.com"}, "EXAMPLE", request("plainkey") - ) - assert proxy == "http://127.0.0.1:5001" diff --git a/tests/remote/unit/test_process_exit.py b/tests/remote/unit/test_process_exit.py index 69219073..24d999a4 100644 --- a/tests/remote/unit/test_process_exit.py +++ b/tests/remote/unit/test_process_exit.py @@ -928,7 +928,7 @@ def test_the_manager_keeps_a_cancelled_job_cancelled( jobs.mkdir() monkeypatch.setattr(tempfile, "tempdir", str(jobs)) monkeypatch.setattr(sys, "executable", str(worker_script(titles.server.url, tmp_path))) - monkeypatch.setattr("unshackle.core.api.job_admission.check_job_start", lambda *args: None) + monkeypatch.setattr("unshackle.core.api.api_proxy.recheck", lambda *args: None) monkeypatch.setattr(download_manager, "record_job_history", lambda job: None) async def cancel() -> Any: diff --git a/tests/remote/unit/test_remote_relay.py b/tests/remote/unit/test_remote_relay.py index 5bbd0624..e1c4fe97 100644 --- a/tests/remote/unit/test_remote_relay.py +++ b/tests/remote/unit/test_remote_relay.py @@ -131,6 +131,15 @@ def test_remote_server_rejects(remote_config, data, code): assert e.value.error_code == code +@pytest.mark.parametrize(("entry", "proxy"), [({"server_proxy": True}, {"proxy": "ca"}), ({}, {})]) +def test_a_relayed_request_gets_the_geofence_proxy_only_under_server_proxy(remote_config, monkeypatch, entry, proxy): + fenced = {**INFO, "geofence": ["ca"]} + monkeypatch.setattr(remote_service, "remote_service_list", lambda name: [fenced]) + monkeypatch.setattr(handlers, "request_policy", lambda request=None: KeyPolicy(entry)) + data = {"remote": "srv", "service": "example"} + assert asyncio.run(handlers.relay_target(data)) == ("srv", fenced, {**data, "service": "EXAMPLE", **proxy}) + + def test_remote_server_applies_the_allowlist_and_reports_an_unreachable_server(remote_config, monkeypatch): monkeypatch.setattr(handlers, "request_policy", lambda request=None: KeyPolicy({"services": ["OTHER"]})) with pytest.raises(APIError) as e: @@ -198,19 +207,6 @@ def test_an_unreachable_server_list_logs_one_warning(monkeypatch, caplog): assert [r.levelname for r in caplog.records if r.levelname in ("WARNING", "ERROR")] == ["WARNING"] -def test_a_geofenced_remote_service_gets_its_first_allowed_region_as_proxy(monkeypatch): - monkeypatch.setattr(handlers, "request_policy", lambda request=None: KeyPolicy({"server_proxy": True})) - fenced = {"tag": "EXAMPLE", "geofence": ["US", "ca"], "geoblock": ["us"]} - assert handlers.geofence_proxy({}, {"tag": "EXAMPLE", "geofence": ["US", "ca"]}) == {"proxy": "us"} - assert handlers.geofence_proxy({}, fenced) == {"proxy": "ca"} - assert handlers.geofence_proxy({"proxy": "gb"}, fenced) == {} - assert handlers.geofence_proxy({"no_proxy": True}, fenced) == {} - assert handlers.geofence_proxy({}, INFO) == {} - - monkeypatch.setattr(handlers, "request_policy", lambda request=None: KeyPolicy({})) - assert handlers.geofence_proxy({}, fenced) == {} - - def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatch): import logging diff --git a/unshackle/core/api/api_proxy.py b/unshackle/core/api/api_proxy.py new file mode 100644 index 00000000..f7000b1c --- /dev/null +++ b/unshackle/core/api/api_proxy.py @@ -0,0 +1,263 @@ +"""The proxy of an API request, decided in one place from the caller's grant and the values the request sends.""" + +import logging +import re +import socket +from collections.abc import Callable, Iterable +from contextlib import suppress +from dataclasses import dataclass +from typing import Any, NamedTuple +from urllib.parse import urlsplit + +from unshackle.core.api.errors import APIError +from unshackle.core.api.sanitize import sanitize_log +from unshackle.core.proxies.resolve import REGION_QUERY, initialize_proxy_providers, is_loopback, resolve_proxy +from unshackle.core.remote_protocol import APIErrorCode +from unshackle.core.services import Services +from unshackle.core.tunnel import is_ip_literal, is_public_ip, tunnel_proxy +from unshackle.core.utils.redact import redact_text + +log = logging.getLogger("api") + +PROXY_URI = re.compile(r"^(https?://|socks)") +Resolver = Callable[[str], Iterable[str]] + + +def system_resolver(host: str) -> set[str]: + """The addresses that the system resolver gives for ``host``; raises socket.gaierror when it gives none.""" + return {str(info[4][0]) for info in socket.getaddrinfo(host, None)} + + +@dataclass(frozen=True) +class ProxyGrant: + """What the caller's API key may do with a proxy on one service. + + ``server_proxy`` spends the server's proxy providers, ``local_proxy`` allows a URI on the server's own network, + and ``owner`` is the API key a tunnel must have. + """ + + server_proxy: bool = False + local_proxy: bool = False + owner: str | None = None + + def stamps(self) -> dict[str, bool]: + """The job keys that carry the grant from admission to the worker, which a later config reload cannot widen.""" + return {"server_proxy": self.server_proxy, "local_proxy": self.local_proxy} + + +class ProxyDecision(NamedTuple): + """The proxy URI a request runs with, or None, and the proxy providers its service gets.""" + + proxy: str | None + providers: list + + +def host_refusal(proxy: str, resolver: Resolver = system_resolver) -> str | None: + """Why an http(s) or socks proxy URI may reach the server's own machine or network, or None when it cannot. + + The host must be a plain DNS name or an IP literal: an HTTP client that follows the WHATWG URL standard + reads a backslash or a percent-escape in the authority differently from ``urlsplit``. + """ + if not PROXY_URI.match(proxy): + return None + try: + host = urlsplit(proxy).hostname or "" + except ValueError: + host = "" + literal = is_ip_literal(host) + if "\\" in proxy or not (literal or re.fullmatch(r"[a-z0-9._-]+", host)): + return "Proxy URI has no plain host name or IP address" + if literal or is_loopback(proxy): + addresses: Iterable[str] = {host} + else: + try: + addresses = set(resolver(host)) + except (socket.gaierror, UnicodeError): + return f"Proxy host {sanitize_log(host)} does not resolve" + # shortcut: the HTTP client resolves the name again when it connects, so a name whose answer changes after + # this check still reaches a local address; pin the checked IP into http and socks URIs (an https proxy needs + # its name for TLS) when a client that controls its own DNS is in scope. + if not all(is_public_ip(address) for address in addresses): + return f"Proxy host {sanitize_log(host)} is not a public address" + return None + + +def decide( + grant: ProxyGrant, + service: str, + proxy: Any = None, + client_region: Any = None, + no_proxy: bool = False, + resolver: Resolver = system_resolver, + server_account: Callable[[], bool] = lambda: False, +) -> ProxyDecision: + """The proxy and the proxy providers for a request, or the APIError of the first refusal. + + ``server_account`` tells whether the service runs on a server account; it is asked only for a proxy URI. + + Without ``server_proxy`` the proxy-provider list stays empty, so the server refuses a country code, and a client + in another region must send a full proxy URI or ``no_proxy``. The list reaches ``ContextData.proxy_providers``, + so the same grant also governs the geofence auto-proxy in ``Service.__init__``. ``client_region`` is what the client + reports: an identifier, not a security boundary. No region, or an unknown one on either side, never refuses. + """ + resolved = proxy + if ( + proxy + and (PROXY_URI.match(str(proxy)) or str(proxy).startswith(("controld://", "tunnel:"))) + and server_account() + ): + raise APIError( + APIErrorCode.FORBIDDEN, + "A server-account service takes a country code or no proxy, not a proxy URI", + details={"service": service}, + ) + + if isinstance(proxy, str) and not no_proxy and not grant.local_proxy: + refusal = host_refusal(proxy, resolver) + if refusal: + raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": service}) + + if isinstance(proxy, str) and proxy.startswith("tunnel:") and not no_proxy: + resolved = tunnel_proxy(proxy.removeprefix("tunnel:"), grant.owner) + if not resolved: + raise APIError( + APIErrorCode.INVALID_PROXY, + "The tunnel for this proxy is not open. Run the command again.", + details={"service": service}, + ) + + providers: list = initialize_proxy_providers(quiet=True) if grant.server_proxy and not no_proxy else [] + + if resolved and not no_proxy: + try: + resolved = resolve_proxy(resolved, providers) + except ValueError as e: + if grant.server_proxy: + raise APIError( + APIErrorCode.INVALID_PROXY, + f"Proxy error: {redact_text(str(e))}", + details={"proxy": redact_text(proxy), "service": service}, + ) from e + raise APIError( + APIErrorCode.INVALID_PROXY, + "This server does not resolve country codes into proxies, pass a full proxy URI", + details={"service": service}, + ) from None + if not PROXY_URI.match(resolved or ""): + raise APIError( + APIErrorCode.INVALID_PROXY, + "Proxy URI has no http, https or socks scheme", + details={"service": service}, + ) + + if client_region is not None and not isinstance(client_region, str): + raise APIError( + APIErrorCode.INVALID_INPUT, + "client_region must be a string country code.", + details={"service": service}, + ) + + if not resolved and not no_proxy and client_region and (providers or not grant.server_proxy): + resolved = region_proxy(grant, service, client_region, providers) + + return ProxyDecision(resolved, providers) + + +def region_proxy(grant: ProxyGrant, service: str, client_region: str, providers: list) -> str | None: + """The auto-proxy for a client in ``client_region`` that sends no proxy, after the geoblock and region checks.""" + try: + from unshackle.core.utils.ip_info import get_ip_info + + server_ip_info = get_ip_info(None, cached=True) + server_region = server_ip_info.get("country", "").lower() if server_ip_info else None + except Exception as e: + log.debug(f"Server region lookup failed: {e!r}") + server_region = None + + geoblock: Any = () + with suppress(KeyError): # a relayed tag need not be installed on this server + geoblock = getattr(Services.load(service), "GEOBLOCK", ()) or () + if client_region.lower() in {x.lower() for x in geoblock}: + raise APIError( + APIErrorCode.GEOFENCE, + f"Service is not available in your region ({client_region.upper()})", + details={"service": service}, + ) + + in_client_region = bool(server_region) and server_region == client_region.lower() + if not grant.server_proxy: + if server_region and not in_client_region: + raise APIError( + APIErrorCode.INVALID_PROXY, + "This server is in a different region from yours, pass --proxy or --no-proxy", + details={"service": service}, + ) + elif in_client_region: + log.info(f"Server already in client region '{sanitize_log(client_region)}', no proxy needed") + elif REGION_QUERY.fullmatch(client_region): + try: + proxy = resolve_proxy(client_region, providers) + log.info(f"Using server proxy for client region '{sanitize_log(client_region)}'") + return proxy + except ValueError: + log.debug(f"No server proxy available for client region '{sanitize_log(client_region)}'") + return None + + +def admit( + grant: ProxyGrant, + service: str, + params: dict[str, Any], + resolver: Resolver = system_resolver, + server_account: Callable[[], bool] = lambda: False, +) -> None: + """Refuse the proxy values of a download job that ``grant`` does not allow. + + A tunnel belongs to one --remote client run, so a job refuses it. Without ``server_proxy`` the proxy and the + download proxy get the checks of :func:`decide`; with it, dl resolves them when the job runs. + """ + download = params.get("proxy_download") + if download is not None and not isinstance(download, str): + raise APIError(APIErrorCode.INVALID_INPUT, "proxy_download must be a string.") + if any(str(params.get(key) or "").startswith("tunnel:") for key in ("proxy", "proxy_download")): + raise APIError( + APIErrorCode.INVALID_PROXY, + "A download job cannot use a tunnel: proxy, because a tunnel belongs to one --remote client run.", + ) + if grant.server_proxy: + return + no_proxy = params.get("no_proxy", False) + decide(grant, service, params.get("proxy"), params.get("client_region"), no_proxy, resolver, server_account) + if download: + decide(grant, service, download, None, no_proxy, resolver, server_account) + + +def recheck(service: str, params: dict[str, Any], resolver: Resolver = system_resolver) -> None: + """INVALID_PROXY when the proxy of a queued job now reaches the server's own network. + + DNS can change between admission and start, so a job runs the host check again when it starts, under the + ``local_proxy`` stamp of its admission. + """ + if params.get("no_proxy") or params.get("local_proxy"): + return + for key in ("proxy", "proxy_download"): + value = params.get(key) + if isinstance(value, str) and (refusal := host_refusal(value, resolver)): + raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": service}) + + +def job_providers(params: dict[str, Any]) -> list: + """The proxy providers a job's dl gets: the server's list only under the ``server_proxy`` stamp.""" + return initialize_proxy_providers(quiet=True) if params.get("server_proxy") is True else [] + + +def geofence_proxy(grant: ProxyGrant, data: dict[str, Any], info: dict) -> dict[str, Any]: + """``{"proxy": region}`` for a geofenced remote service the request sends no proxy for; else {}. + + The relay's counterpart of a local service's geofence auto-proxy, under the same ``server_proxy`` grant. + """ + if data.get("proxy") or data.get("no_proxy") or not grant.server_proxy: + return {} + 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] + return {"proxy": fence[0]} if fence else {} diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index 08604c19..8b3d80c6 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -396,15 +396,14 @@ def perform_download( if params.pop(banned, None) is not None: log.warning(f"Ignoring '{banned}' in API download parameters; post-scripts are config-only") + from unshackle.core.api.api_proxy import job_providers from unshackle.core.api.handlers import DL_TRANSPORT_KEYS, instantiate_service, relay_label from unshackle.core.launch import launch - from unshackle.core.proxies.resolve import initialize_proxy_providers from unshackle.core.run_plan import RunStopped, api_plan ctx = api_plan(params, client_sent_keys(params)).context(dl.cli, service) launch(ctx, {"client_argv": f"{relay_label(params)} download job {job_id}"}) - providers = initialize_proxy_providers(quiet=True) if params.get("server_proxy") is True else [] - dl_instance = dl(ctx=ctx, proxy_providers=providers, **ctx.params) + dl_instance = dl(ctx=ctx, proxy_providers=job_providers(params), **ctx.params) dl_instance.archive_scope = archive_scope dl_instance.archive_cache = archive_cache # Per-request credential ("user:pass"); feed it into the map get_credentials() reads so a @@ -778,9 +777,9 @@ class DownloadQueueManager: log.info(f"Executing download for job {job.job_id}") try: - from unshackle.core.api.job_admission import check_job_start + from unshackle.core.api.api_proxy import recheck - await asyncio.to_thread(check_job_start, job.service, job.parameters) + await asyncio.to_thread(recheck, job.service, job.parameters) output_files = await self.run_download_async(job) job.status = JobStatus.COMPLETED job.output_files = output_files diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 96b9514c..ab7366e2 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -4,7 +4,6 @@ import functools import json import logging import re -import socket import threading import time import uuid @@ -18,13 +17,12 @@ from functools import partial from http.cookiejar import CookieJar from pathlib import Path from typing import Any, Final, Literal, NamedTuple, Optional -from urllib.parse import urlsplit import click from aiohttp import web from unshackle.core import login -from unshackle.core.api import licence_cap, server_keys +from unshackle.core.api import api_proxy, licence_cap, server_keys from unshackle.core.api.compression import InflateLimitError, safe_inflate from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception from unshackle.core.api.input_bridge import InputBridge, NoUserBridge @@ -59,7 +57,6 @@ from unshackle.core.drm import cbcs, monalisa_drm, real_kids, whole_file_cipher from unshackle.core.drm.discovery import ensure_track_drm from unshackle.core.launch import LaunchKeys, served_context from unshackle.core.manifests.snapshot import capture -from unshackle.core.proxies.resolve import REGION_QUERY, initialize_proxy_providers, is_loopback, resolve_proxy from unshackle.core.remote_protocol import ( HEALTH_ROUTE, APIErrorCode, @@ -94,8 +91,6 @@ from unshackle.core.tunnel import ( MAX_TUNNELS, TUNNELS, Tunnel, - is_ip_literal, - is_public_ip, tunnel_proxy, ) from unshackle.core.utilities import call_licence, declared_kwargs @@ -450,18 +445,6 @@ def remote_server(data: dict[str, Any], request: web.Request | None = None) -> t return name, info -def geofence_proxy(data: dict[str, Any], info: dict, request: web.Request | None = None) -> dict[str, Any]: - """``{"proxy": region}`` for a geofenced remote service the request sends no proxy for; else {}. - - 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 request_policy(request).allows("server_proxy"): - return {} - 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] - return {"proxy": fence[0]} if fence else {} - - async def relay_target( data: dict[str, Any], request: web.Request | None = None ) -> tuple[str | None, dict | None, dict[str, Any]]: @@ -473,7 +456,8 @@ async def relay_target( if relay is None: return None, None, data server, info = relay - return server, info, {**data, "service": info["tag"], **geofence_proxy(data, info, request)} + fence = api_proxy.geofence_proxy(proxy_grant(request), data, info) + return server, info, {**data, "service": info["tag"], **fence} def relay_label(data: dict[str, Any]) -> str: @@ -3402,158 +3386,28 @@ async def get_validated_session(session_id: str, request: web.Request | None) -> return session -PROXY_URI = re.compile(r"^(https?://|socks)") - - -def local_proxy_refusal(proxy: str) -> str | None: - """Why an http(s) or socks proxy URI may reach the server's own machine or network, or None when it cannot. - - The host must be a plain DNS name or an IP literal: an HTTP client that follows the WHATWG URL standard - reads a backslash or a percent-escape in the authority differently from ``urlsplit``. - """ - if not PROXY_URI.match(proxy): - return None - try: - host = urlsplit(proxy).hostname or "" - except ValueError: - host = "" - literal = is_ip_literal(host) - if "\\" in proxy or not (literal or re.fullmatch(r"[a-z0-9._-]+", host)): - return "Proxy URI has no plain host name or IP address" - if literal or is_loopback(proxy): - addresses = {host} - else: - try: - addresses = {str(info[4][0]) for info in socket.getaddrinfo(host, None)} - except (socket.gaierror, UnicodeError): - return f"Proxy host {sanitize_log(host)} does not resolve" - # shortcut: the HTTP client resolves the name again when it connects, so a name whose answer changes after this - # check still reaches a local address; pin the checked IP into http and socks URIs (an https proxy needs its name - # for TLS) when a client that controls its own DNS is in scope. - if not all(is_public_ip(address) for address in addresses): - return f"Proxy host {sanitize_log(host)} is not a public address" - return None +def proxy_grant(request: web.Request | None = None) -> api_proxy.ProxyGrant: + """The proxy grant of the caller's API key.""" + policy = request_policy(request) + return api_proxy.ProxyGrant( + server_proxy=policy.allows("server_proxy"), + local_proxy=policy.local_proxy, + owner=request_secret_key(request) if request else None, + ) def resolve_handler_proxy( data: dict[str, Any], normalized_service: str, request: web.Request | None = None -) -> tuple[str | None, list]: - """Get the proxy and the proxy providers for an API request. - - ``server_proxy`` on the calling API key decides whether the server spends its own proxy - subscriptions on this client. Without it the proxy-provider list stays empty, so the server - rejects a country code in ``proxy``, and a client in another region must send a full proxy - URI or ``no_proxy``. The returned list reaches ``ContextData.proxy_providers``, so the same gate - also governs the geofence auto-proxy in ``Service.__init__``. - - The client region is the client-reported ``client_region`` field: an identifier, not a - security boundary, because the spend gate is ``server_proxy`` on the API key. A client that - reports no region, and an unknown region on either side, never blocks the request. - """ - proxy_param = data.get("proxy") - no_proxy = data.get("no_proxy", False) - proxy_providers: list = [] - policy = request_policy(request) - allowed = policy.allows("server_proxy") - - if ( - proxy_param - and (PROXY_URI.match(str(proxy_param)) or str(proxy_param).startswith(("controld://", "tunnel:"))) - and server_account_for(policy, normalized_service) - ): - raise APIError( - APIErrorCode.FORBIDDEN, - "A server-account service takes a country code or no proxy, not a proxy URI", - details={"service": normalized_service}, - ) - - if isinstance(proxy_param, str) and not no_proxy and not policy.local_proxy: - refusal = local_proxy_refusal(proxy_param) - if refusal: - raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": normalized_service}) - - if isinstance(proxy_param, str) and proxy_param.startswith("tunnel:") and not no_proxy: - proxy_param = tunnel_proxy( - proxy_param.removeprefix("tunnel:"), request_secret_key(request) if request else None - ) - if not proxy_param: - raise APIError( - APIErrorCode.INVALID_PROXY, - "The tunnel for this proxy is not open. Run the command again.", - details={"service": normalized_service}, - ) - - if allowed and not no_proxy: - proxy_providers = initialize_proxy_providers(quiet=True) - - if proxy_param and not no_proxy: - try: - proxy_param = resolve_proxy(proxy_param, proxy_providers) - except ValueError as e: - if allowed: - raise APIError( - APIErrorCode.INVALID_PROXY, - f"Proxy error: {redact_text(str(e))}", - details={"proxy": redact_text(data.get("proxy")), "service": normalized_service}, - ) from e - raise APIError( - APIErrorCode.INVALID_PROXY, - "This server does not resolve country codes into proxies, pass a full proxy URI", - details={"service": normalized_service}, - ) from None - if not PROXY_URI.match(proxy_param or ""): - raise APIError( - APIErrorCode.INVALID_PROXY, - "Proxy URI has no http, https or socks scheme", - details={"service": normalized_service}, - ) - - client_region = data.get("client_region") - if client_region is not None and not isinstance(client_region, str): - raise APIError( - APIErrorCode.INVALID_INPUT, - "client_region must be a string country code.", - details={"service": normalized_service}, - ) - - if not proxy_param and not no_proxy and client_region and (proxy_providers or not allowed): - try: - from unshackle.core.utils.ip_info import get_ip_info - - server_ip_info = get_ip_info(None, cached=True) - server_region = server_ip_info.get("country", "").lower() if server_ip_info else None - except Exception as e: - log.debug(f"Server region lookup failed: {e!r}") - server_region = None - - geoblock: Any = () - with suppress(KeyError): # a relayed tag need not be installed on this server - geoblock = getattr(Services.load(normalized_service), "GEOBLOCK", ()) or () - if client_region.lower() in {x.lower() for x in geoblock}: - raise APIError( - APIErrorCode.GEOFENCE, - f"Service is not available in your region ({client_region.upper()})", - details={"service": normalized_service}, - ) - - in_client_region = bool(server_region) and server_region == client_region.lower() - if not allowed: - if server_region and not in_client_region: - raise APIError( - APIErrorCode.INVALID_PROXY, - "This server is in a different region from yours, pass --proxy or --no-proxy", - details={"service": normalized_service}, - ) - elif in_client_region: - log.info(f"Server already in client region '{sanitize_log(client_region)}', no proxy needed") - elif REGION_QUERY.fullmatch(client_region): - try: - proxy_param = resolve_proxy(client_region, proxy_providers) - log.info(f"Using server proxy for client region '{sanitize_log(client_region)}'") - except ValueError: - log.debug(f"No server proxy available for client region '{sanitize_log(client_region)}'") - - return proxy_param, proxy_providers +) -> api_proxy.ProxyDecision: + """The proxy and the proxy providers for an API request, from :func:`api_proxy.decide`.""" + return api_proxy.decide( + proxy_grant(request), + normalized_service, + data.get("proxy"), + data.get("client_region"), + data.get("no_proxy", False), + server_account=lambda: server_account_for(request_policy(request), normalized_service), + ) def handle_proxy_license( diff --git a/unshackle/core/api/job_admission.py b/unshackle/core/api/job_admission.py index a3375099..bb75e019 100644 --- a/unshackle/core/api/job_admission.py +++ b/unshackle/core/api/job_admission.py @@ -9,7 +9,7 @@ from typing import Any import click from aiohttp import web -from unshackle.core.api import handlers, licence_cap +from unshackle.core.api import api_proxy, handlers, licence_cap from unshackle.core.api.download_manager import plan_keys, stamped_keys from unshackle.core.api.errors import APIError from unshackle.core.config import config @@ -103,9 +103,7 @@ def job_spec(data: dict[str, Any], server: str | None, request: web.Request | No handlers.cast_or_refuse(cli_params, click.Context(click.Command(service)), options) handlers.warn_ignored(ignored) params["service_params"] = options - policy = handlers.request_policy(request) - params["server_proxy"] = policy.allows("server_proxy") - params["local_proxy"] = policy.local_proxy + params.update(handlers.proxy_grant(request).stamps()) return JobSpec(service, data["title_id"], params) @@ -226,9 +224,9 @@ def enforce_download_gates(params: dict[str, Any], request: web.Request | None = A download job licenses with the server CDM, so the API key needs ``server_cdm`` for the service, and an API key with its own device config for the service gets a refusal. Under ``server_cdm_max_height`` the job must set a quality at or - under the cap, no ``best_available`` and no HYBRID range. Without ``server_proxy`` a proxy must be a full URI or - nothing, as in :func:`resolve_handler_proxy`. A ``cdm`` override needs ``serve.cdm_overrides`` (a device list, - or ``true`` for any), and a ``credential`` needs ``serve.allow_job_credentials``. + under the cap, no ``best_available`` and no HYBRID range. The proxy values pass :func:`api_proxy.admit`. A ``cdm`` + override needs ``serve.cdm_overrides`` (a device list, or ``true`` for any), and a ``credential`` needs + ``serve.allow_job_credentials``. """ service = params.get("service") policy = handlers.request_policy(request) @@ -244,22 +242,10 @@ def enforce_download_gates(params: dict[str, Any], request: web.Request | None = ) licence_cap.check_job(policy.max_height(service), params) - if params.get("proxy_download") is not None and not isinstance(params["proxy_download"], str): - raise APIError(APIErrorCode.INVALID_INPUT, "proxy_download must be a string.") - - if any(str(params.get(key) or "").startswith("tunnel:") for key in ("proxy", "proxy_download")): - raise APIError( - APIErrorCode.INVALID_PROXY, - "A download job cannot use a tunnel: proxy, because a tunnel belongs to one --remote client run.", - ) - - if not policy.allows("server_proxy"): - handlers.resolve_handler_proxy(params, service or "", request) - if params.get("proxy_download"): - # the download proxy is gated like the main one: a full URI or nothing, never a server provider - handlers.resolve_handler_proxy( - {**params, "proxy": params["proxy_download"], "client_region": None}, service or "", request - ) + tag = service or "" + api_proxy.admit( + handlers.proxy_grant(request), tag, params, server_account=lambda: handlers.server_account_for(policy, tag) + ) requested_cdm = params.get("cdm") if requested_cdm: @@ -278,20 +264,6 @@ def enforce_download_gates(params: dict[str, Any], request: web.Request | None = raise APIError(APIErrorCode.FORBIDDEN, "Per-request credentials are not permitted for API downloads.") -def check_job_start(service: str, params: dict[str, Any]) -> None: - """INVALID_PROXY when a queued job's proxy now reaches the server's own network. - - Admission resolved the proxy host when the client submitted the job, so the job runs the same check again when it - starts. The ``local_proxy`` stamp keeps the API key's right of admission, which a later config reload cannot widen. - """ - if params.get("no_proxy") or params.get("local_proxy"): - return - for key in ("proxy", "proxy_download"): - value = params.get(key) - if isinstance(value, str) and (refusal := handlers.local_proxy_refusal(value)): - raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": service}) - - def service_dl_defaults(service: str) -> dict[str, Any]: """The ``services..dl`` values that name an API download parameter, keyed as the API names them.""" result: dict[str, Any] = {}