|
| 1 | +# Pins the fetch server's direct connections to addresses the private-address |
| 2 | +# guard approved (#5557). The guard in server.py is a request hook: it resolves |
| 3 | +# the URL's host and refuses a non-public address. httpx then opened the |
| 4 | +# connection by resolving the same name a second time, so a name whose DNS |
| 5 | +# answer changed between the two lookups (DNS rebinding) passed the check with |
| 6 | +# a public address and connected to a private one. |
| 7 | +# |
| 8 | +# The fix is to make the lookup that picks the address the one that is |
| 9 | +# checked. httpcore opens every TCP connection through a network backend's |
| 10 | +# `connect_tcp(host, port)`. `PinnedBackend` stands in front of the real |
| 11 | +# backend there: it resolves the host itself, hands every address to the |
| 12 | +# guard, and then connects to those addresses by IP literal, so nothing below |
| 13 | +# it resolves a name again. Nothing above it changes: httpcore still derives |
| 14 | +# the `Host` header, the TLS SNI name and the certificate's expected name from |
| 15 | +# the URL's host, not from what `connect_tcp` was given. |
| 16 | +# |
| 17 | +# Only the client's direct transport is pinned. A request that goes through a |
| 18 | +# proxy connects to the proxy, which may well be on loopback and which resolves |
| 19 | +# the destination on its side, so the proxy transports are left as httpx built |
| 20 | +# them and the request hook stays the (best-effort) check for that case. |
| 21 | +# |
| 22 | +# httpx has no public way to give its default transport a network backend |
| 23 | +# while it still reads the proxy environment variables (passing `transport=` |
| 24 | +# turns those off), so `pin_direct_connections` replaces the client's default |
| 25 | +# transport after construction, and fails loudly if httpx's internals are not |
| 26 | +# the shape it expects, rather than leave connections unpinned. |
| 27 | + |
| 28 | +import asyncio |
| 29 | +import socket |
| 30 | +from collections.abc import Awaitable, Callable, Iterable, Sequence |
| 31 | +from typing import Any, cast |
| 32 | + |
| 33 | +import httpcore |
| 34 | +import httpx |
| 35 | + |
| 36 | +# How long a connection attempt gets before the next address is tried |
| 37 | +# alongside it (RFC 8305's "Connection Attempt Delay"), so one unresponsive |
| 38 | +# address does not hold up a host that has a working one. The name-based |
| 39 | +# connect this replaces raced a host's addresses the same way. |
| 40 | +CONNECTION_ATTEMPT_DELAY = 0.25 |
| 41 | + |
| 42 | +# httpx's own defaults for its connection pool (`httpx.Limits()`), which the |
| 43 | +# pinned transport keeps. |
| 44 | +_MAX_CONNECTIONS = 100 |
| 45 | +_MAX_KEEPALIVE_CONNECTIONS = 20 |
| 46 | +_KEEPALIVE_EXPIRY = 5.0 |
| 47 | + |
| 48 | +Resolver = Callable[[str], Awaitable[Sequence[str]]] |
| 49 | +# Raises to refuse a host given every address it resolved to. |
| 50 | +Vetter = Callable[[str, Sequence[str]], None] |
| 51 | + |
| 52 | + |
| 53 | +class PinnedBackend(httpcore.AsyncNetworkBackend): |
| 54 | + """A network backend that connects only to addresses it resolved and vetted. |
| 55 | +
|
| 56 | + ``resolve`` turns a host into its addresses and ``vet`` raises when any of |
| 57 | + them is refused; ``inner`` (the anyio backend by default) then opens the |
| 58 | + socket to an address, never to the name. |
| 59 | + """ |
| 60 | + |
| 61 | + def __init__( |
| 62 | + self, |
| 63 | + resolve: Resolver, |
| 64 | + vet: Vetter, |
| 65 | + inner: httpcore.AsyncNetworkBackend | None = None, |
| 66 | + ) -> None: |
| 67 | + self._resolve = resolve |
| 68 | + self._vet = vet |
| 69 | + # The cast: httpcore also declares a placeholder `AnyIOBackend` for an |
| 70 | + # install without anyio, which is the declaration a type checker sees. |
| 71 | + # httpx requires anyio, so the real backend is what this builds. |
| 72 | + self._inner = ( |
| 73 | + cast(httpcore.AsyncNetworkBackend, httpcore.AnyIOBackend()) |
| 74 | + if inner is None |
| 75 | + else inner |
| 76 | + ) |
| 77 | + |
| 78 | + async def connect_tcp( |
| 79 | + self, |
| 80 | + host: str, |
| 81 | + port: int, |
| 82 | + timeout: float | None = None, |
| 83 | + local_address: str | None = None, |
| 84 | + socket_options: Iterable[Any] | None = None, |
| 85 | + ) -> httpcore.AsyncNetworkStream: |
| 86 | + try: |
| 87 | + resolved = await self._resolve(host) |
| 88 | + except socket.gaierror as e: |
| 89 | + # What the inner backend reports for a name it cannot resolve. |
| 90 | + raise httpcore.ConnectError(str(e)) from e |
| 91 | + # getaddrinfo lists an address once per socket type. |
| 92 | + addresses = list(dict.fromkeys(resolved)) |
| 93 | + self._vet(host, addresses) |
| 94 | + |
| 95 | + loop = asyncio.get_running_loop() |
| 96 | + started = loop.time() |
| 97 | + waiting = list(addresses) |
| 98 | + attempts: set[asyncio.Task[httpcore.AsyncNetworkStream]] = set() |
| 99 | + failures: list[Exception] = [] |
| 100 | + try: |
| 101 | + while waiting or attempts: |
| 102 | + if waiting: |
| 103 | + # Each attempt gets what is left of the one connect |
| 104 | + # timeout, so trying several addresses does not extend it. |
| 105 | + left = ( |
| 106 | + None if timeout is None else timeout - (loop.time() - started) |
| 107 | + ) |
| 108 | + attempts.add( |
| 109 | + loop.create_task( |
| 110 | + self._inner.connect_tcp( |
| 111 | + waiting.pop(0), |
| 112 | + port, |
| 113 | + timeout=left, |
| 114 | + local_address=local_address, |
| 115 | + socket_options=socket_options, |
| 116 | + ) |
| 117 | + ) |
| 118 | + ) |
| 119 | + # Wake on the first attempt to finish, or to start the next |
| 120 | + # address once this one has had its head start. |
| 121 | + done, attempts = await asyncio.wait( |
| 122 | + attempts, |
| 123 | + timeout=CONNECTION_ATTEMPT_DELAY if waiting else None, |
| 124 | + return_when=asyncio.FIRST_COMPLETED, |
| 125 | + ) |
| 126 | + winner: httpcore.AsyncNetworkStream | None = None |
| 127 | + for attempt in done: |
| 128 | + error = attempt.exception() |
| 129 | + if isinstance(error, Exception): |
| 130 | + failures.append(error) |
| 131 | + elif winner is None: |
| 132 | + winner = attempt.result() |
| 133 | + else: |
| 134 | + await attempt.result().aclose() |
| 135 | + if winner is not None: |
| 136 | + return winner |
| 137 | + # Every address failed: report the first, as a single connect would. |
| 138 | + if failures: |
| 139 | + raise failures[0] |
| 140 | + raise httpcore.ConnectError(f"{host} has no addresses") |
| 141 | + finally: |
| 142 | + # Attempts still running lost the race, or the caller gave up. |
| 143 | + for attempt in attempts: |
| 144 | + attempt.cancel() |
| 145 | + for outcome in await asyncio.gather(*attempts, return_exceptions=True): |
| 146 | + if isinstance(outcome, httpcore.AsyncNetworkStream): |
| 147 | + await outcome.aclose() |
| 148 | + |
| 149 | + async def connect_unix_socket( |
| 150 | + self, |
| 151 | + path: str, |
| 152 | + timeout: float | None = None, |
| 153 | + socket_options: Iterable[Any] | None = None, |
| 154 | + ) -> httpcore.AsyncNetworkStream: |
| 155 | + # A Unix socket has no name to resolve. The server never asks for one. |
| 156 | + return await self._inner.connect_unix_socket( |
| 157 | + path, timeout=timeout, socket_options=socket_options |
| 158 | + ) |
| 159 | + |
| 160 | + async def sleep(self, seconds: float) -> None: |
| 161 | + await self._inner.sleep(seconds) |
| 162 | + |
| 163 | + |
| 164 | +class PinnedTransport(httpx.AsyncHTTPTransport): |
| 165 | + """httpx's HTTP transport with its connections opened by ``backend``. |
| 166 | +
|
| 167 | + Everything else is httpx's default transport: certificate verification |
| 168 | + against the URL's host with the default trust store (``SSL_CERT_FILE`` and |
| 169 | + ``SSL_CERT_DIR`` honored), HTTP/1.1, and the default pool limits. |
| 170 | + """ |
| 171 | + |
| 172 | + def __init__(self, backend: httpcore.AsyncNetworkBackend) -> None: |
| 173 | + ssl_context = httpx.create_ssl_context() |
| 174 | + super().__init__(verify=ssl_context) |
| 175 | + # `AsyncHTTPTransport` takes no network backend, so its pool is |
| 176 | + # rebuilt with one; httpcore's pool takes it as a public argument. |
| 177 | + self._pool = httpcore.AsyncConnectionPool( |
| 178 | + ssl_context=ssl_context, |
| 179 | + max_connections=_MAX_CONNECTIONS, |
| 180 | + max_keepalive_connections=_MAX_KEEPALIVE_CONNECTIONS, |
| 181 | + keepalive_expiry=_KEEPALIVE_EXPIRY, |
| 182 | + network_backend=backend, |
| 183 | + ) |
| 184 | + |
| 185 | + |
| 186 | +def pin_direct_connections( |
| 187 | + client: httpx.AsyncClient, resolve: Resolver, vet: Vetter |
| 188 | +) -> None: |
| 189 | + """Make ``client``'s direct connections go only to vetted addresses. |
| 190 | +
|
| 191 | + Replaces the client's default transport, the one used for every request |
| 192 | + no proxy applies to, with a `PinnedTransport`. Proxy transports are left |
| 193 | + alone (see the top of this file). Raises ``TypeError`` when the client |
| 194 | + is not built the way this relies on, so a future httpx cannot silently |
| 195 | + drop the pinning. |
| 196 | + """ |
| 197 | + if not isinstance(getattr(client, "_transport", None), httpx.AsyncHTTPTransport): |
| 198 | + raise TypeError( |
| 199 | + "Cannot pin connections to the checked addresses: this version of " |
| 200 | + "httpx does not expose its default transport as expected" |
| 201 | + ) |
| 202 | + client._transport = PinnedTransport(PinnedBackend(resolve, vet)) |
0 commit comments