fix(remote): map a cut-off answer to a recoverable error and stop trusting an empty optional answer

This commit is contained in:
imSp4rky
2026-11-28 21:03:54 -07:00
parent 74fa29b6f1
commit f5c8858e6e
12 changed files with 279 additions and 76 deletions
+20
View File
@@ -10,6 +10,7 @@ from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import Mock
import click
import pytest
import requests
from aiohttp import WSMsgType, web
@@ -322,3 +323,22 @@ async def test_a_failed_login_status_shows_the_server_error_without_control_char
with pytest.raises(RemoteError) as caught:
channel.auth_step()
assert caught.value.message == "Remote auth failed: [2Jbadforged"
@pytest.mark.parametrize("answer", [{"license": None}, {}, {"license": "x"}, {"license": 5}])
def test_a_relayed_licence_with_no_licence_is_one_click_error(answer: dict[str, Any]) -> None:
service = RemoteService.__new__(RemoteService)
service._track_alias = {}
service.session_call = lambda call: answer # type: ignore[method-assign]
service.drain_server_logs = lambda: None # type: ignore[method-assign]
track = SimpleNamespace(id="v1", drm=[])
with pytest.raises(click.ClickException, match="no valid licence for track v1"):
service.proxy_license(b"challenge", cast(Any, track), "widevine")
@pytest.mark.parametrize("chapters", [[{"name": "x"}], [{"timestamp": "not a time"}], [5]])
def test_malformed_chapters_from_the_server_are_one_remote_error(chapters: list[Any]) -> None:
service = RemoteService.__new__(RemoteService)
service._chapters_by_title = {"t": chapters}
with pytest.raises(RemoteError, match="malformed chapters"):
service.get_chapters(cast(Any, SimpleNamespace(id="t")))
+77 -2
View File
@@ -4,13 +4,19 @@ from __future__ import annotations
import json
import logging
import socket
import threading
from pathlib import Path
import click
import pytest
import requests
import responses
from unshackle.core.remote_service import RemoteClient
from unshackle.core.config import config
from unshackle.core.remote_protocol import ClientErrorKind
from unshackle.core.remote_service import RemoteClient, RemoteError
from unshackle.core.utilities import close_debug_logger, init_debug_logger
pytestmark = pytest.mark.unit
@@ -216,7 +222,65 @@ def test_late_error_after_heartbeat_is_fatal(client: RemoteClient) -> None:
responses.add(responses.GET, "http://srv:8786/api/session/s/titles", body=body, status=200)
with pytest.raises(SystemExit):
client.get("/api/session/s/titles")
assert client.request("get", "/api/session/s/titles", optional=True) == {}
with pytest.raises(RemoteError):
client.request("get", "/api/session/s/titles", optional=True)
@responses.activate
def test_an_optional_route_the_server_lacks_answers_empty(client: RemoteClient) -> None:
responses.add(responses.POST, "http://srv:8786/api/session/s/segment_filter", body="404: Not Found", status=404)
assert client.post_optional("/api/session/s/segment_filter", {}) == {}
@pytest.mark.parametrize(
("status", "code"),
[(422, "SERVICE_ERROR"), (404, "TRACK_NOT_FOUND"), (404, "SESSION_NOT_FOUND"), (503, "SERVER_DRAINING")],
)
@responses.activate
def test_an_optional_route_that_fails_on_the_server_raises(client: RemoteClient, status: int, code: str) -> None:
body = {"status": "error", "error_code": code, "message": "no"}
responses.add(responses.POST, "http://srv:8786/api/session/s/segment_filter", json=body, status=status)
with pytest.raises(RemoteError) as e:
client.post_optional("/api/session/s/segment_filter", {})
assert e.value.kind == code
@pytest.mark.parametrize("recorded", [False, True], ids=["plain", "debug-requests"])
@pytest.mark.parametrize(
("headers", "body"),
[
(b"Content-Length: 100\r\n", b'{"titles": ['),
(b"Content-Encoding: gzip\r\nContent-Length: 13\r\n", b'{"titles": ['),
(b"Transfer-Encoding: chunked\r\n", b'2\r\n\n\n\r\nc\r\n{"titles": ['),
],
ids=["short-body", "bad-gzip", "cut-chunked"],
)
def test_an_answer_cut_off_after_its_headers_is_a_connect_error(
headers: bytes, body: bytes, recorded: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A body that stops early, or a gzip body that does not decode, is a broken connection the session can survive."""
if recorded:
monkeypatch.setattr(config, "debug_requests", True)
init_debug_logger(log_path=tmp_path / "debug.jsonl", enabled=True)
with socket.create_server(("127.0.0.1", 0)) as server:
def answer() -> None:
conn, _ = server.accept()
with conn:
conn.recv(65536)
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + headers + b"\r\n" + body)
thread = threading.Thread(target=answer, daemon=True)
thread.start()
client = RemoteClient(server_url=f"http://127.0.0.1:{server.getsockname()[1]}", api_key="k")
try:
with pytest.raises(RemoteError) as e:
client.get("/api/session/s/titles")
finally:
close_debug_logger()
thread.join(5)
assert e.value.kind == ClientErrorKind.CONNECT
assert e.value.session_broke
@responses.activate
@@ -381,3 +445,14 @@ def test_a_probe_that_cannot_connect_logs_no_error(client: RemoteClient, caplog:
assert client.probe("/api/health") == {}
assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
@responses.activate
def test_any_other_requests_failure_is_one_remote_error(client: RemoteClient) -> None:
leak = requests.TooManyRedirects("http://user:pw@gw.example/login?token=SECRET")
responses.add(responses.GET, "http://srv:8786/api/session/s/titles", body=leak)
with pytest.raises(RemoteError) as e:
client.get("/api/session/s/titles")
assert e.value.kind == ClientErrorKind.UNKNOWN
assert e.value.message == "Request to remote server failed on /api/session/s/titles: TooManyRedirects"
assert not e.value.session_broke
+8
View File
@@ -152,3 +152,11 @@ def test_resolve_proxy_value_error_becomes_click(monkeypatch: pytest.MonkeyPatch
with pytest.raises(click.ClickException) as exc:
resolve_proxy_arg("xx")
assert "no such country" in str(exc.value.message)
def test_resolve_server_leaves_the_config_services_untouched(single_remote_service) -> None:
from unshackle.core import remote_service as rs
_, _, services = resolve_server("primary")
assert services["_server_cdm"] is True
assert rs.config.remote_services["primary"]["services"] == {"EXAMPLE": True, "DEMO": True}
+7
View File
@@ -116,3 +116,10 @@ def test_local_proxy_is_refused_for_a_server_account_service() -> None:
with pytest.raises(click.ClickException, match="its own account"):
list(svc.search())
def test_malformed_search_results_from_the_server_are_one_remote_error() -> None:
svc, client, _ = make_service({"no_proxy": True}, server_accounts={"global": True})
client.post = lambda endpoint, data: {"results": [{"title": "no id"}]} # type: ignore[method-assign]
with pytest.raises(remote_service.RemoteError, match="malformed search results"):
list(svc.search())
+28 -2
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from types import SimpleNamespace
import click
import pytest
import responses
@@ -58,7 +59,7 @@ async def test_handler_returns_null_without_a_filter(monkeypatch):
assert json.loads(response.body) == {"unwanted": None}
def make_service(unwanted, status=200):
def make_service(unwanted, status=200, error=None):
service = RemoteService.__new__(RemoteService)
service._track_alias = {}
service._title_alias = {}
@@ -68,7 +69,7 @@ def make_service(unwanted, status=200):
responses.add(
responses.POST,
"http://srv:8786/api/session/s1/segment_filter",
json={"unwanted": unwanted} if status == 200 else {"message": "no"},
json={"unwanted": unwanted} if status == 200 else error or {"message": "no"},
status=status,
)
return service
@@ -93,3 +94,28 @@ def test_client_filter_keeps_everything_when_the_server_has_no_route():
segment_filter = service.remote_segment_filter("t1")
assert segment_filter(SimpleNamespace(absolute_uri="https://cdn.test/hls/ad1.ts")) is False
@responses.activate
def test_a_filter_that_fails_on_the_server_stops_the_track_and_caches_nothing():
error = {"status": "error", "error_code": "SERVICE_ERROR", "message": "Could not run the segment filter"}
service = make_service(None, status=422, error=error)
segment_filter = service.remote_segment_filter("t1")
with pytest.raises(click.ClickException, match="segment filter"):
segment_filter(SimpleNamespace(absolute_uri="https://cdn.test/hls/ad1.ts"))
assert service._segment_filters == {}
@responses.activate
def test_a_replayed_filter_call_sends_the_reopened_track_id():
service = make_service([])
def session_call(call):
service._track_alias["t1"] = "t1-new"
return call("s1")
service.session_call = session_call
service.remote_segment_filter("t1")(SimpleNamespace(absolute_uri="https://cdn.test/hls/ad1.ts"))
assert json.loads(responses.calls[0].request.body) == {"track_id": "t1-new"}
+32 -2
View File
@@ -6,6 +6,7 @@ import json
import logging
from threading import Lock
import click
import pytest
import requests
import responses
@@ -85,11 +86,20 @@ def test_a_lost_session_reopens_and_replays_the_call_under_the_new_ids(monkeypat
assert service._title_alias == {"ep3-aaaa": "ep3-bbbb"}
@pytest.mark.parametrize(
"broken",
[
requests.ConnectionError("reset"),
requests.exceptions.ChunkedEncodingError("cut"),
requests.exceptions.ContentDecodingError("cut"),
],
ids=["reset", "cut-body", "cut-gzip"],
)
@responses.activate
def test_a_connect_error_on_a_live_session_runs_again_on_the_same_session():
def test_a_connect_error_on_a_live_session_runs_again_on_the_same_session(broken):
service = make_service()
url = f"{SERVER}/api/session/s1/license"
responses.add(responses.POST, url, body=requests.ConnectionError("reset"))
responses.add(responses.POST, url, body=broken)
responses.add(responses.POST, url, json={"license": "AA=="})
responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"})
responses.add(responses.GET, f"{SERVER}/api/session/s1", json={"valid": True})
@@ -151,3 +161,23 @@ def test_closing_a_session_the_server_lost_logs_no_error(caplog):
assert service._session_id is None
assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")]
@responses.activate
def test_a_certificate_the_server_fails_to_fetch_is_no_certificate():
service = make_service()
error = {"status": "error", "error_code": "SERVICE_ERROR", "message": "no certificate"}
responses.add(responses.POST, f"{SERVER}/api/session/s1/license", json=error, status=422)
track = audio("a1")
assert service.get_widevine_service_certificate(challenge=b"c", title=None, track=track) is None
@responses.activate
def test_a_certificate_call_whose_session_is_gone_is_one_click_error(monkeypatch):
service = make_service()
monkeypatch.setattr(service, "recover", lambda session_id, kind: False)
responses.add(responses.POST, f"{SERVER}/api/session/s1/license", json=GONE, status=404)
with pytest.raises(click.ClickException, match="Remote session not found"):
service.get_widevine_service_certificate(challenge=b"c", title=None, track=audio("a1"))