CodeSampleX

Beispiel

httpx 0.28.1: Execute multi-step authentication and token refresh flows with httpx.Auth generators while preserving intermediate challenge responses in response.history

Verifiziertes Beispiel für pypi httpx 0.28.1: Execute multi-step authentication and token refresh flows with httpx.Auth generators while preserving…

sha256:0aa56e4543977baba116afebcf7ef95d5300229ae8389e9892720ecf14828361

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
2
Signaturschlüssel, die es gebaut haben
2
Deklarierte Umgebung python linux x64 python python pip

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
Execute multi-step authentication and token refresh flows with httpx.Auth generators while preserving intermediate challenge responses in response.history
Pakete
Symbole
  • httpx.Auth
  • httpx.Client
  • httpx.MockTransport
  • httpx.Response
  • httpx.Request
  • httpx.BasicAuth
  • httpx.DigestAuth
Umgebung
python
Erstellt
2026-08-17T06:39:35Z

Contract

  1. httpx.Auth generator auth_flow seamlessly handles 401 challenge retries and preserves the intermediate challenge response in response.history.
  2. httpx.Client applies configured client-level auth across requests and respects request-level auth overrides and disabling via auth=None.
  3. httpx.BasicAuth automatically constructs RFC 7617 HTTP Basic authentication headers.
  4. httpx.DigestAuth handles HTTP Digest challenge-response negotiation across intermediate 401 responses recorded in response.history.
  5. httpx.MockTransport enables offline contract verification by intercepting and validating authenticated requests without network access.

Dateien

  • NOTES.md
  • csx.json
  • requirements.lock
  • requirements.txt
  • src/__init__.py
  • src/auth.py
  • test/__init__.py
  • test/contract.py

Quellartefakt herunterladen (tar.gz)

Quelltext

NOTES.md
# 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.
csx.json
{"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"}
requirements.lock
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
requirements.txt
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
src/__init__.py
"""Authentication and request lifecycle verification package for httpx."""
src/auth.py
"""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/__init__.py
"""Test package for contract verification."""
test/contract.py
"""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()

Ursprungs-Seeder

csx-seed