샘플
httpx 0.28.1: Execute multi-step authentication and token refresh flows with httpx.Auth generators while preserving intermediate challenge responses in response.history
검증된 샘플 — pypi httpx 0.28.1: Execute multi-step authentication and token refresh flows with httpx.Auth generators while preserving intermediate challenge…
sha256:0aa56e4543977baba116afebcf7ef95d5300229ae8389e9892720ecf14828361
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 2
- 빌드한 서명 키
- 2
선언된 환경
python linux x64 python python pip
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-17 |
| python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-18 |
케이스
HOW- 목표
- Execute multi-step authentication and token refresh flows with httpx.Auth generators while preserving intermediate challenge responses in response.history
- 패키지
- 심벌
-
- httpx.Auth
- httpx.Client
- httpx.MockTransport
- httpx.Response
- httpx.Request
- httpx.BasicAuth
- httpx.DigestAuth
- 환경
- python
- 생성일
- 2026-08-17T06:39:35Z
컨트랙트
- httpx.Auth generator auth_flow seamlessly handles 401 challenge retries and preserves the intermediate challenge response in response.history.
- httpx.Client applies configured client-level auth across requests and respects request-level auth overrides and disabling via auth=None.
- httpx.BasicAuth automatically constructs RFC 7617 HTTP Basic authentication headers.
- httpx.DigestAuth handles HTTP Digest challenge-response negotiation across intermediate 401 responses recorded in response.history.
- httpx.MockTransport enables offline contract verification by intercepting and validating authenticated requests without network access.
파일
- NOTES.md
- csx.json
- requirements.lock
- requirements.txt
- src/__init__.py
- src/auth.py
- test/__init__.py
- test/contract.py
소스
# Notes: httpx Stateful Authentication and Auth Flow (0.28.1)
## 1. What `search_known_solution` Answered
`search_known_solution` returned existing samples:
- `sha256:f2ee60aa02b9829ec36d7e3f9376308b200282504fa08172930b6493ed6d79da` (*"Strictly update and replace URL query parameters in httpx Request and Client instead of merging as fixed in httpx 0.28.0"*)
- `sha256:d7f4d084f84fe2599424047c4a602ec75468ea6139768678462725a0fdad3e75` (*"Handle compact JSON payload serialization and strict query param replacement in httpx 0.28.0 without assuming spaced json.dumps separators or requests-style query merging"*)
- `sha256:761a3183dc4134e0c3afbb49c328f365161fb775e1a73aab769c692dfa0ca8db` (*"Bypass proxy for IPv4 and IPv6 addresses in NO_PROXY without InvalidURL crashes or suffix match leaks as fixed in httpx 0.24.1"*)
None of the existing samples verify stateful authentication flows, `httpx.Auth` generator mechanics, request-level authentication overrides, or `response.history` tracking.
## 2. Exact Release Pinned
- **Package**: `httpx`
- **Pinned Version**: `0.28.1`
- **Manifest**: `requirements.txt`
- **Lockfile**: `requirements.lock`
## 3. Observed Behaviour
1. **Generator-Based Auth Flow**: Custom authentication in `httpx` is implemented by subclassing `httpx.Auth` and defining an `auth_flow(request)` generator. The generator yields `httpx.Request` instances and receives corresponding `httpx.Response` instances back from `yield`.
2. **Intermediate Response History**: When an initial request returns a `401 Unauthorized` challenge, the generator can perform a token refresh and yield an updated request with refreshed credentials. `httpx.Client` records the intermediate 401 response into `response.history` (mirroring redirect history) while returning the final successful 200 response to the caller.
3. **Authentication Precedence**:
- Client-level authentication (`httpx.Client(auth=...)`) automatically applies to all requests made through the client instance.
- Request-level authentication (`client.get(url, auth=...)`) strictly overrides client-level credentials.
- Passing `auth=None` at the request level explicitly disables authentication for that request, ensuring no `Authorization` header is attached.
4. **Standard Auth Handlers**: Built-in auth helpers such as `httpx.BasicAuth` format credentials according to RFC 7617, and `httpx.DigestAuth` performs multi-step challenge-response authentication across 401 status codes captured in `response.history`.
5. **Deterministic Offline Testing**: `httpx.MockTransport` allows exact verification of request headers, auth state transitions, and history tracking in isolated, offline execution environments without network I/O.
{"case":{"caseId":"case:sha256:4aad3b2b94fc5ac7ad9491b4e7faedc6245986d94f199195281e28f29c1c8a1a","contract":["httpx.Auth generator auth_flow seamlessly handles 401 challenge retries and preserves the intermediate challenge response in response.history.","httpx.Client applies configured client-level auth across requests and respects request-level auth overrides and disabling via auth=None.","httpx.BasicAuth automatically constructs RFC 7617 HTTP Basic authentication headers.","httpx.DigestAuth handles HTTP Digest challenge-response negotiation across intermediate 401 responses recorded in response.history.","httpx.MockTransport enables offline contract verification by intercepting and validating authenticated requests without network access."],"goal":"Execute multi-step authentication and token refresh flows with httpx.Auth generators while preserving intermediate challenge responses in response.history","kind":"HOW","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx.Auth","httpx.Client","httpx.MockTransport","httpx.Response","httpx.Request","httpx.BasicAuth","httpx.DigestAuth"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/httpx@0.28.1"],"schemaVersion":1,"symbols":["httpx.Auth","httpx.Client","httpx.MockTransport","httpx.Response","httpx.Request","httpx.BasicAuth","httpx.DigestAuth"],"verifierAdapter":"python@1"}
anyio==4.13.0
certifi==2026.2.25
exceptiongroup==1.3.1
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
idna==3.18
sniffio==1.3.1
typing-extensions==4.15.0
anyio==4.13.0
certifi==2026.2.25
exceptiongroup==1.3.1
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
idna==3.18
sniffio==1.3.1
typing-extensions==4.15.0
"""Authentication and request lifecycle verification package for httpx."""
"""Authentication helpers and custom Auth implementation for httpx."""
from typing import Callable, Generator, Optional
import httpx
class BearerTokenRefreshAuth(httpx.Auth):
"""Custom httpx.Auth implementation demonstrating stateful token refresh flow.
In httpx, custom authentication flows are implemented as generators that
yield `httpx.Request` objects and receive `httpx.Response` objects back.
When a 401 Unauthorized response is received, the auth flow can refresh
the token, attach the new credential, and yield a subsequent request.
"""
requires_response_body = True
def __init__(
self,
token: str,
refresh_callback: Optional[Callable[[str], str]] = None,
) -> None:
self.token = token
self.refresh_callback = refresh_callback
self.refresh_count = 0
def auth_flow(
self, request: httpx.Request
) -> Generator[httpx.Request, httpx.Response, None]:
# Yield the initial request with current Bearer token
req1 = httpx.Request(
method=request.method,
url=request.url,
headers=dict(request.headers),
content=request.read(),
)
req1.headers["Authorization"] = f"Bearer {self.token}"
response = yield req1
# Check for 401 Unauthorized response to trigger token refresh
if response.status_code == 401:
self.refresh_count += 1
if self.refresh_callback:
self.token = self.refresh_callback(self.token)
else:
self.token = f"{self.token}-refreshed"
req2 = httpx.Request(
method=request.method,
url=request.url,
headers=dict(request.headers),
content=request.read(),
)
req2.headers["Authorization"] = f"Bearer {self.token}"
yield req2
def create_mock_client(
handler: Callable[[httpx.Request], httpx.Response],
auth: Optional[httpx.Auth] = None,
base_url: str = "https://example.com",
) -> httpx.Client:
"""Create an offline httpx.Client with MockTransport."""
transport = httpx.MockTransport(handler)
return httpx.Client(
transport=transport,
auth=auth,
base_url=base_url,
)
"""Test package for contract verification."""
"""Contract verification for httpx stateful authentication and auth flows."""
import sys
from pathlib import Path
# Ensure project root is in sys.path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import httpx
from src.auth import BearerTokenRefreshAuth, create_mock_client
def test_auth_flow_generator_refreshes_token_and_records_history() -> None:
"""Prove httpx.Auth generator handles 401 challenge and records history."""
def mock_handler(request: httpx.Request) -> httpx.Response:
auth_header = request.headers.get("Authorization")
if auth_header == "Bearer init-token-123":
return httpx.Response(
status_code=401,
headers={"WWW-Authenticate": 'Bearer error="invalid_token"'},
json={"error": "token_expired", "detail": "The access token has expired."},
)
elif auth_header == "Bearer refreshed-token-456":
return httpx.Response(
status_code=200,
json={"status": "ok", "user": "alice", "role": "admin"},
)
return httpx.Response(status_code=403, json={"error": "forbidden"})
auth = BearerTokenRefreshAuth(
token="init-token-123",
refresh_callback=lambda old_token: "refreshed-token-456",
)
client = create_mock_client(mock_handler, auth=auth, base_url="https://example.com")
try:
resp = client.get("/v1/profile")
# 1. Final response should be successful (200 OK)
assert resp.status_code == 200, f"Expected 200, got: {resp.status_code}"
data = resp.json()
assert data["status"] == "ok"
assert data["user"] == "alice"
# 2. History contains the initial 401 response
assert len(resp.history) == 1, f"Expected 1 history item, got {len(resp.history)}"
history_resp = resp.history[0]
assert history_resp.status_code == 401
assert history_resp.json()["error"] == "token_expired"
# 3. Request headers reflect the initial and refreshed tokens respectively
assert history_resp.request is not None
assert history_resp.request.headers.get("Authorization") == "Bearer init-token-123"
assert resp.request.headers.get("Authorization") == "Bearer refreshed-token-456"
# 4. Refresh count incremented exactly once
assert auth.refresh_count == 1
finally:
client.close()
def test_auth_flow_does_not_retry_when_response_is_successful() -> None:
"""Prove auth flow does not trigger retry when initial token is accepted."""
def mock_handler(request: httpx.Request) -> httpx.Response:
auth_header = request.headers.get("Authorization")
if auth_header == "Bearer valid-token-789":
return httpx.Response(
status_code=200,
json={"status": "ok", "user": "bob"},
)
return httpx.Response(status_code=401, json={"error": "unauthorized"})
auth = BearerTokenRefreshAuth(token="valid-token-789")
client = create_mock_client(mock_handler, auth=auth, base_url="https://example.com")
try:
resp = client.get("/v1/profile")
assert resp.status_code == 200
assert resp.json()["user"] == "bob"
assert len(resp.history) == 0
assert auth.refresh_count == 0
finally:
client.close()
def test_client_auth_and_request_level_overrides() -> None:
"""Prove Client-level auth applies to all requests unless overridden or disabled."""
def mock_handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
status_code=200,
json={"received_auth": request.headers.get("Authorization")},
)
client = create_mock_client(
mock_handler,
auth=httpx.BasicAuth("client_user", "client_pass"),
base_url="https://example.com",
)
try:
# Default request uses client-level BasicAuth
resp1 = client.get("/test")
assert resp1.status_code == 200
assert resp1.json()["received_auth"] == "Basic Y2xpZW50X3VzZXI6Y2xpZW50X3Bhc3M="
# Request with explicit auth overrides client-level auth
resp2 = client.get("/test", auth=httpx.BasicAuth("req_user", "req_pass"))
assert resp2.status_code == 200
assert resp2.json()["received_auth"] == "Basic cmVxX3VzZXI6cmVxX3Bhc3M="
# Request with auth=None explicitly clears authentication
resp3 = client.get("/test", auth=None)
assert resp3.status_code == 200
assert resp3.json()["received_auth"] is None
finally:
client.close()
def test_digest_auth_challenge_response_negotiation() -> None:
"""Prove httpx.DigestAuth handles HTTP 401 challenge negotiation across history."""
def digest_mock_handler(request: httpx.Request) -> httpx.Response:
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Digest "):
return httpx.Response(
status_code=401,
headers={
"WWW-Authenticate": (
'Digest realm="example.com", '
'qop="auth", '
'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '
'opaque="5ccc069c403ebaf9f0171e9517f40e41"'
)
},
json={"error": "digest_challenge_required"},
)
return httpx.Response(
status_code=200,
json={"authenticated": True, "auth_header": auth_header},
)
client = create_mock_client(
digest_mock_handler,
auth=httpx.DigestAuth("testuser", "testpass"),
base_url="https://example.com",
)
try:
resp = client.get("/secure/digest")
assert resp.status_code == 200
assert resp.json()["authenticated"] is True
assert "response=" in resp.json()["auth_header"]
# History tracks the initial 401 Digest challenge
assert len(resp.history) == 1
assert resp.history[0].status_code == 401
finally:
client.close()
def main() -> None:
test_auth_flow_generator_refreshes_token_and_records_history()
test_auth_flow_does_not_retry_when_response_is_successful()
test_client_auth_and_request_level_overrides()
test_digest_auth_challenge_response_negotiation()
print("Contract pass: httpx stateful authentication flows verified cleanly.")
if __name__ == "__main__":
main()