Add debug logs to ASGIDispatch (#371)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add debug logs to ASGIDispatch * Tidy up ASGIDispatch * Log entire scope and ASGI messages * Obfuscate sensitive headers using common utility * Update utils.py
authored by Florimond Manca · committed by GitHub · parent c9810a7 · Browse files · 5 files·+130 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+130 added−14 removed
- tests:+28 added−0 removed
- other:+102 added−14 removed
Provenance
- Commit
e62e5c3- Tree
be73c92- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
c9810a7
5 files changed+130 added−14 removed
modified:httpx/dispatch/asgi.py+11 added-8 removed
2 unmodified lines3 from ..concurrency.asyncio import AsyncioBackend4 from ..concurrency.base import ConcurrencyBackend5 from ..config import CertTypes, TimeoutTypes, VerifyTypes6 from ..models import AsyncRequest, AsyncResponse7+from ..utils import MessageLoggerASGIMiddleware, get_logger8 from .base import AsyncDispatcher9 10+logger = get_logger(__name__)11 12+13 class ASGIDispatch(AsyncDispatcher):14 """15 A custom dispatcher that handles sending requests directly to an ASGI app.16 14- The simplest way to use this functionality is to use the `app`argument.17+ The simplest way to use this functionality is to use the `app` argument.18 This will automatically infer if 'app' is a WSGI or an ASGI application,19 and will setup an appropriate dispatch class:20 21 ```10 unmodified lines32 root_path="/submount",33 client=("1.2.3.4", 123)34 )35 client = httpx.Client(dispatch=dispatch)36+ ```37 38 Arguments:39 40 * `app` - The ASGI application.39 unmodified lines80 "server": request.url.host,81 "client": self.client,82 "root_path": self.root_path,83 }80- app = self.app84+ app = MessageLoggerASGIMiddleware(self.app, logger=logger)85 app_exc = None86 status_code = None87 headers = None88 response_started_or_failed = self.backend.create_event()89 response_body = BodyIterator(self.backend)90 request_stream = request.stream()91 92 async def receive() -> dict:89- nonlocal request_stream90-93 try:94 body = await request_stream.__anext__()95 except StopAsyncIteration:96 return {"type": "http.request", "body": b"", "more_body": False}97 return {"type": "http.request", "body": body, "more_body": True}98 99 async def send(message: dict) -> None:98- nonlocal status_code, headers, response_started_or_failed99- nonlocal response_body, request100+ nonlocal status_code, headers101 102 if message["type"] == "http.response.start":103 status_code = message["status"]104 headers = message.get("headers", [])105 response_started_or_failed.set()106+107 elif message["type"] == "http.response.body":108 body = message.get("body", b"")109 more_body = message.get("more_body", False)110+111 if body and request.method != "HEAD":112 await response_body.put(body)113+114 if not more_body:115 await response_body.mark_as_done()116 117 async def run_app() -> None:114- nonlocal app, scope, receive, send, app_exc, response_body118+ nonlocal app_exc119 try:120 await app(scope, receive, send)121 except Exception as exc:122 app_exc = exc17 unmodified lines140 assert status_code is not None, "application did not return a response."141 assert headers is not None142 143 async def on_close() -> None:140- nonlocal response_body144 await response_body.drain()145 await background.close(app_exc)146 if app_exc is not None and self.raise_app_exceptions:147 raise app_exc51 unmodified linesmodified:httpx/models.py+5 added-6 removed
34 unmodified lines35 guess_json_utf,36 is_known_encoding,37 normalize_header_key,38 normalize_header_value,39+ obfuscate_sensitive_headers,40 parse_header_links,41 str_query_param,42 )43 510 unmodified lines554 encoding_str = ""555 if self.encoding != "ascii":556 encoding_str = f", encoding={self.encoding!r}"557 557- sensitive_headers = {"authorization", "proxy-authorization"}558- as_list = [559- (k, "[secure]" if k in sensitive_headers else v) for k, v in self.items()560- ]561-558+ as_list = list(obfuscate_sensitive_headers(self.items()))559 as_dict = dict(as_list)563- if len(as_dict) == len(as_list):560+561+ no_duplicate_keys = len(as_dict) == len(as_list)562+ if no_duplicate_keys:563 return f"{class_name}({as_dict!r}{encoding_str})"564 return f"{class_name}({as_list!r}{encoding_str})"565 566 726 unmodified linesmodified:httpx/utils.py+86 added
158 unmodified lines159 links.append(link)160 return links161 162 163+SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}164+165+166+def obfuscate_sensitive_headers(167+ items: typing.Iterable[typing.Tuple[typing.AnyStr, typing.AnyStr]]168+) -> typing.Iterator[typing.Tuple[typing.AnyStr, typing.AnyStr]]:169+ for k, v in items:170+ if to_str(k.lower()) in SENSITIVE_HEADERS:171+ v = to_bytes_or_str("[secure]", match_type_of=v)172+ yield k, v173+174+175 _LOGGER_INITIALIZED = False176 177 178 def get_logger(name: str) -> logging.Logger:19 unmodified lines198 199 return logging.getLogger(name)200 201 202+def kv_format(**kwargs: typing.Any) -> str:203+ """Format arguments into a key=value line.204+205+ >>> formatkv(x=1, name="Bob")206+ "x=1 name='Bob'"207+ """208+ return " ".join(f"{key}={value!r}" for key, value in kwargs.items())209+210+211 def get_environment_proxies() -> typing.Dict[str, str]:212 """Gets proxy information from the environment"""213 214 # urllib.request.getproxies() falls back on System32 unmodified lines247 def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:248 return value if isinstance(value, str) else value.decode(encoding)249 250 251+def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr:252+ return value if isinstance(match_type_of, str) else value.encode()253+254+255 def unquote(value: str) -> str:256 return value[1:-1] if value[0] == value[-1] == '"' else value257 258 18 unmodified lines277 def elapsed(self) -> timedelta:278 if self.end is None:279 return timedelta(seconds=perf_counter() - self.start)280 return timedelta(seconds=self.end - self.start)281+282+283+ASGI_PLACEHOLDER_FORMAT = {284+ "body": "<{length} bytes>",285+ "bytes": "<{length} bytes>",286+ "text": "<{length} chars>",287+}288+289+290+def asgi_message_with_placeholders(message: dict) -> dict:291+ """292+ Return an ASGI message, with any body-type content omitted and replaced293+ with a placeholder.294+ """295+ new_message = message.copy()296+297+ for attr in ASGI_PLACEHOLDER_FORMAT:298+ if attr in message:299+ content = message[attr]300+ placeholder = ASGI_PLACEHOLDER_FORMAT[attr].format(length=len(content))301+ new_message[attr] = placeholder302+303+ if "headers" in message:304+ new_message["headers"] = list(obfuscate_sensitive_headers(message["headers"]))305+306+ return new_message307+308+309+class MessageLoggerASGIMiddleware:310+ def __init__(self, app: typing.Callable, logger: logging.Logger) -> None:311+ self.app = app312+ self.logger = logger313+314+ async def __call__(315+ self, scope: dict, receive: typing.Callable, send: typing.Callable316+ ) -> None:317+ async def inner_receive() -> dict:318+ message = await receive()319+ logged_message = asgi_message_with_placeholders(message)320+ self.logger.debug(f"sent {kv_format(**logged_message)}")321+ return message322+323+ async def inner_send(message: dict) -> None:324+ logged_message = asgi_message_with_placeholders(message)325+ self.logger.debug(f"received {kv_format(**logged_message)}")326+ await send(message)327+328+ logged_scope = dict(scope)329+ if "headers" in scope:330+ logged_scope["headers"] = list(331+ obfuscate_sensitive_headers(scope["headers"])332+ )333+ self.logger.debug(f"started {kv_format(**logged_scope)}")334+335+ try:336+ await self.app(scope, inner_receive, inner_send)337+ except BaseException as exc:338+ self.logger.debug("raised_exception")339+ raise exc from None340+ else:341+ self.logger.debug("completed")modified:tests/models/test_headers.py+12 added
1+import pytest2+3 import httpx4 5 6 def test_headers():145 unmodified lines152 h.getlist("Set-Cookie") == ["a, b", "b"]153 154 h = httpx.Headers([("vary", "a, b"), ("vary", "c")])155 h.getlist("Vary") == ["a", "b", "c"]156+157+158+@pytest.mark.parametrize("header", ["authorization", "proxy-authorization"])159+def test_sensitive_headers(header):160+ """161+ Some headers should be obfuscated because they contain sensitive data.162+ """163+ value = "s3kr3t"164+ h = httpx.Headers({header: value})165+ assert repr(h) == "Headers({'%s': '[secure]'})" % headermodified:tests/test_utils.py+16 added
10 unmodified lines11 get_ca_bundle_from_env,12 get_environment_proxies,13 get_netrc_login,14 guess_json_utf,15+ obfuscate_sensitive_headers,16 parse_header_links,17 )18 19 172 unmodified lines192 def test_get_environment_proxies(environment, proxies):193 os.environ.update(environment)194 195 assert get_environment_proxies() == proxies196+197+198+@pytest.mark.parametrize(199+ "headers, output",200+ [201+ ([("content-type", "text/html")], [("content-type", "text/html")]),202+ ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),203+ ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),204+ ],205+)206+def test_obfuscate_sensitive_headers(headers, output):207+ bytes_headers = [(k.encode(), v.encode()) for k, v in headers]208+ bytes_output = [(k.encode(), v.encode()) for k, v in output]209+ assert list(obfuscate_sensitive_headers(headers)) == output210+ assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output