Files
headroom/tests/test_copilot_inline_client_auth.py
ad62166ba3 fix(copilot): preserve native inline OAuth identity (#4144)
## 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>
2026-10-24 08:38:54 -07:00

137 lines
5.0 KiB
Python

"""Inline editor OAuth must not be replaced with the proxy operator's seat."""
from __future__ import annotations
import logging
import re
import httpx
import pytest
from headroom import copilot_auth
@pytest.fixture(autouse=True)
def operator_token(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "tid_operator_seat_fixture")
monkeypatch.delenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_COPILOT_PROXY_URL", raising=False)
@pytest.mark.asyncio
async def test_inline_editor_uses_its_own_seat_and_integration() -> None:
headers = await copilot_auth.apply_copilot_api_auth(
{
"authorization": "Bearer ghu_editor_seat_fixture",
"Copilot-Integration-Id": "vscode",
"x-api-key": "unrelated-provider-secret",
"X-Api-Key": "another-provider-secret",
},
url="https://copilot-proxy.githubusercontent.com/v1/engines/gpt-41-copilot/completions",
)
assert headers["authorization"] == "Bearer ghu_editor_seat_fixture"
assert headers["Copilot-Integration-Id"] == "vscode"
assert "x-api-key" not in httpx.Headers(headers)
@pytest.mark.asyncio
async def test_inline_oauth_is_not_relabelled_as_the_chat_integration() -> None:
headers = await copilot_auth.apply_copilot_api_auth(
{"Authorization": "Bearer ghu_editor_seat_fixture"},
url="https://proxy.business.githubcopilot.com/v1/engines/gpt-41-copilot/completions",
)
assert headers["Authorization"] == "Bearer ghu_editor_seat_fixture"
assert all(name.lower() != "copilot-integration-id" for name in headers)
@pytest.mark.asyncio
async def test_inline_oauth_exception_does_not_widen_chat_auth() -> None:
headers = await copilot_auth.apply_copilot_api_auth(
{
"authorization": "Bearer ghu_editor_seat_fixture",
"AUTHORIZATION": "Bearer stale-other-seat",
"x-api-key": "unrelated-provider-secret",
"X-Api-Key": "another-provider-secret",
},
url="https://api.githubcopilot.com/chat/completions",
)
assert headers["Authorization"] == "Bearer tid_operator_seat_fixture"
assert "authorization" not in headers
assert "AUTHORIZATION" not in headers
assert "x-api-key" not in httpx.Headers(headers)
@pytest.mark.asyncio
async def test_inline_editor_keeps_its_seat_through_a_prefixed_gateway(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("GITHUB_COPILOT_PROXY_URL", "https://gateway.example.invalid/copilot")
headers = await copilot_auth.apply_copilot_api_auth(
{
"authorization": "Bearer ghu_editor_seat_fixture",
"Copilot-Integration-Id": "vscode",
},
url="https://gateway.example.invalid/copilot/v1/engines/gpt-41-copilot/completions",
)
assert headers["authorization"] == "Bearer ghu_editor_seat_fixture"
assert headers["Copilot-Integration-Id"] == "vscode"
@pytest.mark.asyncio
@pytest.mark.parametrize(
("gateway", "upstream"),
[
(
"https://gateway.example.invalid/v1",
"https://proxy.business.githubcopilot.com/v1/engines/gpt-41-copilot/completions",
),
(
"https://proxy.business.githubcopilot.com/v1",
"http://proxy.business.githubcopilot.com/v1/engines/gpt-41-copilot/completions",
),
(
"https://proxy.business.githubcopilot.com:8443/v1",
"https://proxy.business.githubcopilot.com/v1/engines/gpt-41-copilot/completions",
),
(
"https://gateway.example.invalid/v",
"https://gateway.example.invalid/v1/engines/gpt-41-copilot/completions",
),
],
ids=["other-host", "other-scheme", "other-port", "segment-boundary"],
)
async def test_gateway_prefix_cannot_rewrite_an_unrelated_native_path(
monkeypatch: pytest.MonkeyPatch, gateway: str, upstream: str
) -> None:
monkeypatch.setenv("GITHUB_COPILOT_PROXY_URL", gateway)
headers = await copilot_auth.apply_copilot_api_auth(
{
"authorization": "Bearer ghu_editor_seat_fixture",
"Copilot-Integration-Id": "vscode",
"x-api-key": "unrelated-provider-secret",
},
url=upstream,
)
header_view = httpx.Headers(headers)
assert header_view["authorization"] == "Bearer ghu_editor_seat_fixture"
assert header_view["Copilot-Integration-Id"] == "vscode"
assert "x-api-key" not in header_view
@pytest.mark.asyncio
async def test_inline_debug_kind_never_discloses_the_editor_credential(caplog) -> None:
secret = "ghu_sensitive_editor_credential_do_not_log"
caplog.set_level(logging.INFO, logger="headroom.copilot_auth")
await copilot_auth.apply_copilot_api_auth(
{"authorization": f"Bearer {secret}"},
url="https://copilot-proxy.githubusercontent.com/v1/engines/gpt-41-copilot/completions",
)
assert set(re.findall(r"\bkind=(\S+)", caplog.text)) == {"ghu_***"}
assert secret not in caplog.text
assert secret.removeprefix("ghu_") not in caplog.text