forked from kenzuya/unshackle
fix(proxy): check the proxy exit IP before any service request
A dead proxy, or one that exits from this machine's IP, now fails with INVALID_PROXY instead of retrying every request; remote session create also builds the service off the event loop so a stuck check cannot block the server.
This commit is contained in:
@@ -18,7 +18,7 @@ from typing import Any, Dict, Iterable, List, Optional
|
||||
from aiohttp import web
|
||||
|
||||
from unshackle.core.api.compression import safe_inflate
|
||||
from unshackle.core.api.errors import APIError, APIErrorCode, handle_api_exception
|
||||
from unshackle.core.api.errors import APIError, APIErrorCode, categorize_exception, handle_api_exception
|
||||
from unshackle.core.api.input_bridge import AuthStatus, InputBridge
|
||||
from unshackle.core.api.sanitize import safe_cache_key, sanitize_log
|
||||
from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs
|
||||
@@ -358,6 +358,8 @@ def run_service_search(
|
||||
|
||||
try:
|
||||
service_instance = instantiate_service(parent_ctx, service_module, query)
|
||||
except ConnectionError as exc:
|
||||
raise categorize_exception(exc, {"service": normalized_service}) from exc
|
||||
except Exception as exc:
|
||||
raise APIError(
|
||||
APIErrorCode.SERVICE_ERROR,
|
||||
@@ -2947,22 +2949,26 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
|
||||
if region is not None and not (isinstance(region, str) and re.fullmatch(r"[A-Za-z]{2}", region)):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "proxy_region must be a two-letter country code.")
|
||||
if region is None and data.get("no_proxy"):
|
||||
region = server_region()
|
||||
region = await asyncio.to_thread(server_region)
|
||||
profile = next_server_profile(normalized_service, region)
|
||||
log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}")
|
||||
|
||||
log_buffer = None if server_account else SessionLogBuffer()
|
||||
service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service)
|
||||
with capture_service_logs(service_class_name, log_buffer):
|
||||
service_instance, cookies, credential = create_service_instance(
|
||||
normalized_service,
|
||||
title_id,
|
||||
data,
|
||||
proxy_param,
|
||||
proxy_providers,
|
||||
profile,
|
||||
server_account=server_account,
|
||||
)
|
||||
|
||||
def build_service() -> Any:
|
||||
with capture_service_logs(service_class_name, log_buffer):
|
||||
return create_service_instance(
|
||||
normalized_service,
|
||||
title_id,
|
||||
data,
|
||||
proxy_param,
|
||||
proxy_providers,
|
||||
profile,
|
||||
server_account=server_account,
|
||||
)
|
||||
|
||||
service_instance, cookies, credential = await asyncio.to_thread(build_service)
|
||||
if log_buffer:
|
||||
service_instance.log = SessionLogMirror(service_instance.log, log_buffer)
|
||||
|
||||
|
||||
@@ -34,12 +34,12 @@ from unshackle.core.session import (
|
||||
RETRY_METHODS,
|
||||
STATUS_FORCELIST,
|
||||
)
|
||||
from unshackle.core.title_cacher import TitleCacher, get_account_hash, get_region_from_proxy
|
||||
from unshackle.core.title_cacher import TitleCacher, get_account_hash
|
||||
from unshackle.core.titles import Title_T, Titles_T, remap_titles
|
||||
from unshackle.core.tracks import Chapters, Tracks
|
||||
from unshackle.core.tracks.video import Video
|
||||
from unshackle.core.utilities import declared_kwargs
|
||||
from unshackle.core.utils.ip_info import get_ip_info
|
||||
from unshackle.core.utils.ip_info import get_ip_info, verify_proxy_exit
|
||||
from unshackle.core.utils.redact import mask_proxy
|
||||
|
||||
# Default (connect, read) timeout for the requests path, mirroring RnetSession's
|
||||
@@ -280,13 +280,9 @@ class Service(metaclass=ABCMeta):
|
||||
# requests authenticate from the credentials embedded in the proxy URL.
|
||||
# A manual header here was malformed (no "Basic " scheme) and broke
|
||||
# plaintext-http forward-proxy requests with HTTP 407.
|
||||
# Always verify proxy IP - proxies can change exit nodes
|
||||
try:
|
||||
proxy_ip_info = get_ip_info(self.session)
|
||||
self.current_region = proxy_ip_info.get("country", "").lower() if proxy_ip_info else None
|
||||
except Exception as e:
|
||||
self.log.warning(f"Failed to verify proxy IP: {e}")
|
||||
self.current_region = get_region_from_proxy(proxy)
|
||||
# Verify the proxy IP every time, because a proxy can change its exit node. A dead
|
||||
# proxy fails here, not after every service request has used up its retries.
|
||||
self.current_region = verify_proxy_exit(self.session).get("country")
|
||||
else:
|
||||
# No proxy, use cached IP info for title caching (non-critical)
|
||||
try:
|
||||
|
||||
@@ -265,36 +265,6 @@ class TitleCacher:
|
||||
self.log.debug(f"Cached {provider_name} data for {title_id}")
|
||||
|
||||
|
||||
def get_region_from_proxy(proxy_url: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
Extract region identifier from proxy URL.
|
||||
|
||||
Args:
|
||||
proxy_url: The proxy URL string
|
||||
|
||||
Returns:
|
||||
Region identifier or None
|
||||
"""
|
||||
if not proxy_url:
|
||||
return None
|
||||
|
||||
import re
|
||||
|
||||
nord_match = re.search(r"([a-z]{2})\d+\.nordvpn", proxy_url.lower())
|
||||
if nord_match:
|
||||
return nord_match.group(1)
|
||||
|
||||
cc_match = re.search(r"([a-z]{2})[-_]", proxy_url.lower())
|
||||
if cc_match:
|
||||
return cc_match.group(1)
|
||||
|
||||
subdomain_match = re.search(r"://([a-z]{2})\.", proxy_url.lower())
|
||||
if subdomain_match:
|
||||
return subdomain_match.group(1)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_account_hash(credential) -> Optional[str]:
|
||||
"""
|
||||
Make a hash for account identification.
|
||||
|
||||
@@ -8,14 +8,15 @@ import requests
|
||||
|
||||
from unshackle.core.cacher import Cacher
|
||||
|
||||
CACHE_KEY = "ip_info_v3"
|
||||
CACHE_KEY = "ip_info_v4"
|
||||
CACHE_TTL = 86400 # 24 hours
|
||||
PROVIDER_STATE_KEY = "ip_provider_state"
|
||||
RATE_LIMIT_COOLDOWN = 300 # 5 minutes
|
||||
REQUEST_TIMEOUT = 10
|
||||
|
||||
# Only these keys are persisted to the global cache.
|
||||
GEO_CACHE_KEYS = ("country", "country_code")
|
||||
# Only these keys are persisted to the global cache. "ip" is the local IP, which
|
||||
# verify_proxy_exit compares against the proxy exit IP.
|
||||
GEO_CACHE_KEYS = ("ip", "country", "country_code")
|
||||
|
||||
Fetcher = Callable[[requests.Session], Optional[dict]]
|
||||
|
||||
@@ -108,6 +109,7 @@ def lookup_session(source: Optional[requests.Session]) -> requests.Session:
|
||||
if proxies:
|
||||
proxy = proxies.get("all") or proxies.get("https") or proxies.get("http")
|
||||
if proxy:
|
||||
sess.trust_env = False
|
||||
sess.proxies.update({"http": proxy, "https": proxy})
|
||||
return sess
|
||||
|
||||
@@ -184,6 +186,7 @@ def get_ip_info(
|
||||
session: Optional[requests.Session] = None,
|
||||
*,
|
||||
cached: bool = False,
|
||||
errors: Optional[list[Exception]] = None,
|
||||
) -> Optional[dict]:
|
||||
"""
|
||||
Look up IP/geolocation info through ipinfo.io (Lite when `ipinfo_api_key` configured)
|
||||
@@ -191,7 +194,7 @@ def get_ip_info(
|
||||
|
||||
Live lookups return a dict with `ip`, `country` (lowercase ISO2), `country_code`
|
||||
(uppercase ISO2), `region`, `city`, `org`, `asn`, `as_name`, `continent_code` and
|
||||
`_provider`. Cached lookups return only `country`/`country_code` (see GEO_CACHE_KEYS).
|
||||
`_provider`. Cached lookups return only `ip`/`country`/`country_code` (see GEO_CACHE_KEYS).
|
||||
Returns None if every geolocation API fails.
|
||||
|
||||
Args:
|
||||
@@ -201,6 +204,8 @@ def get_ip_info(
|
||||
session.headers.
|
||||
cached: When True, read/write a 24h Cacher-backed entry. Use only for
|
||||
local IP lookups, never with a proxied HTTP session.
|
||||
errors: When given, each geolocation API that raised an exception adds it to
|
||||
this list. A 429 or an unusable response adds nothing.
|
||||
"""
|
||||
cache = None
|
||||
if cached:
|
||||
@@ -233,6 +238,8 @@ def get_ip_info(
|
||||
continue
|
||||
except Exception as e:
|
||||
log.debug(f"Provider {name} failed with exception: {e}")
|
||||
if errors is not None:
|
||||
errors.append(e)
|
||||
continue
|
||||
|
||||
if not normalized:
|
||||
@@ -252,3 +259,36 @@ def get_ip_info(
|
||||
|
||||
log.warning("All IP geolocation providers failed")
|
||||
return None
|
||||
|
||||
|
||||
def verify_proxy_exit(session: requests.Session) -> dict:
|
||||
"""
|
||||
Look up the exit IP of the proxy on `session`, and check that it is not the local IP.
|
||||
|
||||
Returns the live IP info of the proxy exit, or an empty dict when geolocation APIs
|
||||
answered through the proxy (a 429, or no usable data) but none returned an IP. Raises
|
||||
ConnectionError when no geolocation API got a response through the proxy, or
|
||||
when the proxy exit IP is the local IP. This function does not check the exit country.
|
||||
The local IP comes from the 24h cached local lookup, and a live local lookup must
|
||||
confirm a match before this function rejects the proxy. If the local IP is not known,
|
||||
the IP comparison does not occur.
|
||||
"""
|
||||
errors: list[Exception] = []
|
||||
info = get_ip_info(session, errors=errors)
|
||||
if not info:
|
||||
if len(errors) < len(build_providers()):
|
||||
log.warning("No geolocation API returned the proxy exit IP, so the exit IP check does not occur")
|
||||
return {}
|
||||
raise ConnectionError(
|
||||
f"Proxy check failed: no IP lookup got through the proxy ({type(errors[-1]).__name__}). "
|
||||
"The proxy is down or refused the connection."
|
||||
)
|
||||
exit_ip = info.get("ip")
|
||||
server_ip = (get_ip_info(cached=True) or {}).get("ip")
|
||||
# The cached IP can be up to 24h old: a machine that was on a VPN when it cached its IP,
|
||||
# and now uses that VPN as a proxy, matches the old IP. A live lookup runs only on a match.
|
||||
if exit_ip and server_ip == exit_ip and (get_ip_info() or {}).get("ip") == exit_ip:
|
||||
raise ConnectionError(
|
||||
"Proxy check failed: the proxy exit IP is the IP of this machine, so traffic does not go through the proxy."
|
||||
)
|
||||
return info
|
||||
|
||||
Reference in New Issue
Block a user