mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(proxy): refuse token-less non-loopback binds, gate operator routes (#3852)
## Why Four related gaps in the proxy's network gate (findings 01-F1, 01-F2, 01-F5, 01-F9): - **Open bind.** A non-loopback bind with no `HEADROOM_PROXY_TOKEN` only logged a warning, then served the `/v1/*` relay, with the operator's upstream credentials, to every peer that could reach the port. - **Missing peer address.** `is_loopback_host(None)` returned `True`. A Unix-domain socket, an ASGI adapter that leaves `scope["client"]` unset, or a hand-built request therefore turned off the token gate, the `/admin` and `/debug` guards and the WebSocket gate. - **Operator data routes.** `/stats-history` (including CSV export), `/quota`, `/subscription-window` and `/metrics` were served to any network caller. - **WebSocket loopback exemption** checked only the peer IP, not the `Host` header, so it had no DNS-rebinding defence. ## What changes - New `headroom/proxy/bind_policy.py`. A non-loopback bind (`0.0.0.0`, `::`, a LAN address or a hostname) with no token is refused at three places: `create_app` (embedders and the multi-worker factory), `run_server` (one exit with code 2 before uvicorn forks) and the `headroom proxy` CLI (a clear error before the banner, exit code 1). An absent host means uvicorn's default `127.0.0.1`. - `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1` acknowledges an open bind when the runtime already restricts reachability, such as a container published on `127.0.0.1`. The `proxy_open_bind` warning is still logged on that path, and the banner says the bind is open. - `is_loopback_host(None)` now returns `False` (fail closed), matching `identity.py`. - `/stats-history`, `/quota` and `/subscription-window` answer only: a non-loopback caller that passed the token gate, a loopback caller (peer and `Host` header both loopback), a trusted dashboard client, or, under an acknowledged token-less bind, the container's own default-gateway TCP peer with a loopback `Host` (the host browser reaching a `127.0.0.1`-published container). Everyone else gets 404, as with `/admin`. Settings writes keep their stricter rule with no token short-cut. - `/metrics` answers a non-loopback caller that passed the token gate, a loopback caller, a connecting peer in `HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS` (whatever it forwards), or a resolved client in the dashboard CIDRs. For CIDR peers a hostname `Host` is fine, so Prometheus scrapers work; a cross-origin browser request is still refused. - The token short-cut applies only to non-loopback requests. The gate exempts loopback peers without checking `Host`, so a loopback request has not proven it holds the token and must pass the loopback `Host` check. This blocks a DNS-rebound browser on the operator's machine. - The `/dashboard` shell stays ungated. It is a static template, like the already public `/dashboard/static` assets. Gating it would break the dashboard for containers published on host loopback, where the peer is the bridge gateway and `Host` is `localhost`. The data routes behind it are gated. - The WebSocket loopback exemption requires a loopback peer and a loopback `Host` header. A loopback peer with a foreign `Host` can still connect with the token. - Launchers that always publish on `127.0.0.1` set the acknowledgement themselves: `headroom install` (docker preset), `scripts/install.sh` and `scripts/install.ps1` (through one helper that adds the acknowledgement only together with the `127.0.0.1` publication), and `docker/docker-compose.native.yml`. - Docs: `proxy.mdx` documents the new variable and which routes the token also gates; `docker-install` (docs and wiki) and the `docker-compose.yml` comment show the acknowledgement in the loopback-published example. `e2e/docker-bind-security.sh` sets it and checks that the same launch without it refuses to start. ## Behaviour change (breaking) - `headroom proxy --host 0.0.0.0`, or `HEADROOM_HOST` set to any non-loopback address, without `HEADROOM_PROXY_TOKEN` now refuses to start. The error names both remedies. Set a token, bind loopback, or set `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1` when the port is already confined. Anyone running the image by hand with `--host 0.0.0.0` and no token must add one of these. - Without a token, `/stats-history`, `/quota`, `/subscription-window` and `/metrics` return 404 to non-loopback callers outside a trusted CIDR. Prometheus scrapers on another host must be in `HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS` or send the token. - Code that relied on a request with no peer address being treated as loopback now gets the non-loopback path. - The default loopback run is unchanged. ## Tests - `tests/test_proxy_bind_policy.py`: the refuse/allow matrix (non-loopback, loopback, unset host, token, acknowledgement values), the warning on the acknowledged path, `create_app`, the `run_server` exit before uvicorn, and the CLI (refusal, `HEADROOM_HOST` from env, acknowledged start, offline banner, start with a token). - `tests/test_proxy_loopback_gating.py`: each data route against non-loopback, loopback, trusted-CIDR and token callers; the dashboard shell stays reachable; the host of an acknowledged, loopback-published container reads the data routes while another bridge peer, a forwarded gateway address and a foreign `Host` do not; CSV export is not served to network callers; `/metrics` across loopback, both CIDR lists, out-of-range peers, cross-origin browsers and token callers, including a trusted gateway relaying a scraper outside its own range. A regression test shows that a token on the proxy does not exempt a loopback peer from the `Host` check; it fails without the fix. - `tests/test_proxy_hardening.py`: the HTTP gate with no peer address, WebSocket `Host` cases, `require_loopback` and `/debug` with no peer. - Installer tests: `headroom install` adds the acknowledgement, and the shell and PowerShell wrappers add it only together with the loopback publication. Launcher-level tests start the proxy with the environment and `--host` that `build_runtime_command()` and `docker-compose.native.yml` produce and check that the host browser (bridge-gateway peer) gets `/stats-history` and another container does not. - Tests that bound `0.0.0.0` for unrelated reasons now set a token or the acknowledgement. Tests that read operator routes use an explicit loopback peer. On `main`, 14 of the gating and hardening tests fail and the bind-policy module does not exist. Manual runs: token-less `--host 0.0.0.0` exits with the refusal from both the CLI and `run_server`; with the acknowledgement, the data routes are 404 to a LAN peer and to a loopback peer with a foreign `Host`; with a token, a LAN peer gets 401 without it and 200 with it; the default loopback bind starts as before. Not tested: a real Unix-domain-socket deployment and a real Prometheus scrape (both covered by tests only). ## Merge order Part of a set. Suggested order: #3852 → #3891 → #3849 → #3860 → #3862 → #3863. This PR goes first: it is the gate the others assume, and it is the release-note event. ## Not in this PR - Enforcing the token for loopback callers when one is configured. Revised 2026-10-02 after review: `/metrics` matches gateway CIDRs against the TCP peer, and the operator data routes serve the host of a loopback-published container (bridge-gateway peer under the launchers' bind acknowledgement) so the default Docker dashboard works. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3852" 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 Fable 5.1 <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
JD Davis
parent
6fb7cadfe4
commit
ee731d7ea8
+3
-1
@@ -10,7 +10,9 @@
|
||||
# 3. point your LLM client at http://localhost:8787 (proxy)
|
||||
#
|
||||
# Just want the proxy without the memory features? You can run the proxy image
|
||||
# on its own (`docker run --rm -p 127.0.0.1:8787:8787 ghcr.io/headroomlabs-ai/headroom --host 0.0.0.0 --port 8787`); the two
|
||||
# on its own (`docker run --rm -p 127.0.0.1:8787:8787 -e HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1
|
||||
# ghcr.io/headroomlabs-ai/headroom --host 0.0.0.0 --port 8787`; the env var acknowledges that the
|
||||
# 127.0.0.1 publication, not a token, is what keeps the port private); the two
|
||||
# database services below are only required for the memory/relevance features.
|
||||
#
|
||||
# Ports published on the host — all bound to 127.0.0.1 (this machine only):
|
||||
|
||||
@@ -30,6 +30,11 @@ services:
|
||||
HOME: /tmp/headroom-home
|
||||
HEADROOM_HOST: 0.0.0.0
|
||||
HEADROOM_PROXY_TOKEN: ${HEADROOM_PROXY_TOKEN:-}
|
||||
# The container binds 0.0.0.0 so the loopback publication below can reach
|
||||
# it; the proxy refuses that bind without a token unless the operator
|
||||
# acknowledges it. This file always publishes on 127.0.0.1, so it does.
|
||||
# Irrelevant (and harmless) once HEADROOM_PROXY_TOKEN is set.
|
||||
HEADROOM_ALLOW_UNAUTHENTICATED_BIND: "1"
|
||||
# Canonical Headroom filesystem contract (issue #175). See `cli` service
|
||||
# above for rationale.
|
||||
HEADROOM_WORKSPACE_DIR: /tmp/headroom-home/.headroom
|
||||
|
||||
@@ -62,17 +62,24 @@ headroom memory list
|
||||
For `proxy`, the maintained wrapper always publishes the selected host port on
|
||||
loopback. It passes `--host 0.0.0.0` inside the container so that the loopback
|
||||
publication can reach the container, and it has no public-publication override.
|
||||
For local-only use, no token is required:
|
||||
For local-only use no token is needed, but the proxy refuses to start on a
|
||||
non-loopback bind without one unless you acknowledge that the runtime already
|
||||
restricts who can reach the port (here: the `127.0.0.1` publication):
|
||||
|
||||
```bash
|
||||
docker run --rm -it \
|
||||
-p 127.0.0.1:8787:8787 \
|
||||
-e HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1 \
|
||||
-v "$PWD:/workspace" \
|
||||
-w /workspace \
|
||||
ghcr.io/headroomlabs-ai/headroom:latest \
|
||||
--host 0.0.0.0 --port 8787
|
||||
```
|
||||
|
||||
The maintained wrappers (`headroom install`, the `install.sh` / `install.ps1`
|
||||
native wrappers, and `docker/docker-compose.native.yml`) set that acknowledgement
|
||||
themselves, and only together with the `127.0.0.1` publication it depends on.
|
||||
|
||||
For deliberate public access, publish on an explicit public address and set
|
||||
`HEADROOM_PROXY_TOKEN`:
|
||||
|
||||
|
||||
@@ -338,7 +338,8 @@ with a privileged job.
|
||||
|
||||
| Flag / env | Default | Effect |
|
||||
|---|---|---|
|
||||
| `HEADROOM_PROXY_TOKEN` | none | Require a token from non-loopback callers, as `X-Headroom-Proxy-Token: <token>` or `Authorization: Bearer <token>`. The token is removed from the request before it is forwarded upstream; clients that also send a provider credential should use `X-Headroom-Proxy-Token` and keep `Authorization` for the provider. |
|
||||
| `HEADROOM_PROXY_TOKEN` | none | Require a token from non-loopback callers, as `X-Headroom-Proxy-Token: <token>` or `Authorization: Bearer <token>`. The token is removed from the request before it is forwarded upstream; clients that also send a provider credential should use `X-Headroom-Proxy-Token` and keep `Authorization` for the provider. Also gates the read-only operator routes (`/stats-history`, `/quota`, `/subscription-window`, `/metrics`), which otherwise answer loopback and trusted-CIDR callers only. |
|
||||
| `HEADROOM_ALLOW_UNAUTHENTICATED_BIND` | `false` | Acknowledge a non-loopback bind (`--host 0.0.0.0`, `::`, a LAN address) with **no** `HEADROOM_PROXY_TOKEN`. Without a token or this flag the proxy refuses to start, because `/v1/*` would relay upstream with the operator's credentials for every peer that can reach the port. Only set it when the runtime already restricts reachability (a container published on `127.0.0.1`). |
|
||||
| `HEADROOM_COMPRESS_ALLOW_REMOTE` | `false` | Allow non-loopback callers to reach [`POST /v1/compress`](#post-v1compress) and `POST /v1/usage`. Required to run Headroom as a remote gateway/sidecar; without it remote callers get `404`. |
|
||||
| `--offline` / `HEADROOM_OFFLINE` | `false` | Air-gap mode: hard-disable **all** egress (telemetry, update checks, license reporting, model downloads). |
|
||||
| `HEADROOM_LICENSE` | unset | Licence token, read by core and every licensed extension. `HEADROOM_LICENSE_KEY` is a deprecated alias for one release and logs a warning. A licence on its own sends nothing to Headroom. |
|
||||
|
||||
@@ -116,9 +116,18 @@ docker run -d --rm --name "$base_container" --network "$network" -p "0.0.0.0:187
|
||||
-e "OPENAI_TARGET_API_URL=http://${mock_container}:8080" -e OPENAI_API_KEY=upstream-secret \
|
||||
"$base_image" >/dev/null
|
||||
docker run -d --rm --name "$head_container" --network "$network" -p "0.0.0.0:18784:8787" "$head_image" >/dev/null
|
||||
# Loopback-published container that binds 0.0.0.0 inside: the proxy cannot see
|
||||
# the host publication, so the operator acknowledges the token-less open bind.
|
||||
docker run -d --rm --name "$local_container" --network "$network" -p "127.0.0.1:18786:8787" \
|
||||
-e HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1 \
|
||||
-e "OPENAI_TARGET_API_URL=http://${mock_container}:8080" -e OPENAI_API_KEY=upstream-secret \
|
||||
"$head_image" --host 0.0.0.0 --port 8787 >/dev/null
|
||||
# Without the acknowledgement or a token, the same launch must refuse to start
|
||||
# and name both ways out.
|
||||
refused_output="$(docker run --rm --network "$network" "$head_image" --host 0.0.0.0 --port 8787 2>&1)" \
|
||||
&& { echo "token-less 0.0.0.0 bind started without acknowledgement" >&2; exit 1; }
|
||||
grep -Fq HEADROOM_PROXY_TOKEN <<<"$refused_output"
|
||||
grep -Fq HEADROOM_ALLOW_UNAUTHENTICATED_BIND <<<"$refused_output"
|
||||
docker image inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$slim_image" \
|
||||
| grep -Fxq 'HEADROOM_HOST=127.0.0.1'
|
||||
docker run --rm --entrypoint python3 "$slim_image" -c 'import headroom._core; print("rust_core=loaded")'
|
||||
@@ -182,4 +191,4 @@ ws_key="$(printf '%s' 'the sample nonce' | base64 | tr -d '\n')"
|
||||
ws_status="$(docker run --rm --name "$attacker_container" --network "$network" curlimages/curl:8.12.1 --silent --output /dev/null --write-out '%{http_code}' --http1.1 -H 'Connection: Upgrade' -H 'Upgrade: websocket' -H 'Sec-WebSocket-Version: 13' -H "Sec-WebSocket-Key: ${ws_key}" "http://${host_ip}:18785/v1/live")"
|
||||
test "$ws_status" = "$ws_status_expected"
|
||||
printf 'base_ref=%s base_digest=%s head_digest=%s slim_digest=%s runtime_slim_config=loopback rust_core=loaded local_completion=200 attacker_loopback=000 ws_status=%s\n' "$base_ref" "$(docker image inspect --format='{{.Id}}' "$base_image")" "$(docker image inspect --format='{{.Id}}' "$head_image")" "$(docker image inspect --format='{{.Id}}' "$slim_image")" "$ws_status"
|
||||
echo "docker bind security: fixture forwarding, loopback isolation, built-image health, slim-image loopback config, and token controls passed"
|
||||
echo "docker bind security: fixture forwarding, loopback isolation, open-bind refusal, built-image health, slim-image loopback config, and token controls passed"
|
||||
|
||||
+20
-8
@@ -1640,21 +1640,33 @@ Memory (Multi-Provider):
|
||||
f"(available: {','.join(_ext_available)})"
|
||||
)
|
||||
|
||||
# Security posture line: inbound auth token + air-gap mode, and a loud
|
||||
# flag for the open-bind case (non-loopback host with no token).
|
||||
from headroom.proxy.loopback_guard import is_loopback_host
|
||||
# Security posture line: inbound auth token + air-gap mode. An open bind
|
||||
# (non-loopback host, no token) is refused here, before the banner, unless
|
||||
# the operator acknowledged it explicitly; see headroom/proxy/bind_policy.py.
|
||||
from headroom.proxy.bind_policy import OPEN_BIND_ACK_ENV, evaluate_bind_policy
|
||||
|
||||
_auth_on = bool(config.proxy_token or os.environ.get("HEADROOM_PROXY_TOKEN"))
|
||||
_bind = evaluate_bind_policy(config.host, config.proxy_token)
|
||||
if _bind.refused:
|
||||
raise click.ClickException(_bind.message())
|
||||
_auth_on = _bind.token_configured
|
||||
_open_bind_note = (
|
||||
f" · WARNING open bind, /v1/* UNAUTHENTICATED (acknowledged via {OPEN_BIND_ACK_ENV}=1)"
|
||||
if _bind.open_bind
|
||||
else ""
|
||||
)
|
||||
if config.offline:
|
||||
_security_status = "OFFLINE (all egress disabled)" + (
|
||||
" · inbound token REQUIRED (non-loopback)" if _auth_on else ""
|
||||
# Offline masks nothing: an acknowledged open bind is still an open bind.
|
||||
_security_status = (
|
||||
"OFFLINE (all egress disabled)"
|
||||
+ (" · inbound token REQUIRED (non-loopback)" if _auth_on else "")
|
||||
+ _open_bind_note
|
||||
)
|
||||
elif _auth_on:
|
||||
_security_status = "inbound token REQUIRED for non-loopback callers"
|
||||
elif not is_loopback_host(config.host):
|
||||
elif _bind.open_bind:
|
||||
_security_status = (
|
||||
"WARNING non-loopback bind with NO token — /v1/* is UNAUTHENTICATED "
|
||||
"(set HEADROOM_PROXY_TOKEN)"
|
||||
f"(acknowledged via {OPEN_BIND_ACK_ENV}=1; set HEADROOM_PROXY_TOKEN instead)"
|
||||
)
|
||||
else:
|
||||
_security_status = "loopback-only (no inbound token)"
|
||||
|
||||
@@ -15,13 +15,18 @@ from typing import Any, cast
|
||||
|
||||
from headroom._subprocess import pid_alive, run
|
||||
|
||||
from ..proxy.bind_policy import OPEN_BIND_ACK_ENV
|
||||
from .health import probe_ready
|
||||
from .models import DeploymentManifest, InstallPreset, RuntimeKind, SupervisorKind
|
||||
from .paths import log_path, pid_path, profile_root
|
||||
from .state import load_manifest
|
||||
|
||||
# Inside the container the proxy must listen on every interface so the
|
||||
# host-side published port (127.0.0.1:<port>) can reach it.
|
||||
# host-side published port (127.0.0.1:<port>) can reach it. The proxy refuses
|
||||
# a non-loopback bind with no HEADROOM_PROXY_TOKEN unless it is acknowledged;
|
||||
# this launcher always publishes on 127.0.0.1, so it acknowledges (see
|
||||
# build_runtime_command). A token in the host env still flows through the
|
||||
# HEADROOM_ passthrough and takes precedence over the acknowledgement.
|
||||
CONTAINER_BIND_HOST = "0.0.0.0" # noqa: S104 — container-internal bind, published only on 127.0.0.1
|
||||
# proxy_args always starts with the host flag/value pair (see planner.py); we
|
||||
# drop it and substitute CONTAINER_BIND_HOST for the in-container bind.
|
||||
@@ -136,6 +141,10 @@ def build_runtime_command(manifest: DeploymentManifest) -> list[str]:
|
||||
manifest.container_name,
|
||||
"-p",
|
||||
f"127.0.0.1:{manifest.port}:{manifest.port}",
|
||||
# Loopback-only publication is what makes the in-container 0.0.0.0
|
||||
# bind acceptable without a token; say so explicitly to the proxy.
|
||||
"--env",
|
||||
f"{OPEN_BIND_ACK_ENV}=1",
|
||||
"--workdir",
|
||||
container_home,
|
||||
"--env",
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Startup policy for the listener bind: no unauthenticated non-loopback bind.
|
||||
|
||||
The proxy's inbound trust model has two legs. Loopback callers are trusted
|
||||
(same boundary as the ``/admin`` and ``/debug`` routes); everyone else must
|
||||
present ``HEADROOM_PROXY_TOKEN``. That model has a hole when the token is not
|
||||
configured *and* the listener is bound to a non-loopback interface: every
|
||||
``/v1/*`` data-plane route -- which relays to the upstream provider with the
|
||||
operator's own credentials where ``*_extra_headers`` or a subscription token
|
||||
is configured -- answers any peer that can reach the port.
|
||||
|
||||
Until 0.40 the proxy only logged a warning for that shape. A warning is not a
|
||||
control: launchers that set ``HEADROOM_HOST=0.0.0.0`` (systemd units, the
|
||||
enterprise bundle's own start script, any ``docker run -p 8787:8787``) start
|
||||
successfully and serve an unauthenticated relay. This module makes the
|
||||
decision explicit and refuses to start unless the operator either configures
|
||||
a token or *acknowledges* the open bind with
|
||||
:data:`OPEN_BIND_ACK_ENV` -- the documented shape for a container that binds
|
||||
``0.0.0.0`` internally but is published on ``127.0.0.1`` by the runtime, which
|
||||
the process itself cannot observe.
|
||||
|
||||
The policy is evaluated in one place (:func:`evaluate_bind_policy`) and
|
||||
enforced from three: :func:`headroom.proxy.server.create_app` (covers every
|
||||
programmatic embedding and the multi-worker factory), :func:`run_server`
|
||||
(before uvicorn forks workers, so a refusal is one clean error and not a
|
||||
crash loop) and the ``headroom proxy`` CLI (before the banner, so the
|
||||
operator sees the reason and not a traceback).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
|
||||
from headroom.exceptions import ConfigurationError
|
||||
from headroom.proxy.loopback_guard import is_loopback_host
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_BIND_HOST",
|
||||
"OPEN_BIND_ACK_ENV",
|
||||
"PROXY_TOKEN_ENV",
|
||||
"BindPolicyDecision",
|
||||
"OpenBindRefused",
|
||||
"enforce_bind_policy",
|
||||
"evaluate_bind_policy",
|
||||
]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Explicit operator acknowledgement that an unauthenticated non-loopback bind
|
||||
#: is intended (for example a container published on a loopback port by the
|
||||
#: runtime). Any of ``1``, ``true``, ``yes``, ``on`` (case-insensitive) enables it.
|
||||
OPEN_BIND_ACK_ENV = "HEADROOM_ALLOW_UNAUTHENTICATED_BIND"
|
||||
|
||||
#: The inbound credential the policy is looking for. Named here so the error
|
||||
#: text and the gate cannot drift on the variable name.
|
||||
PROXY_TOKEN_ENV = "HEADROOM_PROXY_TOKEN"
|
||||
|
||||
#: uvicorn's default when no host is configured at all.
|
||||
DEFAULT_BIND_HOST = "127.0.0.1"
|
||||
|
||||
_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
|
||||
|
||||
|
||||
class OpenBindRefused(ConfigurationError):
|
||||
"""The proxy was asked to bind a non-loopback interface with no inbound token.
|
||||
|
||||
Raised by :func:`enforce_bind_policy`. Callers that own a process (the CLI,
|
||||
:func:`run_server`) turn it into a clean non-zero exit; embedders see a
|
||||
:class:`~headroom.exceptions.ConfigurationError` they can handle.
|
||||
"""
|
||||
|
||||
def __init__(self, decision: BindPolicyDecision) -> None:
|
||||
self.decision = decision
|
||||
super().__init__(decision.message())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BindPolicyDecision:
|
||||
"""Outcome of evaluating the listener bind against the inbound auth config."""
|
||||
|
||||
host: str
|
||||
token_configured: bool
|
||||
loopback: bool
|
||||
acknowledged: bool
|
||||
|
||||
@property
|
||||
def open_bind(self) -> bool:
|
||||
"""True when non-loopback callers can reach ``/v1/*`` with no credential."""
|
||||
return not self.token_configured and not self.loopback
|
||||
|
||||
@property
|
||||
def refused(self) -> bool:
|
||||
"""True when the proxy must not start: open bind, no acknowledgement."""
|
||||
return self.open_bind and not self.acknowledged
|
||||
|
||||
def message(self) -> str:
|
||||
"""Operator-facing explanation. Names both remedies explicitly."""
|
||||
if not self.open_bind:
|
||||
return f"bind {self.host}: inbound auth OK"
|
||||
if self.acknowledged:
|
||||
return (
|
||||
f"bind {self.host}: non-loopback bind with NO {PROXY_TOKEN_ENV} — "
|
||||
f"/v1/* is UNAUTHENTICATED; acknowledged via {OPEN_BIND_ACK_ENV}=1"
|
||||
)
|
||||
return (
|
||||
f"Refusing to bind {self.host!r}: the proxy would serve its /v1/* data-plane "
|
||||
f"routes to every peer on the network without authentication, relaying "
|
||||
f"requests with the operator's upstream credentials. Either set "
|
||||
f"{PROXY_TOKEN_ENV} (e.g. `openssl rand -hex 32`) so non-loopback callers "
|
||||
f"must present a bearer token, bind a loopback address (--host 127.0.0.1), "
|
||||
f"or — only when the runtime already restricts who can reach the port, such "
|
||||
f"as a container published on 127.0.0.1 — set {OPEN_BIND_ACK_ENV}=1 to "
|
||||
f"acknowledge the open bind explicitly."
|
||||
)
|
||||
|
||||
|
||||
def _env_flag(environ: Mapping[str, str], name: str) -> bool:
|
||||
value = environ.get(name)
|
||||
if value is None:
|
||||
return False
|
||||
return value.strip().lower() in _TRUE_VALUES
|
||||
|
||||
|
||||
def evaluate_bind_policy(
|
||||
host: str | None,
|
||||
proxy_token: str | None,
|
||||
*,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
) -> BindPolicyDecision:
|
||||
"""Decide whether ``host`` may be bound with the given inbound token.
|
||||
|
||||
``host`` ``None``/empty means "not configured", which uvicorn resolves to
|
||||
:data:`DEFAULT_BIND_HOST`; it is resolved the same way here so an absent
|
||||
host is never mistaken for a non-loopback one. ``proxy_token`` ``None``
|
||||
falls back to :data:`PROXY_TOKEN_ENV`, matching the security gate.
|
||||
``environ`` is injectable for tests; production passes nothing.
|
||||
"""
|
||||
env = os.environ if environ is None else environ
|
||||
resolved_host = (host or "").strip() or DEFAULT_BIND_HOST
|
||||
token = (proxy_token or env.get(PROXY_TOKEN_ENV) or "").strip()
|
||||
return BindPolicyDecision(
|
||||
host=resolved_host,
|
||||
token_configured=bool(token),
|
||||
loopback=is_loopback_host(resolved_host),
|
||||
acknowledged=_env_flag(env, OPEN_BIND_ACK_ENV),
|
||||
)
|
||||
|
||||
|
||||
def enforce_bind_policy(
|
||||
host: str | None,
|
||||
proxy_token: str | None,
|
||||
*,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
) -> BindPolicyDecision:
|
||||
"""Evaluate the bind policy and refuse an unacknowledged open bind.
|
||||
|
||||
Raises :class:`OpenBindRefused` when the bind must not proceed. When the
|
||||
open bind is acknowledged, emits the ``proxy_open_bind`` warning (kept from
|
||||
the pre-0.40 behaviour so log-based monitoring keeps working) and returns.
|
||||
"""
|
||||
decision = evaluate_bind_policy(host, proxy_token, environ=environ)
|
||||
if decision.refused:
|
||||
logger.error("event=proxy_open_bind_refused host=%s", decision.host)
|
||||
raise OpenBindRefused(decision)
|
||||
if decision.open_bind:
|
||||
logger.warning(
|
||||
"event=proxy_open_bind host=%s — proxy is bound to a non-loopback "
|
||||
"interface with no %s set; the /v1/* data-plane routes are reachable "
|
||||
"WITHOUT authentication. This was acknowledged via %s=1; set %s to "
|
||||
"require a bearer token from non-loopback callers instead.",
|
||||
decision.host,
|
||||
PROXY_TOKEN_ENV,
|
||||
OPEN_BIND_ACK_ENV,
|
||||
PROXY_TOKEN_ENV,
|
||||
)
|
||||
return decision
|
||||
@@ -76,9 +76,15 @@ LOOPBACK_HOSTS: frozenset[str] = frozenset({"127.0.0.1", "::1", "localhost"})
|
||||
def is_loopback_host(host: str | None) -> bool:
|
||||
"""Return True if ``host`` represents a loopback interface.
|
||||
|
||||
``None`` is treated as loopback — this covers ``TestClient`` /
|
||||
UDS-style requests where FastAPI does not populate
|
||||
``request.client``.
|
||||
``None`` is **not** loopback. A missing peer address (a Unix-domain
|
||||
socket, an ASGI adapter that leaves ``scope["client"]`` unset, a
|
||||
hand-built request double) is no evidence that the caller is local, and
|
||||
every guard built on this helper -- the inbound token gate, the
|
||||
``/admin`` and ``/debug`` 404 guards, the WebSocket gate -- must fail
|
||||
closed on it rather than silently disable itself. ``identity.py`` has
|
||||
always treated it that way; this makes the rest of the proxy agree.
|
||||
Tests that need a local caller set an explicit loopback peer
|
||||
(``TestClient(app, client=("127.0.0.1", 12345))``).
|
||||
|
||||
``"localhost"`` is special-cased as a string since it is not a
|
||||
valid IP literal. The comparison is case-insensitive because
|
||||
@@ -89,7 +95,7 @@ def is_loopback_host(host: str | None) -> bool:
|
||||
default. Malformed input returns ``False``.
|
||||
"""
|
||||
if host is None:
|
||||
return True
|
||||
return False
|
||||
if host.lower() == "localhost":
|
||||
return True
|
||||
try:
|
||||
|
||||
+133
-25
@@ -148,7 +148,7 @@ from headroom.proxy.helpers import (
|
||||
retry_after_ms,
|
||||
)
|
||||
from headroom.proxy.loop_callback_failure_policy import is_known_websocket_callback_failure
|
||||
from headroom.proxy.loopback_guard import is_loopback_host
|
||||
from headroom.proxy.loopback_guard import is_loopback_host, is_loopback_host_header
|
||||
from headroom.proxy.malloc_trim import trim_periodically
|
||||
from headroom.proxy.memory_handler import MemoryConfig, MemoryHandler
|
||||
|
||||
@@ -2979,13 +2979,6 @@ class WebSocketAuthMiddleware:
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
client = scope.get("client")
|
||||
client_host = client[0] if client else None
|
||||
if is_loopback_host(client_host):
|
||||
scrub_proxy_token_headers(scope, self.token_bytes)
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
# Starlette's own Headers rather than a hand-built dict: on a repeated
|
||||
# header it returns the FIRST occurrence, which is what the HTTP gate
|
||||
# sees. Building a dict here instead took the LAST one, so the two
|
||||
@@ -2993,7 +2986,22 @@ class WebSocketAuthMiddleware:
|
||||
# drift the shared reader below exists to prevent.
|
||||
from starlette.datastructures import Headers
|
||||
|
||||
provided = read_proxy_token(Headers(scope=scope))
|
||||
headers = Headers(scope=scope)
|
||||
client = scope.get("client")
|
||||
client_host = client[0] if client else None
|
||||
# Loopback exemption needs both gates the HTTP admin guards apply: a
|
||||
# loopback peer *and* a loopback ``Host:`` header. The Host check is
|
||||
# the DNS-rebinding defence — a browser on this machine coerced into
|
||||
# opening a socket to 127.0.0.1 still sends ``Host: attacker.com``. A
|
||||
# missing peer address (UDS, adapters) is not loopback (fails closed).
|
||||
if is_loopback_host(client_host) and is_loopback_host_header(headers.get("host")):
|
||||
# Exempt from the token, not from the scrub: a loopback client that
|
||||
# sends the token anyway must not have it forwarded upstream.
|
||||
scrub_proxy_token_headers(scope, self.token_bytes)
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
provided = read_proxy_token(headers)
|
||||
if provided is not None and hmac.compare_digest(
|
||||
provided.encode("utf-8", "replace"), self.token_bytes
|
||||
):
|
||||
@@ -3983,17 +3991,15 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
# orchestrators can check a container that binds non-loopback.
|
||||
_AUTH_EXEMPT_PATHS = frozenset({"/health", "/healthz", "/livez", "/readyz"})
|
||||
|
||||
# Loud warning when a non-loopback bind has no token configured: that is the
|
||||
# exact shape (e.g. the Docker 0.0.0.0 image) that exposes unauthenticated
|
||||
# /v1/* routes to the surrounding network.
|
||||
if not _proxy_token and not is_loopback_host(getattr(config, "host", None)):
|
||||
logger.warning(
|
||||
"event=proxy_open_bind host=%s — proxy is bound to a non-loopback "
|
||||
"interface with no HEADROOM_PROXY_TOKEN set; the /v1/* data-plane "
|
||||
"routes are reachable WITHOUT authentication. Set HEADROOM_PROXY_TOKEN "
|
||||
"to require a bearer token from non-loopback callers.",
|
||||
getattr(config, "host", None),
|
||||
)
|
||||
# A non-loopback bind with no token is the exact shape (``--host 0.0.0.0``
|
||||
# from any launcher) that exposes the unauthenticated /v1/* relay to the
|
||||
# surrounding network. It used to be a warning; it is now refused unless
|
||||
# the operator acknowledges it explicitly (see bind_policy.py). Enforced
|
||||
# here, not only in run_server, so programmatic embeddings and the
|
||||
# multi-worker factory get the same guarantee.
|
||||
from headroom.proxy.bind_policy import enforce_bind_policy
|
||||
|
||||
_bind_decision = enforce_bind_policy(getattr(config, "host", None), _proxy_token)
|
||||
|
||||
def _apply_security_headers(response) -> None:
|
||||
# setdefault: never clobber a header an upstream/handler already set.
|
||||
@@ -4128,6 +4134,9 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
from headroom.proxy.debug_introspection import (
|
||||
collect_tasks as _collect_tasks,
|
||||
)
|
||||
from headroom.proxy.loopback_guard import (
|
||||
is_container_host_gateway,
|
||||
)
|
||||
from headroom.proxy.loopback_guard import (
|
||||
require_loopback as _require_loopback,
|
||||
)
|
||||
@@ -4148,6 +4157,86 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
if not _request_can_view_dashboard_metadata(request, trusted_dashboard_client_cidrs):
|
||||
raise HTTPException(status_code=404)
|
||||
|
||||
def _authenticated_at_gate(request: Request) -> bool:
|
||||
"""True when the security gate verified this request's proxy token.
|
||||
|
||||
The gate exempts loopback peers without checking the ``Host`` header,
|
||||
so only a *non-loopback* request that reached a handler while a token
|
||||
is configured has proven it holds the token. A loopback peer must
|
||||
still pass the loopback (peer + Host) check: the DNS-rebinding defence.
|
||||
"""
|
||||
client = getattr(request, "client", None)
|
||||
return bool(_proxy_token) and not is_loopback_host(getattr(client, "host", None))
|
||||
|
||||
def _is_host_of_loopback_published_container(request: Request) -> bool:
|
||||
"""True for the host's own dashboard reaching a loopback-published container.
|
||||
|
||||
Docker relays a ``127.0.0.1:<port>`` publication into the container from
|
||||
the bridge gateway, so the host browser's TCP peer is that gateway, not
|
||||
127.0.0.1. The shipped launchers acknowledge their token-less 0.0.0.0
|
||||
bind only together with that loopback publication, so under the
|
||||
acknowledgement the gateway peer can only be a process on the host.
|
||||
Matches the exact TCP peer (never a forwarded header, never another
|
||||
container on the bridge) and keeps the loopback Host check.
|
||||
"""
|
||||
if not (_bind_decision.open_bind and _bind_decision.acknowledged):
|
||||
return False
|
||||
client = getattr(request, "client", None)
|
||||
peer = getattr(client, "host", None) if client is not None else None
|
||||
return is_container_host_gateway(peer) and is_loopback_host_header(
|
||||
request.headers.get("host")
|
||||
)
|
||||
|
||||
def _require_operator_read_client(request: Request) -> None:
|
||||
"""Gate the read-only operator routes (history, quota, subscription window).
|
||||
|
||||
A token-authenticated operator on a public bind is entitled to them, as
|
||||
is the host of a loopback-published container. Everyone else falls back
|
||||
to the /settings* trust chain: loopback, or a trusted dashboard client
|
||||
behind a gateway. Settings *writes* deliberately do not get either
|
||||
short-cut.
|
||||
"""
|
||||
if _authenticated_at_gate(request) or _is_host_of_loopback_published_container(request):
|
||||
return
|
||||
_require_loopback_or_trusted_dashboard_client(request)
|
||||
|
||||
def _require_metrics_scrape_client(request: Request) -> None:
|
||||
"""Gate ``/metrics`` for scrapers without demanding a dashboard's browser shape.
|
||||
|
||||
``/metrics`` is a Prometheus target, so unlike the dashboard routes it
|
||||
cannot require an IP-literal ``Host`` header. Allowed callers:
|
||||
|
||||
* a non-loopback caller that authenticated at the security gate;
|
||||
* loopback (peer *and* Host header, the usual two gates);
|
||||
* a connecting peer inside ``HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS``
|
||||
(whatever it forwards), or a resolved client inside the
|
||||
dashboard-client CIDRs, provided any browser provenance it carries
|
||||
is same-origin (a scraper sends neither Origin nor Referer).
|
||||
|
||||
Everyone else gets the same 404 the other operator routes return.
|
||||
"""
|
||||
if _authenticated_at_gate(request):
|
||||
return
|
||||
if _request_is_loopback(request):
|
||||
return
|
||||
from headroom.proxy.forwarded_headers import (
|
||||
load_trusted_gateway_cidrs,
|
||||
peer_is_trusted_gateway,
|
||||
resolve_client_ip,
|
||||
)
|
||||
|
||||
# Gateway CIDRs describe the TCP peer itself, never a forwarded address;
|
||||
# only the dashboard-client CIDRs apply to the resolved client.
|
||||
client = getattr(request, "client", None)
|
||||
peer = getattr(client, "host", None) if client is not None else None
|
||||
if peer_is_trusted_gateway(peer, load_trusted_gateway_cidrs()) or peer_is_trusted_gateway(
|
||||
resolve_client_ip(request), trusted_dashboard_client_cidrs
|
||||
):
|
||||
host_header = request.headers.get("host")
|
||||
if host_header and _request_has_same_origin_or_no_provenance(request, host_header):
|
||||
return
|
||||
raise HTTPException(status_code=404)
|
||||
|
||||
def _require_same_origin_or_trusted_dashboard_client(request: Request) -> None:
|
||||
"""Same-origin CSRF guard for settings writes, trusted-dashboard aware.
|
||||
|
||||
@@ -4327,6 +4416,15 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
name="dashboard-static",
|
||||
)
|
||||
|
||||
# The read-only telemetry routes below carry operator data (model/project/
|
||||
# session labels, spend history, subscription utilisation, provider quota)
|
||||
# and were served to any network caller. They now answer token-authenticated
|
||||
# operators, loopback, or a trusted dashboard client behind a gateway; other
|
||||
# network callers get 404. The dashboard shell itself is a static template
|
||||
# (like its /dashboard/static assets) and stays reachable, so a container
|
||||
# published on host loopback, whose peer is the bridge gateway, still loads.
|
||||
_dashboard_gate = [Depends(_require_operator_read_client)]
|
||||
|
||||
@app.get("/dashboard", response_class=HTMLResponse)
|
||||
@app.get("/dashboard/", response_class=HTMLResponse, include_in_schema=False)
|
||||
async def dashboard():
|
||||
@@ -5292,7 +5390,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
_stats_snapshot["expires_at"] = 0.0
|
||||
return JSONResponse(status_code=200, content={"status": "reset"})
|
||||
|
||||
@app.get("/stats-history")
|
||||
@app.get("/stats-history", dependencies=_dashboard_gate)
|
||||
async def stats_history(
|
||||
format: Literal["json", "csv"] = "json",
|
||||
series: Literal["history", "hourly", "daily", "weekly", "monthly"] = "history",
|
||||
@@ -5369,7 +5467,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
|
||||
return {"transformations": transformations, "log_full_messages": log_full_messages}
|
||||
|
||||
@app.get("/subscription-window")
|
||||
@app.get("/subscription-window", dependencies=_dashboard_gate)
|
||||
async def subscription_window():
|
||||
"""Current Anthropic subscription window utilisation and Headroom contribution.
|
||||
|
||||
@@ -5394,14 +5492,14 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
await tracker.maybe_poll_on_demand()
|
||||
return JSONResponse(content=tracker.render_state())
|
||||
|
||||
@app.get("/quota")
|
||||
@app.get("/quota", dependencies=_dashboard_gate)
|
||||
async def quota():
|
||||
"""Unified quota/rate-limit stats for all registered providers (Anthropic, Codex, Copilot)."""
|
||||
return JSONResponse(content=get_quota_registry().get_all_stats())
|
||||
|
||||
@app.get("/metrics")
|
||||
@app.get("/metrics", dependencies=[Depends(_require_metrics_scrape_client)])
|
||||
async def metrics():
|
||||
"""Prometheus metrics endpoint."""
|
||||
"""Prometheus metrics endpoint (loopback, trusted CIDR, or token-authenticated)."""
|
||||
return PlainTextResponse(
|
||||
await proxy.metrics.export(),
|
||||
media_type="text/plain; version=0.0.4",
|
||||
@@ -6233,6 +6331,16 @@ def run_server(
|
||||
config.profile_seeded_env_keys = frozenset(
|
||||
set(config.profile_seeded_env_keys) | set(seeded_env_keys)
|
||||
)
|
||||
|
||||
# Refuse an unacknowledged open bind here, before uvicorn forks, so the
|
||||
# operator gets one error and an exit code instead of N workers crashing
|
||||
# in create_app. create_app enforces the same policy for embedders.
|
||||
from headroom.proxy.bind_policy import evaluate_bind_policy
|
||||
|
||||
_bind = evaluate_bind_policy(config.host, config.proxy_token)
|
||||
if _bind.refused:
|
||||
print(f"ERROR: {_bind.message()}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
if workers < 1:
|
||||
raise ValueError("workers must be >= 1")
|
||||
config.worker_processes = workers
|
||||
|
||||
+17
-3
@@ -159,6 +159,18 @@ function Get-PassthroughEnvArgs {
|
||||
return ,$args.ToArray()
|
||||
}
|
||||
|
||||
# Publish the proxy on host loopback only. The container itself must bind
|
||||
# 0.0.0.0 for Docker port forwarding to reach it, and the proxy refuses a
|
||||
# token-less non-loopback bind unless the operator states that the runtime
|
||||
# already confines the port. This is the only place that statement is made,
|
||||
# and it is always made together with the 127.0.0.1 publication it relies on.
|
||||
function Get-LoopbackPublishArgs {
|
||||
param([int]$Port)
|
||||
# Leading comma: return the array as one object so AddRange receives a
|
||||
# string[] rather than an unrolled object[] (same as Get-SharedDockerArgs).
|
||||
return ,[string[]]@('-p',"127.0.0.1`:$Port`:$Port",'--env','HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1')
|
||||
}
|
||||
|
||||
function Get-SharedDockerArgs {
|
||||
Ensure-HostDirs
|
||||
$args = New-Object System.Collections.Generic.List[string]
|
||||
@@ -253,7 +265,8 @@ function Start-ProxyContainer {
|
||||
|
||||
$containerName = "headroom-proxy-$Port-$PID"
|
||||
$dockerArgs = New-Object System.Collections.Generic.List[string]
|
||||
$dockerArgs.AddRange([string[]]@('run','-d','--rm','--name',$containerName,'-p',"127.0.0.1`:$Port`:$Port"))
|
||||
$dockerArgs.AddRange([string[]]@('run','-d','--rm','--name',$containerName))
|
||||
$dockerArgs.AddRange((Get-LoopbackPublishArgs -Port $Port))
|
||||
$dockerArgs.AddRange((Get-SharedDockerArgs))
|
||||
$dockerArgs.Add($HeadroomImage)
|
||||
$dockerArgs.Add('--host')
|
||||
@@ -548,7 +561,8 @@ function Start-PersistentDockerInstall {
|
||||
docker rm -f $containerName | Out-Null 2>$null
|
||||
|
||||
$dockerArgs = New-Object System.Collections.Generic.List[string]
|
||||
$dockerArgs.AddRange([string[]]@('run','-d','--restart','unless-stopped','--name',$containerName,'-p',"127.0.0.1`:$Port`:$Port"))
|
||||
$dockerArgs.AddRange([string[]]@('run','-d','--restart','unless-stopped','--name',$containerName))
|
||||
$dockerArgs.AddRange((Get-LoopbackPublishArgs -Port $Port))
|
||||
$dockerArgs.AddRange((Get-PersistentDockerArgs))
|
||||
Add-DashboardGatewayEnv -ArgsList $dockerArgs
|
||||
$dockerArgs.AddRange([string[]]@(
|
||||
@@ -1739,7 +1753,7 @@ switch ($args[0]) {
|
||||
$dockerArgs = New-Object System.Collections.Generic.List[string]
|
||||
$dockerArgs.AddRange([string[]]@('run','--rm'))
|
||||
Add-TtyArgs -ArgsList $dockerArgs
|
||||
$dockerArgs.AddRange([string[]]@('-p',"127.0.0.1`:$port`:$port"))
|
||||
$dockerArgs.AddRange((Get-LoopbackPublishArgs -Port $port))
|
||||
$dockerArgs.AddRange((Get-SharedDockerArgs))
|
||||
$dockerArgs.Add('--entrypoint')
|
||||
$dockerArgs.Add('headroom')
|
||||
|
||||
+17
-3
@@ -104,6 +104,18 @@ append_passthrough_envs() {
|
||||
done
|
||||
}
|
||||
|
||||
# Publish the proxy on host loopback only. The container itself must bind
|
||||
# 0.0.0.0 for Docker port forwarding to reach it, and the proxy refuses a
|
||||
# token-less non-loopback bind unless the operator states that the runtime
|
||||
# already confines the port. This helper is the only place that statement is
|
||||
# made, and it is made together with the 127.0.0.1 publication it relies on,
|
||||
# so the acknowledgement can never be added without the loopback restriction.
|
||||
append_loopback_publish_args() {
|
||||
local -n _target="$1"
|
||||
local port="$2"
|
||||
_target+=(-p "127.0.0.1:${port}:${port}" --env "HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1")
|
||||
}
|
||||
|
||||
append_common_container_args() {
|
||||
local -n ref=$1
|
||||
|
||||
@@ -186,7 +198,8 @@ start_proxy_container() {
|
||||
|
||||
local container_name="headroom-proxy-${port}-$$"
|
||||
local args=()
|
||||
args=(docker run -d --rm --name "${container_name}" -p "127.0.0.1:${port}:${port}")
|
||||
args=(docker run -d --rm --name "${container_name}")
|
||||
append_loopback_publish_args args "${port}"
|
||||
append_common_container_args args
|
||||
args+=("${HEADROOM_IMAGE}" --host 0.0.0.0 --port "${port}" "$@")
|
||||
"${args[@]}" >/dev/null
|
||||
@@ -491,7 +504,8 @@ start_persistent_docker_install() {
|
||||
|
||||
docker rm -f "${container_name}" >/dev/null 2>&1 || true
|
||||
|
||||
args=(docker run -d --restart unless-stopped --name "${container_name}" -p "127.0.0.1:${port}:${port}")
|
||||
args=(docker run -d --restart unless-stopped --name "${container_name}")
|
||||
append_loopback_publish_args args "${port}"
|
||||
append_persistent_container_args args
|
||||
append_dashboard_gateway_env args
|
||||
args+=(
|
||||
@@ -1571,7 +1585,7 @@ EOF
|
||||
run_args=(docker run --rm)
|
||||
append_tty_args run_args
|
||||
append_common_container_args run_args
|
||||
run_args+=(-p "127.0.0.1:${port}:${port}")
|
||||
append_loopback_publish_args run_args "${port}"
|
||||
run_args+=(--entrypoint headroom "${HEADROOM_IMAGE}" proxy --host 0.0.0.0 --port "${port}" "${args[@]:1}")
|
||||
"${run_args[@]}"
|
||||
;;
|
||||
|
||||
@@ -98,6 +98,10 @@ class HeadroomServer:
|
||||
|
||||
# The loopback guard on /v1/compress is decided when the app is built.
|
||||
os.environ["HEADROOM_COMPRESS_ALLOW_REMOTE"] = "1"
|
||||
# This harness deliberately binds 0.0.0.0 with no inbound token so the
|
||||
# Kong container can reach it; acknowledge the open bind explicitly
|
||||
# (create_app refuses it otherwise).
|
||||
os.environ["HEADROOM_ALLOW_UNAUTHENTICATED_BIND"] = "1"
|
||||
self.app = create_app(
|
||||
ProxyConfig(
|
||||
host="0.0.0.0",
|
||||
|
||||
@@ -248,7 +248,10 @@ class TestCLIProxyEnvVars:
|
||||
result = runner.invoke(
|
||||
main,
|
||||
["proxy"],
|
||||
env={"HEADROOM_HOST": "0.0.0.0"},
|
||||
# 0.0.0.0 with no token is refused at startup since the bind
|
||||
# policy landed (tests/test_proxy_bind_policy.py); this test is
|
||||
# about env→config plumbing, so authenticate the bind.
|
||||
env={"HEADROOM_HOST": "0.0.0.0", "HEADROOM_PROXY_TOKEN": "env-test-token"},
|
||||
catch_exceptions=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -77,6 +77,34 @@ def test_native_compose_keeps_host_publication_loopback_and_optional_token() ->
|
||||
assert proxy["command"] == ["--host", "0.0.0.0", "--port", "${HEADROOM_PORT:-8787}"]
|
||||
|
||||
|
||||
def test_native_compose_lets_the_host_dashboard_read_its_data(monkeypatch) -> None:
|
||||
"""The compose proxy must serve /stats-history to the host browser, which
|
||||
reaches the 127.0.0.1 publication as the compose network's gateway."""
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from headroom.proxy.server import ProxyConfig, create_app
|
||||
|
||||
compose = yaml.safe_load(
|
||||
(ROOT / "docker" / "docker-compose.native.yml").read_text(encoding="utf-8")
|
||||
)
|
||||
proxy = compose["services"]["proxy"]
|
||||
assert proxy["ports"][0].startswith("127.0.0.1:")
|
||||
|
||||
for name, value in proxy["environment"].items():
|
||||
if name != "HOME" and not name.endswith("_DIR"):
|
||||
# "${VAR:-default}" with VAR unset, as compose resolves it.
|
||||
value = value.split(":-", 1)[1].rstrip("}") if value.startswith("${") else value
|
||||
monkeypatch.setenv(name, value)
|
||||
monkeypatch.setenv("HEADROOM_CONTAINER_HOST_GATEWAY", "172.18.0.1")
|
||||
host = proxy["command"][proxy["command"].index("--host") + 1]
|
||||
app = create_app(ProxyConfig(host=host, optimize=False, cache_enabled=False))
|
||||
|
||||
browser = TestClient(app, base_url="http://127.0.0.1:8787", client=("172.18.0.1", 1))
|
||||
assert browser.get("/stats-history").status_code == 200
|
||||
other_container = TestClient(app, base_url="http://127.0.0.1:8787", client=("172.18.0.5", 1))
|
||||
assert other_container.get("/stats-history").status_code == 404
|
||||
|
||||
|
||||
def test_differential_capture_compose_keeps_proxy_internal_and_host_ports_loopback() -> None:
|
||||
compose = yaml.safe_load(
|
||||
(ROOT / "docker" / "differential-network-capture" / "docker-compose.yml").read_text(
|
||||
|
||||
@@ -417,6 +417,43 @@ def test_generated_wrappers_explicitly_override_image_host_for_container_access(
|
||||
assert "dockerArgs.Add('0.0.0.0')" in powershell_source
|
||||
|
||||
|
||||
def test_wrappers_acknowledge_open_bind_only_with_loopback_publication() -> None:
|
||||
"""Every container launch that binds 0.0.0.0 inside the container must
|
||||
publish on host loopback *and* acknowledge the token-less open bind, and
|
||||
the acknowledgement must never appear without that publication.
|
||||
|
||||
The proxy refuses a token-less non-loopback bind unless
|
||||
HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1 is set; the wrappers make that
|
||||
statement only through one helper that also adds ``-p 127.0.0.1:...``.
|
||||
"""
|
||||
ack = "HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1"
|
||||
bash_source = (REPO_ROOT / "scripts" / "install.sh").read_text(encoding="utf-8")
|
||||
powershell_source = (REPO_ROOT / "scripts" / "install.ps1").read_text(encoding="utf-8")
|
||||
|
||||
# Bash: the publish flag and the acknowledgement live only in the helper.
|
||||
helper = bash_source.split("append_loopback_publish_args() {", 1)[1].split("\n}\n", 1)[0]
|
||||
assert '-p "127.0.0.1:${port}:${port}"' in helper and ack in helper
|
||||
outside = bash_source.replace(helper, "")
|
||||
assert '-p "127.0.0.1:' not in outside
|
||||
assert outside.count(ack) == 0
|
||||
# Three launch sites, three helper calls.
|
||||
assert bash_source.count("--host 0.0.0.0") == 3
|
||||
assert bash_source.count("append_loopback_publish_args ") == 3
|
||||
|
||||
# PowerShell: same shape.
|
||||
ps_helper = powershell_source.split("function Get-LoopbackPublishArgs {", 1)[1].split(
|
||||
"\n}\n", 1
|
||||
)[0]
|
||||
assert "127.0.0.1`:$Port`:$Port" in ps_helper and ack in ps_helper
|
||||
# Without the unary comma PowerShell unrolls the array to object[], and
|
||||
# List[string].AddRange rejects it at runtime.
|
||||
assert "return ,[string[]]@(" in ps_helper
|
||||
ps_outside = powershell_source.replace(ps_helper, "")
|
||||
assert "'-p'," not in ps_outside.replace("Get-LoopbackPublishArgs", "")
|
||||
assert ps_outside.count(ack) == 0
|
||||
assert powershell_source.count("Get-LoopbackPublishArgs -Port") == 3
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
os.name == "nt" or shutil.which("bash") is None or not _bash_supports_4_3(),
|
||||
reason="installer requires bash >= 4.3 (macOS system bash is 3.2)",
|
||||
|
||||
@@ -100,12 +100,63 @@ def test_build_runtime_command_for_docker_includes_deployment_env(
|
||||
assert "HEADROOM_DEPLOYMENT_PRESET=persistent-docker" in joined
|
||||
assert "127.0.0.1:8787:8787" in joined
|
||||
assert "ghcr.io/headroomlabs-ai/headroom:latest" in command
|
||||
# The container binds 0.0.0.0 behind a loopback-only publication; the
|
||||
# proxy refuses that bind without a token unless acknowledged, and this
|
||||
# launcher is the canonical case for the acknowledgement.
|
||||
assert "--host 0.0.0.0" in joined
|
||||
assert "HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1" in command
|
||||
assert command[command.index("HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1") - 1] == "--env"
|
||||
# Canonical Headroom filesystem contract (issue #175) forwarded into
|
||||
# the container.
|
||||
assert "HEADROOM_WORKSPACE_DIR=/tmp/headroom-home/.headroom" in command
|
||||
assert "HEADROOM_CONFIG_DIR=/tmp/headroom-home/.headroom/config" in command
|
||||
|
||||
|
||||
def test_build_runtime_command_lets_the_host_dashboard_read_its_data(
|
||||
monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""The container this command starts must serve /stats-history to the host
|
||||
browser, which reaches the 127.0.0.1 publication as the bridge gateway."""
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from headroom.proxy.server import ProxyConfig, create_app
|
||||
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
manifest = DeploymentManifest(
|
||||
profile="default",
|
||||
preset="persistent-docker",
|
||||
runtime_kind="docker",
|
||||
supervisor_kind="none",
|
||||
scope="user",
|
||||
provider_mode="manual",
|
||||
targets=["claude"],
|
||||
port=8787,
|
||||
host="127.0.0.1",
|
||||
backend="anthropic",
|
||||
image="ghcr.io/headroomlabs-ai/headroom:latest",
|
||||
base_env={"HEADROOM_PORT": "8787"},
|
||||
proxy_args=["--host", "127.0.0.1", "--port", "8787"],
|
||||
)
|
||||
command = build_runtime_command(manifest)
|
||||
assert "127.0.0.1:8787:8787" in command
|
||||
|
||||
# Recreate the container's environment (minus its filesystem paths) and
|
||||
# the container's view of its bridge gateway.
|
||||
for index, arg in enumerate(command):
|
||||
if arg == "--env" and "=" in command[index + 1]:
|
||||
name, value = command[index + 1].split("=", 1)
|
||||
if name != "HOME" and not name.endswith("_DIR"):
|
||||
monkeypatch.setenv(name, value)
|
||||
monkeypatch.setenv("HEADROOM_CONTAINER_HOST_GATEWAY", "172.17.0.1")
|
||||
host = command[command.index(manifest.image) + 2]
|
||||
app = create_app(ProxyConfig(host=host, optimize=False, cache_enabled=False))
|
||||
|
||||
browser = TestClient(app, base_url="http://127.0.0.1:8787", client=("172.17.0.1", 1))
|
||||
assert browser.get("/stats-history").status_code == 200
|
||||
other_container = TestClient(app, base_url="http://127.0.0.1:8787", client=("172.17.0.5", 1))
|
||||
assert other_container.get("/stats-history").status_code == 404
|
||||
|
||||
|
||||
def test_build_runtime_command_preserves_non_ascii_ambient_token(
|
||||
monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
"""Bind policy: a non-loopback bind with no inbound token is refused, not warned about.
|
||||
|
||||
Before this change the proxy logged ``proxy_open_bind`` and started anyway,
|
||||
so any launcher that set ``--host 0.0.0.0`` / ``HEADROOM_HOST=0.0.0.0`` without
|
||||
``HEADROOM_PROXY_TOKEN`` served the ``/v1/*`` relay to every peer on the
|
||||
network. The policy is evaluated in :mod:`headroom.proxy.bind_policy` and
|
||||
enforced at three layers -- ``create_app``, ``run_server`` and the CLI -- each
|
||||
of which is covered here, plus the explicit operator acknowledgement
|
||||
(``HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1``) that keeps the documented
|
||||
"container binds 0.0.0.0, runtime publishes on 127.0.0.1" shape working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("fastapi")
|
||||
|
||||
from click.testing import CliRunner # noqa: E402
|
||||
|
||||
from headroom.cli.main import main # noqa: E402
|
||||
from headroom.exceptions import ConfigurationError # noqa: E402
|
||||
from headroom.proxy.bind_policy import ( # noqa: E402
|
||||
OPEN_BIND_ACK_ENV,
|
||||
PROXY_TOKEN_ENV,
|
||||
OpenBindRefused,
|
||||
enforce_bind_policy,
|
||||
evaluate_bind_policy,
|
||||
)
|
||||
from headroom.proxy.models import ProxyConfig # noqa: E402
|
||||
from headroom.proxy.server import create_app, run_server # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clean_bind_env(monkeypatch: pytest.MonkeyPatch):
|
||||
"""The policy reads the process env; never let the developer's shell leak in."""
|
||||
monkeypatch.delenv(PROXY_TOKEN_ENV, raising=False)
|
||||
monkeypatch.delenv(OPEN_BIND_ACK_ENV, raising=False)
|
||||
|
||||
|
||||
# ───────────────────────────── evaluate ────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", ["0.0.0.0", "::", "192.168.1.20", "myhost.internal", "[::]"])
|
||||
def test_non_loopback_bind_without_token_is_refused(host: str) -> None:
|
||||
decision = evaluate_bind_policy(host, None, environ={})
|
||||
assert decision.open_bind is True
|
||||
assert decision.refused is True
|
||||
# The message must name both remedies so the operator can act on it.
|
||||
assert PROXY_TOKEN_ENV in decision.message()
|
||||
assert OPEN_BIND_ACK_ENV in decision.message()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", ["127.0.0.1", "localhost", "::1", "127.5.5.5", "::ffff:127.0.0.1"])
|
||||
def test_loopback_bind_without_token_is_fine(host: str) -> None:
|
||||
decision = evaluate_bind_policy(host, None, environ={})
|
||||
assert decision.loopback is True
|
||||
assert decision.open_bind is False
|
||||
assert decision.refused is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", [None, "", " "])
|
||||
def test_unset_host_means_uvicorn_default_loopback(host: str | None) -> None:
|
||||
"""An absent host is uvicorn's 127.0.0.1, never 'unknown therefore public'."""
|
||||
decision = evaluate_bind_policy(host, None, environ={})
|
||||
assert decision.host == "127.0.0.1"
|
||||
assert decision.refused is False
|
||||
|
||||
|
||||
def test_token_makes_any_bind_acceptable() -> None:
|
||||
assert evaluate_bind_policy("0.0.0.0", "s3cr3t", environ={}).refused is False
|
||||
# Same rule the security gate uses: the env var is the fallback source.
|
||||
assert (
|
||||
evaluate_bind_policy("0.0.0.0", None, environ={PROXY_TOKEN_ENV: "s3cr3t"}).refused is False
|
||||
)
|
||||
# Whitespace-only is not a token.
|
||||
assert evaluate_bind_policy("0.0.0.0", " ", environ={}).refused is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["1", "true", "TRUE", "yes", "on", " On "])
|
||||
def test_acknowledgement_env_allows_the_open_bind(value: str) -> None:
|
||||
decision = evaluate_bind_policy("0.0.0.0", None, environ={OPEN_BIND_ACK_ENV: value})
|
||||
assert decision.open_bind is True
|
||||
assert decision.acknowledged is True
|
||||
assert decision.refused is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["0", "false", "no", "", "maybe"])
|
||||
def test_non_truthy_acknowledgement_still_refuses(value: str) -> None:
|
||||
assert evaluate_bind_policy("0.0.0.0", None, environ={OPEN_BIND_ACK_ENV: value}).refused
|
||||
|
||||
|
||||
# ───────────────────────────── enforce ─────────────────────────────────────
|
||||
|
||||
|
||||
def test_enforce_raises_a_configuration_error_subclass() -> None:
|
||||
with pytest.raises(OpenBindRefused) as exc_info:
|
||||
enforce_bind_policy("0.0.0.0", None, environ={})
|
||||
assert isinstance(exc_info.value, ConfigurationError)
|
||||
assert exc_info.value.decision.host == "0.0.0.0"
|
||||
|
||||
|
||||
def test_enforce_keeps_the_open_bind_warning_when_acknowledged() -> None:
|
||||
"""Log-based monitoring keyed on ``proxy_open_bind`` must keep working."""
|
||||
records: list[logging.LogRecord] = []
|
||||
handler = logging.Handler()
|
||||
handler.emit = records.append # type: ignore[method-assign]
|
||||
log = logging.getLogger("headroom.proxy.bind_policy")
|
||||
log.addHandler(handler)
|
||||
previous = log.level
|
||||
log.setLevel(logging.DEBUG)
|
||||
try:
|
||||
decision = enforce_bind_policy("0.0.0.0", None, environ={OPEN_BIND_ACK_ENV: "1"})
|
||||
finally:
|
||||
log.removeHandler(handler)
|
||||
log.setLevel(previous)
|
||||
assert decision.acknowledged is True
|
||||
messages = [r.getMessage() for r in records]
|
||||
assert any("event=proxy_open_bind " in m for m in messages), messages
|
||||
assert not any("proxy_open_bind_refused" in m for m in messages)
|
||||
|
||||
|
||||
# ───────────────────────────── create_app ──────────────────────────────────
|
||||
|
||||
|
||||
def _config(**overrides) -> ProxyConfig:
|
||||
return ProxyConfig(
|
||||
optimize=False,
|
||||
cache_enabled=False,
|
||||
rate_limit_enabled=False,
|
||||
cost_tracking_enabled=False,
|
||||
**overrides,
|
||||
)
|
||||
|
||||
|
||||
def test_create_app_refuses_open_bind() -> None:
|
||||
with pytest.raises(OpenBindRefused):
|
||||
create_app(_config(host="0.0.0.0", proxy_token=None))
|
||||
|
||||
|
||||
def test_create_app_accepts_open_bind_with_token() -> None:
|
||||
assert create_app(_config(host="0.0.0.0", proxy_token="s3cr3t")) is not None
|
||||
|
||||
|
||||
def test_create_app_accepts_acknowledged_open_bind(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv(OPEN_BIND_ACK_ENV, "1")
|
||||
assert create_app(_config(host="0.0.0.0", proxy_token=None)) is not None
|
||||
|
||||
|
||||
def test_create_app_default_loopback_bind_needs_nothing() -> None:
|
||||
assert create_app(_config()) is not None
|
||||
|
||||
|
||||
# ───────────────────────────── run_server ──────────────────────────────────
|
||||
|
||||
|
||||
def test_run_server_exits_before_uvicorn_on_open_bind(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
"""One clean exit code, not N workers dying in create_app."""
|
||||
called = []
|
||||
with (
|
||||
patch("headroom.proxy.server.uvicorn.run", lambda *a, **k: called.append(1)),
|
||||
pytest.raises(SystemExit) as exc_info,
|
||||
):
|
||||
run_server(_config(host="0.0.0.0", proxy_token=None), print_banner=False)
|
||||
assert exc_info.value.code == 2
|
||||
assert called == []
|
||||
err = capsys.readouterr().err
|
||||
assert "Refusing to bind '0.0.0.0'" in err
|
||||
assert PROXY_TOKEN_ENV in err and OPEN_BIND_ACK_ENV in err
|
||||
|
||||
|
||||
def test_run_server_proceeds_with_token() -> None:
|
||||
called = []
|
||||
with patch("headroom.proxy.server.uvicorn.run", lambda *a, **k: called.append(k)):
|
||||
run_server(_config(host="0.0.0.0", proxy_token="s3cr3t"), print_banner=False)
|
||||
assert len(called) == 1
|
||||
assert called[0]["host"] == "0.0.0.0"
|
||||
|
||||
|
||||
# ───────────────────────────── CLI ─────────────────────────────────────────
|
||||
|
||||
|
||||
def test_cli_refuses_open_bind_with_actionable_error() -> None:
|
||||
runner = CliRunner()
|
||||
called = []
|
||||
with patch("headroom.proxy.server.run_server", lambda config, **kw: called.append(config)):
|
||||
result = runner.invoke(main, ["proxy", "--host", "0.0.0.0"])
|
||||
assert result.exit_code != 0, result.output
|
||||
assert called == []
|
||||
assert "Refusing to bind '0.0.0.0'" in result.output
|
||||
assert PROXY_TOKEN_ENV in result.output
|
||||
assert OPEN_BIND_ACK_ENV in result.output
|
||||
# A refusal is an error message, never a traceback.
|
||||
assert "Traceback" not in result.output
|
||||
|
||||
|
||||
def test_cli_env_host_is_refused_too() -> None:
|
||||
"""``HEADROOM_HOST=0.0.0.0`` in a systemd unit is the common real-world shape."""
|
||||
runner = CliRunner()
|
||||
with patch("headroom.proxy.server.run_server", lambda config, **kw: None):
|
||||
result = runner.invoke(main, ["proxy"], env={"HEADROOM_HOST": "0.0.0.0"})
|
||||
assert result.exit_code != 0, result.output
|
||||
assert "Refusing to bind '0.0.0.0'" in result.output
|
||||
|
||||
|
||||
def test_cli_acknowledged_open_bind_starts_and_says_so() -> None:
|
||||
runner = CliRunner()
|
||||
captured = {}
|
||||
with patch(
|
||||
"headroom.proxy.server.run_server",
|
||||
lambda config, **kw: captured.setdefault("config", config),
|
||||
):
|
||||
result = runner.invoke(
|
||||
main,
|
||||
["proxy", "--host", "0.0.0.0"],
|
||||
env={OPEN_BIND_ACK_ENV: "1"},
|
||||
catch_exceptions=False,
|
||||
)
|
||||
assert result.exit_code == 0, result.output
|
||||
assert captured["config"].host == "0.0.0.0"
|
||||
assert "UNAUTHENTICATED" in result.output
|
||||
assert OPEN_BIND_ACK_ENV in result.output
|
||||
|
||||
|
||||
def test_cli_offline_banner_still_flags_acknowledged_open_bind() -> None:
|
||||
"""Offline mode must not hide that /v1/* is unauthenticated."""
|
||||
runner = CliRunner()
|
||||
with patch("headroom.proxy.server.run_server", lambda config, **kw: None):
|
||||
result = runner.invoke(
|
||||
main,
|
||||
["proxy", "--host", "0.0.0.0"],
|
||||
env={OPEN_BIND_ACK_ENV: "1", "HEADROOM_OFFLINE": "1"},
|
||||
catch_exceptions=False,
|
||||
)
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "OFFLINE" in result.output
|
||||
assert "UNAUTHENTICATED" in result.output
|
||||
|
||||
|
||||
def test_cli_open_bind_with_token_starts() -> None:
|
||||
runner = CliRunner()
|
||||
captured = {}
|
||||
with patch(
|
||||
"headroom.proxy.server.run_server",
|
||||
lambda config, **kw: captured.setdefault("config", config),
|
||||
):
|
||||
result = runner.invoke(
|
||||
main,
|
||||
["proxy", "--host", "0.0.0.0"],
|
||||
env={PROXY_TOKEN_ENV: "s3cr3t"},
|
||||
catch_exceptions=False,
|
||||
)
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "inbound token REQUIRED" in result.output
|
||||
@@ -127,8 +127,9 @@ def app_and_rebinding_client():
|
||||
def test_is_loopback_host_accepts_canonical_hosts():
|
||||
for host in LOOPBACK_HOSTS:
|
||||
assert is_loopback_host(host) is True
|
||||
# None (TestClient with no client info) is treated as loopback.
|
||||
assert is_loopback_host(None) is True
|
||||
# None (no peer address: UDS, adapters, bare request doubles) is NOT
|
||||
# loopback — every guard built on this must fail closed, not open.
|
||||
assert is_loopback_host(None) is False
|
||||
|
||||
|
||||
def test_is_loopback_host_rejects_external_hosts():
|
||||
|
||||
@@ -44,7 +44,13 @@ def _make_app(**overrides):
|
||||
return create_app(config)
|
||||
|
||||
|
||||
def test_create_app_accepts_test_net_host_without_transport_validation() -> None:
|
||||
def test_create_app_accepts_test_net_host_without_transport_validation(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
# No transport-level validation of the host string — but a non-loopback
|
||||
# bind with no token is an *acknowledged* open bind, never a silent one
|
||||
# (see test_proxy_bind_policy.py for the refusal path).
|
||||
monkeypatch.setenv("HEADROOM_ALLOW_UNAUTHENTICATED_BIND", "1")
|
||||
app = _make_app(host="203.0.113.5", proxy_token=None)
|
||||
assert app is not None
|
||||
|
||||
@@ -102,6 +108,18 @@ class TestInboundAuthToken:
|
||||
with TestClient(app, base_url="http://127.0.0.1", client=LOOPBACK) as c:
|
||||
assert c.get("/stats").status_code != 401
|
||||
|
||||
def test_missing_peer_address_is_not_loopback(self):
|
||||
"""No ``scope["client"]`` (UDS, adapters) must fail closed, not open.
|
||||
|
||||
``is_loopback_host(None)`` used to return True, which silently switched
|
||||
the token gate off for any transport that leaves the peer unset.
|
||||
"""
|
||||
app = _make_app(proxy_token="s3cr3t-token")
|
||||
with TestClient(app, base_url="http://127.0.0.1", client=None) as c: # type: ignore[arg-type]
|
||||
assert c.get("/stats").status_code == 401
|
||||
ok = c.get("/stats", headers={"Authorization": "Bearer s3cr3t-token"})
|
||||
assert ok.status_code != 401
|
||||
|
||||
def test_health_endpoints_exempt_even_nonloopback(self):
|
||||
"""Orchestrator health probes must work without the token."""
|
||||
app = _make_app(proxy_token="s3cr3t-token")
|
||||
@@ -218,25 +236,64 @@ class TestWebSocketAuthMiddleware:
|
||||
assert not _closed_with_policy_violation(sent)
|
||||
|
||||
async def test_loopback_is_exempt(self):
|
||||
"""Same trust boundary the HTTP gate already grants loopback."""
|
||||
"""Same trust boundary the HTTP gate already grants loopback.
|
||||
|
||||
Both gates the HTTP admin guards apply: loopback peer *and* loopback
|
||||
``Host`` header (a real handshake always carries one).
|
||||
"""
|
||||
downstream = _SpyApp()
|
||||
mw = WebSocketAuthMiddleware(downstream, proxy_token="s3cr3t-token")
|
||||
|
||||
sent = await _drive(mw, _ws_scope(client=LOOPBACK))
|
||||
sent = await _drive(mw, _ws_scope(client=LOOPBACK, headers=[("host", "127.0.0.1:8787")]))
|
||||
|
||||
assert downstream.called is True
|
||||
assert not _closed_with_policy_violation(sent)
|
||||
|
||||
async def test_unknown_client_is_treated_as_loopback(self):
|
||||
"""Mirrors is_loopback_host(None) -> True, as the HTTP gate does."""
|
||||
async def test_loopback_peer_with_foreign_host_header_is_not_exempt(self):
|
||||
"""DNS rebinding: a local browser reaching 127.0.0.1 still says Host: attacker.
|
||||
|
||||
The HTTP admin routes have checked Host since the loopback guard was
|
||||
written; the WebSocket gate checked the peer only. Same rule now.
|
||||
"""
|
||||
downstream = _SpyApp()
|
||||
mw = WebSocketAuthMiddleware(downstream, proxy_token="s3cr3t-token")
|
||||
|
||||
sent = await _drive(mw, _ws_scope(client=None))
|
||||
sent = await _drive(
|
||||
mw, _ws_scope(client=LOOPBACK, headers=[("host", "attacker.example:8787")])
|
||||
)
|
||||
|
||||
assert downstream.called is False
|
||||
assert _closed_with_policy_violation(sent)
|
||||
|
||||
async def test_loopback_peer_with_foreign_host_but_valid_token_passes(self):
|
||||
"""The Host check only decides the *exemption*; the token still works."""
|
||||
downstream = _SpyApp()
|
||||
mw = WebSocketAuthMiddleware(downstream, proxy_token="s3cr3t-token")
|
||||
|
||||
sent = await _drive(
|
||||
mw,
|
||||
_ws_scope(
|
||||
client=LOOPBACK,
|
||||
headers=[
|
||||
("host", "attacker.example:8787"),
|
||||
("authorization", "Bearer s3cr3t-token"),
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
assert downstream.called is True
|
||||
assert not _closed_with_policy_violation(sent)
|
||||
|
||||
async def test_unknown_client_is_not_loopback(self):
|
||||
"""Mirrors is_loopback_host(None) -> False: fail closed, like the HTTP gate."""
|
||||
downstream = _SpyApp()
|
||||
mw = WebSocketAuthMiddleware(downstream, proxy_token="s3cr3t-token")
|
||||
|
||||
sent = await _drive(mw, _ws_scope(client=None, headers=[("host", "127.0.0.1")]))
|
||||
|
||||
assert downstream.called is False
|
||||
assert _closed_with_policy_violation(sent)
|
||||
|
||||
async def test_repeated_header_resolves_like_the_http_gate(self):
|
||||
"""A duplicated Authorization must mean the same thing on both transports.
|
||||
|
||||
@@ -573,6 +630,29 @@ class TestWebSocketScrubsProxyToken:
|
||||
|
||||
assert downstream.headers == [(b"x-api-key", b"sk-ant")]
|
||||
|
||||
@pytest.mark.parametrize("token_header", ["authorization", "x-headroom-proxy-token"])
|
||||
async def test_loopback_exempt_handshake_is_still_scrubbed(self, token_header):
|
||||
# Loopback peer *and* loopback Host takes the token exemption; the
|
||||
# exemption must not skip the scrub, or a local client that sends the
|
||||
# token anyway has it forwarded upstream.
|
||||
downstream = _HeaderSpyApp()
|
||||
mw = WebSocketAuthMiddleware(downstream, proxy_token=TOKEN)
|
||||
value = f"Bearer {TOKEN}" if token_header == "authorization" else TOKEN
|
||||
|
||||
await _drive(
|
||||
mw,
|
||||
_ws_scope(
|
||||
client=LOOPBACK,
|
||||
headers=[
|
||||
("host", "127.0.0.1:8787"),
|
||||
(token_header, value),
|
||||
("x-api-key", "sk-ant"),
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
assert downstream.headers == [(b"host", b"127.0.0.1:8787"), (b"x-api-key", b"sk-ant")]
|
||||
|
||||
async def test_custom_header_removed_provider_bearer_kept(self):
|
||||
downstream = _HeaderSpyApp()
|
||||
mw = WebSocketAuthMiddleware(downstream, proxy_token=TOKEN)
|
||||
@@ -707,3 +787,37 @@ class TestOfflineSwitch:
|
||||
|
||||
assert os.environ.get("HF_HUB_OFFLINE") == "1"
|
||||
assert os.environ.get("TRANSFORMERS_OFFLINE") == "1"
|
||||
|
||||
|
||||
# ─────────────────── missing peer address fails closed everywhere ───────────
|
||||
|
||||
|
||||
def test_is_loopback_host_none_is_not_loopback() -> None:
|
||||
from headroom.proxy.loopback_guard import is_loopback_host
|
||||
|
||||
assert is_loopback_host(None) is False
|
||||
# Sanity: the genuine loopback literals are unaffected.
|
||||
assert is_loopback_host("127.0.0.1") is True
|
||||
assert is_loopback_host("::1") is True
|
||||
assert is_loopback_host("localhost") is True
|
||||
|
||||
|
||||
def test_require_loopback_404s_a_request_with_no_peer() -> None:
|
||||
"""Admin/debug guards must not open up when ``request.client`` is None."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
from headroom.proxy.loopback_guard import require_loopback
|
||||
|
||||
class _NoPeerRequest:
|
||||
client = None
|
||||
headers = {"host": "127.0.0.1:8787"}
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
require_loopback(_NoPeerRequest()) # type: ignore[arg-type]
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
|
||||
def test_debug_route_404s_for_request_with_no_peer() -> None:
|
||||
app = _make_app()
|
||||
with TestClient(app, base_url="http://127.0.0.1", client=None) as c: # type: ignore[arg-type]
|
||||
assert c.get("/debug/tasks").status_code == 404
|
||||
|
||||
@@ -745,3 +745,256 @@ def test_dashboard_client_cidr_does_not_expand_other_management_endpoints(
|
||||
assert client.get("/admin/upstream").status_code == 404
|
||||
assert client.get("/debug/tasks").status_code == 404
|
||||
assert client.post("/stats/reset").status_code == 404
|
||||
|
||||
|
||||
# ─────────────────────── read-only telemetry routes ─────────────────────────
|
||||
# These carried operator data (model/project/session labels, spend history,
|
||||
# subscription utilisation, provider quota) to any network caller. They now
|
||||
# share the /settings* trust chain: loopback or a trusted dashboard client
|
||||
# behind a gateway; everyone else sees 404. The dashboard shell is a static
|
||||
# template and stays reachable.
|
||||
|
||||
DASHBOARD_GATED = [
|
||||
("get", "/stats-history"),
|
||||
("get", "/stats-history?format=csv"),
|
||||
("get", "/quota"),
|
||||
("get", "/subscription-window"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method,path", DASHBOARD_GATED)
|
||||
def test_dashboard_routes_non_loopback_gets_404(method: str, path: str) -> None:
|
||||
resp = TestClient(_make_app()).request(method, path)
|
||||
assert resp.status_code == 404, resp.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method,path", DASHBOARD_GATED)
|
||||
def test_dashboard_routes_loopback_caller_allowed(method: str, path: str) -> None:
|
||||
resp = _loopback_client().request(method, path)
|
||||
# /subscription-window answers 503 when tracking is off; the point here is
|
||||
# that the *guard* let the caller through.
|
||||
assert resp.status_code != 404, resp.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method,path", DASHBOARD_GATED)
|
||||
def test_dashboard_routes_trusted_gateway_dashboard_client_allowed(
|
||||
monkeypatch: pytest.MonkeyPatch, method: str, path: str
|
||||
) -> None:
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS", "100.90.0.5/32")
|
||||
client = TestClient(
|
||||
_make_app(),
|
||||
base_url="http://100.82.0.2:8787",
|
||||
client=("100.90.0.5", 12345),
|
||||
)
|
||||
resp = client.request(method, path)
|
||||
assert resp.status_code != 404, resp.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method,path", DASHBOARD_GATED)
|
||||
def test_dashboard_routes_token_authenticated_operator_allowed(
|
||||
monkeypatch: pytest.MonkeyPatch, method: str, path: str
|
||||
) -> None:
|
||||
"""With a token configured the security gate is the control: 401 without,
|
||||
through with. Mirrors the docker-bind e2e contract (correct token → 200)."""
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TOKEN", "s3cr3t-token")
|
||||
app = _make_app()
|
||||
network = TestClient(app, base_url="http://headroom.svc.internal:8787", client=("10.10.0.7", 1))
|
||||
assert network.request(method, path).status_code == 401
|
||||
wrong = network.request(method, path, headers={"Authorization": "Bearer wrong"})
|
||||
assert wrong.status_code == 401
|
||||
ok = network.request(method, path, headers={"Authorization": "Bearer s3cr3t-token"})
|
||||
assert ok.status_code not in (401, 404), ok.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/stats-history", "/quota", "/metrics"])
|
||||
def test_token_does_not_exempt_a_loopback_peer_from_the_host_check(
|
||||
monkeypatch: pytest.MonkeyPatch, path: str
|
||||
) -> None:
|
||||
"""The gate waves loopback peers through without a token, so a configured
|
||||
token must not short-cut the DNS-rebinding defence for them."""
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TOKEN", "s3cr3t-token")
|
||||
app = _make_app()
|
||||
local = TestClient(app, base_url="http://127.0.0.1:8787", client=("127.0.0.1", 1))
|
||||
assert local.get(path).status_code != 404
|
||||
rebound = TestClient(app, base_url="http://attacker.example", client=("127.0.0.1", 1))
|
||||
assert rebound.get(path).status_code == 404
|
||||
|
||||
|
||||
def test_dashboard_shell_is_not_gated() -> None:
|
||||
"""Static template, no operator data: a container published on host loopback
|
||||
(peer = bridge gateway, Host = localhost) must still load it."""
|
||||
client = TestClient(_make_app(), base_url="http://localhost:8787", client=("172.17.0.1", 1))
|
||||
assert client.get("/dashboard").status_code == 200
|
||||
assert client.get("/stats-history").status_code == 404
|
||||
|
||||
|
||||
def _acknowledged_container_app(monkeypatch: pytest.MonkeyPatch) -> FastAPI:
|
||||
"""A token-less 0.0.0.0 bind acknowledged as published on host loopback,
|
||||
running in a container whose bridge gateway is 172.17.0.1."""
|
||||
monkeypatch.setenv("HEADROOM_ALLOW_UNAUTHENTICATED_BIND", "1")
|
||||
monkeypatch.setenv("HEADROOM_CONTAINER_HOST_GATEWAY", "172.17.0.1")
|
||||
return create_app(
|
||||
ProxyConfig(
|
||||
host="0.0.0.0",
|
||||
optimize=False,
|
||||
cache_enabled=False,
|
||||
rate_limit_enabled=False,
|
||||
cost_tracking_enabled=False,
|
||||
log_requests=False,
|
||||
ccr_inject_tool=False,
|
||||
ccr_handle_responses=False,
|
||||
ccr_context_tracking=False,
|
||||
image_optimize=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/stats-history", "/quota", "/subscription-window"])
|
||||
def test_loopback_published_container_serves_dashboard_data_to_its_host(
|
||||
monkeypatch: pytest.MonkeyPatch, path: str
|
||||
) -> None:
|
||||
"""Host browser -> 127.0.0.1 publication -> container sees the bridge gateway."""
|
||||
app = _acknowledged_container_app(monkeypatch)
|
||||
host = TestClient(app, base_url="http://localhost:8787", client=("172.17.0.1", 1))
|
||||
assert host.get(path).status_code != 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"client,base_url,headers",
|
||||
[
|
||||
# Another container on the same bridge is not the host.
|
||||
(("172.17.0.5", 1), "http://127.0.0.1:8787", {}),
|
||||
# The trust is the TCP peer; a forwarded header naming the gateway is ignored.
|
||||
(("172.17.0.5", 1), "http://127.0.0.1:8787", {"X-Forwarded-For": "172.17.0.1"}),
|
||||
# The DNS-rebinding defence still applies to the gateway peer.
|
||||
(("172.17.0.1", 1), "http://attacker.example:8787", {}),
|
||||
],
|
||||
)
|
||||
def test_loopback_published_container_trust_is_exact(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
client: tuple[str, int],
|
||||
base_url: str,
|
||||
headers: dict[str, str],
|
||||
) -> None:
|
||||
app = _acknowledged_container_app(monkeypatch)
|
||||
resp = TestClient(app, base_url=base_url, client=client).get("/stats-history", headers=headers)
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_container_gateway_needs_the_open_bind_acknowledgement(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Without the launcher's acknowledgement nothing vouches for the publication."""
|
||||
monkeypatch.setenv("HEADROOM_CONTAINER_HOST_GATEWAY", "172.17.0.1")
|
||||
client = TestClient(_make_app(), base_url="http://localhost:8787", client=("172.17.0.1", 1))
|
||||
assert client.get("/stats-history").status_code == 404
|
||||
|
||||
|
||||
def test_stats_history_csv_export_not_served_to_network_callers() -> None:
|
||||
"""The CSV export is the whole spend/model/session history in one GET."""
|
||||
resp = TestClient(_make_app()).get("/stats-history", params={"format": "csv"})
|
||||
assert resp.status_code == 404
|
||||
assert "text/csv" not in resp.headers.get("content-type", "")
|
||||
|
||||
|
||||
# ─────────────────────────────── /metrics ───────────────────────────────────
|
||||
# A Prometheus target: it cannot demand the dashboard's IP-literal Host header,
|
||||
# but it must not be a free read for every network peer either.
|
||||
|
||||
|
||||
def test_metrics_non_loopback_gets_404_without_token_or_cidr() -> None:
|
||||
resp = TestClient(_make_app()).get("/metrics")
|
||||
assert resp.status_code == 404, resp.text
|
||||
|
||||
|
||||
def test_metrics_loopback_allowed() -> None:
|
||||
resp = _loopback_client().get("/metrics")
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert "text/plain" in resp.headers["content-type"]
|
||||
|
||||
|
||||
def test_metrics_trusted_gateway_cidr_scraper_allowed(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""A scraper inside HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS with a hostname Host."""
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS", "10.9.0.0/24")
|
||||
client = TestClient(
|
||||
_make_app(),
|
||||
base_url="http://headroom.svc.internal:8787",
|
||||
client=("10.9.0.7", 40000),
|
||||
)
|
||||
assert client.get("/metrics").status_code == 200
|
||||
|
||||
|
||||
def test_metrics_trusted_dashboard_cidr_allowed(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS", "100.90.0.5/32")
|
||||
client = TestClient(
|
||||
_make_app(),
|
||||
base_url="http://100.82.0.2:8787",
|
||||
client=("100.90.0.5", 12345),
|
||||
)
|
||||
assert client.get("/metrics").status_code == 200
|
||||
|
||||
|
||||
def test_metrics_trusted_cidr_peer_outside_range_still_404s(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS", "10.9.0.0/24")
|
||||
client = TestClient(
|
||||
_make_app(),
|
||||
base_url="http://headroom.svc.internal:8787",
|
||||
client=("10.10.0.7", 40000),
|
||||
)
|
||||
assert client.get("/metrics").status_code == 404
|
||||
|
||||
|
||||
def test_metrics_trusted_gateway_forwarding_an_outside_scraper_allowed(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Gateway CIDRs vouch for the connecting peer, not the forwarded scraper."""
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS", "10.9.0.0/24")
|
||||
client = TestClient(
|
||||
_make_app(),
|
||||
base_url="http://headroom.svc.internal:8787",
|
||||
client=("10.9.0.7", 40000),
|
||||
)
|
||||
resp = client.get("/metrics", headers={"X-Forwarded-For": "192.0.2.8"})
|
||||
assert resp.status_code == 200, resp.text
|
||||
|
||||
|
||||
def test_metrics_forwarded_gateway_address_from_untrusted_peer_404s(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Naming a gateway-CIDR address in X-Forwarded-For grants nothing."""
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS", "10.9.0.0/24")
|
||||
client = TestClient(
|
||||
_make_app(),
|
||||
base_url="http://headroom.svc.internal:8787",
|
||||
client=("10.10.0.7", 40000),
|
||||
)
|
||||
resp = client.get("/metrics", headers={"X-Forwarded-For": "10.9.0.7"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_metrics_trusted_cidr_cross_origin_browser_rejected(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Browser provenance from another origin is refused even from a trusted peer."""
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS", "10.9.0.0/24")
|
||||
client = TestClient(
|
||||
_make_app(),
|
||||
base_url="http://headroom.svc.internal:8787",
|
||||
client=("10.9.0.7", 40000),
|
||||
)
|
||||
resp = client.get("/metrics", headers={"Origin": "http://attacker.example"})
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_metrics_token_authenticated_network_caller_allowed(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""With a token configured the security gate is the control; /metrics defers to it."""
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TOKEN", "s3cr3t-token")
|
||||
app = _make_app()
|
||||
network = TestClient(app, base_url="http://headroom.svc.internal:8787", client=("10.10.0.7", 1))
|
||||
assert network.get("/metrics").status_code == 401
|
||||
ok = network.get("/metrics", headers={"Authorization": "Bearer s3cr3t-token"})
|
||||
assert ok.status_code == 200, ok.text
|
||||
|
||||
@@ -1379,7 +1379,11 @@ def test_openai_chat_custom_base_flood_cannot_grow_the_provider_set(
|
||||
assert lifetime["rate_limited_by_source"] == {"headroom": 250, "upstream": 250}
|
||||
|
||||
# Prometheus export: every provider series is from the fixed set.
|
||||
export = client.get("/metrics").text
|
||||
# /metrics is an operator route: read it as the local operator does.
|
||||
operator = TestClient(
|
||||
client.app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
)
|
||||
export = operator.get("/metrics").text
|
||||
assert set(re.findall(r'provider="([^"]+)"', export)) <= fixed_providers | {"unknown"}
|
||||
assert 'headroom_requests_by_provider{provider="zai"} 10' in export
|
||||
assert 'headroom_requests_by_provider{provider="custom"} 250' in export
|
||||
|
||||
@@ -237,7 +237,9 @@ def test_funnel_attributes_savings_from_context_and_stats_exposes_them(tmp_path,
|
||||
monkeypatch.setenv("HEADROOM_SAVINGS_PATH", str(tmp_path / "savings.json"))
|
||||
config = ProxyConfig(cache_enabled=False, rate_limit_enabled=False, log_requests=False)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
proxy = client.app.state.proxy
|
||||
|
||||
set_current_project("ctx-project")
|
||||
@@ -290,7 +292,9 @@ def test_stats_payload_keeps_legacy_shape(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("HEADROOM_SAVINGS_PATH", str(tmp_path / "savings.json"))
|
||||
config = ProxyConfig(cache_enabled=False, rate_limit_enabled=False, log_requests=False)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
proxy = client.app.state.proxy
|
||||
_emit_outcome(proxy) # unattributed: no header, no context, no field
|
||||
|
||||
@@ -310,7 +314,9 @@ def test_metrics_record_request_works_without_project_kwarg(tmp_path, monkeypatc
|
||||
monkeypatch.setenv("HEADROOM_SAVINGS_PATH", str(tmp_path / "savings.json"))
|
||||
config = ProxyConfig(cache_enabled=False, rate_limit_enabled=False, log_requests=False)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
proxy = client.app.state.proxy
|
||||
asyncio.run(
|
||||
proxy.metrics.record_request(
|
||||
@@ -341,7 +347,9 @@ def test_middleware_binds_project_header_to_context(tmp_path, monkeypatch):
|
||||
|
||||
monkeypatch.setattr(server_module, "set_current_project", _capture)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
assert client.get("/health", headers={"X-Headroom-Project": " my repo "}).status_code == 200
|
||||
assert client.get("/health").status_code == 200
|
||||
# /p/<name> base-URL prefix (aider/copilot/cursor wraps): stripped
|
||||
|
||||
@@ -1223,7 +1223,9 @@ def test_stats_history_persists_across_restarts_and_stats_stays_compatible(tmp_p
|
||||
log_requests=False,
|
||||
)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
_record_request(client, model="gpt-4o", tokens_saved=40)
|
||||
|
||||
stats = client.get("/stats")
|
||||
@@ -1276,7 +1278,9 @@ def test_stats_history_persists_across_restarts_and_stats_stays_compatible(tmp_p
|
||||
stats_data["persistent_savings"]["display_session"] == history_data["display_session"]
|
||||
)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
history = client.get("/stats-history")
|
||||
assert history.status_code == 200
|
||||
assert history.json()["lifetime"]["tokens_saved"] == 40
|
||||
@@ -1428,7 +1432,9 @@ def test_stats_history_csv_export_is_frontend_friendly(tmp_path, monkeypatch):
|
||||
log_requests=False,
|
||||
)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
_record_request(client, model="gpt-4o", tokens_saved=40)
|
||||
_record_request(client, model="gpt-4o", tokens_saved=10)
|
||||
|
||||
@@ -1464,7 +1470,9 @@ def test_malformed_savings_state_is_ignored_safely(tmp_path, monkeypatch):
|
||||
log_requests=False,
|
||||
)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
response = client.get("/stats-history")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
@@ -1482,7 +1490,9 @@ def test_dashboard_includes_history_toggle_and_endpoint(tmp_path, monkeypatch):
|
||||
log_requests=False,
|
||||
)
|
||||
|
||||
with TestClient(create_app(config)) as client:
|
||||
with TestClient(
|
||||
create_app(config), base_url="http://127.0.0.1", client=("127.0.0.1", 12345)
|
||||
) as client:
|
||||
response = client.get("/dashboard")
|
||||
assert response.status_code == 200
|
||||
html = response.text
|
||||
|
||||
@@ -251,6 +251,10 @@ class TestWorkerConfiguration:
|
||||
from headroom.proxy.server import _MULTI_WORKER_CONFIG_ENV, run_server
|
||||
|
||||
captured = {}
|
||||
# A non-loopback bind needs an inbound token (or an explicit
|
||||
# acknowledgement) since the bind policy landed; this test is about
|
||||
# the multi-worker plumbing, so give it the token.
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TOKEN", "multi-worker-test-token")
|
||||
config = ProxyConfig(
|
||||
host="0.0.0.0",
|
||||
port=8787,
|
||||
|
||||
@@ -59,17 +59,24 @@ headroom memory list
|
||||
For `proxy`, the maintained wrapper always publishes the selected host port on
|
||||
loopback. It passes `--host 0.0.0.0` inside the container so that the loopback
|
||||
publication can reach the container, and it has no public-publication override.
|
||||
For local-only use, no token is required:
|
||||
For local-only use no token is needed, but the proxy refuses to start on a
|
||||
non-loopback bind without one unless you acknowledge that the runtime already
|
||||
restricts who can reach the port (here: the `127.0.0.1` publication):
|
||||
|
||||
```bash
|
||||
docker run --rm -it \
|
||||
-p 127.0.0.1:8787:8787 \
|
||||
-e HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1 \
|
||||
-v "$PWD:/workspace" \
|
||||
-w /workspace \
|
||||
ghcr.io/headroomlabs-ai/headroom:latest \
|
||||
--host 0.0.0.0 --port 8787
|
||||
```
|
||||
|
||||
The maintained wrappers (`headroom install`, the `install.sh` / `install.ps1`
|
||||
native wrappers, and `docker/docker-compose.native.yml`) set that acknowledgement
|
||||
themselves, and only together with the `127.0.0.1` publication it depends on.
|
||||
|
||||
For deliberate public access, publish on an explicit public address and set
|
||||
`HEADROOM_PROXY_TOKEN`:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user