fix(proxy): restrict urlopen SSL context ALPN to http/1.1 (#3567)

## Description

`build_urlopen_context()` in `headroom/proxy/ssl_context.py` is only
used by `copilot_auth.py`'s `_urlopen()` helper, which wraps stdlib
`urllib.request`/`http.client` for the GitHub Copilot device-code auth
flow. It was reusing whatever `build_httpx_verify()` returns, which
(when a custom CA bundle or `HEADROOM_TLS_STRICT=0` is configured)
advertises ALPN `["h2", "http/1.1"]` -- correct for the proxy's httpx
upstream client, but `http.client` has no HTTP/2 support at all.

Under a TLS-inspecting corporate MITM that honors ALPN (GlobalProtect,
per the issue), the far end negotiates HTTP/2 with the client.
`http.client` then tries to read the response as HTTP/1.1 and misreads
the HTTP/2 connection-preface/frame bytes as a garbled status line,
surfacing as `http.client.BadStatusLine: ]MAGIC: Bad MAGIC` on `POST
https://github.com/login/device/code`.

Closes #3344

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

- `build_urlopen_context()` now restricts the returned context's ALPN to
`["http/1.1"]` only, since its sole caller (`urllib.request`) can't
speak anything else.
- Left `build_httpx_verify()`, `find_ca_bundle()`, and the shared
context builders untouched -- the proxy's httpx client still offers `h2`
as before.
- Added regression tests in `tests/test_ssl_context.py` covering the
custom-CA-bundle case, the `HEADROOM_TLS_STRICT=0` case, and the
no-bundle/default case (unaffected, still returns `None`).

## Testing

- [x] Unit tests pass (`pytest tests/test_ssl_context.py`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ uv run --no-project --with pytest --with urllib3 pytest tests/test_ssl_context.py -v
...
tests/test_ssl_context.py::TestBuildUrlopenContext::test_custom_ca_context_only_offers_http_1_1 PASSED
tests/test_ssl_context.py::TestBuildUrlopenContext::test_default_returns_none PASSED
tests/test_ssl_context.py::TestBuildUrlopenContext::test_toggle_off_context_only_offers_http_1_1 PASSED
...
======================== 34 passed, 1 warning in 3.50s =========================
```

I confirmed the new tests are real regression tests, not tautologies:
reverting the one-line fix (removing the
`set_alpn_protocols(["http/1.1"])` call) makes
`test_custom_ca_context_only_offers_http_1_1` and
`test_toggle_off_context_only_offers_http_1_1` fail, because the context
would still carry `["h2", "http/1.1"]`.

## Real Behavior Proof

- Environment: this repo's `main`, Python 3.13, pytest run via an
isolated `uv` environment (the editable install's Rust extension build
wasn't needed for this pure-Python module/test).
- Exact command / steps: shown above.
- Observed result: all 34 tests in `tests/test_ssl_context.py` pass,
including the 3 new ones for `build_urlopen_context()`.
- Not tested: an actual TLS-inspecting MITM / live GitHub Copilot
device-auth flow -- I don't have that network setup available, so this
is verified at the ALPN-configuration level (the confirmed root cause)
rather than an end-to-end repro of the corporate proxy environment.

## Runtime Rollout Safety

- Rollout-managed feature(s): none -- this only affects TLS context
construction for the `urllib.request`-based Copilot device-auth path,
gated the same way it already was (custom CA bundle env var, or
`HEADROOM_TLS_STRICT=0`).
- Minimum rollout channel: n/a
- Stable/default behavior changed: no -- the no-bundle/default case
(`build_httpx_verify()` returns `True`) is unchanged, still returns
`None`. Only the ALPN list on an already-returned custom context is
narrowed.
- Kill switch / disable path: n/a -- restricting ALPN to `http/1.1` can
only fix broken connections for this urlopen-only caller; it can't
regress anything since `http.client` never spoke `h2` to begin with.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert the 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
- [ ] I have made corresponding changes to the documentation (n/a --
internal helper, no public docs reference its ALPN behavior)
- [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`
This commit is contained in:
Waqas Ahmed
2026-09-24 11:32:27 -05:00
committed by GitHub
parent b0dfa33478
commit 5baa439ebf
2 changed files with 44 additions and 1 deletions
+6 -1
View File
@@ -198,7 +198,12 @@ def build_urlopen_context() -> ssl.SSLContext | None:
"""
verify = build_httpx_verify()
return verify if isinstance(verify, ssl.SSLContext) else None
if not isinstance(verify, ssl.SSLContext):
return None
# urllib.request/http.client only implements HTTP/1.1 framing. Offering h2
# can make a TLS-inspecting MITM negotiate a protocol it cannot parse.
verify.set_alpn_protocols(["http/1.1"])
return verify
def apply_global_tls_relaxation() -> bool:
+38
View File
@@ -21,6 +21,7 @@ from headroom.proxy import ssl_context
from headroom.proxy.ssl_context import (
apply_global_tls_relaxation,
build_httpx_verify,
build_urlopen_context,
find_ca_bundle,
tls_strict_disabled,
)
@@ -286,6 +287,43 @@ class TestBuildHttpxVerify:
assert ctx.cert_store_stats()["x509_ca"] == 1
class TestBuildUrlopenContext:
def test_custom_ca_context_only_offers_http_1_1(self, monkeypatch, ca_pem_file):
_clean_env(monkeypatch)
monkeypatch.setenv("SSL_CERT_FILE", ca_pem_file)
created_context = FakeSSLContext()
def fake_create_default_context(*, cafile: str | None = None):
assert cafile == ca_pem_file
return created_context
monkeypatch.setattr(ssl_context.ssl, "SSLContext", FakeSSLContext)
monkeypatch.setattr(ssl_context.ssl, "create_default_context", fake_create_default_context)
ctx = build_urlopen_context()
assert ctx is created_context
assert created_context.alpn_protocols == ["http/1.1"]
def test_default_returns_none(self, monkeypatch):
"""No CA bundle, strict on → build_httpx_verify() is True, nothing to restrict."""
_clean_env(monkeypatch)
assert build_urlopen_context() is None
def test_toggle_off_context_only_offers_http_1_1(self, monkeypatch):
"""No CA bundle, strict OFF → still a real context, still restricted to http/1.1."""
_clean_env(monkeypatch)
monkeypatch.setenv("HEADROOM_TLS_STRICT", "0")
created_context = FakeSSLContext()
monkeypatch.setattr(ssl_context.ssl, "SSLContext", FakeSSLContext)
monkeypatch.setattr(ssl_context.ssl, "create_default_context", lambda: created_context)
ctx = build_urlopen_context()
assert ctx is created_context
assert created_context.alpn_protocols == ["http/1.1"]
class TestApplyGlobalTlsRelaxation:
def test_noop_when_strict_on(self, monkeypatch):
_clean_env(monkeypatch)