|
| 1 | +"""Which upstreams are allowed to receive the operator's *own* credentials. |
| 2 | +
|
| 3 | +``x-headroom-base-url`` lets a client pick the upstream for a single request, so |
| 4 | +OpenAI-compatible gateways (LiteLLM, Azure, self-hosted vLLM) route through the |
| 5 | +dedicated handlers instead of the generic passthrough. That is a deliberate |
| 6 | +feature and this module does not take it away. |
| 7 | +
|
| 8 | +What it takes away is the credential that used to ride along. ``*_extra_headers`` |
| 9 | +is operator-configured, marked ``secret=True`` in the settings store, and its own |
| 10 | +help text suggests an API key as the example value. It was merged into the |
| 11 | +upstream-bound header set *before* the destination was resolved, so a request |
| 12 | +carrying ``X-Headroom-Base-Url: https://attacker.example`` reached the attacker's |
| 13 | +host with the operator's gateway key attached — one request, no user interaction, |
| 14 | +from anything able to talk to the proxy port. |
| 15 | +
|
| 16 | +The rule here is the one ``copilot_auth.is_copilot_upstream_url`` already applies |
| 17 | +to Headroom's own Copilot token, generalized: **a secret only travels to a host |
| 18 | +the operator designated.** Designated means one of |
| 19 | +
|
| 20 | +* a host in the resolved provider API targets (``ANTHROPIC_TARGET_API_URL``, |
| 21 | + ``OPENAI_TARGET_API_URL``, and the Gemini/Vertex/Cloud Code equivalents), or |
| 22 | +* a host listed in ``HEADROOM_UPSTREAM_ALLOWED_HOSTS`` (comma-separated). |
| 23 | +
|
| 24 | +Anything else still gets proxied — the request is not blocked — it just does not |
| 25 | +get the operator's headers. |
| 26 | +
|
| 27 | +Matching is on the parsed hostname, never the URL string: comparing whole strings |
| 28 | +lets ``https://api.anthropic.com@evil.example`` and ``https://api.anthropic.com.evil.example`` |
| 29 | +through, and a base URL matches while base+path does not. Exact hostname equality |
| 30 | +only; no wildcards, because a suffix rule that forgets the label boundary is the |
| 31 | +usual way this class of check fails open. |
| 32 | +""" |
| 33 | + |
| 34 | +from __future__ import annotations |
| 35 | + |
| 36 | +import logging |
| 37 | +import os |
| 38 | +from typing import Any |
| 39 | +from urllib.parse import urlparse |
| 40 | + |
| 41 | +logger = logging.getLogger("headroom.proxy") |
| 42 | + |
| 43 | +ALLOWED_HOSTS_ENV = "HEADROOM_UPSTREAM_ALLOWED_HOSTS" |
| 44 | + |
| 45 | +#: Config attributes holding an operator-designated upstream. |
| 46 | +_API_URL_ATTRS = ( |
| 47 | + "anthropic_api_url", |
| 48 | + "openai_api_url", |
| 49 | + "gemini_api_url", |
| 50 | + "cloudcode_api_url", |
| 51 | + "vertex_api_url", |
| 52 | + "bedrock_api_url", |
| 53 | +) |
| 54 | + |
| 55 | +# Hosts that are always operator-designated: they are what the provider targets |
| 56 | +# resolve to when nothing is overridden, so omitting them would refuse the |
| 57 | +# headers on a completely default install. |
| 58 | +_DEFAULT_HOSTS = frozenset( |
| 59 | + { |
| 60 | + "api.anthropic.com", |
| 61 | + "api.openai.com", |
| 62 | + } |
| 63 | +) |
| 64 | + |
| 65 | +# Warn once per destination rather than once per request; a client looping on a |
| 66 | +# rejected host would otherwise flood the log. |
| 67 | +_warned_hosts: set[str] = set() |
| 68 | + |
| 69 | + |
| 70 | +def url_host(value: str | None) -> str | None: |
| 71 | + """Return the lowercase hostname for ``value``, tolerating a missing scheme. |
| 72 | +
|
| 73 | + ``urlparse("api.example.com/v1").hostname`` is ``None`` — the whole value is |
| 74 | + read as a path — so a scheme-less configured URL would otherwise contribute |
| 75 | + nothing to the trusted set and silently widen or narrow the check. |
| 76 | + """ |
| 77 | + |
| 78 | + if not value: |
| 79 | + return None |
| 80 | + candidate = value.strip() |
| 81 | + if not candidate: |
| 82 | + return None |
| 83 | + parsed = urlparse(candidate) |
| 84 | + if not parsed.hostname and "//" not in candidate: |
| 85 | + parsed = urlparse(f"//{candidate}") |
| 86 | + host = parsed.hostname |
| 87 | + return host.lower() if host else None |
| 88 | + |
| 89 | + |
| 90 | +def _env_allowed_hosts() -> set[str]: |
| 91 | + raw = os.environ.get(ALLOWED_HOSTS_ENV, "") |
| 92 | + hosts: set[str] = set() |
| 93 | + for entry in raw.split(","): |
| 94 | + # Accept a bare host or a full URL, so operators can paste either. |
| 95 | + host = url_host(entry) if entry.strip() else None |
| 96 | + if host: |
| 97 | + hosts.add(host) |
| 98 | + return hosts |
| 99 | + |
| 100 | + |
| 101 | +def trusted_upstream_hosts(config: Any = None) -> frozenset[str]: |
| 102 | + """Hosts permitted to receive operator-configured secret headers.""" |
| 103 | + |
| 104 | + hosts = set(_DEFAULT_HOSTS) |
| 105 | + for attr in _API_URL_ATTRS: |
| 106 | + host = url_host(getattr(config, attr, None)) |
| 107 | + if host: |
| 108 | + hosts.add(host) |
| 109 | + hosts |= _env_allowed_hosts() |
| 110 | + return frozenset(hosts) |
| 111 | + |
| 112 | + |
| 113 | +def is_trusted_upstream(url: str | None, config: Any = None) -> bool: |
| 114 | + """True when ``url`` is a destination the operator designated. |
| 115 | +
|
| 116 | + ``None``/empty means "no per-request override" — the handler is going to the |
| 117 | + configured target — so it is trusted. |
| 118 | + """ |
| 119 | + |
| 120 | + if not url: |
| 121 | + return True |
| 122 | + host = url_host(url) |
| 123 | + if not host: |
| 124 | + # Unparseable destination: refuse rather than guess. |
| 125 | + return False |
| 126 | + return host in trusted_upstream_hosts(config) |
| 127 | + |
| 128 | + |
| 129 | +def warn_untrusted_once(url: str | None, *, request_id: str | None = None) -> None: |
| 130 | + """Log the refusal once per host, with the remedy in the message.""" |
| 131 | + |
| 132 | + host = url_host(url) or "<unparseable>" |
| 133 | + if host in _warned_hosts: |
| 134 | + return |
| 135 | + _warned_hosts.add(host) |
| 136 | + prefix = f"[{request_id}] " if request_id else "" |
| 137 | + logger.warning( |
| 138 | + "%supstream_extra_headers_withheld host=%s reason=not_operator_designated. " |
| 139 | + "The configured extra headers are secret and were NOT sent to this host. " |
| 140 | + "If this upstream is legitimate, add it to %s (comma-separated hosts).", |
| 141 | + prefix, |
| 142 | + host, |
| 143 | + ALLOWED_HOSTS_ENV, |
| 144 | + ) |
| 145 | + |
| 146 | + |
| 147 | +def reset_warning_state() -> None: |
| 148 | + """Test hook: clear the once-per-host warning memo.""" |
| 149 | + |
| 150 | + _warned_hosts.clear() |
0 commit comments