fix(api): redact error replies, lock segment url lookups, refuse unresolvable proxy hosts and recheck job proxies at start

This commit is contained in:
imSp4rky
2026-11-28 21:33:00 -07:00
parent 7713f8df3f
commit 0a791ad6e8
15 changed files with 348 additions and 20 deletions
+3
View File
@@ -828,6 +828,9 @@ class DownloadQueueManager:
log.info(f"Executing download for job {job.job_id}")
try:
from unshackle.core.api.job_admission import check_job_start
await asyncio.to_thread(check_job_start, job.service, job.parameters)
output_files = await self.run_download_async(job)
job.status = JobStatus.COMPLETED
job.output_files = output_files
+2 -2
View File
@@ -101,13 +101,13 @@ def build_error_response(
"""
if isinstance(error, APIError):
error_code = error.error_code.value
message = error.message
message = redact_secrets(error.message) or ""
details = error.details
http_status = error.http_status
retryable = error.retryable
else:
error_code = APIErrorCode.INTERNAL_ERROR.value
message = str(error) or "An unexpected error occurred"
message = redact_secrets(str(error)) or "An unexpected error occurred"
details = {}
http_status = APIError.default_http_status(APIErrorCode.INTERNAL_ERROR)
retryable = False
+14 -6
View File
@@ -3277,7 +3277,7 @@ async def session_segments_handler(
The client calls this after selecting which tracks to download.
Returns segment URLs, init data, DRM info, and any headers/cookies
needed for CDN download.
needed for CDN download. The headers and cookies are read after the URL lookups, which can set them.
"""
session = await get_validated_session(session_id, request)
require_authenticated(session)
@@ -3290,8 +3290,7 @@ async def session_segments_handler(
try:
result: dict[str, Any] = {}
headers, cookies = client_session_auth(session)
tracks = {}
for track_id in track_ids:
track = session.tracks.get(track_id)
if not track:
@@ -3300,12 +3299,18 @@ async def session_segments_handler(
f"Track not found in session: {track_id}",
details={"track_id": track_id, "session_id": session_id},
)
tracks[track_id] = track
async with session.lock:
urls = await asyncio.to_thread(lambda: {track_id: served_url(t) for track_id, t in tracks.items()})
headers, cookies = client_session_auth(session)
for track_id, track in tracks.items():
descriptor_name = track.descriptor.name if hasattr(track.descriptor, "name") else str(track.descriptor)
track_info: dict[str, Any] = {
"descriptor": descriptor_name,
"url": await asyncio.to_thread(served_url, track),
"url": urls[track_id],
"drm": serialize_drm(track.drm) if hasattr(track, "drm") and track.drm else None,
"headers": headers,
"cookies": cookie_values(cookies),
@@ -3516,7 +3521,10 @@ def local_proxy_refusal(proxy: str) -> str | None:
try:
addresses = {str(info[4][0]) for info in socket.getaddrinfo(host, None)}
except (socket.gaierror, UnicodeError):
return None # an unresolvable proxy fails at connect time anyway
return f"Proxy host {sanitize_log(host)} does not resolve"
# shortcut: the HTTP client resolves the name again when it connects, so a name whose answer changes after this
# check still reaches a local address; pin the checked IP into http and socks URIs (an https proxy needs its name
# for TLS) when a client that controls its own DNS is in scope.
if not all(is_public_ip(address) for address in addresses):
return f"Proxy host {sanitize_log(host)} is not a public address"
return None
@@ -3554,7 +3562,7 @@ def resolve_handler_proxy(
details={"service": normalized_service},
)
if isinstance(proxy_param, str) and not no_proxy and not (allowed or policy.admin):
if isinstance(proxy_param, str) and not no_proxy and not policy.local_proxy:
refusal = local_proxy_refusal(proxy_param)
if refusal:
raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": normalized_service})
+18 -2
View File
@@ -21,7 +21,7 @@ from unshackle.core.utils.collections import as_list, ci_get
ENVELOPE_KEYS = ("service", "title_id", "owner_key")
log = logging.getLogger("api")
SERVER_STAMPS = ("client_keys", "server_proxy")
SERVER_STAMPS = ("client_keys", "server_proxy", "local_proxy")
LANGUAGE_LIST_KEYS = (
"lang",
"v_lang",
@@ -103,7 +103,9 @@ def job_spec(data: dict[str, Any], server: str | None, request: web.Request | No
handlers.cast_or_refuse(cli_params, click.Context(click.Command(service)), options)
handlers.warn_ignored(ignored)
params["service_params"] = options
params["server_proxy"] = handlers.request_policy(request).allows("server_proxy")
policy = handlers.request_policy(request)
params["server_proxy"] = policy.allows("server_proxy")
params["local_proxy"] = policy.local_proxy
return JobSpec(service, data["title_id"], params)
@@ -285,6 +287,20 @@ def enforce_download_gates(params: dict[str, Any], request: web.Request | None =
raise APIError(APIErrorCode.FORBIDDEN, "Per-request credentials are not permitted for API downloads.")
def check_job_start(service: str, params: dict[str, Any]) -> None:
"""INVALID_PROXY when a queued job's proxy now reaches the server's own network.
Admission resolved the proxy host when the client submitted the job, so the job runs the same check again when it
starts. The ``local_proxy`` stamp keeps the API key's right of admission, which a later config reload cannot widen.
"""
if params.get("no_proxy") or params.get("local_proxy"):
return
for key in ("proxy", "proxy_download"):
value = params.get(key)
if isinstance(value, str) and (refusal := handlers.local_proxy_refusal(value)):
raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": service})
def service_dl_defaults(service: str) -> dict[str, Any]:
"""The ``services.<TAG>.dl`` values that name an API download parameter, keyed as the API names them."""
result: dict[str, Any] = {}
+5
View File
@@ -133,6 +133,11 @@ class KeyPolicy:
return list(value)
return bool(value)
@property
def local_proxy(self) -> bool:
"""Whether the API key may send a proxy URI on the server's own machine or network."""
return self.allows("server_proxy") or self.admin
def allows(self, name: Grant, service: str | None = None) -> bool:
"""Whether the API key holds ``name`` for ``service``; ``server_cdm`` gives ``server_vault`` too."""
if name == "server_vault" and self.allows("server_cdm", service):
+5 -1
View File
@@ -2260,6 +2260,7 @@ async def session_tracks(request: web.Request) -> web.Response:
@api_handler
@heartbeat
@categorized
async def session_segments(request: web.Request) -> web.Response:
"""
@@ -2289,7 +2290,10 @@ async def session_segments(request: web.Request) -> web.Response:
description: List of track IDs to get segment URLs for
responses:
'200':
description: Segment URLs and DRM info for each track
description: >-
Segment URLs and DRM info for each track.
After 30 s the route sends 200 and a newline every 30 s. A failure after that time
arrives as the error body with status 200.
'404':
description: Remote session or track not found
"""