Debian Codegraph @

crt/s2n/tests/regression/src/lib.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 pub mod git {
5 use std::process::Command;
6
7 pub fn get_current_commit_hash() -> String {
8 let output = Command::new("git")
9 .args(["rev-parse", "HEAD"])
10 .output()
11 .expect("Failed to get commit hash");
12 assert!(output.status.success());
13
14 String::from_utf8(output.stdout)
15 .expect("Invalid UTF-8 in commit hash")
16 .trim()
17 .to_string()
18 }
19
20 /// Returns true if `commit1` is older than `commit2`
21 pub fn is_older_commit(commit1: &str, commit2: &str) -> bool {
22 let status = Command::new("git")
23 .args(["merge-base", "--is-ancestor", commit1, commit2])
24 .status()
25 .expect("Failed to execute git merge-base");
26 status.success()
27 }
28
29 pub fn extract_commit_hash(file: &str) -> String {
30 // input: "target/regression_artifacts/$commit_id/test_name.raw"
31 // output: "$commit_id"
32 file.split("target/regression_artifacts/")
33 .nth(1)
34 .and_then(|s| s.split('/').next())
35 .map(|s| s.to_string())
36 .unwrap_or_default() // This will return an empty string if the Option is None
37 }
38
39 pub fn is_mainline(commit_hash: &str) -> bool {
40 // Execute the git command to check which branches contain the given commit.
41 let output = Command::new("git")
42 .args(["branch", "--contains", commit_hash])
43 .output()
44 .expect("Failed to execute git branch");
45
46 // If the command fails, it indicates that the commit is either detached
47 // or does not exist in any branches. Meaning, it is not part of mainline.
48 if !output.status.success() {
49 return false;
50 }
51
52 // Convert the command output to a string and check each line.
53 let branches = String::from_utf8_lossy(&output.stdout);
54 branches.lines().any(|branch| {
55 // Trim the branch name to remove any leading or trailing whitespace.
56 // The branch name could be prefixed with '*', indicating the current branch.
57 // We check for both "main" and "* main" to account for this possibility.
58 branch.trim() == "main" || branch.trim() == "* main"
59 })
60 }
61 }
62
63 #[cfg(test)]
64 mod tests {
65 use futures_test::task::noop_waker;
66 use s2n_tls::{
67 config::Builder,
68 security,
69 testing::{CertKeyPair, InsecureAcceptAllCertificatesHandler},
70 };
71 type Error = s2n_tls::error::Error;
72 use super::*;
73 use crabgrind as cg;
74 use s2n_tls::testing::TestPair;
75 use std::{
76 env,
77 fs::{create_dir_all, write},
78 io::{self, BufRead},
79 process::{Command, Output},
80 time::{Duration, SystemTime},
81 };
82
83 struct InstrumentationControl;
84
85 impl InstrumentationControl {
86 fn stop_instrumentation(&self) {
87 cg::cachegrind::stop_instrumentation();
88 }
89
90 fn start_instrumentation(&self) {
91 cg::cachegrind::start_instrumentation();
92 }
93 }
94
95 #[derive(Debug)]
96 enum RegressionTestMode {
97 Default,
98 Valgrind,
99 Diff,
100 }
101
102 impl RegressionTestMode {
103 fn from_env() -> Self {
104 match env::var("PERF_MODE").as_deref() {
105 Ok("valgrind") => RegressionTestMode::Valgrind,
106 Ok("diff") => RegressionTestMode::Diff,
107 _ => RegressionTestMode::Default,
108 }
109 }
110 }
111
112 fn valgrind_test<F>(
113 test_name: &str,
114 max_diff: f64,
115 test_body: F,
116 ) -> Result<(), s2n_tls::error::Error>
117 where
118 F: FnOnce(&InstrumentationControl) -> Result<(), s2n_tls::error::Error>,
119 {
120 match RegressionTestMode::from_env() {
121 RegressionTestMode::Valgrind => {
122 let raw_profile = RawProfile::new(test_name);
123 AnnotatedProfile::new(&raw_profile);
124 }
125 RegressionTestMode::Diff => {
126 let (prev_profile, curr_profile) = RawProfile::query(test_name);
127 DiffProfile::new(&prev_profile, &curr_profile).assert_performance(max_diff);
128 }
129 RegressionTestMode::Default => {
130 let ctrl = InstrumentationControl;
131 test_body(&ctrl)?
132 }
133 };
134 Ok(())
135 }
136
137 struct RawProfile {
138 test_name: String,
139 commit_hash: String,
140 }
141
142 impl RawProfile {
143 fn new(test_name: &str) -> Self {
144 let commit_hash = git::get_current_commit_hash();
145 create_dir_all(format!("target/regression_artifacts/{commit_hash}")).unwrap();
146
147 let raw_profile = Self {
148 test_name: test_name.to_owned(),
149 commit_hash,
150 };
151
152 let mut command = Command::new("valgrind");
153 command
154 .args([
155 // use cachegrind to get instruction count
156 "--tool=cachegrind",
157 // write output to output file
158 &format!("--cachegrind-out-file={}", raw_profile.path()),
159 // the "cargo test" executable
160 &std::env::args().next().unwrap(),
161 test_name,
162 ])
163 // remove environment variable to prevent recursive loop
164 .env_remove("PERF_MODE");
165 assert_command_success(command.output().unwrap());
166
167 raw_profile
168 }
169
170 fn path(&self) -> String {
171 format!(
172 "target/regression_artifacts/{}/{}.raw",
173 self.commit_hash, self.test_name
174 )
175 }
176
177 // Returns the annotated profile associated with a raw profile
178 fn associated_annotated_profile(&self) -> AnnotatedProfile {
179 AnnotatedProfile::new(self)
180 }
181
182 /// Return the raw profiles for `test_name` in "git" order. `tuple.0` is older than `tuple.1`
183 ///
184 /// This method will panic if there are not two profiles.
185 /// This method will also panic if both commits are on different logs (not mainline).
186 fn query(test_name: &str) -> (RawProfile, RawProfile) {
187 let pattern = format!("target/regression_artifacts/**/*{}.raw", test_name);
188 let raw_files: Vec<String> = glob::glob(&pattern)
189 .expect("Failed to read glob pattern")
190 .filter_map(Result::ok)
191 .map(|path| path.to_string_lossy().into_owned())
192 .collect();
193 assert_eq!(raw_files.len(), 2);
194
195 let profile1 = RawProfile {
196 test_name: test_name.to_string(),
197 commit_hash: git::extract_commit_hash(&raw_files[0]),
198 };
199 let profile2 = RawProfile {
200 test_name: test_name.to_string(),
201 commit_hash: git::extract_commit_hash(&raw_files[1]),
202 };
203
204 // xor returns true if exactly one commit is mainline
205 if git::is_mainline(&profile1.commit_hash) ^ git::is_mainline(&profile2.commit_hash) {
206 // Return the mainline as first commit
207 if git::is_mainline(&profile1.commit_hash) {
208 (profile1, profile2)
209 } else {
210 (profile2, profile1)
211 }
212 } else {
213 // Neither or both profiles are on the mainline, so return the older one first
214 if git::is_older_commit(&profile1.commit_hash, &profile2.commit_hash) {
215 (profile1, profile2)
216 } else if git::is_older_commit(&profile2.commit_hash, &profile1.commit_hash) {
217 (profile2, profile1)
218 } else {
219 panic!("The commits are not in the same log, are identical, or there are not two commits available");
220 }
221 }
222 }
223 }
224
225 struct AnnotatedProfile {
226 test_name: String,
227 commit_hash: String,
228 }
229
230 impl AnnotatedProfile {
231 fn new(raw_profile: &RawProfile) -> Self {
232 let annotated = Self {
233 test_name: raw_profile.test_name.clone(),
234 commit_hash: raw_profile.commit_hash.clone(),
235 };
236
237 // annotate raw profile
238 let annotate_output = Command::new("cg_annotate")
239 .arg(raw_profile.path())
240 .output()
241 .expect("Failed to run cg_annotate");
242 assert_command_success(annotate_output.clone());
243
244 // write annotated profile to disk
245 let annotate_content = String::from_utf8(annotate_output.stdout)
246 .expect("Invalid UTF-8 in cg_annotate output");
247 write(annotated.path(), annotate_content).expect("Failed to write to file");
248
249 annotated
250 }
251
252 fn path(&self) -> String {
253 format!(
254 "target/regression_artifacts/{}/{}.annotated",
255 self.commit_hash, self.test_name
256 )
257 }
258
259 fn instruction_count(&self) -> i64 {
260 let output = &std::fs::read_to_string(self.path()).unwrap();
261 find_instruction_count(output).unwrap()
262 }
263 }
264
265 struct DiffProfile {
266 test_name: String,
267 prev_profile_count: i64,
268 }
269 impl DiffProfile {
270 fn new(prev_profile: &RawProfile, curr_profile: &RawProfile) -> Self {
271 let diff_profile = Self {
272 test_name: curr_profile.test_name.clone(),
273 // reads the annotated profile for previous instruction count
274 prev_profile_count: prev_profile
275 .associated_annotated_profile()
276 .instruction_count(),
277 };
278
279 // diff the raw profile
280 let diff_output = Command::new("cg_annotate")
281 .args(["--diff", &prev_profile.path(), &curr_profile.path()])
282 .output()
283 .expect("Failed to run cg_annotate --diff");
284 assert_command_success(diff_output.clone());
285
286 // write the diff to disk
287 create_dir_all("target/regression_artifacts/diff").unwrap();
288 let diff_content = String::from_utf8(diff_output.stdout)
289 .expect("Invalid UTF-8 in cg_annotate --diff output");
290 write(diff_profile.path(), diff_content).expect("Failed to write to file");
291
292 diff_profile
293 }
294
295 fn path(&self) -> String {
296 format!("target/regression_artifacts/diff/{}.diff", self.test_name)
297 }
298
299 fn assert_performance(&self, max_diff: f64) {
300 let diff_content = std::fs::read_to_string(self.path()).unwrap();
301 let diff = find_instruction_count(&diff_content)
302 .expect("Failed to parse cg_annotate --diff output");
303 // percentage difference is the overall difference divided by the previous instruction count
304 let diff_percentage = diff as f64 / self.prev_profile_count as f64;
305 assert!(
306 diff_percentage <= max_diff,
307 "Instruction count difference exceeds the threshold, regression of {diff_percentage}% ({diff} instructions).
308 Check the annotated output logs in target/diff/{}.diff for debug information", self.test_name
309 );
310 }
311 }
312
313 /// Pulls the instruction count as an integer from the annotated output file.
314 /// Accepts output from Annotated and Diff profile formats.
315 fn find_instruction_count(output: &str) -> Result<i64, io::Error> {
316 let reader = io::BufReader::new(output.as_bytes());
317 // Example of the line being parsed:
318 // "79,278,369 (100.0%) PROGRAM TOTALS"
319 for line in reader.lines() {
320 let line = line?;
321 if line.contains("PROGRAM TOTALS") {
322 if let Some(instructions) = line.split_whitespace().next() {
323 return instructions
324 .replace(',', "")
325 .parse::<i64>()
326 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e));
327 }
328 }
329 }
330 panic!("Failed to find instruction count in annotated file");
331 }
332
333 // Asserts that a command executed successfully, panic with stdout/stderr if it fails
334 fn assert_command_success(output: Output) {
335 if !output.status.success() {
336 let stdout = std::str::from_utf8(&output.stdout).unwrap_or("Failed to read stdout");
337 let stderr = std::str::from_utf8(&output.stderr).unwrap_or("Failed to read stderr");
338 panic!(
339 "Command failed with status: {}\nstdout: {}\nstderr: {}",
340 output.status, stdout, stderr
341 );
342 }
343 }
344
345 /// Function to create default config with specified parameters.
346 pub fn set_config(
347 cipher_prefs: &security::Policy,
348 keypair: CertKeyPair,
349 ) -> Result<s2n_tls::config::Config, Error> {
350 let mut builder = Builder::new();
351 builder
352 .set_security_policy(cipher_prefs)
353 .expect("Unable to set config cipher preferences");
354 builder
355 .set_verify_host_callback(InsecureAcceptAllCertificatesHandler {})
356 .expect("Unable to set a host verify callback.");
357 builder
358 .load_pem(keypair.cert(), keypair.key())
359 .expect("Unable to load cert/pem");
360 builder.trust_pem(keypair.cert()).expect("load cert pem");
361 builder.build()
362 }
363
364 /// Test to create new config, set security policy, host_callback information, load/trust certs, and build config.
365 #[test]
366 fn test_set_config() {
367 valgrind_test("test_set_config", 0.01, |ctrl| {
368 ctrl.stop_instrumentation();
369 ctrl.start_instrumentation();
370 let keypair_rsa = CertKeyPair::default();
371 let _config =
372 set_config(&security::DEFAULT_TLS13, keypair_rsa).expect("Failed to build config");
373 Ok(())
374 })
375 .unwrap();
376 }
377
378 /// Test which creates a TestPair from config using `rsa_4096_sha512`. Only measures a pair handshake.
379 #[test]
380 fn test_rsa_handshake() {
381 valgrind_test("test_rsa_handshake", 0.01, |ctrl| {
382 ctrl.stop_instrumentation();
383 let keypair_rsa = CertKeyPair::default();
384 let config = set_config(&security::DEFAULT_TLS13, keypair_rsa)?;
385 let mut pair = TestPair::from_config(&config);
386 ctrl.start_instrumentation();
387 assert!(pair.handshake().is_ok());
388 ctrl.stop_instrumentation();
389 Ok(())
390 })
391 .unwrap();
392 }
393
394 /// Test to measure session resumption by performing a handshake and resuming the handshake with a session ticket
395 #[test]
396 fn test_session_resumption() {
397 const KEY_NAME: &str = "InsecureTestKey";
398 const KEY_VALUE: [u8; 16] = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3];
399 valgrind_test("test_session_resumption", 0.01, |ctrl| {
400 ctrl.stop_instrumentation();
401 let keypair_rsa = CertKeyPair::default();
402
403 let mut server_config_builder = Builder::new();
404 server_config_builder
405 .add_session_ticket_key(
406 KEY_NAME.as_bytes(),
407 KEY_VALUE.as_slice(),
408 SystemTime::now() - Duration::from_secs(10),
409 )?
410 .load_pem(keypair_rsa.cert(), keypair_rsa.key())?
411 .set_security_policy(&security::DEFAULT_TLS13)?;
412 let server_config = server_config_builder.build()?;
413
414 let mut client_config_builder = Builder::new();
415 client_config_builder
416 .enable_session_tickets(true)?
417 .trust_pem(keypair_rsa.cert())?
418 .set_verify_host_callback(InsecureAcceptAllCertificatesHandler {})?
419 .set_security_policy(&security::DEFAULT_TLS13)?;
420 let client_config = client_config_builder.build()?;
421
422 // 1st handshake: no session ticket, so no resumption
423 ctrl.start_instrumentation();
424 let session_ticket = {
425 let mut pair = TestPair::from_configs(&client_config, &server_config);
426 pair.client.set_waker(Some(&noop_waker()))?;
427 pair.handshake()?;
428 assert!(pair.client.poll_recv(&mut [0]).is_pending());
429
430 let mut ticket: Vec<u8> = vec![0; pair.client.session_ticket_length().unwrap()];
431 pair.client.session_ticket(&mut ticket).unwrap();
432
433 assert!(!pair.client.resumed());
434 ticket
435 };
436
437 // 2nd handshake: should be able to use the session ticket from the first
438 // handshake (stored in `session ticket`) to resume
439 {
440 let mut pair = TestPair::from_configs(&client_config, &server_config);
441 pair.client.set_waker(Some(&noop_waker()))?;
442
443 pair.client.set_session_ticket(&session_ticket).unwrap();
444 pair.handshake()?;
445
446 // Do a recv call on the client side to read a session ticket. Poll function
447 // returns pending since no application data was read, however it is enough
448 // to collect the session ticket.
449 assert!(pair.client.poll_recv(&mut [0]).is_pending());
450
451 // Assert the resumption status
452 assert!(pair.client.resumed());
453 }
454
455 ctrl.stop_instrumentation();
456
457 Ok(())
458 })
459 .unwrap();
460 }
461 }