Debian Codegraph @

crt/s2n/bindings/rust/standard/s2n-tls-metrics-schema/tests/public_api.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Integration tests for the public API surface of s2n-tls-metrics-schema.
5 //!
6 //! These tests exercise deserialization of `MetricRecord`, field access,
7 //! counter slot layout, and round-trip serialization.
8
9 use std::{borrow::Cow, collections::HashSet, time::SystemTime};
10
11 use s2n_tls_metrics_schema::{
12 metric_names::{self as names, cert, negotiated, supported},
13 static_lists::{
14 CERT_KEY_COUNT, CERT_SIG_COUNT, CIPHER_COUNT, Cipher, DEFINED_ALERTS_COUNT, FiniteCounter,
15 GROUP_COUNT, Group, PROTOCOL_COUNT, SIGNATURE_COUNT, Signature, Version,
16 },
17 };
18
19 fn sample_schema_record() -> s2n_tls_metrics_schema::record::MetricRecord {
20 let json = serde_json::json!({
21 "attribution": {
22 "service": "my-service",
23 "resource": "arn:aws:elasticloadbalancing:us-east-1:123:listener/abc"
24 },
25 "handshake": {
26 "freeze_time": {"secs_since_epoch": 1_700_000_000u64, "nanos_since_epoch": 0u32},
27 "handshake_success_count": 1000,
28 "negotiated_protocols": [[0x0303u16, 400], [0x0304u16, 600]],
29 "negotiated_ciphers": [[[0x13, 0x01], 600], [[0x13, 0x02], 400]],
30 "negotiated_groups": [[23u16, 500], [29u16, 500]],
31 "negotiated_signatures": [[2052u16, 1000]],
32 "sslv2_client_hello": 2,
33 "supported_protocols": [[0x0303u16, 1000], [0x0304u16, 1000]],
34 "supported_ciphers": [[[0x13, 0x01], 1000], [[0x13, 0x02], 1000]],
35 "supported_groups": [[23u16, 1000], [29u16, 1000]],
36 "supported_signatures": [[2052u16, 1000]],
37 "compatibility_general20251201": 950,
38 "compatibility_fips20251201": 800,
39 "compatibility_cnsa1": 100,
40 "compatibility_cnsa2": 0,
41 "handshake_duration_us": 50000,
42 "handshake_compute_us": 25000
43 }
44 });
45 serde_json::from_value(json).unwrap()
46 }
47
48 /// Verify CBOR stream round-trip: serialize via schema, deserialize back.
49 #[test]
50 fn cbor_stream_round_trip() {
51 let original = sample_schema_record();
52
53 let mut stream = Vec::new();
54 for _ in 0..3 {
55 ciborium::into_writer(&original, &mut stream).unwrap();
56 }
57
58 let mut cursor = std::io::Cursor::new(&stream);
59 let mut records: Vec<s2n_tls_metrics_schema::record::MetricRecord> = Vec::new();
60 loop {
61 match ciborium::from_reader(&mut cursor) {
62 Ok(record) => records.push(record),
63 Err(ciborium::de::Error::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
64 break;
65 }
66 Err(e) => panic!("deserialization error: {e}"),
67 }
68 }
69
70 assert_eq!(records.len(), 3);
71 for r in &records {
72 assert_eq!(r.attribution.service, "my-service");
73 assert_eq!(r.handshake.handshake_success_count, 1000);
74 }
75 }
76
77 /// Schema field access after deserialization.
78 #[test]
79 fn schema_field_access() {
80 let record = sample_schema_record();
81
82 assert_eq!(record.attribution.service, "my-service");
83 assert_eq!(
84 record.attribution.resource,
85 "arn:aws:elasticloadbalancing:us-east-1:123:listener/abc"
86 );
87
88 assert_eq!(record.handshake.handshake_success_count, 1000);
89 assert_eq!(record.handshake.sslv2_client_hello, 2);
90 assert_eq!(record.handshake.compatibility_general20251201, 950);
91 assert_eq!(record.handshake.compatibility_fips20251201, 800);
92 assert_eq!(record.handshake.compatibility_cnsa1, 100);
93 assert_eq!(record.handshake.compatibility_cnsa2, 0);
94 assert_eq!(record.handshake.handshake_duration_us, 50000);
95 assert_eq!(record.handshake.handshake_compute_us, 25000);
96
97 let dur = record
98 .handshake
99 .freeze_time
100 .duration_since(SystemTime::UNIX_EPOCH)
101 .unwrap();
102 assert_eq!(dur.as_secs(), 1_700_000_000);
103 }
104
105 #[test]
106 fn frozen_counter_slots_dense_array() {
107 let record = sample_schema_record();
108
109 let protocol_slots = record.handshake.negotiated_protocols.slots();
110 assert_eq!(protocol_slots.len(), PROTOCOL_COUNT);
111 assert_eq!(protocol_slots.iter().sum::<u64>(), 1000);
112
113 let cipher_slots = record.handshake.negotiated_ciphers.slots();
114 assert_eq!(cipher_slots.len(), CIPHER_COUNT);
115 assert_eq!(cipher_slots.iter().sum::<u64>(), 1000);
116
117 let group_slots = record.handshake.negotiated_groups.slots();
118 assert_eq!(group_slots.len(), GROUP_COUNT);
119 assert_eq!(group_slots.iter().sum::<u64>(), 1000);
120
121 let sig_slots = record.handshake.negotiated_signatures.slots();
122 assert_eq!(sig_slots.len(), SIGNATURE_COUNT);
123 assert_eq!(sig_slots.iter().sum::<u64>(), 1000);
124 }
125
126 #[test]
127 fn key_from_slot_produces_display_names() {
128 for slot in 0..PROTOCOL_COUNT {
129 let name = Version::key_from_slot(slot).unwrap().to_string();
130 assert!(!name.is_empty());
131 assert!(!name.starts_with("unknown"));
132 }
133
134 for slot in 0..CIPHER_COUNT {
135 let name = Cipher::key_from_slot(slot).unwrap().to_string();
136 assert!(!name.is_empty());
137 assert!(!name.starts_with("unknown"));
138 }
139
140 for slot in 0..GROUP_COUNT {
141 let name = Group::key_from_slot(slot).unwrap().to_string();
142 assert!(!name.is_empty());
143 assert!(!name.starts_with("unknown"));
144 }
145
146 for slot in 0..SIGNATURE_COUNT {
147 let name = Signature::key_from_slot(slot).unwrap().to_string();
148 assert!(!name.is_empty());
149 assert!(!name.starts_with("unknown"));
150 }
151 }
152
153 #[test]
154 fn iter_non_zero_yields_expected_triples() {
155 let record = sample_schema_record();
156
157 let non_zero: Vec<(usize, Version, u64)> = record
158 .handshake
159 .negotiated_protocols
160 .iter_non_zero()
161 .collect();
162 assert_eq!(non_zero.len(), 2);
163
164 let total: u64 = non_zero.iter().map(|(_, _, c)| c).sum();
165 assert_eq!(total, 1000);
166
167 for (slot, element, count) in &non_zero {
168 assert!(count > &0);
169 let name = element.to_string();
170 assert!(
171 name == "TLSv1_2" || name == "TLSv1_3",
172 "unexpected protocol: {name}"
173 );
174 assert_eq!(Version::key_from_slot(*slot).unwrap(), *element);
175 }
176 }
177
178 #[test]
179 fn slots_and_iter_non_zero_are_consistent() {
180 let record = sample_schema_record();
181
182 let slots = record.handshake.negotiated_ciphers.slots();
183 let from_iter: Vec<(usize, u64)> = record
184 .handshake
185 .negotiated_ciphers
186 .iter_non_zero()
187 .map(|(slot, _, count)| (slot, count))
188 .collect();
189
190 for &(slot, count) in &from_iter {
191 assert_eq!(slots[slot], count);
192 }
193
194 let non_zero_from_slots: Vec<(usize, u64)> = slots
195 .iter()
196 .enumerate()
197 .filter(|&(_, c)| *c > 0)
198 .map(|(i, &c)| (i, c))
199 .collect();
200 assert_eq!(from_iter, non_zero_from_slots);
201 }
202
203 #[test]
204 fn cbor_round_trip_preserves_all_fields() {
205 let original = sample_schema_record();
206 let mut cbor_bytes = Vec::new();
207 ciborium::into_writer(&original, &mut cbor_bytes).unwrap();
208 let recovered: s2n_tls_metrics_schema::record::MetricRecord =
209 ciborium::from_reader(cbor_bytes.as_slice()).unwrap();
210
211 assert_eq!(original, recovered);
212 }
213
214 #[test]
215 fn empty_record_has_zero_slots() {
216 let json = serde_json::json!({
217 "attribution": { "service": "s", "resource": "r" },
218 "handshake": {
219 "freeze_time": {"secs_since_epoch": 0u64, "nanos_since_epoch": 0u32},
220 "handshake_success_count": 0u64
221 }
222 });
223 let record: s2n_tls_metrics_schema::record::MetricRecord =
224 serde_json::from_value(json).unwrap();
225
226 assert!(
227 record
228 .handshake
229 .negotiated_protocols
230 .slots()
231 .iter()
232 .all(|&c| c == 0)
233 );
234 assert!(
235 record
236 .handshake
237 .negotiated_ciphers
238 .slots()
239 .iter()
240 .all(|&c| c == 0)
241 );
242 assert!(
243 record
244 .handshake
245 .negotiated_groups
246 .slots()
247 .iter()
248 .all(|&c| c == 0)
249 );
250 assert!(
251 record
252 .handshake
253 .negotiated_signatures
254 .slots()
255 .iter()
256 .all(|&c| c == 0)
257 );
258 assert!(
259 record
260 .handshake
261 .supported_protocols
262 .slots()
263 .iter()
264 .all(|&c| c == 0)
265 );
266 assert!(
267 record
268 .handshake
269 .supported_ciphers
270 .slots()
271 .iter()
272 .all(|&c| c == 0)
273 );
274 assert!(
275 record
276 .handshake
277 .supported_groups
278 .slots()
279 .iter()
280 .all(|&c| c == 0)
281 );
282 assert!(
283 record
284 .handshake
285 .supported_signatures
286 .slots()
287 .iter()
288 .all(|&c| c == 0)
289 );
290
291 assert_eq!(
292 record
293 .handshake
294 .negotiated_protocols
295 .iter_non_zero()
296 .count(),
297 0
298 );
299 }
300
301 /// Mock writer that captures all metric names written by the Entry impl.
302 struct NameCollector {
303 names: Vec<String>,
304 }
305
306 impl<'a> metrique_writer::EntryWriter<'a> for NameCollector {
307 fn timestamp(&mut self, _: SystemTime) {}
308
309 fn value(
310 &mut self,
311 name: impl Into<Cow<'a, str>>,
312 _value: &(impl metrique_writer::Value + ?Sized),
313 ) {
314 self.names.push(name.into().into_owned());
315 }
316
317 fn config(&mut self, _: &'a dyn metrique_writer::EntryConfig) {}
318 }
319
320 /// Verifies that the metric names emitted by `FrozenHandshakeRecord::write()`
321 /// exactly match the catalog defined in `metric_names`.
322 #[test]
323 fn entry_writes_match_metric_names_catalog() {
324 use metrique_writer::Entry;
325 use s2n_tls_metrics_schema::{
326 bounded_set::FrozenBoundedStringSet, counter::FrozenCounter, record::FrozenHandshakeRecord,
327 };
328
329 // Build a record with every counter slot populated so all names are emitted.
330 let record = FrozenHandshakeRecord {
331 handshake_success_count: 1,
332 handshake_failure_count: 1,
333 negotiated_protocols: FrozenCounter::from_slots([1; PROTOCOL_COUNT]),
334 negotiated_ciphers: FrozenCounter::from_slots([1; CIPHER_COUNT]),
335 negotiated_groups: FrozenCounter::from_slots([1; GROUP_COUNT]),
336 negotiated_signatures: FrozenCounter::from_slots([1; SIGNATURE_COUNT]),
337 supported_protocols: FrozenCounter::from_slots([1; PROTOCOL_COUNT]),
338 supported_ciphers: FrozenCounter::from_slots([1; CIPHER_COUNT]),
339 supported_groups: FrozenCounter::from_slots([1; GROUP_COUNT]),
340 supported_signatures: FrozenCounter::from_slots([1; SIGNATURE_COUNT]),
341 alerts: FrozenCounter::from_slots([1; DEFINED_ALERTS_COUNT]),
342 server_leaf_cert_key: FrozenCounter::from_slots([1; CERT_KEY_COUNT]),
343 server_leaf_cert_sig: FrozenCounter::from_slots([1; CERT_SIG_COUNT]),
344 server_chain_cert_key: FrozenCounter::from_slots([1; CERT_KEY_COUNT]),
345 server_chain_cert_sig: FrozenCounter::from_slots([1; CERT_SIG_COUNT]),
346 client_leaf_cert_key: FrozenCounter::from_slots([1; CERT_KEY_COUNT]),
347 client_leaf_cert_sig: FrozenCounter::from_slots([1; CERT_SIG_COUNT]),
348 client_chain_cert_key: FrozenCounter::from_slots([1; CERT_KEY_COUNT]),
349 client_chain_cert_sig: FrozenCounter::from_slots([1; CERT_SIG_COUNT]),
350 server_cert_parsing_failure: 1,
351 client_cert_parsing_failure: 1,
352 security_policies: FrozenBoundedStringSet::Entries(
353 ["TestPolicy"].into_iter().map(String::from).collect(),
354 ),
355 compatibility_general20251201: 1,
356 compatibility_fips20251201: 1,
357 compatibility_cnsa1: 1,
358 compatibility_cnsa2: 1,
359 sslv2_client_hello: 1,
360 handshake_duration_us: 1,
361 handshake_compute_us: 1,
362 synthetic_traffic_count: 1,
363 ..Default::default()
364 };
365
366 let mut collector = NameCollector { names: Vec::new() };
367 record.write(&mut collector);
368
369 let emitted: HashSet<String> = collector.names.into_iter().collect();
370
371 // Build expected set from the metric_names catalog.
372 let mut expected: HashSet<String> = HashSet::new();
373 for group in negotiated::ALL.iter().chain(supported::ALL.iter()) {
374 for slot in 0..group.count {
375 expected.insert(group.metric_name(slot).to_string());
376 }
377 }
378 for slot in 0..names::ALERTS.count {
379 expected.insert(names::ALERTS.metric_name(slot).to_string());
380 }
381 let cert_groups: &[&names::CounterGroup] = &[
382 &cert::SERVER_LEAF_KEY,
383 &cert::SERVER_LEAF_SIG,
384 &cert::SERVER_CHAIN_KEY,
385 &cert::SERVER_CHAIN_SIG,
386 &cert::CLIENT_LEAF_KEY,
387 &cert::CLIENT_LEAF_SIG,
388 &cert::CLIENT_CHAIN_KEY,
389 &cert::CLIENT_CHAIN_SIG,
390 ];
391 for group in cert_groups {
392 for slot in 0..group.count {
393 expected.insert(group.metric_name(slot).to_string());
394 }
395 }
396 for &name in names::ALL_SCALARS {
397 expected.insert(name.to_string());
398 }
399 expected.insert(names::security_policy_name("TestPolicy"));
400
401 // Guard against a new counter group being added to `write()` without
402 // updating this test and the catalog. If both sides silently omit the new
403 // group the diff checks below pass vacuously — this count check does not.
404 let expected_count = PROTOCOL_COUNT * 2
405 + CIPHER_COUNT * 2
406 + GROUP_COUNT * 2
407 + SIGNATURE_COUNT * 2
408 + DEFINED_ALERTS_COUNT
409 + CERT_KEY_COUNT * 4
410 + CERT_SIG_COUNT * 4
411 + names::ALL_SCALARS.len()
412 + 1; // security_policies: 1 test policy entry
413 assert_eq!(
414 expected.len(),
415 expected_count,
416 "expected set size drifted — did you add a counter group to the catalog without updating this assertion?"
417 );
418
419 let missing: Vec<_> = expected.difference(&emitted).collect();
420 let extra: Vec<_> = emitted.difference(&expected).collect();
421
422 assert!(
423 missing.is_empty() && extra.is_empty(),
424 "metric_names catalog vs Entry impl mismatch.\n Missing from Entry: {missing:?}\n Extra in Entry: {extra:?}"
425 );
426 }