Files
headroom/tests/test_provider_cortex_code.py
Tejas ChopraandClaude Opus 5.5 dea9092e19 fix(security): resolve high-severity CodeQL alerts (#4005)
## Description

Resolves the high-severity CodeQL alerts in product code. Three are real
leaks (an API key in the proxy log, a credential in an oauth2 warning,
XSS in the HTML report); the rest are hardening.

Closes #

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

- **#63, Gemini API key written to the proxy log.** Google forwarders
build `...?key=<api key>` URLs (`batch.py:442` and others) and
`log_outbound_request` logged the full URL at INFO. The log line now
drops the query string, fragment and userinfo, keeping scheme, host
(IPv6 literals stay bracketed) and path. A URL with an invalid port logs
`<unparseable>` rather than raising.
- **#104, credential in an oauth2 warning.** A static header written as
`Authorization: Bearer x=y` splits on the first `=`, so `Authorization:
Bearer x` lands in the key, is rejected as malformed, and was echoed by
the warning. The warning no longer prints the key.
- **#131, XSS in the HTML report.** `model` and other request fields are
client supplied. Jinja2 autoescape is now on; no report field relies on
raw HTML.
- **#127:** `SNOWFLAKE_HOST` must end with `.snowflakecomputing.com`
instead of merely containing it.
- **#19, #128, #129, #130:** the `/\/+$/` trailing-slash regex in the TS
SDK and opencode plugin backtracks quadratically on long runs of `/`.
Replaced with a loop. The committed wheel bundle
(`headroom/providers/opencode/_dist/entry.opencode.js`) is rebuilt to
match.

Not changed (false positives, to dismiss): **#105** (URL already reduced
to `scheme://host` by `_redact_url`) and **#109** (`token_fingerprint`
is a short SHA-256 fingerprint of a high-entropy token for comparison,
not password storage).

## Testing

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

New tests: outbound log keeps no `key=` value or userinfo, keeps IPv6
brackets, and handles relative paths and invalid ports; the report
escapes `<script>`; the Snowflake host must end with the domain; both TS
trailing-slash helpers are tested on normal inputs and on a 100k-slash
input (the old regex took ~5.2 s on it; the test bound is 1 s).

### Test Output

```text
$ HEADROOM_REQUIRE_RUST_CORE=false pytest -q tests/test_proxy_byte_faithful_forwarding.py tests/test_reporting.py tests/test_provider_cortex_code.py
105 passed in 4.65s

$ HEADROOM_REQUIRE_RUST_CORE=false pytest -q plugins/headroom-oauth2/tests
70 passed

$ ruff check headroom/proxy/helpers.py tests/test_proxy_byte_faithful_forwarding.py && ruff format --check ...
All checks passed!
2 files already formatted

$ (cd plugins/opencode && npm run typecheck && npx vitest run)
Test Files  3 passed (3)
     Tests  38 passed (38)

$ (cd sdk/typescript && npx vitest run)
Test Files  19 passed | 5 skipped (24)
     Tests  351 passed | 33 skipped (384)

$ (cd plugins/opencode && npm run build:standalone) && cmp dist-standalone/entry.opencode.js ../../headroom/providers/opencode/_dist/entry.opencode.js
(no output: bundle matches source)
```

The two oauth2 tests that start the full proxy need the Rust core, which
was not built in the local worktree, so they ran with
`HEADROOM_REQUIRE_RUST_CORE=false`.

## Real Behavior Proof

- Environment: macOS 26 (Darwin 25.6), Python 3.12 venv, this branch at
`bb634a3b`, `HEADROOM_REQUIRE_RUST_CORE=false`. A local fake Gemini
upstream (Python `http.server`) listening on IPv6 `[::1]:9911`.
- Exact command / steps:
1. `python fake_gemini.py` (accepts POST, logs the request path, returns
`{"batch":{"name":"batches/fake"}}`)
  2. `headroom proxy --port 8799 --gemini-api-url 'http://[::1]:9911'`
3. `curl -X POST
'http://127.0.0.1:8799/v1beta/models/gemini-2.5-pro:batchGenerateContent'
-H 'x-goog-api-key: AIzaFAKE-RUNTIME-PROOF-123' -H 'content-type:
application/json' -d
'{"batch":{"displayName":"proof","inputConfig":{"requests":{"requests":[]}}}}'`
  4. `grep outbound_request proxy.log; grep -c AIzaFAKE proxy.log`
- Observed result: the client got `HTTP 200`. The upstream still
received the key
(`/v1beta/models/gemini-2.5-pro:batchGenerateContent?key=AIzaFAKE-RUNTIME-PROOF-123`),
so forwarding is unchanged. The proxy log line was
`event=outbound_request forwarder=google_batch_passthrough method=POST
path=http://[::1]:9911/v1beta/models/gemini-2.5-pro:batchGenerateContent
body_bytes=76 ...`, and the key appeared in the proxy log **0** times.
- Not tested: real Google, Snowflake or oauth2 provider endpoints; the
HTML report was exercised only through unit tests; the opencode plugin
was not loaded into a live opencode session; Windows.

## Runtime Rollout Safety

- Rollout-managed feature(s): None. No rollout-managed feature or flag
is touched.
- Minimum rollout channel: Stable. These are security fixes with no
opt-in behaviour.
- Stable/default behavior changed: Only diagnostics and validation: the
`outbound_request` log line no longer includes the query string,
fragment or userinfo; the oauth2 malformed-header warning no longer
prints the key; HTML report fields are escaped; a `SNOWFLAKE_HOST` that
merely contains `.snowflakecomputing.com` is now rejected. Request
forwarding is byte-for-byte unchanged.
- Kill switch / disable path: None needed; nothing new is enabled.
Reverting the PR restores the previous behaviour.
- Unsafe override required: No.
- Qualification impact: None. No compression, routing or
token-accounting path changes.
- Rollback path: 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
- [ ] 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

Possible overlap: #3999 also replaces the opencode trailing-slash regex.
Whichever lands second will need a small rebase.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 23:11:40 -05:00

107 lines
4.1 KiB
Python

from __future__ import annotations
from headroom.providers.cortex_code import build_install_env, proxy_base_url, render_setup_lines
from headroom.providers.cortex_code.runtime import build_launch_env, default_api_url
def test_cortex_code_proxy_base_url_is_openai_compatible() -> None:
assert proxy_base_url(8787) == "http://127.0.0.1:8787/v1"
def test_cortex_code_proxy_base_url_uses_given_port() -> None:
assert proxy_base_url(9999) == "http://127.0.0.1:9999/v1"
def test_cortex_code_build_install_env_sets_openai_base_url() -> None:
env = build_install_env(port=8787, backend="ignored")
assert env == {"OPENAI_BASE_URL": "http://127.0.0.1:8787/v1"}
def test_cortex_code_build_launch_env_does_not_mutate_input() -> None:
source = {"EXISTING": "val"}
env, lines = build_launch_env(port=9999, environ=source)
assert source == {"EXISTING": "val"}
assert env["OPENAI_BASE_URL"] == "http://127.0.0.1:9999/v1"
assert lines == ["OPENAI_BASE_URL=http://127.0.0.1:9999/v1"]
def test_cortex_code_build_launch_env_applies_project_prefix() -> None:
env, lines = build_launch_env(port=9999, environ={}, project="myrepo")
assert env["OPENAI_BASE_URL"] == "http://127.0.0.1:9999/p/myrepo/v1"
assert lines == ["OPENAI_BASE_URL=http://127.0.0.1:9999/p/myrepo/v1"]
def test_cortex_code_build_launch_env_ignores_blank_project() -> None:
env, lines = build_launch_env(port=9999, environ={}, project=" ")
assert env["OPENAI_BASE_URL"] == "http://127.0.0.1:9999/v1"
assert lines == ["OPENAI_BASE_URL=http://127.0.0.1:9999/v1"]
def test_cortex_code_render_setup_lines_contains_proxy_url() -> None:
lines = render_setup_lines(8787)
joined = "\n".join(lines)
assert "http://127.0.0.1:8787/v1" in joined
assert "Cortex Code" in joined
def test_cortex_code_render_setup_lines_project_attribution() -> None:
lines = render_setup_lines(8787, project="my-sf-project")
joined = "\n".join(lines)
assert "my-sf-project" in joined
plain = "\n".join(render_setup_lines(8787))
assert "attributed" not in plain
def test_cortex_code_default_api_url_reads_snowflake_host_env() -> None:
url = default_api_url({"SNOWFLAKE_HOST": "myaccount.snowflakecomputing.com"})
assert url == "https://myaccount.snowflakecomputing.com"
def test_cortex_code_default_api_url_constructs_url_from_account_name() -> None:
url = default_api_url({"SNOWFLAKE_ACCOUNT": "myaccount"})
assert url == "https://myaccount.snowflakecomputing.com"
def test_cortex_code_default_api_url_host_takes_priority_over_account() -> None:
url = default_api_url(
{
"SNOWFLAKE_HOST": "host.snowflakecomputing.com",
"SNOWFLAKE_ACCOUNT": "account",
}
)
assert url == "https://host.snowflakecomputing.com"
def test_cortex_code_default_api_url_falls_back_when_no_env() -> None:
url = default_api_url({})
assert url == "https://app.snowflake.com"
def test_cortex_code_default_api_url_preserves_https_prefix() -> None:
url = default_api_url({"SNOWFLAKE_HOST": "https://already.snowflakecomputing.com"})
assert url == "https://already.snowflakecomputing.com"
def test_cortex_code_install_registry_includes_cortex_code() -> None:
from headroom.providers.install_registry import build_install_target_envs
result = build_install_target_envs(port=1234, backend="ignored", targets=["cortex-code"])
assert result["cortex-code"]["OPENAI_BASE_URL"] == "http://127.0.0.1:1234/v1"
def test_cortex_code_install_registry_unknown_target_skipped() -> None:
from headroom.providers.install_registry import build_install_target_envs
result = build_install_target_envs(
port=1234, backend="ignored", targets=["cortex-code", "unknown-tool"]
)
assert "unknown-tool" not in result
assert "cortex-code" in result
def test_cortex_code_default_api_url_only_trusts_snowflake_suffix() -> None:
# The domain must end the host, not merely appear somewhere in it.
url = default_api_url({"SNOWFLAKE_HOST": "acct.snowflakecomputing.com.evil.io"})
assert url != "https://acct.snowflakecomputing.com.evil.io"
assert url.endswith(".snowflakecomputing.com")