refactor(api): decide the proxy of an API request in one api_proxy module

This commit is contained in:
imSp4rky
2026-12-02 20:04:07 -07:00
parent d23324e27b
commit fef6898823
8 changed files with 617 additions and 468 deletions
+294
View File
@@ -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) == {}
+16 -245
View File
@@ -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"
+1 -1
View File
@@ -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:
+9 -13
View File
@@ -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