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
use crate::credentials::Credentials;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine;
use bon::bon;
use std::collections::HashMap;
use std::path::PathBuf;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("The user's home directory could not be found. Please refer to the `dirs` crate for more information.")]
    HomeDirNotFound,
    #[error("The credentials file could not be loaded: {0}")]
    CouldNotReadCredentials(#[from] std::io::Error),
    #[error("The credentials file could not be parsed: {0}")]
    CredentialsParse(#[from] config::ConfigError),
}

/// A struct representing the remote.it credentials file.
///
/// The credentials file can have multiple profiles, each with its own access key ID and secret access key.
///
/// The secret access keys of the profiles within this struct are base64 encoded.
/// At this point they are unverified, which is why the inner [`HashMap`] is private.
/// The secret key of the profile you want will be verified, when the profile is retrieved using one of:
/// - [`CredentialProfiles::take_profile`]
/// - [`CredentialProfiles::profile`]
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct CredentialProfiles {
    #[serde(flatten)]
    pub(crate) profiles: HashMap<String, Credentials>,
}

impl CredentialProfiles {
    /// See [`CredentialProfiles::take_profile`] if you need an owned value.
    ///
    /// # Returns
    /// - [`None`] if the profile with the given name does not exist.
    /// - [`Some`] containing a reference to the [`Credentials`] with the given name, if the profile exists.
    ///
    /// # Errors
    /// - [`base64::DecodeError`] if the secret access key of the profile with the given name is not base64 encoded.
    pub fn profile(&self, profile_name: &str) -> Result<Option<&Credentials>, base64::DecodeError> {
        let profile = self.profiles.get(profile_name);
        if profile.is_none() {
            return Ok(None);
        }

        let _decode_result = BASE64_STANDARD.decode(&profile.unwrap().r3_secret_access_key)?;

        Ok(profile)
    }

    /// Takes the profile with the given name out of the inner [`HashMap`], validated the secret access key and returns it.
    /// You can only take a profile once, after that it is removed from the inner [`HashMap`].
    ///
    /// # Returns
    /// - [`None`] if the profile with the given name does not exist.
    /// - [`Some`] containing the [`Credentials`] with the given name, if the profile exists.
    ///
    /// # Errors
    /// - [`base64::DecodeError`] if the secret access key of the profile with the given name is not base64 encoded.
    pub fn take_profile(
        &mut self,
        profile_name: &str,
    ) -> Result<Option<Credentials>, base64::DecodeError> {
        let profile = self.profiles.remove(profile_name);

        let Some(profile) = profile else {
            return Ok(None);
        };

        let _decode_result = BASE64_STANDARD.decode(&profile.r3_secret_access_key)?;

        Ok(Some(profile))
    }

    /// # Returns
    /// The number of profiles in the inner [`HashMap`].
    #[must_use]
    pub fn len(&self) -> usize {
        self.profiles.len()
    }

    /// # Returns
    /// - [`true`] if there are no profiles in the inner [`HashMap`].
    /// - [`false`] if there is at least one profile in the inner [`HashMap`].
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.profiles.is_empty()
    }
}

/// Impl block for credentials_loader related functions.
#[bon]
impl Credentials {
    /// Attempts to load the remote.it credentials from the user's home directory.
    /// The default location is `~/.remoteit/credentials`.
    ///
    /// # Errors
    /// * [`Error::HomeDirNotFound`], when the [`dirs`] create cannot find the user's home directory.
    /// * [`Error::CouldNotReadCredentials`], when the credentials file could not be parsed by the [`figment`] crate.
    #[builder]
    pub fn load_from_disk(
        custom_credentials_path: Option<PathBuf>,
    ) -> Result<CredentialProfiles, Error> {
        let credentials_path = custom_credentials_path.unwrap_or(
            dirs::home_dir()
                .ok_or(Error::HomeDirNotFound)?
                .join(".remoteit")
                .join("credentials"),
        );

        let profiles: CredentialProfiles = config::Config::builder()
            .add_source(config::File::new(
                credentials_path
                    .to_str()
                    .expect("It is highly unlikely, that there would be a "),
                config::FileFormat::Ini,
            ))
            .build()?
            .try_deserialize()?;

        Ok(profiles)
    }
}

#[cfg(test)]
mod tests {
    use crate::credentials::Credentials;
    use std::io::Write;

    #[test]
    fn test_load_from_disk_empty() {
        let file = tempfile::NamedTempFile::new().unwrap();

        let credentials = Credentials::load_from_disk()
            .custom_credentials_path(file.path().to_path_buf())
            .call()
            .unwrap();

        assert!(credentials.is_empty());
    }

    #[test]
    fn test_load_from_disk_one() {
        let credentials = r"
            [default]
            R3_ACCESS_KEY_ID=foo
            R3_SECRET_ACCESS_KEY=YmFy
        ";

        let mut file = tempfile::NamedTempFile::new().unwrap();
        file.write_all(credentials.as_bytes()).unwrap();

        let credentials = Credentials::load_from_disk()
            .custom_credentials_path(file.path().to_path_buf())
            .call()
            .unwrap();

        assert_eq!(credentials.len(), 1);
        let credentials = credentials.profile("default").unwrap().unwrap();
        assert_eq!(credentials.r3_access_key_id, "foo");
        assert_eq!(credentials.r3_secret_access_key, "YmFy");
    }

    #[test]
    fn test_load_from_disk_two() {
        let credentials = r"
            [default]
            R3_ACCESS_KEY_ID=foo
            R3_SECRET_ACCESS_KEY=YmFy

            [other]
            R3_ACCESS_KEY_ID=baz
            R3_SECRET_ACCESS_KEY=YmFy
        ";

        let mut file = tempfile::NamedTempFile::new().unwrap();
        file.write_all(credentials.as_bytes()).unwrap();

        let credentials = Credentials::load_from_disk()
            .custom_credentials_path(file.path().to_path_buf())
            .call()
            .unwrap();

        assert_eq!(credentials.len(), 2);
        let profile = credentials.profile("default").unwrap().unwrap();
        assert_eq!(profile.r3_access_key_id, "foo");
        assert_eq!(profile.r3_secret_access_key, "YmFy");
        let profile = credentials.profile("other").unwrap().unwrap();
        assert_eq!(profile.r3_access_key_id, "baz");
        assert_eq!(profile.r3_secret_access_key, "YmFy");
    }
}