mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 07:25:08 +00:00
refactor(api): decide the proxy of an API request in one api_proxy module
This commit is contained in:
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user