1use actix_tls::accept::rustls_0_23::TlsStream;
10use actix_web::body::{BoxBody, MessageBody};
11use actix_web::dev::{Extensions, ServiceRequest, ServiceResponse};
12use actix_web::http::{Method, StatusCode};
13use actix_web::middleware::Next;
14use actix_web::rt::net::TcpStream;
15use actix_web::{HttpResponse, ResponseError};
16use feldera_types::error::{DetailedError, ErrorResponse};
17use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
18use rustls::client::verify_server_cert_signed_by_trust_anchor;
19use rustls::crypto::{CryptoProvider, verify_tls13_signature};
20use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
21use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
22use rustls::server::{ParsedCertificate, WebPkiClientVerifier};
23use rustls::{
24 ClientConfig, DigitallySignedStruct, DistinguishedName, RootCertStore, ServerConfig,
25 SignatureScheme,
26};
27use serde::Serialize;
28use std::any::Any;
29use std::borrow::Cow;
30use std::fmt;
31use std::sync::Arc;
32use tracing::warn;
33use uuid::Uuid;
34
35pub const REQUIRE_CLIENT_CERTIFICATES_ENV: &str = "FELDERA_REQUIRE_CLIENT_CERTIFICATES";
38
39pub const EXTRA_CLIENT_CERTIFICATE_URIS_ENV: &str = "FELDERA_EXTRA_CLIENT_CERTIFICATE_URIS";
41
42pub const CONTROL_PLANE_CERTIFICATE_URI: &str = "urn:feldera:control-plane";
44
45const PIPELINE_CERTIFICATE_URI_PREFIX: &str = "urn:feldera:pipeline:";
47
48const FELDERA_URI_PREFIX: &str = "urn:feldera:";
50
51fn is_feldera_uri(uri: &str) -> bool {
52 uri.get(..FELDERA_URI_PREFIX.len())
53 .is_some_and(|prefix| prefix.eq_ignore_ascii_case(FELDERA_URI_PREFIX))
54}
55
56pub fn pipeline_certificate_uri(pipeline_id: Uuid) -> String {
58 format!("{PIPELINE_CERTIFICATE_URI_PREFIX}{pipeline_id}")
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum Caller {
64 Anonymous,
66 ControlPlane,
67 Pipeline(Uuid),
68 External(String),
70}
71
72impl Caller {
73 pub fn from_certificate(cert: &CertificateDer<'_>) -> Self {
76 let Ok(cert) = webpki::EndEntityCert::try_from(cert) else {
77 return Self::Anonymous;
78 };
79 let mut callers = cert.valid_uri_names().filter_map(|uri| {
80 if uri == CONTROL_PLANE_CERTIFICATE_URI {
81 Some(Self::ControlPlane)
82 } else if let Some(id) = uri.strip_prefix(PIPELINE_CERTIFICATE_URI_PREFIX) {
83 Uuid::parse_str(id).ok().map(Self::Pipeline)
84 } else if is_feldera_uri(uri) {
85 None
87 } else {
88 Some(Self::External(uri.to_string()))
89 }
90 });
91 match (callers.next(), callers.next()) {
92 (Some(caller), None) => caller,
93 _ => Self::Anonymous,
95 }
96 }
97
98 pub fn record(connection: &dyn Any, extensions: &mut Extensions) {
101 let caller = connection
102 .downcast_ref::<TlsStream<TcpStream>>()
103 .and_then(|stream| stream.get_ref().1.peer_certificates())
104 .and_then(|certs| certs.first())
105 .map_or(Self::Anonymous, Self::from_certificate);
106 extensions.insert(caller);
107 }
108
109 pub fn of(req: &ServiceRequest) -> Self {
111 req.conn_data::<Self>().cloned().unwrap_or(Self::Anonymous)
112 }
113}
114
115pub async fn authorize<B: MessageBody>(
118 server: &'static str,
119 is_allowed: impl FnOnce(&Caller, &Method, &str) -> bool,
120 req: ServiceRequest,
121 next: Next<B>,
122) -> Result<ServiceResponse<B>, actix_web::Error> {
123 let caller = Caller::of(&req);
124 if is_allowed(&caller, req.method(), req.path()) {
125 return next.call(req).await;
126 }
127 let method = req.method().to_string();
128 let path = req.path().to_string();
129 warn!("The {server} server refused {method} {path} from {caller:?}");
130 Err(match caller {
131 Caller::Anonymous => ClientAuthError::ClientCertificateRequired {
132 server,
133 method,
134 path,
135 },
136 _ => ClientAuthError::CallerNotAllowed {
137 server,
138 caller: format!("{caller:?}"),
139 method,
140 path,
141 },
142 }
143 .into())
144}
145
146#[derive(Debug, Serialize)]
148#[serde(untagged)]
149pub enum ClientAuthError {
150 ClientCertificateRequired {
151 server: &'static str,
152 method: String,
153 path: String,
154 },
155 CallerNotAllowed {
156 server: &'static str,
157 caller: String,
158 method: String,
159 path: String,
160 },
161}
162
163impl DetailedError for ClientAuthError {
164 fn error_code(&self) -> Cow<'static, str> {
165 match self {
166 Self::ClientCertificateRequired { .. } => Cow::from("ClientCertificateRequired"),
167 Self::CallerNotAllowed { .. } => Cow::from("CallerNotAllowed"),
168 }
169 }
170}
171
172impl fmt::Display for ClientAuthError {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 match self {
175 Self::ClientCertificateRequired {
176 server,
177 method,
178 path,
179 } => write!(
180 f,
181 "The {server} server requires a client certificate for {method} {path}: present a certificate that the private CA signed (control plane: --https-client-cert-path)"
182 ),
183 Self::CallerNotAllowed {
184 server,
185 caller,
186 method,
187 path,
188 } => write!(
189 f,
190 "{caller} may not send {method} {path} to the {server} server"
191 ),
192 }
193 }
194}
195
196impl std::error::Error for ClientAuthError {}
197
198impl ResponseError for ClientAuthError {
199 fn status_code(&self) -> StatusCode {
200 match self {
201 Self::ClientCertificateRequired { .. } => StatusCode::UNAUTHORIZED,
202 Self::CallerNotAllowed { .. } => StatusCode::FORBIDDEN,
203 }
204 }
205
206 fn error_response(&self) -> HttpResponse<BoxBody> {
207 HttpResponse::build(self.status_code()).json(ErrorResponse::from_error_nolog(self))
208 }
209}
210
211pub fn crypto_provider() -> Arc<CryptoProvider> {
215 CryptoProvider::get_default()
216 .cloned()
217 .unwrap_or_else(|| Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
218}
219
220pub fn client_certificate_verifier(
226 ca_chain: &[CertificateDer<'static>],
227) -> Result<Arc<dyn ClientCertVerifier>, String> {
228 let issuing_ca = ca_chain
229 .first()
230 .ok_or("the CA chain holds no certificate")?;
231 let mut roots = RootCertStore::empty();
232 roots
233 .add(issuing_ca.clone())
234 .map_err(|e| format!("invalid CA certificate: {e}"))?;
235 WebPkiClientVerifier::builder_with_provider(Arc::new(roots), crypto_provider())
236 .allow_unauthenticated()
237 .build()
238 .map_err(|e| format!("client certificate verifier: {e}"))
239}
240
241pub struct PipelineClientAuth {
245 pub own: Caller,
246 pub extra_client_uris: Vec<String>,
248 pub verifier: Arc<dyn ClientCertVerifier>,
249}
250
251impl PipelineClientAuth {
252 pub fn from_chain(
253 chain: &[CertificateDer<'static>],
254 extra_client_uris: &[String],
255 ) -> Result<Self, String> {
256 if let Some(uri) = extra_client_uris
259 .iter()
260 .find(|uri| uri.is_empty() || uri.contains(char::is_whitespace) || is_feldera_uri(uri))
261 {
262 return Err(format!(
263 "extra client URI '{uri}' must be non-empty, have no whitespace, and lie outside {FELDERA_URI_PREFIX}, which Feldera components use"
264 ));
265 }
266 let (leaf, ca_chain) = chain
267 .split_first()
268 .ok_or("the certificate file holds no certificate")?;
269 let own @ Caller::Pipeline(_) = Caller::from_certificate(leaf) else {
270 return Err(format!(
271 "the certificate names no pipeline: client certificates need the URI SAN {PIPELINE_CERTIFICATE_URI_PREFIX}<id>, which the runner adds"
272 ));
273 };
274 if ca_chain.is_empty() {
275 return Err(
276 "the certificate file holds no CA chain after the leaf to verify clients with"
277 .to_string(),
278 );
279 }
280 Ok(Self {
281 own,
282 extra_client_uris: extra_client_uris.to_vec(),
283 verifier: client_certificate_verifier(ca_chain)?,
284 })
285 }
286
287 pub fn is_allowed(&self, caller: &Caller) -> bool {
291 match caller {
292 Caller::ControlPlane => true,
293 Caller::Pipeline(_) => *caller == self.own,
294 Caller::External(uri) => self.extra_client_uris.contains(uri),
295 Caller::Anonymous => false,
296 }
297 }
298}
299
300#[derive(Clone, Debug)]
302pub struct PipelinePeerTls {
303 pub client: Arc<ClientConfig>,
304 pub server: Arc<ServerConfig>,
305}
306
307impl PipelinePeerTls {
308 pub fn from_chain(
313 chain: Vec<CertificateDer<'static>>,
314 key: PrivateKeyDer<'static>,
315 ) -> Result<Self, String> {
316 let verifier = Arc::new(PipelinePeerVerifier::from_chain(&chain)?);
317 let provider = verifier.provider.clone();
318 let no_tls13 = |e| format!("the crypto provider does not support TLS 1.3: {e}");
319 let bad_key = |e| {
320 format!(
321 "the private key does not match the pipeline certificate, or its type is not supported: {e}"
322 )
323 };
324 let server = ServerConfig::builder_with_provider(provider.clone())
325 .with_protocol_versions(&[&rustls::version::TLS13])
326 .map_err(no_tls13)?
327 .with_client_cert_verifier(verifier.clone())
328 .with_single_cert(chain.clone(), key.clone_key())
329 .map_err(bad_key)?;
330 let client = ClientConfig::builder_with_provider(provider)
331 .with_protocol_versions(&[&rustls::version::TLS13])
332 .map_err(no_tls13)?
333 .dangerous()
340 .with_custom_certificate_verifier(verifier)
341 .with_client_auth_cert(chain, key)
342 .map_err(bad_key)?;
343 Ok(Self {
344 client: Arc::new(client),
345 server: Arc::new(server),
346 })
347 }
348}
349
350#[derive(Debug)]
353struct PipelinePeerVerifier {
354 own: Caller,
355 roots: Arc<RootCertStore>,
356 provider: Arc<CryptoProvider>,
357 client_verifier: Arc<dyn ClientCertVerifier>,
358}
359
360impl PipelinePeerVerifier {
361 fn from_chain(chain: &[CertificateDer<'static>]) -> Result<Self, String> {
364 let (leaf, ca_chain) = chain
365 .split_first()
366 .ok_or("the certificate file holds no certificate")?;
367 let own @ Caller::Pipeline(_) = Caller::from_certificate(leaf) else {
368 return Err(format!(
369 "the certificate names no pipeline: peer certificates need the URI SAN {PIPELINE_CERTIFICATE_URI_PREFIX}<id>, which the runner adds"
370 ));
371 };
372 let issuing_ca = ca_chain
373 .first()
374 .ok_or("the certificate file holds no CA chain after the leaf to verify peers with: the runner appends the chain of the private CA (Helm value `caSecretRef`)")?;
375 let mut roots = RootCertStore::empty();
376 roots
377 .add(issuing_ca.clone())
378 .map_err(|e| format!("invalid CA certificate: {e}"))?;
379 let roots = Arc::new(roots);
380 let provider = crypto_provider();
381 Ok(Self {
382 own,
383 client_verifier: WebPkiClientVerifier::builder_with_provider(
384 roots.clone(),
385 provider.clone(),
386 )
387 .build()
388 .map_err(|e| format!("peer certificate verifier: {e}"))?,
389 roots,
390 provider,
391 })
392 }
393
394 fn check_identity(&self, end_entity: &CertificateDer<'_>) -> Result<(), rustls::Error> {
395 let caller = Caller::from_certificate(end_entity);
396 if caller == self.own {
397 Ok(())
398 } else {
399 Err(rustls::Error::General(format!(
400 "peer certificate identifies {caller:?}, not this pipeline ({:?})",
401 self.own
402 )))
403 }
404 }
405}
406
407fn tls12_refused() -> rustls::Error {
410 rustls::Error::General("exchange between hosts allows only TLS 1.3".to_string())
411}
412
413impl ServerCertVerifier for PipelinePeerVerifier {
414 fn verify_server_cert(
420 &self,
421 end_entity: &CertificateDer<'_>,
422 intermediates: &[CertificateDer<'_>],
423 _server_name: &ServerName<'_>,
424 _ocsp_response: &[u8],
425 now: UnixTime,
426 ) -> Result<ServerCertVerified, rustls::Error> {
427 verify_server_cert_signed_by_trust_anchor(
428 &ParsedCertificate::try_from(end_entity)?,
429 &self.roots,
430 intermediates,
431 now,
432 self.provider.signature_verification_algorithms.all,
433 )?;
434 self.check_identity(end_entity)?;
435 Ok(ServerCertVerified::assertion())
436 }
437
438 fn verify_tls12_signature(
439 &self,
440 _message: &[u8],
441 _cert: &CertificateDer<'_>,
442 _dss: &DigitallySignedStruct,
443 ) -> Result<HandshakeSignatureValid, rustls::Error> {
444 Err(tls12_refused())
445 }
446
447 fn verify_tls13_signature(
448 &self,
449 message: &[u8],
450 cert: &CertificateDer<'_>,
451 dss: &DigitallySignedStruct,
452 ) -> Result<HandshakeSignatureValid, rustls::Error> {
453 verify_tls13_signature(
454 message,
455 cert,
456 dss,
457 &self.provider.signature_verification_algorithms,
458 )
459 }
460
461 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
462 self.provider
463 .signature_verification_algorithms
464 .supported_schemes()
465 }
466}
467
468impl ClientCertVerifier for PipelinePeerVerifier {
469 fn root_hint_subjects(&self) -> &[DistinguishedName] {
470 self.client_verifier.root_hint_subjects()
471 }
472
473 fn verify_client_cert(
474 &self,
475 end_entity: &CertificateDer<'_>,
476 intermediates: &[CertificateDer<'_>],
477 now: UnixTime,
478 ) -> Result<ClientCertVerified, rustls::Error> {
479 let verified = self
480 .client_verifier
481 .verify_client_cert(end_entity, intermediates, now)?;
482 self.check_identity(end_entity)?;
483 Ok(verified)
484 }
485
486 fn verify_tls12_signature(
487 &self,
488 _message: &[u8],
489 _cert: &CertificateDer<'_>,
490 _dss: &DigitallySignedStruct,
491 ) -> Result<HandshakeSignatureValid, rustls::Error> {
492 Err(tls12_refused())
493 }
494
495 fn verify_tls13_signature(
496 &self,
497 message: &[u8],
498 cert: &CertificateDer<'_>,
499 dss: &DigitallySignedStruct,
500 ) -> Result<HandshakeSignatureValid, rustls::Error> {
501 self.client_verifier
502 .verify_tls13_signature(message, cert, dss)
503 }
504
505 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
506 self.client_verifier.supported_verify_schemes()
507 }
508}
509
510#[cfg(test)]
511mod tests {
512 use super::crypto_provider;
513 use super::{
514 CONTROL_PLANE_CERTIFICATE_URI, Caller, PipelineClientAuth, PipelinePeerTls,
515 PipelinePeerVerifier, client_certificate_verifier, pipeline_certificate_uri,
516 };
517 use rcgen::{
518 BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer,
519 KeyPair, SanType,
520 };
521 use rustls::pki_types::{
522 CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime,
523 };
524 use rustls::{ClientConfig, ClientConnection, ServerConfig, ServerConnection};
525 use std::sync::Arc;
526 use uuid::Uuid;
527
528 const PIPELINE_A: Uuid = Uuid::from_u128(0xa);
529 const PIPELINE_B: Uuid = Uuid::from_u128(0xb);
530
531 fn ca() -> (Issuer<'static, KeyPair>, CertificateDer<'static>) {
532 named_ca("ca", None)
533 }
534
535 fn named_ca(
537 name: &str,
538 parent: Option<&Issuer<'static, KeyPair>>,
539 ) -> (Issuer<'static, KeyPair>, CertificateDer<'static>) {
540 let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
541 params.distinguished_name.push(DnType::CommonName, name);
542 params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
543 let key = KeyPair::generate().unwrap();
544 let cert = match parent {
545 Some(parent) => params.signed_by(&key, parent),
546 None => params.self_signed(&key),
547 }
548 .unwrap();
549 (Issuer::new(params, key), cert.der().clone())
550 }
551
552 fn leaf(issuer: &Issuer<'static, KeyPair>, uris: &[String]) -> CertificateDer<'static> {
553 let mut params = CertificateParams::default();
554 params.subject_alt_names = uris
555 .iter()
556 .map(|uri| SanType::URI(uri.as_str().try_into().unwrap()))
557 .collect();
558 params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
559 let key = KeyPair::generate().unwrap();
560 params.signed_by(&key, issuer).unwrap().der().clone()
561 }
562
563 fn caller_of(uris: &[String]) -> Caller {
564 Caller::from_certificate(&leaf(&ca().0, uris))
565 }
566
567 const SIDECAR: &str = "urn:example:sidecar";
568
569 #[test]
571 fn caller_from_certificate() {
572 let control_plane = CONTROL_PLANE_CERTIFICATE_URI.to_string();
573 let a = pipeline_certificate_uri(PIPELINE_A);
574 let b = pipeline_certificate_uri(PIPELINE_B);
575 let sidecar = SIDECAR.to_string();
576 assert_eq!(
577 caller_of(std::slice::from_ref(&control_plane)),
578 Caller::ControlPlane
579 );
580 assert_eq!(
581 caller_of(std::slice::from_ref(&a)),
582 Caller::Pipeline(PIPELINE_A)
583 );
584 assert_eq!(caller_of(&[]), Caller::Anonymous);
585 assert_eq!(
586 caller_of(&["urn:feldera:pipeline:not-a-uuid".to_string()]),
587 Caller::Anonymous
588 );
589 assert_eq!(
590 caller_of(std::slice::from_ref(&sidecar)),
591 Caller::External(SIDECAR.to_string())
592 );
593 assert_eq!(
594 caller_of(&[format!("URN:Feldera:pipeline:{PIPELINE_A}")]),
595 Caller::Anonymous
596 );
597 assert_eq!(
598 caller_of(&["urn:feldera:sidecar".to_string()]),
599 Caller::Anonymous
600 );
601 assert_eq!(
602 caller_of(&[control_plane.clone(), a.clone()]),
603 Caller::Anonymous
604 );
605 assert_eq!(caller_of(&[control_plane, sidecar]), Caller::Anonymous);
606 assert_eq!(caller_of(&[a, b]), Caller::Anonymous);
607 }
608
609 #[test]
612 fn pipeline_client_auth() {
613 let (issuer, ca_cert) = ca();
614 let own_leaf = leaf(&issuer, &[pipeline_certificate_uri(PIPELINE_A)]);
615 let chain = [own_leaf.clone(), ca_cert.clone()];
616 let auth = PipelineClientAuth::from_chain(&chain, &[SIDECAR.to_string()]).unwrap();
617 assert!(auth.is_allowed(&Caller::ControlPlane));
618 assert!(auth.is_allowed(&Caller::Pipeline(PIPELINE_A)));
619 assert!(auth.is_allowed(&Caller::External(SIDECAR.to_string())));
620 assert!(!auth.is_allowed(&Caller::External("urn:example:other".to_string())));
621 assert!(!auth.is_allowed(&Caller::Pipeline(PIPELINE_B)));
622 assert!(!auth.is_allowed(&Caller::Anonymous));
623
624 let no_external = PipelineClientAuth::from_chain(&chain, &[]).unwrap();
625 assert!(!no_external.is_allowed(&Caller::External(SIDECAR.to_string())));
626
627 for invalid in [
628 pipeline_certificate_uri(PIPELINE_B),
629 format!("URN:FELDERA:pipeline:{PIPELINE_B}"),
630 String::new(),
631 "urn:example:a urn:example:b".to_string(),
632 ] {
633 assert!(
634 PipelineClientAuth::from_chain(&chain, std::slice::from_ref(&invalid)).is_err(),
635 "{invalid}"
636 );
637 }
638
639 assert!(PipelineClientAuth::from_chain(&[own_leaf], &[]).is_err());
640 let server_leaf = leaf(&issuer, &[]);
641 assert!(PipelineClientAuth::from_chain(&[server_leaf, ca_cert], &[]).is_err());
642 }
643
644 #[test]
647 fn verifier_trusts_only_private_ca() {
648 let (root, root_cert) = named_ca("root", None);
649 let (private_ca, private_ca_cert) = named_ca("private", Some(&root));
650 let (other_ca, other_ca_cert) = named_ca("other", Some(&root));
651 let own_leaf = leaf(&private_ca, &[pipeline_certificate_uri(PIPELINE_A)]);
652 let pipeline_chain = [own_leaf, private_ca_cert.clone(), root_cert.clone()];
653 let ca_chain = [private_ca_cert, root_cert];
654 let control_plane = [CONTROL_PLANE_CERTIFICATE_URI.to_string()];
655 let now = UnixTime::now();
656 for verifier in [
657 client_certificate_verifier(&ca_chain).unwrap(),
658 PipelineClientAuth::from_chain(&pipeline_chain, &[])
659 .unwrap()
660 .verifier,
661 ] {
662 let from_private_ca = leaf(&private_ca, &control_plane);
663 assert!(
664 verifier
665 .verify_client_cert(&from_private_ca, &[], now)
666 .is_ok()
667 );
668 let from_root = leaf(&root, &control_plane);
669 assert!(verifier.verify_client_cert(&from_root, &[], now).is_err());
670 let from_other_ca = leaf(&other_ca, &control_plane);
671 let other_chain = std::slice::from_ref(&other_ca_cert);
672 assert!(
673 verifier
674 .verify_client_cert(&from_other_ca, other_chain, now)
675 .is_err()
676 );
677 }
678 }
679
680 fn peer_chain(
683 issuer: &Issuer<'static, KeyPair>,
684 ca_chain: &[CertificateDer<'static>],
685 uri: &str,
686 ) -> (Vec<CertificateDer<'static>>, PrivateKeyDer<'static>) {
687 let mut params = CertificateParams::default();
688 params.subject_alt_names = vec![SanType::URI(uri.try_into().unwrap())];
689 params.extended_key_usages = vec![
690 ExtendedKeyUsagePurpose::ServerAuth,
691 ExtendedKeyUsagePurpose::ClientAuth,
692 ];
693 let key = KeyPair::generate().unwrap();
694 let leaf = params.signed_by(&key, issuer).unwrap().der().clone();
695 let chain = std::iter::once(leaf)
696 .chain(ca_chain.iter().cloned())
697 .collect();
698 (chain, PrivatePkcs8KeyDer::from(key.serialize_der()).into())
699 }
700
701 fn peer_tls(
702 issuer: &Issuer<'static, KeyPair>,
703 ca_chain: &[CertificateDer<'static>],
704 uri: &str,
705 ) -> PipelinePeerTls {
706 let (chain, key) = peer_chain(issuer, ca_chain, uri);
707 PipelinePeerTls::from_chain(chain, key).unwrap()
708 }
709
710 fn handshake(
712 client: Arc<ClientConfig>,
713 server: Arc<ServerConfig>,
714 ) -> Result<(), rustls::Error> {
715 let mut client = ClientConnection::new(client, ServerName::try_from("127.0.0.1").unwrap())?;
716 let mut server = ServerConnection::new(server)?;
717 for _ in 0..10 {
718 let mut buf = Vec::new();
719 while client.wants_write() {
720 client.write_tls(&mut buf).unwrap();
721 }
722 server.read_tls(&mut buf.as_slice()).unwrap();
723 server.process_new_packets()?;
724
725 let mut buf = Vec::new();
726 while server.wants_write() {
727 server.write_tls(&mut buf).unwrap();
728 }
729 client.read_tls(&mut buf.as_slice()).unwrap();
730 client.process_new_packets()?;
731
732 if !client.is_handshaking() && !server.is_handshaking() {
733 return Ok(());
734 }
735 }
736 panic!("handshake did not finish");
737 }
738
739 #[test]
743 fn peer_tls_admits_only_own_pipeline() {
744 let (root, root_cert) = named_ca("root", None);
745 let (private_ca, private_ca_cert) = named_ca("private", Some(&root));
746 let (other_ca, other_ca_cert) = named_ca("other", Some(&root));
747 let ca_chain = [private_ca_cert, root_cert.clone()];
748 let a = pipeline_certificate_uri(PIPELINE_A);
749 let b = pipeline_certificate_uri(PIPELINE_B);
750
751 let host0 = peer_tls(&private_ca, &ca_chain, &a);
752 let host1 = peer_tls(&private_ca, &ca_chain, &a);
753 handshake(host0.client.clone(), host1.server.clone()).unwrap();
754 handshake(host1.client.clone(), host0.server.clone()).unwrap();
755
756 let verifier = Arc::new(
759 PipelinePeerVerifier::from_chain(&peer_chain(&private_ca, &ca_chain, &a).0).unwrap(),
760 );
761 let client_builder = || {
762 ClientConfig::builder_with_provider(crypto_provider())
763 .with_protocol_versions(&[&rustls::version::TLS13])
764 .unwrap()
765 .dangerous()
766 .with_custom_certificate_verifier(verifier.clone())
767 };
768 let anonymous = client_builder().with_no_client_auth();
769 assert!(
770 handshake(Arc::new(anonymous), host0.server.clone()).is_err(),
771 "server admitted a client without a certificate"
772 );
773
774 let refused = [
775 ("another pipeline", peer_chain(&private_ca, &ca_chain, &b)),
776 (
777 "the control plane",
778 peer_chain(&private_ca, &ca_chain, CONTROL_PLANE_CERTIFICATE_URI),
779 ),
780 (
781 "the same pipeline from a sibling CA",
782 peer_chain(&other_ca, &[other_ca_cert, root_cert.clone()], &a),
783 ),
784 (
785 "the same pipeline from the root CA",
786 peer_chain(&root, std::slice::from_ref(&root_cert), &a),
787 ),
788 ];
789 for (name, (chain, key)) in refused {
790 let client = client_builder()
791 .with_client_auth_cert(chain.clone(), key.clone_key())
792 .unwrap();
793 assert!(
794 handshake(Arc::new(client), host0.server.clone()).is_err(),
795 "server admitted {name}"
796 );
797
798 let server = ServerConfig::builder_with_provider(crypto_provider())
800 .with_protocol_versions(&[&rustls::version::TLS13])
801 .unwrap()
802 .with_no_client_auth()
803 .with_single_cert(chain, key)
804 .unwrap();
805 assert!(
806 handshake(host0.client.clone(), Arc::new(server)).is_err(),
807 "client admitted {name}"
808 );
809 }
810 }
811
812 #[test]
815 fn peer_tls_needs_pipeline_chain() {
816 let (issuer, ca_cert) = ca();
817 let ca_chain = [ca_cert];
818 let a = pipeline_certificate_uri(PIPELINE_A);
819 let (chain, key) = peer_chain(&issuer, &[], &a);
820 assert!(PipelinePeerTls::from_chain(chain, key).is_err());
821 let (chain, key) = peer_chain(&issuer, &ca_chain, CONTROL_PLANE_CERTIFICATE_URI);
822 assert!(PipelinePeerTls::from_chain(chain, key).is_err());
823
824 let (chain, _) = peer_chain(&issuer, &ca_chain, &a);
825 let (_, other_key) = peer_chain(&issuer, &ca_chain, &a);
826 let error = PipelinePeerTls::from_chain(chain, other_key).unwrap_err();
827 assert!(
828 error.contains("does not match the pipeline certificate"),
829 "{error}"
830 );
831 }
832
833 #[test]
835 fn peer_tls_refuses_tls12() {
836 let (issuer, ca_cert) = ca();
837 let ca_chain = [ca_cert];
838 let a = pipeline_certificate_uri(PIPELINE_A);
839 let host = peer_tls(&issuer, &ca_chain, &a);
840 let verifier = Arc::new(
841 PipelinePeerVerifier::from_chain(&peer_chain(&issuer, &ca_chain, &a).0).unwrap(),
842 );
843
844 let (chain, key) = peer_chain(&issuer, &ca_chain, &a);
845 let client = ClientConfig::builder_with_provider(crypto_provider())
846 .with_protocol_versions(&[&rustls::version::TLS12])
847 .unwrap()
848 .dangerous()
849 .with_custom_certificate_verifier(verifier.clone())
850 .with_client_auth_cert(chain.clone(), key.clone_key())
851 .unwrap();
852 let server = ServerConfig::builder_with_provider(crypto_provider())
853 .with_protocol_versions(&[&rustls::version::TLS12])
854 .unwrap()
855 .with_client_cert_verifier(verifier)
856 .with_single_cert(chain, key)
857 .unwrap();
858
859 for (name, result) in [
861 ("server", handshake(Arc::new(client), host.server.clone())),
862 ("client", handshake(host.client.clone(), Arc::new(server))),
863 ] {
864 assert!(
865 matches!(result, Err(rustls::Error::PeerIncompatible(_))),
866 "{name} allowed TLS 1.2: {result:?}"
867 );
868 }
869 }
870}