mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
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:
@@ -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