Commit Graph
3 Commits
Author SHA1 Message Date
a9c1ac5368 fix(providers/vertex): Vertex route multi-region locations (#3802)
## Description

Vertex AI's `us` and `eu` **multi-region** locations use a third
hostname shape
(`aiplatform.<location>.rep.googleapis.com`) that's distinct from both
the `global` endpoint and single-region endpoints
(`<location>-aiplatform.googleapis.com`). Headroom's
`vertex_target_for_location` only knew about the latter two shapes, so
`/locations/us/...` requests were forwarded to
`https://us-aiplatform.googleapis.com`, which 404s.

Closes #3798

## 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/vertex/runtime.py`: `vertex_target_for_location`
now routes bare-word locations other than `global` (currently `us`,
`eu`) to`https://aiplatform.<location>.rep.googleapis.com`. This is a
structural rule (no hyphen ⇒ multi-region), not a `{"us", "eu"}`
allowlist — GCP single-region ids are always hyphenated (`us-central1`,
`europe-west4`, ...), so any multi-region Google adds later is covered
without a follow-up patch. The existing `global`/empty check is
unchanged and still runs first, since `global` is also a bare word and
needs its own (hostless) branch.
- `tests/test_provider_vertex_runtime.py`: added
`test_vertex_target_for_location_uses_rep_hostname_for_multi_region`
covering `us`, `eu`, and a hypothetical future bare-word multi-region.

## Testing

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

### Test Output

```text
$ uv run ruff check headroom/providers/vertex/runtime.py tests/test_provider_vertex_runtime.py
All checks passed!

$ uv run mypy headroom/providers/vertex/runtime.py
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: local dev sandbox; no GCP ADC / Vertex project
configured, so the exact repro in #3798 (`headroom wrap claude` against
a real `us` multi-region Vertex endpoint) could not be run end-to-end
here.
- Exact command / steps: ran the new unit test asserting
`vertex_target_for_location(DEFAULT_VERTEX_API_URL, "us") ==
"https://aiplatform.us.rep.googleapis.com"` (and `"eu"`), matching the
hostname format documented in Google's own multi-region announcement
([cloud.google.com
blog](https://cloud.google.com/blog/products/ai-machine-learning/multi-region-endpoints-for-claude-available-on-vertex-ai)).
- Observed result: assertion passes; existing
single-region/global/explicit-gateway tests are unaffected.
- Not tested: a live request against a real Vertex `us`/`eu`
multi-region project through `headroom wrap claude`.

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: Requests whose Vertex `location` is a
bare word other than `global` (currently only `us`/`eu`) now resolve to
`aiplatform.<location>.rep.googleapis.com` instead of the
previously-wrong `<location>-aiplatform.googleapis.com`, which always
404'd. Hyphenated single-region locations and `global` are unchanged.
- Kill switch / disable path: The existing `ANTHROPIC_VERTEX_BASE_URL` /
`--vertex-api-url` override already bypasses this location-derivation
logic entirely if a hardcoded upstream host is needed.
- Unsafe override required: No
- Qualification impact: None known
- Rollback path: Revert 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
- [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)

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3802"
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 Sonnet 5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-05 08:33:07 -05:00
Abhay Singh 7c0b886004 fix(vertex): validate location region to close a path-parameter SSRF (#3304)
## Description

Closes #3280.

`vertex_target_for_location` interpolated the user-controlled `location`
path segment straight into the upstream **hostname** with no validation:

```python
return f"https://{location}-aiplatform.googleapis.com"
```

`location` comes from the Vertex route path
`/{api_version}/projects/{project}/locations/{location}/publishers/...`,
so it is fully attacker-controlled. A `location` of `169.254.169.254#`
(decoded from a percent-encoded `%23` in the path) produces:

```
https://169.254.169.254#-aiplatform.googleapis.com
```

which an HTTP client parses as host `169.254.169.254` with the remainder
treated as a URL fragment — a server-side request forgery (CWE-918) to
the cloud metadata endpoint. A `host:port` payload (`127.0.0.1:44919#`)
reaches an arbitrary internal port the same way. I confirmed the pre-fix
formula against the reported PoC:

```
'169.254.169.254#'  -> 'https://169.254.169.254#-aiplatform.googleapis.com'  host='169.254.169.254' port=None
'127.0.0.1:44919#'  -> 'https://127.0.0.1:44919#-aiplatform.googleapis.com'  host='127.0.0.1'      port=44919
```

The fix validates `location` against a strict GCP region shape
(`^[a-z0-9]+(?:-[a-z0-9]+)*$`) before interpolation. Anything that is
not a well-formed region — including port, path, userinfo, and
fragment-delimiter payloads — falls back to the default public
`aiplatform.googleapis.com` endpoint, which can never resolve to an
attacker-chosen host. Real regions (`us-central1`, `europe-west4`, ...),
`global`, empty, and an explicitly configured gateway target are all
unaffected.

Root-cause input validation on the pure routing formula fully closes the
reported vector; it is the same place every Vertex route derives its
target from, so there is one choke point rather than a per-route guard.

## 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/vertex/runtime.py`: added `_VERTEX_REGION_RE`
(anchored `^[a-z0-9]+(?:-[a-z0-9]+)*$`) and `_VERTEX_GLOBAL_API_URL`.
`vertex_target_for_location` now falls back to the public endpoint for
any `location` that is empty, `global`, or not a well-formed region, and
only interpolates a validated region into the hostname.
- `tests/test_provider_vertex_runtime.py`: added a parametrized
region-acceptance test, a parametrized SSRF-payload test
(fragment/host:port/path/userinfo/underscore/uppercase/malformed-hyphen
— asserts the fallback endpoint **and** that the parsed host is
`aiplatform.googleapis.com` with no port), and a test that an explicit
gateway target is still returned verbatim.

## Testing

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

### Test Output

```text
tests/test_provider_vertex_runtime.py tests/test_provider_proxy_targets.py tests/test_vertex_claude_compression.py  ->  39 passed
uvx ruff@0.16.2 check headroom/providers/vertex/runtime.py tests/test_provider_vertex_runtime.py  ->  All checks passed!
uvx mypy@1.20.2 headroom/providers/vertex/runtime.py  ->  Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.11, project venv, pytest 9.1.1,
ruff 0.16.2 and mypy 1.20.2 via uvx.
- Exact command / steps: reproduced the SSRF against the pre-fix formula
(the two lines above, showing `urlsplit(...).hostname` = the injected
`169.254.169.254` / `127.0.0.1:44919`); applied the fix and re-ran,
confirming both fall back to `https://aiplatform.googleapis.com` with
host `aiplatform.googleapis.com`. Red/green: with the fix reverted (`git
stash`) the 11 SSRF-payload cases fail; restored, all 27 vertex-runtime
tests pass.
- Observed result: a malicious `location` can no longer place a host,
port, path, or fragment delimiter into the upstream hostname; legitimate
regions and configured gateways are unchanged.
- Not tested: a live end-to-end request against a real metadata endpoint
(would require a network SSRF target); the URL-construction root cause
is covered by unit tests, including host/port parsing of the constructed
URL.

## Runtime Rollout Safety

- Rollout-managed feature(s): none — no feature flag or rollout channel
involved.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: only for malformed `location` values,
which previously produced a broken/attacker-controlled host and now
resolve to the public Vertex endpoint. Valid regions, `global`, empty,
and configured gateways are byte-for-byte unchanged.
- Kill switch / disable path: N/A (no config surface added).
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this commit; `location` goes back to being
interpolated unvalidated (reintroducing the SSRF).

## 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 (N/A: no
user-facing surface change for valid input)
- [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`

## Additional Notes

The region allowlist is intentionally strict (lowercase alphanumeric
groups joined by single hyphens), matching the shape of every GCP Vertex
region; `global`/empty keep their existing public-endpoint behavior. If
a defense-in-depth `is_safe_upstream_url` check at the route layer is
also wanted (as the issue suggests), that can follow as a separate
change — this PR fixes the root cause at the single point where the
hostname is built.
2026-08-27 15:02:32 +05:30
JD DavisandCopilot Autofix powered by AI e6243f65c9 refactor(providers): split proxy route adapters (#1934)
## Description
Refactors provider-specific proxy routing into provider-owned helper
modules so `headroom/providers/proxy_routes.py` primarily registers
routes and delegates behavior. This keeps Codex, OpenAI
Responses/images, model metadata, Vertex, Cloud Code, passthrough target
selection, and request path normalization logic testable outside the
route table.

Closes #

## Type of Change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] Documentation update
- [ ] Performance improvement
- [x] Code refactoring (no functional changes)

## Changes Made
- Extracted Codex routing helpers for headers, endpoint URLs, image
forwarding, response subpaths, and model metadata.
- Moved provider target selection, route specs, OpenAI Responses/images
helpers, Vertex runtime helpers, Cloud Code path normalization,
passthrough telemetry, and request scope normalization into focused
modules.
- Kept `proxy_routes.py` as route registration/delegation and preserved
current-main `/v1/messages` custom-base behavior.
- Added focused provider/proxy tests for the extracted modules and route
delegation behavior.

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

### Test Output
```text
python -m pytest tests/test_package_init_lazy.py::test_codex_package_import_stays_runtime_only tests/test_provider_cloudcode_runtime.py tests/test_provider_codex_endpoints.py tests/test_provider_codex_headers.py tests/test_provider_codex_images.py tests/test_provider_codex_model_metadata.py tests/test_provider_codex_responses.py tests/test_provider_model_metadata.py tests/test_provider_openai_images.py tests/test_provider_openai_responses.py tests/test_provider_proxy_targets.py tests/test_provider_route_specs.py tests/test_provider_vertex_runtime.py tests/test_proxy_request_scope.py tests/test_provider_proxy_routes.py::test_provider_passthrough_routes_forward_expected_targets tests/test_provider_proxy_routes.py::test_proxy_route_helpers_prefer_legacy_targets_and_gemini_passthrough tests/test_provider_proxy_routes.py::test_provider_specific_routes_delegate_to_expected_proxy_handlers tests/test_provider_proxy_routes.py::test_openai_response_websocket_aliases_delegate_to_openai_ws_handler tests/test_provider_proxy_routes.py::test_openai_response_subpath_passthrough_returns_502_on_http_failure tests/test_provider_proxy_routes.py::test_openai_response_subpath_passthrough_uses_openai_target tests/test_provider_proxy_routes.py::test_openai_response_subpath_aliases_and_chatgpt_auth_use_expected_targets tests/test_provider_proxy_routes.py::test_openai_image_routes_use_codex_backend_under_chatgpt_auth tests/test_provider_proxy_routes.py::test_openai_image_codex_response_strips_stale_compression_headers tests/test_provider_proxy_routes.py::test_openai_image_edits_api_key_auth_falls_through_to_openai_passthrough tests/test_provider_proxy_routes.py::test_openai_image_edits_preserves_multipart_body_under_chatgpt_auth tests/test_provider_proxy_routes.py::test_gemini_batch_embed_contents_passthrough_uses_gemini_target tests/test_provider_proxy_routes.py::test_v1_models_fetches_codex_registry_under_chatgpt_auth tests/test_provider_proxy_routes.py::test_v1_models_falls_back_to_synthetic_list_under_chatgpt_auth tests/test_provider_proxy_routes.py::test_v1_models_get_single_dynamic_under_chatgpt_auth tests/test_provider_proxy_routes.py::test_v1_models_still_forwards_under_non_chatgpt_auth tests/test_provider_proxy_routes.py::test_v1_models_routes_claude_code_gateway_discovery_to_anthropic tests/test_provider_proxy_routes.py::test_anthropic_model_metadata_strips_ansi_model_ids tests/test_custom_base_passthrough_telemetry.py tests/test_proxy_passthrough.py tests/test_proxy_google_cloudcode_route_aliases.py tests/test_proxy_project_savings.py::test_with_project_prefix_round_trips_through_split tests/test_vertex_claude_compression.py
============================ 102 passed in 34.83s =============================

python -m ruff check headroom/providers/cloudcode headroom/providers/codex headroom/providers/vertex headroom/providers/model_metadata.py headroom/providers/openai_images.py headroom/providers/openai_responses.py headroom/providers/proxy_targets.py headroom/providers/route_specs.py headroom/providers/proxy_routes.py headroom/proxy/handlers/openai.py headroom/proxy/passthrough.py headroom/proxy/request_scope.py headroom/proxy/project_context.py tests/test_package_init_lazy.py tests/test_provider_cloudcode_runtime.py tests/test_provider_codex_endpoints.py tests/test_provider_codex_headers.py tests/test_provider_codex_images.py tests/test_provider_codex_model_metadata.py tests/test_provider_codex_responses.py tests/test_provider_model_metadata.py tests/test_provider_openai_images.py tests/test_provider_openai_responses.py tests/test_provider_proxy_targets.py tests/test_provider_route_specs.py tests/test_provider_vertex_runtime.py tests/test_proxy_request_scope.py tests/test_provider_proxy_routes.py tests/test_custom_base_passthrough_telemetry.py tests/test_proxy_passthrough.py tests/test_proxy_google_cloudcode_route_aliases.py tests/test_proxy_project_savings.py tests/test_vertex_claude_compression.py
All checks passed!

python -m compileall -q headroom\providers\cloudcode headroom\providers\codex headroom\providers\vertex headroom\providers\model_metadata.py headroom\providers\openai_images.py headroom\providers\openai_responses.py headroom\providers\proxy_targets.py headroom\providers\route_specs.py headroom\providers\proxy_routes.py headroom\proxy\handlers\openai.py headroom\proxy\passthrough.py headroom\proxy\request_scope.py headroom\proxy\project_context.py
# no output; exited 0

git commit -m "refactor(providers): split proxy route adapters"
Sync plugin versions.....................................................Passed
check for merge conflicts................................................Passed
ruff.....................................................................Passed
ruff-format..............................................................Passed
mypy.....................................................................Passed
```

## Real Behavior Proof
- Environment: Windows PowerShell, Python 3.13.13, branch
`jd/provider-route-slices` based on `headroomlabs/main`.
- Exact command / steps: Ran the focused provider/proxy pytest suite,
focused ruff command, compileall over changed Python modules, and commit
hooks.
- Observed result: Provider/proxy route behavior tests passed; lint,
formatting, and mypy passed.
- Not tested: Full pytest suite, live upstream provider calls, and
manual end-to-end proxy traffic.

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

## Screenshots (if applicable)
N/A

## Additional Notes
Documentation and CHANGELOG updates are N/A for this internal refactor.
The full pytest suite was not run; coverage here is focused on
provider/proxy routing behavior touched by this slice.

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-07-12 16:27:45 -05:00