Repository navigation
feat: runtime forward proxy rulesets for outbound egress routing - #248
Conversation
Deployments that generate heavy GitHub traffic (CI fleets in particular)
can get their egress IP throttled or banned. Forward proxy rulesets let
operators steer GitHub-destined traffic out through specific upstream
forward proxies at runtime, splitting or pinning load across egress paths.
- ForwardProxyRuleset model + CRUD store methods on all three backends
(SQLite, Postgres, Vault) with migration 011 and contract tests.
- ForwardProxyRouter compiles enabled rulesets into an immutable route
table and selects a proxy per outbound request via http.Transport.Proxy.
Rule layers resolve most-specific first: token -> app -> net (CIDR,
longest prefix) -> system -> ambient environment (ProxyFromEnvironment).
Algorithms: round_robin, weighted, sticky (FNV hash of client IP over
the weighted target list). Invalid targets/rules fail open to ambient.
- All outbound GitHub backends (API proxy, github.com passthrough,
codeload, Copilot) share one router-driven transport; route info is
seeded per request (client IP) and enriched after token resolution.
- Admin API: /api/forward-proxy-rulesets CRUD with validation, PATCH
partial-update semantics, immediate route-table reload on mutation,
and a periodic refresh for HA convergence.
- Metrics: forward_proxy_selection decision stage,
ghp_forward_proxy_select_total{ruleset,layer},
ghp_forward_proxy_rulesets_active gauge, with tests.
- Docs: features/forward-proxy-rulesets.md, how-it-works summary,
CLAUDE.md metric tables.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MWmuf2JwYiQ5VFeXHPWHxG
✅ E2E Test Results — Passed
Test Details
📸 Screenshots & report: Download artifacts Run #746 · 2026-09-17 00:13:17 UTC |
ghp's own outbound calls — OAuth login flows and token refresh, GitHub App installation token minting, username resolution lookups, and release redirect HEAD probes — are some of the most important traffic it emits: losing them to a banned egress IP takes down every client behind the proxy. Give operators the ability to pin this control traffic to its own egress path instead of always using the ambient environment. - New rule type "control" (no value, like "system"). Control traffic resolves control rule -> system rule -> ambient; token/app/net layers never apply since control calls are not attributable to a client. - NewForwardProxyControlTransport routes every request as control; it is installed on the app registry (and config-fallback provider), the auth handler's OAuth client, the username resolver, and the release HEAD probe client via new SetTransport hooks / an optional transport arg. - OAuth token refresh triggered inside a proxied request is re-classified via WithForwardProxyControl so it no longer inherits the triggering client's token/app/net routing. - Admin API accepts "control" rules (value must be empty); docs, metric label docs, and CLAUDE.md updated; router/API/metrics tests extended. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MWmuf2JwYiQ5VFeXHPWHxG
Release redirect HEAD probes target the operator's redirect mirror, not GitHub, and mirrors are typically internal — routing them through a GitHub egress proxy by default is the wrong assumption. Send them DIRECT (no proxy at all, not even the ambient environment) and let operators opt them into control-layer routing explicitly. - ForwardProxyRule gains include_non_github (JSON-stored, no migration), valid only on control rules. When true, control calls targeting non-GitHub hosts follow the control ruleset like GitHub-destined control traffic; when false or absent they are sent direct. - New NewForwardProxyNonGitHubControlTransport installed on the release HEAD-probe client; new "direct" layer label on ghp_forward_proxy_select_total for observability. - API validation rejects include_non_github on non-control rules; store contract, router, API, and metrics tests extended; docs updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MWmuf2JwYiQ5VFeXHPWHxG
…ders
A team may know something the operator's rules can't express — their own
egress path with IP allow-listing on the far side, needed only for
particular requests. Let clients select the upstream forward proxy per
request while still flowing through ghp, so scoping, audit logging, and
metrics all apply.
- Headers: X-GitHub-Proxy-Forward-HTTP / -HTTPS (http/https proxy URLs,
aliases) and X-GitHub-Proxy-Forward-SOCKS (socks5/socks5h). At most one
proxy per request; conflicting or invalid values return 400. The
headers are always stripped before forwarding upstream.
- Gated system-wide by forward_proxy.allow_request_header (default
false / GHP_FORWARD_PROXY_ALLOW_REQUEST_HEADER): honouring the headers
lets a client direct ghp to connect to an arbitrary proxy endpoint, so
operators must opt in. When disabled the headers are stripped silently.
- A client-specified proxy beats every ruleset layer; recorded as
layer="header" in ghp_forward_proxy_select_total plus a dedicated
ghp_forward_proxy_client_specified_total{scheme,token_type} counter
(the proxy URL itself is never a label — client-controlled).
- Docs: feature page section, configuration reference, CLAUDE.md; tests
for extraction/validation/stripping, precedence, and metrics.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MWmuf2JwYiQ5VFeXHPWHxG
Findings from the five-persona precommit-review skill (added here as .claude/skills/precommit-review/SKILL.md, adapted to ghp): - [blocker] GHP_FORWARD_PROXY_ALLOW_REQUEST_HEADER was documented but inert: the env TransformFunc splits sections at the first underscore and had no "forward" case, so the key never mapped to forward_proxy.allow_request_header. Add the mapping + regression test. - [major] Client-specified proxy headers are now honoured only after a ghx_/gha_ token has resolved. Without the gate, an unauthenticated caller on the passthrough path could use the header to make ghp dial arbitrary internal host:port targets (SSRF/port-scan). - [major] usernameResolver.SetTransport ran after WarmCache had spawned background GraphQL lookups — an unsynchronized transport write racing in-flight requests, and warm-cache traffic bypassed control routing. Transports are now installed immediately after construction. - [minor] Reload no longer logs rejected proxy target URLs verbatim (targets may embed userinfo credentials); log the redacted form. - [minor] Stale comments/docs from the direct-by-default change fixed (server wiring comment, NewReleasesHandler godoc, how-it-works summary); CLAUDE.md stage row now covers control-plane selections. - [minor] Route-info middleware extracted to a named function with tests (400 on invalid header, strip-when-disabled, IP seeding); new tests for PATCH proxies:[] rejection, StartRefresh, IPv6 net rules, and the header auth gate. - [minor] Vault name-uniqueness create/rename race documented as a known limitation (check-then-write, no CAS) per the Vault backend conventions; token/app rule values documented as opaque references that dangle after the referenced record is deleted. Deferred deliberately: replacing the substring-based duplicate-name 409 mapping with a store-level sentinel (architecture/portability minor) — it matches the existing cached-repositories pattern; aligning both belongs in a dedicated refactor per the CLAUDE.md convention of fixing patterns as they are touched repo-wide. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MWmuf2JwYiQ5VFeXHPWHxG
goodtune
left a comment
There was a problem hiding this comment.
Found five issues that should be addressed before merge. Four are annotated inline. One additional control-plane issue cannot be anchored because internal/proxy/enterprise.go is not part of GitHub's current PR diff:
[P2] Route team membership checks through control egress. newTeamChecker still constructs an http.Client with the default transport at internal/proxy/enterprise.go:326. In deployments where direct GitHub egress is unavailable or disallowed, installation-token minting follows control routing but the membership GET bypasses it, fails closed, and caches a false verdict for five minutes. Inject the control transport so membership checks select control → system as required by CLAUDE.md:88-102.
Five findings from the owner's review of #248: - [P1] Cached-repo git traffic now follows ruleset egress selection: gitcache.Handler gains SetTransport and the server installs the shared forward proxy transport. Upstream ls-refs/fetch requests already carry the inbound request context, so seeded route info (client IP + resolved token/app identity) selects layers exactly like the raw passthrough. - [P1] GHE-style API paths on the management host (/api/v3/*, /api/graphql via mux) now pass through forwardProxyRouteInfoMiddleware; previously they bypassed host-dispatch wrapping and silently fell back to ambient egress. - [P2] Enterprise team membership checks route via the control layer: EnterprisePolicy gains SetTransport (installed with the control transport) so membership GETs follow control -> system instead of dialing GitHub directly and caching a false negative for five minutes in proxy-only deployments. - [P2] Vault ruleset create/rename now claims the by-name index first with an atomic KV v2 CAS create and rolls the claim back if the record write fails — no sequence leaves a listed record without an index, and a transient failure no longer manufactures a phantom duplicate on retry. The known-limitations doc entry is updated accordingly. - [P2] GetForwardProxyRulesetByID returns wrapped database.ErrNotFound on all three backends per the sentinel-error convention; the API maps it to 404 via errors.Is, Vault's read-style ByName/List lookups tolerate stale index entries, and contract tests assert the sentinel. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MWmuf2JwYiQ5VFeXHPWHxG
|
All five review findings addressed in 06f9345:
Build, vet, and Generated by Claude Code |
NewEnterprisePolicy returns nil when github.enterprise_slug is empty (the feature-disabled default, including the E2E environment), and the server now calls SetTransport unconditionally — crashing the server at startup with a nil pointer dereference. Guard the nil receiver and the nil team checker, with a regression test covering both plus the enabled-without-identity case. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MWmuf2JwYiQ5VFeXHPWHxG
…ault name index Three review findings on the forward proxy ruleset work. HTTP/2 connection reuse defeated per-request routing. http.Transport consults Proxy only when it dials; once a destination negotiates HTTP/2, Go's bundled h2 transport pools connections by authority alone, so every later request to that host rode the first request's proxy — ignoring token rules, client-specified proxies and ruleset reloads. Reproduced: four HTTP/2 requests, one Proxy call. The transport constructors now return a routingTransport that resolves the proxy per request and dispatches to an http.Transport dedicated to that proxy, so HTTP/2 and connection pooling survive while each egress path keeps its own pool. The cache is bounded (client-specified proxies are caller-controlled) and evicts with idle connections closed. Applied to all three constructors, including control. Vault delete released the name reservation before deleting the record, so a failed record delete left a live ruleset whose name was free to claim — two rulesets under one supposedly unique name. Record is deleted first now, and index-cleanup failures are reported rather than swallowed. Vault rename overwrote the record unconditionally, so concurrent renames A->B and A->C could both claim their destination and both write; the loser left its name reserved forever. Updates now write with a compare-and-set on the record version read at the start, releasing the claim on conflict. Adds kvReadVersioned/kvWriteCAS alongside kvCreate, both withRelogin-wrapped and context-propagating. Lookups now reject index entries whose record no longer bears the name, and create reclaims a demonstrably stale reservation via CAS, so a failed cleanup is recoverable rather than permanent. Tests: HTTP/2 per-request selection regression, transport-per-proxy and cache bound, kvVersionOf shapes, name reuse after delete in the store contract. Docs updated. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MWmuf2JwYiQ5VFeXHPWHxG
…oxy-rulesets-akpkt9
Summary
Outbound GitHub traffic keeps its existing default — the ambient environment (
HTTPS_PROXYet al.) — but operators can now build forward proxy rulesets at runtime to deliberately steer GitHub-destined traffic across egress paths. Motivating case: CI fleets whose concentrated API/clone traffic gets an egress IP throttled or banned; splitting or pinning that traffic contains the blast radius.What's included
Data model & storage
ForwardProxyRuleset(name, description, algorithm, proxy targets with weights, rules, enabled) with CRUDStoremethods on all three backends (SQLite, Postgres, Vault) and migration011_add_forward_proxy_rulesets(unique name index, algorithm CHECK constraint).testForwardProxyRulesetCRUDcovering every field, name uniqueness, rename,ErrNotFoundpaths.Selection engine (
internal/proxy/forwardproxy.go)ForwardProxyRoutercompiles enabled rulesets into an immutable route table;Reloadswaps atomically.header→token→app→net(CIDR, longest prefix wins) →system→ ambient environment.round_robin(atomic counter),weighted(random over weight distribution, e.g. 80/20),sticky(FNV hash of client source IP over the weighted target list).Control-plane routing
controlrule type routes ghp's own outbound calls — OAuth login flows and token refresh, App installation token minting, username resolution lookups — via a dedicated egress path. This is ghp's most important traffic: losing it to a banned egress IP takes down every client behind the proxy.control→system→ ambient; token/app/net layers never apply (not attributable to a client). A dedicated control transport is installed on the app registry, auth handler, and username resolver; OAuth refresh triggered inside a proxied request is re-classified so it doesn't inherit the client's routing.include_non_github: trueon the control rule opts them into control-layer routing, giving non-GitHub domains the same treatment as GitHub targets.Per-request client selection
forward_proxy.allow_request_header: true(default false;GHP_FORWARD_PROXY_ALLOW_REQUEST_HEADER), a client may pick the forward proxy for a single request viaX-GitHub-Proxy-Forward-HTTP/-HTTPS(http/https proxies) orX-GitHub-Proxy-Forward-SOCKS(socks5/socks5h). Use case: a team with its own egress (e.g. IP allow-listed on the far side) that only needs it on particular requests.ghp_forward_proxy_client_specified_total{scheme,token_type}(proxy URL deliberately never a label).Wiring
http.Transportwhose per-requestProxyfunction consults the router; installed on the API proxy, github.com passthrough, codeload, and Copilot backends — connection pools are kept per selected proxy.server.client_ip_header) and enriched with token/app identity after token resolution in both the API handler and the git passthrough.Runtime management
/api/forward-proxy-rulesets(list/create/get/PATCH/delete) following the repo's validation conventions (UUID checks, MaxBytesReader/413, pointer-based PATCH semantics, 409 on duplicate names).Observability
forward_proxy_selection, countersghp_forward_proxy_select_total{ruleset,layer}(layer ∈ header/token/app/net/system/control/ambient/direct) andghp_forward_proxy_client_specified_total{scheme,token_type}, gaugeghp_forward_proxy_rulesets_active— all with tests; CLAUDE.md metric tables updated.Docs
docs/features/forward-proxy-rulesets.md(concepts, API examples, control-plane routing, per-request client selection, failure modes, known limitations), configuration reference, how-it-works summary, mkdocs nav.Testing
go build ./...,go vet ./...clean.Known limitations
net/systemrules.include_non_github.🤖 Generated with Claude Code