Files
unshackle/tests/remote/unit/test_session_lifetime.py
T

624 lines
23 KiB
Python

"""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 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 unshackle.core import process_exit, remote_lifetime, remote_service
from unshackle.core.api import handlers, routes, session_store
from unshackle.core.api.errors import APIError
from unshackle.core.api.session_store import SessionEntry
from unshackle.core.config import config
from unshackle.core.remote_channel import 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")
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 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_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_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
@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_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_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
with pytest.raises(APIError) as e:
handlers.new_session_id({})
assert e.value.error_code == APIErrorCode.CLIENT_OUTDATED
with pytest.raises(APIError) as e:
handlers.new_session_id({"session_id": named, "cdm_relay": True})
assert e.value.error_code == APIErrorCode.CLIENT_OUTDATED
def test_a_create_that_answers_after_the_end_leaves_no_session(
build: SimpleNamespace, caplog: pytest.LogCaptureFixture
) -> None:
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_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() == []
@pytest.fixture
def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]:
hooks: list[Any] = []
def unregister(hook: Any) -> None:
if hook in hooks:
hooks.remove(hook)
fake = SimpleNamespace(register=hooks.append, unregister=unregister)
monkeypatch.setattr(remote_lifetime, "atexit", fake) # other modules register hooks of their own meanwhile
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")]
@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_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) -> None:
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"]
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 == [] and process_exit.ends == set()
@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_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
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))
monkeypatch.setattr(WebSocketChannel, "connect", connect)
channel.close()
channel.thread.run()
assert channel.attempted.is_set()
assert connected == []