Skip to content
Myr

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

5 files+130 added−14 removed

modified:httpx/dispatch/asgi.py+11 added-8 removed
2 unmodified lines
3from ..concurrency.asyncio import AsyncioBackend4from ..concurrency.base import ConcurrencyBackend5from ..config import CertTypes, TimeoutTypes, VerifyTypes6from ..models import AsyncRequest, AsyncResponse7from ..utils import MessageLoggerASGIMiddleware, get_logger8from .base import AsyncDispatcher910logger = get_logger(__name__)111213class ASGIDispatch(AsyncDispatcher):14 """15 A custom dispatcher that handles sending requests directly to an ASGI app.1614 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:2021 ```
10 unmodified lines
32 root_path="/submount",33 client=("1.2.3.4", 123)34 )35 client = httpx.Client(dispatch=dispatch)36 ```3738 Arguments:3940 * `app` - The ASGI application.
39 unmodified lines
80 "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()9192 async def receive() -> dict:89 nonlocal request_stream9093 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}9899 async def send(message: dict) -> None:98 nonlocal status_code, headers, response_started_or_failed99 nonlocal response_body, request100 nonlocal status_code, headers101102 if message["type"] == "http.response.start":103 status_code = message["status"]104 headers = message.get("headers", [])105 response_started_or_failed.set()106107 elif message["type"] == "http.response.body":108 body = message.get("body", b"")109 more_body = message.get("more_body", False)110111 if body and request.method != "HEAD":112 await response_body.put(body)113114 if not more_body:115 await response_body.mark_as_done()116117 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 = exc
17 unmodified lines
140 assert status_code is not None, "application did not return a response."141 assert headers is not None142143 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_exc
51 unmodified lines
modified:httpx/models.py+5 added-6 removed
34 unmodified lines
35 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 lines
554 encoding_str = ""555 if self.encoding != "ascii":556 encoding_str = f", encoding={self.encoding!r}"557557 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 ]561558 as_list = list(obfuscate_sensitive_headers(self.items()))559 as_dict = dict(as_list)563 if len(as_dict) == len(as_list):560561 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})"565566
726 unmodified lines
modified:httpx/utils.py+86 added
158 unmodified lines
159 links.append(link)160 return links161162163SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}164165166def 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, v173174175_LOGGER_INITIALIZED = False176177178def get_logger(name: str) -> logging.Logger:
19 unmodified lines
198199 return logging.getLogger(name)200201202def kv_format(**kwargs: typing.Any) -> str:203 """Format arguments into a key=value line.204205 >>> formatkv(x=1, name="Bob")206 "x=1 name='Bob'"207 """208 return " ".join(f"{key}={value!r}" for key, value in kwargs.items())209210211def get_environment_proxies() -> typing.Dict[str, str]:212 """Gets proxy information from the environment"""213214 # urllib.request.getproxies() falls back on System
32 unmodified lines
247def to_str(value: typing.Union[str, bytes], encoding: str = "utf-8") -> str:248 return value if isinstance(value, str) else value.decode(encoding)249250251def 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()253254255def unquote(value: str) -> str:256 return value[1:-1] if value[0] == value[-1] == '"' else value257258
18 unmodified lines
277 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)281282283ASGI_PLACEHOLDER_FORMAT = {284 "body": "<{length} bytes>",285 "bytes": "<{length} bytes>",286 "text": "<{length} chars>",287}288289290def 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()296297 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] = placeholder302303 if "headers" in message:304 new_message["headers"] = list(obfuscate_sensitive_headers(message["headers"]))305306 return new_message307308309class MessageLoggerASGIMiddleware:310 def __init__(self, app: typing.Callable, logger: logging.Logger) -> None:311 self.app = app312 self.logger = logger313314 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 message322323 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)327328 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)}")334335 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
1import pytest23import httpx456def test_headers():
145 unmodified lines
152 h.getlist("Set-Cookie") == ["a, b", "b"]153154 h = httpx.Headers([("vary", "a, b"), ("vary", "c")])155 h.getlist("Vary") == ["a", "b", "c"]156157158@pytest.mark.parametrize("header", ["authorization", "proxy-authorization"])159def 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]'})" % header
modified:tests/test_utils.py+16 added
10 unmodified lines
11 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)1819
172 unmodified lines
192def test_get_environment_proxies(environment, proxies):193 os.environ.update(environment)194195 assert get_environment_proxies() == proxies196197198@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)206def 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