AnyBot/src/net.rs

51 lines
2.6 KiB
Rust

//! 一個 HTTP 用戶端: every HTTP client AnyBot makes starts here, so they all trust the same
//! certificates — the public ones every browser knows plus the ones this computer trusts itself
//! (tunnel::trusted_roots). Before, only the account server's client did: a connector, a model
//! service or a webhook on the local network with a certificate its company signs (trusted by
//! the computer, as in the browser) failed with "unknown issuer" everywhere else.
//!
//! Each caller still sets its own timeouts, redirects and user agent on top. `clippy.toml` refuses
//! `ureq::Agent::config_builder` anywhere but here (grok-build does the same for its HTTP clients).
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
/// The certificates an AnyBot HTTP client accepts (made once: the system's list takes a moment).
fn tls() -> ureq::tls::TlsConfig {
static T: OnceLock<ureq::tls::TlsConfig> = OnceLock::new();
T.get_or_init(|| {
let roots: Vec<_> = crate::tunnel::trusted_roots().iter().map(|c| ureq::tls::Certificate::from_der(c.as_ref()).to_owned()).collect();
ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::new_with_certs(&roots)).build()
})
.clone()
}
/// An HTTP client's settings, with AnyBot's certificates already in: add timeouts and the rest,
/// then `.build().into()`.
#[allow(clippy::disallowed_methods)]
pub fn config() -> ureq::config::ConfigBuilder<ureq::typestate::AgentScope> {
ureq::Agent::config_builder().tls_config(tls())
}
/// The common client: `secs` for the whole request, an HTTP error status is an answer (not an
/// Err). One per timeout, kept (its connections are reused).
pub fn agent(secs: u64) -> ureq::Agent {
static AGENTS: OnceLock<Mutex<HashMap<u64, ureq::Agent>>> = OnceLock::new();
AGENTS.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()).entry(secs).or_insert_with(|| config().timeout_global(Some(Duration::from_secs(secs))).http_status_as_error(false).build().into()).clone()
}
#[cfg(test)]
mod tests {
#[test]
fn every_client_trusts_the_same_certificates() {
// The public list at least, and the system's on top.
assert!(crate::tunnel::trusted_roots().len() >= webpki_root_certs::TLS_SERVER_ROOT_CERTS.len());
let a = super::agent(7);
let b = super::agent(7);
// (The same client for the same timeout: its connections are reused.)
assert_eq!(format!("{:?}", a.config().timeouts().global), format!("{:?}", b.config().timeouts().global));
assert!(!a.config().http_status_as_error());
}
}