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>
This commit is contained in:
Tejas Chopra
2026-10-06 23:11:40 -05:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 5a516b54af
commit dea9092e19
14 changed files with 200 additions and 18 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ def default_api_url(environ: Mapping[str, str] | None = None) -> str:
if host:
if host.startswith("https://"):
return host
if ".snowflakecomputing.com" in host:
if host.endswith(".snowflakecomputing.com"):
return f"https://{host}"
return f"https://{host}.snowflakecomputing.com"
return _FALLBACK_API_URL
@@ -12431,8 +12431,13 @@ var _proxyUrlCache = null;
function getDefaultProxyUrl() {
return _proxyUrlCache ?? process.env.HEADROOM_BASE_URL ?? "http://localhost:8787";
}
function trimTrailingSlashes(value) {
let end = value.length;
while (end > 0 && value.charCodeAt(end - 1) === 47) end--;
return value.slice(0, end);
}
function createHeadroomRetrieveTool(config2) {
const origin = config2.proxyBaseUrl.replace(/\/+$/, "");
const origin = trimTrailingSlashes(config2.proxyBaseUrl);
return {
name: "headroom_retrieve",
description: "Retrieve original uncompressed content from Headroom's compression store. Use when compressed context mentions a hash and you need the full details. Pass the hash from the compression marker (24 hex characters). Retrieval is by hash and always returns the full original content.",
@@ -12896,7 +12901,7 @@ function uninstallHeadroomTransport() {
// src/plugin.ts
function normalizeProxyUrl2(url2) {
return url2.replace(/\/+$/, "");
return trimTrailingSlashes(url2);
}
function resolveProxyUrl(options) {
return normalizeProxyUrl2(
+25 -3
View File
@@ -24,6 +24,7 @@ from dataclasses import dataclass
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, cast
from urllib.parse import urlsplit, urlunsplit
from headroom import fileperms as _fileperms
from headroom import paths as _paths
@@ -368,6 +369,27 @@ def sanitize_forwarded_response_headers(
return {key: value for key, value in dict(headers).items() if key.lower() not in drop}
def _path_for_log(path: str) -> str:
"""Drop the query string, fragment and userinfo from an outbound URL.
Callers pass the full upstream URL, and Google routes put the API key in
the query (``?key=...``), so logging it verbatim writes the key to disk.
Scheme, host and path are enough to tell forwarder calls apart.
"""
try:
parts = urlsplit(path)
port = parts.port
except ValueError:
return "<unparseable>"
host = parts.hostname or ""
# ``hostname`` drops the brackets around an IPv6 literal; put them back
# so the logged URL still names the upstream that was contacted.
netloc = f"[{host}]" if ":" in host else host
if port:
netloc = f"{netloc}:{port}"
return urlunsplit((parts.scheme, netloc, parts.path, "", ""))
def log_outbound_request(
*,
forwarder: str,
@@ -383,8 +405,8 @@ def log_outbound_request(
"""Structured log line for every outbound forwarder call.
Per realignment build constraints: every cache-affecting decision is
logged. Never includes ``Authorization``/``x-api-key`` content or full
body bytes.
logged. Never includes ``Authorization``/``x-api-key`` content, the URL
query string (where Google puts ``key=``) or full body bytes.
``dropped_mutation_reasons`` records edits that byte-faithful passthrough
discarded before the wire. That is a WARNING, not a detail: the line above
@@ -396,7 +418,7 @@ def log_outbound_request(
"body_mutated=%s mutation_reasons=%s source=%s request_id=%s",
forwarder,
method,
path,
_path_for_log(path),
body_bytes_count,
"true" if body_mutated else "false",
",".join(mutation_reasons) if mutation_reasons else "",
+3 -1
View File
@@ -18,7 +18,9 @@ def _get_jinja2_template(template_str: str):
try:
from jinja2 import Template
return Template(template_str)
# Request fields such as ``model`` come from clients; escape them so a
# crafted value cannot inject script into the report.
return Template(template_str, autoescape=True)
except ImportError as e:
raise ImportError(
"jinja2 is required for report generation. Install with: pip install headroom[reports]"
@@ -39,7 +39,12 @@ def parse_headers(s: str | None) -> dict[str, str]:
if not k:
continue
if _ctrl(k) or _ctrl(v) or " " in k or ":" in k:
log.warning("headroom-oauth2: dropping malformed static header: %r", k)
# Don't echo the key: a pair like "Authorization: Bearer x=y" lands
# here whole, so the "key" can carry the credential itself.
log.warning(
"headroom-oauth2: dropping malformed static header "
"(name has a space, colon or control character)"
)
continue
out[k] = v
return out
+6 -2
View File
@@ -2,7 +2,11 @@ import type { Plugin } from "@opencode-ai/plugin";
import { tool } from "@opencode-ai/plugin";
import { z } from "zod";
import { createHeadroomRetrieveTool, getDefaultProxyUrl } from "./retrieve.js";
import {
createHeadroomRetrieveTool,
getDefaultProxyUrl,
trimTrailingSlashes,
} from "./retrieve.js";
import { installHeadroomTransport } from "./transport.js";
export interface HeadroomOpenCodePluginOptions {
@@ -14,7 +18,7 @@ export interface HeadroomOpenCodePluginOptions {
}
function normalizeProxyUrl(url: string): string {
return url.replace(/\/+$/, "");
return trimTrailingSlashes(url);
}
function resolveProxyUrl(options?: HeadroomOpenCodePluginOptions): string {
+3 -1
View File
@@ -1,3 +1,5 @@
import { trimTrailingSlashes } from "./retrieve.js";
export interface HeadroomModelMapping {
name: string;
limit: {
@@ -39,7 +41,7 @@ export const DEFAULT_MODELS: Record<string, HeadroomModelMapping> = {
export const DEFAULT_MODEL = "claude-sonnet-4-6";
function resolveBaseUrl(options: HeadroomProviderOptions): string {
if (options.proxyBaseUrl) return options.proxyBaseUrl.replace(/\/+$/, "");
if (options.proxyBaseUrl) return trimTrailingSlashes(options.proxyBaseUrl);
const port = options.proxyPort ?? 8787;
return `http://127.0.0.1:${port}`;
}
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { trimTrailingSlashes } from "./retrieve.js";
describe("trimTrailingSlashes", () => {
it.each([
["http://localhost:8787", "http://localhost:8787"],
["http://localhost:8787/", "http://localhost:8787"],
["http://localhost:8787///", "http://localhost:8787"],
["http://localhost:8787/v1/", "http://localhost:8787/v1"],
["///", ""],
["", ""],
])("trims %j to %j", (input, expected) => {
expect(trimTrailingSlashes(input)).toBe(expected);
});
it("runs in linear time on long runs of slashes", () => {
// The previous /\/+$/ regex backtracked quadratically on a long run of
// "/" that is not at the end of the string (CodeQL js/polynomial-redos).
const slashes = "/".repeat(100_000);
const input = `http://localhost:8787${slashes}x${slashes}`;
const start = performance.now();
const result = trimTrailingSlashes(input);
expect(performance.now() - start).toBeLessThan(1000);
expect(result).toBe(`http://localhost:8787${slashes}x`);
});
});
+11 -1
View File
@@ -15,8 +15,18 @@ export interface RetrieveToolConfig {
proxyBaseUrl: string;
}
/**
* Strip trailing "/" characters. A loop rather than a `+$` regex, which
* backtracks quadratically on inputs with long runs of slashes.
*/
export function trimTrailingSlashes(value: string): string {
let end = value.length;
while (end > 0 && value.charCodeAt(end - 1) === 47) end--;
return value.slice(0, end);
}
export function createHeadroomRetrieveTool(config: RetrieveToolConfig) {
const origin = config.proxyBaseUrl.replace(/\/+$/, "");
const origin = trimTrailingSlashes(config.proxyBaseUrl);
return {
name: "headroom_retrieve",
+13 -5
View File
@@ -75,6 +75,16 @@ export interface HeadroomParams {
headroomToolProfiles?: Record<string, Record<string, any>>;
}
/**
* Strip trailing "/" characters. A loop rather than a `+$` regex, which
* backtracks quadratically on inputs with long runs of slashes.
*/
function trimTrailingSlashes(value: string): string {
let end = value.length;
while (end > 0 && value.charCodeAt(end - 1) === 47) end--;
return value.slice(0, end);
}
// --- Sub-clients ---
class ChatCompletions {
@@ -211,11 +221,9 @@ export class HeadroomClient implements HeadroomClientInterface {
readonly messages: Messages;
constructor(options: ExtendedClientOptions = {}) {
this.baseUrl = (
options.baseUrl ??
getEnv("HEADROOM_BASE_URL") ??
DEFAULT_BASE_URL
).replace(/\/+$/, "");
this.baseUrl = trimTrailingSlashes(
options.baseUrl ?? getEnv("HEADROOM_BASE_URL") ?? DEFAULT_BASE_URL,
);
this.apiKey = options.apiKey ?? getEnv("HEADROOM_API_KEY");
this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
this.fallback = options.fallback ?? true;
+17
View File
@@ -119,6 +119,23 @@ describe("HeadroomClient", () => {
expect(url).toBe("http://localhost:8787/v1/compress");
});
it("handles long runs of slashes in baseUrl in linear time", async () => {
// The previous /\/+$/ regex backtracked quadratically on a long run of
// "/" that is not at the end of the string (CodeQL js/polynomial-redos).
const slashes = "/".repeat(100_000);
mockFetch.mockResolvedValueOnce(okResponse(sampleProxyResponse));
const start = performance.now();
const client = new HeadroomClient({
baseUrl: `http://localhost:8787${slashes}x${slashes}`,
});
expect(performance.now() - start).toBeLessThan(1000);
await client.compress(sampleMessages, { model: "gpt-4o" });
const [url] = mockFetch.mock.calls[0];
expect(url).toBe(`http://localhost:8787${slashes}x/v1/compress`);
});
it("throws HeadroomAuthError on 401 (always, even with fallback)", async () => {
mockFetch.mockResolvedValueOnce(
errorResponse(401, {
+7
View File
@@ -97,3 +97,10 @@ def test_cortex_code_install_registry_unknown_target_skipped() -> None:
)
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")
@@ -41,6 +41,7 @@ from headroom.proxy.body_forwarding import (
thinking_blocks_survived_mutation,
)
from headroom.proxy.helpers import (
_path_for_log,
_reset_session_beta_tracker_for_test,
append_text_to_latest_user_chat_message,
get_session_beta_tracker,
@@ -509,6 +510,67 @@ def test_log_outbound_request_emits_structured_fields() -> None:
assert "x-api-key" not in msg.lower()
def test_log_outbound_request_strips_query_string_api_key() -> None:
"""Google forwarders put the API key in ``?key=``; it must not reach the log."""
import logging
proxy_logger = logging.getLogger("headroom.proxy")
records: list[logging.LogRecord] = []
class _ListHandler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
records.append(record)
handler = _ListHandler(level=logging.INFO)
prev_level = proxy_logger.level
proxy_logger.addHandler(handler)
proxy_logger.setLevel(logging.INFO)
try:
log_outbound_request(
forwarder="google_batch_passthrough",
method="POST",
path=(
"https://user:pw@generativelanguage.googleapis.com/v1beta/"
"models/gemini-2.5-pro:batchGenerateContent?key=AIzaSECRET#frag"
),
body_bytes_count=1,
body_mutated=False,
mutation_reasons=[],
request_id=None,
source="passthrough",
)
finally:
proxy_logger.removeHandler(handler)
proxy_logger.setLevel(prev_level)
msg = next(r.getMessage() for r in records if "outbound_request" in r.getMessage())
assert (
"path=https://generativelanguage.googleapis.com/v1beta/"
"models/gemini-2.5-pro:batchGenerateContent " in msg
)
assert "AIzaSECRET" not in msg
assert "key=" not in msg
assert "user:pw" not in msg
@pytest.mark.parametrize(
("path", "expected"),
[
# IPv6 upstreams keep their brackets so the log stays a valid URL.
("https://[::1]:8787/v1/messages?key=SECRET", "https://[::1]:8787/v1/messages"),
("http://[2001:db8::1]/v1/chat", "http://[2001:db8::1]/v1/chat"),
("https://api.example.com:8443/v1?x=1#f", "https://api.example.com:8443/v1"),
# Relative paths pass through without a query.
("/v1/messages?key=SECRET", "/v1/messages"),
# An invalid port makes urlsplit raise; never fall back to the raw URL.
("https://host:notaport/v1?key=SECRET", "<unparseable>"),
("https://[::1/v1?key=SECRET", "<unparseable>"),
],
)
def test_path_for_log(path: str, expected: str) -> None:
assert _path_for_log(path) == expected
# ---------------------------------------------------------------------------
# httpx-mock end-to-end byte-faithful checks
# ---------------------------------------------------------------------------
+11 -1
View File
@@ -49,8 +49,9 @@ def test_reporting_public_export() -> None:
def test_get_jinja2_template_success_with_stub(monkeypatch) -> None:
class FakeTemplate:
def __init__(self, template_str: str) -> None:
def __init__(self, template_str: str, **options) -> None:
self.template_str = template_str
self.options = options
def render(self, **kwargs) -> str:
return f"{self.template_str}:{kwargs['name']}"
@@ -58,6 +59,15 @@ def test_get_jinja2_template_success_with_stub(monkeypatch) -> None:
monkeypatch.setitem(sys.modules, "jinja2", SimpleNamespace(Template=FakeTemplate))
template = generator._get_jinja2_template("hello")
assert template.render(name="world") == "hello:world"
assert template.options == {"autoescape": True}
def test_report_template_escapes_client_supplied_fields() -> None:
pytest.importorskip("jinja2")
template = generator._get_jinja2_template("<td>{{ model }}</td>")
html = template.render(model="<script>alert(1)</script>")
assert "<script>" not in html
assert "&lt;script&gt;" in html
def test_get_jinja2_template_raises_helpful_error(monkeypatch) -> None: