mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-12-03 02:16:29 +08:00
## Description Closes #3352. Preserve the native inline editor OAuth identity without widening Chat/Responses auth. Current head `4609ac6b6162e81e4471492cb4c056065ce7f450` includes upstream main `f1bc2609`. ## Type of Change - [x] Bug fix - [x] Documentation update - [x] Code refactoring ## Changes Made - Share one case-insensitive in-place header-removal helper across all three auth branches; remove every unrelated provider API-key spelling and every replaced Authorization spelling. - Classify `ghu_` as the safe `ghu_***` kind and log that kind in the inline branch, never the editor credential. - Preserve the fetched same-origin/segment-boundary gateway-prefix fix and its host/scheme/port regressions; this was already present in `c368f1d`, not reimplemented here. - Retain managed-seed exclusion and the existing Chat/Responses token policy. No new live-account fallback or provider mock was introduced. - Keep the optional path-helper extraction out; the small existing origin guard remains explicit. ## Testing - [x] Relevant unit/API regressions pass - [x] Changed-file Ruff check and format pass - [x] Manual auth operation/privacy smoke performed ### Test Output ```text 222 passed 181 passed, 5 warnings ci-precheck PASSED — safe to push. ``` Focused command: `pytest -q tests/test_copilot_inline_client_auth.py tests/test_copilot_auth.py tests/test_proxy_copilot_auth_hooks.py tests/test_copilot_vscode_completions_routing.py tests/test_copilot_integration_id_hmac.py`. Normal commit and full pre-push hooks passed, including workspace Rust gates, genuine native rebuild/import, critical Python and commitlint. No hooks/tests were bypassed or filtered. The first normal push hit the unchanged native `expired_get_does_not_wipe_concurrent_refresh` final-live assertion: its 20 ms idle TTL can expire legitimately before the assertion under scheduling load. This is the already-documented main stress-test issue, not an auth-source change. A subsequent complete normal gate run used `RUST_TEST_THREADS=1` and passed; no Rust fix or general flake elimination is claimed. ## Real Behavior Proof - Environment: Linux x86_64, Python 3.13.14, current published source, real `apply_copilot_api_auth` and logging, synthetic credential environment, isolated HOME, `DO_NOT_TRACK=1`. - Exact command / steps: Execute `python artifacts/review-20261013/run-native.py WORKTREE TARGET/release/lib_core.so PROBE OUTPUT.json`. Invoke actual auth operations for native inline on a different origin, same-origin prefixed gateway inline, client-owned Chat gho, and Chat ghu requiring operator replacement; include mixed-case duplicate API-key headers and capture actual module logs. - Observed result: Four auth cases preserve/select the correct identity, remove all unrelated provider secrets, and log only safe kinds. Captured kinds are `ghu_***`, `ghu_***`, `gho_***`, `ghu_***`; the full editor credential and its suffix are absent. Existing real-proxy MockTransport credential-gate and streaming/disconnect regressions passed in the focused suite. - Not tested: Live Copilot or VS Code signed-in end-to-end. The isolated verification environment has no live Copilot credential; #3352 has no reporter confirmation of this branch. The synthetic upstream/credential gate is not presented as live entitlement proof. Full standalone mypy and hosted-CI success are not asserted. ## Runtime Rollout Safety - Rollout-managed feature(s): Existing Copilot auth routes; no feature rollout added. - Minimum rollout channel: Unchanged stable/default auth. - Stable/default behavior changed: Inline token-kind diagnostics and one shared secret-removal rule; native inline identity exception remains host/path constrained. - Kill switch / disable path: Existing Copilot upstream/auth configuration; no new switch. - Unsafe override required: No. - Qualification impact: Auth selection, case-variant secret removal, log privacy, gateway origin boundaries and existing proxy streaming gates requalified; live entitlement remains external. - Rollback path: Revert this auth helper/logging revision; no data migration. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] Documentation updated - [x] Did not edit `CHANGELOG.md` --------- Co-authored-by: Tejas Chopra <tejas@headroomlabs.ai> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
179 lines
6.4 KiB
Python
179 lines
6.4 KiB
Python
from __future__ import annotations
|
|
|
|
import httpx
|
|
import pytest
|
|
from starlette.requests import Request
|
|
from starlette.responses import StreamingResponse
|
|
|
|
from headroom import paths
|
|
from headroom.proxy.server import HeadroomProxy, ProxyConfig
|
|
|
|
|
|
def test_openai_chat_routes_copilot_requests_per_model() -> None:
|
|
from headroom.proxy.handlers import openai as openai_mod
|
|
|
|
copilot_base = "https://api.githubcopilot.com"
|
|
gpt54_mini_url = openai_mod.build_copilot_upstream_url(
|
|
copilot_base,
|
|
openai_mod._resolve_openai_handler_path(
|
|
{},
|
|
handler_path=openai_mod._resolve_openai_chat_handler_path(copilot_base, "gpt-5.4-mini"),
|
|
),
|
|
)
|
|
claude_url = openai_mod.build_copilot_upstream_url(
|
|
copilot_base,
|
|
openai_mod._resolve_openai_handler_path(
|
|
{},
|
|
handler_path=openai_mod._resolve_openai_chat_handler_path(
|
|
copilot_base, "claude-sonnet-5"
|
|
),
|
|
),
|
|
)
|
|
openai_url = openai_mod.build_copilot_upstream_url(
|
|
"https://api.openai.com",
|
|
openai_mod._resolve_openai_handler_path(
|
|
{},
|
|
handler_path=openai_mod._resolve_openai_chat_handler_path(
|
|
"https://api.openai.com", "gpt-5.4-mini"
|
|
),
|
|
),
|
|
)
|
|
|
|
assert gpt54_mini_url == "https://api.githubcopilot.com/responses"
|
|
assert claude_url == "https://api.githubcopilot.com/chat/completions"
|
|
assert openai_url == "https://api.openai.com/v1/chat/completions"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("entrypoint", ["passthrough", "streaming", "streaming-disconnected"])
|
|
@pytest.mark.parametrize(
|
|
("path", "expected_auth"),
|
|
[
|
|
(
|
|
"/v1/engines/gpt-41-copilot/completions",
|
|
"Bearer ghu_editor_seat_fixture",
|
|
),
|
|
("/chat/completions", "Bearer tid_operator_seat_fixture"),
|
|
],
|
|
ids=["native-editor-seat", "chat-operator-seat"],
|
|
)
|
|
async def test_real_forwarders_enforce_credential_and_secret_boundaries(
|
|
monkeypatch: pytest.MonkeyPatch, entrypoint: str, path: str, expected_auth: str
|
|
) -> None:
|
|
monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "tid_operator_seat_fixture")
|
|
monkeypatch.setenv("GITHUB_COPILOT_PROXY_URL", "https://gateway.example.invalid/v1")
|
|
monkeypatch.delenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", raising=False)
|
|
monkeypatch.setattr(paths, "_PROCESS_STATELESS", paths._PROCESS_STATELESS)
|
|
for name in (
|
|
"ANTHROPIC_API_URL",
|
|
"OPENAI_API_URL",
|
|
"GEMINI_API_URL",
|
|
"CLOUDCODE_API_URL",
|
|
"VERTEX_API_URL",
|
|
):
|
|
monkeypatch.setattr(HeadroomProxy, name, getattr(HeadroomProxy, name))
|
|
proxy = HeadroomProxy(
|
|
ProxyConfig(
|
|
stateless=True,
|
|
optimize=False,
|
|
disable_kompress=True,
|
|
discover_pipeline_extensions=False,
|
|
cache_enabled=False,
|
|
rate_limit_enabled=False,
|
|
cost_tracking_enabled=False,
|
|
)
|
|
)
|
|
content = b'data: {"choices":[{"text":"accepted"}]}\n\ndata: [DONE]\n\n'
|
|
|
|
class UpstreamStream(httpx.AsyncByteStream):
|
|
def __init__(self) -> None:
|
|
self.closed = False
|
|
|
|
async def __aiter__(self):
|
|
yield content
|
|
|
|
async def aclose(self) -> None:
|
|
self.closed = True
|
|
|
|
upstream_stream = UpstreamStream()
|
|
|
|
def credential_gate(request: httpx.Request) -> httpx.Response:
|
|
admitted = (
|
|
request.headers.get("authorization") == expected_auth
|
|
and request.headers.get("copilot-integration-id") == "vscode"
|
|
and "x-api-key" not in request.headers
|
|
)
|
|
if admitted:
|
|
return httpx.Response(
|
|
200,
|
|
stream=upstream_stream,
|
|
headers={"content-type": "text/event-stream"},
|
|
)
|
|
return httpx.Response(
|
|
401,
|
|
content=b'{"error":"wrong credential or leaked secret"}',
|
|
headers={"content-type": "application/json"},
|
|
)
|
|
|
|
headers = {
|
|
"authorization": "Bearer ghu_editor_seat_fixture",
|
|
"copilot-integration-id": "vscode",
|
|
"x-api-key": "unrelated-provider-secret",
|
|
}
|
|
base = (
|
|
"https://proxy.business.githubcopilot.com"
|
|
if path.startswith("/v1/engines/")
|
|
else "https://api.githubcopilot.com"
|
|
)
|
|
try:
|
|
async with httpx.AsyncClient(transport=httpx.MockTransport(credential_gate)) as client:
|
|
proxy.http_client = client
|
|
if entrypoint == "passthrough":
|
|
|
|
async def receive() -> dict[str, object]:
|
|
return {"type": "http.request", "body": b"{}", "more_body": False}
|
|
|
|
request = Request(
|
|
{
|
|
"type": "http",
|
|
"method": "POST",
|
|
"scheme": "http",
|
|
"server": ("proxy.test", 80),
|
|
"path": path,
|
|
"query_string": b"",
|
|
"headers": [(k.encode(), v.encode()) for k, v in headers.items()],
|
|
},
|
|
receive,
|
|
)
|
|
response = await proxy.handle_passthrough(request, base)
|
|
else:
|
|
response = await proxy._stream_response(
|
|
url=base + path,
|
|
headers=headers,
|
|
body={"model": "gpt-41-copilot"},
|
|
provider="openai",
|
|
model="gpt-41-copilot",
|
|
request_id="inline-auth-regression",
|
|
original_tokens=0,
|
|
optimized_tokens=0,
|
|
tokens_saved=0,
|
|
transforms_applied=[],
|
|
tags={},
|
|
optimization_latency=0.0,
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
if isinstance(response, StreamingResponse):
|
|
assert not upstream_stream.closed
|
|
if entrypoint == "streaming":
|
|
received = b"".join([chunk async for chunk in response.body_iterator])
|
|
assert received == content
|
|
if response.background is not None:
|
|
await response.background()
|
|
else:
|
|
assert response.body == content
|
|
assert upstream_stream.closed
|
|
finally:
|
|
proxy._compression_executor.shutdown()
|
|
proxy._background_compression_executor.shutdown()
|