mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): pin non-ASCII upstream hosts by A-label and resolve x-headroom-base-url once (#4855)
## Description
Two related fixes for client-chosen upstreams (`x-headroom-base-url`).
1. **Non-ASCII hosts.** The upstream guard resolved and pinned a host
under the spelling the client sent (e.g. `évil.test`), but httpx
IDNA-encodes the host and httpcore asks
`PinnedAddressBackend.connect_tcp` for the A-label (`xn--vil-9la.test`).
The pin lookup missed, the destination looked "never checked", and the
name was resolved a second time at connect. `socket.getaddrinfo` also
encodes Unicode names with IDNA 2003, which spells some names
differently from httpx's IDNA 2008 (`straße` → `strasse` vs
`xn--strae-oqa`), so the check could look up a different name from the
one dialled. The guard now converts the host to the A-label httpx will
use, resolves that name and pins under it; `guarded_pin` normalises the
same way, so either spelling finds the pin.
2. **One resolution per request.** `handle_openai_chat` resolved
`x-headroom-base-url` three times and `handle_openai_responses` twice.
Each resolution is a separate DNS lookup, so the destination and the
extra-header trust check could be decided from different answers, and
operator extra headers could be merged for a destination different from
the one validated. Both handlers now resolve once and pass that result
to a new `_openai_upstream_from(request, custom)`;
`_resolve_openai_upstream` keeps its behaviour by delegating to it.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- `headroom/proxy/upstream_guard.py`: `_connect_name()` (lower-case IDNA
A-label via `httpx.URL`, ASCII hosts unchanged); `is_safe_upstream_url`
resolves and pins that name and rejects a host that cannot be encoded;
`guarded_pin` looks up by the same key.
- `headroom/proxy/handlers/openai.py`: `_openai_upstream_from`; chat and
responses reuse the single `custom_upstream_base_url`; the second lookup
later in chat is removed.
- Tests:
`tests/test_upstream_guard.py::test_a_non_ascii_host_is_resolved_and_pinned_under_its_connect_name`,
`tests/test_grok_shared_proxy_call_sites.py::test_the_base_url_override_is_resolved_once_per_request[chat|responses]`.
**Sibling PRs that touch the same code** (merge order note): the
off-loop guard PR (`fix/upstream-guard-off-loop`) contains the identical
`_openai_upstream_from` / resolve-once hunks plus the async resolver, so
it should rebase cleanly on top of this one; the 400-on-rejection PR
(`fix/openai-base-url-reject`) edits `_resolve_openai_upstream_base`.
Suggested order: this PR, then off-loop, then reject.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
# New tests on origin/main (c21b0813)
E AssertionError: assert ['straße.example'] == ['xn--strae-oqa.example']
E AssertionError: the override was resolved 3 times (chat)
E AssertionError: the override was resolved 2 times (responses)
============================== 3 failed in 7.66s ===============================
# Same tests on this branch
tests/test_upstream_guard.py . [ 33%]
tests/test_grok_shared_proxy_call_sites.py .. [100%]
============================== 3 passed in 6.94s ===============================
# Area suites: test_upstream_guard, test_grok_shared_proxy_call_sites, test_proxy/test_openai_upstream_header,
# test_proxy_openai_cache_key_integration, test_upstream_credential_scoping, test_header_isolation,
# test_proxy_hardening, test_openai_codex_routing
================= 283 passed, 5 warnings in 122.32s (0:02:02) ==================
$ ruff check / ruff format --check (0.17.3) on changed files
All checks passed!
4 files already formatted
$ mypy headroom/proxy/upstream_guard.py headroom/proxy/handlers/openai.py --ignore-missing-imports
Success: no issues found in 2 source files
```
## Real Behavior Proof
- Environment: macOS, Python 3.12, `create_app` + `TestClient` with the
real guard, real `PinnedAddressBackend` and a real local HTTP server on
127.0.0.1; only `socket.getaddrinfo` is replaced, answering `8.8.8.8`
for the Unicode name and `127.0.0.1` for its A-label (a resolver that
answers differently per spelling).
- Exact command / steps: POST to a passthrough route with
`x-headroom-base-url: http://évil.test:<port>` (raw byte on the wire),
on origin/main and on this branch.
- Observed result:
```text
== origin/main
RESULT (200, '{"secret":"internal-only"}')
DNS ['évil.test', 'xn--vil-9la.test'] # checked one name, connected by
resolving another
HITS ['/internal/admin/canary?mode=mutate']
== this branch
RESULT (400, '{"detail":"Rejected unsafe upstream base URL"}')
DNS ['xn--vil-9la.test'] # one lookup, of the name that would be dialled
HITS []
```
- Not tested: live public IDN domains.
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: ASCII hosts unchanged. Non-ASCII
hosts are now resolved by their A-label (the name that is actually
dialled). A host httpx cannot IDNA-encode is rejected by the guard
(httpx could not connect to it anyway).
- Kill switch / disable path: none needed
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Additional Notes
Fix adapted from a proposal by HetCreep. The resolver now also looks up
the A-label itself (not just pins under it), which closes the IDNA
2003/2008 spelling difference.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4855"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
b9f6255395
commit
904e56a357
@@ -60,7 +60,11 @@ from headroom.proxy.tool_schema_savings_policy import (
|
||||
without_deferral_flags,
|
||||
)
|
||||
from headroom.proxy.turn_hooks import conversation_from, run_responses_create_hooks
|
||||
from headroom.proxy.upstream_guard import is_safe_upstream_url
|
||||
from headroom.proxy.upstream_guard import (
|
||||
guarded_pin,
|
||||
is_safe_upstream_url,
|
||||
is_safe_upstream_url_async,
|
||||
)
|
||||
from headroom.proxy.ws_headers import WS_HOP_BY_HOP_HEADERS
|
||||
from headroom.proxy.ws_session_registry import (
|
||||
TerminationCause,
|
||||
@@ -521,6 +525,12 @@ def _resolve_openai_upstream_base(request_headers: dict[str, str]) -> str | None
|
||||
return normalized
|
||||
|
||||
|
||||
def _upstream_pin_lapsed(url: str) -> bool:
|
||||
"""True when this request pinned ``url``'s host and that pin has expired."""
|
||||
pin = guarded_pin(urlparse(url).hostname or "")
|
||||
return pin is not None and pin.is_expired()
|
||||
|
||||
|
||||
def _resolve_openai_chat_handler_path(base_url: str, model: str | None) -> str:
|
||||
"""Return the upstream path suffix for an OpenAI chat-completions request."""
|
||||
|
||||
@@ -2355,7 +2365,16 @@ class OpenAIHandlerMixin:
|
||||
Otherwise falls back to the configured ``OPENAI_API_URL``
|
||||
(``OPENAI_TARGET_API_URL``).
|
||||
"""
|
||||
custom = _resolve_openai_upstream_base(request.headers)
|
||||
return self._openai_upstream_from(request, _resolve_openai_upstream_base(request.headers))
|
||||
|
||||
def _openai_upstream_from(self, request: Request, custom: str | None) -> str:
|
||||
"""Pick the upstream given this request's already-resolved override.
|
||||
|
||||
Handlers resolve ``x-headroom-base-url`` once and pass that one result
|
||||
here and to ``merge_extra_headers``. Resolving it again could get a
|
||||
different DNS answer, so the destination and the extra-header trust
|
||||
check would be judging different upstreams.
|
||||
"""
|
||||
if custom is not None:
|
||||
return custom
|
||||
if route_grok_to_xai(request.headers, self.OPENAI_API_URL):
|
||||
@@ -3617,7 +3636,7 @@ class OpenAIHandlerMixin:
|
||||
model = body.get("model", "unknown")
|
||||
messages = body.get("messages", [])
|
||||
custom_upstream_base_url = _resolve_openai_upstream_base(request.headers)
|
||||
upstream_base_url = self._resolve_openai_upstream(request)
|
||||
upstream_base_url = self._openai_upstream_from(request, custom_upstream_base_url)
|
||||
# Ghost text and next edits: CAPI does not serve these models. A
|
||||
# caller-chosen x-headroom-base-url is left alone, as in
|
||||
# select_passthrough_base_url.
|
||||
@@ -3825,6 +3844,7 @@ class OpenAIHandlerMixin:
|
||||
# tags is populated downstream at L1229 — defer apply_to_tags
|
||||
# to where the tags dict exists. The decision is captured here
|
||||
# so the conditional is uniform with the other gates.
|
||||
images_compressed = False
|
||||
if _image_decision.should_compress:
|
||||
from headroom.proxy.helpers import _get_image_compressor
|
||||
|
||||
@@ -3832,6 +3852,7 @@ class OpenAIHandlerMixin:
|
||||
try:
|
||||
compressor = _get_image_compressor()
|
||||
if compressor and compressor.has_images(messages):
|
||||
images_compressed = True
|
||||
messages, image_result = await run_image_compression_isolated(
|
||||
messages,
|
||||
provider="openai",
|
||||
@@ -3851,12 +3872,26 @@ class OpenAIHandlerMixin:
|
||||
finally:
|
||||
if compressor and hasattr(compressor, "close"):
|
||||
compressor.close()
|
||||
# The guard's pin for a client-chosen upstream lasts 60 s and image
|
||||
# compression can run longer. If the pin lapsed, check the same URL again
|
||||
# (off the event loop) so the connection has a current pin. The
|
||||
# destination is not chosen again: if the host no longer passes, the
|
||||
# request is refused.
|
||||
if (
|
||||
images_compressed
|
||||
and custom_upstream_base_url is not None
|
||||
and _upstream_pin_lapsed(custom_upstream_base_url)
|
||||
and not await is_safe_upstream_url_async(custom_upstream_base_url)
|
||||
):
|
||||
logger.warning(
|
||||
"[%s] rejecting x-headroom-base-url that no longer passes the guard", request_id
|
||||
)
|
||||
raise HTTPException(status_code=400, detail="Rejected unsafe upstream base URL")
|
||||
|
||||
# Surface the image-compression decision (computed earlier) into
|
||||
# tags now that the tags dict exists. Same observability pattern
|
||||
# the funnel uses for passthrough_reason + memory_skip_reason.
|
||||
_image_decision.apply_to_tags(tags)
|
||||
custom_upstream_base_url = _resolve_openai_upstream_base(request.headers)
|
||||
handler_path = _resolve_openai_chat_forward_path(request.headers, custom_upstream_base_url)
|
||||
_, custom_chat_provider = _custom_base_passthrough_telemetry(
|
||||
request.method,
|
||||
@@ -6375,7 +6410,7 @@ class OpenAIHandlerMixin:
|
||||
# below sends the request to chatgpt.com.
|
||||
custom_upstream_base_url = _resolve_openai_upstream_base(request.headers)
|
||||
upstream_base_url = custom_upstream_base_url
|
||||
openai_upstream_base_url = self._resolve_openai_upstream(request)
|
||||
openai_upstream_base_url = self._openai_upstream_from(request, custom_upstream_base_url)
|
||||
headers = merge_extra_headers(
|
||||
headers,
|
||||
self._openai_extra_headers_for_upstream(openai_upstream_base_url),
|
||||
|
||||
@@ -144,6 +144,26 @@ def begin_pin_scope() -> dict[str, UpstreamPin]:
|
||||
return scope
|
||||
|
||||
|
||||
def _connect_name(host: str) -> str | None:
|
||||
"""Return ``host`` as the connection will name it: lower-case IDNA A-label.
|
||||
|
||||
httpx IDNA-encodes a non-ASCII request host (IDNA 2008) and httpcore hands
|
||||
that A-label to ``connect_tcp``, so the check has to resolve and pin the
|
||||
same name. ``socket.getaddrinfo`` would encode a Unicode name itself, with
|
||||
IDNA 2003, which spells some names differently (``faß.de`` vs
|
||||
``xn--fa-hia.de``). ``None`` when the host cannot be encoded at all.
|
||||
"""
|
||||
key = (host or "").strip().lower()
|
||||
if key.isascii():
|
||||
return key
|
||||
import httpx # local: this module otherwise needs only the standard library
|
||||
|
||||
try:
|
||||
return httpx.URL(scheme="https", host=key).raw_host.decode("ascii").lower()
|
||||
except (httpx.InvalidURL, UnicodeError):
|
||||
return None
|
||||
|
||||
|
||||
def _record_validated_addresses(
|
||||
host: str,
|
||||
addresses: tuple[str, ...],
|
||||
@@ -181,7 +201,7 @@ def guarded_pin(host: str) -> UpstreamPin | None:
|
||||
scope = _PIN_SCOPE.get()
|
||||
if not scope:
|
||||
return None
|
||||
key = (host or "").strip().lower()
|
||||
key = _connect_name(host)
|
||||
if not key:
|
||||
return None
|
||||
return scope.get(key)
|
||||
@@ -340,9 +360,15 @@ def is_safe_upstream_url(url: str, *, scope: dict[str, UpstreamPin] | None = Non
|
||||
port = -1 # matches no origin; a listed bare host still passes, as before
|
||||
return destination_listed(allow, parsed.scheme, host, port)
|
||||
|
||||
# Resolve and pin the name the connection will dial, not the spelling the
|
||||
# client sent, or a non-ASCII host would be checked under one name and
|
||||
# connected under another.
|
||||
connect_host = _connect_name(host)
|
||||
if not connect_host:
|
||||
return False
|
||||
try:
|
||||
infos = _RESOLVER_POOL.submit(
|
||||
socket.getaddrinfo, host, None, 0, 0, socket.IPPROTO_TCP
|
||||
socket.getaddrinfo, connect_host, None, 0, 0, socket.IPPROTO_TCP
|
||||
).result(timeout=_resolve_timeout_seconds())
|
||||
except (OSError, _FutureTimeout):
|
||||
# Resolution and connection are separate operations, so allowing a DNS
|
||||
@@ -363,7 +389,7 @@ def is_safe_upstream_url(url: str, *, scope: dict[str, UpstreamPin] | None = Non
|
||||
# A destination that cannot be pinned is rejected rather than allowed
|
||||
# through unpinned: an unpinned client-supplied host is one the connection
|
||||
# would have to resolve for itself, which is the hole this closes.
|
||||
return _record_validated_addresses(host.lower(), addresses, scope)
|
||||
return _record_validated_addresses(connect_host, addresses, scope)
|
||||
|
||||
|
||||
async def is_safe_upstream_url_async(url: str) -> bool:
|
||||
|
||||
@@ -303,3 +303,150 @@ def test_configured_chat_backend_retains_its_operator_extras() -> None:
|
||||
assert headers["x-operator-sentinel"] == _SENTINEL_VALUE
|
||||
assert headers["authorization"] == _OPERATOR_KEY
|
||||
assert handler.captured_request is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("handle", ["handle_openai_chat", "handle_openai_responses"])
|
||||
def test_the_base_url_override_is_resolved_once_per_request(
|
||||
handle: str, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The destination and the extra-header trust check must come from one lookup.
|
||||
|
||||
The first lookup of the client's host answers with a private address and
|
||||
every later one with a public address. When the handler resolved the header
|
||||
more than once, the trust check saw "no override" while the destination was
|
||||
the client's host, so operator extras were sent there.
|
||||
"""
|
||||
import socket
|
||||
|
||||
from headroom.proxy import upstream_guard
|
||||
|
||||
monkeypatch.delenv("HEADROOM_ALLOWED_BASE_URLS", raising=False)
|
||||
calls: list[str] = []
|
||||
|
||||
def changing_answer(host: str, *args: object, **kwargs: object) -> list[object]:
|
||||
calls.append(host)
|
||||
address = "10.0.0.5" if len(calls) == 1 else "93.184.216.34"
|
||||
return [(None, None, None, None, (address, 443))]
|
||||
|
||||
monkeypatch.setattr(socket, "getaddrinfo", changing_answer)
|
||||
upstream_guard.clear_validated_addresses()
|
||||
|
||||
handler = _ChatHandler()
|
||||
handler.config.openai_extra_headers = dict(_SENTINEL_ONLY_EXTRAS)
|
||||
body: dict[str, Any] = {"model": "gpt-4o-mini"}
|
||||
if handle == "handle_openai_chat":
|
||||
body["messages"] = [{"role": "user", "content": "hello"}]
|
||||
else:
|
||||
body["input"] = "hello"
|
||||
request = _build_request(
|
||||
body,
|
||||
{**_OPENAI_CLIENT_HEADERS, "x-headroom-base-url": "https://changing.example/v1"},
|
||||
path="/v1/chat/completions" if handle == "handle_openai_chat" else "/v1/responses",
|
||||
)
|
||||
anyio.run(getattr(handler, handle), request)
|
||||
|
||||
assert calls == ["changing.example"], f"the override was resolved {len(calls)} times"
|
||||
if handler.captured_request is not None:
|
||||
outbound = _outbound(handler.captured_request)
|
||||
assert "changing.example" not in outbound.url, outbound.url
|
||||
|
||||
|
||||
def _run_image_chat(monkeypatch: pytest.MonkeyPatch, *, expire_pins: bool) -> dict[str, list[Any]]:
|
||||
"""Send an image chat request to a client-chosen gateway; record guard activity.
|
||||
|
||||
The stub image compression optionally ages every pin in the request's scope
|
||||
past its deadline, standing in for a compression that outlasts the pin.
|
||||
"""
|
||||
import asyncio
|
||||
import socket
|
||||
|
||||
from headroom.proxy import upstream_guard
|
||||
|
||||
monkeypatch.delenv("HEADROOM_ALLOWED_BASE_URLS", raising=False)
|
||||
seen: dict[str, list[Any]] = {"lookups": [], "guard_on_loop": [], "pin_at_send": []}
|
||||
|
||||
def _public(host: str, *a: object, **k: object) -> list[object]:
|
||||
seen["lookups"].append(host)
|
||||
return [(None, None, None, None, ("93.184.216.34", 443))]
|
||||
|
||||
real_guard = upstream_guard.is_safe_upstream_url
|
||||
|
||||
def _recording_guard(url: str, **kwargs: Any) -> bool:
|
||||
try:
|
||||
asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
seen["guard_on_loop"].append(False)
|
||||
else:
|
||||
seen["guard_on_loop"].append(True)
|
||||
return real_guard(url, **kwargs)
|
||||
|
||||
monkeypatch.setattr(socket, "getaddrinfo", _public)
|
||||
monkeypatch.setattr(upstream_guard, "is_safe_upstream_url", _recording_guard)
|
||||
upstream_guard.clear_validated_addresses()
|
||||
|
||||
class _Compressor:
|
||||
def has_images(self, messages: object) -> bool:
|
||||
return True
|
||||
|
||||
def close(self) -> None:
|
||||
return None
|
||||
|
||||
async def _compression(messages: Any, **kwargs: Any) -> tuple[Any, None]:
|
||||
if expire_pins:
|
||||
scope = upstream_guard._PIN_SCOPE.get() or {}
|
||||
for host, pin in list(scope.items()):
|
||||
scope[host] = upstream_guard.UpstreamPin(pin.addresses, 0.0)
|
||||
return messages, None
|
||||
|
||||
monkeypatch.setattr("headroom.proxy.helpers._get_image_compressor", lambda: _Compressor())
|
||||
monkeypatch.setattr(
|
||||
"headroom.proxy.handlers.openai.run_image_compression_isolated", _compression
|
||||
)
|
||||
|
||||
class _Handler(_ChatHandler):
|
||||
async def _retry_request(self, method: str, url: str, headers: dict, body: dict, **kwargs): # noqa: ANN201
|
||||
seen["pin_at_send"].append(upstream_guard.guarded_pin("gateway.example"))
|
||||
return await super()._retry_request(method, url, headers, body, **kwargs)
|
||||
|
||||
handler = _Handler()
|
||||
handler.config.image_optimize = True
|
||||
request = _build_request(
|
||||
{
|
||||
"model": "gpt-4o",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "what is this"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
|
||||
],
|
||||
}
|
||||
],
|
||||
},
|
||||
{**_OPENAI_CLIENT_HEADERS, "x-headroom-base-url": "https://gateway.example/v1"},
|
||||
path="/v1/chat/completions",
|
||||
)
|
||||
anyio.run(handler.handle_openai_chat, request)
|
||||
return seen
|
||||
|
||||
|
||||
def test_a_long_image_compression_does_not_leave_an_expired_pin(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A pin that lapsed during image compression is renewed off the event loop."""
|
||||
seen = _run_image_chat(monkeypatch, expire_pins=True)
|
||||
|
||||
assert seen["pin_at_send"], "the request was not sent"
|
||||
pin = seen["pin_at_send"][0]
|
||||
assert pin is not None and not pin.is_expired(), "the connection would find an expired pin"
|
||||
assert seen["guard_on_loop"][-1] is False, "the renewal ran on the event-loop thread"
|
||||
|
||||
|
||||
def test_a_still_valid_pin_is_not_checked_again_after_image_compression(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A second lookup is only needed once the pin lapsed; it could fail a valid request."""
|
||||
seen = _run_image_chat(monkeypatch, expire_pins=False)
|
||||
|
||||
assert seen["pin_at_send"], "the request was not sent"
|
||||
assert seen["lookups"] == ["gateway.example"], seen["lookups"]
|
||||
|
||||
@@ -1048,3 +1048,43 @@ async def test_a_proxied_client_still_pins_its_direct_transport(
|
||||
assert isinstance(proxied, GuardedUpstreamRefusingTransport)
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# A non-ASCII host is checked and pinned under the name httpcore connects with
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_a_non_ascii_host_is_resolved_and_pinned_under_its_connect_name(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""httpx IDNA-encodes the host, so httpcore asks ``connect_tcp`` for the A-label.
|
||||
|
||||
The check used to resolve and pin the Unicode spelling. The connection's
|
||||
lookup by A-label then found no pin, treated the host as never checked, and
|
||||
resolved it again. ``ß`` also shows the check must resolve the A-label
|
||||
itself: the resolver's own encoding would have looked up ``strasse.example``.
|
||||
"""
|
||||
from headroom.proxy import upstream_guard
|
||||
|
||||
looked_up: list[str] = []
|
||||
|
||||
def public_answer(host: str, *args: object, **kwargs: object) -> list[object]:
|
||||
looked_up.append(host)
|
||||
return [(None, None, None, None, ("8.8.8.8", 443))]
|
||||
|
||||
monkeypatch.setattr(socket, "getaddrinfo", public_answer)
|
||||
monkeypatch.delenv("HEADROOM_ALLOWED_BASE_URLS", raising=False)
|
||||
upstream_guard.clear_validated_addresses()
|
||||
url = "https://Straße.example/v1"
|
||||
assert is_safe_upstream_url(url) is True
|
||||
|
||||
connect_name = httpx.URL(url).raw_host.decode("ascii")
|
||||
assert connect_name == "xn--strae-oqa.example"
|
||||
assert looked_up == [connect_name]
|
||||
assert upstream_guard.guarded_pin(connect_name) is not None
|
||||
assert upstream_guard.guarded_pin("straße.example") is not None
|
||||
|
||||
inner, stream, error = await _connect(connect_name)
|
||||
assert error is None and stream is not None
|
||||
assert inner.targets == ["8.8.8.8"], f"the name was resolved again: {inner.targets}"
|
||||
|
||||
Reference in New Issue
Block a user