fix(remote): stop with one line when a remote server rejects the API key instead of building the stub command

This commit is contained in:
imSp4rky
2026-12-04 17:03:59 -07:00
parent 3bdca22bc7
commit 7a40b7739b
7 changed files with 180 additions and 15 deletions
+39 -1
View File
@@ -14,7 +14,7 @@ import requests
import responses
from unshackle.core.config import config
from unshackle.core.remote_protocol import ClientErrorKind
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
@@ -445,3 +445,41 @@ def test_any_other_requests_failure_is_one_remote_error(client: RemoteClient) ->
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
@@ -0,0 +1,100 @@
"""A remote server that rejects the API key stops the run with one line; an unreachable one keeps the stub."""
from __future__ import annotations
import json
from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Thread
import click
import pytest
from click.testing import CliRunner
from unshackle.commands.dl import dl
from unshackle.core import remote_service
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError
from unshackle.core.config import config
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.services import Services
from unshackle.core.utilities import get_free_port
KEY = "0" * 32
class Gateway(BaseHTTPRequestHandler):
calls = 0
def do_GET(self) -> None:
Gateway.calls += 1
body = json.dumps({"error": "unauthorized"}).encode()
self.send_response(401)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args: object) -> None:
pass
@pytest.fixture
def servers(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Gateway)
Thread(target=httpd.serve_forever, daemon=True).start()
closed_port = get_free_port()
monkeypatch.setattr(
config,
"remote_services",
{
"keyed": {"url": f"http://127.0.0.1:{httpd.server_address[1]}", "api_key": KEY},
"down": {"url": f"http://127.0.0.1:{closed_port}", "api_key": KEY},
},
)
remote_service.reset_remote_lists()
Gateway.calls = 0
yield
remote_service.reset_remote_lists()
httpd.shutdown()
httpd.server_close()
def test_a_rejected_key_stops_dl_with_one_line_not_a_stub_parse_error(servers: None) -> None:
result = CliRunner().invoke(dl.cli, ["--remote", "--server", "keyed", "EXAMPLE", "-ht", "1"])
assert result.exit_code != 0
assert "rejected the API key (HTTP 401)" in result.output
assert "No such option" not in result.output
assert KEY not in result.output
def test_an_unreachable_server_keeps_the_stub_command(servers: None) -> None:
cmd = Services.make_remote_command("EXAMPLE", "down")
assert cmd.name == "EXAMPLE"
assert cmd.help is None
def test_remote_list_answers_a_rejected_key_as_auth_failed(servers: None) -> None:
with pytest.raises(APIError) as e:
handlers.remote_list("keyed")
assert e.value.error_code == APIErrorCode.AUTH_FAILED and e.value.http_status == 424
assert "rejected the API key" in e.value.message and "\n" not in e.value.message
def test_a_cached_rejection_raises_again_without_a_new_request(servers: None) -> None:
raised = []
for _ in range(2):
with pytest.raises(click.ClickException) as e:
remote_service.remote_service_list("keyed")
raised.append(e.value)
calls = Gateway.calls
with pytest.raises(click.ClickException) as e:
remote_service.make_remote_service(None, "keyed", "EXAMPLE", "1", {})
assert Gateway.calls == calls
assert raised[0] is not raised[1]
assert e.value.error_code == APIErrorCode.AUTH_FAILED