Commit Graph
2 Commits
Author SHA1 Message Date
Tejas ChopraandClaude Fable 5.1 9d98ea5908 fix(rust-proxy): forward request paths verbatim and pin the rustls provider (#3853)
## Summary

VAPT-readiness findings **03-F2** (Bedrock/Vertex path traversal to a
signed request, previously *unverified* — now **confirmed** by the tests
below), **03-F3** (`join_upstream_path` base-prefix escape), **03-F1**
(rustls provider panic on `wss://`) and part of **03-F9** (lint
posture). Rust `headroom-proxy` only; the Python wheel is untouched.

**Problem.** `url::Url::set_path` resolves `.`/`..` (also `%2e`) and
folds `\\` into `/`. So a client could walk out of a tenant base prefix
on the generic forwarder, move a **SigV4-signed** Bedrock request to
another resource (`/model/../invoke`), or move an **ADC-signed** Vertex
request to another project. Bedrock also re-interpolated the URL-decoded
`model_id`, so an inference-profile ARN (contains `/`) became two
segments and a hostile id gained segments.

**Fix, one generic module rather than per-provider patches.** New
`crates/headroom-proxy/src/upstream_path.rs`, used by every upstream URL
builder (forwarder, Bedrock invoke + streaming, Vertex, WebSocket
upgrade):
- `join_request_path` rejects any raw path the URL parser would rewrite
and asserts the result still sits under the configured base prefix (400
before anything is signed or sent).
- `append_segments` rebuilds provider paths segment by segment from
decoded route parameters, percent-encoding `/` so an ARN stays one `%2F`
segment, and rejecting `.`, `..`, empty and control-character segments.
Side effect: a `bedrock_endpoint` with a path prefix now keeps that
prefix.

Also:
- ring is installed as the **process-wide** rustls `CryptoProvider` in
`AppState::new`. The binary links both ring and aws-lc-rs, and rustls
panics in `ClientConfig::builder()` without a default. Main already
names ring explicitly for the `wss://` relay (#3831), so that path no
longer panics there; this makes every present and future TLS client in
the process safe and adds the first end-to-end `wss://` relay test
(rcgen certificate generated at test time, trusted via
`HEADROOM_CA_BUNDLE`).
- `#![forbid(unsafe_code)]` on the four crates that have no `unsafe`
today; `overflow-checks = true` in the release profile for the proxy
package only.

## Reproduction / regression tests

`tests/integration_path_traversal.rs` (6) and
`tests/integration_ws_tls.rs` (2), mock upstream records the path it
receives.

Against **origin/main** (test files copied over, test-only crates
added):
```
thread 'forwarder_keeps_requests_under_the_base_prefix' (653400) panicked at crates/headroom-proxy/tests/integration_path_traversal.rs:103:9:
assertion `left == right` failed: /../tenant-b/v1/models must be rejected
  left: 200
 right: 400
thread 'websocket_upgrade_with_traversal_path_is_rejected_before_upgrade' (653402) panicked at crates/headroom-proxy/tests/integration_path_traversal.rs:130:5:
assertion `left == right` failed: a traversal path must not be upgraded (101)
  left: 404
 right: 400
thread 'vertex_dot_segment_project_is_rejected_unsigned' (653401) panicked at crates/headroom-proxy/tests/integration_path_traversal.rs:269:5:
assertion `left == right` failed
  left: 200
 right: 400
thread 'bedrock_streaming_dot_segment_model_id_is_rejected_unsigned' (653399) panicked at crates/headroom-proxy/tests/integration_path_traversal.rs:246:9:
assertion `left == right` failed: /model/../invoke-with-response-stream must be rejected
  left: 200
 right: 400
thread 'bedrock_dot_segment_model_id_is_rejected_unsigned' (653397) panicked at crates/headroom-proxy/tests/integration_path_traversal.rs:172:9:
assertion `left == right` failed: /model/../invoke must be rejected
  left: 200
 right: 400
thread 'bedrock_encoded_slashes_in_model_id_stay_one_segment' (653398) panicked at crates/headroom-proxy/tests/integration_path_traversal.rs:203:5:
traversal reached the upstream: ["/guardrail/GID/version/1/apply/invoke"]
test result: FAILED. 0 passed; 6 failed
```
The last line is the important one: on main a crafted `model_id` made
the proxy sign and send a request to
`/guardrail/GID/version/1/apply/invoke`.

`integration_ws_tls.rs` **passes on main as well**: the explicit-ring
fix in #3831 already covers the relay, and test builds unify crypto
features differently from the release binary, so these two tests guard
the behaviour but do not reproduce the original panic. Stated plainly so
nobody counts them as fail-before.

On this branch: `cargo test -p headroom-proxy` **498 passed, 0 failed**;
`cargo clippy -p headroom-proxy --all-targets -- -D warnings` clean;
`cargo fmt --all -- --check` clean.

## Real behavior proof

The integration tests run the real proxy router in-process against a
real local HTTP upstream and a real TLS WebSocket upstream; the
traversal assertions are on the path the upstream actually received.
**Not tested:** a live Bedrock or Vertex endpoint (no credentials used),
the release binary's startup against a live `wss://` provider, and the
`overflow-checks` performance cost (no benchmark run; expected to be
small on the proxy, which is I/O bound). The Rust proxy ships only in
the OSS core image, not in the enterprise wheelhouse.

## Behaviour change / release note

Requests whose path contains dot-segments, encoded dot-segments or
backslashes, or that would leave the configured base prefix, now get
**400** instead of being normalised and forwarded. Bedrock model ids
containing `/` (inference-profile ARNs) are now sent as one encoded
segment, which is what the Bedrock API expects.

## Decision assumed

None. Not done here from the original item: workspace-level clippy
`unwrap_used`/`expect_used` warnings (left for a separate, noisier PR).

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

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 14:10:33 -05:00
JD Davis 2c9eb7c5f1 feat(simulators): add provider simulator service (#2014)
## Description  
Adds a Rust-only `headroom-simulators` workspace crate: a deterministic
local upstream simulator service for Headroom proxy and pipeline
validation. It supplies configurable stubs plus bottled provider-shaped
responses for supported provider/path surfaces without calling real
LLMs.

## Type of Change  
- [x] 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)
- [x] Documentation update  
- [ ] Performance improvement  
- [ ] Code refactoring (no functional changes)

## Changes Made  
- Added `crates/headroom-simulators` Rust crate with library and
`headroom-simulators` binary.
- Added clean domain classification for supported surfaces: Anthropic
`/v1/messages`, OpenAI chat/responses/conversations, Bedrock
invoke/stream routes, Vertex raw/stream predict, health, and generic
fallback.
- Added JSON-configured stub matching by method, path, body substring,
and JSON pointer.
- Added bottled provider-shaped JSON, SSE, and Bedrock EventStream
responses for unconfigured requests.
- Added a container `Dockerfile` and README for local/GitHub Actions
usage.
- Added unit and HTTP integration tests for defaults, configured stubs,
SSE, Vertex, and Bedrock EventStream behavior.
- Added proxy-level simulator-backed E2E tests that run Headroom against
the simulator across Anthropic, OpenAI Chat, OpenAI Responses, OpenAI
Conversations, Bedrock invoke/converse/streaming, Vertex raw/stream
predict, and upstream health.
- Added simulator-backed provider error-path E2E coverage for OpenAI
429, Anthropic 529, Bedrock 502, and Vertex 503 responses flowing
through Headroom unchanged.
- Added Headroom-owned preflight error E2E coverage proving Bedrock
missing credentials and invalid Vertex envelopes stop inside the proxy
instead of silently falling through to the simulator/provider.
- Fixed direct Rust `headroom-core` binaries/tests on Windows so Magika
initializes ONNX Runtime via `ort::init_from` from an explicit pip
`onnxruntime` library path, with fail-fast fallback only when no safe
runtime is discoverable.
- Added a Rust CI `simulator-e2e` matrix for `ubuntu-latest`,
`macos-latest`, and `windows-latest` that runs `cargo test -p
headroom-proxy --test e2e_simulators`.
- Gated dynamic Magika `Path`/`PathBuf` imports to Windows and x86_64
macOS so Linux clippy does not see unused dynamic-ORT-only imports.

## Testing  
- [ ] 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  
cargo fmt --all -- --check  
# passed  

cargo clippy --workspace -- -D warnings  
# passed  

$env:ORT_DYLIB_PATH=$null  
cargo test -p headroom-core transforms::magika_detector::tests:: --lib  
# 17 passed, 0 failed; Magika initialized from discovered pip
onnxruntime DLL

$env:ORT_DYLIB_PATH=$null  
cargo test --workspace  
# passed  

gitleaks protect --staged --no-banner --redact  
# no leaks found  

gitleaks git --log-opts="headroomlabs/main..HEAD" --no-banner --redact  
# 5 commits scanned; no leaks found

## Real Behavior Proof  
- **Environment:** Windows PowerShell, Rust toolchain `1.95.0`, clean
worktree from `headroomlabs/main` at `9bacf481`.
- **Exact simulator command / steps:**  
  - `cargo run -p headroom-simulators -- --listen 127.0.0.1:8789`  
- Point Headroom proxy upstream at `http://127.0.0.1:8789` for local
deterministic provider responses.
- Use optional `--config path/to/simulator.json` to bind exact request
fixtures.
- **Observed simulator result:**  
  - OpenAI chat default returns `chat.completion` shape.  
  - OpenAI Responses stream returns named SSE events.  
  - Vertex raw predict returns Anthropic message shape.  
- Bedrock stream can return binary `application/vnd.amazon.eventstream`
bytes.
  - Configured stubs override bottled defaults.  
- **Observed Magika result:**  
- Direct Rust `headroom-core` tests pass with `ORT_DYLIB_PATH` unset.
- Magika discovers the installed pip `onnxruntime.dll`, loads it via
`ort::init_from`, and only falls back if no safe runtime is available.
- **Not tested:**  
- No live provider calls; simulator behavior is intentionally offline
and deterministic.

## 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  
- [ ] I have updated the CHANGELOG.md if applicable

## Screenshots (if applicable)  
N/A

## Additional Notes  
No CHANGELOG entry was added because this introduces a developer/CI
simulator crate plus a Windows direct-Rust Magika runtime fix, without
changing shipped Python package behavior. The simulator intentionally
does not include a lightweight fallback LLM in this slice; unbound
inputs receive deterministic bottled responses so tests stay
reproducible and offline.
2026-07-11 09:41:49 -07:00