aboutsummaryrefslogtreecommitdiff
path: root/src/config.rs
blob: 4c8bef1079eab8ef77b2e63d0489a6fe462a0e4d (plain)
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
use crate::dyndns_service::DynDnsProvider;
use crate::error::{AppError, AppResult};
use crate::ip_service::IpServiceProvider;
use fqdn::FQDN;
use serde::{Deserialize, Serialize};
use serde_with::DisplayFromStr;
use serde_with::serde_as;
use std::path::Path;
use std::{fs, io};
use strum::Display;

#[derive(Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct Config {
    pub networks: Vec<WanConfig>,
}

impl Config {
    pub fn load<P: AsRef<Path>>(path: P) -> AppResult<Config> {
        let path = path.as_ref();
        let content = fs::read_to_string(path).map_err(|e| match e.kind() {
            io::ErrorKind::NotFound => AppError::FileNotFound(path.to_path_buf()),
            _ => AppError::IoError(e),
        })?;

        serde_json::from_str(&content).map_err(|e| AppError::ConfigParseError {
            source: e,
            path: path.to_path_buf(),
        })
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct WanConfig {
    pub interface: Option<String>,
    #[serde(flatten)]
    pub dns_record: DnsRecord,
    pub providers: Vec<DynDnsProvider>,
    #[serde(default)]
    pub ip_service: IpServiceProvider,
}

#[derive(Debug, Display, Deserialize, Serialize, PartialEq)]
pub enum DnsRecordType {
    A,
    AAAA,
}

#[serde_as]
#[derive(Debug, Deserialize, Serialize)]
pub struct DnsRecord {
    #[serde_as(as = "DisplayFromStr")]
    fqdn: FQDN,
    #[serde(default = "default_ttl")]
    ttl: u32,
    #[serde(default = "default_record_type")]
    record_type: DnsRecordType,
}

fn default_record_type() -> DnsRecordType {
    DnsRecordType::A
}
fn default_ttl() -> u32 {
    300
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dyndns_service::DynDnsProvider::GANDI;
    use crate::dyndns_service::gandi::Gandi;
    use crate::{assert_config_parse_error, assert_error, assert_file_not_found, assert_io_error};
    use serde_json::json;
    use std::error::Error;
    use std::fs::{File, read_dir};
    use std::io::BufReader;
    use std::str::FromStr;

    #[test]
    fn check_minimal_config() {
        let input = json!({
            "fqdn": "dyn.domain.com",
            "providers": [ {
                "type": "GANDI",
                "api_key": "SOME-API-KEY",
            } ]
        });

        let wan_config = serde_json::from_value::<WanConfig>(input).unwrap();

        assert_eq!(
            wan_config.dns_record.fqdn,
            FQDN::from_str("dyn.domain.com").unwrap()
        );
        assert_eq!(wan_config.interface, None);

        assert_eq!(wan_config.providers.len(), 1);
        let expected = Gandi::new("SOME-API-KEY".to_string());
        let actual = wan_config.providers.get(0).unwrap();
        assert_eq!(&GANDI(expected), actual);
    }

    #[test]
    fn check_defaults_on_dns_record_deserialization() {
        let input = json!({
            "fqdn": "dyn.mydomain.com",
        });

        let dns_record = serde_json::from_value::<DnsRecord>(input).unwrap();

        assert_eq!(dns_record.record_type, default_record_type());
        assert_eq!(dns_record.ttl, default_ttl());

        assert_eq!(dns_record.fqdn, FQDN::from_str("dyn.mydomain.com").unwrap());
    }

    #[test]
    fn check_file_configs() -> Result<(), Box<dyn Error>> {
        let path = Path::new("test");
        for entry in read_dir(path)? {
            let entry = entry?;
            let test_file_path = entry.path();
            if test_file_path.extension().unwrap_or_default() != "json" {
                continue;
            }

            let file = File::open(test_file_path)?;
            let reader = BufReader::new(file);

            let actual: Config = serde_json::from_reader(reader)?;
            assert_eq!(actual.networks.len(), 2);
        }
        Ok(())
    }

    #[test]
    fn check_missing_config() -> Result<(), Box<dyn Error>> {
        let path = Path::new("test/unknown.yaml");

        assert_file_not_found!(Config::load(path), path);
        Ok(())
    }

    #[test]
    fn check_broken_config() -> Result<(), Box<dyn Error>> {
        let path = Path::new("test/config.bork");

        assert_config_parse_error!(Config::load(path), path);
        Ok(())
    }

    #[test]
    fn check_inaccessible_config() -> Result<(), Box<dyn Error>> {
        let path = Path::new("/root/secure-config.json");

        assert_io_error!(Config::load(path));
        Ok(())
    }
}