"""Who ends a remote session, and when: the client before and after the create reply, and the server during the build.""" from __future__ import annotations import asyncio import atexit import contextlib import signal import subprocess import sys import uuid from collections.abc import Callable, Iterator from pathlib import Path from threading import Event, Thread from types import SimpleNamespace from typing import Any import pytest import requests import responses from requests.adapters import HTTPAdapter from tests.remote.unit.test_remote_loopback import server # noqa: F401 from tests.remote.unit.test_remote_loopback import ( KEY, OTHER_KEY, StubService, count, make_client, ) from tests.remote.unit.test_remote_service_helpers import blob from tests.remote.unit.test_session_reopen import SERVER, make_service from tests.remote.unit.test_tunnel import wait_until from unshackle.core import remote_channel, remote_service from unshackle.core.api import handlers, routes, session_store from unshackle.core.api.download_manager import busy_services from unshackle.core.api.session_store import SessionEntry from unshackle.core.config import config from unshackle.core.remote_channel import PollingChannel, ServerMessages, WebSocketChannel from unshackle.core.remote_lifetime import Presses, RemoteSessionLifetime from unshackle.core.remote_protocol import SESSION_CREATE_ROUTE, SESSION_ROUTE, APIErrorCode, ClientErrorKind from unshackle.core.remote_service import RemoteError, RemoteService from unshackle.core.tunnel import TunnelClient pytestmark = pytest.mark.unit ROOT = Path(__file__).parents[3] DEADLINE = 20.0 posix_signals = pytest.mark.skipif(sys.platform == "win32", reason="a test cannot send SIGINT to one process") CLIENT = """ import sys, time from pathlib import Path import click from unshackle.core.config import config config.directories.cache = Path(sys.argv[2]) config.directories.cookies = Path(sys.argv[2]) / "cookies" config.credentials = {} from tests.remote.unit.test_remote_loopback import make_client service = make_client(sys.argv[1]) @click.command() def run(): service.authenticate() print("authenticated", flush=True) if sys.argv[3:]: service.close() print("closed", flush=True) time.sleep(120) run(args=[]) """ def sessions() -> list[SessionEntry]: return session_store.get_session_store().list() def cache_files() -> list[Path]: return list(config.directories.cache.rglob("*.json")) @pytest.fixture(autouse=True) def no_presses(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(Presses, "count", 0) @pytest.fixture def logins(monkeypatch: pytest.MonkeyPatch) -> list[Any]: """The logins that the server started; each one succeeds at once.""" started: list[Any] = [] monkeypatch.setattr(StubService, "authenticate", lambda self, cookies, credential: started.append(self)) return started @pytest.fixture def build(server: SimpleNamespace, logins: list[Any]) -> Iterator[SimpleNamespace]: # noqa: F811 """A server whose first service build waits for ``release``.""" barrier = SimpleNamespace(server=server, logins=logins, started=Event(), release=Event()) def hold(stub: StubService) -> None: if not barrier.started.is_set(): barrier.started.set() assert barrier.release.wait(DEADLINE), "the test did not release the build" StubService.hooks["init"] = hold try: yield barrier finally: barrier.release.set() def create(url: str, session_id: Any, key: str = KEY, **body: Any) -> requests.Response: data = {"service": "EXAMPLE", "title_id": "example-1", "session_id": session_id, **body} return requests.post(url + SESSION_CREATE_ROUTE, json=data, headers={"X-Secret-Key": key}, timeout=DEADLINE) def delete(url: str, session_id: str, key: str = KEY) -> requests.Response: route = SESSION_ROUTE.format(session_id=session_id) return requests.delete(url + route, headers={"X-Secret-Key": key}, timeout=DEADLINE) def in_thread(call: Callable[[], Any]) -> Callable[[], Any]: """Run *call* on a thread; the returned function waits for its result, or for the exception it raised.""" result: list[Any] = [] def run() -> None: try: result.append(call()) except BaseException as e: result.append(e) thread = Thread(target=run, daemon=True) thread.start() def wait() -> Any: thread.join(DEADLINE) assert not thread.is_alive() return result[0] return wait def error_code(response: requests.Response) -> str: return response.json()["error_code"] def answered(server: SimpleNamespace, status: int) -> bool: # noqa: F811 return ("POST", SESSION_CREATE_ROUTE, status) in server.seen @pytest.fixture def client(tmp_path: Path) -> Iterator[Callable[..., subprocess.Popen[str]]]: """Start a client process that logs in and then waits; its returned cache goes to ``client-cache``.""" started: list[subprocess.Popen[str]] = [] def start(url: str, *then: str) -> subprocess.Popen[str]: process = subprocess.Popen( [sys.executable, "-c", CLIENT, url, str(tmp_path / "client-cache"), *then], cwd=ROOT, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", start_new_session=True, ) started.append(process) return process yield start for process in started: process.kill() process.communicate() def wait_authenticated(process: subprocess.Popen[str]) -> None: assert process.stdout is not None for line in process.stdout: if "authenticated" in line: return pytest.fail("the client did not log in") @posix_signals def test_a_ctrl_c_before_the_create_reply_leaves_no_session( build: SimpleNamespace, client: Callable[[str], subprocess.Popen[str]] ) -> None: process = client(build.server.url) assert build.started.wait(DEADLINE) process.send_signal(signal.SIGINT) process.communicate(timeout=DEADLINE) assert count(build.server, "DELETE", SESSION_ROUTE) == 1 build.release.set() assert wait_until(lambda: answered(build.server, 404) or answered(build.server, 200), DEADLINE) assert sessions() == [] assert build.logins == [] class HeldDelete: """The DELETE route of the server, which waits for ``release`` before it does its work.""" def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: self.started, self.release = Event(), Event() handler = routes.session_delete_handler async def held(session_id: str, request: Any) -> Any: self.started.set() while not self.release.is_set(): await asyncio.sleep(0.01) return await handler(session_id, request) monkeypatch.setattr(routes, "session_delete_handler", held) @pytest.fixture def held_delete(monkeypatch: pytest.MonkeyPatch) -> Iterator[HeldDelete]: held = HeldDelete(monkeypatch) yield held held.release.set() def press_while_it_waits(process: subprocess.Popen[str]) -> None: """Send one Ctrl+C that the client must survive.""" process.send_signal(signal.SIGINT) with pytest.raises(subprocess.TimeoutExpired): process.wait(0.3) @posix_signals @pytest.mark.parametrize("gives_up", [False, True], ids=["one-press", "two-presses"]) @pytest.mark.parametrize("phase", ["create", "idle"]) def test_a_ctrl_c_during_the_end_is_ignored_once( build: SimpleNamespace, held_delete: HeldDelete, client: Callable[[str], subprocess.Popen[str]], tmp_path: Path, phase: str, gives_up: bool, ) -> None: """The first Ctrl+C starts the end, and the two that count come while its DELETE waits for the server.""" process = client(build.server.url) assert build.started.wait(DEADLINE) if phase == "idle": build.release.set() wait_authenticated(process) (entry,) = sessions() stored = config.directories.cache / str(entry.cache_tag) / "token.json" stored.parent.mkdir(parents=True) stored.write_text('"EXAMPLE"', encoding="utf-8") process.send_signal(signal.SIGINT) assert held_delete.started.wait(DEADLINE) press_while_it_waits(process) if gives_up: process.send_signal(signal.SIGINT) else: held_delete.release.set() output, _ = process.communicate(timeout=DEADLINE) held_delete.release.set() assert wait_until(lambda: count(build.server, "DELETE", SESSION_ROUTE) == 1, DEADLINE) build.release.set() assert wait_until(lambda: answered(build.server, 404 if phase == "create" else 200), DEADLINE) assert "Traceback" not in output and "KeyboardInterrupt" not in output saved = (tmp_path / "client-cache" / "EXAMPLE" / "token.json").exists() assert saved is (phase == "idle" and not gives_up) assert count(build.server, "DELETE", SESSION_ROUTE) == 1 and sessions() == [] assert len(build.logins) == (phase == "idle") @posix_signals def test_giving_up_on_the_close_of_the_run_stops_the_run( server: SimpleNamespace, # noqa: F811 logins: list[Any], held_delete: HeldDelete, client: Callable[..., subprocess.Popen[str]], ) -> None: process = client(server.url, "close") assert held_delete.started.wait(DEADLINE) press_while_it_waits(process) process.send_signal(signal.SIGINT) output, _ = process.communicate(timeout=DEADLINE) assert "closed" not in output and "Aborted" in output and "Traceback" not in output def test_a_delete_of_the_owner_ends_a_create_in_progress(build: SimpleNamespace) -> None: session_id = str(uuid.uuid4()) reply = in_thread(lambda: create(build.server.url, session_id, cache={"token": blob('"EXAMPLE"')})) assert build.started.wait(DEADLINE) assert delete(build.server.url, session_id, OTHER_KEY).status_code == 404 assert delete(build.server.url, session_id).status_code == 200 build.release.set() assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND assert sessions() == [] and build.logins == [] assert not (config.directories.cache / "_sessions").exists() assert delete(build.server.url, session_id).status_code == 404 def test_a_delete_of_another_key_leaves_a_create_in_progress(build: SimpleNamespace) -> None: session_id = str(uuid.uuid4()) reply = in_thread(lambda: create(build.server.url, session_id)) assert build.started.wait(DEADLINE) assert error_code(delete(build.server.url, session_id, OTHER_KEY)) == APIErrorCode.SESSION_NOT_FOUND build.release.set() assert reply().json()["session_id"] == session_id assert [s.session_id for s in sessions()] == [session_id] def test_the_id_of_another_key_is_refused(build: SimpleNamespace) -> None: session_id = str(uuid.uuid4()) reply = in_thread(lambda: create(build.server.url, session_id)) assert build.started.wait(DEADLINE) assert error_code(create(build.server.url, session_id, OTHER_KEY)) == APIErrorCode.FORBIDDEN build.release.set() assert reply().status_code == 200 (entry,) = sessions() assert error_code(create(build.server.url, session_id, OTHER_KEY)) == APIErrorCode.FORBIDDEN assert sessions() == [entry] and not entry.channel.ended def test_a_create_sent_again_takes_over_from_the_one_in_progress(build: SimpleNamespace) -> None: """A gateway error page makes the client send the same create again while the server still builds the first.""" session_id = str(uuid.uuid4()) cache = {"token": blob('"EXAMPLE"')} first = in_thread(lambda: create(build.server.url, session_id, cache=cache)) assert build.started.wait(DEADLINE) assert create(build.server.url, session_id, cache=cache).status_code == 200 (entry,) = sessions() build.release.set() assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND assert sessions() == [entry] and entry.owner_key == KEY assert cache_files() == [config.directories.cache / str(entry.cache_tag) / "token.json"] def test_a_create_sent_again_after_its_delete_is_refused(build: SimpleNamespace) -> None: session_id = str(uuid.uuid4()) first = in_thread(lambda: create(build.server.url, session_id)) assert build.started.wait(DEADLINE) assert delete(build.server.url, session_id).status_code == 200 assert error_code(create(build.server.url, session_id)) == APIErrorCode.SESSION_NOT_FOUND build.release.set() assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND assert sessions() == [] def test_a_create_sent_again_replaces_the_open_session_when_it_is_stored(build: SimpleNamespace) -> None: build.started.set() session_id = str(uuid.uuid4()) assert create(build.server.url, session_id, cache={"token": blob('"EXAMPLE"')}).status_code == 200 (first,) = sessions() build.started.clear() reply = in_thread(lambda: create(build.server.url, session_id, cache={"token": blob('"EXAMPLE"')})) assert build.started.wait(DEADLINE) assert sessions() == [first] and not first.channel.ended build.release.set() assert reply().status_code == 200 (second,) = sessions() assert second is not first and second.session_id == session_id assert first.channel.ended and not second.channel.ended assert cache_files() == [config.directories.cache / str(second.cache_tag) / "token.json"] @pytest.mark.parametrize("fault", ["body", "build", "cache"]) def test_a_create_sent_again_that_fails_leaves_the_open_session( server: SimpleNamespace, # noqa: F811 logins: list[Any], monkeypatch: pytest.MonkeyPatch, fault: str, ) -> None: session_id = str(uuid.uuid4()) assert create(server.url, session_id, cache={"token": blob('"EXAMPLE"')}).status_code == 200 (first,) = sessions() stored = cache_files() if fault == "build": monkeypatch.setitem(StubService.hooks, "init", lambda stub: 1 / 0) body: dict[str, Any] = {"body": {"title_id": ""}, "build": {}, "cache": {"cache": [1]}}[fault] assert create(server.url, session_id, **body).status_code >= 400 assert sessions() == [first] and not first.channel.ended assert cache_files() == stored and len(stored) == 1 def test_a_delete_ends_both_the_open_session_and_the_create_that_would_replace_it(build: SimpleNamespace) -> None: build.started.set() session_id = str(uuid.uuid4()) assert create(build.server.url, session_id).status_code == 200 build.started.clear() reply = in_thread(lambda: create(build.server.url, session_id)) assert build.started.wait(DEADLINE) assert delete(build.server.url, session_id).status_code == 200 assert sessions() == [] build.release.set() assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND assert sessions() == [] @pytest.mark.skipif(sys.platform == "darwin", reason="macOS has only one loopback address") @pytest.mark.parametrize("state", ["pending", "open"]) def test_an_id_stays_with_the_address_that_made_it(build: SimpleNamespace, state: str) -> None: """Every address is a different client, as in no-key mode, where all of them have the same API key.""" class OtherAddress(HTTPAdapter): def init_poolmanager(self, *args: Any, **kwargs: Any) -> None: super().init_poolmanager(*args, source_address=("127.0.0.2", 0), **kwargs) other = requests.Session() other.mount("http://", OtherAddress()) headers = {"X-Secret-Key": KEY} session_id = str(uuid.uuid4()) body = {"service": "EXAMPLE", "title_id": "example-1", "session_id": session_id} reply = in_thread(lambda: create(build.server.url, session_id)) assert build.started.wait(DEADLINE) if state == "open": build.release.set() assert reply().status_code == 200 url = build.server.url refused = other.post(url + SESSION_CREATE_ROUTE, json=body, headers=headers, timeout=DEADLINE) assert error_code(refused) == APIErrorCode.FORBIDDEN deleted = other.delete(url + SESSION_ROUTE.format(session_id=session_id), headers=headers, timeout=DEADLINE) assert deleted.status_code == (404 if state == "pending" else 403) build.release.set() assert reply().status_code == 200 (entry,) = sessions() assert entry.session_id == session_id and not entry.channel.ended def test_the_end_of_a_replaced_create_leaves_the_next_one_pending(build: SimpleNamespace) -> None: """The first create finishes while the second one still builds, and a DELETE must still find the second.""" session_id = str(uuid.uuid4()) second = SimpleNamespace(started=Event(), release=Event()) hold_first = StubService.hooks["init"] def hold(stub: StubService) -> None: if not build.started.is_set(): hold_first(stub) else: second.started.set() assert second.release.wait(DEADLINE) StubService.hooks["init"] = hold first = in_thread(lambda: create(build.server.url, session_id)) assert build.started.wait(DEADLINE) again = in_thread(lambda: create(build.server.url, session_id)) assert second.started.wait(DEADLINE) build.release.set() assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND assert delete(build.server.url, session_id).status_code == 200 second.release.set() assert error_code(again()) == APIErrorCode.SESSION_NOT_FOUND assert sessions() == [] def test_a_create_ended_before_its_build_builds_nothing( server: SimpleNamespace, # noqa: F811 logins: list[Any], monkeypatch: pytest.MonkeyPatch, ) -> None: started, release = Event(), Event() def resolve(*args: Any) -> Any: started.set() assert release.wait(DEADLINE) return None, [] monkeypatch.setattr(handlers, "resolve_handler_proxy", resolve) session_id = str(uuid.uuid4()) reply = in_thread(lambda: create(server.url, session_id)) assert started.wait(DEADLINE) assert delete(server.url, session_id).status_code == 200 release.set() assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND assert StubService.logins == 0 def test_a_session_deleted_between_its_store_and_its_login_starts_no_login( server: SimpleNamespace, # noqa: F811 logins: list[Any], monkeypatch: pytest.MonkeyPatch, ) -> None: """The store removes the cache directory of an evicted session after it stored the new one.""" store = session_store.get_session_store() real = store.create async def create_then_delete(*args: Any, **kwargs: Any) -> SessionEntry: entry = await real(*args, **kwargs) await store.delete(entry.session_id) return entry monkeypatch.setattr(store, "create", create_then_delete) assert error_code(create(server.url, str(uuid.uuid4()))) == APIErrorCode.SESSION_NOT_FOUND assert logins == [] def test_a_service_that_a_create_builds_is_not_reloaded( build: SimpleNamespace, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr("unshackle.core.api.stats.stats.mode", "remote_only") scheduled: list[str] = [] monkeypatch.setattr(session_store, "_schedule_pending_reload", scheduled.append) reply = in_thread(lambda: create(build.server.url, str(uuid.uuid4()))) assert build.started.wait(DEADLINE) assert busy_services() == {"EXAMPLE"} and scheduled == [] build.release.set() assert reply().status_code == 200 assert scheduled == ["EXAMPLE"] def test_a_create_that_is_refused_holds_no_id( server: SimpleNamespace, # noqa: F811 logins: list[Any], monkeypatch: pytest.MonkeyPatch, ) -> None: session_id = str(uuid.uuid4()) with monkeypatch.context() as broken: broken.setitem(StubService.hooks, "init", lambda stub: 1 / 0) assert create(server.url, session_id).status_code == 422 assert delete(server.url, session_id).status_code == 404 assert create(server.url, session_id, OTHER_KEY).status_code == 200 @pytest.mark.parametrize( "session_id", [ None, "", 7, "../../etc", "0f9e1c52-7b1c-11ef-9cd2-0242ac120002", "0F9E1C52-7B1C-41EF-9CD2-0242AC120002", "{0f9e1c52-7b1c-41ef-9cd2-0242ac120002}", "0f9e1c527b1c41ef9cd20242ac120002", "0f9e1c52-7b1c-41ef-9cd2-0242ac120002 ", ], ids=["null", "empty", "number", "path", "version-1", "upper-case", "braces", "no-dashes", "space"], ) def test_an_id_that_is_not_a_canonical_uuid4_is_refused(server: SimpleNamespace, session_id: Any) -> None: # noqa: F811 reply = create(server.url, session_id) assert reply.status_code == 400 and error_code(reply) == APIErrorCode.INVALID_INPUT assert StubService.logins == 0 def test_the_server_takes_the_id_that_the_client_names() -> None: named = RemoteSessionLifetime(SimpleNamespace(), lambda cache: None).name() # type: ignore[arg-type] assert handlers.new_session_id({"session_id": named}) == named assert uuid.UUID(handlers.new_session_id({})).version == 4 def test_a_create_that_times_out_is_deleted(build: SimpleNamespace) -> None: service = make_client(build.server.url) service.client.timeout = 1.0 with pytest.raises(RemoteError) as e: service.authenticate() assert e.value.kind == ClientErrorKind.TIMEOUT assert count(build.server, "DELETE", SESSION_ROUTE) == 1 assert service._session_id is None build.release.set() assert wait_until(lambda: answered(build.server, 404) or answered(build.server, 200), DEADLINE) assert sessions() == [] and build.logins == [] service.close() assert count(build.server, "DELETE", SESSION_ROUTE) == 1 @pytest.mark.parametrize("older", [False, True], ids=["server", "older-server"]) def test_a_create_that_answers_after_the_end_leaves_no_session( build: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, older: bool ) -> None: """An older server picks the id itself, so the DELETE of the named id finds nothing and the reply is deleted.""" if older: monkeypatch.setattr(handlers, "new_session_id", lambda data: str(uuid.uuid4())) service = make_client(build.server.url) opened = in_thread(service.authenticate) assert build.started.wait(DEADLINE) service.close() build.release.set() error = opened() assert isinstance(error, RemoteError) and error.kind == APIErrorCode.SESSION_NOT_FOUND assert sessions() == [] assert service._session_id is None and service.channel is None assert not [seen for seen in build.server.seen if seen[0] == "GET"] assert not [r for r in caplog.records if r.levelname == "ERROR"] def test_the_client_takes_the_id_that_an_older_server_picks( server: SimpleNamespace, # noqa: F811 logins: list[Any], monkeypatch: pytest.MonkeyPatch, ) -> None: picked = str(uuid.uuid4()) monkeypatch.setattr(handlers, "new_session_id", lambda data: picked) service = make_client(server.url) service.authenticate() assert service._session_id == picked service.close() assert sessions() == [] assert count(server, "DELETE", SESSION_ROUTE) == 1 def test_an_ended_owner_never_opens_again(server: SimpleNamespace, logins: list[Any]) -> None: # noqa: F811 service = make_client(server.url) service.authenticate() service.close() assert not service.wait_for_server(accepting=True) assert not service.recover(None, ClientErrorKind.CONNECT) assert not service.reopen() with pytest.raises(RemoteError): service.authenticate() assert len(logins) == 1 and sessions() == [] def test_the_end_does_not_wait_for_a_reopen(server: SimpleNamespace, logins: list[Any]) -> None: # noqa: F811 service = make_client(server.url) service.authenticate() with service._reopen_lock: assert in_thread(service.close)() is None assert sessions() == [] @pytest.fixture def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]: hooks: list[Any] = [] monkeypatch.setattr(atexit, "register", hooks.append) monkeypatch.setattr(atexit, "unregister", lambda hook: hooks.remove(hook) if hook in hooks else None) return hooks def local_proxy_client(monkeypatch: pytest.MonkeyPatch, start: Callable[[], str]) -> tuple[RemoteService, list[Any]]: """A client with --local-proxy whose tunnel starts with *start*, and the tunnels that it stopped.""" stopped: list[Any] = [] class Tunnel: id = "t1" lost = False def __init__(self, *args: Any) -> None: self.start = start def stop(self) -> None: stopped.append(self) monkeypatch.setattr(remote_service, "TunnelClient", Tunnel) monkeypatch.setattr("unshackle.core.utils.ip_info.get_ip_info", lambda *args, **kwargs: None) service = make_client(SERVER) service.client._auth_header_found = True service.ctx.parent.params = {"local_proxy": True} return service, stopped def interrupt(*args: Any) -> Any: raise KeyboardInterrupt @pytest.mark.parametrize("at", ["start", "log", "argv"]) def test_an_exit_before_the_create_stops_the_tunnel( monkeypatch: pytest.MonkeyPatch, exit_hooks: list[Any], at: str ) -> None: hooked: list[int] = [] def start() -> str: hooked.append(len(exit_hooks)) return interrupt() if at == "start" else "t1" service, stopped = local_proxy_client(monkeypatch, start) if at == "log": monkeypatch.setattr(service.log, "info", interrupt) elif at == "argv": monkeypatch.setattr(remote_service, "launch_keys", interrupt) with pytest.raises(KeyboardInterrupt): service.authenticate() assert hooked == [1] assert len(stopped) == 1 and service.client.tunnel is None service.close() assert exit_hooks == [] def test_an_interrupted_end_can_run_again(exit_hooks: list[Any]) -> None: service = make_service() sent: list[str] = [] saved: list[dict[str, str]] = [] answers = [interrupt, lambda: SimpleNamespace(ok=True, json=lambda: {"cache": {"token": "x"}})] def send(method: str, endpoint: str, timeout: float, background: bool = False) -> Any: assert background and timeout <= 15 sent.append(endpoint) return answers[len(sent) - 1]() service.client.send = send # type: ignore[method-assign,assignment] service.lifetime.save_cache = saved.append hook = service.lifetime.end_at_exit exit_hooks.append(hook) with pytest.raises(KeyboardInterrupt): service.close() assert saved == [] and exit_hooks == [hook] hook() service.close() assert sent == ["/api/session/s1"] * 2 assert saved == [{"token": "x"}] and exit_hooks == [] def test_the_end_gives_up_after_a_failed_delete_and_saves_before_the_rest( exit_hooks: list[Any], caplog: pytest.LogCaptureFixture ) -> None: service = make_service() order: list[str] = [] service.lifetime.channel = SimpleNamespace(close=lambda: order.append("channel")) # type: ignore[assignment] service.client.tunnel = SimpleNamespace(stop=lambda: order.append("tunnel"), lost=False) # type: ignore[assignment] service.lifetime.save_cache = lambda cache: order.append("cache") with responses.RequestsMock() as mocked: mocked.add(responses.DELETE, f"{SERVER}/api/session/s1", body=requests.Timeout()) service.close() service.close() assert order == ["channel", "cache", "tunnel"] assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")] def test_the_end_on_another_thread_leaves_the_signal_handlers() -> None: before = signal.getsignal(signal.SIGINT) seen: list[Any] = [] service = make_service() service.client.send = lambda *a, **k: seen.append(signal.getsignal(signal.SIGINT)) or interrupt() # type: ignore assert isinstance(in_thread(service.close)(), KeyboardInterrupt) service.lifetime.end_at_exit() assert seen[0] is before and seen[1] is not before assert signal.getsignal(signal.SIGINT) is before @pytest.mark.parametrize( "kind,deleted", [(ClientErrorKind.TUNNEL_CLOSED, True), (ClientErrorKind.TIMEOUT, True), (APIErrorCode.SESSION_NOT_FOUND, False)], ) @responses.activate def test_a_reopen_ends_the_session_it_gives_up(monkeypatch: pytest.MonkeyPatch, kind: str, deleted: bool) -> None: service = make_service() order: list[Any] = [] service.lifetime.save_cache = order.append monkeypatch.setattr(service, "reopen", lambda: order.append("reopen") or True) responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"}) responses.add(responses.GET, f"{SERVER}/api/session/s1", status=503, json={}) responses.add(responses.DELETE, f"{SERVER}/api/session/s1", json={"status": "ok", "cache": {"token": "x"}}) assert service.recover("s1", kind) assert order == ([{"token": "x"}] if deleted else []) + ["reopen"] assert service._session_id is None and not service.lifetime.ended def test_a_search_interrupted_in_its_tunnel_stops_it(monkeypatch: pytest.MonkeyPatch) -> None: service, stopped = local_proxy_client(monkeypatch, interrupt) with pytest.raises(KeyboardInterrupt): list(service.search()) assert len(stopped) == 1 @pytest.mark.parametrize("channel", ["socket", "polling"]) def test_an_end_during_the_login_is_silent( server: SimpleNamespace, # noqa: F811 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, channel: str, ) -> None: asked, release = Event(), Event() def login(stub: StubService, cookies: Any, credential: Any) -> None: asked.set() release.wait(DEADLINE) monkeypatch.setattr(StubService, "authenticate", login) if channel == "polling": monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False) service = make_client(server.url) opened = in_thread(service.authenticate) try: assert asked.wait(DEADLINE) assert wait_until(lambda: isinstance(service.channel, WebSocketChannel | PollingChannel), DEADLINE) service.close() assert isinstance(opened(), RemoteError) finally: release.set() assert sessions() == [] assert not [seen for seen in server.seen if "/None" in seen[1]] assert not [r for r in caplog.records if r.levelname == "ERROR" and r.name.startswith("remote_")] assert channel == "polling" or not service.client.no_channel def test_an_end_during_the_channel_open_is_silent( server: SimpleNamespace, # noqa: F811 logins: list[Any], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, ) -> None: service = make_client(server.url) connect = WebSocketChannel.open def end_then_open(self: WebSocketChannel, timeout: float = 10) -> bool: assert in_thread(service.close)() is None self.stopped = False return connect(self, timeout) monkeypatch.setattr(WebSocketChannel, "open", end_then_open) with pytest.raises(RemoteError): service.authenticate() assert not [seen for seen in server.seen if "/None" in seen[1]] assert not [r for r in caplog.records if r.levelname == "ERROR"] assert not service.client.no_channel def test_an_exit_in_the_channel_open_closes_the_channel( server: SimpleNamespace, # noqa: F811 logins: list[Any], monkeypatch: pytest.MonkeyPatch, ) -> None: closed: list[Any] = [] monkeypatch.setattr(WebSocketChannel, "open", interrupt) monkeypatch.setattr(WebSocketChannel, "close", lambda self: closed.append(self)) service = make_client(server.url) with pytest.raises(KeyboardInterrupt): service.authenticate() assert len(closed) == 1 and sessions() == [] def test_a_reopen_after_a_drain_ends_the_session_and_not_its_owner( server: SimpleNamespace, # noqa: F811 logins: list[Any], exit_hooks: list[Any], ) -> None: service = make_client(server.url) service.authenticate() first = service._session_id service.reopen_after_drain() assert [s.session_id for s in sessions()] == [service._session_id] != [first] assert count(server, "DELETE", SESSION_ROUTE) == 1 assert len(exit_hooks) == 1 and not service.lifetime.ended service.close() assert sessions() == [] and exit_hooks == [] def test_the_save_of_the_returned_cache_is_not_interrupted() -> None: service = make_service() saved: list[dict[str, str]] = [] def save(cache: dict[str, str]) -> None: signal.raise_signal(signal.SIGINT) signal.raise_signal(signal.SIGINT) saved.append(cache) service.lifetime.save_cache = save service.client.send = lambda *a, **k: SimpleNamespace(ok=True, json=lambda: {"cache": {"token": "x"}}) # type: ignore service.close() assert saved == [{"token": "x"}] def test_a_press_that_a_destructor_swallows_does_not_disable_the_next() -> None: service = make_service() def send(*args: Any, **kwargs: Any) -> Any: signal.raise_signal(signal.SIGINT) with contextlib.suppress(KeyboardInterrupt): signal.raise_signal(signal.SIGINT) signal.raise_signal(signal.SIGINT) pytest.fail("the third press did not stop the end") service.client.send = send # type: ignore[method-assign] with pytest.raises(KeyboardInterrupt): service.close() def test_a_user_who_gave_up_waits_for_no_other_end(exit_hooks: list[Any]) -> None: first, second = make_service(), make_service() def send(*args: Any, **kwargs: Any) -> Any: signal.raise_signal(signal.SIGINT) signal.raise_signal(signal.SIGINT) first.client.send = second.client.send = send # type: ignore[method-assign,assignment] with pytest.raises(KeyboardInterrupt): first.close() second.client.send = pytest.fail # type: ignore[method-assign,assignment] second.lifetime.end_at_exit() assert second.lifetime.ended def test_an_ignored_ctrl_c_stays_ignored(monkeypatch: pytest.MonkeyPatch) -> None: """A process that nohup or a shell started with SIGINT ignored keeps that during the end.""" service = make_service() seen: list[Any] = [] service.client.send = lambda *a, **k: seen.append(signal.getsignal(signal.SIGINT)) # type: ignore before = signal.signal(signal.SIGINT, signal.SIG_IGN) try: service.close() finally: signal.signal(signal.SIGINT, before) assert seen == [signal.SIG_IGN] @pytest.mark.parametrize("fault", ["send", "body", "shape", "save"]) def test_a_fault_of_one_delete_does_not_stop_the_rest(exit_hooks: list[Any], fault: str) -> None: service = make_service() service.lifetime.name() sent: list[str] = [] stopped: list[int] = [] def broken(*args: Any) -> Any: raise {"save": SystemExit, "body": RecursionError}.get(fault, RuntimeError)("EXAMPLE fault") def send(method: str, endpoint: str, timeout: float, background: bool) -> Any: sent.append(endpoint) if fault == "send": broken() return SimpleNamespace(ok=True, json=broken if fault == "body" else lambda: [] if fault == "shape" else {}) service.client.send = send # type: ignore[method-assign] service.client.tunnel = SimpleNamespace(stop=lambda: stopped.append(1), lost=False) # type: ignore[assignment] if fault == "save": service.lifetime.save_cache = broken exit_hooks.append(service.lifetime.end_at_exit) service.close() assert len(sent) == 2 and stopped == [1] and exit_hooks == [] service.close() assert len(sent) == 2 @responses.activate def test_the_error_of_a_failed_create_is_the_one_that_the_user_sees() -> None: service = make_client(SERVER) error = {"status": "error", "error_code": "AUTH_FAILED", "message": "EXAMPLE reason"} responses.add(responses.POST, SERVER + SESSION_CREATE_ROUTE, json=error, status=422) service.lifetime.save_cache = interrupt with pytest.raises(RemoteError, match="EXAMPLE reason"): service.authenticate() def test_an_interrupted_channel_close_runs_again() -> None: service = make_service() closes = iter([interrupt, lambda: None]) service.lifetime.channel = SimpleNamespace(close=lambda: next(closes)()) # type: ignore[assignment] service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore with pytest.raises(KeyboardInterrupt): service.close() service.close() assert next(closes, None) is None and service.channel is None def test_a_release_keeps_what_another_thread_opened_meanwhile() -> None: service = make_service() channel: Any = SimpleNamespace(close=lambda: None) tunnel: Any = SimpleNamespace(stop=lambda: None, lost=False) service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore service.lifetime.channel = SimpleNamespace(close=lambda: setattr(service.lifetime, "channel", channel)) # type: ignore service.client.tunnel = SimpleNamespace(stop=lambda: setattr(service.client, "tunnel", tunnel), lost=False) # type: ignore service.lifetime.release() assert service.channel is channel and service.client.tunnel is tunnel @pytest.mark.parametrize("at", ["hook", "create", "end"]) def test_an_end_of_another_thread_stops_the_opening( server: SimpleNamespace, # noqa: F811 logins: list[Any], exit_hooks: list[Any], monkeypatch: pytest.MonkeyPatch, at: str, ) -> None: """Each test hook ends the owner from another thread at one point of the opening.""" service = make_client(server.url) def end(*args: Any) -> Any: assert in_thread(service.close)() is None return {} if at == "hook": monkeypatch.setattr(atexit, "register", lambda hook: end() and None or exit_hooks.append(hook)) elif at == "create": monkeypatch.setattr(remote_service, "launch_keys", end) else: drain = service.drain_server_logs monkeypatch.setattr(service, "drain_server_logs", lambda: (drain(), end())) monkeypatch.setattr(WebSocketChannel, "keep_alive", lambda self: None) with pytest.raises(RemoteError): service.authenticate() assert sessions() == [] and exit_hooks == [] assert count(server, "POST", SESSION_CREATE_ROUTE) == (2 if at == "end" else 0) def test_an_ended_owner_opens_no_tunnel(monkeypatch: pytest.MonkeyPatch) -> None: service, _ = local_proxy_client(monkeypatch, lambda: pytest.fail("the ended owner opened a tunnel")) service.close() with pytest.raises(RemoteError): service.authenticate() @pytest.mark.parametrize("thread", ["tunnel", "channel"]) def test_a_stop_before_the_thread_runs_keeps_it_from_connecting(monkeypatch: pytest.MonkeyPatch, thread: str) -> None: connected: list[Any] = [] async def connect(self: Any) -> None: connected.append(self) if thread == "tunnel": tunnel = TunnelClient(SERVER, {}) monkeypatch.setattr(TunnelClient, "connect", connect) tunnel.stop() tunnel.thread.run() else: service = make_service() service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment] channel = WebSocketChannel(ServerMessages(service), PollingChannel(ServerMessages(service))) monkeypatch.setattr(WebSocketChannel, "connect", connect) channel.close() channel.thread.run() assert channel.attempted.is_set() assert connected == [] def test_the_end_does_not_wait_for_a_cdm_call(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(remote_channel, "CDM_CLOSE_TIMEOUT", 0.01) service = make_service() service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment] messages = ServerMessages(service) with messages.cdm_lock: assert in_thread(messages.close_cdm_sessions)() is None def test_the_tunnel_test_stops_the_tunnel_it_was_interrupted_in(monkeypatch: pytest.MonkeyPatch) -> None: from unshackle.commands import tunnel_test service, stopped = local_proxy_client(monkeypatch, interrupt) monkeypatch.setattr(tunnel_test, "get_ip_info", lambda session=None: {"ip": "192.0.2.1"}) monkeypatch.setattr(tunnel_test, "remote_client", lambda name: service.client) with pytest.raises(KeyboardInterrupt): tunnel_test.tunnel_test.callback(None, None) assert len(stopped) == 1 def test_a_press_after_the_end_does_not_leave_its_handler(monkeypatch: pytest.MonkeyPatch) -> None: service = make_service() service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore before, set_handler = signal.getsignal(signal.SIGINT), signal.signal def press_first(signum: int, handler: Any) -> Any: if handler is before: signal.raise_signal(signal.SIGINT) signal.raise_signal(signal.SIGINT) return set_handler(signum, handler) monkeypatch.setattr(signal, "signal", press_first) service.close() assert signal.getsignal(signal.SIGINT) is before def test_a_channel_of_an_ended_owner_stops_by_itself() -> None: service = make_service() service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment] channel = WebSocketChannel(ServerMessages(service), PollingChannel(ServerMessages(service))) service.lifetime.ended = True channel.thread.run() assert channel.attempted.is_set() and not channel.connected.is_set() def test_a_create_of_a_reopen_passes_through_the_old_channel() -> None: """The client's in_flight hook stays the one of the closed channel until the new channel is open.""" service = make_service() channel = PollingChannel(ServerMessages(service)) service.lifetime.session_id = None with channel.in_flight(SESSION_CREATE_ROUTE): assert channel.cdm_requests == 0