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

292 lines
12 KiB
Python

"""Unit tests for unshackle.core.remote_service.RemoteClient."""
from __future__ import annotations
import json
import socket
import threading
from pathlib import Path
import pytest
import requests
import responses
from unshackle.core.config import config
from unshackle.core.remote_protocol import APIErrorCode, ClientErrorKind
from unshackle.core.remote_service import RemoteClient, RemoteError
from unshackle.core.utilities import close_debug_logger, init_debug_logger
pytestmark = pytest.mark.unit
@pytest.fixture
def client() -> RemoteClient:
return RemoteClient(server_url="http://srv:8786", api_key="secret-xyz")
def test_session_omits_secret_key_when_empty() -> None:
c = RemoteClient(server_url="http://srv:8786", api_key="")
assert "X-Secret-Key" not in c.session.headers
@responses.activate
def test_4xx_raises_systemexit_with_logged_error(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
responses.add(
responses.GET,
"http://srv:8786/api/session/none",
json={"error_code": "SESSION_NOT_FOUND", "message": "no such session"},
status=404,
)
with caplog.at_level("ERROR"), pytest.raises(SystemExit):
client.get("/api/session/none")
assert "SESSION_NOT_FOUND" in caplog.text
assert "no such session" in caplog.text
PROXY_502 = "<html><head><title>unshackle.dev | 502: Bad gateway</title></head></html>"
@responses.activate
def test_proxy_502_page_is_retried_once(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("unshackle.core.remote_service.time.sleep", lambda _s: None)
url = "http://srv:8786/api/session/abc/license"
responses.add(responses.POST, url, body=PROXY_502, status=502, content_type="text/html")
responses.add(responses.POST, url, json={"keys": {}}, status=200)
assert client.post("/api/session/abc/license", {}) == {"keys": {}}
assert len(responses.calls) == 2
@responses.activate
def test_second_proxy_502_page_exits(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("unshackle.core.remote_service.time.sleep", lambda _s: None)
url = "http://srv:8786/api/session/abc/license"
responses.add(responses.POST, url, body=PROXY_502, status=502, content_type="text/html")
with pytest.raises(SystemExit):
client.post("/api/session/abc/license", {})
assert len(responses.calls) == 2
@responses.activate
def test_401_falls_back_to_next_auth_header(client: RemoteClient) -> None:
seen: list[tuple[str | None, str | None]] = []
def cb(request):
seen.append((request.headers.get("X-Secret-Key"), request.headers.get("X-Api-Key")))
if request.headers.get("X-Api-Key") == "secret-xyz":
return (200, {}, json.dumps({"status": "ok"}))
return (401, {}, json.dumps({"message": "Secret Key is Invalid."}))
responses.add_callback(responses.GET, "http://srv:8786/api/services", callback=cb)
assert client.get("/api/services") == {"status": "ok"}
assert seen == [("secret-xyz", None), (None, "secret-xyz")]
# the winning header is sticky: no second attempt on the next request
seen.clear()
assert client.get("/api/services") == {"status": "ok"}
assert seen == [(None, "secret-xyz")]
@responses.activate
def test_non_401_error_does_not_fall_back(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
responses.add(
responses.GET,
"http://srv:8786/api/services",
json={"error_code": "FORBIDDEN", "message": "nope"},
status=403,
)
with caplog.at_level("ERROR"), pytest.raises(SystemExit):
client.get("/api/services")
assert len(responses.calls) == 1
assert client.session.headers.get("X-Secret-Key") == "secret-xyz"
@responses.activate
def test_401_on_every_header_exits(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
responses.add(
responses.GET,
"http://srv:8786/api/services",
json={"error_code": "UNAUTHORIZED", "message": "Secret Key is Invalid."},
status=401,
)
with caplog.at_level("ERROR"), pytest.raises(SystemExit):
client.get("/api/services")
assert len(responses.calls) == 2
assert "Secret Key is Invalid." in caplog.text
@responses.activate
def test_single_configured_auth_header_does_not_retry() -> None:
c = RemoteClient(server_url="http://srv:8786", api_key="k", auth_headers=["X-Api-Key"])
responses.add(responses.GET, "http://srv:8786/api/services", json={"message": "nope"}, status=401)
with pytest.raises(SystemExit):
c.get("/api/services")
assert len(responses.calls) == 1
assert c.session.headers.get("X-Api-Key") == "k"
@responses.activate
def test_late_error_after_heartbeat_is_fatal(client: RemoteClient) -> None:
"""A heartbeat response carries a late failure as a 200 error body after leading newlines."""
body = "\n\n" + json.dumps({"status": "error", "error_code": "SERVICE_ERROR", "message": "late"})
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")
@pytest.mark.parametrize(
("status", "code"),
[(422, "SERVICE_ERROR"), (404, "TRACK_NOT_FOUND"), (404, "SESSION_NOT_FOUND"), (503, "SERVER_DRAINING")],
)
@responses.activate
def test_a_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("/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
def test_a_429_with_retry_after_waits_then_retries(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None:
waits: list[int] = []
monkeypatch.setattr("unshackle.core.remote_service.wait_retry_after", waits.append)
url = "http://srv:8786/api/services"
responses.add(responses.GET, url, status=429, json={"status": 429}, headers={"Retry-After": "7"})
responses.add(responses.GET, url, json={"status": "ok"})
assert client.get("/api/services") == {"status": "ok"}
assert waits == [7]
@responses.activate
def test_a_429_without_retry_after_fails_at_once(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("unshackle.core.remote_service.wait_retry_after", pytest.fail)
responses.add(responses.GET, "http://srv:8786/api/services", status=429, json={"error_code": "RATE_LIMITED"})
with pytest.raises(SystemExit):
client.get("/api/services")
@responses.activate
def test_a_401_after_a_header_worked_keeps_that_header(client: RemoteClient) -> None:
responses.add(responses.GET, "http://srv:8786/api/services", json={"services": []})
responses.add(responses.GET, "http://srv:8786/api/health", status=401, json={"message": "Secret Key is Invalid."})
responses.add(responses.GET, "http://srv:8786/api/health", json={"status": "ok"})
client.get("/api/services")
assert client.probe("/api/health") == {}
assert client.probe("/api/health") == {"status": "ok"}
assert client.session.headers.get("X-Secret-Key") == "secret-xyz"
@responses.activate
def test_a_probe_does_not_wait_out_a_429(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None:
waits: list[int] = []
monkeypatch.setattr("unshackle.core.remote_service.wait_retry_after", waits.append)
responses.add(responses.GET, "http://srv:8786/api/session/s1", status=429, headers={"Retry-After": "5"}, json={})
assert client.probe("/api/session/s1") == {}
assert not waits
@responses.activate
def test_a_probe_reads_a_gateway_page_as_the_request_does(
client: RemoteClient, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("unshackle.core.remote_service.time.sleep", lambda _s: None)
url = "http://srv:8786/api/health"
responses.add(responses.GET, url, body=PROXY_502, status=502, content_type="text/html")
responses.add(responses.GET, url, json={"status": "ok"})
assert client.probe("/api/health") == {"status": "ok"}
responses.replace(responses.GET, url, body=PROXY_502, status=502, content_type="text/html")
assert client.probe("/api/health") == {}
@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
@responses.activate
@pytest.mark.parametrize(
("status", "body"),
[(401, {"error": "unauthorized"}), (403, {"error": "unauthorized"}), (401, {"message": "Secret Key is Invalid."})],
)
def test_a_401_or_json_403_without_a_code_is_a_rejected_key(client: RemoteClient, status: int, body: dict) -> None:
responses.add(responses.GET, "http://srv:8786/api/services", json=body, status=status)
with pytest.raises(RemoteError) as e:
client.get("/api/services")
assert e.value.kind == APIErrorCode.AUTH_FAILED
assert e.value.message == f"Remote server http://srv:8786 rejected the API key (HTTP {status})"
@responses.activate
def test_a_403_page_that_is_not_json_is_not_a_rejected_key(client: RemoteClient) -> None:
page = "<html><head><title>Access denied | srv.example</title></head></html>"
responses.add(responses.GET, "http://srv:8786/api/services", body=page, status=403, content_type="text/html")
with pytest.raises(RemoteError) as e:
client.get("/api/services")
assert e.value.kind != APIErrorCode.AUTH_FAILED
assert "Access denied" in e.value.message
@responses.activate
def test_a_serve_403_keeps_its_own_error_code(client: RemoteClient) -> None:
body = {"error_code": "FORBIDDEN", "message": "Key not allowed"}
responses.add(responses.GET, "http://srv:8786/api/services", json=body, status=403)
with pytest.raises(RemoteError) as e:
client.get("/api/services")
assert e.value.kind == APIErrorCode.FORBIDDEN