forked from mtusi2026/mtusi2026lab7
91 lines
2.8 KiB
Python
91 lines
2.8 KiB
Python
import json
|
|
import time
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from scripts.research_security import observe_get
|
|
|
|
|
|
def test_transient_reads_remain_observed_until_an_actual_200(monkeypatch):
|
|
observations = {}
|
|
attempts = 0
|
|
|
|
def handle(request):
|
|
nonlocal attempts
|
|
attempts += 1
|
|
if attempts == 1:
|
|
return httpx.Response(503, request=request)
|
|
if attempts == 2:
|
|
raise httpx.ReadTimeout(
|
|
"synthetic private diagnostic", request=request
|
|
)
|
|
return httpx.Response(200, json={"status": "ready"}, request=request)
|
|
|
|
monkeypatch.setattr("scripts.research_security.time.sleep", lambda _: None)
|
|
with httpx.Client(transport=httpx.MockTransport(handle)) as client:
|
|
result = observe_get(
|
|
client,
|
|
"https://synthetic/attachment",
|
|
deadline=time.monotonic() + 3,
|
|
observations=observations,
|
|
kind="metadata",
|
|
headers={"Authorization": "Bearer synthetic-private-token"},
|
|
)
|
|
assert result.json()["status"] == "ready"
|
|
assert attempts == 3
|
|
assert observations == {
|
|
"metadata": {"503": 1, "transport:ReadTimeout": 1, "200": 1}
|
|
}
|
|
assert "private" not in json.dumps(observations)
|
|
|
|
|
|
@pytest.mark.parametrize("status", [401, 403, 404, 500])
|
|
def test_auth_acl_missing_objects_and_unexpected_errors_are_fatal(status):
|
|
observations = {}
|
|
attempts = 0
|
|
|
|
def handle(request):
|
|
nonlocal attempts
|
|
attempts += 1
|
|
return httpx.Response(status, request=request)
|
|
|
|
with httpx.Client(transport=httpx.MockTransport(handle)) as client:
|
|
with pytest.raises(AssertionError, match=str(status)):
|
|
observe_get(
|
|
client,
|
|
"https://synthetic/attachment",
|
|
deadline=time.monotonic() + 3,
|
|
observations=observations,
|
|
kind="metadata",
|
|
)
|
|
assert attempts == 1
|
|
assert observations == {"metadata": {str(status): 1}}
|
|
|
|
|
|
def test_retries_cannot_turn_permanent_unavailability_into_success(
|
|
monkeypatch,
|
|
):
|
|
clock = [0.0]
|
|
monkeypatch.setattr(
|
|
"scripts.research_security.time.monotonic", lambda: clock[0]
|
|
)
|
|
monkeypatch.setattr(
|
|
"scripts.research_security.time.sleep",
|
|
lambda seconds: clock.__setitem__(0, clock[0] + seconds),
|
|
)
|
|
observations = {}
|
|
with httpx.Client(
|
|
transport=httpx.MockTransport(lambda r: httpx.Response(503, request=r))
|
|
) as client:
|
|
with pytest.raises(TimeoutError, match="deadline exceeded"):
|
|
observe_get(
|
|
client,
|
|
"https://synthetic/attachment",
|
|
deadline=1,
|
|
observations=observations,
|
|
kind="metadata",
|
|
)
|
|
assert clock[0] == 1
|
|
assert observations == {"metadata": {"503": 4}}
|