"""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) == {}