fix(proxy): make the Rust front's native Bedrock and Vertex routes opt-in (#4851)

## Description

Two routes in the Rust front (`crates/headroom-proxy`) attach the host's
own cloud credentials to whatever request reaches them, without checking
the caller:

- **Bedrock native** (`/model/{id}/invoke`, `/converse`,
`/invoke-with-response-stream`, `/converse-stream`) is on by default and
signs every request with SigV4 using the AWS credentials found on the
host.
- **Vertex** (`…/publishers/anthropic/models/{m}:rawPredict` /
`:streamRawPredict`) is mounted unconditionally, replaces the caller's
`Authorization` with a bearer from the host's Google ADC, and forwards
to the generic `--upstream`, whatever host that is. So with a non-Google
upstream (the Python proxy, another provider) the host's Google token is
sent there. `--vertex-adc-scope` was parsed but never used.

This PR makes both routes explicit opt-ins, only sends the ADC bearer to
a Google API host, and uses the configured scope.

**Dependency:** these routes still do not authenticate callers
themselves. Callers are expected to be authenticated by the inbound
`HEADROOM_PROXY_TOKEN` gate added in #4840 (which also moves the default
listen address to loopback). This PR is based on `main` and does not
require #4840 to merge first, but operators who enable either route on a
non-loopback address need #4840 to restrict who can use them.

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

- `config.rs`: `--enable-bedrock-native` /
`HEADROOM_PROXY_ENABLE_BEDROCK_NATIVE` now defaults to `false`. New
`--enable-vertex-native` / `HEADROOM_PROXY_ENABLE_VERTEX_NATIVE`
(default `false`) and `--vertex-allow-non-google-upstream` /
`HEADROOM_PROXY_VERTEX_ALLOW_NON_GOOGLE_UPSTREAM` (default `false`).
`Config::for_test` keeps both routes on so the existing route tests run
unchanged.
- `proxy.rs`: the Vertex route is mounted only when enabled; with it
off, Vertex paths go through the catch-all with the caller's own headers
(as the Python proxy's Vertex passthrough expects). The ADC token source
is built with `--vertex-adc-scope`. The "Bedrock route not mounted"
startup line is now `info`, since off is the default.
- `vertex/raw_predict.rs`: before fetching the ADC bearer, the handler
refuses (502 `vertex upstream is not a Google API host`,
`vertex_upstream_not_google` error log) unless `--upstream` is
`https://` on a `*.googleapis.com` host (regional, global and
`*.p.googleapis.com` endpoints), or the operator set
`--vertex-allow-non-google-upstream=true` (local emulators, gateways).
No token is fetched on that path.
- `RUST_DEV.md`: the three flags in the configuration table, with what
enabling them means.

**Behaviour change for operators:** deployments that used the Rust
front's native Bedrock or Vertex signing must now pass
`--enable-bedrock-native true` / `--enable-vertex-native true` (or the
env vars). Vertex with a non-Google `--upstream` additionally needs
`--vertex-allow-non-google-upstream true`. Without the flags, those
paths are forwarded to `--upstream` unsigned with the client's own
credentials (Claude Code in Vertex mode keeps sending its own ADC token,
which is what `docs/content/docs/claude-code-vertex.mdx` describes).
`scripts/qualify_cargo_dependencies.py` already passes
`--enable-bedrock-native true`.

## Testing

- [x] `cargo test -p headroom-proxy` (45 test binaries, 596 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 in `tests/integration_cloud_routes_opt_in.rs` build the config
from the real CLI defaults (`CliArgs` → `Config::from_cli`), give the
app host AWS credentials and a host ADC bearer, and record what a
`wiremock` upstream receives:
- `default_config_does_not_sign_bedrock_requests`: no `AWS4-HMAC-SHA256`
Authorization on `invoke`, `invoke-with-response-stream`, `converse`.
- `default_config_never_attaches_host_adc_bearer`: `rawPredict` and
`streamRawPredict` reach the upstream without the host bearer.
- `vertex_bearer_is_not_sent_to_a_non_google_upstream`: with the route
enabled and an `http://127.0.0.1` upstream, 502 and the upstream sees
nothing.
- `vertex_opt_in_still_signs_when_non_google_upstream_is_allowed`: the
explicit escape hatch still works.
- `configured_adc_scope_reaches_token_source`.
- Unit test `vertex::raw_predict::tests::google_api_host_check`
(`http://`, `googleapis.com.example.net`, `example-googleapis.com`,
loopback are rejected).

### Test Output

Before (the three tests that compile against `main`, run with this PR's
`src/` changes stashed):

```text
test configured_adc_scope_reaches_token_source ... FAILED
test default_config_never_attaches_host_adc_bearer ... FAILED
test default_config_does_not_sign_bedrock_requests ... FAILED
test result: FAILED. 0 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.77s
```

After:

```text
$ cargo test -p headroom-proxy --test integration_cloud_routes_opt_in
test configured_adc_scope_reaches_token_source ... ok
test vertex_opt_in_still_signs_when_non_google_upstream_is_allowed ... ok
test vertex_bearer_is_not_sent_to_a_non_google_upstream ... ok
test default_config_never_attaches_host_adc_bearer ... ok
test default_config_does_not_sign_bedrock_requests ... ok
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.69s
```

## Real Behavior Proof

- Environment: macOS (Darwin 27.2), debug builds of `headroom-proxy`
from `origin/main` (c21b0813) and this branch. AWS credentials supplied
to the proxy through `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (fake
values), IMDS disabled. Upstream and Bedrock endpoint are a small Python
recorder on `127.0.0.1:18788` that prints the `Authorization` it
receives.
- Exact command / steps: `headroom-proxy --listen 127.0.0.1:18787
--upstream http://127.0.0.1:18788 --bedrock-endpoint
http://127.0.0.1:18788` (no Bedrock/Vertex flags), then `curl -d
'<anthropic body>'
http://127.0.0.1:18787/model/anthropic.claude-3-haiku-20240307-v1:0/invoke`
with no client credentials. Repeated on this branch with
`--enable-bedrock-native true`.
- Observed result (key id and signature redacted):

```text
== origin/main (no flags)
POST /model/anthropic.claude-3-haiku-20240307-v1:0/invoke, no client credentials -> 200
UPSTREAM SAW {"path": "/model/...:0/invoke", "authorization": "AWS4-HMAC-SHA256 Credential=<redacted>/20261113/us-east-1/bedrock/aws4_request, SignedHeaders=..., Signature=<sig>"}

== this branch (no flags)
POST /model/anthropic.claude-3-haiku-20240307-v1:0/invoke, no client credentials -> 200
UPSTREAM SAW {"path": "/model/...:0/invoke", "authorization": null}

== this branch, --enable-bedrock-native true
UPSTREAM SAW {"path": "/model/...:0/invoke", "authorization": "AWS4-HMAC-SHA256 Credential=<redacted>/20261113/us-east-1/bedrock/aws4_request, SignedHeaders=..., Signature=<sig>"}
```

- Not tested: Vertex against real Google ADC and a real
`*.googleapis.com` upstream (covered by the integration tests with a
static token source; no GCP credentials on the test machine).

## Runtime Rollout Safety

- Rollout-managed feature(s): `native_bedrock` (existing). The CLI flag
already maps `false` to a rollout disable, so with the new default the
feature reports disabled unless `--enable-bedrock-native true` is
passed. Vertex is not rollout-managed.
- Minimum rollout channel: unchanged
- Stable/default behavior changed: yes, both native routes are off by
default
- Kill switch / disable path: the routes are now off unless enabled
- Unsafe override required: no
- Qualification impact: none, the qualification script already passes
`--enable-bedrock-native true`
- Rollback path: pass `--enable-bedrock-native true` /
`--enable-vertex-native true` (plus `--vertex-allow-non-google-upstream
true` if the upstream is not a Google host), or 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

Fix adapted from a proposal by HetCreep.

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

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

---

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

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:
Tejas Chopra
2026-11-16 23:07:49 -06:00
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent d077263012
commit 99021af20a
6 changed files with 323 additions and 25 deletions
+4 -1
View File
@@ -97,6 +97,9 @@ curl -si http://127.0.0.1:8787/v1/models
| `--graceful-shutdown-timeout` | | `30s` | wait for in-flight on SIGTERM/SIGINT |
| `--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`) |
| `--enable-bedrock-native` | `HEADROOM_PROXY_ENABLE_BEDROCK_NATIVE` | (unset: off) | `true` or `--features native_bedrock` mounts `/model/{id}/invoke`, `/converse` and the streaming variants; they sign every request with this host's AWS credentials and do not authenticate the caller |
| `--enable-vertex-native` | `HEADROOM_PROXY_ENABLE_VERTEX_NATIVE` | `false` | mount Vertex `:rawPredict` / `:streamRawPredict`; replaces the caller's `Authorization` with this host's Google ADC bearer (scope `--vertex-adc-scope`) and does not authenticate the caller |
| `--vertex-allow-non-google-upstream` | `HEADROOM_PROXY_VERTEX_ALLOW_NON_GOOGLE_UPSTREAM` | `false` | by default the Vertex route only sends the ADC bearer when `--upstream` is `https://*.googleapis.com`, and answers 502 otherwise |
### Inbound authentication
@@ -130,7 +133,7 @@ Python proxy trusts loopback callers (no token needed, and access to
The Rust proxy records per-request savings/cost telemetry on every
lane it forwards — Anthropic `/v1/messages`, OpenAI Chat/Responses,
all four native Bedrock routes, and Vertex `rawPredict` /
`streamRawPredict` — and serves it locally (never tunnelled
`streamRawPredict` when those are enabled — and serves it locally (never tunnelled
upstream):
```bash
+11 -2
View File
@@ -78,7 +78,8 @@ impl Feature {
Self::NativeBedrock => FeatureSpec {
name: "native_bedrock",
available_in: RolloutChannel::Stable,
default_enabled_in: Some(RolloutChannel::Stable),
// Signs requests with the host's AWS credentials: opt-in only.
default_enabled_in: None,
},
Self::OpenAiResponsesStreaming => FeatureSpec {
name: "openai_responses_streaming",
@@ -365,11 +366,19 @@ mod tests {
#[test]
fn default_enabled_feature_has_default_reason() {
let rollout = RolloutSnapshot::default();
let decision = rollout.decision(Feature::NativeBedrock);
let decision = rollout.decision(Feature::OpenAiResponsesStreaming);
assert!(decision.enabled);
assert_eq!(decision.reason, FeatureDecisionReason::Default);
}
#[test]
fn native_bedrock_is_not_on_by_default() {
let rollout = RolloutSnapshot::default();
let decision = rollout.decision(Feature::NativeBedrock);
assert!(!decision.enabled);
assert_eq!(decision.reason, FeatureDecisionReason::NotRequested);
}
#[test]
fn unsafe_override_crosses_boundary_and_is_ineligible() {
let rollout = RolloutSnapshot::from_parts("stable", "canary_probe", "", true);
+97 -14
View File
@@ -504,7 +504,7 @@ pub struct CliArgs {
pub enable_conversations_passthrough: bool,
/// Phase D PR-D1: enable the native Bedrock InvokeModel route.
/// When `true` (default), `POST /model/{model_id}/invoke` is
/// When `true`, `POST /model/{model_id}/invoke` is
/// handled by the Rust `bedrock::invoke` handler — Anthropic-shape
/// bodies run through the live-zone compression path and the
/// proxy re-signs the request with SigV4 before forwarding to
@@ -514,15 +514,21 @@ pub struct CliArgs {
/// re-sign — operators MUST run an unsigned upstream that
/// happens to know what to do, otherwise this fails closed).
///
/// Default `false`: the route signs every request it receives with
/// this host's AWS credentials and does not authenticate the caller,
/// so only enable it where every caller that can reach `--listen`
/// may use those credentials. `--features native_bedrock` also
/// enables it; `false` here (or `--disable-features native_bedrock`)
/// forces it off.
///
/// Source priority: CLI flag → `HEADROOM_PROXY_ENABLE_BEDROCK_NATIVE`
/// env var → default (`true`).
/// env var → rollout (`native_bedrock`, not on by default).
#[arg(
long = "enable-bedrock-native",
env = "HEADROOM_PROXY_ENABLE_BEDROCK_NATIVE",
default_value_t = true,
action = clap::ArgAction::Set,
)]
pub enable_bedrock_native: bool,
pub enable_bedrock_native: Option<bool>,
/// AWS region to use when signing Bedrock requests. Default
/// `us-east-1`. The Bedrock endpoint URL derived from this
@@ -610,6 +616,39 @@ pub struct CliArgs {
)]
pub vertex_adc_scope: String,
/// Mount the native Vertex `:rawPredict` / `:streamRawPredict`
/// route. That route replaces the caller's `Authorization` with a
/// bearer from this host's Google ADC and does not authenticate the
/// caller, so only enable it where every caller that can reach
/// `--listen` may use that identity. Default `false`: Vertex paths
/// fall through to the catch-all with the caller's own headers.
///
/// Source priority: CLI flag → `HEADROOM_PROXY_ENABLE_VERTEX_NATIVE`
/// env var → default (`false`).
#[arg(
long = "enable-vertex-native",
env = "HEADROOM_PROXY_ENABLE_VERTEX_NATIVE",
default_value_t = false,
action = clap::ArgAction::Set,
)]
pub enable_vertex_native: bool,
/// Let the native Vertex route attach the ADC bearer when
/// `--upstream` is not an `https://*.googleapis.com` host (a local
/// emulator or a gateway that forwards to Vertex). Default `false`:
/// the route refuses such requests and no token is fetched.
///
/// Source priority: CLI flag →
/// `HEADROOM_PROXY_VERTEX_ALLOW_NON_GOOGLE_UPSTREAM` env var →
/// default (`false`).
#[arg(
long = "vertex-allow-non-google-upstream",
env = "HEADROOM_PROXY_VERTEX_ALLOW_NON_GOOGLE_UPSTREAM",
default_value_t = false,
action = clap::ArgAction::Set,
)]
pub vertex_allow_non_google_upstream: bool,
/// Native savings stats: record per-request savings/cost
/// telemetry and serve `/stats`, `/stats/timeseries`,
/// `/stats/events`, and `/dashboard`. When disabled, nothing is
@@ -731,7 +770,7 @@ pub struct Config {
/// C5+/B-phase territory).
pub enable_conversations_passthrough: bool,
/// PR-D1: enable the native Bedrock InvokeModel route. Default
/// `true`. When disabled, the explicit Rust handlers are not
/// `false`. When disabled, the explicit Rust handlers are not
/// mounted; operators relying on the Python LiteLLM converter
/// keep their existing path.
pub enable_bedrock_native: bool,
@@ -755,6 +794,11 @@ pub struct Config {
/// PR-D4: GCP ADC OAuth scope used when fetching the bearer
/// token. Default `https://www.googleapis.com/auth/cloud-platform`.
pub vertex_adc_scope: String,
/// Mount the native Vertex route. Default `false`.
pub enable_vertex_native: bool,
/// Attach the ADC bearer even when `upstream` is not a Google API
/// host. Default `false`.
pub vertex_allow_non_google_upstream: bool,
/// Native savings stats: record per-request telemetry and serve
/// `/stats`, `/stats/timeseries`, `/stats/events`, `/dashboard`.
pub stats: bool,
@@ -768,17 +812,17 @@ impl Config {
if args.enable_responses_streaming {
explicit_features.push(Feature::OpenAiResponsesStreaming);
}
if args.enable_bedrock_native {
if args.enable_bedrock_native == Some(true) {
explicit_features.push(Feature::NativeBedrock);
}
// Preserve the pre-rollout rollback controls as legacy disables. Both
// features are stable defaults in the registry, so merely omitting a
// false flag from `explicit_features` would turn it straight back on.
// Preserve the pre-rollout rollback controls as legacy disables: a
// false flag must win over a default or a `--features` request.
// An omitted Bedrock flag leaves the decision to the rollout.
let mut disabled_features = split_feature_names(&args.disable_features);
if !args.enable_responses_streaming {
disabled_features.push(Feature::OpenAiResponsesStreaming.spec().name.to_owned());
}
if !args.enable_bedrock_native {
if args.enable_bedrock_native == Some(false) {
disabled_features.push(Feature::NativeBedrock.spec().name.to_owned());
}
let rollout = RolloutSnapshot::from_parts_with_explicit(
@@ -820,14 +864,18 @@ impl Config {
args.enable_responses_streaming,
),
enable_conversations_passthrough: args.enable_conversations_passthrough,
enable_bedrock_native: rollout
.is_enabled(Feature::NativeBedrock, args.enable_bedrock_native),
enable_bedrock_native: rollout.is_enabled(
Feature::NativeBedrock,
args.enable_bedrock_native == Some(true),
),
bedrock_region: args.bedrock_region,
bedrock_endpoint: args.bedrock_endpoint,
aws_profile: args.aws_profile,
bedrock_validate_eventstream_crc: args.bedrock_validate_eventstream_crc,
vertex_region: args.vertex_region,
vertex_adc_scope: args.vertex_adc_scope,
enable_vertex_native: args.enable_vertex_native,
vertex_allow_non_google_upstream: args.vertex_allow_non_google_upstream,
stats: args.stats,
stats_path: args.stats_path.or_else(default_stats_path),
}
@@ -879,8 +927,8 @@ impl Config {
// production traffic will hit.
enable_responses_streaming: true,
enable_conversations_passthrough: true,
// PR-D1: bedrock route default-on so tests exercise
// it without per-test opt-in. Tests that set
// PR-D1: bedrock route on so tests exercise it without
// per-test opt-in (production default is off). Tests that set
// `bedrock_endpoint` to a wiremock URL get the full
// sign-and-forward path.
enable_bedrock_native: true,
@@ -894,6 +942,11 @@ impl Config {
// only; the upstream URL is `upstream`).
vertex_region: "us-central1".to_string(),
vertex_adc_scope: "https://www.googleapis.com/auth/cloud-platform".to_string(),
// Vertex route on, against the wiremock upstream, so tests
// exercise it without per-test opt-in (production default
// is off for both, see `CliArgs`).
enable_vertex_native: true,
vertex_allow_non_google_upstream: true,
// Stats on (routes mounted, recording active) but
// in-memory: tests never touch a real home directory.
stats: true,
@@ -979,6 +1032,36 @@ mod rollout_input_tests {
assert!(!config.enable_bedrock_native);
}
#[test]
fn native_bedrock_is_off_by_default_and_follows_rollout_requests() {
let parse = |extra: &[&str]| {
let mut argv = vec!["headroom-proxy", "--upstream", "http://127.0.0.1:9"];
argv.extend_from_slice(extra);
Config::from_cli(CliArgs::try_parse_from(argv).unwrap())
};
assert!(!parse(&[]).enable_bedrock_native);
assert!(parse(&["--features", "native_bedrock"]).enable_bedrock_native);
assert!(parse(&["--enable-bedrock-native", "true"]).enable_bedrock_native);
assert!(
!parse(&[
"--features",
"native_bedrock",
"--disable-features",
"native_bedrock"
])
.enable_bedrock_native
);
assert!(
!parse(&[
"--features",
"native_bedrock",
"--enable-bedrock-native",
"false"
])
.enable_bedrock_native
);
}
#[test]
fn native_stats_require_explicit_opt_in() {
let base = ["headroom-proxy", "--upstream", "http://127.0.0.1:9"];
+16 -8
View File
@@ -132,8 +132,9 @@ impl AppState {
// PR-D4: lazy ADC token source. Provider resolution is
// deferred to first `bearer()` call so proxy startup stays
// cheap when no Vertex route is exercised.
let vertex_token_source: Arc<dyn crate::vertex::TokenSource> =
Arc::new(crate::vertex::adc::GcpAdcTokenSource::new());
let vertex_token_source: Arc<dyn crate::vertex::TokenSource> = Arc::new(
crate::vertex::adc::GcpAdcTokenSource::with_scope(config.vertex_adc_scope.clone()),
);
let stats = if config.stats {
match config.stats_path.clone() {
@@ -281,7 +282,13 @@ pub fn build_app(state: AppState) -> Router {
"/v1/responses",
post(crate::handlers::responses::handle_responses)
.layer(DefaultBodyLimit::max(state.config.max_body_bytes as usize)),
)
);
// Mounted only with `--enable-vertex-native`: the handler replaces
// the caller's Authorization with this host's ADC bearer. When off,
// Vertex paths reach the catch-all with the caller's own headers.
if state.config.enable_vertex_native {
router = router
// PR-D4: native Vertex publisher path. The Vertex AI Anthropic
// publisher endpoints look like
// `POST /v1beta1/projects/{p}/locations/{l}/publishers/anthropic/models/{m}:rawPredict`
@@ -296,6 +303,7 @@ pub fn build_app(state: AppState) -> Router {
"/v1beta1/projects/{project}/locations/{location}/publishers/anthropic/models/{model_action}",
post(crate::vertex::handle_vertex_predict_dispatch),
);
}
// PR-D3: Prometheus scrape endpoint. Renders the global registry in
// text format. The handler is stateless — no `AppState` needed — and
@@ -319,7 +327,7 @@ pub fn build_app(state: AppState) -> Router {
router = router.merge(metrics_router);
// PR-D1: native AWS Bedrock InvokeModel route. Mounts only when
// `enable_bedrock_native` is on (default). The handler runs the
// `enable_bedrock_native` is on (off by default). The handler runs the
// live-zone compressor over Anthropic-shape bodies, signs with
// SigV4, and forwards to the configured Bedrock endpoint. The
// `/converse` route mounts the same handler — the wire shape is
@@ -377,11 +385,11 @@ pub fn build_app(state: AppState) -> Router {
);
}
} else {
tracing::warn!(
tracing::info!(
event = "bedrock_native_disabled",
"Bedrock native InvokeModel route disabled by \
--enable-bedrock-native=false; Bedrock requests will fall \
through to the catch-all (no SigV4 re-signing — fails closed)"
"Bedrock native InvokeModel route not mounted \
(--enable-bedrock-native=false, the default); Bedrock requests \
fall through to the catch-all (no SigV4 re-signing)"
);
}
@@ -224,6 +224,24 @@ pub(crate) async fn forward_vertex_request(
}
// ─── 4. RESOLVE BEARER TOKEN ───────────────────────────────────────
// The ADC bearer is this host's Google identity: only send it to a
// Google API host unless the operator explicitly allowed otherwise.
if !state.config.vertex_allow_non_google_upstream && !is_google_api_host(&state.config.upstream)
{
tracing::error!(
event = "vertex_upstream_not_google",
request_id = %request_id,
upstream_host = state.config.upstream.host_str().unwrap_or(""),
"native Vertex route needs --upstream on https://*.googleapis.com \
(or --vertex-allow-non-google-upstream=true); refusing to attach \
the ADC bearer"
);
capture::finalize_rejected(pending_stats.take());
return error_response(
StatusCode::BAD_GATEWAY,
"vertex upstream is not a Google API host",
);
}
let bearer = match state.vertex_token_source.bearer().await {
Ok(t) => t,
Err(e) => {
@@ -471,6 +489,14 @@ pub(crate) async fn forward_vertex_request(
response
}
/// `https://` plus a host under `googleapis.com` (regional
/// `{region}-aiplatform.googleapis.com`, global, and Private Service
/// Connect `*.p.googleapis.com` endpoints).
fn is_google_api_host(upstream: &url::Url) -> bool {
upstream.scheme() == "https"
&& matches!(upstream.host(), Some(url::Host::Domain(h)) if h.ends_with(".googleapis.com"))
}
fn error_response(status: StatusCode, msg: &'static str) -> Response {
Response::builder()
.status(status)
@@ -534,3 +560,28 @@ async fn run_anthropic_sse_state_machine(
p.finalize(capture::usage_from_anthropic_state(&state));
}
}
#[cfg(test)]
mod tests {
use super::is_google_api_host;
#[test]
fn google_api_host_check() {
for ok in [
"https://us-central1-aiplatform.googleapis.com",
"https://aiplatform.googleapis.com/",
"https://aiplatform-x.p.googleapis.com",
] {
assert!(is_google_api_host(&ok.parse().unwrap()), "{ok}");
}
for bad in [
"http://us-central1-aiplatform.googleapis.com",
"https://googleapis.com.example.net",
"https://example-googleapis.com",
"https://127.0.0.1:8788",
"http://127.0.0.1:8788",
] {
assert!(!is_google_api_host(&bad.parse().unwrap()), "{bad}");
}
}
}
@@ -0,0 +1,144 @@
//! The native Bedrock and Vertex routes attach this host's cloud
//! credentials (SigV4 / Google ADC bearer) to whatever request reaches
//! them. They are mounted only on explicit opt-in, the Vertex bearer
//! goes only to a Google API host, and the ADC token source uses the
//! configured scope.
mod common;
use std::net::SocketAddr;
use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::{Request, StatusCode};
use clap::Parser;
use headroom_proxy::config::CliArgs;
use headroom_proxy::{build_app, AppState, Config};
use tower::util::ServiceExt;
use wiremock::matchers::any;
use wiremock::{Mock, MockServer, ResponseTemplate};
const HOST_BEARER: &str = "ya29.host-adc-bearer";
const VERTEX_PREFIX: &str =
"/v1beta1/projects/p/locations/us-central1/publishers/anthropic/models/m";
const BODY: &str = r#"{"anthropic_version":"vertex-2023-10-16","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}"#;
async fn upstream() -> MockServer {
let server = MockServer::start().await;
Mock::given(any())
.respond_with(ResponseTemplate::new(200).set_body_string("{}"))
.mount(&server)
.await;
server
}
/// The production defaults, as `main` builds them from the command line.
fn default_config(upstream: &MockServer) -> Config {
let args = CliArgs::try_parse_from(["headroom-proxy", "--upstream", &upstream.uri()])
.expect("parse defaults");
let mut config = Config::from_cli(args);
// Keep any Bedrock signing on the mock, and stats in memory.
config.bedrock_endpoint = Some(upstream.uri().parse().unwrap());
config.stats_path = None;
config
}
/// POST `path` with host AWS credentials and a host ADC bearer both
/// available to the proxy, as they would be on a cloud VM.
async fn post(config: Config, path: &str) -> StatusCode {
let state = AppState::new(config)
.expect("app state")
.with_bedrock_credentials(common::test_credentials());
let app = build_app(common::install_static_token_source(state, HOST_BEARER));
let mut req = Request::post(path)
.header("content-type", "application/json")
.body(Body::from(BODY))
.unwrap();
let peer: SocketAddr = "127.0.0.1:40000".parse().unwrap();
req.extensions_mut().insert(ConnectInfo(peer));
app.oneshot(req).await.unwrap().status()
}
async fn authorizations(upstream: &MockServer) -> Vec<String> {
upstream
.received_requests()
.await
.unwrap()
.iter()
.filter_map(|r| r.headers.get("authorization"))
.map(|v| v.to_str().unwrap().to_owned())
.collect()
}
#[tokio::test]
async fn default_config_does_not_sign_bedrock_requests() {
let up = upstream().await;
let verbs = [
"invoke",
"invoke-with-response-stream",
"converse",
"converse-stream",
];
for verb in verbs {
post(
default_config(&up),
&format!("/model/anthropic.claude-3-haiku-20240307-v1:0/{verb}"),
)
.await;
}
// Every request reached the upstream, so the check below is not vacuous.
assert_eq!(up.received_requests().await.unwrap().len(), verbs.len());
let auth = authorizations(&up).await;
assert!(
auth.iter().all(|a| !a.starts_with("AWS4-HMAC-SHA256")),
"host AWS credentials signed a request by default: {auth:?}"
);
}
#[tokio::test]
async fn default_config_never_attaches_host_adc_bearer() {
let up = upstream().await;
for verb in ["rawPredict", "streamRawPredict"] {
post(default_config(&up), &format!("{VERTEX_PREFIX}:{verb}")).await;
}
assert_eq!(up.received_requests().await.unwrap().len(), 2);
let auth = authorizations(&up).await;
assert!(
auth.iter().all(|a| !a.contains(HOST_BEARER)),
"host ADC bearer sent by default: {auth:?}"
);
}
#[tokio::test]
async fn vertex_bearer_is_not_sent_to_a_non_google_upstream() {
let up = upstream().await;
let mut config = default_config(&up);
config.enable_vertex_native = true;
let status = post(config, &format!("{VERTEX_PREFIX}:rawPredict")).await;
assert_eq!(status, StatusCode::BAD_GATEWAY);
assert!(up.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn vertex_opt_in_still_signs_when_non_google_upstream_is_allowed() {
let up = upstream().await;
let mut config = default_config(&up);
config.enable_vertex_native = true;
config.vertex_allow_non_google_upstream = true;
let status = post(config, &format!("{VERTEX_PREFIX}:rawPredict")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
authorizations(&up).await,
vec![format!("Bearer {HOST_BEARER}")]
);
}
#[test]
fn configured_adc_scope_reaches_token_source() {
let mut config = Config::for_test("http://127.0.0.1:9".parse().unwrap());
config.vertex_adc_scope = "https://www.googleapis.com/auth/test-narrow-scope".into();
let state = AppState::new(config).expect("app state");
// `GcpAdcTokenSource`'s Debug prints its scope; no GCP call is made.
let debug = format!("{:?}", state.vertex_token_source);
assert!(debug.contains("test-narrow-scope"), "{debug}");
}