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
@@ -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": {
+10
View File
@@ -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)
+20
View File
@@ -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"]
+70 -2
View File
@@ -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"))
@@ -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",
+32
View File
@@ -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"] = {}
@@ -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