ring/
test.rs

1// Copyright 2015-2016 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15//! Testing framework.
16//!
17//! Unlike the rest of *ring*, this testing framework uses panics pretty
18//! liberally. It was originally designed for internal use--it drives most of
19//! *ring*'s internal tests, and so it is optimized for getting *ring*'s tests
20//! written quickly at the expense of some usability. The documentation is
21//! lacking. The best way to learn it is to look at some examples. The digest
22//! tests are the most complicated because they use named sections. Other tests
23//! avoid named sections and so are easier to understand.
24//!
25//! # Examples
26//!
27//! ## Writing Tests
28//!
29//! Input files look like this:
30//!
31//! ```text
32//! # This is a comment.
33//!
34//! HMAC = SHA1
35//! Input = "My test data"
36//! Key = ""
37//! Output = 61afdecb95429ef494d61fdee15990cabf0826fc
38//!
39//! HMAC = SHA256
40//! Input = "Sample message for keylen<blocklen"
41//! Key = 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
42//! Output = A28CF43130EE696A98F14A37678B56BCFCBDD9E5CF69717FECF5480F0EBDF790
43//! ```
44//!
45//! Test cases are separated with blank lines. Note how the bytes of the `Key`
46//! attribute are specified as a quoted string in the first test case and as
47//! hex in the second test case; you can use whichever form is more convenient
48//! and you can mix and match within the same file. The empty sequence of bytes
49//! can only be represented with the quoted string form (`""`).
50//!
51//! Here's how you would consume the test data:
52//!
53//! ```ignore
54//! use ring::test;
55//!
56//! test::run(test::test_file!("hmac_tests.txt"), |section, test_case| {
57//!     assert_eq!(section, ""); // This test doesn't use named sections.
58//!
59//!     let digest_alg = test_case.consume_digest_alg("HMAC");
60//!     let input = test_case.consume_bytes("Input");
61//!     let key = test_case.consume_bytes("Key");
62//!     let output = test_case.consume_bytes("Output");
63//!
64//!     // Do the actual testing here
65//! });
66//! ```
67//!
68//! Note that `consume_digest_alg` automatically maps the string "SHA1" to a
69//! reference to `digest::SHA1_FOR_LEGACY_USE_ONLY`, "SHA256" to
70//! `digest::SHA256`, etc.
71//!
72//! ## Output When a Test Fails
73//!
74//! When a test case fails, the framework automatically prints out the test
75//! case. If the test case failed with a panic, then the backtrace of the panic
76//! will be printed too. For example, let's say the failing test case looks
77//! like this:
78//!
79//! ```text
80//! Curve = P-256
81//! a = 2b11cb945c8cf152ffa4c9c2b1c965b019b35d0b7626919ef0ae6cb9d232f8af
82//! b = 18905f76a53755c679fb732b7762251075ba95fc5fedb60179e730d418a9143c
83//! r = 18905f76a53755c679fb732b7762251075ba95fc5fedb60179e730d418a9143c
84//! ```
85//! If the test fails, this will be printed (if `$RUST_BACKTRACE` is `1`):
86//!
87//! ```text
88//! src/example_tests.txt: Test panicked.
89//! Curve = P-256
90//! a = 2b11cb945c8cf152ffa4c9c2b1c965b019b35d0b7626919ef0ae6cb9d232f8af
91//! b = 18905f76a53755c679fb732b7762251075ba95fc5fedb60179e730d418a9143c
92//! r = 18905f76a53755c679fb732b7762251075ba95fc5fedb60179e730d418a9143c
93//! thread 'example_test' panicked at 'Test failed.', src\test.rs:206
94//! stack backtrace:
95//!    0:     0x7ff654a05c7c - std::rt::lang_start::h61f4934e780b4dfc
96//!    1:     0x7ff654a04f32 - std::rt::lang_start::h61f4934e780b4dfc
97//!    2:     0x7ff6549f505d - std::panicking::rust_panic_with_hook::hfe203e3083c2b544
98//!    3:     0x7ff654a0825b - rust_begin_unwind
99//!    4:     0x7ff6549f63af - std::panicking::begin_panic_fmt::h484cd47786497f03
100//!    5:     0x7ff654a07e9b - rust_begin_unwind
101//!    6:     0x7ff654a0ae95 - core::panicking::panic_fmt::h257ceb0aa351d801
102//!    7:     0x7ff654a0b190 - core::panicking::panic::h4bb1497076d04ab9
103//!    8:     0x7ff65496dc41 - from_file<closure>
104//!                         at C:\Users\Example\example\<core macros>:4
105//!    9:     0x7ff65496d49c - example_test
106//!                         at C:\Users\Example\example\src\example.rs:652
107//!   10:     0x7ff6549d192a - test::stats::Summary::new::ha139494ed2e4e01f
108//!   11:     0x7ff6549d51a2 - test::stats::Summary::new::ha139494ed2e4e01f
109//!   12:     0x7ff654a0a911 - _rust_maybe_catch_panic
110//!   13:     0x7ff6549d56dd - test::stats::Summary::new::ha139494ed2e4e01f
111//!   14:     0x7ff654a03783 - std::sys::thread::Thread::new::h2b08da6cd2517f79
112//!   15:     0x7ff968518101 - BaseThreadInitThunk
113//! ```
114//!
115//! Notice that the output shows the name of the data file
116//! (`src/example_tests.txt`), the test inputs that led to the failure, and the
117//! stack trace to the line in the test code that panicked: entry 9 in the
118//! stack trace pointing to line 652 of the file `example.rs`.
119
120#[cfg(feature = "alloc")]
121use alloc::{format, string::String, vec::Vec};
122
123#[cfg(feature = "alloc")]
124use crate::{bits, digest, error};
125
126#[cfg(any(feature = "std", feature = "test_logging"))]
127extern crate std;
128
129/// `compile_time_assert_clone::<T>();` fails to compile if `T` doesn't
130/// implement `Clone`.
131pub fn compile_time_assert_clone<T: Clone>() {}
132
133/// `compile_time_assert_copy::<T>();` fails to compile if `T` doesn't
134/// implement `Copy`.
135pub fn compile_time_assert_copy<T: Copy>() {}
136
137/// `compile_time_assert_eq::<T>();` fails to compile if `T` doesn't
138/// implement `Eq`.
139pub fn compile_time_assert_eq<T: Eq>() {}
140
141/// `compile_time_assert_send::<T>();` fails to compile if `T` doesn't
142/// implement `Send`.
143pub fn compile_time_assert_send<T: Send>() {}
144
145/// `compile_time_assert_sync::<T>();` fails to compile if `T` doesn't
146/// implement `Sync`.
147pub fn compile_time_assert_sync<T: Sync>() {}
148
149/// `compile_time_assert_std_error_error::<T>();` fails to compile if `T`
150/// doesn't implement `std::error::Error`.
151#[cfg(feature = "std")]
152pub fn compile_time_assert_std_error_error<T: std::error::Error>() {}
153
154/// A test case. A test case consists of a set of named attributes. Every
155/// attribute in the test case must be consumed exactly once; this helps catch
156/// typos and omissions.
157///
158/// Requires the `alloc` default feature to be enabled.
159#[cfg(feature = "alloc")]
160#[derive(Debug)]
161pub struct TestCase {
162    attributes: Vec<(String, String, bool)>,
163}
164
165#[cfg(feature = "alloc")]
166impl TestCase {
167    /// Maps the string "true" to true and the string "false" to false.
168    pub fn consume_bool(&mut self, key: &str) -> bool {
169        match self.consume_string(key).as_ref() {
170            "true" => true,
171            "false" => false,
172            s => panic!("Invalid bool value: {}", s),
173        }
174    }
175
176    /// Maps the strings "SHA1", "SHA256", "SHA384", and "SHA512" to digest
177    /// algorithms, maps "SHA224" to `None`, and panics on other (erroneous)
178    /// inputs. "SHA224" is mapped to None because *ring* intentionally does
179    /// not support SHA224, but we need to consume test vectors from NIST that
180    /// have SHA224 vectors in them.
181    pub fn consume_digest_alg(&mut self, key: &str) -> Option<&'static digest::Algorithm> {
182        let name = self.consume_string(key);
183        match name.as_ref() {
184            "SHA1" => Some(&digest::SHA1_FOR_LEGACY_USE_ONLY),
185            "SHA224" => None, // We actively skip SHA-224 support.
186            "SHA256" => Some(&digest::SHA256),
187            "SHA384" => Some(&digest::SHA384),
188            "SHA512" => Some(&digest::SHA512),
189            "SHA512_256" => Some(&digest::SHA512_256),
190            _ => panic!("Unsupported digest algorithm: {}", name),
191        }
192    }
193
194    /// Returns the value of an attribute that is encoded as a sequence of an
195    /// even number of hex digits, or as a double-quoted UTF-8 string. The
196    /// empty (zero-length) value is represented as "".
197    pub fn consume_bytes(&mut self, key: &str) -> Vec<u8> {
198        let s = self.consume_string(key);
199        if s.starts_with('\"') {
200            // The value is a quoted UTF-8 string.
201
202            let mut bytes = Vec::with_capacity(s.as_bytes().len() - 2);
203            let mut s = s.as_bytes().iter().skip(1);
204            loop {
205                let b = match s.next() {
206                    Some(b'\\') => {
207                        match s.next() {
208                            // We don't allow all octal escape sequences, only "\0" for null.
209                            Some(b'0') => 0u8,
210                            Some(b't') => b'\t',
211                            Some(b'n') => b'\n',
212                            // "\xHH"
213                            Some(b'x') => {
214                                let hi = s.next().expect("Invalid hex escape sequence in string.");
215                                let lo = s.next().expect("Invalid hex escape sequence in string.");
216                                if let (Ok(hi), Ok(lo)) = (from_hex_digit(*hi), from_hex_digit(*lo))
217                                {
218                                    (hi << 4) | lo
219                                } else {
220                                    panic!("Invalid hex escape sequence in string.");
221                                }
222                            }
223                            _ => {
224                                panic!("Invalid hex escape sequence in string.");
225                            }
226                        }
227                    }
228                    Some(b'"') => {
229                        if s.next().is_some() {
230                            panic!("characters after the closing quote of a quoted string.");
231                        }
232                        break;
233                    }
234                    Some(b) => *b,
235                    None => panic!("Missing terminating '\"' in string literal."),
236                };
237                bytes.push(b);
238            }
239            bytes
240        } else {
241            // The value is hex encoded.
242            match from_hex(&s) {
243                Ok(s) => s,
244                Err(err_str) => {
245                    panic!("{} in {}", err_str, s);
246                }
247            }
248        }
249    }
250
251    /// Returns the value of an attribute that is an integer, in decimal
252    /// notation.
253    pub fn consume_usize(&mut self, key: &str) -> usize {
254        let s = self.consume_string(key);
255        s.parse::<usize>().unwrap()
256    }
257
258    /// Returns the value of an attribute that is an integer, in decimal
259    /// notation, as a bit length.
260    #[cfg(feature = "alloc")]
261    pub fn consume_usize_bits(&mut self, key: &str) -> bits::BitLength {
262        let s = self.consume_string(key);
263        let bits = s.parse::<usize>().unwrap();
264        bits::BitLength::from_usize_bits(bits)
265    }
266
267    /// Returns the raw value of an attribute, without any unquoting or
268    /// other interpretation.
269    pub fn consume_string(&mut self, key: &str) -> String {
270        self.consume_optional_string(key)
271            .unwrap_or_else(|| panic!("No attribute named \"{}\"", key))
272    }
273
274    /// Like `consume_string()` except it returns `None` if the test case
275    /// doesn't have the attribute.
276    pub fn consume_optional_string(&mut self, key: &str) -> Option<String> {
277        for (name, value, consumed) in &mut self.attributes {
278            if key == name {
279                if *consumed {
280                    panic!("Attribute {} was already consumed", key);
281                }
282                *consumed = true;
283                return Some(value.clone());
284            }
285        }
286        None
287    }
288}
289
290/// References a test input file.
291#[cfg(feature = "alloc")]
292#[macro_export]
293macro_rules! test_file {
294    ($file_name:expr) => {
295        crate::test::File {
296            file_name: $file_name,
297            contents: include_str!($file_name),
298        }
299    };
300}
301
302/// A test input file.
303#[cfg(feature = "alloc")]
304pub struct File<'a> {
305    /// The name (path) of the file.
306    pub file_name: &'a str,
307
308    /// The contents of the file.
309    pub contents: &'a str,
310}
311
312/// Parses test cases out of the given file, calling `f` on each vector until
313/// `f` fails or until all the test vectors have been read. `f` can indicate
314/// failure either by returning `Err()` or by panicking.
315///
316/// Requires the `alloc` default feature to be enabled
317#[cfg(feature = "alloc")]
318pub fn run<F>(test_file: File, mut f: F)
319where
320    F: FnMut(&str, &mut TestCase) -> Result<(), error::Unspecified>,
321{
322    let lines = &mut test_file.contents.lines();
323
324    let mut current_section = String::from("");
325    let mut failed = false;
326
327    while let Some(mut test_case) = parse_test_case(&mut current_section, lines) {
328        let result = match f(&current_section, &mut test_case) {
329            Ok(()) => {
330                if !test_case
331                    .attributes
332                    .iter()
333                    .any(|&(_, _, consumed)| !consumed)
334                {
335                    Ok(())
336                } else {
337                    failed = true;
338                    Err("Test didn't consume all attributes.")
339                }
340            }
341            Err(error::Unspecified) => Err("Test returned Err(error::Unspecified)."),
342        };
343
344        if result.is_err() {
345            failed = true;
346        }
347
348        #[cfg(feature = "test_logging")]
349        {
350            if let Err(msg) = result {
351                std::println!("{}: {}", test_file.file_name, msg);
352
353                for (name, value, consumed) in test_case.attributes {
354                    let consumed_str = if consumed { "" } else { " (unconsumed)" };
355                    std::println!("{}{} = {}", name, consumed_str, value);
356                }
357            };
358        }
359    }
360
361    if failed {
362        panic!("Test failed.")
363    }
364}
365
366/// Decode an string of hex digits into a sequence of bytes. The input must
367/// have an even number of digits.
368#[cfg(feature = "alloc")]
369pub fn from_hex(hex_str: &str) -> Result<Vec<u8>, String> {
370    if hex_str.len() % 2 != 0 {
371        return Err(String::from(
372            "Hex string does not have an even number of digits",
373        ));
374    }
375
376    let mut result = Vec::with_capacity(hex_str.len() / 2);
377    for digits in hex_str.as_bytes().chunks(2) {
378        let hi = from_hex_digit(digits[0])?;
379        let lo = from_hex_digit(digits[1])?;
380        result.push((hi * 0x10) | lo);
381    }
382    Ok(result)
383}
384
385#[cfg(feature = "alloc")]
386fn from_hex_digit(d: u8) -> Result<u8, String> {
387    use core::ops::RangeInclusive;
388    const DECIMAL: (u8, RangeInclusive<u8>) = (0, b'0'..=b'9');
389    const HEX_LOWER: (u8, RangeInclusive<u8>) = (10, b'a'..=b'f');
390    const HEX_UPPER: (u8, RangeInclusive<u8>) = (10, b'A'..=b'F');
391    for (offset, range) in &[DECIMAL, HEX_LOWER, HEX_UPPER] {
392        if range.contains(&d) {
393            return Ok(d - range.start() + offset);
394        }
395    }
396    Err(format!("Invalid hex digit '{}'", d as char))
397}
398
399#[cfg(feature = "alloc")]
400fn parse_test_case(
401    current_section: &mut String,
402    lines: &mut dyn Iterator<Item = &str>,
403) -> Option<TestCase> {
404    let mut attributes = Vec::new();
405
406    let mut is_first_line = true;
407    loop {
408        let line = lines.next();
409
410        #[cfg(feature = "test_logging")]
411        {
412            if let Some(text) = &line {
413                std::println!("Line: {}", text);
414            }
415        }
416
417        match line {
418            // If we get to EOF when we're not in the middle of a test case,
419            // then we're done.
420            None if is_first_line => {
421                return None;
422            }
423
424            // End of the file on a non-empty test cases ends the test case.
425            None => {
426                return Some(TestCase { attributes });
427            }
428
429            // A blank line ends a test case if the test case isn't empty.
430            Some(ref line) if line.is_empty() => {
431                if !is_first_line {
432                    return Some(TestCase { attributes });
433                }
434                // Ignore leading blank lines.
435            }
436
437            // Comments start with '#'; ignore them.
438            Some(ref line) if line.starts_with('#') => (),
439
440            Some(ref line) if line.starts_with('[') => {
441                assert!(is_first_line);
442                assert!(line.ends_with(']'));
443                current_section.truncate(0);
444                current_section.push_str(line);
445                let _ = current_section.pop();
446                let _ = current_section.remove(0);
447            }
448
449            Some(ref line) => {
450                is_first_line = false;
451
452                let parts: Vec<&str> = line.splitn(2, " = ").collect();
453                if parts.len() != 2 {
454                    panic!("Syntax error: Expected Key = Value.");
455                };
456
457                let key = parts[0].trim();
458                let value = parts[1].trim();
459
460                // Don't allow the value to be ommitted. An empty value can be
461                // represented as an empty quoted string.
462                assert_ne!(value.len(), 0);
463
464                // Checking is_none() ensures we don't accept duplicate keys.
465                attributes.push((String::from(key), String::from(value), false));
466            }
467        }
468    }
469}
470
471/// Deterministic implementations of `ring::rand::SecureRandom`.
472///
473/// These implementations are particularly useful for testing implementations
474/// of randomized algorithms & protocols using known-answer-tests where the
475/// test vectors contain the random seed to use. They are also especially
476/// useful for some types of fuzzing.
477#[doc(hidden)]
478pub mod rand {
479    use crate::{error, polyfill, rand};
480
481    /// An implementation of `SecureRandom` that always fills the output slice
482    /// with the given byte.
483    #[derive(Debug)]
484    pub struct FixedByteRandom {
485        pub byte: u8,
486    }
487
488    impl rand::sealed::SecureRandom for FixedByteRandom {
489        fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
490            polyfill::slice::fill(dest, self.byte);
491            Ok(())
492        }
493    }
494
495    /// An implementation of `SecureRandom` that always fills the output slice
496    /// with the slice in `bytes`. The length of the slice given to `slice`
497    /// must match exactly.
498    #[derive(Debug)]
499    pub struct FixedSliceRandom<'a> {
500        pub bytes: &'a [u8],
501    }
502
503    impl rand::sealed::SecureRandom for FixedSliceRandom<'_> {
504        fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
505            dest.copy_from_slice(self.bytes);
506            Ok(())
507        }
508    }
509
510    /// An implementation of `SecureRandom` where each slice in `bytes` is a
511    /// test vector for one call to `fill()`. *Not thread-safe.*
512    ///
513    /// The first slice in `bytes` is the output for the first call to
514    /// `fill()`, the second slice is the output for the second call to
515    /// `fill()`, etc. The output slice passed to `fill()` must have exactly
516    /// the length of the corresponding entry in `bytes`. `current` must be
517    /// initialized to zero. `fill()` must be called exactly once for each
518    /// entry in `bytes`.
519    #[derive(Debug)]
520    pub struct FixedSliceSequenceRandom<'a> {
521        /// The value.
522        pub bytes: &'a [&'a [u8]],
523        pub current: core::cell::UnsafeCell<usize>,
524    }
525
526    impl rand::sealed::SecureRandom for FixedSliceSequenceRandom<'_> {
527        fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
528            let current = unsafe { *self.current.get() };
529            let bytes = self.bytes[current];
530            dest.copy_from_slice(bytes);
531            // Remember that we returned this slice and prepare to return
532            // the next one, if any.
533            unsafe { *self.current.get() += 1 };
534            Ok(())
535        }
536    }
537
538    impl Drop for FixedSliceSequenceRandom<'_> {
539        fn drop(&mut self) {
540            // Ensure that `fill()` was called exactly the right number of
541            // times.
542            assert_eq!(unsafe { *self.current.get() }, self.bytes.len());
543        }
544    }
545}
546
547#[cfg(test)]
548mod tests {
549    use crate::{error, test};
550
551    #[test]
552    fn one_ok() {
553        test::run(test_file!("test_1_tests.txt"), |_, test_case| {
554            let _ = test_case.consume_string("Key");
555            Ok(())
556        });
557    }
558
559    #[test]
560    #[should_panic(expected = "Test failed.")]
561    fn one_err() {
562        test::run(test_file!("test_1_tests.txt"), |_, test_case| {
563            let _ = test_case.consume_string("Key");
564            Err(error::Unspecified)
565        });
566    }
567
568    #[test]
569    #[should_panic(expected = "Oh noes!")]
570    fn one_panics() {
571        test::run(test_file!("test_1_tests.txt"), |_, test_case| {
572            let _ = test_case.consume_string("Key");
573            panic!("Oh noes!");
574        });
575    }
576
577    #[test]
578    #[should_panic(expected = "Test failed.")]
579    fn first_err() {
580        err_one(0)
581    }
582
583    #[test]
584    #[should_panic(expected = "Test failed.")]
585    fn middle_err() {
586        err_one(1)
587    }
588
589    #[test]
590    #[should_panic(expected = "Test failed.")]
591    fn last_err() {
592        err_one(2)
593    }
594
595    fn err_one(test_to_fail: usize) {
596        let mut n = 0;
597        test::run(test_file!("test_3_tests.txt"), |_, test_case| {
598            let _ = test_case.consume_string("Key");
599            let result = if n != test_to_fail {
600                Ok(())
601            } else {
602                Err(error::Unspecified)
603            };
604            n += 1;
605            result
606        });
607    }
608
609    #[test]
610    #[should_panic(expected = "Oh Noes!")]
611    fn first_panic() {
612        panic_one(0)
613    }
614
615    #[test]
616    #[should_panic(expected = "Oh Noes!")]
617    fn middle_panic() {
618        panic_one(1)
619    }
620
621    #[test]
622    #[should_panic(expected = "Oh Noes!")]
623    fn last_panic() {
624        panic_one(2)
625    }
626
627    fn panic_one(test_to_fail: usize) {
628        let mut n = 0;
629        test::run(test_file!("test_3_tests.txt"), |_, test_case| {
630            let _ = test_case.consume_string("Key");
631            if n == test_to_fail {
632                panic!("Oh Noes!");
633            };
634            n += 1;
635            Ok(())
636        });
637    }
638
639    #[test]
640    #[should_panic(expected = "Syntax error: Expected Key = Value.")]
641    fn syntax_error() {
642        test::run(test_file!("test_1_syntax_error_tests.txt"), |_, _| Ok(()));
643    }
644}