diff --git a/docs/guide/vaults.md b/docs/guide/vaults.md index ba8517b3..8bbb15be 100644 --- a/docs/guide/vaults.md +++ b/docs/guide/vaults.md @@ -23,7 +23,7 @@ A vault stores every content key as a **KID → KEY** pair, grouped by **service ## How lookups and caching work -When unshackle needs a content key during a download it asks your vaults **in the order they appear in your config**. It returns the first non-null key it finds and stops searching. If a vault raises a permission error or is unreachable, unshackle skips it and continues the search with the next one. +When unshackle needs a content key during a download it asks your vaults **in the order they appear in your config**. It returns the first non-null key it finds and stops searching. If a vault raises a permission error or is unreachable, unshackle skips it and continues the search with the next one. unshackle does not ask a remote vault again for the rest of the run when it is unreachable or answers with a body that is not a JSON object. It always asks a local SQLite vault. Each failure of a vault shows one warning with the host and the reason; the same failure again goes to the debug log. A track needs no licence when a vault holds the content key of the KID that encrypts it. The DRM header of the track can name more KIDs, for example those of other tracks. Before the decrypt, unshackle reads the downloaded file, and licenses each of those KIDs that the file uses and no vault holds. When unshackle cannot read which KIDs the file uses, it licenses all of them. diff --git a/tests/core/test_vault_failure_messages.py b/tests/core/test_vault_failure_messages.py new file mode 100644 index 00000000..b6dc2762 --- /dev/null +++ b/tests/core/test_vault_failure_messages.py @@ -0,0 +1,193 @@ +import logging +from pathlib import Path +from uuid import UUID + +import click +import pytest +import requests + +from unshackle.commands.kv import copy_service_data +from unshackle.core.utilities import close_debug_logger, init_debug_logger +from unshackle.core.vault import brief +from unshackle.core.vaults import Vaults +from unshackle.vaults.API import API +from unshackle.vaults.HTTP import HTTP +from unshackle.vaults.SQLite import SQLite + +KID = UUID("11111111-2222-3333-4444-555555555555") +SIBLING = UUID("99999999-2222-3333-4444-555555555555") +URL = "http://u:SECRETPW@vault.example:8080/vault.php?username=u&password=SECRETPW&kid=00" +REFUSED = ( + "HTTPConnectionPool(host='vault.example', port=8080): Max retries exceeded with url: " + '/vault.php?username=u&password=SECRETPW (Caused by NewConnectionError(": Failed to establish a new connection: [Errno 111] Connection refused"))' +) + + +def request() -> requests.PreparedRequest: + return requests.Request("GET", URL).prepare() + + +def html(status: int = 200) -> requests.Response: + r = requests.Response() + r.status_code = status + r.headers["Content-Type"] = "text/html" + r._content = b"parked" + r.request = request() + return r + + +def test_brief_keeps_the_host_and_reason_and_drops_the_url() -> None: + text = brief(requests.ConnectionError(REFUSED, request=request())) + assert "vault.example:8080" in text + assert "Connection refused" in text + for leak in ("SECRETPW", "?", "/vault.php", "\n"): + assert leak not in text + + +def test_brief_names_a_timeout() -> None: + error = requests.ReadTimeout( + "HTTPConnectionPool(host='vault.example', port=8080): Read timed out. (read timeout=10)", request=request() + ) + text = brief(error) + assert "timed out" in text + assert "SECRETPW" not in text + + +def test_brief_gives_the_status_of_an_http_error() -> None: + response = html(503) + error = requests.HTTPError(f"503 Server Error: Service Unavailable for url: {URL}", response=response) + assert brief(error) == "HTTP 503 from vault.example:8080" + + +def test_brief_keeps_one_short_line_of_any_other_error() -> None: + assert brief(ValueError("line1\nline2")) == "line1" + assert len(brief(ValueError("x" * 5000))) <= 200 + assert brief(ValueError()) == "ValueError" + + +def test_brief_keeps_the_reason_of_a_tls_failure() -> None: + error = requests.exceptions.SSLError( + "HTTPSConnectionPool(host='vault.example', port=8080): Max retries exceeded with url: /vault.php?password=SECRETPW " + "(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: " + "self-signed certificate (_ssl.c:1010)')))", + request=request(), + ) + assert brief(error) == "SSLError to vault.example:8080 (certificate verify failed: self-signed certificate)" + + +def test_brief_keeps_the_text_of_a_requests_error_with_no_request() -> None: + assert brief(requests.JSONDecodeError("Expecting value", "", 0)).startswith("Expecting value") + text = brief(requests.exceptions.InvalidSchema(f"No connection adapters were found for 'htp{URL[4:]}'")) + assert text.startswith("No connection adapters were found") + assert "SECRETPW" not in text + + +def test_brief_masks_a_password_in_the_text_of_any_other_error() -> None: + assert "SECRETPW" not in brief(ValueError(f"bad answer from {URL}")) + + +def records(caplog: pytest.LogCaptureFixture, level: int) -> list[str]: + return [r.getMessage() for r in caplog.records if r.levelno == level] + + +def test_a_query_mode_vault_that_is_down_never_logs_its_password( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + def down(*args: object, **kw: object) -> None: + raise requests.ConnectionError(REFUSED, request=request()) + + vault = HTTP("http", "http://vault.example:8080/vault.php", password="SECRETPW", username="u") + monkeypatch.setattr(vault.session, "get", down) + vaults = Vaults("SVC") + vaults.vaults = [vault] + + debug_log = tmp_path / "debug.jsonl" + init_debug_logger(log_path=debug_log, enabled=True) + try: + with caplog.at_level(logging.DEBUG): + assert vaults.get_key(KID) == (None, None) + assert vaults.get_key(SIBLING) == (None, None) + finally: + close_debug_logger() + + assert "vault_get_key" in debug_log.read_text() + assert "SECRETPW" not in debug_log.read_text() + + assert not [m for m in (r.getMessage() for r in caplog.records) if "SECRETPW" in m] + assert len([m for m in records(caplog, logging.WARNING) if m.startswith("Failed to get key")]) == 1 + assert vault in vaults.unreachable + + +def test_an_api_vault_that_answers_html_is_skipped_after_one_warning( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + calls: list[str] = [] + + def parked(url: str, **kw: object) -> requests.Response: + calls.append(url) + return html() + + vault = API("api", "https://api.example/", "tok") + monkeypatch.setattr(vault.session, "get", parked) + monkeypatch.setattr(vault.session, "post", parked) + vaults = Vaults("SVC") + vaults.vaults = [vault] + + with caplog.at_level(logging.DEBUG): + assert vaults.get_key(KID) == (None, None) + assert vaults.get_key(SIBLING) == (None, None) + + assert len(calls) == 1 + assert vault in vaults.unreachable + warnings = [m for m in records(caplog, logging.WARNING) if m.startswith("Failed to get key")] + assert warnings == ["Failed to get key from Vault 'api': HTTP 200 text/html response is not a JSON object"] + assert not [r for r in caplog.records if " None: + path = tmp_path / "local.db" + path.write_bytes(b"not a database" * 100) + vault = SQLite("local", path) + queried: list[UUID | str] = [] + get_key = vault.get_key + + def counted(kid: UUID | str, service: str) -> str | None: + queried.append(kid) + return get_key(kid, service) + + monkeypatch.setattr(vault, "get_key", counted) + vaults = Vaults("SVC") + vaults.vaults = [vault] + + with caplog.at_level(logging.DEBUG): + assert vaults.get_key(KID) == (None, None) + assert vaults.get_key(SIBLING) == (None, None) + assert vaults.add_keys({KID: "bb" * 16}) == 0 + + warnings = records(caplog, logging.WARNING) + assert len(warnings) == 1 + assert "file is not a database" in warnings[0] + assert len([m for m in records(caplog, logging.DEBUG) if "file is not a database" in m]) == 2 + assert vault not in vaults.unreachable + assert queried == [KID, SIBLING] + + +def test_kv_copy_names_the_vault_it_cannot_write_to_without_its_password(tmp_path: Path) -> None: + class Down(SQLite): + def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int: + raise requests.ConnectionError(REFUSED, request=request()) + + source = SQLite("source", tmp_path / "source.db") + source.add_key("EXAMPLE", KID, "bb" * 16) + with pytest.raises(click.ClickException) as raised: + copy_service_data(Down("down", tmp_path / "down.db"), source, "EXAMPLE", logging.getLogger("kv")) + assert ( + raised.value.message + == "Could not write to down Down (ConnectionError to vault.example:8080 (Connection refused))" + ) diff --git a/tests/core/test_vault_push_retry.py b/tests/core/test_vault_push_retry.py index 53a018e1..78d662b8 100644 --- a/tests/core/test_vault_push_retry.py +++ b/tests/core/test_vault_push_retry.py @@ -9,6 +9,7 @@ import pytest import requests from unshackle.core.api import handlers +from unshackle.core.vault import json_body from unshackle.core.vaults import Vaults from unshackle.vaults.HTTP import HTTP @@ -83,7 +84,7 @@ def test_a_vault_that_answers_html_is_skipped_after_one_request( def test_a_hostile_content_type_stays_out_of_the_error() -> None: r = fake_response(content_type="text/html\r\n INJECTED" + "x" * 1000) with pytest.raises(ConnectionError) as error: - HTTP.parse_json(r) + json_body(r) assert str(error.value) == "HTTP 200 text/html response is not a JSON object" diff --git a/unshackle/commands/kv.py b/unshackle/commands/kv.py index 44b4788f..ef8f9279 100644 --- a/unshackle/commands/kv.py +++ b/unshackle/commands/kv.py @@ -24,7 +24,7 @@ from unshackle.core.config import config from unshackle.core.console import GradientPulseBarColumn, console from unshackle.core.constants import context_settings from unshackle.core.services import Services -from unshackle.core.vault import Vault, is_null_key +from unshackle.core.vault import Vault, brief, is_null_key from unshackle.core.vaults import Vaults, load_config_vaults @@ -114,7 +114,7 @@ def copy_service_data( try: content_keys = process_service_keys(from_vault, service, log) except Exception as e: - log.warning(f"{service}: Could not read from {from_vault} ({e}), skipped") + log.warning(f"{service}: Could not read from {from_vault} ({brief(e)}), skipped") return 0 content_keys = {kid: key for kid, key in content_keys.items() if not to_vault.is_bad_key(kid, key)} @@ -129,6 +129,8 @@ def copy_service_data( except PermissionError: log.warning(f"{service}: No permission to create table in {to_vault}, skipped") return 0 + except Exception as e: + raise click.ClickException(f"Could not write to {to_vault} ({brief(e)})") from None existed = total_count - added @@ -213,7 +215,7 @@ def copy( try: services_to_copy = list(from_vault.get_services()) except Exception as e: - log.debug(f"{from_vault.name}: cannot list services ({e}), skipped") + log.debug(f"{from_vault.name}: cannot list services ({brief(e)}), skipped") continue if installed is not None: @@ -313,7 +315,10 @@ def add(file: Path, service: str, vaults: list[str]) -> None: for vault in vaults_: log.info(f"Adding {total_count} Content Keys to {vault}") - added_count = add_keys_with_progress(vault, service, kid_keys, log) + try: + added_count = add_keys_with_progress(vault, service, kid_keys, log) + except Exception as e: + raise click.ClickException(f"Could not write to {vault} ({brief(e)})") from None existed_count = total_count - added_count log.info(f"{vault}: {added_count} newly added, {existed_count} already existed (skipped)") @@ -327,7 +332,7 @@ def search_vault(vault: Vault, kid: str, services: list[str], log: logging.Logge try: key = vault.get_key(kid, svc) except Exception as e: - log.debug(f"{vault} [{svc}]: lookup error ({e})") + log.debug(f"{vault} [{svc}]: lookup error ({brief(e)})") return None if key and not is_null_key(key): return svc, key @@ -392,7 +397,7 @@ def search(kid: str, service: str | None, vault_name: str | None) -> None: try: services_to_check = list(vault.get_services()) except Exception as e: - log.debug(f"{vault}: get_services() failed ({e})") + log.debug(f"{vault}: get_services() failed ({brief(e)})") services_to_check = [] if not services_to_check: services_to_check = list(Services.get_tags()) diff --git a/unshackle/core/vault.py b/unshackle/core/vault.py index b00cda10..0d050df6 100644 --- a/unshackle/core/vault.py +++ b/unshackle/core/vault.py @@ -1,14 +1,17 @@ +import re from abc import ABCMeta, abstractmethod from collections.abc import Iterator +from urllib.parse import urlsplit from uuid import UUID from requests import ConnectionError as RequestsConnectionError -from requests import Session, Timeout +from requests import RequestException, Response, Session, Timeout from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from unshackle.core import __version__ from unshackle.core.session import POOL_MAX_SIZE +from unshackle.core.utils.redact import redact_text RATE_LIMIT_RETRIES = 3 @@ -22,6 +25,36 @@ class RateLimited(Exception): UNREACHABLE = (RequestsConnectionError, Timeout, ConnectionError, TimeoutError) +OS_REASON_RE = re.compile(r"\[(?:Errno -?\d+|WinError -?\d+|SSL: \w+)\] ([^'\"()\[\]]+)") + + +def brief(error: BaseException) -> str: + """One line for a vault failure, without the request URL, whose query can hold the vault password.""" + if not isinstance(error, RequestException) or (error.request is None and error.response is None): + text = (redact_text(str(error).strip().split("\n", 1)[0]) or "")[:200] + return text or type(error).__name__ + url = getattr(error.request, "url", None) + host = urlsplit(url).netloc.rpartition("@")[2] if url else "vault" + if error.response is not None: + return f"HTTP {error.response.status_code} from {host}" + text = str(error) + reasons = OS_REASON_RE.findall(text) + reason = reasons[-1].strip() if reasons else "timed out" if "timed out" in text else "" + return f"{type(error).__name__} to {host}" + (f" ({reason})" if reason else "") + + +def json_body(r: Response) -> dict: + """The response body as a JSON object. Any other body means the host is not a vault, so it is unreachable.""" + try: + data = r.json() + except ValueError: + data = None + if not isinstance(data, dict): + mime = re.match(r"[\w.+-]{1,64}/[\w.+-]{1,64}", r.headers.get("Content-Type", "")) + content_type = mime.group() if mime else "unknown" + raise ConnectionError(f"HTTP {r.status_code} {content_type} response is not a JSON object") + return data + def is_null_key(key: str | None) -> bool: """True for a blank or all-zero content key, the null key that no vault stores.""" @@ -115,4 +148,4 @@ class Vault(metaclass=ABCMeta): """Forget a flagged KID:KEY, for example when a CDM licence confirmed it.""" -__all__ = ("Vault",) +__all__ = ("Vault", "brief", "json_body") diff --git a/unshackle/core/vaults.py b/unshackle/core/vaults.py index 6e63d0ce..86ccddce 100644 --- a/unshackle/core/vaults.py +++ b/unshackle/core/vaults.py @@ -9,7 +9,7 @@ from uuid import UUID from unshackle.core.config import config from unshackle.core.utilities import get_debug_logger, import_module_by_path -from unshackle.core.vault import UNREACHABLE, RateLimited, Vault, is_null_key +from unshackle.core.vault import UNREACHABLE, RateLimited, Vault, brief, is_null_key log = logging.getLogger(__name__) @@ -30,6 +30,7 @@ class Vaults: self.flagged: set[tuple[UUID | str, str]] = set() self.candidates: dict[UUID | str, list[tuple[str, Vault]]] = {} self.warned: set[tuple[str, UUID | str, str]] = set() + self.failed: set[tuple[str, str]] = set() self.unreachable: set[Vault] = set() self.unreported: dict[tuple[UUID | str, str], Vault] = {} @@ -110,7 +111,7 @@ class Vaults: except (PermissionError, NotImplementedError): return None except Exception as e: - log.warning(f"Failed to get key from Vault '{vault.name}': {e}") + self.warn_failure(vault, "get key from", e) self.mark_unreachable(vault, e) if dl: dl.log_vault_query( @@ -209,7 +210,7 @@ class Vaults: except (PermissionError, NotImplementedError): return 0 except Exception as e: - log.warning(f"Failed to add key to Vault '{vault.name}': {e}") + self.warn_failure(vault, "add key to", e) self.mark_unreachable(vault, e) if dl: dl.log_vault_query(vault.name, "add_key", kid=str(kid), success=False, error=e) @@ -240,7 +241,7 @@ class Vaults: except (PermissionError, NotImplementedError): return 0 except Exception as e: - log.warning(f"Failed to add keys to Vault '{vault.name}': {e}") + self.warn_failure(vault, "add keys to", e) self.mark_unreachable(vault, e) return 0 @@ -252,6 +253,16 @@ class Vaults: """True when a local vault already holds this KID:KEY.""" return any(self.query_vault(vault, kid) == key for vault in self.vaults if vault.local) + def warn_failure(self, vault: Vault, action: str, error: Exception) -> None: + """Warn once per vault for each distinct failure; a repeat goes to the debug log.""" + text = brief(error) + message = f"Failed to {action} Vault '{vault.name}': {text}" + if (vault.name, text) in self.failed: + log.debug(message) + else: + self.failed.add((vault.name, text)) + log.warning(message) + def mark_unreachable(self, vault: Vault, error: Exception) -> None: """Skip a vault that is down or still rate limited for the rest of the run, so it costs one timeout, not one per KID.""" diff --git a/unshackle/vaults/API.py b/unshackle/vaults/API.py index 471b6da7..27fe1270 100644 --- a/unshackle/vaults/API.py +++ b/unshackle/vaults/API.py @@ -3,7 +3,7 @@ from uuid import UUID from requests import HTTPError, Response -from unshackle.core.vault import RateLimited, Vault, vault_session +from unshackle.core.vault import RateLimited, Vault, json_body, vault_session class API(Vault): @@ -40,7 +40,7 @@ class API(Vault): if response.status_code == 429: raise Exceptions.TooManyRequests() response.raise_for_status() - data = response.json() + data = json_body(response) code = int(data.get("code", 0)) message = data.get("message") @@ -76,7 +76,7 @@ class API(Vault): allow_redirects=False, ) response.raise_for_status() - data = response.json() + data = json_body(response) code = int(data.get("code", 0)) message = data.get("message") @@ -116,7 +116,7 @@ class API(Vault): allow_redirects=False, ) response.raise_for_status() - data = response.json() + data = json_body(response) code = int(data.get("code", 0)) message = data.get("message") @@ -173,9 +173,8 @@ class API(Vault): if response.status_code == 429: raise Exceptions.TooManyRequests() response.raise_for_status() - data = response.json() - except (ValueError, HTTPError): - # an HTTP error or a broken JSON reply - try smaller batch + data = json_body(response) + except HTTPError: if batch_size > 1: if batch_size > 100: batch_size -= 100 @@ -239,7 +238,7 @@ class API(Vault): if response.status_code in (404, 405, 501): return response.raise_for_status() - data = response.json() + data = json_body(response) code = int(data.get("code", 0)) if not code or code in ignore: return @@ -251,7 +250,7 @@ class API(Vault): url=self.uri, headers={"Accept": "application/json"}, timeout=self.timeout, allow_redirects=False ) response.raise_for_status() - data = response.json() + data = json_body(response) code = int(data.get("code", 0)) message = data.get("message") diff --git a/unshackle/vaults/HTTP.py b/unshackle/vaults/HTTP.py index 3bc476c6..9af48145 100644 --- a/unshackle/vaults/HTTP.py +++ b/unshackle/vaults/HTTP.py @@ -1,11 +1,8 @@ import json -import re from collections.abc import Iterator from uuid import UUID -from requests import Response - -from unshackle.core.vault import RateLimited, Vault, is_null_key, vault_session +from unshackle.core.vault import RateLimited, Vault, is_null_key, json_body, vault_session class HTTP(Vault): @@ -65,19 +62,6 @@ class HTTP(Vault): elif self.api_mode not in ["query", "json", "decrypt_labs"]: raise ValueError("api_mode must be either 'query', 'json', or 'decrypt_labs'") - @staticmethod - def parse_json(r: Response) -> dict: - """The response body as a JSON object. Any other body means the host is not a vault, so it is unreachable.""" - try: - data = r.json() - except ValueError: - data = None - if not isinstance(data, dict): - mime = re.match(r"[\w.+-]{1,64}/[\w.+-]{1,64}", r.headers.get("Content-Type", "")) - content_type = mime.group() if mime else "unknown" - raise ConnectionError(f"HTTP {r.status_code} {content_type} response is not a JSON object") - return data - def request(self, method: str, params: dict | None = None) -> dict: """Make a request to the JSON API vault.""" if self.api_mode != "json": @@ -101,10 +85,10 @@ class HTTP(Vault): raise RateLimited() if not r.ok: - detail = self.parse_json(r).get("message") or r.reason.title() + detail = json_body(r).get("message") or r.reason.title() raise ValueError(f"API returned HTTP Error {r.status_code}: {detail}") - res = self.parse_json(r) + res = json_body(r) if res.get("status_code") != 200: raise ValueError(f"API returned an error: {res['status_code']} - {res['message']}") @@ -123,7 +107,7 @@ class HTTP(Vault): if not response.ok: return None - data = self.parse_json(response) + data = json_body(response) if data.get("message") != "success": return None @@ -180,7 +164,7 @@ class HTTP(Vault): timeout=self.timeout, ) - data = self.parse_json(response) + data = json_body(response) if not data.get("keys"): return None @@ -201,7 +185,7 @@ class HTTP(Vault): timeout=self.timeout, ) - data = self.parse_json(response) + data = json_body(response) if data.get("status_code") != 200 or not data.get("keys"): return @@ -251,7 +235,7 @@ class HTTP(Vault): timeout=self.timeout, ) - data = self.parse_json(response) + data = json_body(response) return data.get("status_code") == 200 @@ -317,7 +301,7 @@ class HTTP(Vault): timeout=self.timeout, ) - data = self.parse_json(response) + data = json_body(response) if data.get("status_code") == 200 and data.get("inserted", True): inserted_count += 1 @@ -342,7 +326,7 @@ class HTTP(Vault): timeout=self.timeout, ) - data = self.parse_json(response) + data = json_body(response) if data.get("status_code") != 200: return