Skip to main content

agentmux_srv_core/
http_client.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one place srv builds an HTTP client.
5//!
6//! reqwest 0.13 reads the machine's certificates when it builds a client, and on Linux it refuses to build one when
7//! there are none ("No CA certificates were loaded from the system"). `Client::new()` turns that refusal into a panic,
8//! so a server on a machine without `ca-certificates` died at start. Here a client is always built:
9//!
10//!   * With system certificates the client trusts exactly them, as before.
11//!   * Without any, the client trusts nothing: every https request fails (an untrusted certificate), plain http to the
12//!     local machine and the LAN keeps working, and the log and the connectivity error say why. Nothing is bundled,
13//!     no other trust source is read, and no verification is relaxed.
14//!
15//! Every client srv builds goes through [`builder`], [`client_with`] or [`client`]; `scripts/check-srv-http-clients.mjs` fails CI on a
16//! direct `reqwest::Client::new()` or `reqwest::Client::builder()` anywhere else in srv's own code.
17
18use std::sync::OnceLock;
19
20use agentmux_common::system_certs::no_system_certs_message;
21
22/// What srv's https requests are checked against on this machine.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum Trust {
25    /// The machine's own certificates.
26    System,
27    /// Nothing: the machine has no certificates (the reason says what reqwest reported).
28    Nothing { reason: String },
29}
30
31/// Finds out what the machine offers by building a client the way reqwest does by default. Reads the certificates
32/// each time it is called; [`trust`] keeps the answer.
33fn probe() -> Trust {
34    agentmux_common::tls_provider::install_ring_provider();
35    match reqwest::Client::builder().build() {
36        Ok(_) => Trust::System,
37        Err(e) => Trust::Nothing { reason: chain(&e) },
38    }
39}
40
41/// An error and its causes, on one line.
42fn chain(e: &dyn std::error::Error) -> String {
43    let mut out = e.to_string();
44    let mut cause = e.source();
45    while let Some(c) = cause {
46        out.push_str(": ");
47        out.push_str(&c.to_string());
48        cause = c.source();
49    }
50    out
51}
52
53/// What the machine offers, found out once per process. The first call that finds no certificates says so in the log.
54pub fn trust() -> &'static Trust {
55    static TRUST: OnceLock<Trust> = OnceLock::new();
56    TRUST.get_or_init(|| {
57        let found = probe();
58        if let Trust::Nothing { reason } = &found {
59            tracing::warn!(reason = %reason, "{}", no_system_certs_message());
60        }
61        found
62    })
63}
64
65/// True on a machine with no system certificates, where every https request fails.
66pub fn no_system_certs() -> bool {
67    matches!(trust(), Trust::Nothing { .. })
68}
69
70/// A client builder for srv's own requests: set what the site needs (timeouts, headers, proxy) and `build()`.
71/// On a machine with no system certificates it trusts nothing, so `build()` still works.
72pub fn builder() -> reqwest::ClientBuilder {
73    agentmux_common::tls_provider::install_ring_provider();
74    let builder = reqwest::Client::builder();
75    match trust() {
76        Trust::System => builder,
77        Trust::Nothing { .. } => builder.tls_certs_only(Vec::<reqwest::Certificate>::new()),
78    }
79}
80
81/// A client with reqwest's defaults, for a site that sets nothing. Never fails: the one way a build can fail with
82/// nothing to trust is a missing TLS provider, which this module installs itself.
83pub fn client() -> reqwest::Client {
84    builder().build().unwrap_or_else(|e| {
85        tracing::error!(error = %chain(&e), "building the HTTP client failed; using one that trusts nothing");
86        distrusting_client()
87    })
88}
89
90/// A client built from the site's own settings (timeouts, headers, redirect rules, proxy), for a site with nowhere to
91/// return an error to. Never fails. The settings come as a function because a builder is used up by `build()`, and a
92/// build that fails (the certificates the probe saw are gone since: a bundle removed or replaced while the server runs)
93/// is tried again with the same settings and nothing to trust, so a site's redirect rule or `no_proxy` is never lost
94/// and every https request still fails closed. Only if that fails too, [`client`] is the last step.
95pub fn client_with(settings: impl Fn(reqwest::ClientBuilder) -> reqwest::ClientBuilder) -> reqwest::Client {
96    match settings(builder()).build() {
97        Ok(c) => c,
98        Err(first) => {
99            tracing::error!(error = %chain(&first), "building the HTTP client failed; trying again with no certificates to trust");
100            agentmux_common::tls_provider::install_ring_provider();
101            match settings(reqwest::Client::builder().tls_certs_only(Vec::<reqwest::Certificate>::new())).build() {
102                Ok(c) => c,
103                Err(second) => {
104                    tracing::error!(error = %chain(&second), "the site's settings cannot build a client; using one with the defaults that trusts nothing");
105                    distrusting_client()
106                }
107            }
108        }
109    }
110}
111
112/// The client that trusts nothing, built with no other setting: the last step when a build fails.
113fn distrusting_client() -> reqwest::Client {
114    reqwest::Client::builder().tls_certs_only(Vec::<reqwest::Certificate>::new()).build().unwrap_or_else(|e| {
115        // Unreachable once the provider is installed: an empty set of roots is a valid configuration.
116        panic!("the TLS provider is missing, so no HTTP client can be built: {}", chain(&e))
117    })
118}
119
120/// What to say when an https request failed: on a machine with no system certificates and a failed certificate check,
121/// that there are none and what to install; otherwise the error as it is.
122pub fn explain(e: &reqwest::Error) -> String {
123    explain_with(e, no_system_certs())
124}
125
126fn explain_with(e: &reqwest::Error, no_certs: bool) -> String {
127    let https = e.url().is_some_and(|u| u.scheme() == "https");
128    if no_certs && https && chain(e).contains("invalid peer certificate") {
129        format!("{} ({})", no_system_certs_message(), chain(e))
130    } else {
131        e.to_string()
132    }
133}
134
135#[cfg(test)]
136#[path = "http_client_tests.rs"]
137mod tests;