mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 19:35:06 +00:00
fix(vaults): raise when an http vault is rate limited or refuses a push
This commit is contained in:
@@ -222,7 +222,7 @@ 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.
|
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 to a lookup is the exception: it means that the vault has no entry. In decrypt_labs mode, an error status other than 429 is a miss.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -146,11 +146,15 @@ def test_a_json_vault_that_is_down_fails_the_service_list(monkeypatch: pytest.Mo
|
|||||||
list(vault.get_services())
|
list(vault.get_services())
|
||||||
|
|
||||||
|
|
||||||
|
def rate_limited(*args: object, **kw: object) -> requests.Response:
|
||||||
|
return fake_response(429, b"{}", "application/json")
|
||||||
|
|
||||||
|
|
||||||
def test_an_api_vault_still_rate_limited_fails_the_key_list_and_kv_copy_skips_it(
|
def test_an_api_vault_still_rate_limited_fails_the_key_list_and_kv_copy_skips_it(
|
||||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||||
) -> None:
|
) -> None:
|
||||||
api = API("api", "https://api.example/", "tok")
|
api = API("api", "https://api.example/", "tok")
|
||||||
monkeypatch.setattr(api.session, "get", lambda *a, **kw: fake_response(429, b"{}", "application/json"))
|
monkeypatch.setattr(api.session, "get", rate_limited)
|
||||||
with pytest.raises(RateLimited):
|
with pytest.raises(RateLimited):
|
||||||
list(api.get_keys("SVC"))
|
list(api.get_keys("SVC"))
|
||||||
|
|
||||||
@@ -161,6 +165,71 @@ def test_an_api_vault_still_rate_limited_fails_the_key_list_and_kv_copy_skips_it
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def query_vault() -> HTTP:
|
||||||
|
return HTTP("EXAMPLE", "https://vault.example/", password="tok", username="user")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"vault, call",
|
||||||
|
[
|
||||||
|
pytest.param(query_vault(), lambda v: v.get_key(KID, "SVC"), id="query-get_key"),
|
||||||
|
pytest.param(query_vault(), lambda v: list(v.get_keys("SVC")), id="query-get_keys"),
|
||||||
|
pytest.param(query_vault(), lambda v: v.add_key("SVC", KID, KEY), id="query-add_key"),
|
||||||
|
pytest.param(query_vault(), lambda v: v.add_keys("SVC", {KID: KEY}), id="query-add_keys"),
|
||||||
|
pytest.param(query_vault(), lambda v: list(v.get_services()), id="query-get_services"),
|
||||||
|
pytest.param(
|
||||||
|
HTTP("EXAMPLE", "https://vault.example/", api_key="tok", api_mode="decrypt_labs"),
|
||||||
|
lambda v: v.get_key(KID, "SVC"),
|
||||||
|
id="decrypt_labs-get_key",
|
||||||
|
),
|
||||||
|
pytest.param(API("api", "https://api.example/", "tok"), lambda v: v.add_key("SVC", KID, KEY), id="api-add_key"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_a_vault_still_rate_limited_after_the_retries_raises(
|
||||||
|
vault: HTTP | API, call: Callable[[Any], object], monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setattr(vault.session, "get", rate_limited)
|
||||||
|
monkeypatch.setattr(vault.session, "post", rate_limited)
|
||||||
|
with pytest.raises(RateLimited):
|
||||||
|
call(vault)
|
||||||
|
|
||||||
|
|
||||||
|
def answers(*replies: bytes) -> Callable[..., requests.Response]:
|
||||||
|
queue = list(replies)
|
||||||
|
return lambda *a, **kw: fake_response(200, queue.pop(0), "application/json")
|
||||||
|
|
||||||
|
|
||||||
|
REFUSED = b'{"status_code": 401, "message": "bad login"}'
|
||||||
|
EXISTS = b'{"status_code": 200, "inserted": false}'
|
||||||
|
INSERTED = b'{"status_code": 200, "inserted": true}'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"vault, method, status",
|
||||||
|
[
|
||||||
|
pytest.param(query_vault(), "get", 200, id="query-refused"),
|
||||||
|
pytest.param(one_json_vault()[0], "post", 200, id="json-refused"),
|
||||||
|
pytest.param(one_json_vault()[0], "post", 404, id="json-not-found"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_a_push_the_vault_refuses_for_every_key_fails(
|
||||||
|
vault: HTTP, method: str, status: int, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
vaults = vaults_of(vault, service="SVC")
|
||||||
|
monkeypatch.setattr(vault.session, method, lambda *a, **kw: fake_response(status, REFUSED, "application/json"))
|
||||||
|
assert vaults.add_keys({KID: KEY, KID2: KEY}) == 0
|
||||||
|
assert vault not in vaults.unreachable
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("replies, count", [((EXISTS, EXISTS), 0), ((REFUSED, INSERTED), 1)])
|
||||||
|
def test_a_query_push_counts_the_keys_the_vault_inserted(
|
||||||
|
replies: tuple[bytes, ...], count: int, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
vault = query_vault()
|
||||||
|
monkeypatch.setattr(vault.session, "get", answers(*replies))
|
||||||
|
assert vault.add_keys("SVC", {KID: KEY, KID2: KEY}) == count
|
||||||
|
|
||||||
|
|
||||||
def test_server_does_not_push_a_pair_it_already_stored(monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_server_does_not_push_a_pair_it_already_stored(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
vault = MemoryVault()
|
vault = MemoryVault()
|
||||||
monkeypatch.setattr(handlers, "load_server_vaults", lambda name: vaults_of(vault, service="SVC"))
|
monkeypatch.setattr(handlers, "load_server_vaults", lambda name: vaults_of(vault, service="SVC"))
|
||||||
|
|||||||
@@ -117,6 +117,8 @@ class API(Vault):
|
|||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
allow_redirects=False,
|
allow_redirects=False,
|
||||||
)
|
)
|
||||||
|
if response.status_code == 429:
|
||||||
|
raise Exceptions.TooManyRequests()
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
data = json_body(response)
|
data = json_body(response)
|
||||||
|
|
||||||
|
|||||||
+29
-57
@@ -7,6 +7,11 @@ from requests import RequestException
|
|||||||
from unshackle.core.vault import RateLimited, Vault, is_null_key, json_body, vault_session
|
from unshackle.core.vault import RateLimited, Vault, is_null_key, json_body, vault_session
|
||||||
|
|
||||||
|
|
||||||
|
def refusal(answer: dict) -> ValueError:
|
||||||
|
"""The error answer of a vault that refused the call."""
|
||||||
|
return ValueError(f"API returned an error: {answer.get('status_code')} - {answer.get('message')}")
|
||||||
|
|
||||||
|
|
||||||
class HTTP(Vault):
|
class HTTP(Vault):
|
||||||
"""
|
"""
|
||||||
Key Vault using HTTP API that can operate in several API modes.
|
Key Vault using HTTP API that can operate in several API modes.
|
||||||
@@ -93,19 +98,30 @@ class HTTP(Vault):
|
|||||||
res = json_body(r)
|
res = json_body(r)
|
||||||
|
|
||||||
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 refusal(res)
|
||||||
|
|
||||||
if session_id := res.get("message", {}).get("session_id"):
|
if session_id := res.get("message", {}).get("session_id"):
|
||||||
self.api_session_id = session_id
|
self.api_session_id = session_id
|
||||||
|
|
||||||
return res.get("message", res)
|
return res.get("message", res)
|
||||||
|
|
||||||
|
def _query(self, params: dict) -> dict:
|
||||||
|
"""A query-mode GET with the credentials. A 429 that remains after the retries raises RateLimited."""
|
||||||
|
response = self.session.get(
|
||||||
|
self.url, params={**params, "username": self.username, "password": self.password}, timeout=self.timeout
|
||||||
|
)
|
||||||
|
if response.status_code == 429:
|
||||||
|
raise RateLimited()
|
||||||
|
return json_body(response)
|
||||||
|
|
||||||
def get_key(self, kid: UUID | str, service: str) -> str | None:
|
def get_key(self, kid: UUID | str, service: str) -> str | None:
|
||||||
if isinstance(kid, UUID):
|
if isinstance(kid, UUID):
|
||||||
kid = kid.hex
|
kid = kid.hex
|
||||||
|
|
||||||
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)
|
||||||
|
if response.status_code == 429:
|
||||||
|
raise RateLimited()
|
||||||
if not response.ok:
|
if not response.ok:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -160,13 +176,7 @@ class HTTP(Vault):
|
|||||||
return key_entry.get("key")
|
return key_entry.get("key")
|
||||||
return None
|
return None
|
||||||
else: # query mode
|
else: # query mode
|
||||||
response = self.session.get(
|
data = self._query({"service": service.lower(), "kid": kid})
|
||||||
self.url,
|
|
||||||
params={"service": service.lower(), "username": self.username, "password": self.password, "kid": kid},
|
|
||||||
timeout=self.timeout,
|
|
||||||
)
|
|
||||||
|
|
||||||
data = json_body(response)
|
|
||||||
|
|
||||||
if not data.get("keys"):
|
if not data.get("keys"):
|
||||||
return None
|
return None
|
||||||
@@ -181,13 +191,7 @@ class HTTP(Vault):
|
|||||||
# This will cause the copy command to rely on the API's internal duplicate handling
|
# This will cause the copy command to rely on the API's internal duplicate handling
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
response = self.session.get(
|
data = self._query({"service": service.lower()})
|
||||||
self.url,
|
|
||||||
params={"service": service.lower(), "username": self.username, "password": self.password},
|
|
||||||
timeout=self.timeout,
|
|
||||||
)
|
|
||||||
|
|
||||||
data = json_body(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
|
||||||
@@ -226,21 +230,7 @@ class HTTP(Vault):
|
|||||||
except ValueError: # an error answer from the vault
|
except ValueError: # an error answer from the vault
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
response = self.session.get(
|
data = self._query({"service": service.lower(), "kid": kid, "key": key, "title": title})
|
||||||
self.url,
|
|
||||||
params={
|
|
||||||
"service": service.lower(),
|
|
||||||
"username": self.username,
|
|
||||||
"password": self.password,
|
|
||||||
"kid": kid,
|
|
||||||
"key": key,
|
|
||||||
"title": title,
|
|
||||||
},
|
|
||||||
timeout=self.timeout,
|
|
||||||
)
|
|
||||||
|
|
||||||
data = json_body(response)
|
|
||||||
|
|
||||||
return data.get("status_code") == 200
|
return data.get("status_code") == 200
|
||||||
|
|
||||||
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
|
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
|
||||||
@@ -283,33 +273,21 @@ class HTTP(Vault):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
if res.get("status") == "not_found":
|
if res.get("status") == "not_found":
|
||||||
continue
|
failures.append(ValueError("API returned HTTP Error 404: Not Found"))
|
||||||
if res.get("inserted", False):
|
elif res.get("inserted", False):
|
||||||
inserted_count += 1
|
inserted_count += 1
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
failures.append(e)
|
failures.append(e)
|
||||||
if failures and len(failures) == len(processed_kid_keys):
|
|
||||||
raise failures[-1]
|
|
||||||
else:
|
else:
|
||||||
for kid, key in processed_kid_keys.items():
|
for kid, key in processed_kid_keys.items():
|
||||||
response = self.session.get(
|
data = self._query({"service": service.lower(), "kid": kid, "key": key, "title": title})
|
||||||
self.url,
|
if data.get("status_code") != 200:
|
||||||
params={
|
failures.append(refusal(data))
|
||||||
"service": service.lower(),
|
elif data.get("inserted", True):
|
||||||
"username": self.username,
|
|
||||||
"password": self.password,
|
|
||||||
"kid": kid,
|
|
||||||
"key": key,
|
|
||||||
"title": title,
|
|
||||||
},
|
|
||||||
timeout=self.timeout,
|
|
||||||
)
|
|
||||||
|
|
||||||
data = json_body(response)
|
|
||||||
|
|
||||||
if data.get("status_code") == 200 and data.get("inserted", True):
|
|
||||||
inserted_count += 1
|
inserted_count += 1
|
||||||
|
|
||||||
|
if failures and len(failures) == len(processed_kid_keys):
|
||||||
|
raise failures[-1]
|
||||||
return inserted_count
|
return inserted_count
|
||||||
|
|
||||||
def get_services(self) -> Iterator[str]:
|
def get_services(self) -> Iterator[str]:
|
||||||
@@ -318,13 +296,7 @@ class HTTP(Vault):
|
|||||||
elif self.api_mode == "json":
|
elif self.api_mode == "json":
|
||||||
yield from self.request("GetServices").get("services", [])
|
yield from self.request("GetServices").get("services", [])
|
||||||
else:
|
else:
|
||||||
response = self.session.get(
|
data = self._query({"list_services": True})
|
||||||
self.url,
|
|
||||||
params={"username": self.username, "password": self.password, "list_services": True},
|
|
||||||
timeout=self.timeout,
|
|
||||||
)
|
|
||||||
|
|
||||||
data = json_body(response)
|
|
||||||
|
|
||||||
if data.get("status_code") != 200:
|
if data.get("status_code") != 200:
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user