1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
mod certificate;
mod extensions;
mod loggers;
mod name;
mod structure;
use std::marker::PhantomData;

pub use certificate::*;
pub use extensions::*;
pub use loggers::*;
pub use name::*;
pub use structure::*;

/// Trait for validating item (for ex. validate X.509 structure)
///
/// # Examples
///
/// Using callbacks:
///
/// ```
/// use x509_parser::certificate::X509Certificate;
/// # #[allow(deprecated)]
/// use x509_parser::validate::Validate;
/// # #[allow(deprecated)]
/// #[cfg(feature = "validate")]
/// fn validate_certificate(x509: &X509Certificate<'_>) -> Result<(), &'static str> {
///     println!("  Subject: {}", x509.subject());
///     // validate and print warnings and errors to stderr
///     let ok = x509.validate(
///         |msg| {
///             eprintln!("  [W] {}", msg);
///         },
///         |msg| {
///             eprintln!("  [E] {}", msg);
///         },
///     );
///     print!("Structure validation status: ");
///     if ok {
///         println!("Ok");
///         Ok(())
///     } else {
///         println!("FAIL");
///         Err("validation failed")
///     }
/// }
/// ```
///
/// Collecting warnings and errors to `Vec`:
///
/// ```
/// use x509_parser::certificate::X509Certificate;
/// # #[allow(deprecated)]
/// use x509_parser::validate::Validate;
///
/// # #[allow(deprecated)]
/// #[cfg(feature = "validate")]
/// fn validate_certificate(x509: &X509Certificate<'_>) -> Result<(), &'static str> {
///     println!("  Subject: {}", x509.subject());
///     // validate and print warnings and errors to stderr
///     let (ok, warnings, errors) = x509.validate_to_vec();
///     print!("Structure validation status: ");
///     if ok {
///         println!("Ok");
///     } else {
///         println!("FAIL");
///     }
///     for warning in &warnings {
///         eprintln!("  [W] {}", warning);
///     }
///     for error in &errors {
///         eprintln!("  [E] {}", error);
///     }
///     println!();
///     if !errors.is_empty() {
///         return Err("validation failed");
///     }
///     Ok(())
/// }
/// ```
#[deprecated(since = "0.13.0", note = "please use `X509StructureValidator` instead")]
pub trait Validate {
    /// Attempts to validate current item.
    ///
    /// Returns `true` if item was validated.
    ///
    /// Call `warn()` if a non-fatal error was encountered, and `err()`
    /// if the error is fatal. These fucntions receive a description of the error.
    fn validate<W, E>(&self, warn: W, err: E) -> bool
    where
        W: FnMut(&str),
        E: FnMut(&str);

    /// Attempts to validate current item, storing warning and errors in `Vec`.
    ///
    /// Returns the validation result (`true` if validated), the list of warnings,
    /// and the list of errors.
    fn validate_to_vec(&self) -> (bool, Vec<String>, Vec<String>) {
        let mut warn_list = Vec::new();
        let mut err_list = Vec::new();
        let res = self.validate(
            |s| warn_list.push(s.to_owned()),
            |s| err_list.push(s.to_owned()),
        );
        (res, warn_list, err_list)
    }
}

/// Trait for build item validators (for ex. validate X.509 structure)
///
/// See [`X509StructureValidator`] for a default implementation, validating the
/// DER structure of a X.509 Certificate.
///
/// See implementors of the [`Logger`] trait for methods to collect or handle warnings and errors.
///
/// # Examples
///
/// Collecting warnings and errors to `Vec`:
///
/// ```
/// use x509_parser::certificate::X509Certificate;
/// use x509_parser::validate::*;
///
/// # #[allow(deprecated)]
/// #[cfg(feature = "validate")]
/// fn validate_certificate(x509: &X509Certificate<'_>) -> Result<(), &'static str> {
///     let mut logger = VecLogger::default();
///     println!("  Subject: {}", x509.subject());
///     // validate and print warnings and errors to stderr
///     let ok = X509StructureValidator.validate(&x509, &mut logger);
///     print!("Structure validation status: ");
///     if ok {
///         println!("Ok");
///     } else {
///         println!("FAIL");
///     }
///     for warning in logger.warnings() {
///         eprintln!("  [W] {}", warning);
///     }
///     for error in logger.errors() {
///         eprintln!("  [E] {}", error);
///     }
///     println!();
///     if !logger.errors().is_empty() {
///         return Err("validation failed");
///     }
///     Ok(())
/// }
/// ```
pub trait Validator<'a> {
    /// The item to validate
    type Item;

    /// Attempts to validate current item.
    ///
    /// Returns `true` if item was validated.
    ///
    /// Call `l.warn()` if a non-fatal error was encountered, and `l.err()`
    /// if the error is fatal. These functions receive a description of the error.
    fn validate<L: Logger>(&self, item: &'a Self::Item, l: &'_ mut L) -> bool;

    fn chain<V2>(self, v2: V2) -> ChainValidator<'a, Self, V2, Self::Item>
    where
        Self: Sized,
        V2: Validator<'a, Item = Self::Item>,
    {
        ChainValidator {
            v1: self,
            v2,
            _p: PhantomData,
        }
    }
}

#[derive(Debug)]
pub struct ChainValidator<'a, A, B, I>
where
    A: Validator<'a, Item = I>,
    B: Validator<'a, Item = I>,
{
    v1: A,
    v2: B,
    _p: PhantomData<&'a ()>,
}

impl<'a, A, B, I> Validator<'a> for ChainValidator<'a, A, B, I>
where
    A: Validator<'a, Item = I>,
    B: Validator<'a, Item = I>,
{
    type Item = I;

    fn validate<L: Logger>(&'_ self, item: &'a Self::Item, l: &'_ mut L) -> bool {
        self.v1.validate(item, l) & self.v2.validate(item, l)
    }
}

#[allow(deprecated)]
#[cfg(test)]
mod tests {
    use crate::validate::*;

    struct V1 {
        a: u32,
    }

    impl Validate for V1 {
        fn validate<W, E>(&self, mut warn: W, _err: E) -> bool
        where
            W: FnMut(&str),
            E: FnMut(&str),
        {
            if self.a > 10 {
                warn("a is greater than 10");
            }
            true
        }
    }

    struct V1Validator;

    impl<'a> Validator<'a> for V1Validator {
        type Item = V1;

        fn validate<L: Logger>(&self, item: &'a Self::Item, l: &'_ mut L) -> bool {
            if item.a > 10 {
                l.warn("a is greater than 10");
            }
            true
        }
    }

    #[test]
    fn validate_warn() {
        let v1 = V1 { a: 1 };
        let (res, warn, err) = v1.validate_to_vec();
        assert!(res);
        assert!(warn.is_empty());
        assert!(err.is_empty());
        // same, with one warning
        let v20 = V1 { a: 20 };
        let (res, warn, err) = v20.validate_to_vec();
        assert!(res);
        assert_eq!(warn, vec!["a is greater than 10".to_string()]);
        assert!(err.is_empty());
    }

    #[test]
    fn validator_warn() {
        let mut logger = VecLogger::default();
        let v1 = V1 { a: 1 };
        let res = V1Validator.validate(&v1, &mut logger);
        assert!(res);
        assert!(logger.warnings().is_empty());
        assert!(logger.errors().is_empty());
        // same, with one warning
        let v20 = V1 { a: 20 };
        let res = V1Validator.validate(&v20, &mut logger);
        assert!(res);
        assert_eq!(logger.warnings(), &["a is greater than 10".to_string()]);
        assert!(logger.errors().is_empty());
    }
}