Repository navigation
Description
Summary
Every *http.Client produced by networking.HttpClientBuilder.Build() has a connection pool that can never be drained — not by an idle timeout, and not by an explicit CloseIdleConnections() call. Each such client that performs one request leaks an idle persistConn (2 goroutines + 1 socket/fd) for the lifetime of the process.
On the auth-server upstream path this compounds: authserver.New builds one private *http.Transport per configured upstream, server.Close() never releases them, and any embedder that constructs an authserver.Server more than once in a process leaks the whole set per construction.
Three changes fix it, in dependency order. The first is a self-contained bug fix with no API change; the second is a small additive API; the third is an API surface decision worth discussing separately.
Observed against v0.46.0.
Why: the two independent defects in the shared client builder
HttpClientBuilder.Build() — pkg/networking/http_client.go:277
1. Idle connections never expire. Build() constructs its transport setting only TLSHandshakeTimeout and ResponseHeaderTimeout:
transport := &http.Transport{
TLSHandshakeTimeout: b.tlsHandshakeTimeout,
ResponseHeaderTimeout: b.responseHeaderTimeout,
}
transport.DisableKeepAlives = b.disableKeepAlivesIdleConnTimeout, MaxIdleConns and MaxIdleConnsPerHost are left at their zero values. IdleConnTimeout: 0 means no timeout — an idle keep-alive connection is retained forever, holding its readLoop/writeLoop goroutine pair. http.DefaultTransport sets IdleConnTimeout: 90 * time.Second precisely to avoid this; this builder does not, so a client that is dropped after a single request never releases anything and the transport itself stays reachable from the runtime's connection bookkeeping.
This only affects builders that leave keep-alives on. WithDisableKeepAlives(true) callers (e.g. the DCR resolver's guarded client) are unaffected.
2. CloseIdleConnections() is silently a no-op. Build() always wraps the transport:
var clientTransport http.RoundTripper = &ValidatingTransport{
Transport: transport,
InsecureAllowHTTP: b.insecureAllowHTTP,
}ValidatingTransport implements RoundTrip and nothing else (http_client.go:110-116). http.Client.CloseIdleConnections() is a type assertion on the outermost transport:
func (c *Client) CloseIdleConnections() {
type closeIdler interface{ CloseIdleConnections() }
if tr, ok := c.transport().(closeIdler); ok {
tr.CloseIdleConnections()
}
}*ValidatingTransport does not satisfy closeIdler, so the assertion fails and the call returns having done nothing — no error, no log. The same applies to the authTokenFile path, where oauth2.Transport is the outermost wrapper and also has no CloseIdleConnections (it exposes only RoundTrip, CancelRequest, base).
So the remediation a reader would naturally reach for is already unavailable, and its failure is invisible.
There are ~12 non-test call sites of the three builder constructors (pkg/auth/dcr, pkg/auth/discovery, pkg/auth/oauth, pkg/auth/token.go, pkg/auth/github_provider.go, pkg/authserver/server/tokenexchange, pkg/authserver/upstream, pkg/config/registry.go, pkg/oauthproto/grants.go, pkg/registry/...), so this is not specific to one consumer.
Why: how this surfaces on the auth-server upstream path
upstream.NewOIDCProvider builds a private client per provider (pkg/authserver/upstream/oidc.go:184) via newHTTPClientForHost → networking.NewHostScopedClientBuilder(...).Build() (oauth2.go:909), and keep-alives are deliberately left on there — a documented and reasonable choice, since the client is retained on BaseOAuth2Provider and reused for many token-refresh/userinfo calls against one operator-configured host. NewOAuth2Provider does the same (oauth2.go:319).
Those providers are then held by the server (server_impl.go:44, upstreams []handlers.NamedUpstream) and by upstreamTokenRefresher.providers. But:
// Close releases resources held by the server.
func (s *server) Close() error {
slog.Debug("closing OAuth authorization server")
return s.storage.Close()
}server.Close() (server_impl.go:399) closes storage only. Neither BaseOAuth2Provider nor OIDCProviderImpl has any close method, and nothing walks s.upstreams on shutdown. So even a single clean New → Close cycle abandons one transport per configured upstream, each with its discovery connection still idle and unexpiring.
Where it becomes a real leak rather than a shutdown untidiness. An embedder that keeps a long-lived process and reconstructs the auth server to change its upstream set — a live-reconfiguration pattern the current API otherwise supports well, since New accepts an existing storage.Storage and KeyProvider so token/JWKS continuity is preserved across a reconstruction — leaks one transport (2 goroutines, 1 fd) per OIDC upstream per reconstruction, unbounded. The superseded server cannot be Close()d to reclaim them, because Close() also closes the storage the new server is now serving through. There is currently no way to release only the upstream connections.
The pathological case is a reconstruction that fails repeatedly: it re-runs discovery on every attempt, so a mistyped or unreachable issuer_url turns into a steady goroutine/fd climb at the retry cadence with no successful state to stop it.
Secondarily, any consumer that builds an upstream provider per request pays a fresh discovery round trip and a leaked transport per request. NewOIDCProvider is a reasonable-looking public constructor and its cost is not obvious from its signature; that trap goes away once the pool is bounded and closeable.
Proposed changes
1. Bound the pool in the shared builder — pkg/networking/http_client.go
In Build(), set IdleConnTimeout (90s, matching http.DefaultTransport) and a bounded MaxIdleConnsPerHost.
Unconditional, no API change, no consumer opt-in. On its own this converts every leak of this shape in the repo from unbounded to self-draining, and makes an abandoned transport garbage-collectable. Worth landing on its own merits independently of 2 and 3.
Suggested test: a client from Build() that performs one request against an httptest server, then is dropped, releases its idle connection within the timeout (or, more cheaply, assert the transport's IdleConnTimeout is non-zero — a regression guard against the field being dropped again).
2. Make the pool reachable — pkg/networking, pkg/authserver/upstream, pkg/authserver
func (t *ValidatingTransport) CloseIdleConnections(), forwarding tot.Transport. Without this, everything below is still a no-op, and so is any consumer's ownclient.CloseIdleConnections()call today. Same treatment (passthrough or unwrap) for theoauth2.Transportwrapper on theauthTokenFilepath.CloseIdleConnections()onBaseOAuth2Provider(inherited byOIDCProviderImpl), delegating top.httpClient.CloseIdleConnections().CloseIdleConnections()on theauthserver.Serverinterface, kept distinct fromClose(), walkings.upstreams.Close()should call it before closing storage, which fixes the shutdown path.
Suggestion on the provider-level method: expose it as an optional capability that the server type-asserts, rather than adding it to the upstream.OAuth2Provider interface (oauth2.go:68). doc.go:72 invites external implementations of that interface, so widening it is a breaking change for them; a capability assertion is additive and degrades to a no-op for a provider that doesn't implement it.
The Close()/CloseIdleConnections() split is the load-bearing part for embedders. An embedder retiring a superseded server must not call Close(), because that closes shared storage; a storage-free CloseIdleConnections() is what lets it drain in-flight work and then release just that server's upstream connections. Without the split there is no correct call to make.
Suggested test: New with two OIDC upstreams against httptest issuers, then Close(), leaves no idle connections and no residual goroutines (goleak, or an fd/goroutine count across N cycles).
3. Export the upstream provider factory — pkg/authserver
withUpstreamFactory already exists as an unexported test seam (server_impl.go:75), with defaultUpstreamFactory as the production implementation (server_impl.go:62). Expose it — either as a public ServerOption or as a Config.UpstreamFactory func(ctx, *UpstreamConfig) (upstream.OAuth2Provider, error) field.
Two things this buys that 1 and 2 do not:
- Reconstruction becomes structurally free rather than merely bounded. A caller can build providers with
upstream.WithHTTPClient/WithOAuth2HTTPClient(both already public —oidc.go:131,oauth2.go:303) passing a client shared per issuer host, so repeated reconstruction creates no new transports at all and reuses warm connections. - Per-upstream failure isolation becomes possible. Today upstream construction inside
Newis all-or-nothing: one unreachable or mistypedissuer_urlfails the whole call, and the returned error does not name which upstream caused it. A caller owning the factory can apply a per-upstream deadline, and skip or substitute a single failing provider while the rest serve. (A smaller, non-API alternative that would help regardless: include the offending upstream'sNamein the errorNewreturns when a provider fails to construct.)
This one is a genuine API surface commitment — it makes the component that validates upstream ID tokens caller-substitutable — so it deserves its own discussion and shouldn't block 1 and 2. Precedent for the shape: authserver.Config already accepts injected KeyProvider, storage.Storage and UpstreamFilter collaborators on equally security-relevant paths.
Impact if only 1 lands
Leaks stop being unbounded and drain on their own within the idle timeout. That alone would be a meaningful improvement; 2 makes retirement deterministic and fixes the shutdown path; 3 removes the churn entirely and addresses the isolation gap.
Activity
Bound and close HTTP client connection pools (#6480)
Release per-issuer JWKS refresh workers on auth-server shutdown (#6493)