mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): resolve the forwarded client from the right and keep settings writes loopback-only (#4847)
## Description
Two fixes for proxies run with `HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS`
(opt-in, empty by default):
1. **Client address.** The proxy took the *leftmost* `X-Forwarded-For`
element as the client. A gateway that appends to the header keeps
whatever the client itself sent on the left, so the client could pick
its own address (for example `127.0.0.1`). The client is now the
right-most hop that is not itself inside a trusted-gateway CIDR. If
every hop is trusted it falls back to the leftmost, as before.
2. **Settings writes.** A peer inside a trusted-gateway CIDR counted as
loopback in `_request_is_loopback`, so `POST /settings` and `POST
/settings/apply` (which restarts the proxy) were open to anything routed
through the gateway. That rule exists so a containerised dashboard can
show its read-only views. Writes now need a real loopback peer, or a
client inside `HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS` (the
existing #2466 path, with IP-literal Host and same-origin checks).
**Behaviour change:** someone who runs Headroom in a Docker bridge
container, sets only `HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS`, and saves
settings from the host browser via `localhost` will now get 404 on save.
Reads still work. To keep saving, add the gateway address to
`HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS` (e.g. `172.17.0.1/32`)
and open the dashboard at `http://127.0.0.1:<port>`. That path is
checked below. Without the env var nothing changes.
Fix adapted from a proposal by HetCreep.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- `headroom/proxy/forwarded_policy.py`: new `header_client()` walks
`X-Forwarded-For` from the right and skips trusted-gateway hops.
`resolve_forwarded_headers` uses it.
- `headroom/proxy/server.py`: `_request_is_loopback` /
`_request_can_view_dashboard_metadata` take `allow_gateway_peer`
(default unchanged). `POST /settings` and `POST /settings/apply` use a
new write guard with `allow_gateway_peer=False`, and so does the
same-origin guard for those routes.
- Tests: the leftmost-XFF test now expects the right-to-left resolution.
Added tests for a client-written XFF, the all-trusted fallback, settings
reads still served to a gateway peer, writes refused to a gateway peer
(both routes), and writes still allowed on loopback.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
# new tests against origin/main (c21b0813)
$ pytest tests/test_forwarded_headers.py tests/test_proxy_loopback_gating.py
FAILED tests/test_forwarded_headers.py::test_client_written_x_forwarded_for_is_not_the_client
FAILED tests/test_proxy_loopback_gating.py::test_settings_write_refused_for_trusted_gateway_peer[/settings]
FAILED tests/test_proxy_loopback_gating.py::test_settings_write_refused_for_trusted_gateway_peer[/settings/apply]
================== 3 failed, 189 passed, 5 warnings in 46.16s ==================
# this branch
$ pytest tests/test_forwarded_headers.py tests/test_proxy_loopback_gating.py tests/test_proxy_hardening.py tests/test_header_isolation.py tests/*settings* tests/*dashboard*
4 failed, 456 passed, 1 skipped
# the 4 failures are tests/test_dashboard/test_live_feed.py (Playwright, needs a live server
# on :8787: net::ERR_CONNECTION_REFUSED). They fail the same way on origin/main.
$ ruff check / ruff format --check (0.17.3) on changed files: All checks passed!
$ mypy headroom/proxy/forwarded_policy.py headroom/proxy/server.py --ignore-missing-imports
Success: no issues found in 2 source files
```
## Real Behavior Proof
- Environment: macOS, Python 3.12, `create_app(ProxyConfig(...))` driven
by Starlette TestClient with a set peer address.
`HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS=172.17.0.0/16`.
- Exact command / steps: resolve the client for peer `172.17.0.9` with
`X-Forwarded-For: 127.0.0.1, 203.0.113.9`. Then GET/POST `/settings` as
peer `172.17.0.9` with `Host: localhost:8787`, and POST as peer
`127.0.0.1`.
- Observed result:
```text
origin/main this branch
client ip 127.0.0.1 203.0.113.9
gateway peer GET /settings 200 200
gateway peer POST /settings 200 404
loopback POST /settings 200 200
```
Opt-in path: with
`HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS=172.17.0.1/32`, peer
`172.17.0.1`, `Host: 127.0.0.1:8787`, same-origin `Origin`: `POST
/settings` → 200.
- Not tested: a real Docker bridge deployment behind a real reverse
proxy.
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: see Description
- Kill switch / disable path: none needed
- Unsafe override required: no
- Qualification impact: none
- 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
- [ ] 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)
## Screenshots (if applicable)
N/A
## Additional Notes
`_auth_rejection_context` still logs the leftmost hop. That is log-only,
documented as unverified, and not used for any decision, so it is left
as is.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4847"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
d2fb350a34
commit
e15e342d9b
@@ -85,6 +85,34 @@ def header_first(value: str) -> str:
|
||||
return head.strip()
|
||||
|
||||
|
||||
def _hop_address(hop: str) -> str:
|
||||
"""Drop a port some gateways append to a hop (``1.2.3.4:5678``, ``[::1]:5678``)."""
|
||||
if hop.startswith("["):
|
||||
host, sep, _ = hop[1:].partition("]")
|
||||
return host if sep else hop
|
||||
host, sep, port = hop.partition(":")
|
||||
if sep and ":" not in port and port.isdigit():
|
||||
return host
|
||||
return hop
|
||||
|
||||
|
||||
def header_client(value: str, cidrs: tuple[Network, ...]) -> str:
|
||||
"""Return the client element of ``X-Forwarded-For``, resolved from the right.
|
||||
|
||||
A gateway that appends to the header leaves whatever the client wrote on
|
||||
the left, so walk from the rightmost element and skip trusted gateways;
|
||||
the first untrusted address is the one a trusted gateway actually saw.
|
||||
If every element is a trusted gateway, fall back to the leftmost. A port
|
||||
on a hop is dropped, so the result is an address.
|
||||
"""
|
||||
parts = [_hop_address(p.strip()) for p in value.split(",")] if value else []
|
||||
parts = [p for p in parts if p]
|
||||
for part in reversed(parts):
|
||||
if not peer_is_trusted_gateway(part, cidrs):
|
||||
return part
|
||||
return parts[0] if parts else ""
|
||||
|
||||
|
||||
def resolve_forwarded_headers(
|
||||
inputs: ForwardedHeaderInputs,
|
||||
cidrs: tuple[Network, ...],
|
||||
@@ -92,7 +120,7 @@ def resolve_forwarded_headers(
|
||||
"""Resolve client IP and sanitized forwarded headers from pure inputs."""
|
||||
trusted = peer_is_trusted_gateway(inputs.peer_host or None, cidrs)
|
||||
if trusted:
|
||||
forwarded_for = header_first(inputs.forwarded_for)
|
||||
forwarded_for = header_client(inputs.forwarded_for, cidrs)
|
||||
return ForwardedHeaderResolution(
|
||||
client_ip=forwarded_for or inputs.peer_host,
|
||||
forwarded={
|
||||
|
||||
@@ -2979,7 +2979,7 @@ def _register_memory_components(proxy: HeadroomProxy, tracker: MemoryTracker) ->
|
||||
# registered when the memory system is initialized with specific backends.
|
||||
|
||||
|
||||
def _request_is_loopback(request: Request) -> bool:
|
||||
def _request_is_loopback(request: Request, *, allow_gateway_peer: bool = True) -> bool:
|
||||
"""Return True iff the caller is on loopback by *both* peer IP and Host header.
|
||||
|
||||
Mirrors the two-gate check in :func:`loopback_guard.require_loopback`
|
||||
@@ -2988,6 +2988,9 @@ def _request_is_loopback(request: Request) -> bool:
|
||||
payload — serving sensitive sub-blocks (upstream URLs, per-request logs)
|
||||
only to loopback callers — rather than 404ing network callers that still
|
||||
have a legitimate use for the non-sensitive aggregate fields.
|
||||
|
||||
``allow_gateway_peer=False`` drops the trusted-gateway-CIDR equivalence
|
||||
below, for callers (settings writes) that need a genuine loopback peer.
|
||||
"""
|
||||
from headroom.proxy.loopback_guard import is_loopback_host, is_loopback_host_header
|
||||
|
||||
@@ -3005,6 +3008,8 @@ def _request_is_loopback(request: Request) -> bool:
|
||||
# Genuine loopback peer (native run, or curl inside the container).
|
||||
if is_loopback_host(client_host):
|
||||
return True
|
||||
if not allow_gateway_peer:
|
||||
return False
|
||||
|
||||
# Containerized dashboards: when Headroom runs in a bridge-network
|
||||
# container, a browser on the host reaches it via the container's
|
||||
@@ -3025,9 +3030,11 @@ def _request_is_loopback(request: Request) -> bool:
|
||||
def _request_can_view_dashboard_metadata(
|
||||
request: Request,
|
||||
trusted_dashboard_client_cidrs: tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...],
|
||||
*,
|
||||
allow_gateway_peer: bool = True,
|
||||
) -> bool:
|
||||
"""Authorize sensitive ``/stats`` metadata without widening admin access."""
|
||||
if _request_is_loopback(request):
|
||||
if _request_is_loopback(request, allow_gateway_peer=allow_gateway_peer):
|
||||
return True
|
||||
|
||||
from headroom.proxy.forwarded_headers import peer_is_trusted_gateway, resolve_client_ip
|
||||
@@ -4661,6 +4668,17 @@ 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 _require_loopback_or_trusted_dashboard_client_for_write(request: Request) -> None:
|
||||
"""Like the read guard, but a trusted-gateway peer is not loopback.
|
||||
|
||||
The gateway-CIDR equivalence exists for read-only dashboard views; it
|
||||
must not confer settings writes (nor /settings/apply's restart).
|
||||
"""
|
||||
if not _request_can_view_dashboard_metadata(
|
||||
request, trusted_dashboard_client_cidrs, allow_gateway_peer=False
|
||||
):
|
||||
raise HTTPException(status_code=404)
|
||||
|
||||
def _authenticated_at_gate(request: Request) -> bool:
|
||||
"""True when the security gate verified this request's proxy token.
|
||||
|
||||
@@ -4752,7 +4770,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
already an IP-literal-Host, CIDR-trusted dashboard client. Loopback
|
||||
callers keep the stricter loopback-only origin check unchanged.
|
||||
"""
|
||||
if not _request_is_loopback(request):
|
||||
if not _request_is_loopback(request, allow_gateway_peer=False):
|
||||
origin = request.headers.get("origin")
|
||||
host_header = request.headers.get("host")
|
||||
if (
|
||||
@@ -4760,7 +4778,9 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
and origin != "null"
|
||||
and host_header
|
||||
and _request_has_same_origin_or_no_provenance(request, host_header)
|
||||
and _request_can_view_dashboard_metadata(request, trusted_dashboard_client_cidrs)
|
||||
and _request_can_view_dashboard_metadata(
|
||||
request, trusted_dashboard_client_cidrs, allow_gateway_peer=False
|
||||
)
|
||||
):
|
||||
return
|
||||
_require_same_origin(request)
|
||||
@@ -4979,7 +4999,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
@app.post(
|
||||
"/settings",
|
||||
dependencies=[
|
||||
Depends(_require_loopback_or_trusted_dashboard_client),
|
||||
Depends(_require_loopback_or_trusted_dashboard_client_for_write),
|
||||
Depends(_require_same_origin_or_trusted_dashboard_client),
|
||||
],
|
||||
)
|
||||
@@ -5029,7 +5049,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
|
||||
@app.post(
|
||||
"/settings/apply",
|
||||
dependencies=[
|
||||
Depends(_require_loopback_or_trusted_dashboard_client),
|
||||
Depends(_require_loopback_or_trusted_dashboard_client_for_write),
|
||||
Depends(_require_same_origin_or_trusted_dashboard_client),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -342,8 +342,10 @@ def test_comma_whitespace_tolerance_in_env(
|
||||
assert resolve_client_ip(req) == "203.0.113.7", f"peer={peer}"
|
||||
|
||||
|
||||
def test_x_forwarded_for_takes_leftmost(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""``X-Forwarded-For: client, p1, p2`` → leftmost is the origin."""
|
||||
def test_x_forwarded_for_skips_trusted_gateways_from_the_right(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""``X-Forwarded-For: client, p1, p2`` → first untrusted hop from the right."""
|
||||
monkeypatch.setenv(TRUSTED_GATEWAY_CIDRS_ENV, "10.0.0.0/8")
|
||||
req = _fake_request(
|
||||
peer_host="10.0.0.5",
|
||||
@@ -497,3 +499,41 @@ def test_integration_non_ip_peer_fails_gate(
|
||||
body = resp.json()
|
||||
assert body["client_ip"] == "testclient"
|
||||
assert body["forwarded"] == {"for": "", "proto": "", "host": ""}
|
||||
|
||||
|
||||
def test_client_written_x_forwarded_for_is_not_the_client(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""An appending gateway keeps the client's own header on the left."""
|
||||
monkeypatch.setenv(TRUSTED_GATEWAY_CIDRS_ENV, "10.0.0.0/8")
|
||||
req = _fake_request(
|
||||
peer_host="10.0.0.5",
|
||||
forwarded_for="127.0.0.1, 203.0.113.9", # client wrote 127.0.0.1; gateway added .9
|
||||
)
|
||||
assert resolve_client_ip(req) == "203.0.113.9"
|
||||
|
||||
|
||||
def test_x_forwarded_for_all_trusted_falls_back_to_leftmost(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv(TRUSTED_GATEWAY_CIDRS_ENV, "10.0.0.0/8")
|
||||
req = _fake_request(peer_host="10.0.0.5", forwarded_for="10.1.1.1, 10.0.0.99")
|
||||
assert resolve_client_ip(req) == "10.1.1.1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("forwarded_for", "expected"),
|
||||
[
|
||||
("198.51.100.7, 10.0.0.99:50123", "198.51.100.7"),
|
||||
("198.51.100.7:4711, 10.0.0.99", "198.51.100.7"),
|
||||
("[2001:db8::7]:4711, 10.0.0.99:50123", "2001:db8::7"),
|
||||
("2001:db8::7, 10.0.0.99", "2001:db8::7"),
|
||||
],
|
||||
)
|
||||
def test_x_forwarded_for_hops_with_ports(
|
||||
monkeypatch: pytest.MonkeyPatch, forwarded_for: str, expected: str
|
||||
) -> None:
|
||||
"""Gateways that append ``IP:port`` are still recognised and skipped."""
|
||||
monkeypatch.setenv(TRUSTED_GATEWAY_CIDRS_ENV, "10.0.0.0/8")
|
||||
req = _fake_request(peer_host="10.0.0.5", forwarded_for=forwarded_for)
|
||||
assert resolve_client_ip(req) == expected
|
||||
|
||||
@@ -1119,3 +1119,40 @@ def test_metrics_token_authenticated_network_caller_allowed(
|
||||
assert network.get("/metrics").status_code == 401
|
||||
ok = network.get("/metrics", headers={"Authorization": "Bearer s3cr3t-token"})
|
||||
assert ok.status_code == 200, ok.text
|
||||
|
||||
|
||||
def _gateway_peer_client(monkeypatch: pytest.MonkeyPatch, **kwargs) -> TestClient:
|
||||
monkeypatch.setenv("HEADROOM_PROXY_TRUSTED_GATEWAY_CIDRS", "172.17.0.0/16")
|
||||
monkeypatch.delenv("HEADROOM_PROXY_TRUSTED_DASHBOARD_CLIENT_CIDRS", raising=False)
|
||||
return TestClient(
|
||||
_make_app(), base_url="http://localhost:8787", client=("172.17.0.9", 1), **kwargs
|
||||
)
|
||||
|
||||
|
||||
def test_settings_read_still_served_to_trusted_gateway_peer(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The gateway-CIDR rule exists so a containerised dashboard can read."""
|
||||
client = _gateway_peer_client(monkeypatch)
|
||||
assert client.get("/settings").status_code == 200
|
||||
assert client.get("/settings/schema").status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/settings", "/settings/apply"])
|
||||
def test_settings_write_refused_for_trusted_gateway_peer(
|
||||
monkeypatch: pytest.MonkeyPatch, path: str
|
||||
) -> None:
|
||||
"""A gateway-CIDR peer is loopback-equivalent for reads only, never writes."""
|
||||
from headroom.install import runtime as install_runtime
|
||||
|
||||
# Safety net: if the guard regresses, /settings/apply must not restart anything.
|
||||
monkeypatch.setattr(install_runtime, "restart_current_deployment", lambda: {"restarted": False})
|
||||
monkeypatch.setattr(install_runtime, "detect_current_deployment", lambda: (None, "foreground"))
|
||||
client = _gateway_peer_client(monkeypatch)
|
||||
resp = client.post(path, json={"values": {}})
|
||||
assert resp.status_code == 404, resp.text
|
||||
|
||||
|
||||
def test_settings_write_allowed_for_real_loopback() -> None:
|
||||
resp = _loopback_client().post("/settings", json={"values": {}})
|
||||
assert resp.status_code == 200, resp.text
|
||||
|
||||
@@ -238,7 +238,7 @@ def test_stats_recent_requests_includes_cost_usd(monkeypatch) -> None:
|
||||
monkeypatch.setattr(proxy.cost_tracker, "estimate_cost", lambda **_: 0.0135)
|
||||
# recent_requests is served only to loopback callers; TestClient's peer
|
||||
# host is "testclient", so force the loopback branch (not under test).
|
||||
monkeypatch.setattr("headroom.proxy.server._request_is_loopback", lambda request: True)
|
||||
monkeypatch.setattr("headroom.proxy.server._request_is_loopback", lambda request, **_: True)
|
||||
proxy.logger._logs.append(_sample_log())
|
||||
|
||||
resp = client.get("/stats")
|
||||
@@ -257,7 +257,7 @@ def test_stats_recent_requests_carry_turn_id_beyond_raw_log_tail(monkeypatch) ->
|
||||
with TestClient(app) as client:
|
||||
proxy = client.app.state.proxy
|
||||
monkeypatch.setattr(proxy.cost_tracker, "estimate_cost", lambda **_: 0.001)
|
||||
monkeypatch.setattr("headroom.proxy.server._request_is_loopback", lambda request: True)
|
||||
monkeypatch.setattr("headroom.proxy.server._request_is_loopback", lambda request, **_: True)
|
||||
for i in range(20):
|
||||
proxy.logger._logs.append(_sample_log(f"hr_test_{i:06d}", turn_id=f"turn_{i // 4}"))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user