[edge] Proxy: Pingora data plane with SNI certs, forward-auth, header rules, health checks, ACME
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals)
|
||||
//! without touching connections in flight.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use rustls::server::{ClientHello, ResolvesServerCert};
|
||||
use rustls::sign::CertifiedKey;
|
||||
use rustls_pki_types::pem::PemObject;
|
||||
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CertStore {
|
||||
certs: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
|
||||
}
|
||||
|
||||
impl CertStore {
|
||||
pub fn insert(&self, host: &str, key: CertifiedKey) {
|
||||
let key = Arc::new(key);
|
||||
self.certs.rcu(|m| {
|
||||
let mut m = HashMap::clone(m);
|
||||
m.insert(host.to_owned(), key.clone());
|
||||
m
|
||||
});
|
||||
}
|
||||
|
||||
pub fn has(&self, host: &str) -> bool {
|
||||
self.certs.load().contains_key(host)
|
||||
}
|
||||
}
|
||||
|
||||
impl ResolvesServerCert for CertStore {
|
||||
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
|
||||
// No SNI or an unknown name: no certificate, the handshake fails (as with Caddy).
|
||||
let name = hello.server_name()?.to_ascii_lowercase();
|
||||
self.certs.load().get(&name).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a PEM chain and PEM private key into a rustls key pair, checking they match.
|
||||
pub fn certified_key(cert_pem: &[u8], key_pem: &[u8]) -> Result<CertifiedKey, String> {
|
||||
let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(cert_pem)
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(|e| format!("cannot parse the certificate chain: {e}"))?;
|
||||
if chain.is_empty() {
|
||||
return Err("the certificate file has no certificate".into());
|
||||
}
|
||||
// Never include key bytes in an error.
|
||||
let key = PrivateKeyDer::from_pem_slice(key_pem)
|
||||
.map_err(|_| "cannot parse the private key".to_owned())?;
|
||||
let provider = rustls::crypto::ring::default_provider();
|
||||
CertifiedKey::from_der(chain, key, &provider)
|
||||
.map_err(|e| format!("certificate and key do not form a usable pair: {e}"))
|
||||
}
|
||||
|
||||
/// `notAfter` of the first certificate in a PEM chain, as Unix seconds.
|
||||
pub fn not_after(cert_pem: &[u8]) -> Option<i64> {
|
||||
let first = CertificateDer::pem_slice_iter(cert_pem).next()?.ok()?;
|
||||
let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?;
|
||||
Some(cert.validity().not_after.timestamp())
|
||||
}
|
||||
Reference in New Issue
Block a user