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
use crate::secret_type::SecretType;
use crate::MinosCodexError;
use rust_embed::RustEmbed;
use serde::Deserialize;
use std::collections::HashMap;
use std::str::Utf8Error;

impl From<Utf8Error> for MinosCodexError {
    fn from(err: Utf8Error) -> Self {
        MinosCodexError::ConfigLoadError(std::io::Error::new(std::io::ErrorKind::InvalidData, err))
    }
}

#[derive(Deserialize)]
struct SecretTypeWrapper {
    secret_type: SecretType,
}

#[derive(RustEmbed)]
#[folder = "detections/"]
struct ConfigAssets;

pub struct Config {
    secret_types: HashMap<String, SecretType>,
}

impl Config {
    pub fn new() -> Self {
        Config {
            secret_types: HashMap::new(),
        }
    }

    pub fn load_from_embedded() -> Result<Self, MinosCodexError> {
        let mut config = Config::new();

        for file in ConfigAssets::iter() {
            if file.ends_with(".toml") {
                let file_data = ConfigAssets::get(&file).ok_or_else(|| {
                    MinosCodexError::ConfigLoadError(std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        "File not found",
                    ))
                })?;
                let contents = std::str::from_utf8(file_data.data.as_ref())?;
                let secret_type = Config::load_secret_type_from_data(contents)?;
                config
                    .secret_types
                    .insert(secret_type.name.clone(), secret_type);
            }
        }

        Ok(config)
    }

    fn load_secret_type_from_data(data: &str) -> Result<SecretType, MinosCodexError> {
        let wrapper: SecretTypeWrapper = toml::from_str(data)?;
        wrapper
            .secret_type
            .validate()
            .map_err(MinosCodexError::ValidationError)?;
        Ok(wrapper.secret_type)
    }

    pub fn get_secret_type(&self, name: &str) -> Option<&SecretType> {
        self.secret_types.get(name)
    }

    pub fn secret_types(&self) -> impl Iterator<Item = &SecretType> {
        self.secret_types.values()
    }
}