mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 07:25:08 +00:00
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:
@@ -17,7 +17,7 @@ Start the server with [`unshackle serve`](../../guide/cli-reference.md). By defa
|
||||
- **CORS.** Every response carries permissive CORS headers, and the server answers `OPTIONS` preflight requests automatically.
|
||||
- **Compression.** JSON responses of 256 bytes or more are gzip-compressed when the client sends `Accept-Encoding: gzip`. A [slow response](#slow-responses) is not compressed.
|
||||
- **Service allowlist.** The effective allowlist for your API key filters the service-facing endpoints (the intersection of the global `serve.services` list and your per-key list). The server treats services you cannot use as unknown.
|
||||
- **Remote services.** A full-mode server can run a service through one of its own `remote_services` servers (see [Remote sessions](remote-sessions.md)). `GET /api/config` lists their names in `remote_services`, and `GET /api/services?remote=<name>` lists that server's services, each with `remote` set to the name. Add `"remote": "<name>"` to `POST /api/search`, `/api/list-titles`, `/api/list-tracks` or `/api/download`, and the server opens a remote session with its own key for that server: the remote logs in and resolves titles, tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or an alias, and your allowlist applies to it. An unknown name is `400 INVALID_PARAMETERS`, a server that does not answer is `SERVICE_UNAVAILABLE`, and a tag it does not offer is `INVALID_SERVICE`. List calls from the same API key for the same title, profile, proxy, client region and service options share one remote session, which closes after 120 seconds unused. When the server stops, a list call that waits on the login of a new remote session, or starts one, gets `SERVER_DRAINING` (409). A call that opens a lost remote session again can be cut too: `list-titles` then gets `SERVER_DRAINING`, and `list-tracks` that or `SERVICE_ERROR` (422). An optional `client_name` names your client on the remote server's dashboard as `serve (<client_name>)`. A relayed search opens no remote session. The server sends its own credentials, cookies and cache for the `profile` with the search. A service that searches with no login gets none of them. A `--remote-only` server does not relay. A remote login that waits on you (a pair code or URL to approve on another device) cannot answer through a list call, so poll `GET /api/remote/logins` alongside it: each entry carries the login's `notice`, its `qr` (the text of a QR code to scan, or null), and its `prompt` when it asks a question (an OTP), which you answer with `POST /api/remote/logins/{id}/input` and `{"response": "..."}`. A remote download job shows the same text as its own `notice`, and asks a question (an OTP) through `input_prompt` as a local job does.
|
||||
- **Remote services.** A full-mode server can run a service through one of its own `remote_services` servers (see [Remote sessions](remote-sessions.md)). `GET /api/config` lists their names in `remote_services`, and `GET /api/services?remote=<name>` lists that server's services, each with `remote` set to the name. Add `"remote": "<name>"` to `POST /api/search`, `/api/list-titles`, `/api/list-tracks` or `/api/download`, and the server opens a remote session with its own key for that server: the remote logs in and resolves titles, tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or an alias, and your allowlist applies to it. An unknown name is `400 INVALID_PARAMETERS`, a server that does not answer is `SERVICE_UNAVAILABLE`, a server that rejects this server's API key is `AUTH_FAILED` (424), and a tag it does not offer is `INVALID_SERVICE`. List calls from the same API key for the same title, profile, proxy, client region and service options share one remote session, which closes after 120 seconds unused. When the server stops, a list call that waits on the login of a new remote session, or starts one, gets `SERVER_DRAINING` (409). A call that opens a lost remote session again can be cut too: `list-titles` then gets `SERVER_DRAINING`, and `list-tracks` that or `SERVICE_ERROR` (422). An optional `client_name` names your client on the remote server's dashboard as `serve (<client_name>)`. A relayed search opens no remote session. The server sends its own credentials, cookies and cache for the `profile` with the search. A service that searches with no login gets none of them. A `--remote-only` server does not relay. A remote login that waits on you (a pair code or URL to approve on another device) cannot answer through a list call, so poll `GET /api/remote/logins` alongside it: each entry carries the login's `notice`, its `qr` (the text of a QR code to scan, or null), and its `prompt` when it asks a question (an OTP), which you answer with `POST /api/remote/logins/{id}/input` and `{"response": "..."}`. A remote download job shows the same text as its own `notice`, and asks a question (an OTP) through `input_prompt` as a local job does.
|
||||
|
||||
!!! warning "Error responses have two shapes"
|
||||
Structured application errors (raised inside a handler) return `{"status": "error", "error_code": "...", "message": "...", "timestamp": "..."}`. The authentication middleware, however, returns a **different** shape: `{"status": 401, "message": "..."}` with an integer `status` and no `error_code`. The same middleware answers `429` in that shape when an API key goes over its rate limit. Clients must accept both shapes. The [Error responses](#error-responses) section at the bottom of this page gives the full error model.
|
||||
|
||||
@@ -117,7 +117,7 @@ while the server restarts.
|
||||
| `INVALID_SERVICE` | 400 | The named service is unknown, or is not permitted for your API key. |
|
||||
| `INVALID_PROXY` | 400 | The supplied proxy specification could not be resolved or is malformed, or the proxy failed the [exit check](../../guide/proxies-and-vpn.md#exit-check). |
|
||||
| `INVALID_PARAMETERS` | 400 | One or more download or query parameters failed validation (bad codec, bitrate, sort field, and so on). |
|
||||
| `AUTH_FAILED` | 401 | Authentication with the streaming service failed (bad credentials or cookies). |
|
||||
| `AUTH_FAILED` | 401 | Authentication with the streaming service failed (bad credentials or cookies). With status `424`, a `remote_services` server rejected the API key of this server. |
|
||||
| `FORBIDDEN` | 403 | The action is not allowed. Raised by server-side gates (per-key restrictions on CDM or credential overrides) and by remote session IP binding. |
|
||||
| `SERVER_CDM_CAPPED` | 403 | The server CDM does not license live above the `server_cdm_max_height` of the API key. `details.reason` is `server_cdm_max_height` (with `details.max_height`), `client_device`, for a remote session where the client's own device licenses, or `server_device`, for a remote session that runs on the server's device. A remote client licenses the track with its own device, except for `server_device`: then only its own vaults can supply the key. |
|
||||
| `GEOFENCE` | 403 | The title is not available in the applicable region. |
|
||||
|
||||
@@ -154,6 +154,11 @@ no longer moves the API key to another name. Names you give keep your spelling a
|
||||
are not repeated in the fallbacks, so unshackle tries
|
||||
`auth_headers: ["Authorization", "x-secret-key"]` as `Authorization`, `x-secret-key`, `X-Api-Key`.
|
||||
|
||||
When the server answers `401` to each name, or `403` with a JSON body and no `error_code`, the
|
||||
run stops with one line: `Remote server <url> rejected the API key (HTTP 401)`. When the server
|
||||
does not answer, `dl --remote` keeps a service command with no service options, so `--help` still
|
||||
works.
|
||||
|
||||
`timeout` is the time in seconds that the client waits for data from the server. The
|
||||
default is `120`. The server sends a heartbeat every 30 seconds while it gets titles, tracks
|
||||
or licences, so a slow service does not cause a timeout. Increase `timeout` only when the
|
||||
|
||||
@@ -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
|
||||
@@ -419,7 +419,10 @@ class RequestCache:
|
||||
|
||||
|
||||
def remote_list(name: Any) -> list[dict]:
|
||||
"""The services of a configured ``remote_services`` server; an APIError for an unknown or unreachable one."""
|
||||
"""The services of a configured ``remote_services`` server; an APIError for an unknown or unreachable one.
|
||||
|
||||
A server that rejects this server's API key is a 424 AUTH_FAILED, not a 401: the caller's own key is valid.
|
||||
"""
|
||||
from unshackle.core.api.stats import stats
|
||||
from unshackle.core.remote_service import remote_service_list
|
||||
|
||||
@@ -427,7 +430,10 @@ def remote_list(name: Any) -> list[dict]:
|
||||
raise APIError(APIErrorCode.INVALID_PARAMETERS, "A remote-only server does not relay to other servers")
|
||||
if not isinstance(name, str) or name not in (config.remote_services or {}):
|
||||
raise APIError(APIErrorCode.INVALID_PARAMETERS, f"Unknown remote server: {sanitize_log(str(name))}")
|
||||
services = remote_service_list(name)
|
||||
try:
|
||||
services = remote_service_list(name)
|
||||
except click.ClickException as e:
|
||||
raise APIError(getattr(e, "error_code", APIErrorCode.AUTH_FAILED), e.message, http_status=424) from None
|
||||
if services is None:
|
||||
raise APIError(APIErrorCode.SERVICE_UNAVAILABLE, f"Remote server '{name}' is unreachable")
|
||||
return services
|
||||
|
||||
@@ -354,6 +354,7 @@ class RemoteClient:
|
||||
"""Send one request and return its JSON body; an error outside ``expect`` exits, one inside it returns.
|
||||
|
||||
A raw ``body`` goes as ``application/octet-stream``, and a binary answer comes back under ``"body"``.
|
||||
A 401, or a JSON 403, with no error code is a rejected API key; a 403 page is a gateway block, such as a WAF.
|
||||
"""
|
||||
payload: dict[str, Any] = (
|
||||
{"json": data} if body is None else {"data": body, "headers": {"Content-Type": "application/octet-stream"}}
|
||||
@@ -391,6 +392,12 @@ class RemoteClient:
|
||||
)
|
||||
late_error = detail.get("status") == "error" and "error_code" in detail
|
||||
if resp.status_code >= 400 or late_error:
|
||||
if "error_code" not in detail and (resp.status_code == 401 or (resp.status_code == 403 and detail)):
|
||||
server_url = safe_display_url(self.server_url)
|
||||
raise RemoteError(
|
||||
f"Remote server {server_url} rejected the API key (HTTP {resp.status_code})",
|
||||
APIErrorCode.AUTH_FAILED,
|
||||
)
|
||||
page_title = re.search(r"<title>(.*?)</title>", resp.text, re.S) if not detail else None
|
||||
fallback = f"HTTP {resp.status_code}: {page_title.group(1).strip()}" if page_title else resp.text
|
||||
error_msg = redact_secrets(str(detail.get("message", fallback)), data)
|
||||
@@ -576,7 +583,7 @@ def resolve_server(server_name: str | None) -> tuple[str, str, dict]:
|
||||
|
||||
REMOTE_LIST_TTL = 300.0
|
||||
REMOTE_LIST_FAILURE_TTL = 30.0
|
||||
_remote_lists: dict[str | None, tuple[float, list[dict] | None]] = {}
|
||||
_remote_lists: dict[str | None, tuple[float, list[dict] | str | None]] = {}
|
||||
_remote_list_locks: dict[str | None, Lock] = {}
|
||||
|
||||
|
||||
@@ -589,28 +596,37 @@ def remote_client(server_name: str | None) -> RemoteClient:
|
||||
def remote_service_list(server_name: str | None) -> list[dict] | None:
|
||||
"""The services a ``remote_services`` server offers, cached for ``REMOTE_LIST_TTL``; None when it is unreachable.
|
||||
|
||||
A failure is cached for ``REMOTE_LIST_FAILURE_TTL``, so a server that is down does not stall every caller
|
||||
for its timeout, and a blip does not hide its services for long. One caller fetches; the rest wait for it.
|
||||
A server that rejects the API key raises a ClickException coded AUTH_FAILED. A failure is cached for
|
||||
``REMOTE_LIST_FAILURE_TTL``, so a server that is down does not stall every caller for its timeout, and a blip
|
||||
does not hide its services for long. One caller fetches; the rest wait for it.
|
||||
"""
|
||||
|
||||
def cached() -> tuple[float, list[dict] | None] | None:
|
||||
def cached() -> tuple[float, list[dict] | str | None] | None:
|
||||
hit = _remote_lists.get(server_name)
|
||||
ttl = REMOTE_LIST_FAILURE_TTL if hit and hit[1] is None else REMOTE_LIST_TTL
|
||||
ttl = REMOTE_LIST_FAILURE_TTL if hit and not isinstance(hit[1], list) else REMOTE_LIST_TTL
|
||||
return hit if hit and time.monotonic() - hit[0] < ttl else None
|
||||
|
||||
def answer(listed: list[dict] | str | None) -> list[dict] | None:
|
||||
if isinstance(listed, str):
|
||||
raise coded(click.ClickException(listed), APIErrorCode.AUTH_FAILED)
|
||||
return listed
|
||||
|
||||
if hit := cached():
|
||||
return hit[1]
|
||||
return answer(hit[1])
|
||||
with _remote_list_locks.setdefault(server_name, Lock()):
|
||||
if hit := cached():
|
||||
return hit[1]
|
||||
services: list[dict] | None = None
|
||||
return answer(hit[1])
|
||||
services: list[dict] | str | None = None
|
||||
try:
|
||||
with quiet():
|
||||
services = remote_client(server_name).get(SERVICES_ROUTE).get("services") or []
|
||||
except (Exception, SystemExit) as e:
|
||||
log.warning(f"Could not list the services of remote server '{server_name}': {e}")
|
||||
if isinstance(e, RemoteError) and e.kind == APIErrorCode.AUTH_FAILED:
|
||||
services = e.message
|
||||
else:
|
||||
log.warning(f"Could not list the services of remote server '{server_name}': {e}")
|
||||
_remote_lists[server_name] = (time.monotonic(), services)
|
||||
return services
|
||||
return answer(services)
|
||||
|
||||
|
||||
def reset_remote_lists() -> None:
|
||||
|
||||
Reference in New Issue
Block a user