Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/callbacks/cert_validation.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use s2n_tls_sys::*;
5
6 use crate::{
7 connection::Connection,
8 error::{Error, Fallible},
9 };
10 use std::{marker::PhantomData, ptr::NonNull};
11
12 pub struct CertValidationInfo<'a> {
13 info: NonNull<s2n_cert_validation_info>,
14 _lifetime: PhantomData<&'a s2n_cert_validation_info>,
15 }
16
17 impl CertValidationInfo<'_> {
18 pub(crate) fn from_ptr(info: *mut s2n_cert_validation_info) -> Self {
19 let info = NonNull::new(info).expect("info pointer should not be null");
20 CertValidationInfo {
21 info,
22 _lifetime: PhantomData,
23 }
24 }
25
26 pub(crate) fn as_ptr(&mut self) -> *mut s2n_cert_validation_info {
27 self.info.as_ptr()
28 }
29
30 /// Corresponds to [`s2n_cert_validation_accept`].
31 pub(crate) fn accept(&mut self) -> Result<(), Error> {
32 unsafe { s2n_cert_validation_accept(self.as_ptr()).into_result() }?;
33 Ok(())
34 }
35
36 /// Corresponds to [`s2n_cert_validation_reject`].
37 pub(crate) fn reject(&mut self) -> Result<(), Error> {
38 unsafe { s2n_cert_validation_reject(self.as_ptr()).into_result() }?;
39 Ok(())
40 }
41 }
42
43 pub trait CertValidationCallbackSync: 'static + Send + Sync {
44 /// Return a boolean to indicate if the certificate chain passed the validation
45 fn handle_validation(
46 &self,
47 connection: &mut Connection,
48 validation_info: &mut CertValidationInfo,
49 ) -> Result<bool, Error>;
50 }
51
52 #[cfg(test)]
53 mod tests {
54 use super::*;
55 use crate::{connection::Connection, security, testing::*};
56
57 struct ValidationContext {
58 accept: bool,
59 }
60
61 struct SyncCallback(Counter);
62 impl CertValidationCallbackSync for SyncCallback {
63 fn handle_validation(
64 &self,
65 conn: &mut Connection,
66 _info: &mut CertValidationInfo,
67 ) -> Result<bool, Error> {
68 self.0.increment();
69 let context = conn.application_context::<ValidationContext>().unwrap();
70 Ok(context.accept)
71 }
72 }
73
74 #[test]
75 fn sync_cert_validation() -> Result<(), Box<dyn std::error::Error>> {
76 for accept in [true, false] {
77 let counter = Counter::default();
78 let callback = SyncCallback(counter.clone());
79
80 let config = {
81 let mut config = config_builder(&security::DEFAULT_TLS13)?;
82 config.set_cert_validation_callback_sync(callback)?;
83 config.build()?
84 };
85
86 let mut pair = TestPair::from_config(&config);
87 let context = ValidationContext { accept };
88 pair.client.set_application_context(context);
89
90 assert_eq!(counter.count(), 0);
91
92 if accept {
93 pair.handshake()?;
94 } else {
95 let s2n_err = pair.handshake().unwrap_err();
96 assert_eq!(s2n_err.name(), "S2N_ERR_CERT_REJECTED");
97 }
98
99 assert_eq!(counter.count(), 1);
100 }
101
102 Ok(())
103 }
104 }