Skip to content

Commit 9d7f58e

Browse files
fix: redact credential headers on API error requests (#4316)
Use the existing sensitive-header list for request copies attached to API errors. Both `error.request` and `error.response.request` point to the same copy. Redirect history and pending redirects follow the same rule. The transport keeps its original request. Callers that resend a request from an error must reapply authentication. This change is limited to known request headers on these public attributes. Verified with sync and async client, streaming, authentication, and redirect tests (654 passed, 36 skipped), Ruff, and ty.
1 parent fa01235 commit 9d7f58e

4 files changed

Lines changed: 72 additions & 7 deletions

File tree

‎src/openai/_exceptions.py‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
from __future__ import annotations
22

3+
from copy import copy
34
from typing import TYPE_CHECKING, Any, Optional, cast
45
from typing_extensions import Literal, override
56

67
import httpx2
78

89
from ._utils import is_dict
910
from ._models import construct_type
11+
from ._utils._logs import SENSITIVE_HEADERS
1012
from .types.shared.oauth_error_code import OAuthErrorCode
1113

1214
if TYPE_CHECKING:
@@ -43,6 +45,36 @@ def __init__(self, message: str, *, response: httpx2.Response | None = None) ->
4345
self.response = response
4446

4547

48+
def _error_request(request: httpx2.Request) -> httpx2.Request:
49+
if not any(name in request.headers for name in SENSITIVE_HEADERS):
50+
return request
51+
52+
safe = copy(request)
53+
# HTTPX omits the stream and extensions when copying. Never read a streaming upload here.
54+
safe.stream = request.stream
55+
safe.extensions = request.extensions.copy()
56+
safe.headers = request.headers.copy()
57+
for name in SENSITIVE_HEADERS:
58+
safe.headers.pop(name, None)
59+
return safe
60+
61+
62+
def _error_response(response: httpx2.Response, request: httpx2.Request) -> httpx2.Response:
63+
if request is response.request and not response.history and response.next_request is None:
64+
return response
65+
66+
history: list[httpx2.Response] = []
67+
for hop in [*response.history, response]:
68+
safe = copy(hop)
69+
safe.extensions = hop.extensions.copy()
70+
safe.request = request if hop is response else _error_request(hop.request)
71+
if hop.next_request is not None:
72+
safe.next_request = _error_request(hop.next_request)
73+
safe.history = history.copy()
74+
history.append(safe)
75+
return history[-1]
76+
77+
4678
class APIError(OpenAIError):
4779
message: str
4880
request: httpx2.Request
@@ -64,7 +96,7 @@ class APIError(OpenAIError):
6496

6597
def __init__(self, message: str, request: httpx2.Request, *, body: object | None) -> None:
6698
super().__init__(message)
67-
self.request = request
99+
self.request = _error_request(request)
68100
self.message = message
69101
self.body = body
70102

@@ -85,7 +117,7 @@ class APIResponseValidationError(APIError):
85117

86118
def __init__(self, response: httpx2.Response, body: object | None, *, message: str | None = None) -> None:
87119
super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body)
88-
self.response = response
120+
self.response = _error_response(response, self.request)
89121
self.status_code = response.status_code
90122

91123

@@ -98,7 +130,7 @@ class APIStatusError(APIError):
98130

99131
def __init__(self, message: str, *, response: httpx2.Response, body: object | None) -> None:
100132
super().__init__(message, response.request, body=body)
101-
self.response = response
133+
self.response = _error_response(response, self.request)
102134
self.status_code = response.status_code
103135
self.request_id = response.headers.get("x-request-id")
104136

‎tests/test_client.py‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,7 +1062,10 @@ def mock_handler(request: httpx2.Request) -> httpx2.Response:
10621062
)
10631063
except APIStatusError as exc:
10641064
assert rewind_fails
1065-
assert exc.response is original_response
1065+
assert exc.response.status_code == original_response.status_code
1066+
assert exc.response.request is exc.request
1067+
assert "authorization" not in exc.request.headers
1068+
assert "authorization" in original_response.request.headers
10661069
else:
10671070
assert not rewind_fails
10681071
assert response.status_code == 200
@@ -1334,6 +1337,8 @@ class Model(BaseModel):
13341337
client.get("/foo", cast_to=Model)
13351338

13361339
assert isinstance(exc.value.__cause__, ValidationError)
1340+
assert exc.value.response.request is exc.value.request
1341+
assert "authorization" not in exc.value.request.headers
13371342

13381343
def test_client_max_retries_validation(self) -> None:
13391344
with pytest.raises(TypeError, match=r"max_retries cannot be None"):
@@ -2476,7 +2481,10 @@ async def mock_handler(request: httpx2.Request) -> httpx2.Response:
24762481
)
24772482
except APIStatusError as exc:
24782483
assert rewind_fails
2479-
assert exc.response is original_response
2484+
assert exc.response.status_code == original_response.status_code
2485+
assert exc.response.request is exc.request
2486+
assert "authorization" not in exc.request.headers
2487+
assert "authorization" in original_response.request.headers
24802488
else:
24812489
assert not rewind_fails
24822490
assert response.status_code == 200
@@ -2727,6 +2735,8 @@ class Model(BaseModel):
27272735
await async_client.get("/foo", cast_to=Model)
27282736

27292737
assert isinstance(exc.value.__cause__, ValidationError)
2738+
assert exc.value.response.request is exc.value.request
2739+
assert "authorization" not in exc.value.request.headers
27302740

27312741
async def test_client_max_retries_validation(self) -> None:
27322742
with pytest.raises(TypeError, match=r"max_retries cannot be None"):
@@ -3585,7 +3595,9 @@ def handler(request: httpx2.Request) -> httpx2.Response:
35853595
except APIConnectionError as exc:
35863596
assert failures > max_retries
35873597
assert exc.__cause__ is error
3588-
assert exc.request is requests[-1]
3598+
assert exc.request.url == requests[-1].url
3599+
assert "authorization" not in exc.request.headers
3600+
assert "authorization" in requests[-1].headers
35893601
else:
35903602
assert failures <= max_retries
35913603
assert result == {"recovered": True}

‎tests/test_status_error_messages.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,22 @@ async def test_status_error_message(
5454
logging.getLogger(__name__).error("Request failed", exc_info=(type(error), error, error.__traceback__))
5555
assert expected_message in caplog.text
5656
assert "extra-response-data" not in caplog.text
57+
58+
59+
@pytest.mark.respx2(base_url=base_url)
60+
def test_status_error_request_headers(client: OpenAI, respx2_mock: MockRouter) -> None:
61+
respx2_mock.get("/start").mock(return_value=httpx2.Response(307, headers={"Location": "/end"}))
62+
respx2_mock.get("/end").mock(return_value=httpx2.Response(500, headers={"x-request-id": "req_test"}))
63+
headers = {"Api-Key": "fake", "X-Amz-Security-Token": "fake", "X-Trace": "trace"}
64+
65+
with pytest.raises(InternalServerError) as exc:
66+
client.with_options(max_retries=0, default_headers=headers).get("/start", cast_to=object)
67+
68+
error = exc.value
69+
assert error.request_id == "req_test"
70+
assert error.response.request is error.request
71+
for request in (error.request, error.response.history[0].request):
72+
assert "authorization" not in request.headers
73+
assert "api-key" not in request.headers
74+
assert "x-amz-security-token" not in request.headers
75+
assert request.headers["x-trace"] == "trace"

‎tests/test_streaming.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,9 @@ def handler(request: Any) -> Any:
264264

265265
assert received == (["hello"] if delivered else [])
266266
assert len(requests) == 1
267-
assert caught.value.request is requests[0]
267+
assert caught.value.request.content == requests[0].content
268+
assert "authorization" not in caught.value.request.headers
269+
assert "authorization" in requests[0].headers
268270
assert caught.value.__cause__ is error
269271

270272

0 commit comments

Comments
 (0)