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
use std::{
    env,
    error::Error,
    fs::{self, OpenOptions},
    io::{Read, Write},
    path::Path,
};

use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct KdfObject {
    pub algorithm: String,
    pub parameters: Option<KdfParams>,
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct KdfParams {
    pub iterations: u8,
    pub threads: u8,
    pub memory: u32,
}

impl Default for KdfParams {
    fn default() -> Self {
        // Default params
        // According to default argon2 rust crate
        // (https://docs.rs/argon2/latest/src/argon2/params.rs.html#40)
        KdfParams {
            iterations: 2,
            threads: 1,
            memory: 19 * 1024,
        }
    }
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct AlgorithmConfig {
    pub encryption: String,
    pub hash: String,
    pub kdf: KdfObject,
    pub compression: bool,
}

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct Config {
    pub db_path: String,
    pub algorithms: AlgorithmConfig,
    pub lock_timeout: u32,
    pub debug_mode: bool,
}

pub fn default_config() -> Config {
    let mut default_path = home::home_dir().unwrap_or_else(env::temp_dir);
    default_path.push(".deadbolt");
    default_path.push("database.dblt");

    Config {
        db_path: default_path.to_string_lossy().to_string(),
        algorithms: AlgorithmConfig {
            encryption: "aes-gcm".to_string(),
            hash: "sha-256".to_string(),
            kdf: KdfObject {
                algorithm: "argon2d".to_string(),
                parameters: Some(KdfParams::default()),
            },
            compression: true,
        },
        lock_timeout: 1800,
        debug_mode: false,
    }
}

pub fn get_config(path: &str) -> Result<Config, Box<dyn Error>> {
    let mut file = OpenOptions::new().read(true).open(path)?;
    let mut buf: String = Default::default();
    file.read_to_string(&mut buf)?;

    let value: Config = serde_yaml::from_str(&buf)?;
    Ok(value)
}

pub fn set_config(path: &str, config: &Config) -> Result<(), Box<dyn Error>> {
    let yaml = serde_yaml::to_string(&config)?;
    // Create parent folder(s) if not exist
    let parent = Path::new(path).parent();
    if let Some(parent_dir) = parent {
        fs::create_dir_all(parent_dir)?;
    }

    let mut file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(path)?;

    file.write_all(yaml.as_bytes())?;
    Ok(())
}