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
//! Sources

mod dispatch;
mod file;
mod http;

pub use self::http::*;
pub use dispatch::*;
pub use file::*;

use crate::{
    discover::{DiscoverConfig, DiscoveredSbom},
    model::metadata::SourceMetadata,
    retrieve::RetrievedSbom,
};
use anyhow::bail;
use fluent_uri::Uri;
use std::fmt::{Debug, Display};
use std::future::Future;
use url::Url;
use walker_common::fetcher::{Fetcher, FetcherOptions};

/// A source of SBOM documents
pub trait Source: Clone {
    type Error: Display + Debug;

    fn load_metadata(&self) -> impl Future<Output = Result<SourceMetadata, Self::Error>>;
    fn load_index(&self) -> impl Future<Output = Result<Vec<DiscoveredSbom>, Self::Error>>;
    fn load_sbom(
        &self,
        sbom: DiscoveredSbom,
    ) -> impl Future<Output = Result<RetrievedSbom, Self::Error>>;
}

pub async fn new_source(
    discover: impl Into<DiscoverConfig>,
    fetcher: impl Into<FetcherOptions>,
) -> anyhow::Result<DispatchSource> {
    let discover = discover.into();
    let source = discover.source;

    match Uri::parse(&source) {
        Ok(uri) => {
            match uri.scheme().map(|s| s.as_str()) {
                Some("file") => {
                    let source = uri.path().as_str();
                    log::debug!("Creating file source: {source}");
                    Ok(FileSource::new(source, FileOptions::new().since(discover.since))?.into())
                }
                Some(_scheme) => {
                    log::debug!("Creating HTTP source: {source}");
                    let fetcher = Fetcher::new(fetcher.into()).await?;
                    Ok(HttpSource::new(
                        Url::parse(&source)?,
                        fetcher,
                        HttpOptions::new().since(discover.since).keys(discover.keys),
                    )
                    .into())
                }
                None => {
                    bail!("Failed to parse '{source}' as URL. For SBOMs there is no domain-based lookup");
                }
            }
        }
        Err(err) => {
            bail!(
                "Failed to parse '{source}' as URL. For SBOMs there is no domain-based lookup: {err}"
            );
        }
    }
}

#[cfg(test)]
mod test {
    use crate::discover::DiscoverConfig;
    use crate::source::new_source;
    use walker_common::fetcher::FetcherOptions;

    #[tokio::test]
    pub async fn test_file_source() {
        let result = new_source(
            DiscoverConfig {
                source: "file:/".to_string(),
                since: None,
                keys: vec![],
            },
            FetcherOptions::default(),
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    pub async fn test_http_source() {
        let result = new_source(
            DiscoverConfig {
                source: "https://foo.bar/baz".to_string(),
                since: None,
                keys: vec![],
            },
            FetcherOptions::default(),
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    pub async fn test_invalid_source() {
        let result = new_source(
            DiscoverConfig {
                source: "/var/files".to_string(),
                since: None,
                keys: vec![],
            },
            FetcherOptions::default(),
        )
        .await;

        assert!(result.is_err());
    }
}