Commit Graph
3 Commits
Author SHA1 Message Date
944eafc6d4 fix(wrap): reject saved bob gateway URLs the proxy would not route (#3975)
## Description

Follow-up to #3801, promised on its Devin threads ([path
shape](https://github.com/headroomlabs-ai/headroom/pull/3801#discussion_r4175286291),
[invalid
port](https://github.com/headroomlabs-ai/headroom/pull/3801#discussion_r4175286403)).
Both findings landed after that PR was approved, so they ship here
rather than resetting its review.

`bob_preflight` guards against a saved `~/.bob/settings/settings.json`
`gatewayUrl`, which bobshell resolves over `BOB_GATEWAY_URL` at startup.
It compared only scheme/host/port, so two classes of saved URL got
through or crashed it:

- A proxy URL with an extra path segment, query or fragment
(`http://127.0.0.1:8787/p/work/v1`, `…/p/work?team=a`) passed. Bob then
appended `/inference/v1/...` to it; `split_project_path` strips only one
`/p/<project>` segment, so the request arrived as `/v1/inference/v1/...`
and matched nothing. The wrap launched and Bob failed.
- A non-numeric port (`http://127.0.0.1:not-a-port`) made
`urlsplit(...).port` raise outside the parse `try`, so the user got a
traceback instead of the guidance.

Two helpers now answer the two questions separately: `_origin` gives
(scheme, host, port) or None for an unparsable value;
`_routable_proxy_path` is true only for a bare origin or exactly one
`/p/<project>` prefix (reusing `split_project_path`, the router's own
grammar), checked on the **decoded** path the ASGI server hands the
router (so `%2F` in the project segment counts as the extra segment it
becomes, while the `%20` that `with_project_prefix` itself emits is
fine) and with no `?`/`#` anywhere, even bare, since Bob appends to the
string. The abort message names the real problem: "could not be parsed"
/ "is not a URL the proxy can route" when it points at the proxy with a
bad shape / "would bypass the Headroom proxy" for any foreign host,
regardless of its path. A trailing slash remains accepted: bobshell's
`AJ()` collapses repeated slashes and strips a trailing one before
appending paths (verified in 2.0.5).

Closes # (no issue; follow-up to #3801)

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] 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/providers/wrap_registry.py`: `_origin_key` → `_origin` +
`_routable_proxy_path`; `bob_preflight` passes only when the saved
origin equals the proxy's and the path is routable, and picks the
message by cause. `split_project_path` is imported from
`headroom.proxy.project_context` alongside the existing
`with_project_prefix`.
- `tests/test_cli/test_wrap_bob.py`:
`TestBobPreflight::test_fails_on_non_proxy_shapes` (12 rejected shapes,
each asserting its reason: bypass / unroutable / unparsable) and
`test_unparsable_env_url_never_matches` (two `None` identities must not
compare equal). Passing cases now also cover `/p/my%20proj` and
`HTTP://LOCALHOST:8787/`.

## 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
$ PYTHONPATH=$PWD python -m pytest -q -p no:cacheprovider tests/test_cli/
981 passed, 1 skipped, 17 warnings in 19.79s

$ git stash push headroom/   # previous head's wrap_registry, new tests
$ pytest tests/test_cli/test_wrap_bob.py -k "non_proxy_shapes or unparsable_env"
5 failed, 3 passed   # the two cases already rejected by #3801 plus one message-only case pass; all new shapes fail

$ uvx ruff@0.16.8 check headroom/providers/wrap_registry.py tests/test_cli/test_wrap_bob.py
All checks passed!
$ uvx ruff@0.16.8 format --check ...
2 files already formatted
$ uvx mypy==1.20.2 headroom --ignore-missing-imports
Success: no issues found in 556 source files
```

## Real Behavior Proof

- Environment: macOS, bobshell 2.0.5, isolated `HOME` whose
`.bob/settings/settings.json` holds
`{"gatewayUrl":"http://127.0.0.1:8788/p/work/v1"}`; proxy code from each
head via `PYTHONPATH`.
- Exact command / steps: `HOME=<fakehome> PYTHONPATH=<checkout> python
-m headroom.cli wrap bob --port 8788 -- --version`, once on
`upstream/main` (`befdb52f`, contains #3801) and once on this branch.
- Observed result: main launched Bob; this branch aborted before the
spawn. Details:
- main: `Launching BOB (API routed through Headroom)...
BOB_GATEWAY_URL=http://127.0.0.1:8788/p/scratchpad` then Bob prints
`2.0.5` — the guard passed and Bob would have used the saved
`/p/work/v1` URL.
- this branch: `Error: Bob's saved gatewayUrl
(http://127.0.0.1:8788/p/work/v1) is not a URL the proxy can route (use
the bare proxy origin, optionally with one /p/<project> prefix). Remove
the gatewayUrl entry from <fakehome>/.bob/settings/settings.json ...` —
Bob never spawned.
- Not tested: a full Bob inference round trip (this change only alters
the pre-launch guard; the account's IBM plan is suspended, see #3801).

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: only `headroom wrap bob` on a machine
whose saved Bob `gatewayUrl` points at the proxy with an extra
path/query/fragment, or is unparsable. Those launches used to proceed
(and then fail inside Bob) or crash with a traceback; they now abort
with guidance.
- Kill switch / disable path: remove `gatewayUrl` from Bob's settings
(the message says so); no other wrap target has a preflight.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert the commit

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

- Documentation: n/a, the guard's behavior is explained by its own error
message.
- Self-review found and fixed, beyond the two Devin findings:
query/fragment acceptance, scheme-less/host-less URLs comparing equal to
an unparsable env URL, and the "bypass" wording being wrong for
proxy-pointing URLs.
- Deliberately unchanged: `localhost`→`127.0.0.1` normalization does not
cover `[::1]`/`0.0.0.0` (pre-existing; `with_project_prefix` only ever
emits `127.0.0.1`).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3975"
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>
2026-10-07 20:56:28 -05:00
Mansurshakh Japarov 278bbc8771 fix(wrap): warn when reused proxy ignores compression settings (#4019)
## Description

A healthy shared proxy is intentionally not restarted: doing so would
interrupt other clients. Explicit startup compression settings must not
be silently ignored when a wrapper reuses it. This implements the
issue's warning-on-reuse alternative.

Closes #3588.

## Type of Change

- [x] Bug fix
- [x] Documentation update

## Changes Made

- Expose the effective tool exclusions alongside the existing effective
minimum-token setting in `/health`.
- Warn when explicitly supplied `HEADROOM_MIN_TOKENS` or
`HEADROOM_EXCLUDE_TOOLS` differs from the running configuration.
- Compare tool names case-insensitively and include built-in exclusions
on both sides. Skip comparisons when older health responses lack the
setting or the requested integer is invalid.
- Preserve the existing mode warning and shared-proxy lifecycle.
Document startup-only configuration and the restart/separate-port
remedies.
- Query the running settings for explicit compression environment
variables even with `--no-proxy` and no explicit `HEADROOM_MODE`.

## Testing

- [x] Focused unit tests: `python -m pytest -q
tests/test_cli/test_wrap_bob.py` — **59 passed**. With current main's
dashboard-license tests: **67 passed**.
- [x] New consumer-visible warning regressions: **4 failed on unchanged
baseline**; the additional no-start/MODE-unset cases produced **2
failures before the final fix**, passing afterwards.
- [x] Changed-file Ruff and formatting checks; installed pre-commit
hooks, including `mypy headroom` and Commitlint, passed.
- [x] Manual testing performed.
- [ ] Full-tree `ruff check .`: blocked locally by EXE002 on five
unchanged OAuth2 plugin files checked out with executable filesystem
permissions (Git tracks them as 100644). No unrelated plugin files or
permissions changed.
- [ ] Separate full dev-environment `mypy headroom`: found one
`truthy-function` error in unchanged
`headroom/integrations/langchain/chat_model.py:394`. The file is
byte-identical to baseline (SHA256
`701a9fe8457907406a2b2810211c1534bc9dfcacf3d841ec4c27d56897209bc7`); the
project's isolated pre-commit mypy environment passed.

The mandatory pre-push `make ci-precheck` completed: workspace Rust
fmt/clippy/tests, native extension build/import verification, Python
gate **177 passed / 4 skipped**, and Commitlint all passed. The native
model gate used `ORT_DYLIB_PATH` pointing to the installed CPU
`libonnxruntime.so.1.26.0`; the cached Kompress parity suite matched
**21 fixtures byte-for-byte**. Implicit runtime selection did not finish
and was cancelled, not reported as a pass; explicit CPU runtime
qualification completed without skipping the cached-model assertions.

### Test Output

```text
[build_rust_extension] headroom._core build + install + verify: OK
================== 177 passed, 4 skipped, 1 warning in 7.29s ===================
✅ ci-precheck PASSED — safe to push.
```

## Real Behavior Proof

- Environment: Linux x86_64, CPython 3.13.14; original baseline
`dea9092e19385f286b7f67a64f4d85de2708d756` and final fix rebased onto
current main `1ad92f0cbc3dea27676e253588100f64a2af6994`; real CLI proxy
and real health endpoint.
- Exact command / steps: start the real proxy, then reuse it with
`HEADROOM_MODE` unset and conflicting compression settings without
starting/restarting it; commands below.
  ```sh
HEADROOM_BEACON=off HEADROOM_MIN_TOKENS=120 HEADROOM_EXCLUDE_TOOLS='' \
headroom proxy --host 127.0.0.1 --port 18795 --stateless --no-optimize \
--no-cache --no-rate-limit --no-subscription-tracking --disable-kompress
  ```
- With `HEADROOM_MODE` unset, reuse it without starting/restarting a
proxy:
  ```sh
  HEADROOM_MIN_TOKENS=2000 HEADROOM_EXCLUDE_TOOLS=Bash,Read,Grep,Glob \
python -c 'from headroom.cli.wrap import _ensure_proxy; print("RESULT",
_ensure_proxy(18795, True))'
  ```
- Before the final no-start-path fix: only `RESULT (None, 18795)`; both
explicit settings were silent. The original baseline was also silent.
- Observed result: both explicit-setting warnings appeared after the
fix; the same PID and running configuration remained unchanged. Output:
  ```text
Warning: this session requested HEADROOM_MIN_TOKENS=2000 (running: 120);
HEADROOM_EXCLUDE_TOOLS=['bash', 'glob', 'grep', 'read'] (running: []),
but those settings are fixed at proxy startup. Restart the proxy, or use
--port for a separate one.
  RESULT (None, 18795)
{"proxy_pid_before": 1231619, "proxy_pid_after": 1231619, "min_tokens":
120, "exclude_tools": [], "no_proxy": true, "explicit_mode": null}
  ```
- Not tested: an external interactive agent session or paid upstream
model request. The actual proxy process, health response, and wrapper
reuse path were exercised.

## Runtime Rollout Safety

- Rollout-managed feature(s): none; diagnostic-only wrapper fix.
- Minimum rollout channel: stable; no rollout-managed feature is
enabled.
- Stable/default behavior changed: a warning only when explicit settings
conflict with the running proxy; no configuration mutation or forced
restart.
- Kill switch / disable path: remove the conflicting explicit
environment setting, or revert the commit; no new switch.
- Unsafe override required: no.
- Qualification impact: wrapper diagnostics only; no model/compression
rollout change.
- Rollback path: revert this commit; the extra health field is additive.

## Review Readiness

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

## Checklist

- [x] Existing conventions reused; documentation updated.
- [x] Regression tests cover mismatches, matching settings, built-in
exclusions, missing fields, and invalid integers.
- [x] `CHANGELOG.md` not edited; Conventional Commit title supplied for
release-please.

The intentional warning is the requested behavior, not a new unsolicited
runtime warning. Full remote CI results will be reported by GitHub, not
inferred from local checks.
2026-10-07 14:17:35 -05:00
0b7dab47c6 feat(wrap): add headroom wrap bob for IBM Bob CLI (#3801)
## Description

Adds `headroom wrap bob` for the IBM Bob CLI as a wrap-registry target.
`BOB_GATEWAY_URL` points Bob at the proxy, and the proxy forwards to
`https://api.us-east.bob.ibm.com/inference/v1`. Bob's own
`Authorization: apikey …` credential and `~/.bob/settings` are left
untouched.

**Stacked on #3800.** Until that merges, this diff also contains its
commit. The Bob change is the last commit only (`feat(wrap): add
headroom wrap bob …`).

Bob's gateway needs three proxy seams, each declared on the target:

- **`extra_chat_routes`**: Bob posts to
`/inference/v1/chat/completions`. Without a real route that matches only
the catch-all and is forwarded **uncompressed**.
- **`origin_passthrough_prefixes`** (`/inference/`, `/admin/`, `/rag/`,
`/metrics-forwarder/`): Bob builds these paths itself against the bare
origin (inference and model info, profile and budget, the IBM
docs-search tools, telemetry). Joining them onto the `/inference` base
produces doubled or misrooted URLs
(`…/inference/inference/v1/model/info`, `…/inference/admin/v1/profile`)
that IBM's edge rejects with 403.
- **`origin_passthrough_strip_json_keys`**: Bob 2.0.1 through 2.0.5
rewrites its gateway host from `region_domain` in the
`/admin/v1/profile` response while keeping the proxy's port, so every
later request goes to an unreachable `api.<region>:<proxy-port>`. The
proxy removes that key.

Bob bills flat per token, so the target defaults `HEADROOM_MODE` to
`token`; an explicit `HEADROOM_MODE` still wins. `/health` now reports
the proxy's `mode`, and `headroom wrap` warns when it reuses a proxy
running a different mode than the session asked for. The warning applies
to every harness.

Replaces the Bob part of #3366, without its `wrap_targets.json` overlay,
and supersedes #3323.

Closes #

## Type of Change

- [x] New feature (non-breaking change that adds functionality)

## Changes Made

- `headroom/providers/wrap_registry.py`: `bare_origin` URL style;
`openai_api_url`, `extra_chat_routes`, `origin_passthrough_prefixes`,
`origin_passthrough_strip_json_keys`, `default_mode`, `preflight`
fields; the `bob` target; `bob_preflight`, which aborts the wrap when a
saved `~/.bob/settings/settings.json` `gatewayUrl` would override
`BOB_GATEWAY_URL` (bobshell re-resolves `settings.gatewayUrl ??
policy.GatewayUrl ?? env` at startup, verified in 2.0.5);
`resolve_origin_passthrough_url` /
`strip_origin_passthrough_response_keys` over a host-keyed index built
once from the static registry
- `headroom/providers/route_specs.py`: `OPENAI_HANDLER_ROUTES` gains the
registry's `extra_chat_routes`, built from static code data (no
user-file read)
- `headroom/proxy/handlers/openai.py`: catch-all passthrough uses the
origin-rooted URL for declared paths and strips declared keys from 200
JSON responses
- `headroom/proxy/server.py`: `/health` config block adds `mode`
- `headroom/cli/wrap.py`: generated commands export `default_mode` and
pass `openai_api_url`; new `_warn_proxy_mode_mismatch` on both
proxy-reuse paths
- `tests/test_cli/test_wrap_bob.py` (22 tests), including a
handler-level test that fails without the `openai.py` wiring

## 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
$ pytest tests/test_cli/ tests/test_provider_route_specs.py tests/test_agent_savings.py \
    tests/test_custom_base_passthrough_telemetry.py tests/test_compress_passthrough.py
878 passed, 1 skipped
$ pytest tests/test_cli/test_wrap_bob.py -k handler   # with openai.py reverted to the parent commit
1 failed  (upstream URL was not origin-rooted)       # -> the test guards the wiring
$ mypy headroom/cli/wrap.py headroom/providers/wrap_registry.py headroom/providers/route_specs.py
Success: no issues found in 3 source files
```

Locally, `tests/test_proxy_healthchecks.py` (where I added the `mode`
assertion) and two `tests/test_proxy_openai.py` cases fail identically
on `main`, because of a Starlette `TestClient` version mismatch in my
environment. So I checked `/health` separately through
`httpx.ASGITransport` from a loopback client:
`ProxyConfig(mode="token")` → `"mode": "token"`,
`ProxyConfig(mode="cache")` → `"mode": "cache"`.

## Real Behavior Proof

- Environment: macOS (darwin 25.6.0), Python 3.13, this branch; the real
IBM gateway, no Bob credentials
- Exact command / steps: a stub `bob` on PATH reads `/health` through
`BOB_GATEWAY_URL` and sends uncredentialed requests for Bob's three
paths; `headroom wrap bob --port 8911 -- run "fix it"` with
`HEADROOM_MODE` unset. For comparison, the same GETs sent straight to
IBM at the correct URLs and at the misrooted ones.
- Observed result: all three paths reach the correct IBM URLs.
- The child gets `BOB_GATEWAY_URL=http://127.0.0.1:8911/p/run` and
`argv=run fix it`. The proxy reports `mode: token`.
- The chat POST is logged as `outbound_request …
path=https://api.us-east.bob.ibm.com/inference/v1/chat/completions`.
Cloudflare rejects it with 403 because there are no credentials.
- `/admin/v1/profile` returns **401**, which matches the origin-rooted
URL (direct GET → 401). The misrooted `/inference/admin/v1/profile`
returns **403**.
- Not tested: a credentialed, live Bob session on this branch (it spends
IBM credits). That ran end to end on #3366, which shares these code
paths except for the removed overlay. `/inference/v1/model/info` can't
be told apart without credentials (403 either way); the handler and unit
tests cover it.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: two changes reach every proxy:
- The route `POST /inference/v1/chat/completions` is added. It
previously matched the catch-all.
- Catch-all passthrough changes only for requests whose OpenAI upstream
is the Bob gateway host.

  `/health` gains a `mode` field. Other clients behave the same.
- Kill switch / disable path: don't use `wrap bob`; the passthrough
rules only fire for the Bob gateway host
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR; no persisted state. What to monitor:
403s on `/inference` or `/admin` paths in the proxy log for Bob
sessions.

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

- Documentation: `headroom wrap bob --help` documents usage and the mode
default. There's no separate docs page, matching the other env-var wrap
targets.
- Known limitations, deliberate in this PR:
- The saved-`gatewayUrl` guard runs from `configure_launch`, after the
proxy is up, because it must see the actual port. A misconfigured
machine pays one proxy start/teardown (~2 s) before the abort; an
earlier requested-port check reintroduces the "rejected too early" case.
- Registry commands have no `--openai-api-url`; a non-us-east Bob
account needs a hand-started `headroom proxy --openai-api-url
https://api.<region>.bob.ibm.com/inference/v1` plus `--no-proxy`. The
passthrough rules now key on `.bob.ibm.com`, so that setup gets the same
path rooting and `region_domain` strip.
- `default_mode` is delivered through `HEADROOM_MODE` in the wrapper's
environment; that is the documented mode interface and what
`_start_proxy` already reads. It is also visible to the child process.
- `/inference/v1/chat/completions` is a static route on every proxy, not
gated on the upstream; no other upstream serves that path.
- After a persistent restart the mode warning queries the restarted
proxy's config; the "recovered but nothing listening" return stays
silent because there is no proxy to compare.
- Known limitation, unchanged by this PR: one proxy has one
OpenAI-family upstream and one mode. When Bob joins a shared proxy
started without the IBM upstream, wrap restarts it and repoints OpenAI
traffic for every attached client (kimi and vibe behave the same way).
Give Bob its own `--port` when running several harnesses.
- One of three PRs replacing #3366.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3801"
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 (1M context) <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-04 13:58:42 -07:00