Files
headroom/tests/test_proxy/test_factory_decoy_proof.py
bb8d18a56a feat(wrap): add headroom wrap droid for Factory Droid (#4143)
## Description

Add `headroom wrap droid` so Factory subscription traffic, including
Droid Core, can be compressed on the existing Factory plan.

Droid ignores `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` for
Factory-served models. It honors `FACTORY_API_BASE_URL`. This wrapper
points that at the local proxy and gives the proxy a Factory upstream
(`--factory-api-url` / `FACTORY_TARGET_API_URL`, default
`https://api.factory.ai`).

With a Factory upstream configured the proxy registers:

- `POST /api/llm/a/v1/messages` — compressed with the existing Anthropic
pipeline and forwarded to `{factory}/api/llm/a/v1/messages`. A
client-sent `x-headroom-base-url` is ignored. `x-headroom-*` headers are
stripped. Operator Anthropic extra headers are withheld from the
untrusted Factory host.
- Every other `/api/*` path — forwarded verbatim to Factory, except
Hermes Studio's scoped prefixes and requests that name their own
`x-headroom-base-url`.

Nothing outside `/api/` is sent to Factory.
`select_passthrough_base_url` and `upstream_trust` are untouched, so a
leftover Codex, Claude, or Copilot config pointed at a Factory-mode
proxy keeps its own upstream and credentials. That is the deliberate
difference from https://github.com/headroomlabs-ai/headroom/pull/2352,
which is still open and which this does not close. #2352 sends every
unrouted request on a Factory-mode proxy to Factory.

`wrap droid` writes no Droid config. It threads `factory_api_url`
through the existing proxy-reuse logic. With `--no-proxy` it refuses
unless `/health` shows a Headroom proxy serving the same Factory
upstream. OpenAI-shaped `/api/llm/o/*` traffic is forwarded
uncompressed. Those routes are deferred.

This commit is `74c889fb` rebased onto current `main` (`0dd8e0b5`). The
only conflicts were `docs/content/docs/meta.json` (kept both the new
`hermes` page and `droid`) and the `--no-proxy` branch in
`headroom/cli/wrap.py` (kept upstream's OpenAI upstream check and the
Factory check).

Refs #2351

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom wrap droid` sets `FACTORY_API_BASE_URL` to the local proxy
and resolves the Factory upstream from `--factory-api-url`, then
`FACTORY_API_BASE_URL`, then `https://api.factory.ai`. Loopback,
credential, query, and fragment URLs are rejected.
- Factory inference and `/api/*` passthrough routes are registered only
when a Factory upstream is configured. The default proxy is unchanged.
- `/health` reports `factory_api_url`.
- Docs: `docs/content/docs/droid.mdx`.

## Testing

- [x] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

Rebased tree `/home/hermes/workspace/headroom-rebase` at `0dd8e0b5`,
importing that tree via `PYTHONPATH` and the existing venv at
`/home/hermes/workspace/headroom/.venv` (Python 3.11.16).

```text
tests/test_cli/test_wrap_droid.py ............................           [ 31%]
tests/test_provider_droid_runtime.py ................................    [ 66%]
```

60 passed. Those are the wrap launch-env tests and the Factory runtime
tests.

`tests/test_proxy/test_factory_decoy_proof.py` did not complete in this
worktree. The proxy refuses to start because `headroom._core` is not
built here (`ModuleNotFoundError`, exit 78). Setting
`HEADROOM_REQUIRE_RUST_CORE=false` still did not finish within 180s. The
decoy proof (decoy upstream stays silent, Factory stand-in receives the
inference request, spoofed `x-headroom-*` headers, REST passthrough,
`--no-proxy` refusals) was written for this change and passed in the
pre-rebase review session. It was not re-run to a green result after
this rebase.

`ruff` and `mypy` were not re-run after the rebase.

## Real Behavior Proof

- Environment: Linux, Python 3.11.16, rebased commit `0dd8e0b5` on top
of `upstream/main` `8c1beb20`. No Factory token. No call to
`api.factory.ai`.
- Exact command / steps:
`PYTHONPATH=/home/hermes/workspace/headroom-rebase
/home/hermes/workspace/headroom/.venv/bin/python -m pytest
tests/test_cli/test_wrap_droid.py tests/test_provider_droid_runtime.py`
- Observed result: 60 passed.
- Not tested: a live Factory subscription, `droid` itself, the socket
decoy proof on this rebased commit (blocked locally by the missing Rust
extension), `ruff`, `mypy`, and CI on GitHub.

## Runtime Rollout Safety

- Rollout-managed feature(s): none. Factory routes register only when
`factory_api_url` / `--factory-api-url` is set.
- Minimum rollout channel: stable. Default proxy behavior is unchanged.
- Stable/default behavior changed: no, unless a Factory upstream is
configured.
- Kill switch / disable path: do not pass `--factory-api-url` and do not
set `FACTORY_TARGET_API_URL`. `wrap droid` is opt-in.
- Unsafe override required: no.
- Qualification impact: none on the default proxy.
- Rollback path: revert this commit. No config is written into Droid.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

The pre-rebase commit `74c889fb` was approved by a fresh Claude Opus 5.5
high review with an empty blocking list. This commit is that change
rebased onto current main. The two conflict resolutions are described
above and have not had a second Opus pass.

## 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
- [ ] 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

Does not close #2352. That PR is the prior attempt. This one is a
current-main rebuild with the catch-all leak removed: only `/api/*` is
forwarded to Factory.

akbarkanso is not a Headroom maintainer. Please do not expect this
account to merge.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4143"
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 -->

### Maintainer current-main requalification

Exact head `e28dfe6422dfcb9b2cbd5ce0fe673196d3b6ad40`, upstream main
`e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`.

Updated against upstream/main e4a60ed7. Resolved the OpenAI passthrough
overlap by retaining main's prepared-request/model/timing parameters and
soft-passthrough guard alongside the contributor's verbatim flag;
generic compression requires both guards to permit it. Re-reviewed
Factory direct-routing/verbatim semantics and existing discussion. All
93 wrapper/runtime/Factory passthrough/socket-decoy tests pass with
existing native extension; changed-file Ruff lint/format and whitespace
checks pass. No contributor routing policy was rewritten.

Independently reran the official Droid1.3.0 CLI with isolated home,
dummy API key, actual Headroom/Uvicorn proxy and controlled LAN HTTP
upstream on this exact combined head. The CLI consumed the controlled
Anthropic SSE reply and exited zero with HEADROOM_QUALIFICATION_OK. The
message request preserved dummy Authorization and forwarded no
x-headroom headers. This is controlled transport/runtime qualification,
not a live Factory subscription or savings benchmark, and not a fresh
native build. Applied shared test-only Gemini fixture repair for
independently established main failures; all ten cases pass. Formal
approval awaits exact-head hosted qualification.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.


### Maintainer current-main requalification

Exact head `7dd0725a9ac4dd8103dedf78552ceca886fc3620`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Clean mechanical merge with upstream main
c01cf07d94. Re-reviewed current
Factory/Droid routing and author/Devin discussion. Factory inference
retains force_direct to bypass translating backends; Factory passthrough
retains verbatim alongside main's soft-passthrough/prepared-request
guards. Hermes scoped proxy prefixes remain excluded from Factory
dispatch; the existing standalone environment precedence is
intentionally consistent with sibling targets, while Click/wrap retain
flag precedence. No contributor routing policy rewritten.

Fresh wrapper/runtime/Factory passthrough/socket-decoy/Hermes
verification: 100 passed, with test-client/runpy warnings only. All 14
changed Python files pass Ruff lint/format; main-relative whitespace
clean and owned tree clean. Tests use the current-main native DLL for
local startup. Earlier official Droid 1.3.0 controlled-upstream runtime
proof remains scoped to its original run; no fresh official CLI replay,
Factory subscription inference, savings benchmark or branch-native build
is claimed. No new blocker found; approval awaits exact-head hosted
checks. Nothing merged.


Exact-head hosted checks are being handled by maintainers. No new
finding in the reviewed scope; formal approval awaits exact-head hosted
qualification; nothing merged.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-07 20:48:53 -06:00

347 lines
12 KiB
Python

"""Local decoy proof for Factory Droid routing, over real sockets.
Two local HTTP servers stand in for the outside world:
* a **decoy**, configured as the proxy's Anthropic and OpenAI upstream (and
allowlisted as a client-named base), which must stay silent for every
Factory-bound request, and
* a **Factory stand-in**, configured as ``factory_api_url``, which must
receive Droid's inference request and its non-inference REST calls.
The proxy runs under a real uvicorn server. ``headroom wrap droid --no-proxy``
then probes real listeners and either refuses or launches a fake ``droid``
executable. Nothing here contacts Factory or needs a Factory token.
"""
from __future__ import annotations
import json
import os
import signal
import socket
import stat
import sys
import threading
import time
from collections.abc import Iterator
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
import pytest
pytest.importorskip("fastapi")
httpx = pytest.importorskip("httpx")
uvicorn = pytest.importorskip("uvicorn")
from click.testing import CliRunner # noqa: E402
from headroom.cli.main import main # noqa: E402
from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
MESSAGES = "/api/llm/a/v1/messages"
UNCONTACTED_FACTORY = "https://factory.invalid"
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return int(sock.getsockname()[1])
@dataclass
class _Seen:
method: str
path: str
headers: dict[str, str]
body: bytes
@dataclass
class _Upstream:
name: str
server: ThreadingHTTPServer
seen: list[_Seen] = field(default_factory=list)
@property
def url(self) -> str:
return f"http://127.0.0.1:{self.server.server_address[1]}"
def _start_upstream(name: str) -> _Upstream:
upstream: _Upstream
class _Handler(BaseHTTPRequestHandler):
def _serve(self) -> None:
length = int(self.headers.get("content-length") or 0)
body = self.rfile.read(length) if length else b""
upstream.seen.append(
_Seen(
self.command,
self.path,
{k.lower(): v for k, v in self.headers.items()},
body,
)
)
if self.path.split("?")[0].endswith("/v1/messages"):
reply: dict[str, Any] = {
"id": "msg_1",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-4-5",
"content": [{"type": "text", "text": f"from {name}"}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 10, "output_tokens": 3},
}
else:
reply = {"served_by": name, "path": self.path}
payload = json.dumps(reply).encode()
self.send_response(200)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
do_GET = do_POST = do_PATCH = do_PUT = do_DELETE = _serve
def log_message(self, *args: Any) -> None:
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
server.daemon_threads = True
upstream = _Upstream(name, server)
threading.Thread(target=server.serve_forever, daemon=True).start()
return upstream
class _ProxyThread:
def __init__(self, config: ProxyConfig) -> None:
self.port = _free_port()
config.port = self.port
self.server = uvicorn.Server(
uvicorn.Config(
create_app(config),
host="127.0.0.1",
port=self.port,
log_level="warning",
loop="asyncio",
lifespan="on",
ws="none",
)
)
self.thread = threading.Thread(target=self.server.run, daemon=True)
@property
def url(self) -> str:
return f"http://127.0.0.1:{self.port}"
def start(self) -> None:
self.thread.start()
deadline = time.perf_counter() + 30.0
while time.perf_counter() < deadline:
if self.server.started:
return
time.sleep(0.05)
raise RuntimeError("proxy failed to start within 30s")
def stop(self) -> None:
self.server.should_exit = True
self.thread.join(timeout=10.0)
def _config(**overrides: Any) -> ProxyConfig:
base: dict[str, Any] = {
"optimize": True,
"cache_enabled": False,
"rate_limit_enabled": False,
"cost_tracking_enabled": False,
"log_requests": False,
}
base.update(overrides)
return ProxyConfig(**base)
@dataclass
class _Stack:
decoy: _Upstream
factory: _Upstream
factory_proxy: _ProxyThread
plain_proxy: _ProxyThread
uncontacted_factory_proxy: _ProxyThread
@pytest.fixture
def stack(monkeypatch: pytest.MonkeyPatch, tmp_path) -> Iterator[_Stack]:
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
# Allowlist the loopback decoy as a client-named base, so a spoofed
# x-headroom-base-url pointing at it would pass the SSRF guard if it were
# honoured. The decoy staying silent then proves the route ignores it.
monkeypatch.setenv("HEADROOM_ALLOWED_BASE_URLS", "127.0.0.1")
for name in ("FACTORY_API_BASE_URL", "FACTORY_TARGET_API_URL"):
monkeypatch.delenv(name, raising=False)
saved_signals = {
sig: signal.getsignal(sig)
for sig in (signal.SIGINT, signal.SIGTERM, getattr(signal, "SIGHUP", None))
if sig is not None
}
decoy = _start_upstream("decoy")
factory = _start_upstream("factory")
# Provider targets are process-wide, so every in-process proxy gets the
# decoy; otherwise the last one created would reset them to the public
# defaults and stray traffic would leave the machine.
decoy_targets = {"anthropic_api_url": decoy.url, "openai_api_url": decoy.url}
proxies = [
_ProxyThread(_config(factory_api_url=factory.url, **decoy_targets)),
_ProxyThread(_config(**decoy_targets)),
_ProxyThread(_config(factory_api_url=UNCONTACTED_FACTORY, **decoy_targets)),
]
try:
for proxy in proxies:
proxy.start()
yield _Stack(decoy, factory, *proxies)
finally:
for proxy in proxies:
proxy.stop()
decoy.server.shutdown()
factory.server.shutdown()
for sig, handler in saved_signals.items():
signal.signal(sig, handler)
def test_inference_reaches_factory_stand_in_and_decoy_stays_silent(stack: _Stack) -> None:
body = {
"model": "claude-sonnet-4-5",
"max_tokens": 16,
"messages": [{"role": "user", "content": "lorem ipsum dolor " * 400}],
}
response = httpx.post(
f"{stack.factory_proxy.url}{MESSAGES}",
headers={
"authorization": "Bearer fk-local-dummy",
"anthropic-version": "2023-06-01",
# Spoofed Headroom control headers: none may redirect the request.
"x-headroom-base-url": stack.decoy.url,
"x-headroom-provider": "openai",
"x-headroom-target": stack.decoy.url,
},
json=body,
timeout=60,
)
assert response.status_code == 200, response.text
assert response.json()["content"][0]["text"] == "from factory"
assert stack.decoy.seen == []
[seen] = stack.factory.seen
assert (seen.method, seen.path) == ("POST", MESSAGES)
assert seen.headers["authorization"] == "Bearer fk-local-dummy"
assert not [k for k in seen.headers if k.startswith("x-headroom-")]
def test_non_inference_factory_paths_pass_through(stack: _Stack) -> None:
get = httpx.get(
f"{stack.factory_proxy.url}/api/sessions?limit=5",
headers={"authorization": "Bearer fk-local-dummy"},
timeout=30,
)
patch = httpx.patch(
f"{stack.factory_proxy.url}/api/sessions/s1",
headers={"authorization": "Bearer fk-local-dummy"},
content=b'{"title":"x"}',
timeout=30,
)
assert get.json() == {"served_by": "factory", "path": "/api/sessions?limit=5"}
assert patch.json()["served_by"] == "factory"
assert [(s.method, s.path) for s in stack.factory.seen] == [
("GET", "/api/sessions?limit=5"),
("PATCH", "/api/sessions/s1"),
]
assert stack.factory.seen[1].body == b'{"title":"x"}'
assert stack.decoy.seen == []
def test_unmatched_traffic_never_reaches_factory(stack: _Stack) -> None:
unrouted = httpx.get(
f"{stack.factory_proxy.url}/totally/unrouted",
headers={"authorization": "Bearer sk-other-tool"},
timeout=30,
)
hermes = httpx.post(
f"{stack.factory_proxy.url}/api/codex-proxy/s1/v1/responses",
headers={"authorization": "Bearer sk-hermes"},
json={"model": "gpt-4o-mini", "input": "hi"},
timeout=30,
)
assert unrouted.json()["served_by"] == "decoy"
assert hermes.json()["served_by"] == "decoy"
assert stack.factory.seen == []
assert [s.path for s in stack.decoy.seen] == [
"/totally/unrouted",
"/api/codex-proxy/s1/v1/responses",
]
@pytest.fixture
def fake_droid(tmp_path, monkeypatch: pytest.MonkeyPatch):
record = tmp_path / "droid-env.txt"
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
script = bin_dir / "droid"
script.write_text(f'#!/bin/sh\nprintf "%s" "$FACTORY_API_BASE_URL" > "{record}"\n')
script.chmod(script.stat().st_mode | stat.S_IXUSR)
if sys.platform == "win32":
# `shutil.which("droid")` ignores the extensionless script on Windows
# but finds `droid.cmd` via PATHEXT. Python does the write so the
# record has no trailing newline, matching `printf "%s"`.
write = (
"import os, pathlib, sys; "
"pathlib.Path(sys.argv[1]).write_text(os.environ.get('FACTORY_API_BASE_URL', ''))"
)
(bin_dir / "droid.cmd").write_bytes(
f'@echo off\r\n"{sys.executable}" -c "{write}" "{record}"\r\n'.encode()
)
monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}")
return record
def _wrap_droid_no_proxy(port: int, upstream: str):
return CliRunner().invoke(
main,
["wrap", "droid", "--no-proxy", "--port", str(port), "--factory-api-url", upstream],
)
def test_no_proxy_refuses_non_factory_listener(stack: _Stack, fake_droid) -> None:
result = _wrap_droid_no_proxy(stack.plain_proxy.port, UNCONTACTED_FACTORY)
assert result.exit_code != 0
assert "--no-proxy requires a Headroom proxy" in result.output
assert not fake_droid.exists()
def test_no_proxy_refuses_mismatched_factory_listener(stack: _Stack, fake_droid) -> None:
result = _wrap_droid_no_proxy(
stack.uncontacted_factory_proxy.port, "https://eu.factory.example"
)
assert result.exit_code != 0
assert "--no-proxy requires a Headroom proxy" in result.output
assert not fake_droid.exists()
def test_no_proxy_refuses_absent_listener(stack: _Stack, fake_droid) -> None:
result = _wrap_droid_no_proxy(_free_port(), UNCONTACTED_FACTORY)
assert result.exit_code != 0
assert not fake_droid.exists()
def test_no_proxy_launches_against_matching_listener(stack: _Stack, fake_droid) -> None:
port = stack.uncontacted_factory_proxy.port
result = _wrap_droid_no_proxy(port, f"{UNCONTACTED_FACTORY}/")
assert result.exit_code == 0, result.output
assert fake_droid.read_text() == f"http://127.0.0.1:{port}"