"""The background and probe calls of a remote session go through RemoteClient and so rotate the auth header.""" from __future__ import annotations import asyncio import json from collections.abc import Callable from threading import Thread from types import SimpleNamespace from typing import Any import pytest import responses from tests.remote.unit.test_session_reopen import SERVER, make_service from unshackle.core import remote_service from unshackle.core.remote_channel import ServerMessages, WebSocketChannel from unshackle.core.remote_protocol import ClientErrorKind from unshackle.core.remote_service import RemoteClient from unshackle.core.tunnel import TunnelClient, run_loop pytestmark = pytest.mark.unit KEY = "k" @pytest.fixture(autouse=True) def no_reopen_wait(monkeypatch: pytest.MonkeyPatch) -> None: """Give up on the first unanswered health probe, so a regression fails fast instead of waiting 30 minutes.""" monkeypatch.setattr(remote_service, "REOPEN_WAIT", 0.0) def second_header_only(body: dict, hit: Callable[[], None] = lambda: None) -> Callable[[Any], tuple]: """A route that refuses the first candidate header, as a server that reads only X-Api-Key does.""" def answer(request: Any) -> tuple: if request.headers.get("X-Api-Key") != KEY: return 401, {}, json.dumps({"status": 401, "message": "Secret Key is Invalid."}) hit() return 200, {"Content-Type": "application/json"}, json.dumps(body) return answer @responses.activate def test_wait_for_server_moves_to_the_next_auth_header() -> None: service = make_service() responses.add_callback(responses.GET, f"{SERVER}/api/health", callback=second_header_only({"status": "ok"})) assert service.wait_for_server(accepting=True) assert [c.response.status_code for c in responses.calls] == [401, 200] @responses.activate def test_recover_moves_to_the_next_auth_header() -> None: service = make_service() responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"}) responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only({"valid": True})) assert service.recover("s1", ClientErrorKind.CONNECT) assert service._session_id == "s1" @responses.activate def test_recover_waits_out_a_429_instead_of_reopening(monkeypatch: pytest.MonkeyPatch) -> None: waits: list[int] = [] monkeypatch.setattr(remote_service, "wait_retry_after", lambda seconds, *args: waits.append(seconds)) service = make_service() responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"}) url = f"{SERVER}/api/session/s1" responses.add(responses.GET, url, status=429, headers={"Retry-After": "5"}, json={}) responses.add(responses.GET, url, json={"valid": True}) assert service.recover("s1", ClientErrorKind.CONNECT) assert waits == [5] assert service._session_id == "s1" @responses.activate def test_a_tunnel_copies_the_auth_header_the_server_reads(monkeypatch: pytest.MonkeyPatch) -> None: sent: list[dict] = [] class Tunnel: def __init__(self, url: str, headers: dict, proxy: Any) -> None: sent.append(headers) def start(self) -> str: return "t1" monkeypatch.setattr(remote_service, "TunnelClient", Tunnel) client = RemoteClient(server_url=SERVER, api_key=KEY) responses.add_callback(responses.GET, f"{SERVER}/api/health", callback=second_header_only({"status": "ok"})) remote_service.start_tunnel(client) assert sent[0].get("X-Api-Key") == KEY and "X-Secret-Key" not in sent[0] def test_a_channel_closes_after_its_loop_has_closed() -> None: """A refused upgrade closes the loop of the channel thread before the thread ends.""" service = make_service() service.ctx = SimpleNamespace(obj=None) messages = ServerMessages(service) channel = WebSocketChannel(messages) loop = asyncio.new_event_loop() loop.close() channel.loop, channel.task = loop, SimpleNamespace(cancel=lambda: None) channel.thread = SimpleNamespace(is_alive=lambda: True, join=lambda timeout=None: None) channel.close() def refuse_threads_after_executor_use(monkeypatch: pytest.MonkeyPatch) -> Callable[[Any], Any]: """A run that uses the default executor, then refuses every new thread, as Python 3.12.0 to 3.12.2 do at exit.""" def refuse(self: Thread) -> None: raise RuntimeError("can't create new thread at interpreter shutdown") async def run(self: Any) -> None: await asyncio.get_running_loop().run_in_executor(None, lambda: None) monkeypatch.setattr(Thread, "start", refuse) return run def test_a_channel_loop_ends_without_starting_a_thread(monkeypatch: pytest.MonkeyPatch) -> None: """The channel thread shuts its loop's executor down without a new thread.""" monkeypatch.setattr(WebSocketChannel, "run", refuse_threads_after_executor_use(monkeypatch)) service = make_service() service.ctx = SimpleNamespace(obj=None) messages = ServerMessages(service) channel = WebSocketChannel(messages) channel.thread.run() def test_a_tunnel_loop_ends_without_starting_a_thread(monkeypatch: pytest.MonkeyPatch) -> None: """The tunnel thread, which the same atexit close stops, shuts its loop's executor down without a new thread.""" monkeypatch.setattr(TunnelClient, "run", refuse_threads_after_executor_use(monkeypatch)) client = TunnelClient(SERVER, {}) client.thread.run() def test_a_thread_loop_cancels_the_tasks_its_run_leaves() -> None: """A task that the run leaves, such as a channel answer still sending, ends cancelled when the loop closes.""" left: list[asyncio.Future[None]] = [] async def main() -> None: left.append(asyncio.ensure_future(asyncio.sleep(10))) run_loop(main) assert left[0].cancelled()