1 Connection Pooling & Client Certificates (mTLS to Backends)
vBlackOut edited this page 2026-08-14 01:41:23 +02:00

Connection Pooling & Client Certificates (mTLS to Backends)

This page explains how ProxyAuth manages outbound HTTP connections to your backends - why there are two separate connection pools in the codebase rather than one, and how client certificates (mTLS) work when a route needs them.


Two separate pools, for two separate code paths

This is worth understanding up front, since it's not obvious from the outside: ProxyAuth maintains two independent connection-pooling mechanisms, used by different parts of the request path.

network/shared_client.rs network/loadbalancing.rs
Used by The main proxy path (single-target routes), and error-page rendering Routes with backends configured (failover/load balancing)
Cache key A ClientKey - the configuration (egress proxy on/off + address, client cert on/off + paths) The backend URL itself
Purpose One client per distinct configuration, reused across whatever backend a route targets One client per backend, reused across whatever route targets that backend

In practice, these overlap in what they achieve (both avoid rebuilding a TLS-capable HTTP client on every request) but they're keyed differently because they serve different call sites with different needs - a single-target route mostly cares about "which cert/proxy settings does this need", while the load balancer's failover logic mostly cares about "which specific backend am I about to hit". See Load Balancing & Failover for the second pool's role in that flow specifically.


How the main pool works (shared_client.rs)

pub fn get_or_build_client(opts: ClientOptions, state: &Arc<AppConfig>) -> HttpsClient {
    let key = ClientKey::from_options(&opts);
    if let Some(client) = CLIENT_CACHE.get(&key) { return client.clone(); }
    // ... build and cache it
}

ClientOptions (and its cache-key twin ClientKey) captures everything that determines how a connection should be made:

pub struct ClientOptions {
    pub use_proxy:  bool,
    pub proxy_addr: Option<String>,
    pub use_cert:   bool,
    pub cert_path:  Option<String>,
    pub key_path:   Option<String>,
}

Every call with the same combination of these five fields gets back the same cached client (a cheap .clone() of an Arc-backed hyper client), rather than rebuilding TLS configuration and connection pools from scratch on every request. There's a separate cache (CLIENT_CACHE_PROXY) for the proxy-enabled variant, keyed the same way.

Pool tuning comes straight from config.json:

Setting Effect
keep_alive Both the idle connection timeout (pool_idle_timeout) and the underlying TCP keepalive interval.
max_idle_per_host pool_max_idle_per_host - how many idle connections are kept warm per backend host.

See config.json Reference for both.


Client certificates (mTLS to a backend)

Set per-route in routes.yml:

cert:
  file: "/etc/proxyauth/certs/client.pk12"
  key: "/etc/proxyauth/certs/client.key"

(See routes.yml Reference for the basic syntax.) When a route has cert set, build_hyper_client_cert() builds a client that presents this certificate during the TLS handshake with the backend - standard mutual TLS, for backends that authenticate their callers by client cert rather than (or in addition to) anything ProxyAuth itself checks.

Root trust: the client trusts both your OS's native root store and Mozilla's bundled root list (webpki-roots) at the same time - both are loaded and merged into one trust store. This is a slightly unusual choice (most tools pick one or the other) but the practical effect is simply a broader set of trusted CAs than either source alone.

Fail-safe, not fail-closed: if the certificate or key can't be loaded, or the pair doesn't parse as a valid TLS identity, ProxyAuth logs a warning and silently falls back to a normal connection without client auth - it does not refuse to start or block the route:

let cert_chain = match load_certs(opts.cert_path.as_ref().unwrap()) {
    Ok(c) if !c.is_empty() => c,
    _ => {
        tracing::warn!("TLS: cert chain vide ou invalide, fallback sans client auth");
        return build_hyper_client_normal(state);
    }
};

Practical implication: if your backend requires a client certificate to accept connections at all, a misconfigured cert/key path won't surface as a startup error - it'll surface as the backend itself rejecting the connection (or serving degraded/default content), while ProxyAuth's own logs only show a warn-level message you have to know to look for. If mTLS to a backend suddenly stops working, check for this warning in your logs (see Logging) before assuming the problem is on the backend's side.


The egress proxy client

Set per-route via proxy/proxy_config in routes.yml (see routes.yml Reference). build_hyper_client_proxy() wraps the same HTTPS connector behind a ProxyConnector, routing all traffic for that client through the configured upstream proxy address (Intercept::All - every request, not just some). If proxy_addr is left unset while use_proxy is true, it silently defaults to http://127.0.0.1:8888.


A loose end worth knowing about: unused pre-built clients

AppState (built once at startup, in main.rs) has three client fields:

pub client_normal: Client<HttpsConnector<HttpConnector>, BoxBody>,
#[allow(dead_code)]
pub client_with_cert: Client<HttpsConnector<HttpConnector>, BoxBody>,
#[allow(dead_code)]
pub client_with_proxy: Client<ProxyConnector<HttpsConnector<HttpConnector>>, BoxBody>,

These are built once when the server starts (build_hyper_client_normal/_cert/_proxy, called directly against a fixed, mostly-empty ClientOptions) and stored on AppState. In practice, none of the three are ever read anywhere in the codebase - every actual request instead goes through get_or_build_client(), which builds (or reuses, via CLIENT_CACHE) a client dynamically based on each route's real cert/proxy settings, not these fixed startup-time ones. The #[allow(dead_code)] annotations on two of the three confirm this is known, not accidental.

Practical effect: none on request handling - traffic is unaffected, since the dynamic pool is what's actually used. The only cost is a small amount of wasted work at startup (building three HTTP clients, one of which does TLS certificate loading, for values that are then never read) - harmless, but worth knowing if you're reading main.rs/AppState and wondering why a client field appears unused.


Practical guidance

  • Connections are pooled per configuration, not per request - you don't need to worry about connection-setup overhead on every proxied request; the cache handles reuse automatically as long as cert/proxy settings for a route stay the same between requests (they do, since they come from static routes.yml config).
  • A bad cert/key path degrades silently - if you rely on mTLS to a backend, actively monitor for the TLS: cert chain vide ou invalide / TLS: clé vide ou invalide warnings rather than assuming a route working "without errors" means the certificate is actually being presented.
  • max_idle_per_host and keep_alive are shared, server-wide settings - there's no per-route override; if one backend needs a very different pooling profile than another (e.g. a much slower backend that benefits from more idle connections), that's not currently configurable independently per route.

See also