feat(remote)!: make remote serve WebSocket-only and refuse older clients with CLIENT_OUTDATED

This commit is contained in:
imSp4rky
2026-12-05 09:47:22 -07:00
parent 641623590d
commit 00ad15527c
62 changed files with 657 additions and 2098 deletions
+100 -69
View File
@@ -31,8 +31,8 @@ from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_
from unshackle.core.cdm import client_relay
from unshackle.core.config import config
from unshackle.core.console import console, qr_text
from unshackle.core.remote_channel import PollingChannel, WebSocketChannel
from unshackle.core.remote_protocol import CHANNEL_ROUTE, LOGS_ROUTE, PROMPT_ROUTE, SESSION_ROUTE, APIErrorCode
from unshackle.core.remote_channel import WebSocketChannel
from unshackle.core.remote_protocol import CHANNEL_ROUTE, SESSION_ROUTE, TITLES_ROUTE, APIErrorCode, ClientErrorKind
from unshackle.core.remote_service import RemoteError, RemoteService
from unshackle.core.service import Service
from unshackle.core.session import RnetSession, record_requests
@@ -103,6 +103,10 @@ class StubService:
def decrypts_samples(self, track: Any) -> bool:
return False
def get_widevine_license(self, *, challenge: bytes, title: Movie, track: Any, **_: Any) -> bytes:
"""Make one call on the client's CDM, as a service with a CDM-based licence step does."""
return json.dumps(self._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"})).encode()
fairplay_bridge = TitleSource.fairplay_bridge
@@ -146,7 +150,6 @@ def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_
monkeypatch.setattr(StubService, "hooks", {})
monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.02)
monkeypatch.setattr(routes.web, "StreamResponse", CountedHeartbeat)
monkeypatch.setattr(remote_channel, "KEEPALIVE_MIN_INTERVAL", 0.05)
monkeypatch.setattr(remote_channel, "AUTH_POLL_INTERVAL", 0.01)
monkeypatch.setattr(remote_service, "REOPEN_WAIT", 5.0)
monkeypatch.setattr(session_store, "session_store", None)
@@ -223,57 +226,47 @@ def count(server: SimpleNamespace, method: str, route: str, session_id: str | No
return len([s for s in server.seen if s[:2] == (method, route.format(session_id=session_id))])
def polled(server: SimpleNamespace) -> list[tuple[str, str, int]]:
"""The requests to a prompt or logs route, which the server no longer has and the client never sends."""
return [s for s in server.seen if s[1].endswith(("/prompt", "/logs"))]
def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]:
"""What the client logged as the service's own lines, which the server relayed."""
return [r.getMessage() for r in caplog.records if r.name == "EXAMPLE"]
@pytest.mark.parametrize(
"server,channel",
[(True, "none"), (False, "refused"), (True, "failed")],
ids=["old-client", "refused-upgrade", "failed-connect"],
indirect=["server"],
)
def test_a_remote_session_runs_end_to_end_over_http(
server: SimpleNamespace, channel: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
def test_a_remote_session_runs_end_to_end_over_the_channel(
server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A client that does not open the channel, or whose upgrade is refused or fails, polls with the same replies."""
"""Create, a login prompt, titles, tracks, a licence that calls the client's CDM and a lost session: none polls."""
caplog.set_level(logging.DEBUG)
monkeypatch.setattr(session_store.SessionStore, "_expired", lambda self, entry: False)
if channel == "none":
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
if channel == "failed":
async def unreachable(self: Any, url: str, **kwargs: Any) -> Any:
raise aiohttp.ClientConnectionError("EXAMPLE connect failed")
monkeypatch.setattr(aiohttp.ClientSession, "_ws_connect", unreachable)
service = make_client(server.url)
monkeypatch.setattr(client_relay, "answer_cdm_call", lambda cdm, call, sessions: {"op": call["op"]})
asked: list[str] = []
service = make_client(server.url, cdm=SimpleNamespace())
service._input_bridge = SimpleNamespace(request_input=lambda prompt, qr=None: asked.append(prompt) or CODE)
try:
service.authenticate()
first = service._session_id
assert first
assert server.seen[0] == ("POST", "/api/session/create", 401)
assert ("GET", f"/api/session/{first}/prompt", 200) in server.seen
assert isinstance(service.channel, PollingChannel)
assert count(server, "GET", CHANNEL_ROUTE, first) == int(channel == "refused")
channel_lines = [r for r in caplog.records if r.name == "remote_channel"]
assert all(r.levelno == logging.DEBUG for r in channel_lines)
assert bool(channel_lines) == (channel != "none")
assert asked == ["Enter the EXAMPLE code"]
assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set()
assert any(r.name == "EXAMPLE" and r.message == "Logged in to EXAMPLE, login 1" for r in caplog.records)
info = SESSION_ROUTE.format(session_id=first)
assert wait_until(lambda: len([s for s in server.seen if s[:2] == ("GET", info)]) >= 2, 10)
titles = service.get_titles()
assert [str(t.id) for t in titles] == ["example-1", "example-2", "example-3"]
m1, m2, m3 = titles
assert [str(t.id) for t in service.get_tracks(m1).audio] == ["example-1-login1"]
(audio,) = service.get_tracks(m1).audio
assert str(audio.id) == "example-1-login1"
assert service.get_widevine_license(challenge=b"EXAMPLE", title=m1, track=audio) == b'{"op": "close"}'
forget(server, first)
assert [str(t.id) for t in service.get_tracks(m2).audio] == ["example-2-login2"]
assert service._session_id not in (None, first)
assert "The remote session was lost, opening a new one" in caplog.messages
assert asked == ["Enter the EXAMPLE code"] * 2
with pytest.raises(RemoteError) as late:
service.get_tracks(m3)
@@ -286,26 +279,74 @@ def test_a_remote_session_runs_end_to_end_over_http(
assert service.channel is None
assert ("DELETE", SESSION_ROUTE.format(session_id=second), 200) in server.seen
assert not session_store.get_session_store()._sessions
prompts = {body for path, body in server.bodies if path.endswith("/prompt")}
assert prompts <= {
b'{"status": "authenticating"}',
b'{"status": "pending_input", "prompt": "Enter the EXAMPLE code"}',
b'{"status": "authenticated"}',
b'{"status": "accepted"}',
}
assert b'{"status": "pending_input", "prompt": "Enter the EXAMPLE code"}' in prompts
logs = [json.loads(body) for path, body in server.bodies if path.endswith("/logs")]
assert logs and all(list(reply) == ["session_id", "logs", "last_seq"] for reply in logs)
assert [list(r) for reply in logs for r in reply["logs"]][:1] == [["seq", "level", "message", "ts"]]
assert polled(server) == []
@pytest.mark.parametrize("channel", ["socket", "polling"])
def test_a_qr_code_reaches_the_client_terminal_with_its_prompt(
@pytest.mark.parametrize(
"server,channel",
[(False, "refused"), (True, "failed")],
ids=["refused-upgrade", "failed-connect"],
indirect=["server"],
)
def test_a_channel_that_cannot_open_stops_the_client_with_one_line(
server: SimpleNamespace, channel: str, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(remote_channel, "RECONNECT_DELAY", 0.05)
if channel == "failed":
async def unreachable(self: Any, url: str, **kwargs: Any) -> Any:
raise aiohttp.ClientConnectionError("EXAMPLE connect failed")
monkeypatch.setattr(aiohttp.ClientSession, "_ws_connect", unreachable)
service = make_client(server.url)
try:
with pytest.raises(RemoteError) as stopped:
service.authenticate()
finally:
service.close()
if channel == "refused":
assert stopped.value.message == f"The remote server at {server.url} refused the session channel: HTTP 502"
assert stopped.value.kind == ClientErrorKind.UNKNOWN
else:
assert stopped.value.message == f"Could not open the session channel to {server.url}: EXAMPLE connect failed"
assert stopped.value.kind == ClientErrorKind.CONNECT
assert count(server, "GET", TITLES_ROUTE) == 0 and polled(server) == []
assert wait_until(lambda: not session_store.get_session_store()._sessions, 5)
assert count(server, "GET", CHANNEL_ROUTE) == (2 if channel == "refused" else 0)
@pytest.mark.parametrize(("status", "opens"), [(429, True), (422, False)])
def test_the_first_channel_open_tries_once_more_after_a_rate_limit_answer(
server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, status: int, opens: bool
) -> None:
monkeypatch.setattr(remote_channel, "RECONNECT_DELAY", 0.05)
channel_handler = routes.session_channel_handler
answered: list[int] = []
async def once(session_id: str, request: web.Request) -> web.StreamResponse:
if not answered:
answered.append(status)
return web.Response(status=status, headers={"Retry-After": "0"})
return await channel_handler(session_id, request)
monkeypatch.setattr(routes, "session_channel_handler", once)
service = make_client(server.url)
try:
if opens:
service.authenticate()
assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set()
else:
with pytest.raises(RemoteError, match=f"refused the session channel: HTTP {status}$"):
service.authenticate()
finally:
service.close()
assert answered == [status]
def test_a_qr_code_reaches_the_client_terminal_with_its_prompt(
server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = "https://login.example/scan?code=EXAMPLE"
if channel == "polling":
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
def authenticate(self: StubService, cookies: Any, credential: Any) -> None:
if self._input_bridge.request_input("Scan the EXAMPLE code, then press Enter", qr=payload) != CODE:
@@ -320,21 +361,18 @@ def test_a_qr_code_reaches_the_client_terminal_with_its_prompt(
service._input_bridge = None
try:
service.authenticate()
assert isinstance(service.channel, WebSocketChannel if channel == "socket" else PollingChannel)
assert isinstance(service.channel, WebSocketChannel)
finally:
service.close()
assert [p.plain for p in printed if hasattr(p, "plain")] == [qr_text(payload).plain]
assert len(asked) == 1 and "Scan the EXAMPLE code" in asked[0]
@pytest.mark.parametrize("channel", ["socket", "polling"])
def test_a_qr_code_to_approve_reaches_the_client_with_its_log_line(
server: SimpleNamespace, channel: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
) -> None:
caplog.set_level(logging.INFO)
payload = "https://login.example/approve?code=EXAMPLE"
if channel == "polling":
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
printed: list[Any] = []
monkeypatch.setattr(console, "print", lambda *a, **k: printed.extend(a))
@@ -351,7 +389,7 @@ def test_a_qr_code_to_approve_reaches_the_client_with_its_log_line(
service._input_bridge = None
try:
service.authenticate()
assert isinstance(service.channel, WebSocketChannel if channel == "socket" else PollingChannel)
assert isinstance(service.channel, WebSocketChannel)
finally:
service.close()
assert "Scan the EXAMPLE code" in example_messages(caplog)
@@ -392,7 +430,6 @@ def test_the_session_channel_carries_what_the_server_starts(
assert [str(t.id) for t in listed[0]] == ["example-1", "example-2", "example-3"]
assert answers == [{"op": "close"}, CODE]
assert service.get_tracks(listed[0][0]).audio
assert count(server, "GET", PROMPT_ROUTE) == count(server, "GET", LOGS_ROUTE) == 0
forget(server, first)
assert wait_until(lambda: not service.channel.connected.is_set(), 5)
@@ -411,7 +448,7 @@ def test_the_session_channel_carries_what_the_server_starts(
server.loop.call_soon_threadsafe(store.stop_drain)
assert wait_until(lambda: not store.draining, 5)
assert wait_until(lambda: not service.server_draining(), 5)
assert count(server, "GET", PROMPT_ROUTE) == count(server, "GET", LOGS_ROUTE) == 0
assert polled(server) == []
finally:
release.set()
service.close()
@@ -430,18 +467,14 @@ class Origin(BaseHTTPRequestHandler):
self.wfile.write(b"{}")
@pytest.mark.parametrize("channel", ["socket", "polling"])
def test_server_request_records_never_reach_the_remote_client(
server: SimpleNamespace,
channel: str,
caplog: pytest.LogCaptureFixture,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
"""The http_request entries of the service's requests stay in the server's JSONL, out of the session log."""
caplog.set_level(logging.DEBUG)
if channel == "polling":
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
origin = ThreadingHTTPServer(("127.0.0.1", 0), Origin)
origin.daemon_threads = True
Thread(target=origin.serve_forever, daemon=True).start()
@@ -469,7 +502,6 @@ def test_server_request_records_never_reach_the_remote_client(
try:
service.authenticate()
assert len(service.get_titles()) == 3
service.drain_server_logs()
assert wait_until(lambda: {"EXAMPLE init done", "EXAMPLE titles fetched"} <= set(example_messages(caplog)), 10)
(entry,) = session_store.get_session_store()._sessions.values()
buffered = [r["message"] for r in entry.log_buffer.since(0)]
@@ -506,7 +538,7 @@ def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkey
assert on_loop(server, store.cleanup_expired()) == 0
assert store.peek(session_id) is entry
assert count(server, "GET", SESSION_ROUTE, session_id) == 0
assert count(server, "GET", LOGS_ROUTE) == count(server, "GET", PROMPT_ROUTE) == 0
assert polled(server) == []
monkeypatch.setitem(config.serve, "session_ttl", 300)
service.lifetime.close_channel()
@@ -535,7 +567,7 @@ def gate_channel(monkeypatch: pytest.MonkeyPatch) -> threading.Event:
return refuse
def test_a_dropped_channel_falls_back_to_polling_until_it_reconnects(
def test_a_dropped_channel_reconnects_and_nothing_polls_meanwhile(
server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
) -> None:
caplog.set_level(logging.INFO)
@@ -555,22 +587,20 @@ def test_a_dropped_channel_falls_back_to_polling_until_it_reconnects(
on_loop(server, entry.channel.ws.close())
assert wait_until(lambda: not channel.connected.is_set(), 5)
titles = service.get_titles()
assert count(server, "GET", LOGS_ROUTE, session_id) >= 1
assert "Listing EXAMPLE titles" in example_messages(caplog)
assert wait_until(lambda: count(server, "GET", SESSION_ROUTE, session_id) >= 1, 5), "no keepalive took over"
assert "Listing EXAMPLE titles" not in example_messages(caplog)
assert count(server, "GET", SESSION_ROUTE, session_id) == 0 and polled(server) == []
refuse.clear()
assert wait_until(lambda: channel.connected.is_set() and entry.channel.attached, 10)
assert wait_until(lambda: channel.fallback.keepalive_stop.is_set(), 5)
logs = count(server, "GET", LOGS_ROUTE, session_id)
assert wait_until(lambda: "Listing EXAMPLE titles" in example_messages(caplog), 5)
assert service.get_tracks(titles[0]).audio
assert count(server, "GET", LOGS_ROUTE, session_id) == logs
assert example_messages(caplog).count("Listing EXAMPLE titles") == 1
assert count(server, "GET", SESSION_ROUTE, session_id) == 0 and polled(server) == []
finally:
service.close()
def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling(
def test_a_cdm_call_made_while_the_channel_is_down_waits_for_the_reconnect(
server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
refuse = gate_channel(monkeypatch)
@@ -584,6 +614,7 @@ def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling(
entry = store.peek(service._session_id)
asyncio.run_coroutine_threadsafe(entry.channel.ws.close(), server.loop).result(5)
assert wait_until(lambda: not service.channel.connected.is_set() and not entry.channel.attached, 5)
refuse.clear()
answers.append(stub._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"}))
StubService.hooks["titles"] = titles
@@ -592,7 +623,7 @@ def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling(
assert isinstance(service.channel, WebSocketChannel)
service.get_titles()
assert answers == [{"op": "close"}]
assert count(server, "GET", PROMPT_ROUTE, service._session_id) >= 1
assert polled(server) == []
finally:
service.close()