Repository: encode/httpx

Issue:
Don't render Authorization, Proxy-Authorization headers, password in URLs
We could render them as `[secure]` when calling `__repr__` so that they're not exposed by logging services. Was wondering what others thought of this idea?

Discussion:
cansarigol: Thanks for help @sethmlarson. I applied your comments
tomchristie: I'm liking this, yup! Coupla minor comments.
cansarigol: Thanks again @tomchristie, I applied your comments.
tomchristie: General thought: Do we prefer `[secure]` or `********` as the placeholder here?

We use the asterix style in Starlette, and I quite like it as being language independent, and mirroring eg. password input styling. What prior art is there in other places in Python - is there anything similar in eg. werkzeug or urllib or requests, or anything?
sethmlarson: Btw I chose `[secure]` just because it's what Travis does to obscure private environment values. 
StephenBrown2: Random comment from the peanut gallery: I'm in favor of `********`, as pydantic uses asterisks for it's Secret types as well: https://pydantic-docs.helpmanual.io/#secret-types
pquentin: Another data point: [Sentry uses [Filtered]](https://help.sentry.io/hc/en-us/articles/115000154594-Why-am-I-seeing-Filtered-in-my-event-data-). (But `********` is fine.)
cansarigol: I'm using Elastic APM. it uses `********`

Patch:
diff --git a/httpx/dispatch/asgi.py b/httpx/dispatch/asgi.py
index 23eebb0..e3b4b0a 100644
--- a/httpx/dispatch/asgi.py
+++ b/httpx/dispatch/asgi.py
@@ -78,7 +78,7 @@ class ASGIDispatch(AsyncDispatcher):
         app_exc = None
         status_code = None
         headers = None
-        response_started = asyncio.Event()
+        response_started_or_failed = asyncio.Event()
         response_body = BodyIterator()
         request_stream = request.stream()
 
@@ -92,19 +92,20 @@ class ASGIDispatch(AsyncDispatcher):
             return {"type": "http.request", "body": body, "more_body": True}
 
         async def send(message: dict) -> None:
-            nonlocal status_code, headers, response_started, response_body, request
+            nonlocal status_code, headers, response_started_or_failed
+            nonlocal response_body, request
 
             if message["type"] == "http.response.start":
                 status_code = message["status"]
                 headers = message.get("headers", [])
-                response_started.set()
+                response_started_or_failed.set()
             elif message["type"] == "http.response.body":
                 body = message.get("body", b"")
                 more_body = message.get("more_body", False)
                 if body and request.method != "HEAD":
                     await response_body.put(body)
                 if not more_body:
-                    await response_body.done()
+                    await response_body.mark_as_done()
 
         async def run_app() -> None:
             nonlocal app, scope, receive, send, app_exc, response_body
@@ -113,7 +114,8 @@ class ASGIDispatch(AsyncDispatcher):
             except Exception as exc:
                 app_exc = exc
             finally:
-                await response_body.done()
+                await response_body.mark_as_done()
+                response_started_or_failed.set()
 
         # Really we'd like to push all `asyncio` logic into concurrency.py,
         # with a standardized interface, so that we can support other event
@@ -122,17 +124,13 @@ class ASGIDispatch(AsyncDispatcher):
         # `ConcurrencyBackend` with the `Client(app=asgi_app)` case.
         loop = asyncio.get_event_loop()
         app_task = loop.create_task(run_app())
-        response_task = loop.create_task(response_started.wait())
 
-        tasks = {app_task, response_task}  # type: typing.Set[asyncio.Task]
-
-        await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
+        await response_started_or_failed.wait()
 
         if app_exc is not None and self.raise_app_exceptions:
             raise app_exc
 
-        assert response_started.is_set(), "application did not return a response."
-        assert status_code is not None
+        assert status_code is not None, "application did not return a response."
         assert headers is not None
 
         async def on_close() -> None:
@@ -189,7 +187,7 @@ class BodyIterator:
         """
         await self._queue.put(data)
 
-    async def done(self) -> None:
+    async def mark_as_done(self) -> None:
         """
         Used by the server to signal the end of the response body.
         """
diff --git a/httpx/models.py b/httpx/models.py
index e433320..edb5723 100644
--- a/httpx/models.py
+++ b/httpx/models.py
@@ -210,6 +210,12 @@ class URL:
     def __repr__(self) -> str:
         class_name = self.__class__.__name__
         url_str = str(self)
+        if self._uri_reference.userinfo:
+            url_str = (
+                rfc3986.urlparse(url_str)
+                .copy_with(userinfo=f"{self.username}:[secure]")
+                .unsplit()
+            )
         return f"{class_name}({url_str!r})"
 
 
@@ -489,10 +495,14 @@ class Headers(typing.MutableMapping[str, str]):
         if self.encoding != "ascii":
             encoding_str = f", encoding={self.encoding!r}"
 
-        as_dict = dict(self.items())
-        if len(as_dict) == len(self):
+        sensitive_headers = {"authorization", "proxy-authorization"}
+        as_list = [
+            (k, "[secure]" if k in sensitive_headers else v) for k, v in self.items()
+        ]
+
+        as_dict = dict(as_list)
+        if len(as_dict) == len(as_list):
             return f"{class_name}({as_dict!r}{encoding_str})"
-        as_list = self.items()
         return f"{class_name}({as_list!r}{encoding_str})"
 
 


Test patch:
diff --git a/tests/client/test_auth.py b/tests/client/test_auth.py
index 6cc64a7..725ea56 100644
--- a/tests/client/test_auth.py
+++ b/tests/client/test_auth.py
@@ -2,6 +2,7 @@ import json
 import os
 
 from httpx import (
+    URL,
     AsyncDispatcher,
     AsyncRequest,
     AsyncResponse,
@@ -100,3 +101,20 @@ def test_trust_env_auth():
     assert response.json() == {
         "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"
     }
+
+
+def test_auth_hidden_url():
+    url = "http://example-username:example-password@example.org/"
+    expected = "URL('http://example-username:[secure]@example.org/')"
+    assert url == URL(url)
+    assert expected == repr(URL(url))
+
+
+def test_auth_hidden_header():
+    url = "https://example.org/"
+    auth = ("example-username", "example-password")
+
+    with Client(dispatch=MockDispatch()) as client:
+        response = client.get(url, auth=auth)
+
+    assert "'authorization': '[secure]'" in str(response.request.headers)