Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@
| RunNowRefusalViewType9
)
DEADLINE: ContextVar[float | None] = ContextVar("proofline_request_deadline", default=None)
# Set once any response reaches the client, so operation_errors can tell a failure
# caused by what Proofline sent from an error raised before a request left the process.
RESPONDED: ContextVar[bool] = ContextVar("proofline_response_received", default=False)


class BearerAuth(httpx2.Auth):
Expand Down Expand Up @@ -163,14 +166,25 @@ def network_error(error: httpx2.HTTPError) -> ProoflineError:

@contextmanager
def operation_errors() -> Iterator[None]:
"""Map failures inside one generated operation to ProoflineError.

Only a response that arrived can be an invalid API response. An error raised
while the request is still being built, such as an unknown keyword or a body
of the wrong type, is the caller's and propagates unchanged.
"""
marker = RESPONDED.set(False)
try:
yield
except ProoflineError:
raise
except httpx2.HTTPError as error:
raise network_error(error) from None
except Exception:
if not RESPONDED.get():
raise
raise invalid_response() from None
finally:
RESPONDED.reset(marker)


def timeout_error() -> ProoflineError:
Expand Down Expand Up @@ -279,7 +293,8 @@ def text(value: object) -> bool:
def problem(response: httpx2.Response, token: SecretStr) -> ProoflineError:
try:
body = response.json()
except (ValueError, UnicodeError):
except (ValueError, UnicodeError, RecursionError):
# Nesting deeper than the decoder allows still fits in 8 MiB.
body = None
if not isinstance(body, dict):
return ProoflineError(
Expand Down Expand Up @@ -447,6 +462,7 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response:
response = self._inner.handle_request(request)
finally:
IO_DEADLINE.reset(marker)
RESPONDED.set(True)
if 300 <= response.status_code < 400:
response.close()
raise redirect_error(response.status_code) from None
Expand Down Expand Up @@ -498,6 +514,7 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response
response = await self._inner.handle_async_request(request)
except TimeoutError:
raise httpx2.ReadTimeout("The request deadline expired.") from None
RESPONDED.set(True)
if 300 <= response.status_code < 400:
await response.aclose()
raise redirect_error(response.status_code) from None
Expand Down
68 changes: 68 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,74 @@ async def test_successful_private_body_decoder_failure_is_static(mode: str) -> N
assert TOKEN not in "".join(traceback.format_exception(error))


@MODES
async def test_caller_errors_before_any_request_are_not_reported_as_api_responses(
mode: str,
) -> None:
# Nothing reaches Proofline, so nothing can be an invalid Proofline response: the
# caller's mistake keeps its own type, message and traceback.
with Server(lambda request, index: Reply(body=finding())) as server:
async with session(mode, server.url) as client:
with pytest.raises(TypeError, match="limt"):
await call(client, "list_reviews", ORG, limt=5)
with pytest.raises(AttributeError, match="to_dict"):
await call(client, "request_patch_review", ORG, REPOSITORY, body={"patch": "x"})
# Methods generated from the contract share the same mapping.
with pytest.raises(AttributeError, match="to_dict"):
await call(client, "request_scan", ORG, REPOSITORY, body={"budget_credits": 1})
with pytest.raises(TypeError) as raised:
await call(client, "get_finding", ORG)
assert raised.value.__traceback__ is not None
assert not isinstance(raised.value, ProoflineError)
assert server.requests == []


@MODES
async def test_a_body_that_arrives_still_decodes_to_the_static_sdk_problem(mode: str) -> None:
# A caller error earlier on the same client must not change how a later reply maps.
with Server(lambda request, index: Reply(body={"id": PRIVATE})) as server:
async with session(mode, server.url) as client:
with pytest.raises(TypeError):
await call(client, "list_reviews", ORG, limt=5)
scan = models.ScanRequestBody(budget_credits=1, request_id=REVIEW)
for name, args, kwargs in [
("get_finding", (ORG, FINDING), {}),
("request_scan", (ORG, REPOSITORY), {"body": scan}),
]:
with pytest.raises(ProoflineError) as raised:
await call(client, name, *args, **kwargs)
assert raised.value.type == "urn:proofline:sdk:invalid-response"
assert PRIVATE not in "".join(traceback.format_exception(raised.value))
assert len(server.requests) == 2


@MODES
@pytest.mark.parametrize("status", [400, 500])
async def test_problem_nested_past_the_decoder_limit_stays_a_typed_problem(
mode: str, status: int
) -> None:
# Nesting deeper than json allows fits well inside 8 MiB and raises RecursionError.
deep = b"[" * 100_000 + b"]" * 100_000
with Server(lambda request, index: Reply(status, deep)) as server:
async with session(mode, server.url) as client:
scan = models.ScanRequestBody(budget_credits=1, request_id=REVIEW)
for name, args, kwargs in [
("get_finding", (ORG, FINDING), {}),
("request_scan", (ORG, REPOSITORY), {"body": scan}),
(
"export_reviews",
(ORG, "reviews"),
{"from_time": "2026-10-01T00:00:00Z", "to_time": "2026-10-02T00:00:00Z"},
),
]:
with pytest.raises(ProoflineError) as raised:
await call(client, name, *args, **kwargs)
assert raised.value.status == status
assert raised.value.detail == (
"Proofline returned an HTTP error without a problem document."
)


@MODES
async def test_redirect_never_contacts_other_origin(mode: str) -> None:
with Server(lambda request, index: Reply(body=finding())) as other:
Expand Down