forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

tls.rs193 lines, 8.4 KiBHistoryRawDownload
1//! TLS material for the AI bridge listener.
2//!
3//! QUIC has no plaintext mode, so the bridge always needs a certificate. Two
4//! sources: a PEM pair from config (`AI_TLS_CERT` / `AI_TLS_KEY`) for a real
5//! deployment, or a self-signed one generated at boot for local development.
6//!
7//! The certificate only proves *the backend* to a dialling service. It is not
8//! the authentication: that is the shared token in the `Hello` frame, checked
9//! in constant time by [`super::server`]. A self-signed certificate therefore
10//! costs nothing in a private network — the service pins the fingerprint the
11//! bridge logs at startup.
12
13use std::fs;
14use std::sync::Arc;
15use std::time::Duration;
16
17use quinn::crypto::rustls::QuicServerConfig;
18use rustls::pki_types::{CertificateDer, PrivateKeyDer};
19
20use crate::ai::error::AiError;
21use crate::constant::{AI_ALPN, AI_IDLE_TIMEOUT_SECS, AI_MAX_CONCURRENT_PER_WORKER};
22
23/// The certificate chain the listener presents, plus the leaf in DER so a
24/// caller (the boot log, an in-process test service) can pin it.
25#[derive(Debug)]
26pub struct BridgeTls {
27 pub server_config: quinn::ServerConfig,
28 pub leaf: CertificateDer<'static>,
29}
30
31/// Install the process-wide rustls crypto provider, once. Both the bridge and
32/// any in-process test client need it, and rustls refuses a second install —
33/// an already-installed provider is success, not an error.
34pub fn install_crypto_provider() {
35 let _ = rustls::crypto::ring::default_provider().install_default();
36}
37
38/// Build the listener's TLS config from a PEM pair, or self-signed when *both*
39/// paths are absent.
40///
41/// Half-configured is a setup error, never a fallback: with one path set the
42/// operator plainly meant to present a real certificate, and self-signing
43/// instead would hand every dialling service a throwaway `localhost` leaf,
44/// regenerated on every boot, with nothing in the log to say so — every service
45/// pinning the real fingerprint then fails the handshake and every chatbot send
46/// degrades to a `503` with no cause visible anywhere. Note that config's
47/// `parse_optional` folds a blank variable to `None`, so `AI_TLS_KEY=""`
48/// arrives here as an absent path like any other.
49pub fn build(cert_path: Option<&str>, key_path: Option<&str>) -> Result<BridgeTls, AiError> {
50 install_crypto_provider();
51 let (chain, key) = match (cert_path, key_path) {
52 (Some(c), Some(k)) => load_pem(c, k)?,
53 (Some(_), None) => {
54 return Err(AiError::Setup(
55 "AI_TLS_CERT is set but AI_TLS_KEY is not — set both for a real certificate, \
56 or neither for a self-signed development one"
57 .into(),
58 ));
59 }
60 (None, Some(_)) => {
61 return Err(AiError::Setup(
62 "AI_TLS_KEY is set but AI_TLS_CERT is not — set both for a real certificate, \
63 or neither for a self-signed development one"
64 .into(),
65 ));
66 }
67 (None, None) => self_signed()?,
68 };
69 let leaf = chain
70 .first()
71 .cloned()
72 .ok_or_else(|| AiError::Setup("certificate chain is empty".into()))?;
73
74 let mut tls = rustls::ServerConfig::builder()
75 .with_no_client_auth()
76 .with_single_cert(chain, key)
77 .map_err(|e| {
78 AiError::Setup(format!("certificate and key do not form a valid pair: {e}"))
79 })?;
80 // ALPN is the version gate: a service built against a future frame format
81 // announces a different protocol id and is refused during the TLS
82 // handshake, before either side can misread the other's bytes.
83 tls.alpn_protocols = vec![AI_ALPN.to_vec()];
84
85 let quic_tls = QuicServerConfig::try_from(tls)
86 .map_err(|e| AiError::Setup(format!("TLS config is not usable for QUIC: {e}")))?;
87 let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_tls));
88
89 let mut transport = quinn::TransportConfig::default();
90 // A service that stops answering is dropped within this window, which is
91 // what removes it from the registry — there is no application heartbeat.
92 transport.max_idle_timeout(Some(
93 Duration::from_secs(AI_IDLE_TIMEOUT_SECS)
94 .try_into()
95 .expect("idle timeout fits in a QUIC varint"),
96 ));
97 // Bounds how many control streams one connection may open toward us; the
98 // request streams flow the other way and are bounded by the *client's*
99 // config, so this is only about incoming ones.
100 transport.max_concurrent_bidi_streams(
101 u32::try_from(AI_MAX_CONCURRENT_PER_WORKER)
102 .unwrap_or(64)
103 .into(),
104 );
105 transport.max_concurrent_uni_streams(0u32.into());
106 server_config.transport_config(Arc::new(transport));
107
108 Ok(BridgeTls {
109 server_config,
110 leaf,
111 })
112}
113
114/// Read a PEM certificate chain and private key off disk.
115fn load_pem(
116 cert_path: &str,
117 key_path: &str,
118) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), AiError> {
119 let cert_pem = fs::read(cert_path)
120 .map_err(|e| AiError::Setup(format!("cannot read AI_TLS_CERT `{cert_path}`: {e}")))?;
121 let key_pem = fs::read(key_path)
122 .map_err(|e| AiError::Setup(format!("cannot read AI_TLS_KEY `{key_path}`: {e}")))?;
123 let chain = rustls_pemfile::certs(&mut cert_pem.as_slice())
124 .collect::<Result<Vec<_>, _>>()
125 .map_err(|e| AiError::Setup(format!("`{cert_path}` is not a PEM certificate: {e}")))?;
126 if chain.is_empty() {
127 return Err(AiError::Setup(format!(
128 "`{cert_path}` contained no certificates"
129 )));
130 }
131 let key = rustls_pemfile::private_key(&mut key_pem.as_slice())
132 .map_err(|e| AiError::Setup(format!("`{key_path}` is not a PEM private key: {e}")))?
133 .ok_or_else(|| AiError::Setup(format!("`{key_path}` contained no private key")))?;
134 Ok((chain, key))
135}
136
137/// Generate a throwaway certificate for `localhost` / `127.0.0.1`.
138fn self_signed() -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), AiError> {
139 let names = vec!["localhost".to_string(), "127.0.0.1".to_string()];
140 let certified = rcgen::generate_simple_self_signed(names).map_err(|e| {
141 AiError::Setup(format!("could not generate a self-signed certificate: {e}"))
142 })?;
143 let key = PrivateKeyDer::try_from(certified.signing_key.serialize_der())
144 .map_err(|e| AiError::Setup(format!("generated key is unusable: {e}")))?;
145 Ok((vec![certified.cert.der().clone()], key))
146}
147
148/// SHA-256 of the leaf certificate, hex, for the startup log. A service pins
149/// this instead of installing a CA.
150pub fn fingerprint(leaf: &CertificateDer<'_>) -> String {
151 use sha2::{Digest, Sha256};
152 hex::encode(Sha256::digest(leaf.as_ref()))
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[tokio::test]
160 async fn self_signed_config_builds_and_pins() {
161 let tls = build(None, None).expect("self-signed path works with no config");
162 let fp = fingerprint(&tls.leaf);
163 assert_eq!(fp.len(), 64, "sha-256 hex is 64 chars");
164 // Regenerating gives a different key, so the fingerprint must differ —
165 // otherwise pinning would be meaningless.
166 let other = build(None, None).unwrap();
167 assert_ne!(fp, fingerprint(&other.leaf));
168 }
169
170 #[tokio::test]
171 async fn a_missing_cert_path_is_a_setup_error_not_a_silent_fallback() {
172 // Half-configured TLS must fail loudly: silently self-signing when the
173 // operator meant to supply a real certificate would be worse than
174 // refusing to boot.
175 let err = build(Some("/nonexistent/cert.pem"), Some("/nonexistent/key.pem")).unwrap_err();
176 assert!(matches!(err, AiError::Setup(m) if m.contains("AI_TLS_CERT")));
177
178 // The half-*configured* case, which used to take the self-signed arm:
179 // one path set and the other absent (unset, or blank — `parse_optional`
180 // folds a blank variable to `None` before it reaches here) must name
181 // the missing variable, not quietly mint a throwaway certificate.
182 let no_key = build(Some("/nonexistent/cert.pem"), None).unwrap_err();
183 assert!(
184 matches!(&no_key, AiError::Setup(m) if m.contains("AI_TLS_KEY")),
185 "a cert with no key must name the key: {no_key}"
186 );
187 let no_cert = build(None, Some("/nonexistent/key.pem")).unwrap_err();
188 assert!(
189 matches!(&no_cert, AiError::Setup(m) if m.contains("AI_TLS_CERT")),
190 "a key with no cert must name the cert: {no_cert}"
191 );
192 }
193}