Skip to main content

hoike_server/
forwarding.rs

1//! Startup-validated outbound clients for nonce forwarding (October audit
2//! F10, design S8).
3//!
4//! Forwarding trust belongs to each configured CA. `build_forward_clients`
5//! constructs one reused reqwest client per forward-enabled CA label:
6//!
7//! - with `forward_ca`, the PEM bundle is parsed at construction, must yield
8//!   at least one certificate, and becomes the *only* trusted root material
9//!   (`tls_built_in_root_certs(false)` + one `add_root_certificate` per
10//!   parsed root). Hostname and validity checking stay on; invalid-certificate
11//!   or invalid-hostname acceptance is never enabled.
12//! - without `forward_ca`, the client keeps reqwest's bundled WebPKI roots
13//!   (the `rustls-tls` feature selects webpki-roots — not the system store).
14//!
15//! All clients share the serving policy that `forward_request` enforced from
16//! the start: a 10-second timeout and no redirects. An unreadable, empty, or
17//! malformed root file, a `forward_ca` on a non-HTTPS target, or a duplicate
18//! CA label is a configuration error — construction fails instead of
19//! silently falling back to a different trust policy. `hoike check` calls the
20//! same function, so it fails on the same inputs without opening a listener
21//! or sending a request.
22
23use hoike_core::config::Config;
24use std::collections::{HashMap, HashSet};
25use std::time::Duration;
26
27/// Build the per-CA forwarding clients described by `config`, keyed by CA
28/// label. Only CAs with a `forward_to` target get a client; a non-forwarding
29/// CA requires none.
30pub fn build_forward_clients(config: &Config) -> Result<HashMap<String, reqwest::Client>, String> {
31    let mut labels: HashSet<&str> = HashSet::new();
32    let mut clients = HashMap::new();
33    for ca in &config.ca {
34        // Duplicate labels must reject rather than overwrite one CA's trust
35        // policy with another's. (Config validation rejects these too; this
36        // keeps the constructor self-contained for `hoike check` and tests.)
37        if !labels.insert(ca.label.as_str()) {
38            return Err(format!(
39                "duplicate CA label '{}' — each forwarding CA needs a unique trust policy",
40                ca.label
41            ));
42        }
43        let Some(url) = ca.forward_to.as_deref() else {
44            continue;
45        };
46        let mut builder = base_client_builder();
47        if let Some(ca_path) = &ca.forward_ca {
48            // Pinned private roots are meaningless without TLS: reject a
49            // custom root configured for a cleartext (or otherwise non-HTTPS)
50            // target rather than shipping trust material that is never used.
51            if !url.starts_with("https://") {
52                return Err(format!(
53                    "CA '{}': forward_ca requires an https:// forward_to (got '{url}')",
54                    ca.label
55                ));
56            }
57            let pem = std::fs::read(ca_path).map_err(|e| {
58                format!(
59                    "CA '{}': cannot read forward_ca {}: {e}",
60                    ca.label,
61                    ca_path.display()
62                )
63            })?;
64            let roots = reqwest::Certificate::from_pem_bundle(&pem).map_err(|e| {
65                format!(
66                    "CA '{}': invalid forward_ca PEM bundle {}: {e}",
67                    ca.label,
68                    ca_path.display()
69                )
70            })?;
71            if roots.is_empty() {
72                return Err(format!(
73                    "CA '{}': forward_ca {} contains no certificates",
74                    ca.label,
75                    ca_path.display()
76                ));
77            }
78            builder = builder.tls_built_in_root_certs(false);
79            for root in roots {
80                builder = builder.add_root_certificate(root);
81            }
82        }
83        let client = builder
84            .build()
85            .map_err(|e| format!("CA '{}': building forwarding client: {e}", ca.label))?;
86        clients.insert(ca.label.clone(), client);
87    }
88    Ok(clients)
89}
90
91/// The shared forward-channel policy: 10-second timeout, no redirects.
92fn base_client_builder() -> reqwest::ClientBuilder {
93    reqwest::Client::builder()
94        .timeout(Duration::from_secs(10))
95        .redirect(reqwest::redirect::Policy::none())
96}