Repository: encode/httpx

Issue:
DigestAuth should raise a clear error if the request cannot replay.
Our DigestAuth implementation cannot work with non-replayable requests.
We ought to raise a nice clear error if `request.stream.is_replayable` is not True.

Discussion:
florimondmanca: @kousikmitra Issued https://github.com/encode/httpx/pull/690. Feel free to have a look!

Patch:
diff --git a/httpx/auth.py b/httpx/auth.py
index e0ef50c..e412c57 100644
--- a/httpx/auth.py
+++ b/httpx/auth.py
@@ -6,7 +6,7 @@ import typing
 from base64 import b64encode
 from urllib.request import parse_http_list
 
-from .exceptions import ProtocolError
+from .exceptions import ProtocolError, RequestBodyUnavailable
 from .models import Request, Response
 from .utils import to_bytes, to_str, unquote
 
@@ -104,6 +104,8 @@ class DigestAuth(Auth):
         self.password = to_bytes(password)
 
     def __call__(self, request: Request) -> AuthFlow:
+        if not request.stream.can_replay():
+            raise RequestBodyUnavailable("Request body is no longer available.")
         response = yield request
 
         if response.status_code != 401 or "www-authenticate" not in response.headers:


Test patch:
diff --git a/tests/client/test_auth.py b/tests/client/test_auth.py
index ea6ff8a..34ec77e 100644
--- a/tests/client/test_auth.py
+++ b/tests/client/test_auth.py
@@ -5,7 +5,15 @@ import typing
 
 import pytest
 
-from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response
+from httpx import (
+    URL,
+    AsyncClient,
+    DigestAuth,
+    ProtocolError,
+    Request,
+    RequestBodyUnavailable,
+    Response,
+)
 from httpx.auth import Auth, AuthFlow
 from httpx.config import CertTypes, TimeoutTypes, VerifyTypes
 from httpx.dispatch.base import Dispatcher
@@ -442,3 +450,16 @@ async def test_auth_history() -> None:
     assert resp2.history == [resp1]
 
     assert len(resp1.history) == 0
+
+
+@pytest.mark.asyncio
+async def test_digest_auth_unavailable_streaming_body():
+    url = "https://example.org/"
+    auth = DigestAuth(username="tomchristie", password="password123")
+    client = AsyncClient(dispatch=MockDispatch())
+
+    async def streaming_body():
+        yield b"Example request body"
+
+    with pytest.raises(RequestBodyUnavailable):
+        await client.post(url, data=streaming_body(), auth=auth)