mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): enforce HEADROOM_PROXY_TOKEN in the Rust front and listen on loopback by default (#4840)
## Description
The Rust front (`crates/headroom-proxy`) relays every request to the
Python proxy from `127.0.0.1`. The Python proxy treats a loopback caller
as local: it skips the `HEADROOM_PROXY_TOKEN` check and serves `/admin`,
`/debug` and `/settings` to it. The front had no inbound check of its
own, listened on `0.0.0.0:8787` by default, and dropped
`x-headroom-proxy-token` (as an `x-headroom-*` header), so a token set
on the Python side neither protected the stack nor could be presented
through the front.
This PR makes the Rust front apply the same token model as the Python
proxy (`read_proxy_token` / `scrub_proxy_token_headers` in
`headroom/proxy/server.py`, `headroom/proxy/bind_policy.py`) before
anything is forwarded, and makes its default listen address loopback.
Fix adapted from a proposal by HetCreep.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [x] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- New `crates/headroom-proxy/src/inbound_auth.rs`, installed as a
router-wide layer (all routes, the catch-all and WebSocket upgrades)
when `HEADROOM_PROXY_TOKEN` / `--proxy-token` is set:
- a non-loopback peer (or one with no peer address) must send the token
as `X-Headroom-Proxy-Token` or `Authorization: Bearer`; the explicit
header wins, as in Python. Constant-time compare. Otherwise `401
{"error":"unauthorized"}` and no upstream contact; a
`proxy_auth_rejected` warning is logged (no credential values).
- loopback peers are exempt (same as Python); `GET /healthz`,
`/healthz/upstream`, `/health`, `/livez`, `/readyz` stay open;
`GET`/`HEAD /api/hello` (also under `/p/<project>`) is answered locally
with an empty 200, as Python does, instead of being relayed.
- the token is removed before forwarding: `x-headroom-proxy-token`
always, `Authorization` only when it carries the token (a provider
credential is left alone).
- the token is redacted from `Debug` output of `Config`.
- `main.rs`: startup bind policy, same rule and variable as Python: a
non-loopback `--listen` with no token exits with code 2 and a message
naming both remedies, unless `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1`
(then a warning is logged).
- `config.rs`: `--listen` / `HEADROOM_PROXY_LISTEN` default changes from
`0.0.0.0:8787` to `127.0.0.1:8787`; new `--proxy-token` (env
`HEADROOM_PROXY_TOKEN`, value hidden from `--help`).
- `RUST_DEV.md`: runbook exports a token for the `0.0.0.0` cutover, flag
table updated, new "Inbound authentication" section.
**Behaviour change for operators:** a Rust front started with `--listen
0.0.0.0:...` (or relying on the old default to be reachable from other
hosts) now needs `HEADROOM_PROXY_TOKEN` set, and clients on other hosts
must send it. Setups that front the port with something else that
restricts access can set `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1`.
Loopback clients (Claude Code, Codex, SDKs on the same host) are
unaffected. The Docker image's entrypoint is the Python proxy, so it is
unaffected.
## Testing
- [x] `cargo test -p headroom-proxy` (46 test binaries, 608 tests pass)
- [x] `cargo clippy -p headroom-proxy --all-targets -- -D warnings` and
`cargo fmt --all -- --check` clean
- [x] New tests added for new functionality
- [x] Manual testing performed
- [ ] `pytest` / `ruff` / `mypy`: N/A, no Python changes
New tests:
- `tests/integration_inbound_auth.rs` (11 tests, `oneshot` with an
injected `ConnectInfo` so a non-loopback peer can be simulated,
`wiremock` upstream): missing/wrong token is 401 and the upstream sees
nothing; correct token via header or Bearer is forwarded without the
token; provider `Authorization` kept when the header carries the token;
loopback and IPv4-mapped loopback peers pass; missing peer address fails
closed; health probes open but `POST /readyz` is 401; `/api/hello`
answered locally; no token configured keeps passthrough.
- `tests/integration_bind_policy.rs` (3 tests, real binary): `0.0.0.0`
with no token refuses to start; loopback starts; default `--listen` is
loopback.
- unit tests in `inbound_auth.rs` for token parsing, constant-time
compare, bind policy and exemptions.
### Test Output
Before (the bind-policy test file copied onto a clean `origin/main`
worktree; `integration_inbound_auth.rs` does not compile there since
main has no token setting at all):
```text
test default_listen_address_is_loopback ... FAILED
test loopback_listen_without_token_still_starts ... ok
test non_loopback_listen_without_token_refuses_to_start ... FAILED
test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 20.01s
```
After:
```text
$ cargo test -p headroom-proxy --test integration_inbound_auth --test integration_bind_policy
test default_listen_address_is_loopback ... ok
test non_loopback_listen_without_token_refuses_to_start ... ok
test loopback_listen_without_token_still_starts ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.01s
test missing_peer_address_fails_closed ... ok
test remote_peer_with_bearer_token_is_forwarded_without_it ... ok
test remote_peer_without_token_gets_401_and_upstream_is_not_contacted ... ok
test token_header_wins_over_a_provider_bearer ... ok
test no_token_configured_keeps_todays_passthrough ... ok
test loopback_peer_without_token_is_still_forwarded ... ok
test ipv4_mapped_loopback_peer_counts_as_loopback ... ok
test remote_peer_with_token_header_is_forwarded_without_it ... ok
test hello_probe_is_answered_locally_without_token ... ok
test remote_peer_with_wrong_token_gets_401 ... ok
test health_probes_stay_reachable_without_token ... ok
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.74s
```
## Real Behavior Proof
- Environment: macOS (Darwin 27.2), debug builds of `headroom-proxy`
from `origin/main` (c21b0813) and from this branch. Upstream is a small
Python HTTP recorder on `127.0.0.1:18788` that prints each request it
receives. Requests are sent with curl to the machine's LAN address
(non-loopback peer) and to `127.0.0.1`.
- Exact command / steps: `HEADROOM_PROXY_TOKEN=s3cret
HEADROOM_PROXY_STATS=false headroom-proxy --listen 0.0.0.0:18787
--upstream http://127.0.0.1:18788`, then `curl
http://<lan-ip>:18787/admin/upstream` with no token, a wrong token and
the right token in `x-headroom-proxy-token`, `GET /readyz` with no token
from the LAN address, and `GET /v1/models` from `127.0.0.1` with no
token.
- Observed result:
```text
== origin/main
GET /admin/upstream (no token) -> 200
GET /admin/upstream -H x-headroom-proxy-token:wrong -> 200
GET /admin/upstream -H x-headroom-proxy-token:s3cret -> 200
GET /readyz (no token) -> 200
GET /v1/models from 127.0.0.1 (no token) -> 200
UPSTREAM SAW {"path": "/admin/upstream", "peer": "127.0.0.1", "token_hdr": null, "authorization": null} (x3)
UPSTREAM SAW {"path": "/readyz", ...}
UPSTREAM SAW {"path": "/v1/models", ...}
== this branch
GET /admin/upstream (no token) -> 401
GET /admin/upstream -H x-headroom-proxy-token:wrong -> 401
GET /admin/upstream -H x-headroom-proxy-token:s3cret -> 200
GET /readyz (no token) -> 200
GET /v1/models from 127.0.0.1 (no token) -> 200
UPSTREAM SAW {"path": "/admin/upstream", "peer": "127.0.0.1", "token_hdr": null, "authorization": null} (only the authenticated one)
UPSTREAM SAW {"path": "/readyz", ...}
UPSTREAM SAW {"path": "/v1/models", ...}
$ headroom-proxy --listen 0.0.0.0:18787 --upstream http://127.0.0.1:18788 # no token
headroom-proxy: Refusing to listen on 0.0.0.0:18787: with no HEADROOM_PROXY_TOKEN this proxy would relay every network peer to the upstream Headroom proxy from 127.0.0.1, where it is treated as a trusted local caller. Either set HEADROOM_PROXY_TOKEN ... or ... set HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1 to acknowledge the open bind.
(exit 2)
```
- Not tested: a full chain with the real Python proxy behind the Rust
front (the recorder stands in for it); WebSocket upgrades through the
gate are covered only by the layer wrapping the catch-all, not by a
dedicated test.
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: N/A
- Stable/default behavior changed: yes, default listen address is now
loopback, and a non-loopback listen needs a token or the acknowledgement
variable
- Kill switch / disable path: `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1`
restores starting on a non-loopback address without a token; `--listen
0.0.0.0:8787` restores the old address
- Unsafe override required: no
- Qualification impact: none (qualification scripts already pass
`--listen 127.0.0.1:<port>`)
- Rollback path: revert this PR
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Additional Notes
A companion PR makes the Rust front's native Bedrock and Vertex routes
opt-in; it relies on this token gate for callers on those routes.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reported by @JoaoMarcos44. Thank you for your contribution! 🩵
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
cfdeb1c466
commit
f5c4217648
+40
-8
@@ -54,9 +54,8 @@ at it; end users notice nothing.
|
||||
make build-proxy
|
||||
./target/release/headroom-proxy --help
|
||||
|
||||
# Run against a local upstream
|
||||
# Run against a local upstream (listens on 127.0.0.1:8787 by default)
|
||||
./target/release/headroom-proxy \
|
||||
--listen 0.0.0.0:8787 \
|
||||
--upstream http://127.0.0.1:8788
|
||||
|
||||
# Health checks
|
||||
@@ -70,7 +69,10 @@ curl -s http://127.0.0.1:8787/healthz/upstream # => 200 if upstream reachable
|
||||
# 1. Move the Python proxy to a private port (e.g. 8788)
|
||||
HEADROOM_HOST=127.0.0.1 HEADROOM_PORT=8788 python -m headroom.proxy & # or your existing launcher
|
||||
|
||||
# 2. Run the Rust proxy on the previously-public port (8787) pointing at it
|
||||
# 2. Run the Rust proxy on the previously-public port (8787) pointing at it.
|
||||
# The Python proxy sees every relayed request as coming from 127.0.0.1,
|
||||
# so the Rust proxy enforces HEADROOM_PROXY_TOKEN itself (see below).
|
||||
export HEADROOM_PROXY_TOKEN="$(openssl rand -hex 32)"
|
||||
./target/release/headroom-proxy --listen 0.0.0.0:8787 --upstream http://127.0.0.1:8788 &
|
||||
|
||||
# 3. End users keep hitting :8787 unchanged.
|
||||
@@ -83,7 +85,8 @@ curl -si http://127.0.0.1:8787/v1/models
|
||||
|
||||
| Flag | Env var | Default | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| `--listen` | `HEADROOM_PROXY_LISTEN` | `0.0.0.0:8787` | bind address |
|
||||
| `--listen` | `HEADROOM_PROXY_LISTEN` | `127.0.0.1:8787` | bind address; a non-loopback address refuses to start without `HEADROOM_PROXY_TOKEN` unless `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1` |
|
||||
| `--proxy-token` | `HEADROOM_PROXY_TOKEN` | (unset) | inbound token required from non-loopback peers (below); prefer the env var |
|
||||
| `--metrics-require-loopback` | `HEADROOM_PROXY_METRICS_REQUIRE_LOOPBACK` | `false` | when set, `/metrics` is served only to loopback peers (403 otherwise); recommended on non-loopback binds |
|
||||
| `--upstream` | `HEADROOM_PROXY_UPSTREAM` | (required) | base URL the proxy forwards to |
|
||||
| `--upstream-timeout` | | `600s` | end-to-end request timeout (long for streams) |
|
||||
@@ -95,6 +98,33 @@ curl -si http://127.0.0.1:8787/v1/models
|
||||
| `--stats` | `HEADROOM_PROXY_STATS` | `true` | native savings stats + `/dashboard` (below) |
|
||||
| `--stats-path` | `HEADROOM_PROXY_STATS_PATH` | `~/.headroom/native_stats.json` | ledger persistence (honours `HEADROOM_WORKSPACE_DIR`) |
|
||||
|
||||
### Inbound authentication
|
||||
|
||||
The Rust proxy connects to the Python proxy from `127.0.0.1`, and the
|
||||
Python proxy trusts loopback callers (no token needed, and access to
|
||||
`/admin`, `/debug` and `/settings`). So the Rust proxy applies the same
|
||||
`HEADROOM_PROXY_TOKEN` rules itself, before anything is forwarded:
|
||||
|
||||
- With a token set, a non-loopback peer must send it as
|
||||
`X-Headroom-Proxy-Token: <token>` or `Authorization: Bearer <token>`,
|
||||
or gets `401 {"error":"unauthorized"}`. Loopback peers are exempt, as
|
||||
in the Python proxy. The token is removed from the request before it
|
||||
is forwarded (`Authorization` only when it carries the token).
|
||||
- A caller that is not local here (a non-loopback peer, or a loopback
|
||||
peer whose `Host` is not a loopback name) is never forwarded with a
|
||||
`Host` that may name loopback (including scoped IPv6 such as
|
||||
`[::1%lo]`), whatever `--rewrite-host` is and whatever the upstream
|
||||
name resolves to: that `Host` is replaced with
|
||||
`headroom-remote.invalid`, so the Python proxy's local-only routes
|
||||
(`/admin`, `/debug`, `/settings`, ...) stay closed to it, with or
|
||||
without a token.
|
||||
- `GET /healthz`, `/healthz/upstream`, `/health`, `/livez` and `/readyz`
|
||||
stay reachable without the token, and `GET`/`HEAD /api/hello` is
|
||||
answered locally with an empty `200`.
|
||||
- A non-loopback `--listen` with no token refuses to start. Set
|
||||
`HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1` only when something else
|
||||
already restricts who can reach the port.
|
||||
|
||||
### Savings stats & dashboard (native)
|
||||
|
||||
The Rust proxy records per-request savings/cost telemetry on every
|
||||
@@ -143,13 +173,15 @@ the hot path every 10 s and on shutdown.
|
||||
> the numbers start flowing on their own.
|
||||
|
||||
> **No auth; exposure is split by tier.** These endpoints bind
|
||||
> wherever `--listen` points (default `0.0.0.0:8787`) and carry no
|
||||
> auth, so the payload is split the same way the Python proxy splits
|
||||
> wherever `--listen` points (default `127.0.0.1:8787`) and, for
|
||||
> loopback peers or with no `HEADROOM_PROXY_TOKEN`, carry no auth, so the payload is split the same way the Python proxy splits
|
||||
> its own `/stats`:
|
||||
>
|
||||
> - **Aggregates** — spend, tokens, per-model/provider rollups,
|
||||
> history — are served to anyone, like the Prometheus `/metrics`
|
||||
> endpoint next door. Same data class, same stance.
|
||||
> history — are served to any caller that gets past the inbound gate
|
||||
> (above), like the Prometheus `/metrics` endpoint next door: with
|
||||
> `HEADROOM_PROXY_TOKEN` set, remote callers need the token for these
|
||||
> too; without it, they are open to anyone who can reach the port.
|
||||
> - **Per-request rows** — `recent_requests`, all of `/stats/events`
|
||||
> — plus the ledger's filesystem path are served **only to local
|
||||
> callers**: loopback peer *and* a loopback `Host` header (the
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Configuration for the proxy: CLI flags + env vars.
|
||||
|
||||
use crate::inbound_auth::ProxyToken;
|
||||
use clap::{Parser, ValueEnum};
|
||||
use headroom_core::rollout::{
|
||||
feature_names, split_feature_names, Feature, RolloutChannel, RolloutSnapshot,
|
||||
@@ -272,8 +273,10 @@ pub struct CliArgs {
|
||||
)]
|
||||
pub unsafe_allow_unstable_features: bool,
|
||||
|
||||
/// Address the proxy listens on (e.g. 0.0.0.0:8787).
|
||||
#[arg(long, env = "HEADROOM_PROXY_LISTEN", default_value = "0.0.0.0:8787")]
|
||||
/// Address the proxy listens on. Loopback by default, like the Python
|
||||
/// proxy; a non-loopback address needs `HEADROOM_PROXY_TOKEN` (or
|
||||
/// `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1`) to start.
|
||||
#[arg(long, env = "HEADROOM_PROXY_LISTEN", default_value = "127.0.0.1:8787")]
|
||||
pub listen: SocketAddr,
|
||||
|
||||
/// Restrict the Prometheus `/metrics` scrape endpoint to loopback
|
||||
@@ -295,6 +298,20 @@ pub struct CliArgs {
|
||||
)]
|
||||
pub metrics_require_loopback: bool,
|
||||
|
||||
/// Inbound proxy token. When set, every request from a non-loopback
|
||||
/// peer must present it as `x-headroom-proxy-token` or
|
||||
/// `Authorization: Bearer`, the same rules as the Python proxy, or it
|
||||
/// gets 401 without reaching the upstream. Prefer the env var: a
|
||||
/// command-line value is visible in the process list. A non-loopback
|
||||
/// `--listen` refuses to start without it unless
|
||||
/// `HEADROOM_ALLOW_UNAUTHENTICATED_BIND=1` acknowledges the open bind.
|
||||
#[arg(
|
||||
long = "proxy-token",
|
||||
env = "HEADROOM_PROXY_TOKEN",
|
||||
hide_env_values = true
|
||||
)]
|
||||
pub proxy_token: Option<String>,
|
||||
|
||||
/// Upstream base URL the proxy forwards to (e.g. http://127.0.0.1:8788).
|
||||
/// REQUIRED — there is no default; we want operators to be explicit.
|
||||
#[arg(long, env = "HEADROOM_PROXY_UPSTREAM")]
|
||||
@@ -667,6 +684,8 @@ pub struct Config {
|
||||
/// Gate the Prometheus `/metrics` endpoint to loopback clients.
|
||||
/// Default `false`; recommend `true` when `listen` is non-loopback.
|
||||
pub metrics_require_loopback: bool,
|
||||
/// Inbound token required from non-loopback peers (`None` = no gate).
|
||||
pub proxy_token: Option<ProxyToken>,
|
||||
pub upstream: Url,
|
||||
pub upstream_timeout: Duration,
|
||||
pub upstream_connect_timeout: Duration,
|
||||
@@ -781,6 +800,7 @@ impl Config {
|
||||
rollout: rollout.clone(),
|
||||
listen: args.listen,
|
||||
metrics_require_loopback: args.metrics_require_loopback,
|
||||
proxy_token: args.proxy_token.as_deref().and_then(ProxyToken::new),
|
||||
upstream: args.upstream,
|
||||
upstream_timeout: args.upstream_timeout,
|
||||
upstream_connect_timeout: args.upstream_connect_timeout,
|
||||
@@ -824,6 +844,7 @@ impl Config {
|
||||
// carry no `ConnectInfo`. Tests that exercise the gate set
|
||||
// this to `true` explicitly.
|
||||
metrics_require_loopback: false,
|
||||
proxy_token: None,
|
||||
upstream,
|
||||
upstream_timeout: Duration::from_secs(60),
|
||||
upstream_connect_timeout: Duration::from_secs(5),
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
//! Inbound `HEADROOM_PROXY_TOKEN` gate and startup bind policy.
|
||||
//!
|
||||
//! The Rust front connects to the Python proxy from `127.0.0.1`, and the
|
||||
//! Python proxy exempts loopback peers from its token gate and trusts them
|
||||
//! on `/admin`, `/debug` and `/settings`. So the front must apply the same
|
||||
//! model itself, or every peer that reaches it is a "local" caller. Names,
|
||||
//! credential rules and exemptions mirror `headroom/proxy/server.py`
|
||||
//! (`_security_gate`, `read_proxy_token`) and `headroom/proxy/bind_policy.py`
|
||||
//! so operators configure one token model for both processes.
|
||||
|
||||
use std::fmt;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{ConnectInfo, State};
|
||||
use axum::http::{header, HeaderMap, HeaderValue, Method, Request, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::Json;
|
||||
use serde_json::json;
|
||||
|
||||
/// The inbound credential. Same variable as the Python proxy.
|
||||
pub const PROXY_TOKEN_ENV: &str = "HEADROOM_PROXY_TOKEN";
|
||||
/// Explicit acknowledgement of an unauthenticated non-loopback bind.
|
||||
/// Same variable and truthy values as the Python bind policy.
|
||||
pub const OPEN_BIND_ACK_ENV: &str = "HEADROOM_ALLOW_UNAUTHENTICATED_BIND";
|
||||
const PROXY_TOKEN_HEADER: &str = "x-headroom-proxy-token";
|
||||
|
||||
/// A configured proxy token. `Debug` never prints the value, because
|
||||
/// `Config` derives `Debug`.
|
||||
#[derive(Clone)]
|
||||
pub struct ProxyToken(String);
|
||||
|
||||
impl ProxyToken {
|
||||
/// `None` for an empty or whitespace-only value, which the Python bind
|
||||
/// policy also treats as "not configured". A real value is kept
|
||||
/// verbatim, as the Python gate compares it.
|
||||
pub fn new(value: &str) -> Option<Self> {
|
||||
(!value.trim().is_empty()).then(|| Self(value.to_owned()))
|
||||
}
|
||||
|
||||
fn matches(&self, provided: &str) -> bool {
|
||||
constant_time_eq(provided.as_bytes(), self.0.as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ProxyToken {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("ProxyToken(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
// Like Python's hmac.compare_digest: time does not depend on where the
|
||||
// bytes differ (the length is not hidden, as there).
|
||||
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
fn is_loopback(addr: &SocketAddr) -> bool {
|
||||
addr.ip().to_canonical().is_loopback()
|
||||
}
|
||||
|
||||
/// Outcome of the startup bind check that lets the process start.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum BindPolicy {
|
||||
/// Loopback bind, or a token is configured.
|
||||
Ok,
|
||||
/// Non-loopback bind with no token, acknowledged via [`OPEN_BIND_ACK_ENV`].
|
||||
OpenAcknowledged,
|
||||
}
|
||||
|
||||
/// Refuse a non-loopback `listen` with no token unless acknowledged.
|
||||
/// `ack` is the raw value of [`OPEN_BIND_ACK_ENV`]. The error text names
|
||||
/// both remedies.
|
||||
pub fn check_bind_policy(
|
||||
listen: SocketAddr,
|
||||
token_configured: bool,
|
||||
ack: Option<&str>,
|
||||
) -> Result<BindPolicy, String> {
|
||||
if token_configured || is_loopback(&listen) {
|
||||
return Ok(BindPolicy::Ok);
|
||||
}
|
||||
let acknowledged = ack.is_some_and(|v| {
|
||||
matches!(
|
||||
v.trim().to_ascii_lowercase().as_str(),
|
||||
"1" | "true" | "yes" | "on"
|
||||
)
|
||||
});
|
||||
if acknowledged {
|
||||
return Ok(BindPolicy::OpenAcknowledged);
|
||||
}
|
||||
Err(format!(
|
||||
"Refusing to listen on {listen}: with no {PROXY_TOKEN_ENV} this proxy would relay \
|
||||
every network peer to the upstream Headroom proxy from 127.0.0.1, where it is \
|
||||
treated as a trusted local caller. Either set {PROXY_TOKEN_ENV} (e.g. \
|
||||
`openssl rand -hex 32`) so non-loopback callers must present it, listen on a \
|
||||
loopback address (--listen 127.0.0.1:8787), or, only when the runtime already \
|
||||
restricts who can reach the port (such as a container published on 127.0.0.1), \
|
||||
set {OPEN_BIND_ACK_ENV}=1 to acknowledge the open bind."
|
||||
))
|
||||
}
|
||||
|
||||
/// The caller-supplied token, read exactly as Python's `read_proxy_token`:
|
||||
/// the explicit header wins when present (even empty, then it is no
|
||||
/// credential); otherwise a `Bearer` Authorization value.
|
||||
fn read_proxy_token(headers: &HeaderMap) -> Option<&str> {
|
||||
if let Some(raw) = headers.get(PROXY_TOKEN_HEADER) {
|
||||
return raw.to_str().ok().filter(|v| !v.is_empty());
|
||||
}
|
||||
bearer(headers)
|
||||
}
|
||||
|
||||
fn bearer(headers: &HeaderMap) -> Option<&str> {
|
||||
let auth = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
|
||||
let scheme = auth.get(..7)?;
|
||||
if !scheme.eq_ignore_ascii_case("bearer ") {
|
||||
return None;
|
||||
}
|
||||
Some(auth[7..].trim()).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Python exempts `GET /health`, `/livez` and `/readyz`; `/healthz` and
|
||||
/// `/healthz/upstream` are this proxy's own probe routes.
|
||||
fn is_health_probe(method: &Method, path: &str) -> bool {
|
||||
*method == Method::GET
|
||||
&& matches!(
|
||||
path,
|
||||
"/healthz" | "/healthz/upstream" | "/health" | "/livez" | "/readyz"
|
||||
)
|
||||
}
|
||||
|
||||
/// The Anthropic SDK's `GET`/`HEAD /api/hello` reachability probe (also
|
||||
/// under `/p/<project>`). It never carries custom headers, so it cannot
|
||||
/// hold the token.
|
||||
fn is_hello_probe(method: &Method, path: &str) -> bool {
|
||||
let hello = path == "/api/hello"
|
||||
|| path
|
||||
.strip_prefix("/p/")
|
||||
.and_then(|rest| rest.split_once('/'))
|
||||
.is_some_and(|(project, rest)| !project.is_empty() && rest == "api/hello");
|
||||
(*method == Method::GET || *method == Method::HEAD) && hello
|
||||
}
|
||||
|
||||
/// Request extension: the caller is not local (not a loopback peer with a
|
||||
/// loopback `Host`). `forward_http` then never sends it upstream with a
|
||||
/// loopback `Host`, so the upstream's local-only routes (`/admin`,
|
||||
/// `/debug`, `/settings`, ...) do not treat a relayed caller as local.
|
||||
/// Without it this process's own loopback connection and rewritten `Host`
|
||||
/// would pass both checks those routes make.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct NonLocalCaller;
|
||||
|
||||
/// `Host` sent upstream in place of one that may name loopback, for a
|
||||
/// [`NonLocalCaller`]. A reserved name (RFC 2606), never the caller's own
|
||||
/// value: the caller controls that, and the upstream's parser may accept
|
||||
/// loopback forms this one does not.
|
||||
pub const NON_LOCAL_HOST: &str = "headroom-remote.invalid";
|
||||
|
||||
/// For a [`NonLocalCaller`]: [`NON_LOCAL_HOST`] when the `Host` that would
|
||||
/// be sent may name loopback, else `None` (keep it). That `Host` is the
|
||||
/// explicit outgoing one (`--no-rewrite-host`), else the upstream URL's
|
||||
/// authority. Judged on the value, not on the upstream address, so an
|
||||
/// upstream name that resolves to loopback cannot be paired with a
|
||||
/// loopback `Host`.
|
||||
pub(crate) fn host_override_for_non_local(
|
||||
outgoing: Option<&HeaderValue>,
|
||||
upstream: &url::Url,
|
||||
) -> Option<HeaderValue> {
|
||||
let effective = match outgoing {
|
||||
Some(h) => h.to_str().ok().map(str::to_owned),
|
||||
None => upstream.host_str().map(|h| match upstream.port() {
|
||||
Some(port) => format!("{h}:{port}"),
|
||||
None => h.to_owned(),
|
||||
}),
|
||||
};
|
||||
may_name_loopback(effective.as_deref()).then(|| HeaderValue::from_static(NON_LOCAL_HOST))
|
||||
}
|
||||
|
||||
/// Conservative superset of what the Python proxy treats as a loopback
|
||||
/// `Host`: anything [`is_loopback_host_header`] accepts, an unreadable
|
||||
/// value, and any value with an IPv6 zone (`%`), since Python's
|
||||
/// `ipaddress` accepts scoped literals such as `[::1%lo]`.
|
||||
fn may_name_loopback(value: Option<&str>) -> bool {
|
||||
match value {
|
||||
None => true,
|
||||
Some(v) => v.contains('%') || is_loopback_host_header(Some(v)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Same rules as Python's `loopback_guard.is_loopback_host_header`:
|
||||
/// `localhost`, or a loopback IP literal, with an optional port and
|
||||
/// brackets around IPv6. Missing or malformed is not loopback.
|
||||
fn is_loopback_host_header(value: Option<&str>) -> bool {
|
||||
let Some(candidate) = value.map(str::trim).filter(|v| !v.is_empty()) else {
|
||||
return false;
|
||||
};
|
||||
let host = if let Some(rest) = candidate.strip_prefix('[') {
|
||||
match rest.split_once(']') {
|
||||
Some((h, _)) => h,
|
||||
None => return false,
|
||||
}
|
||||
} else if candidate.matches(':').count() == 1 {
|
||||
candidate.rsplit_once(':').map_or(candidate, |(h, _)| h)
|
||||
} else {
|
||||
candidate
|
||||
};
|
||||
host.eq_ignore_ascii_case("localhost")
|
||||
|| host
|
||||
.parse::<IpAddr>()
|
||||
.is_ok_and(|ip| ip.to_canonical().is_loopback())
|
||||
}
|
||||
|
||||
/// Router-wide middleware. Marks every caller that is not local with
|
||||
/// [`NonLocalCaller`]. When a token is configured, a non-loopback (or
|
||||
/// unknown) peer must also present it or gets 401 with no upstream
|
||||
/// contact, and the credential is removed before forwarding.
|
||||
pub async fn inbound_gate(
|
||||
State(token): State<Option<ProxyToken>>,
|
||||
mut req: Request<Body>,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
// No ConnectInfo is no evidence of a local caller: fail closed, as
|
||||
// Python's is_loopback_host(None) does.
|
||||
let peer = req
|
||||
.extensions()
|
||||
.get::<ConnectInfo<SocketAddr>>()
|
||||
.map(|c| c.0);
|
||||
let loopback_peer = peer.as_ref().is_some_and(is_loopback);
|
||||
if let Some(token) = &token {
|
||||
// Answered here and empty, never relayed upstream without a
|
||||
// credential: the same answer the Python proxy gives it.
|
||||
if is_hello_probe(req.method(), req.uri().path()) {
|
||||
return StatusCode::OK.into_response();
|
||||
}
|
||||
if !loopback_peer && !is_health_probe(req.method(), req.uri().path()) {
|
||||
let provided = read_proxy_token(req.headers());
|
||||
if !provided.is_some_and(|p| token.matches(p)) {
|
||||
tracing::warn!(
|
||||
event = "proxy_auth_rejected",
|
||||
method = %req.method(),
|
||||
path = req.uri().path(),
|
||||
peer = ?peer,
|
||||
reason = if provided.is_none() { "missing_token" } else { "bad_token" },
|
||||
);
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({ "error": "unauthorized" })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
let headers = req.headers_mut();
|
||||
headers.remove(PROXY_TOKEN_HEADER);
|
||||
if bearer(headers).is_some_and(|b| token.matches(b)) {
|
||||
headers.remove(header::AUTHORIZATION);
|
||||
}
|
||||
}
|
||||
let host = req
|
||||
.headers()
|
||||
.get(header::HOST)
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.or_else(|| req.uri().authority().map(|a| a.as_str()));
|
||||
if !(loopback_peer && is_loopback_host_header(host)) {
|
||||
req.extensions_mut().insert(NonLocalCaller);
|
||||
}
|
||||
next.run(req).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn addr(s: &str) -> SocketAddr {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_policy_refuses_open_non_loopback_bind() {
|
||||
let err = check_bind_policy(addr("0.0.0.0:8787"), false, None).unwrap_err();
|
||||
assert!(err.contains(PROXY_TOKEN_ENV) && err.contains(OPEN_BIND_ACK_ENV));
|
||||
assert!(check_bind_policy(addr("[::]:8787"), false, Some("0")).is_err());
|
||||
assert!(check_bind_policy(addr("192.0.2.1:8787"), false, Some("")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_policy_allows_loopback_token_or_ack() {
|
||||
assert_eq!(
|
||||
check_bind_policy(addr("127.0.0.1:8787"), false, None),
|
||||
Ok(BindPolicy::Ok)
|
||||
);
|
||||
assert_eq!(
|
||||
check_bind_policy(addr("[::1]:8787"), false, None),
|
||||
Ok(BindPolicy::Ok)
|
||||
);
|
||||
assert_eq!(
|
||||
check_bind_policy(addr("0.0.0.0:8787"), true, None),
|
||||
Ok(BindPolicy::Ok)
|
||||
);
|
||||
for ack in ["1", "TRUE", " yes ", "on"] {
|
||||
assert_eq!(
|
||||
check_bind_policy(addr("0.0.0.0:8787"), false, Some(ack)),
|
||||
Ok(BindPolicy::OpenAcknowledged)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_rules_match_python() {
|
||||
assert!(ProxyToken::new(" ").is_none());
|
||||
let mut h = HeaderMap::new();
|
||||
h.insert(header::AUTHORIZATION, "BEARER abc ".parse().unwrap());
|
||||
assert_eq!(read_proxy_token(&h), Some("abc"));
|
||||
h.insert(PROXY_TOKEN_HEADER, "".parse().unwrap());
|
||||
assert_eq!(read_proxy_token(&h), None, "present-but-empty header wins");
|
||||
assert!(constant_time_eq(b"abc", b"abc"));
|
||||
assert!(!constant_time_eq(b"abc", b"abd"));
|
||||
assert!(!constant_time_eq(b"abc", b"abcd"));
|
||||
assert!(format!("{:?}", ProxyToken::new("abc").unwrap()).contains("redacted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_host_header_matches_python() {
|
||||
for ok in [
|
||||
"127.0.0.1:8787",
|
||||
"localhost",
|
||||
"LOCALHOST:1",
|
||||
"[::1]:8787",
|
||||
"::1",
|
||||
"127.1.2.3",
|
||||
] {
|
||||
assert!(is_loopback_host_header(Some(ok)), "{ok}");
|
||||
}
|
||||
for bad in [
|
||||
"",
|
||||
"evil.example",
|
||||
"evil.example:8787",
|
||||
"10.0.0.1:8787",
|
||||
"[::1",
|
||||
"localhost.evil.example",
|
||||
] {
|
||||
assert!(!is_loopback_host_header(Some(bad)), "{bad}");
|
||||
}
|
||||
assert!(!is_loopback_host_header(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_local_caller_never_gets_a_loopback_host_upstream() {
|
||||
let up = |u: &str| url::Url::parse(u).unwrap();
|
||||
let hv = |h: &str| HeaderValue::from_str(h).unwrap();
|
||||
let alias = up("http://headroom-upstream.internal:8788");
|
||||
let loopback = up("http://127.0.0.1:8788");
|
||||
// --no-rewrite-host: the caller's Host is what would be sent.
|
||||
for host in [
|
||||
"localhost",
|
||||
"127.0.0.1:8787",
|
||||
"[::1]:8787",
|
||||
"[::1%lo]:8787",
|
||||
"::1%lo",
|
||||
] {
|
||||
assert_eq!(
|
||||
host_override_for_non_local(Some(&hv(host)), &alias).unwrap(),
|
||||
NON_LOCAL_HOST,
|
||||
"{host}"
|
||||
);
|
||||
}
|
||||
// Rewritten Host on a loopback upstream: the reserved name.
|
||||
assert_eq!(
|
||||
host_override_for_non_local(None, &loopback).unwrap(),
|
||||
NON_LOCAL_HOST
|
||||
);
|
||||
// Not loopback: left alone.
|
||||
assert!(host_override_for_non_local(None, &alias).is_none());
|
||||
assert!(host_override_for_non_local(Some(&hv("proxy.example")), &loopback).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exemptions_match_python() {
|
||||
assert!(is_health_probe(&Method::GET, "/healthz"));
|
||||
assert!(is_health_probe(&Method::GET, "/readyz"));
|
||||
assert!(!is_health_probe(&Method::POST, "/readyz"));
|
||||
assert!(!is_health_probe(&Method::HEAD, "/readyz"));
|
||||
assert!(!is_health_probe(&Method::GET, "/admin/upstream"));
|
||||
assert!(!is_health_probe(&Method::GET, "/rollout/status"));
|
||||
assert!(is_hello_probe(&Method::HEAD, "/api/hello"));
|
||||
assert!(is_hello_probe(&Method::GET, "/p/demo/api/hello"));
|
||||
assert!(!is_hello_probe(&Method::GET, "/p//api/hello"));
|
||||
assert!(!is_hello_probe(&Method::POST, "/api/hello"));
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod error;
|
||||
pub mod handlers;
|
||||
pub mod headers;
|
||||
pub mod health;
|
||||
pub mod inbound_auth;
|
||||
pub mod observability;
|
||||
pub mod proxy;
|
||||
pub mod responses_items;
|
||||
|
||||
@@ -10,6 +10,7 @@ use std::net::SocketAddr;
|
||||
|
||||
use clap::Parser;
|
||||
use headroom_proxy::config::CliArgs;
|
||||
use headroom_proxy::inbound_auth::{check_bind_policy, BindPolicy, OPEN_BIND_ACK_ENV};
|
||||
use headroom_proxy::{build_app, AppState, Config};
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
@@ -22,6 +23,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
|
||||
init_tracing(&config.log_level);
|
||||
|
||||
// Same rule as the Python proxy's bind policy: no unauthenticated
|
||||
// non-loopback listener unless the operator acknowledges it.
|
||||
let ack = std::env::var(OPEN_BIND_ACK_ENV).ok();
|
||||
match check_bind_policy(config.listen, config.proxy_token.is_some(), ack.as_deref()) {
|
||||
Ok(BindPolicy::Ok) => {}
|
||||
Ok(BindPolicy::OpenAcknowledged) => tracing::warn!(
|
||||
event = "proxy_open_bind",
|
||||
listen = %config.listen,
|
||||
"non-loopback listen with no HEADROOM_PROXY_TOKEN; every peer that \
|
||||
reaches this port is relayed upstream as a loopback caller. \
|
||||
Acknowledged via HEADROOM_ALLOW_UNAUTHENTICATED_BIND"
|
||||
),
|
||||
Err(msg) => {
|
||||
eprintln!("headroom-proxy: {msg}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
listen = %config.listen,
|
||||
upstream = %config.upstream,
|
||||
|
||||
@@ -425,7 +425,17 @@ pub fn build_app(state: AppState) -> Router {
|
||||
);
|
||||
}
|
||||
|
||||
router.fallback(any(catch_all)).with_state(state)
|
||||
// Inbound gate (caller locality + optional HEADROOM_PROXY_TOKEN).
|
||||
// Applied last so it wraps every route and the fallback: the upstream
|
||||
// Python proxy sees this process as a loopback caller and cannot tell
|
||||
// who the real peer is itself.
|
||||
let router = router
|
||||
.fallback(any(catch_all))
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
state.config.proxy_token.clone(),
|
||||
crate::inbound_auth::inbound_gate,
|
||||
));
|
||||
router.with_state(state)
|
||||
}
|
||||
|
||||
/// Catch-all handler. If the request is a WebSocket upgrade, hand off to the
|
||||
@@ -647,6 +657,21 @@ pub(crate) async fn forward_http(
|
||||
outgoing_headers.insert(http::header::HOST, h.clone());
|
||||
}
|
||||
}
|
||||
// The upstream (the Python proxy) sees this process as a loopback
|
||||
// peer; never also hand it a loopback Host for a caller that is not
|
||||
// local here, or its local-only routes would treat that caller as local.
|
||||
if req
|
||||
.extensions()
|
||||
.get::<crate::inbound_auth::NonLocalCaller>()
|
||||
.is_some()
|
||||
{
|
||||
if let Some(host) = crate::inbound_auth::host_override_for_non_local(
|
||||
outgoing_headers.get(http::header::HOST),
|
||||
&state.config.upstream,
|
||||
) {
|
||||
outgoing_headers.insert(http::header::HOST, host);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── COMPRESSION GATE ──────────────────────────────────────────────
|
||||
//
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Startup bind policy, driven through the real binary.
|
||||
//!
|
||||
//! Same rule as the Python proxy (`headroom/proxy/bind_policy.py`): a
|
||||
//! non-loopback `--listen` with no `HEADROOM_PROXY_TOKEN` must not start
|
||||
//! unless `HEADROOM_ALLOW_UNAUTHENTICATED_BIND` acknowledges it.
|
||||
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
fn proxy(listen: &str) -> Command {
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_headroom-proxy"));
|
||||
cmd.args(["--listen", listen, "--upstream", "http://127.0.0.1:9"])
|
||||
.env_remove("HEADROOM_PROXY_TOKEN")
|
||||
.env_remove("HEADROOM_ALLOW_UNAUTHENTICATED_BIND")
|
||||
.env_remove("HEADROOM_PROXY_LISTEN")
|
||||
.env("HEADROOM_PROXY_STATS", "false")
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
cmd
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn non_loopback_listen_without_token_refuses_to_start() {
|
||||
let child = proxy("0.0.0.0:0").spawn().expect("spawn proxy");
|
||||
let out = tokio::time::timeout(Duration::from_secs(20), child.wait_with_output())
|
||||
.await
|
||||
.expect("proxy kept running on 0.0.0.0 with no inbound token")
|
||||
.expect("wait");
|
||||
assert!(!out.status.success());
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(stderr.contains("HEADROOM_PROXY_TOKEN"), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains("HEADROOM_ALLOW_UNAUTHENTICATED_BIND"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loopback_listen_without_token_still_starts() {
|
||||
let mut child = proxy("127.0.0.1:0").spawn().expect("spawn proxy");
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
assert!(
|
||||
child.try_wait().expect("try_wait").is_none(),
|
||||
"loopback bind must start without a token"
|
||||
);
|
||||
let _ = child.kill().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_listen_address_is_loopback() {
|
||||
use clap::Parser;
|
||||
use headroom_proxy::config::CliArgs;
|
||||
let args = CliArgs::try_parse_from(["headroom-proxy", "--upstream", "http://127.0.0.1:9"])
|
||||
.expect("parse");
|
||||
if std::env::var_os("HEADROOM_PROXY_LISTEN").is_none() {
|
||||
assert!(args.listen.ip().is_loopback(), "{}", args.listen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Inbound `HEADROOM_PROXY_TOKEN` gate.
|
||||
//!
|
||||
//! The Rust front connects to the Python proxy from `127.0.0.1`, so
|
||||
//! Python's own token gate (which exempts loopback peers) cannot see a
|
||||
//! network caller behind it. These tests pin that the Rust proxy checks
|
||||
//! the token itself, before any upstream contact, using the same
|
||||
//! credential rules as the Python gate. The app is driven with
|
||||
//! `oneshot` and an injected `ConnectInfo` so a non-loopback peer can be
|
||||
//! simulated; a real loopback-only test listener cannot produce one.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::ConnectInfo;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use headroom_proxy::inbound_auth::ProxyToken;
|
||||
use headroom_proxy::{build_app, AppState, Config};
|
||||
use tower::util::ServiceExt;
|
||||
use wiremock::matchers::any;
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
const TOKEN: &str = "s3cret-token";
|
||||
// 203.0.113.0/24 is TEST-NET-3 (RFC 5737): never loopback.
|
||||
const REMOTE: &str = "203.0.113.7:40000";
|
||||
const LOCAL: &str = "127.0.0.1:40000";
|
||||
|
||||
async fn upstream() -> MockServer {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(any())
|
||||
.respond_with(ResponseTemplate::new(200).set_body_string("upstream"))
|
||||
.mount(&server)
|
||||
.await;
|
||||
server
|
||||
}
|
||||
|
||||
async fn send(
|
||||
upstream: &MockServer,
|
||||
token: Option<&str>,
|
||||
peer: Option<&str>,
|
||||
method: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, &str)],
|
||||
) -> StatusCode {
|
||||
let mut config = Config::for_test(upstream.uri().parse().unwrap());
|
||||
config.proxy_token = token.and_then(ProxyToken::new);
|
||||
let app = build_app(AppState::new(config).unwrap());
|
||||
let mut builder = Request::builder().method(method).uri(path);
|
||||
for (k, v) in headers {
|
||||
builder = builder.header(*k, *v);
|
||||
}
|
||||
let mut req = builder.body(Body::empty()).unwrap();
|
||||
if let Some(peer) = peer {
|
||||
let addr: SocketAddr = peer.parse().unwrap();
|
||||
req.extensions_mut().insert(ConnectInfo(addr));
|
||||
}
|
||||
app.oneshot(req).await.unwrap().status()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_peer_without_token_gets_401_and_upstream_is_not_contacted() {
|
||||
let up = upstream().await;
|
||||
let status = send(
|
||||
&up,
|
||||
Some(TOKEN),
|
||||
Some(REMOTE),
|
||||
"GET",
|
||||
"/admin/upstream",
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
assert!(up.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_peer_with_wrong_token_gets_401() {
|
||||
let up = upstream().await;
|
||||
for header in [
|
||||
("x-headroom-proxy-token", "wrong"),
|
||||
("authorization", "Bearer wrong"),
|
||||
] {
|
||||
let status = send(
|
||||
&up,
|
||||
Some(TOKEN),
|
||||
Some(REMOTE),
|
||||
"POST",
|
||||
"/v1/messages",
|
||||
&[header],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED, "{header:?}");
|
||||
}
|
||||
assert!(up.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_peer_with_token_header_is_forwarded_without_it() {
|
||||
let up = upstream().await;
|
||||
let status = send(
|
||||
&up,
|
||||
Some(TOKEN),
|
||||
Some(REMOTE),
|
||||
"GET",
|
||||
"/v1/models",
|
||||
&[("x-headroom-proxy-token", TOKEN)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let seen = up.received_requests().await.unwrap();
|
||||
assert_eq!(seen.len(), 1);
|
||||
assert!(seen[0].headers.get("x-headroom-proxy-token").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_peer_with_bearer_token_is_forwarded_without_it() {
|
||||
let up = upstream().await;
|
||||
let bearer = format!("bearer {TOKEN}");
|
||||
let status = send(
|
||||
&up,
|
||||
Some(TOKEN),
|
||||
Some(REMOTE),
|
||||
"GET",
|
||||
"/v1/models",
|
||||
&[("authorization", &bearer)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let seen = up.received_requests().await.unwrap();
|
||||
assert_eq!(seen.len(), 1);
|
||||
// The proxy credential is not the provider's business.
|
||||
assert!(seen[0].headers.get("authorization").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn token_header_wins_over_a_provider_bearer() {
|
||||
// Same rule as Python's read_proxy_token: when the explicit header is
|
||||
// present, Authorization belongs to the provider and is forwarded.
|
||||
let up = upstream().await;
|
||||
let status = send(
|
||||
&up,
|
||||
Some(TOKEN),
|
||||
Some(REMOTE),
|
||||
"GET",
|
||||
"/v1/models",
|
||||
&[
|
||||
("x-headroom-proxy-token", TOKEN),
|
||||
("authorization", "Bearer provider-key"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let seen = up.received_requests().await.unwrap();
|
||||
assert_eq!(
|
||||
seen[0].headers.get("authorization").unwrap(),
|
||||
"Bearer provider-key"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loopback_peer_without_token_is_still_forwarded() {
|
||||
let up = upstream().await;
|
||||
let status = send(&up, Some(TOKEN), Some(LOCAL), "GET", "/v1/models", &[]).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(up.received_requests().await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ipv4_mapped_loopback_peer_counts_as_loopback() {
|
||||
let up = upstream().await;
|
||||
let status = send(
|
||||
&up,
|
||||
Some(TOKEN),
|
||||
Some("[::ffff:127.0.0.1]:40000"),
|
||||
"GET",
|
||||
"/v1/models",
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_peer_address_fails_closed() {
|
||||
let up = upstream().await;
|
||||
let status = send(&up, Some(TOKEN), None, "GET", "/v1/models", &[]).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
assert!(up.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_probes_stay_reachable_without_token() {
|
||||
let up = upstream().await;
|
||||
assert_eq!(
|
||||
send(&up, Some(TOKEN), Some(REMOTE), "GET", "/healthz", &[]).await,
|
||||
StatusCode::OK
|
||||
);
|
||||
assert_eq!(
|
||||
send(&up, Some(TOKEN), Some(REMOTE), "GET", "/readyz", &[]).await,
|
||||
StatusCode::OK
|
||||
);
|
||||
// Only GET is exempt, as in the Python gate: anything else on a probe
|
||||
// path would fall through to the relay.
|
||||
assert_eq!(
|
||||
send(&up, Some(TOKEN), Some(REMOTE), "POST", "/readyz", &[]).await,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_token_configured_keeps_todays_passthrough() {
|
||||
let up = upstream().await;
|
||||
let status = send(&up, None, Some(REMOTE), "GET", "/v1/models", &[]).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hello_probe_is_answered_locally_without_token() {
|
||||
let up = upstream().await;
|
||||
for method in ["GET", "HEAD"] {
|
||||
let status = send(&up, Some(TOKEN), Some(REMOTE), method, "/api/hello", &[]).await;
|
||||
assert_eq!(status, StatusCode::OK, "{method}");
|
||||
}
|
||||
assert!(up.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// `Host` the upstream received for one request.
|
||||
async fn upstream_host(
|
||||
token: Option<&str>,
|
||||
peer: &str,
|
||||
path: &str,
|
||||
headers: &[(&str, &str)],
|
||||
) -> String {
|
||||
let up = upstream().await;
|
||||
let status = send(&up, token, Some(peer), "GET", path, headers).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let seen = up.received_requests().await.unwrap();
|
||||
seen[0]
|
||||
.headers
|
||||
.get("host")
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn is_loopback_name(host: &str) -> bool {
|
||||
host.starts_with("127.") || host.starts_with("localhost") || host.starts_with("[::1]")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_caller_keeps_the_rewritten_upstream_host() {
|
||||
let host = upstream_host(
|
||||
None,
|
||||
LOCAL,
|
||||
"/admin/upstream",
|
||||
&[("host", "127.0.0.1:8787")],
|
||||
)
|
||||
.await;
|
||||
assert!(is_loopback_name(&host), "{host}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loopback_peer_with_a_foreign_host_is_not_relayed_as_local() {
|
||||
// A browser reaching the port through a name that resolves to
|
||||
// 127.0.0.1: loopback peer, foreign Host.
|
||||
let host = upstream_host(
|
||||
None,
|
||||
LOCAL,
|
||||
"/admin/upstream",
|
||||
&[("host", "evil.example:8787")],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(host, "headroom-remote.invalid");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_token_holder_is_not_relayed_as_local() {
|
||||
// `[::1%lo]` is a scoped IPv6 literal the Python proxy accepts as
|
||||
// loopback; it must not be passed through.
|
||||
for client_host in ["proxy.example:8787", "localhost:8787", "[::1%lo]:8787"] {
|
||||
let host = upstream_host(
|
||||
Some(TOKEN),
|
||||
REMOTE,
|
||||
"/admin/upstream",
|
||||
&[("x-headroom-proxy-token", TOKEN), ("host", client_host)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(host, "headroom-remote.invalid", "{client_host}");
|
||||
}
|
||||
}
|
||||
@@ -1175,3 +1175,17 @@ def test_settings_write_refused_for_trusted_gateway_peer(
|
||||
def test_settings_write_allowed_for_real_loopback() -> None:
|
||||
resp = _loopback_client().post("/settings", json={"values": {}})
|
||||
assert resp.status_code == 200, resp.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", ["headroom-remote.invalid", "evil.example:8787"])
|
||||
def test_local_only_routes_refuse_the_hosts_the_rust_front_relays_for_remote_callers(
|
||||
host: str,
|
||||
) -> None:
|
||||
# The Rust front reaches this proxy from 127.0.0.1. For a caller that is
|
||||
# not local on its side it sends a non-loopback Host (the reserved
|
||||
# headroom-remote.invalid when the Host would otherwise name loopback),
|
||||
# so these routes must refuse a loopback peer carrying such a Host.
|
||||
client = TestClient(_make_app(), base_url=f"http://{host}", client=("127.0.0.1", 12345))
|
||||
assert client.get("/admin/upstream").status_code == 404
|
||||
assert client.get("/debug/tasks").status_code == 404
|
||||
assert client.get("/transformations/feed").status_code == 404
|
||||
|
||||
Reference in New Issue
Block a user