Debian Codegraph @

crt/s2n/bindings/rust/standard/s2n-tls-metrics-subscriber/tests/entry_snapshot.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Snapshot test that performs a real handshake and renders the resulting
5 //! MetricRecord as an EMF entry. Any change to what fields the Entry impl
6 //! emits will show up as a diff in the snapshot file.
7
8 use metrique_writer::format::Format;
9 use metrique_writer_format_emf::Emf;
10 use s2n_tls::{security::DEFAULT_TLS13, testing::CertKeyPair};
11 use s2n_tls_metrics_subscriber::{
12 AggregatedMetricsSubscriber, Attribution, MetricRecord, TelemetrySink,
13 };
14 use std::sync::{Arc, Mutex};
15
16 #[derive(Clone)]
17 struct CaptureSink(Arc<Mutex<Vec<MetricRecord>>>);
18 impl TelemetrySink for CaptureSink {
19 fn export_record(&self, record: &MetricRecord) {
20 self.0.lock().unwrap().push(record.clone());
21 }
22 }
23
24 /// Normalize non-deterministic values (timestamps, timings) so the snapshot
25 /// is stable across runs.
26 fn normalize(value: &mut serde_json::Value) {
27 if let Some(obj) = value.as_object_mut() {
28 // Zero out timing fields
29 for key in ["handshake_duration_us", "handshake_compute_us"] {
30 if obj.contains_key(key) {
31 obj.insert(key.to_owned(), serde_json::json!("<DURATION>"));
32 }
33 }
34 // Zero out the EMF timestamp
35 if let Some(aws) = obj.get_mut("_aws").and_then(|v| v.as_object_mut()) {
36 if aws.contains_key("Timestamp") {
37 aws.insert("Timestamp".to_owned(), serde_json::json!("<TIMESTAMP>"));
38 }
39 }
40 // Recurse
41 for (_, v) in obj.iter_mut() {
42 normalize(v);
43 }
44 } else if let Some(arr) = value.as_array_mut() {
45 for v in arr {
46 normalize(v);
47 }
48 }
49 }
50
51 /// Render a real handshake record to EMF and compare against the expected
52 /// snapshot.
53 ///
54 /// If you changed the Entry implementation, update
55 /// `tests/snapshots/entry_emf.json` to match the new output.
56 #[test]
57 fn entry_emf_snapshot() {
58 let sink = CaptureSink(Arc::new(Mutex::new(Vec::new())));
59 let subscriber = AggregatedMetricsSubscriber::new(
60 sink.clone(),
61 Attribution {
62 service: "my-service".to_owned(),
63 resource: "arn:aws:elasticloadbalancing:us-east-1:123:listener/abc".to_owned(),
64 component: "test-frontend-whatever".to_owned(),
65 },
66 );
67
68 let server_config = {
69 let keypair = CertKeyPair::from_path(
70 "permutations/rsae_pkcs_4096_sha384/",
71 "server-chain",
72 "server-key",
73 "ca-cert",
74 );
75 let mut c = s2n_tls::config::Builder::new();
76 c.set_security_policy(&DEFAULT_TLS13).unwrap();
77 c.load_pem(keypair.cert(), keypair.key()).unwrap();
78 c.trust_pem(keypair.cert()).unwrap();
79 c.set_verify_host_callback(s2n_tls::testing::InsecureAcceptAllCertificatesHandler {})
80 .unwrap();
81 c.set_event_subscriber(subscriber.clone()).unwrap();
82 c.build().unwrap()
83 };
84 let client_config = {
85 let keypair = CertKeyPair::from_path(
86 "permutations/rsae_pkcs_4096_sha384/",
87 "server-chain",
88 "server-key",
89 "ca-cert",
90 );
91 let mut c = s2n_tls::config::Builder::new();
92 c.set_security_policy(&DEFAULT_TLS13).unwrap();
93 c.load_pem(keypair.cert(), keypair.key()).unwrap();
94 c.trust_pem(keypair.cert()).unwrap();
95 c.with_system_certs(false).unwrap();
96 c.set_verify_host_callback(s2n_tls::testing::InsecureAcceptAllCertificatesHandler {})
97 .unwrap();
98 c.build().unwrap()
99 };
100 let mut pair = s2n_tls::testing::TestPair::from_configs(&client_config, &server_config);
101 pair.handshake().unwrap();
102
103 // Failed handshake: client does not trust the server cert, shuts down
104 // (sending close_notify), and the server receives the alert.
105 {
106 use std::task::Poll;
107
108 let untrusted_client_config = {
109 let mut builder = s2n_tls::config::Builder::new();
110 builder.set_security_policy(&DEFAULT_TLS13).unwrap();
111 builder.set_max_blinding_delay(0).unwrap();
112 builder.with_system_certs(false).unwrap();
113 builder.build().unwrap()
114 };
115 let mut failed_pair =
116 s2n_tls::testing::TestPair::from_configs(&untrusted_client_config, &server_config);
117 // Drive handshake until client fails cert validation
118 assert!(failed_pair.client.poll_negotiate().is_pending());
119 assert!(failed_pair.server.poll_negotiate().is_pending());
120 let client_err = match failed_pair.client.poll_negotiate() {
121 Poll::Ready(Err(e)) => e,
122 other => panic!("expected client error, got {:?}", other),
123 };
124 assert_eq!(client_err.name(), "S2N_ERR_CERT_UNTRUSTED");
125
126 // Client sends close_notify
127 assert!(failed_pair.client.poll_shutdown_send().is_ready());
128
129 // Server reads the alert and fails
130 let server_err = match failed_pair.server.poll_negotiate() {
131 Poll::Ready(Err(e)) => e,
132 other => panic!("expected server error, got {:?}", other),
133 };
134 assert_eq!(server_err.name(), "S2N_ERR_CLOSED");
135 assert_eq!(failed_pair.server.alert().unwrap(), 0); // close_notify
136 }
137
138 subscriber.finish_record();
139
140 let records = sink.0.lock().unwrap();
141 let record = &records[0];
142
143 let mut emf = Emf::no_validations("TlsMetrics".into(), vec![vec![]]);
144 let mut buf = Vec::new();
145 emf.format(record, &mut buf).unwrap();
146 let emf_output = String::from_utf8(buf).unwrap();
147
148 let mut actual: serde_json::Value = serde_json::from_str(&emf_output).unwrap();
149 normalize(&mut actual);
150 let actual_pretty = serde_json::to_string_pretty(&actual).unwrap();
151
152 // Uncomment to update the snapshot:
153 // std::fs::write(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/snapshots/entry_emf.json"), &actual_pretty).unwrap();
154
155 let expected = include_str!("snapshots/entry_emf.json").trim_end();
156 assert_eq!(actual_pretty, expected);
157 }