diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 02f4ae63..fd178540 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -482,6 +482,7 @@ Make a download job. It requires `service` and `title_id`. Every other field is | `workers` | int | `null` | Threads per track. | | `adaptive_workers` | boolean | `false` | Scale segment workers to measured CDN throughput, up to the `workers` cap. | | `download_processes` | int | `1` | Split a track's segments across this many processes. Only engages for large batches. | +| `continue_downloads` | boolean | `false` | Keep the completed segment files across runs and resume a download that failed before. | | `downloads` | int | `1` | Concurrent tracks. | | `worst` | boolean | `false` | Pick the lowest-bitrate video at each resolution in `quality`, or at the lowest resolution if `quality` is empty. | | `best_available` | boolean | `false` | Fall back to best available. With `all_drm`, a DRM system that does not license is a warning. | @@ -972,7 +973,7 @@ DELETE /api/session/{id} → tear down, harvest updated cache ### Slow responses -The `titles`, `tracks` and `license` routes can take minutes on a large catalogue. When the +The `titles`, `tracks`, `segments` and `license` routes can take minutes on a large catalogue. When the answer is not ready after 30 seconds, the route sends status `200` and the headers. It then sends a newline every 30 seconds until the JSON body is ready. JSON parsers ignore the leading newlines. This keeps the connection open through a reverse proxy that closes an idle request. @@ -994,7 +995,7 @@ Make a remote session for a service and title. Authentication runs asynchronousl Service CLI options also travel in a nested `service_params` object. When the body has `service_params`, the server reads service options only from it, and a flat key with the same name stays a `dl` value. `profile` at the top level always means the credentials profile, never a service's own `--profile` option. -The `proxy` value must be a full proxy URI, unless the operator gives your API key `server_proxy` in the `serve.users` config. Without `server_proxy`, a proxy URI gets `INVALID_PROXY` when its host is not a public address or is not a plain host name or IP address. Without `server_proxy`, the server does not resolve country codes with its own proxy providers. It rejects the request with `INVALID_PROXY` when no `proxy` is set and the reported `client_region` differs from the server's region. A request that reports no `client_region` is not blocked. Pass `proxy` with your own proxy, or `no_proxy` to accept the server's own connection. With `server_proxy`, the server resolves a country code and picks a proxy for your `client_region` itself. A Control D resolver, `controld://@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own. A proxy URI needs an `http`, `https` or `socks` scheme: the server answers `INVALID_PROXY` to a `host:port` value, also with `server_proxy`. +The `proxy` value must be a full proxy URI, unless the operator gives your API key `server_proxy` in the `serve.users` config. Without `server_proxy`, a proxy URI gets `INVALID_PROXY` when its host is not a public address, does not resolve, or is not a plain host name or IP address. Without `server_proxy`, the server does not resolve country codes with its own proxy providers. It rejects the request with `INVALID_PROXY` when no `proxy` is set and the reported `client_region` differs from the server's region. A request that reports no `client_region` is not blocked. Pass `proxy` with your own proxy, or `no_proxy` to accept the server's own connection. With `server_proxy`, the server resolves a country code and picks a proxy for your `client_region` itself. A Control D resolver, `controld://@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own. A proxy URI needs an `http`, `https` or `socks` scheme: the server answers `INVALID_PROXY` to a `host:port` value, also with `server_proxy`. === "Response `200`" @@ -1149,7 +1150,7 @@ Get tracks and chapters for a specific title within the remote session. Body: `{ ### `POST /api/session/{session_id}/segments` -Get the download URL, DRM info, headers, cookies, and raw track data for the selected tracks. Body: `{ "track_ids": ["v-1", "a-1"] }` (required). +Get the download URL, DRM info, headers, cookies, and raw track data for the selected tracks. Body: `{ "track_ids": ["v-1", "a-1"] }` (required). A track that the tracks response sent with `resolve_url` gets its URL from the service here. The server makes one service call at a time per remote session, so parallel requests wait for each other. A slow answer arrives as described in [Slow responses](#slow-responses). === "Response `200`" diff --git a/docs/reference/configuration/services.md b/docs/reference/configuration/services.md index 79b28c57..d2ac2fdf 100644 --- a/docs/reference/configuration/services.md +++ b/docs/reference/configuration/services.md @@ -362,10 +362,14 @@ pick a proxy for the client's region and for a service geofence. The client repo region; a client that reports none is not blocked. Without `server_proxy`, the server refuses a proxy URI whose host is not a public address: -loopback, private, link-local and other special-purpose addresses, and `localhost`. This also -applies to a server on a LAN, so a client proxy on that LAN needs `server_proxy` or an admin key. -The server checks the proxy values the job uses, including a `proxy` default from the server's -own config. +loopback, private, link-local and other special-purpose addresses, and `localhost`. It also +refuses a host name that does not resolve. This also applies to a server on a LAN, so a client +proxy on that LAN needs `server_proxy` or an admin key. The server checks the proxy values the +job uses, including a `proxy` default from the server's own config, when you submit the job and +again when the job starts. A job whose proxy host does not resolve at that time fails with +`INVALID_PROXY`; submit it again. The checks read the DNS answer at that time only, so a host +name that a client controls can still answer another address when the server connects. Give +`server_proxy` only to API keys you trust with your network. ```yaml serve: diff --git a/tests/remote/unit/snapshots/route_error_replies.json b/tests/remote/unit/snapshots/route_error_replies.json index 2c818a56..c29b8a7f 100644 --- a/tests/remote/unit/snapshots/route_error_replies.json +++ b/tests/remote/unit/snapshots/route_error_replies.json @@ -3688,6 +3688,116 @@ }, "status": 422 }, + "segments url exit": { + "body": { + "details": { + "operation": "session_segments", + "reason": "service_exit", + "session_id": "pinned-session" + }, + "error_code": "SERVICE_ERROR", + "message": "Service exited (ref REF)", + "ref": "REF", + "status": "error", + "timestamp": "TIMESTAMP" + }, + "content_type": "application/json", + "leading_newlines": false, + "log": [ + "Error ref REF: SERVICE_ERROR 422 POST /api/session/pinned-session/segments service=EXAMPLE user=test\u2026: Service exited" + ], + "stats": { + "error": { + "code": "SERVICE_ERROR", + "message": "Service exited", + "ref": "REF" + }, + "late_status": null + }, + "status": 422 + }, + "segments url exit late": { + "body": { + "details": { + "operation": "session_segments", + "reason": "service_exit", + "session_id": "pinned-session" + }, + "error_code": "SERVICE_ERROR", + "message": "Service exited (ref REF)", + "ref": "REF", + "status": "error", + "timestamp": "TIMESTAMP" + }, + "content_type": "application/json", + "leading_newlines": true, + "log": [ + "Error ref REF: SERVICE_ERROR 422 POST /api/session/pinned-session/segments service=EXAMPLE user=test\u2026: Service exited" + ], + "stats": { + "error": { + "code": "SERVICE_ERROR", + "message": "Service exited", + "ref": "REF" + }, + "late_status": 422 + }, + "status": 200 + }, + "segments url plain": { + "body": { + "details": { + "operation": "session_segments", + "session_id": "pinned-session" + }, + "error_code": "INTERNAL_ERROR", + "message": "An unexpected error occurred: pinned failure (ref REF)", + "ref": "REF", + "status": "error", + "timestamp": "TIMESTAMP" + }, + "content_type": "application/json", + "leading_newlines": false, + "log": [ + "Error ref REF: INTERNAL_ERROR 422 POST /api/session/pinned-session/segments service=EXAMPLE user=test\u2026: An unexpected error occurred: pinned failure" + ], + "stats": { + "error": { + "code": "INTERNAL_ERROR", + "message": "An unexpected error occurred: pinned failure", + "ref": "REF" + }, + "late_status": null + }, + "status": 422 + }, + "segments url plain late": { + "body": { + "details": { + "operation": "session_segments", + "session_id": "pinned-session" + }, + "error_code": "INTERNAL_ERROR", + "message": "An unexpected error occurred: pinned failure (ref REF)", + "ref": "REF", + "status": "error", + "timestamp": "TIMESTAMP" + }, + "content_type": "application/json", + "leading_newlines": true, + "log": [ + "Error ref REF: INTERNAL_ERROR 422 POST /api/session/pinned-session/segments service=EXAMPLE user=test\u2026: An unexpected error occurred: pinned failure" + ], + "stats": { + "error": { + "code": "INTERNAL_ERROR", + "message": "An unexpected error occurred: pinned failure", + "ref": "REF" + }, + "late_status": 422 + }, + "status": 200 + }, "services plain": { "body": { "details": { diff --git a/tests/remote/unit/test_api_dl_options.py b/tests/remote/unit/test_api_dl_options.py index 7851a44b..d83caa1a 100644 --- a/tests/remote/unit/test_api_dl_options.py +++ b/tests/remote/unit/test_api_dl_options.py @@ -1,6 +1,8 @@ from __future__ import annotations import inspect +import re +from pathlib import Path import click import pytest @@ -37,6 +39,14 @@ def test_the_openapi_yaml_names_each_api_dl_option_and_no_other(): assert properties.keys() - DEFAULT_DOWNLOAD_PARAMS.keys() == {"service", "title_id", "remote", "client_name", "cdm"} +def test_the_endpoint_docs_name_each_api_dl_option(): + """The POST /api/download table of the endpoint reference has a row for every dl option the API takes.""" + page = (Path(__file__).parents[3] / "docs/dev/rest-api/endpoints.md").read_text(encoding="utf-8") + section = page.split("### `POST /api/download`", 1)[1].split("\n### ", 1)[0] + rows = [line.split("|")[1] for line in section.splitlines() if line.startswith("| `")] + assert DEFAULT_DOWNLOAD_PARAMS.keys() <= {name for row in rows for name in re.findall(r"`(\w+)`", row)} + + def test_api_defaults_cast_to_the_dl_defaults(): """``wanted`` keeps its API default of no keys, which dl reads as every title, like the CLI's None.""" ctx = click.Context(dl.cli) diff --git a/tests/remote/unit/test_errors.py b/tests/remote/unit/test_errors.py index c921eac9..8156fc6f 100644 --- a/tests/remote/unit/test_errors.py +++ b/tests/remote/unit/test_errors.py @@ -293,3 +293,23 @@ def test_a_system_exit_stays_a_service_error_whatever_its_cause_names() -> None: raise SystemExit(1) from e except SystemExit as exit_: assert categorize_exception(exit_).error_code == APIErrorCode.SERVICE_ERROR + + +@pytest.mark.parametrize( + "error", + [ + APIError( + APIErrorCode.SERVICE_ERROR, + "Licence request failed: 403 Client Error: Forbidden for url: https://lic.example.com/wv?token=s3cr3t&kid=1", + ), + RuntimeError("Failed to initialize service: 403 for url: https://lic.example.com/wv?token=s3cr3t&kid=1"), + ], + ids=["api-error", "exception"], +) +def test_the_reply_masks_a_secret_in_the_error_text(error: Exception) -> None: + """A service exception names the URL it failed on, and a server-account login puts the operator's token there.""" + resp = build_error_response(error) + body = _body(resp) + assert "s3cr3t" not in body["message"] + assert "s3cr3t" not in resp["error"]["message"] + assert "https://lic.example.com/wv?token=***&kid=1" in body["message"] diff --git a/tests/remote/unit/test_handler_proxy_policy.py b/tests/remote/unit/test_handler_proxy_policy.py index 60931a66..16fbda2a 100644 --- a/tests/remote/unit/test_handler_proxy_policy.py +++ b/tests/remote/unit/test_handler_proxy_policy.py @@ -1,5 +1,6 @@ """The server spends its own proxy subscriptions only for a key that opts in.""" +import asyncio from datetime import UTC from types import SimpleNamespace @@ -33,6 +34,11 @@ 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) @@ -78,6 +84,7 @@ def test_region_unknown_no_error(monkeypatch): 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") ) @@ -221,7 +228,8 @@ class TestDownloadGates: 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): + 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") ) @@ -293,6 +301,12 @@ class TestDownloadEnforcement: created = created_params({"service": "EXAMPLE", "title_id": "t1"}, request("proxykey")) assert created["server_proxy"] is True + @pytest.mark.parametrize(("key", "stamp"), [("plainkey", False), ("proxykey", True), ("adminkey", True)]) + def test_the_local_proxy_stamp_records_the_key_at_submit(self, created_params, key, stamp): + """A key removed by a reload before the job starts reads as admin then, so the stamp keeps the submit view.""" + created = created_params({"service": "EXAMPLE", "title_id": "t1", "local_proxy": True}, request(key)) + assert created["local_proxy"] is stamp + @pytest.mark.parametrize(("params", "expected"), [({}, []), ({"server_proxy": True}, ["server"])]) def test_perform_download_maps_stamp_to_dl_providers(self, monkeypatch, tmp_path, params, expected): """An unstamped or denied job hands dl an empty provider list; a stamped one gets the server's list.""" @@ -402,12 +416,66 @@ def test_a_client_region_that_is_no_region_code_gets_no_proxy(monkeypatch, clien 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))]) + 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 + + from unshackle.core.api.download_manager import DownloadJob, DownloadQueueManager, JobStatus + + 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( + "job1", + JobStatus.DOWNLOADING, + datetime.now(), + "EXAMPLE", + "t1", + {"proxy": "http://rebind.example: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")) diff --git a/tests/remote/unit/test_route_error_replies.py b/tests/remote/unit/test_route_error_replies.py index ba6fd663..0167a7df 100644 --- a/tests/remote/unit/test_route_error_replies.py +++ b/tests/remote/unit/test_route_error_replies.py @@ -190,6 +190,14 @@ def fault_cases() -> dict[str, Case]: session=Faulty(), patch={"fetch_init_segment": Faulty(kind, late).fail, **heartbeat}, ) + if kind != "api": + cases[f"segments url {kind}{when}"] = Case( + "POST", + fill(SEGMENTS_ROUTE), + BODIES[SEGMENTS_ROUTE], + session=Faulty(), + patch={"served_url": Faulty(kind, late).fail, **heartbeat}, + ) cases[f"license proxy {kind}"] = Case("POST", fill(LICENSE_ROUTE), BODIES[LICENSE_ROUTE], session=Faulty(kind)) cases[f"segments {kind}"] = Case( "POST", diff --git a/tests/remote/unit/test_routes.py b/tests/remote/unit/test_routes.py index 8eb22ecb..7936a8a7 100644 --- a/tests/remote/unit/test_routes.py +++ b/tests/remote/unit/test_routes.py @@ -340,6 +340,38 @@ async def test_services_load_errors_go_to_the_admin_key_only( assert admin["load_errors"] == ["BAD: failed to import - ImportError: boom"] +@pytest.mark.parametrize( + "path", ["/api/maintenance/clear-cache", "/api/maintenance/clear-temp", "/api/maintenance/refresh-services"] +) +async def test_maintenance_needs_an_admin_key(make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch, path) -> None: + from unshackle.commands import env + from unshackle.core import services as services_module + from unshackle.core.config import config + + monkeypatch.setattr(env, "clear_directory", lambda path: (0, 0)) + monkeypatch.setattr(services_module, "refresh_and_reload", lambda busy: []) + monkeypatch.setattr(config, "serve", {"api_secret": "admin", "users": {"user": {}, "boss": {"admin": True}}}) + client = await aiohttp_client(make_app()) + user = await client.post(path, headers={"X-Secret-Key": "user"}) + assert user.status == 403 + assert (await user.json())["error_code"] == "FORBIDDEN" + for key in ("admin", "boss"): + assert (await client.post(path, headers={"X-Secret-Key": key})).status == 200, key + + +async def test_config_sends_directories_to_an_admin_key_only( + make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch +) -> None: + from unshackle.core.config import config + + monkeypatch.setattr(config, "serve", {"api_secret": "admin", "users": {"user": {}}}) + client = await aiohttp_client(make_app()) + user = await (await client.get("/api/config", headers={"X-Secret-Key": "user"})).json() + admin = await (await client.get("/api/config", headers={"X-Secret-Key": "admin"})).json() + assert "directories" not in user["config"] + assert set(admin["config"]["directories"]) == {"downloads", "temp", "cache"} + + async def test_health_needs_an_api_key(make_app, aiohttp_client) -> None: app = make_app(remote_only=True, with_auth_middleware=True) app["config"]["users"]["good-key"] = {} diff --git a/tests/remote/unit/test_session_service_lock.py b/tests/remote/unit/test_session_service_lock.py index 869af611..ced49cf2 100644 --- a/tests/remote/unit/test_session_service_lock.py +++ b/tests/remote/unit/test_session_service_lock.py @@ -251,3 +251,42 @@ async def test_each_session_entry_gets_its_own_lock() -> None: finally: await store.delete(first.session_id) await store.delete(second.session_id) + + +class LookupTrack: + """A track whose URL costs a service request, as one sent with ``resolve_url``.""" + + def __init__(self, track_id: str, overlap: Overlap) -> None: + self.id = track_id + self.url: str | None = None + self.descriptor = SimpleNamespace(name="URL") + self.drm = None + self.data: dict = {} + self.overlap = overlap + + def ensure_url(self) -> None: + with self.overlap.call(f"url:{self.id}"): + self.url = f"https://cdn.example.com/{self.id}.mp4" + + +@pytest.mark.asyncio +async def test_two_segment_requests_never_share_the_service() -> None: + """The client asks the segments route for each lookup track's URL in parallel.""" + overlap = Overlap() + store = get_session_store() + session = await store.create("EXAMPLE", ServiceProbe(overlap), session_id="lock-test-segments") + session.authenticated = True + session.tracks = {tid: LookupTrack(tid, overlap) for tid in ("v-1", "a-1")} + try: + responses = list( + await asyncio.gather( + handlers.session_segments_handler({"track_ids": ["v-1"]}, session.session_id), + handlers.session_segments_handler({"track_ids": ["a-1"]}, session.session_id), + ) + ) + finally: + await store.delete(session.session_id) + + urls = [body["tracks"][tid]["url"] for body, tid in zip(bodies(responses), ("v-1", "a-1"), strict=True)] + assert urls == ["https://cdn.example.com/v-1.mp4", "https://cdn.example.com/a-1.mp4"] + assert overlap.max_active == 1, overlap.trace diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index 211d2a04..59d6e7fb 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -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 diff --git a/unshackle/core/api/errors.py b/unshackle/core/api/errors.py index 0fd546b2..a19bb838 100644 --- a/unshackle/core/api/errors.py +++ b/unshackle/core/api/errors.py @@ -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 diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index a35ee981..bf344e9c 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -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}) diff --git a/unshackle/core/api/job_admission.py b/unshackle/core/api/job_admission.py index 8f97234e..48c3fb2b 100644 --- a/unshackle/core/api/job_admission.py +++ b/unshackle/core/api/job_admission.py @@ -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..dl`` values that name an API download parameter, keyed as the API names them.""" result: dict[str, Any] = {} diff --git a/unshackle/core/api/key_policy.py b/unshackle/core/api/key_policy.py index eb05408c..7f235a2e 100644 --- a/unshackle/core/api/key_policy.py +++ b/unshackle/core/api/key_policy.py @@ -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): diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index 80174fc0..2cdd357c 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -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 """