csaf-walker 0.18.1

A library to work with CSAF data
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Verification
//!
//! Checks to ensure conformity with the specification.

use crate::check::Capped;
use crate::{
    discover::{AsDiscovered, DiscoveredAdvisory},
    retrieve::{AsRetrieved, RetrievalContext, RetrievedAdvisory, RetrievedVisitor},
    source::Source,
    validation::{ValidatedAdvisory, ValidatedVisitor, ValidationContext, ValidationError},
    verification::check::Check,
};
use csaf::json::JsonSource;
use serde::de::Error as _;
use std::{
    collections::{HashMap, HashSet},
    fmt::{Debug, Display},
    future::Future,
    hash::Hash,
    marker::PhantomData,
    ops::{Deref, DerefMut},
};
use url::Url;
use walker_common::{retrieve::RetrievalError, utils::url::Urlify};

pub mod check;

#[derive(Debug, Clone)]
pub enum Csaf {
    V2_0(csaf::schema::csaf2_0::schema::CommonSecurityAdvisoryFramework),
    V2_1(csaf::schema::csaf2_1::schema::CommonSecurityAdvisoryFramework),
}

impl Csaf {
    pub fn parse<T: JsonSource>(data: T) -> Result<Self, std::io::Error> {
        use csaf::csaf::loader::*;

        detect_version_with(data).and_then(|VersionAndData { version, data }| match &*version {
            "2.0" => Ok(Csaf::V2_0(data.parse()?)),
            "2.1" => Ok(Csaf::V2_1(data.parse()?)),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                format!("Unsupported CSAF version: {}", version),
            )),
        })
    }

    pub fn document(&self) -> DocumentLevelMetadata<'_> {
        match self {
            Self::V2_0(csaf) => DocumentLevelMetadata::V2_0(&csaf.document),
            Self::V2_1(csaf) => DocumentLevelMetadata::V2_1(&csaf.document),
        }
    }
}

pub enum DocumentLevelMetadata<'a> {
    V2_0(&'a csaf::schema::csaf2_0::schema::DocumentLevelMetaData),
    V2_1(&'a csaf::schema::csaf2_1::schema::DocumentLevelMetaData),
}

impl DocumentLevelMetadata<'_> {
    pub fn title(&self) -> &str {
        match self {
            Self::V2_0(csaf) => &csaf.title,
            Self::V2_1(csaf) => &csaf.title,
        }
    }

    pub fn tracking(&self) -> Tracking<'_> {
        match self {
            Self::V2_0(csaf) => Tracking::V2_0(&csaf.tracking),
            Self::V2_1(csaf) => Tracking::V2_1(&csaf.tracking),
        }
    }
}

pub enum Tracking<'a> {
    V2_0(&'a csaf::schema::csaf2_0::schema::Tracking),
    V2_1(&'a csaf::schema::csaf2_1::schema::Tracking),
}

impl Tracking<'_> {
    pub fn id(&self) -> &str {
        match self {
            Self::V2_0(csaf) => &csaf.id,
            Self::V2_1(csaf) => &csaf.id,
        }
    }

    pub fn initial_release_date(&self) -> &str {
        match self {
            Self::V2_0(csaf) => &csaf.initial_release_date,
            Self::V2_1(csaf) => &csaf.initial_release_date,
        }
    }
}

#[derive(Debug)]
pub struct VerifiedAdvisory<A, I>
where
    A: AsRetrieved,
    I: Clone + PartialEq + Eq + Hash,
{
    /// The advisory that was verified.
    pub advisory: A,
    /// The parsed CSAF document.
    pub csaf: Csaf,
    /// Per-check mandatory failures (errors).
    pub errors: HashMap<I, Capped>,
    /// Per-check optional/recommended failures (warnings).
    pub warnings: HashMap<I, Capped>,
    /// Per-check informational notes.
    pub infos: HashMap<I, Capped>,
    /// Checks that passed all tests.
    pub successes: HashSet<I>,
}

impl<A, I> Deref for VerifiedAdvisory<A, I>
where
    A: AsRetrieved,
    I: Clone + PartialEq + Eq + Hash,
{
    type Target = A;

    fn deref(&self) -> &Self::Target {
        &self.advisory
    }
}

impl<A, I> DerefMut for VerifiedAdvisory<A, I>
where
    A: AsRetrieved,
    I: Clone + PartialEq + Eq + Hash,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.advisory
    }
}

#[derive(Debug, thiserror::Error)]
pub enum VerificationError<UE, A>
where
    A: Debug,
    UE: Display + Debug,
{
    #[error(transparent)]
    Upstream(UE),
    #[error("document parsing error: {error}")]
    Parsing {
        advisory: A,
        error: serde_json::Error,
    },
    #[error("check runtime error: {error}")]
    Check { advisory: A, error: anyhow::Error },
}

impl<A, UE> AsDiscovered for VerificationError<UE, A>
where
    A: AsDiscovered + Debug,
    UE: AsDiscovered + Display + Debug,
{
    fn as_discovered(&self) -> &DiscoveredAdvisory {
        match self {
            Self::Upstream(err) => err.as_discovered(),
            Self::Parsing { advisory, .. } => advisory.as_discovered(),
            Self::Check { advisory, .. } => advisory.as_discovered(),
        }
    }
}

impl<UE, A> Urlify for VerificationError<UE, A>
where
    A: AsRetrieved + Debug,
    UE: Urlify + Display + Debug,
{
    fn url(&self) -> &Url {
        match self {
            Self::Upstream(err) => err.url(),
            Self::Parsing { advisory, .. } => advisory.as_retrieved().url(),
            Self::Check { advisory, .. } => advisory.as_retrieved().url(),
        }
    }
}

pub struct VerificationContext {}

/// A visitor accepting a verified advisory
pub trait VerifiedVisitor<A, E, I>
where
    A: AsRetrieved,
    E: Display + Debug,
    I: Clone + PartialEq + Eq + Hash,
{
    type Error: Display + Debug;
    type Context;

    fn visit_context(
        &self,
        context: &VerificationContext,
    ) -> impl Future<Output = Result<Self::Context, Self::Error>>;

    fn visit_advisory(
        &self,
        context: &Self::Context,
        result: Result<VerifiedAdvisory<A, I>, VerificationError<E, A>>,
    ) -> impl Future<Output = Result<(), Self::Error>>;
}

#[derive(Debug, thiserror::Error)]
pub enum Error<VE>
where
    VE: Display + Debug,
{
    #[error(transparent)]
    Visitor(VE),
}

/// A visitor implementing the verification of a CSAF document
pub struct VerifyingVisitor<A, E, V, I>
where
    A: AsRetrieved,
    V: VerifiedVisitor<A, E, I>,
    E: Display + Debug,
    I: Clone + PartialEq + Eq + Hash,
{
    visitor: V,
    checks: Vec<(I, Box<dyn Check>)>,
    _marker: PhantomData<(A, E)>,
}

impl<A, E, V, I> VerifyingVisitor<A, E, V, I>
where
    A: AsRetrieved,
    V: VerifiedVisitor<A, E, I>,
    E: Display + Debug,
    I: Clone + PartialEq + Eq + Hash,
{
    pub fn new(visitor: V) -> Self {
        Self {
            visitor,
            checks: vec![],
            _marker: Default::default(),
        }
    }

    pub fn with_checks(visitor: V, checks: Vec<(I, Box<dyn Check>)>) -> Self {
        Self {
            visitor,
            checks,
            _marker: Default::default(),
        }
    }

    pub fn add<F: Check + 'static>(mut self, index: I, check: F) -> Self {
        self.checks.push((index, Box::new(check)));
        self
    }

    async fn verify(&self, advisory: A) -> Result<VerifiedAdvisory<A, I>, VerificationError<E, A>> {
        let data = advisory.as_retrieved().data.clone();

        let csaf = match tokio::task::spawn_blocking(move || Csaf::parse(&*data)).await {
            Ok(Ok(csaf)) => csaf,
            Ok(Err(error)) => {
                return Err(VerificationError::Parsing {
                    error: serde::de::Error::custom(error),
                    advisory,
                });
            }
            Err(_) => {
                return Err(VerificationError::Parsing {
                    error: serde_json::error::Error::custom("failed to wait for deserialization"),
                    advisory,
                });
            }
        };

        let mut errors = HashMap::new();
        let mut warnings = HashMap::new();
        let mut infos = HashMap::new();
        let mut successes = HashSet::new();

        for (index, check) in &self.checks {
            let result = match check.as_ref().check(&csaf).await {
                Ok(result) => result,
                Err(error) => return Err(VerificationError::Check { error, advisory }),
            };
            if result.is_ok() {
                successes.insert(index.clone());
            } else {
                errors.insert(index.clone(), result.errors);
                warnings.insert(index.clone(), result.warnings);
                infos.insert(index.clone(), result.infos);
            }
        }

        Ok(VerifiedAdvisory {
            advisory,
            csaf,
            errors,
            warnings,
            infos,
            successes,
        })
    }
}

impl<V, I, S> RetrievedVisitor<S>
    for VerifyingVisitor<RetrievedAdvisory, RetrievalError<DiscoveredAdvisory, S>, V, I>
where
    V: VerifiedVisitor<RetrievedAdvisory, RetrievalError<DiscoveredAdvisory, S>, I>,
    I: Clone + PartialEq + Eq + Hash,
    S: Source,
{
    type Error = Error<V::Error>;
    type Context = V::Context;

    async fn visit_context(
        &self,
        _context: &RetrievalContext<'_>,
    ) -> Result<Self::Context, Self::Error> {
        self.visitor
            .visit_context(&VerificationContext {})
            .await
            .map_err(Error::Visitor)
    }

    async fn visit_advisory(
        &self,
        context: &Self::Context,
        result: Result<RetrievedAdvisory, RetrievalError<DiscoveredAdvisory, S>>,
    ) -> Result<(), Self::Error> {
        let result = match result {
            Ok(doc) => self.verify(doc).await,
            Err(err) => Err(VerificationError::Upstream(err)),
        };

        self.visitor
            .visit_advisory(context, result)
            .await
            .map_err(Error::Visitor)?;

        Ok(())
    }
}

impl<V, I, S> ValidatedVisitor<S> for VerifyingVisitor<ValidatedAdvisory, ValidationError<S>, V, I>
where
    V: VerifiedVisitor<ValidatedAdvisory, ValidationError<S>, I>,
    I: Clone + PartialEq + Eq + Hash,
    S: Source,
{
    type Error = Error<V::Error>;
    type Context = V::Context;

    async fn visit_context(
        &self,
        _context: &ValidationContext<'_>,
    ) -> Result<Self::Context, Self::Error> {
        self.visitor
            .visit_context(&VerificationContext {})
            .await
            .map_err(Error::Visitor)
    }

    async fn visit_advisory(
        &self,
        context: &Self::Context,
        result: Result<ValidatedAdvisory, ValidationError<S>>,
    ) -> Result<(), Self::Error> {
        let result = match result {
            Ok(doc) => self.verify(doc).await,
            Err(err) => Err(VerificationError::Upstream(err)),
        };

        self.visitor
            .visit_advisory(context, result)
            .await
            .map_err(Error::Visitor)?;

        Ok(())
    }
}

impl<F, E, Fut, A, I, UE> VerifiedVisitor<A, UE, I> for F
where
    UE: Debug + Display + 'static,
    F: Fn(Result<VerifiedAdvisory<A, I>, VerificationError<UE, A>>) -> Fut,
    Fut: Future<Output = Result<(), E>>,
    E: Display + Debug + 'static,
    A: AsRetrieved + 'static,
    I: Clone + PartialEq + Eq + Hash + 'static,
{
    type Error = E;
    type Context = ();

    async fn visit_context(
        &self,
        _context: &VerificationContext,
    ) -> Result<Self::Context, Self::Error> {
        Ok(())
    }

    async fn visit_advisory(
        &self,
        _ctx: &Self::Context,
        outcome: Result<VerifiedAdvisory<A, I>, VerificationError<UE, A>>,
    ) -> Result<(), Self::Error> {
        self(outcome).await
    }
}