mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 19:35:06 +00:00
fix(vaults): log a one-line warning and skip an http vault that answers non-json
This commit is contained in:
@@ -222,6 +222,8 @@ A flexible HTTP vault that speaks one of three wire protocols, selected with `ap
|
|||||||
|
|
||||||
You must supply either `password` or `api_key`, or the vault will fail to load.
|
You must supply either `password` or `api_key`, or the vault will fail to load.
|
||||||
|
|
||||||
|
A host that answers with a body that is not a JSON object, for example a parked domain or a login page, is unreachable. unshackle logs one warning, skips the vault for the rest of the run, and the `serve` health check reports the vault as failed. In json mode, HTTP 404 is the exception: it means that the vault has no entry. In decrypt_labs mode, an error status is a miss.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## API backend
|
## API backend
|
||||||
|
|||||||
@@ -1,18 +1,43 @@
|
|||||||
"""A failed vault push is reported as a failure, and a server does not store the same pair twice."""
|
"""A failed vault push or lookup is reported as a failure, and a server does not store the same pair twice."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from collections.abc import Callable
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
import requests
|
||||||
|
|
||||||
from unshackle.core.api import handlers
|
from unshackle.core.api import handlers
|
||||||
from unshackle.core.vaults import Vaults
|
from unshackle.core.vaults import Vaults
|
||||||
from unshackle.vaults.HTTP import HTTP
|
from unshackle.vaults.HTTP import HTTP
|
||||||
|
|
||||||
KID = UUID("11111111-2222-3333-4444-555555555555")
|
KID = UUID("11111111-2222-3333-4444-555555555555")
|
||||||
|
KID2 = UUID("66666666-7777-8888-9999-000000000000")
|
||||||
KEY = "a" * 32
|
KEY = "a" * 32
|
||||||
|
|
||||||
|
|
||||||
|
PARKED_PAGE = b"<!DOCTYPE html><html><body>This domain may be for sale.</body></html>"
|
||||||
|
|
||||||
|
|
||||||
|
def fake_response(
|
||||||
|
status: int = 200, body: bytes = PARKED_PAGE, content_type: str = "text/html; charset=utf-8"
|
||||||
|
) -> requests.Response:
|
||||||
|
r = requests.Response()
|
||||||
|
r.status_code = status
|
||||||
|
r.headers["Content-Type"] = content_type
|
||||||
|
r._content = body
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def parked_host(calls: list, status: int = 200, body: bytes = PARKED_PAGE) -> Callable[..., requests.Response]:
|
||||||
|
def parked(*args: object, **kw: object) -> requests.Response:
|
||||||
|
calls.append(1)
|
||||||
|
return fake_response(status, body)
|
||||||
|
|
||||||
|
return parked
|
||||||
|
|
||||||
|
|
||||||
def test_an_unreachable_json_vault_fails_the_push(monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_an_unreachable_json_vault_fails_the_push(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
vault = HTTP("json", "https://vault.invalid/rpc", "token", api_mode="json")
|
vault = HTTP("json", "https://vault.invalid/rpc", "token", api_mode="json")
|
||||||
|
|
||||||
@@ -25,6 +50,52 @@ def test_an_unreachable_json_vault_fails_the_push(monkeypatch: pytest.MonkeyPatc
|
|||||||
assert vaults.add_keys({KID: KEY}) == 0
|
assert vaults.add_keys({KID: KEY}) == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"mode, status, body",
|
||||||
|
[
|
||||||
|
("json", 200, PARKED_PAGE),
|
||||||
|
("decrypt_labs", 200, PARKED_PAGE),
|
||||||
|
("query", 200, PARKED_PAGE),
|
||||||
|
("json", 502, PARKED_PAGE),
|
||||||
|
("json", 200, b"[]"),
|
||||||
|
("query", 200, b"null"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_a_vault_that_answers_html_is_skipped_after_one_request(
|
||||||
|
mode: str, status: int, body: bytes, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
calls: list = []
|
||||||
|
vault = HTTP("EXAMPLE", "https://vault.example/", password="tok", api_mode=mode, username="user")
|
||||||
|
monkeypatch.setattr(vault.session, "get", parked_host(calls, status, body))
|
||||||
|
monkeypatch.setattr(vault.session, "post", parked_host(calls, status, body))
|
||||||
|
vaults = Vaults("SVC")
|
||||||
|
vaults.vaults = [vault]
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
assert vaults.get_key(KID) == (None, None)
|
||||||
|
assert vaults.get_key(KID2) == (None, None)
|
||||||
|
assert len(calls) == 1
|
||||||
|
assert vault in vaults.unreachable
|
||||||
|
messages = [record.getMessage() for record in caplog.records]
|
||||||
|
assert any(f"HTTP {status} text/html response is not a JSON object" in m for m in messages)
|
||||||
|
assert not any("<html" in m or "DOCTYPE" in m or "\n" in m for m in messages)
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
assert str(error.value) == "HTTP 200 text/html response is not a JSON object"
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_html_answer_fails_the_json_push_without_a_single_key_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
calls: list = []
|
||||||
|
vault = HTTP("EXAMPLE", "https://vault.example/", password="tok", api_mode="json")
|
||||||
|
monkeypatch.setattr(vault.session, "post", parked_host(calls))
|
||||||
|
with pytest.raises(ConnectionError):
|
||||||
|
vault.add_keys("SVC", {KID: KEY, KID2: KEY})
|
||||||
|
assert len(calls) == 1
|
||||||
|
|
||||||
|
|
||||||
class FakeVault:
|
class FakeVault:
|
||||||
no_push = False
|
no_push = False
|
||||||
|
|
||||||
|
|||||||
+69
-70
@@ -1,7 +1,10 @@
|
|||||||
import json
|
import json
|
||||||
|
import re
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from uuid import UUID
|
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, vault_session
|
||||||
|
|
||||||
|
|
||||||
@@ -62,6 +65,19 @@ class HTTP(Vault):
|
|||||||
elif self.api_mode not in ["query", "json", "decrypt_labs"]:
|
elif self.api_mode not in ["query", "json", "decrypt_labs"]:
|
||||||
raise ValueError("api_mode must be either 'query', 'json', or '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:
|
def request(self, method: str, params: dict | None = None) -> dict:
|
||||||
"""Make a request to the JSON API vault."""
|
"""Make a request to the JSON API vault."""
|
||||||
if self.api_mode != "json":
|
if self.api_mode != "json":
|
||||||
@@ -85,18 +101,10 @@ class HTTP(Vault):
|
|||||||
raise RateLimited()
|
raise RateLimited()
|
||||||
|
|
||||||
if not r.ok:
|
if not r.ok:
|
||||||
try:
|
detail = self.parse_json(r).get("message") or r.reason.title()
|
||||||
detail = r.json().get("message") or r.reason.title()
|
|
||||||
except (json.JSONDecodeError, AttributeError):
|
|
||||||
detail = r.reason.title()
|
|
||||||
raise ValueError(f"API returned HTTP Error {r.status_code}: {detail}")
|
raise ValueError(f"API returned HTTP Error {r.status_code}: {detail}")
|
||||||
|
|
||||||
try:
|
res = self.parse_json(r)
|
||||||
res = r.json()
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
if r.status_code == 404:
|
|
||||||
return {"status": "not_found"}
|
|
||||||
raise ValueError(f"API returned an invalid response: {r.text}") from None
|
|
||||||
|
|
||||||
if res.get("status_code") != 200:
|
if res.get("status_code") != 200:
|
||||||
raise ValueError(f"API returned an error: {res['status_code']} - {res['message']}")
|
raise ValueError(f"API returned an error: {res['status_code']} - {res['message']}")
|
||||||
@@ -112,67 +120,58 @@ class HTTP(Vault):
|
|||||||
|
|
||||||
if self.api_mode == "decrypt_labs":
|
if self.api_mode == "decrypt_labs":
|
||||||
response = self.session.post(self.url, json={"service": service.lower(), "kid": kid}, timeout=self.timeout)
|
response = self.session.post(self.url, json={"service": service.lower(), "kid": kid}, timeout=self.timeout)
|
||||||
try:
|
if not response.ok:
|
||||||
if not response.ok:
|
|
||||||
return None
|
|
||||||
|
|
||||||
data = response.json()
|
|
||||||
|
|
||||||
if data.get("message") != "success":
|
|
||||||
return None
|
|
||||||
|
|
||||||
cached_keys = data.get("cached_keys")
|
|
||||||
if not cached_keys:
|
|
||||||
return None
|
|
||||||
|
|
||||||
if isinstance(cached_keys, str):
|
|
||||||
try:
|
|
||||||
cached_keys = json.loads(cached_keys)
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
return cached_keys
|
|
||||||
|
|
||||||
if isinstance(cached_keys, dict):
|
|
||||||
if cached_keys.get("kid") == kid:
|
|
||||||
return cached_keys.get("key")
|
|
||||||
if kid in cached_keys:
|
|
||||||
return cached_keys[kid]
|
|
||||||
elif isinstance(cached_keys, list):
|
|
||||||
for entry in cached_keys:
|
|
||||||
if isinstance(entry, dict):
|
|
||||||
if entry.get("kid") == kid:
|
|
||||||
return entry.get("key")
|
|
||||||
elif isinstance(entry, str) and ":" in entry:
|
|
||||||
entry_kid, entry_key = entry.split(":", 1)
|
|
||||||
if entry_kid == kid:
|
|
||||||
return entry_key
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Failed to get key from DecryptLabs ({e.__class__.__name__}: {e})")
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
data = self.parse_json(response)
|
||||||
|
|
||||||
|
if data.get("message") != "success":
|
||||||
|
return None
|
||||||
|
|
||||||
|
cached_keys = data.get("cached_keys")
|
||||||
|
if not cached_keys:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if isinstance(cached_keys, str):
|
||||||
|
try:
|
||||||
|
cached_keys = json.loads(cached_keys)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return cached_keys
|
||||||
|
|
||||||
|
if isinstance(cached_keys, dict):
|
||||||
|
if cached_keys.get("kid") == kid:
|
||||||
|
return cached_keys.get("key")
|
||||||
|
if kid in cached_keys:
|
||||||
|
return cached_keys[kid]
|
||||||
|
elif isinstance(cached_keys, list):
|
||||||
|
for entry in cached_keys:
|
||||||
|
if isinstance(entry, dict):
|
||||||
|
if entry.get("kid") == kid:
|
||||||
|
return entry.get("key")
|
||||||
|
elif isinstance(entry, str) and ":" in entry:
|
||||||
|
entry_kid, entry_key = entry.split(":", 1)
|
||||||
|
if entry_kid == kid:
|
||||||
|
return entry_key
|
||||||
return None
|
return None
|
||||||
|
|
||||||
elif self.api_mode == "json":
|
elif self.api_mode == "json":
|
||||||
try:
|
params = {
|
||||||
params = {
|
"kid": kid,
|
||||||
"kid": kid,
|
"service": service.lower(),
|
||||||
"service": service.lower(),
|
}
|
||||||
}
|
|
||||||
|
|
||||||
res = self.request("GetKey", params)
|
res = self.request("GetKey", params)
|
||||||
if res.get("status") == "not_found":
|
if res.get("status") == "not_found":
|
||||||
return None
|
|
||||||
keys = res.get("keys", [])
|
|
||||||
for key_entry in keys:
|
|
||||||
if isinstance(key_entry, str) and ":" in key_entry:
|
|
||||||
entry_kid, entry_key = key_entry.split(":", 1)
|
|
||||||
if entry_kid == kid:
|
|
||||||
return entry_key
|
|
||||||
elif isinstance(key_entry, dict):
|
|
||||||
if key_entry.get("kid") == kid:
|
|
||||||
return key_entry.get("key")
|
|
||||||
except ValueError as e:
|
|
||||||
print(f"Failed to get key ({e.__class__.__name__}: {e})")
|
|
||||||
return None
|
return None
|
||||||
|
keys = res.get("keys", [])
|
||||||
|
for key_entry in keys:
|
||||||
|
if isinstance(key_entry, str) and ":" in key_entry:
|
||||||
|
entry_kid, entry_key = key_entry.split(":", 1)
|
||||||
|
if entry_kid == kid:
|
||||||
|
return entry_key
|
||||||
|
elif isinstance(key_entry, dict):
|
||||||
|
if key_entry.get("kid") == kid:
|
||||||
|
return key_entry.get("key")
|
||||||
return None
|
return None
|
||||||
else: # query mode
|
else: # query mode
|
||||||
response = self.session.get(
|
response = self.session.get(
|
||||||
@@ -181,7 +180,7 @@ class HTTP(Vault):
|
|||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
data = response.json()
|
data = self.parse_json(response)
|
||||||
|
|
||||||
if not data.get("keys"):
|
if not data.get("keys"):
|
||||||
return None
|
return None
|
||||||
@@ -202,7 +201,7 @@ class HTTP(Vault):
|
|||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
data = response.json()
|
data = self.parse_json(response)
|
||||||
|
|
||||||
if data.get("status_code") != 200 or not data.get("keys"):
|
if data.get("status_code") != 200 or not data.get("keys"):
|
||||||
return
|
return
|
||||||
@@ -252,7 +251,7 @@ class HTTP(Vault):
|
|||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
data = response.json()
|
data = self.parse_json(response)
|
||||||
|
|
||||||
return data.get("status_code") == 200
|
return data.get("status_code") == 200
|
||||||
|
|
||||||
@@ -318,7 +317,7 @@ class HTTP(Vault):
|
|||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
data = response.json()
|
data = self.parse_json(response)
|
||||||
|
|
||||||
if data.get("status_code") == 200 and data.get("inserted", True):
|
if data.get("status_code") == 200 and data.get("inserted", True):
|
||||||
inserted_count += 1
|
inserted_count += 1
|
||||||
@@ -343,7 +342,7 @@ class HTTP(Vault):
|
|||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
data = response.json()
|
data = self.parse_json(response)
|
||||||
|
|
||||||
if data.get("status_code") != 200:
|
if data.get("status_code") != 200:
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user