refactor(proxies): resolve every --proxy value through one shared entry

This commit is contained in:
imSp4rky
2026-11-27 10:59:53 -07:00
parent dcfd2f66ba
commit f00f8cdc3c
14 changed files with 301 additions and 101 deletions
+51
View File
@@ -0,0 +1,51 @@
"""The dl --proxy block resolves each form through the shared proxy entry and codes its errors."""
from __future__ import annotations
from pathlib import Path
import click
import pytest
from unshackle.core.remote_protocol import APIErrorCode
pytestmark = pytest.mark.unit
def run_dl(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str) -> click.Context:
from unshackle.commands import dl as dl_module
monkeypatch.setattr(dl_module.config, "key_vaults", [])
monkeypatch.setattr(dl_module.config, "output_template", {"movies": "{title}"})
monkeypatch.setattr(dl_module.dl, "get_cdm", lambda self, *a, **k: None)
monkeypatch.setattr(dl_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
monkeypatch.setattr(dl_module.dl.cli, "_result_callback", dl_module.dl.cli._result_callback)
ctx = click.Context(dl_module.dl.cli)
ctx.invoked_subcommand = "EXAMPLE"
dl_module.dl(ctx=ctx, no_proxy=False, proxy=proxy, proxy_providers=[])
return ctx
@pytest.mark.usefixtures("example_service")
def test_dl_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
from unshackle.core.proxies import controld
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
params = run_dl(monkeypatch, tmp_path, "controld://efgh456@dns.controld.com").params
assert params["proxy"] == "http://127.0.0.1:4000"
assert (params["proxy_query"], params["proxy_provider"]) == (None, None)
@pytest.mark.usefixtures("example_service")
def test_dl_keeps_a_host_and_port_as_given(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
assert run_dl(monkeypatch, tmp_path, "nas:3128").params["proxy"] == "nas:3128"
@pytest.mark.usefixtures("example_service")
@pytest.mark.parametrize("proxy", ["nope:us", "us", "controld://bad id@dns.controld.com"])
def test_a_dl_proxy_error_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str) -> None:
from unshackle.core.run_plan import PlanError
with pytest.raises(PlanError) as raised:
run_dl(monkeypatch, tmp_path, proxy)
assert getattr(raised.value, "error_code", None) == APIErrorCode.INVALID_PROXY
+32
View File
@@ -0,0 +1,32 @@
"""The search command resolves --proxy with the same grammar as dl."""
from __future__ import annotations
from pathlib import Path
import click
import pytest
pytestmark = pytest.mark.unit
SENT = "controld://efgh456@dns.controld.com"
@pytest.mark.usefixtures("example_service")
def test_search_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
from unshackle.commands import search as search_module
from unshackle.core.proxies import controld
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
monkeypatch.setattr(search_module, "load_proxy_providers", lambda: [])
monkeypatch.setattr(search_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
ctx = click.Context(search_module.search)
ctx.invoked_subcommand = "EXAMPLE"
ctx.params = {"proxy": SENT, "no_proxy": False}
with ctx:
assert search_module.search.callback
search_module.search.callback(no_proxy=False, proxy=SENT)
assert ctx.params["proxy"] == "http://127.0.0.1:4000"
assert ctx.params["proxy_arg"] == SENT
assert ctx.params.get("proxy_query") is None
+4 -5
View File
@@ -7,7 +7,6 @@ from __future__ import annotations
import base64
import http.server
import logging
import re
import socket
import socketserver
import threading
@@ -31,7 +30,7 @@ from unshackle.core.proxies.controld import (
local_proxy,
parse_a_records,
)
from unshackle.core.proxies.resolve import REGION, resolve_proxy
from unshackle.core.proxies.resolve import REGION_QUERY, resolve_proxy, resolve_proxy_value
from unshackle.core.utilities import get_free_port
pytestmark = pytest.mark.unit
@@ -462,10 +461,10 @@ def test_a_server_gets_the_typed_proxy_only_when_this_machine_resolved_it_to_loo
@pytest.mark.parametrize("query", ["ca", "us:seattle", "us-ny", "uk1", "yul", "jfk", "res_yyz", "nordvpn:ca"])
def test_a_region_query_matches(query: str) -> None:
assert re.fullmatch(rf"(?:[a-z]+:)?{REGION}", query, re.IGNORECASE)
assert re.fullmatch(rf"(?:[a-z]+:){{0,2}}{REGION}", f"gluetun:{query}", re.IGNORECASE)
assert REGION_QUERY.fullmatch(query)
@pytest.mark.parametrize("uri", ["nas:3128", "localhost:8080", "proxy.example.com:8080", "1.2.3.4:8080", "us:1080"])
def test_a_host_and_port_is_never_a_region_query(uri: str) -> None:
assert not re.fullmatch(rf"(?:[a-z]+:){{0,2}}{REGION}", uri, re.IGNORECASE)
resolved = resolve_proxy_value(uri, [])
assert resolved.uri == uri and resolved.query is None
+24
View File
@@ -0,0 +1,24 @@
"""An import falls back to the export region for a proxy only when the region is a region code."""
from __future__ import annotations
import logging
from types import SimpleNamespace
import pytest
from unshackle.core import import_service
pytestmark = pytest.mark.unit
@pytest.mark.parametrize(("region", "proxies"), [("ca", {"all": "http://ca.proxy:8080"}), ("localhost:8080", {})])
def test_the_export_region_becomes_a_proxy_only_when_it_is_a_region(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, region: str, proxies: dict
) -> None:
monkeypatch.setattr(import_service, "resolve_proxy_arg", lambda query: f"http://{query}.proxy:8080")
ctx = SimpleNamespace(parent=SimpleNamespace(params={}))
with caplog.at_level(logging.WARNING):
session = import_service.ImportService.build_session(ctx, region) # type: ignore[arg-type]
assert session.proxies == proxies
assert ("continuing without one" in caplog.text) is not proxies
+79 -2
View File
@@ -1,21 +1,24 @@
"""Unit tests for the shared proxy dispatch that dl, search and resolve_proxy use: the provider:query
split, the named or bare provider lookup, and the line that reports which proxy provider answered."""
"""Unit tests for the shared proxy dispatch that dl, search, the REST API and the remote client use: the
provider:query split, the named or bare provider lookup, and the line that reports which proxy provider answered."""
from __future__ import annotations
import json
import logging
from collections.abc import Iterator
from contextlib import contextmanager
import pytest
from unshackle.core.proxies import Basic
from unshackle.core.proxies.proxy import Proxy
from unshackle.core.proxies.resolve import (
ResolvedProxy,
Unavailable,
describe_proxy,
pick_proxy,
resolve_proxy,
resolve_proxy_value,
split_proxy_query,
)
@@ -215,3 +218,77 @@ def test_named_query_passes_a_query_error_on_unchanged() -> None:
with pytest.raises(ValueError, match="^no server for us150$"):
pick_proxy([Strict()], "us150", "strict")
class Gluetun(Alpha):
pass
@pytest.mark.parametrize(
("value", "expected"),
[
(
"US",
ResolvedProxy(
"http://a:b@alpha.example:80", None, "us", "Using Alpha Proxy: http://xxxxx:xxxxx@alpha.example:80"
),
),
(
"Beta:CA",
ResolvedProxy("http://c:d@beta-ca.example:80", "Beta", "ca", "Using Beta Proxy via Dallas (server 12)"),
),
(
"alpha:beta:ca",
ResolvedProxy(
"http://a:b@alpha-beta.example:80",
"alpha",
"beta:ca",
"Using Alpha Proxy: http://xxxxx:xxxxx@alpha-beta.example:80",
),
),
(
"http://user:pass@proxy.example:8080",
ResolvedProxy(
"http://user:pass@proxy.example:8080",
None,
None,
"Using explicit Proxy: http://xxxxx:xxxxx@proxy.example:8080",
),
),
("localhost:8080", ResolvedProxy("localhost:8080", None, None, "Using a local proxy on port 8080")),
("1.2.3.4:3128", ResolvedProxy("1.2.3.4:3128", None, None, "Using explicit Proxy: 1.2.3.4:3128")),
("us:1080", ResolvedProxy("us:1080", None, None, "Using explicit Proxy: us:1080")),
],
)
def test_resolve_proxy_value_reads_each_form(providers: list, value: str, expected: ResolvedProxy) -> None:
providers[1].answers["beta:ca"] = "http://a:b@alpha-beta.example:80"
assert resolve_proxy_value(value, providers) == expected
def test_resolve_proxy_value_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core.proxies import controld
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
resolved = resolve_proxy_value("controld://efgh456@dns.controld.com", [])
assert resolved == ResolvedProxy("http://127.0.0.1:4000", None, None, "Using a local proxy on port 4000")
@pytest.mark.parametrize(
("value", "message"), [("us", "Getting a Proxy to us..."), ("gluetun:ca", "Connecting to VPN (ca)...")]
)
def test_the_status_wraps_only_the_provider_lookup(providers: list, value: str, message: str) -> None:
shown: list[str] = []
@contextmanager
def status(text: str) -> Iterator[None]:
shown.append(text)
yield
resolve_proxy_value(value, [*providers, Gluetun(ca="http://g.example:8888")], status=status)
resolve_proxy_value("http://proxy.example:8080", providers, status=status)
assert shown == [message]
@pytest.mark.parametrize("value", ["localhost:8080", "1.2.3.4:3128"])
def test_resolve_proxy_passes_a_host_and_port_through(providers: list, value: str) -> None:
assert resolve_proxy(value, providers) == value
+2 -3
View File
@@ -3,7 +3,6 @@
from __future__ import annotations
import datetime
import re
import socket
import ssl
import threading
@@ -19,7 +18,7 @@ from cryptography.x509.oid import NameOID
from unshackle.core.proxies import asn, surfsharkvpn
from unshackle.core.proxies.nordvpn import NordVPN
from unshackle.core.proxies.resolve import REGION
from unshackle.core.proxies.resolve import REGION_QUERY
from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN
from unshackle.core.proxies.windscribevpn import WindscribeVPN
from unshackle.core.remote_service import resolve_remote_proxy_arg
@@ -54,7 +53,7 @@ def known_networks(monkeypatch: pytest.MonkeyPatch) -> None:
)
def test_region_grammar_takes_the_selector_but_not_a_uri(value: str, is_query: bool) -> None:
"""dl and search send a value to the proxy providers only when it matches; anything else is an explicit URI."""
assert bool(re.fullmatch(rf"(?:[a-z]+:)?{REGION}", value, re.IGNORECASE)) is is_query
assert bool(REGION_QUERY.fullmatch(value)) is is_query
@pytest.mark.parametrize(
@@ -384,6 +384,23 @@ def test_local_proxy_uri_allowed_with_server_proxy_or_admin(monkeypatch, 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):
monkeypatch.setattr(handlers.socket, "getaddrinfo", lambda host, port: [(2, 1, 6, "", ("10.0.0.7", 0))])
with pytest.raises(APIError) as exc_info: