#![allow(dead_code)] use std::sync::Arc; use std::net::IpAddr; use rcgen::{Certificate, CertificateParams, DistinguishedName, DnType, SanType}; use tokio_rustls::rustls::{Certificate as RustlsCert, PrivateKey}; /// Generate a self-signed certificate and matching key for test TLS servers. pub fn generate_self_signed_cert() -> (RustlsCert, PrivateKey) { let mut params = CertificateParams::default(); params.distinguished_name = DistinguishedName::new(); params .distinguished_name .push(DnType::CommonName, "niom-turn-test"); params.alg = &rcgen::PKCS_ECDSA_P256_SHA256; params .subject_alt_names .push(SanType::DnsName("localhost".into())); params.subject_alt_names.push(SanType::IpAddress( "127.0.0.1" .parse::() .expect("localhost loopback ip"), )); let cert = Certificate::from_params(params).expect("certificate params"); let pem = cert.serialize_der().expect("cert der"); let key = cert.serialize_private_key_der(); (RustlsCert(pem), PrivateKey(key)) } /// Build a rustls server config for tests using a generated certificate. pub fn build_server_config() -> tokio_rustls::rustls::ServerConfig { let (cert, key) = generate_self_signed_cert(); let mut cfg = tokio_rustls::rustls::ServerConfig::builder() .with_safe_defaults() .with_no_client_auth() .with_single_cert(vec![cert], key) .expect("valid test server config"); cfg.alpn_protocols = vec![b"turn".to_vec()]; cfg } /// Build a rustls client config trusting the generated test certificate. pub fn build_client_config(cert: &RustlsCert) -> tokio_rustls::rustls::ClientConfig { let mut root_store = tokio_rustls::rustls::RootCertStore::empty(); root_store.add(cert).expect("add root cert"); tokio_rustls::rustls::ClientConfig::builder() .with_safe_defaults() .with_root_certificates(root_store) .with_no_client_auth() } /// Wrap tls config into acceptor for tests. pub fn build_acceptor(cfg: tokio_rustls::rustls::ServerConfig) -> tokio_rustls::TlsAcceptor { tokio_rustls::TlsAcceptor::from(Arc::new(cfg)) }