nethsm_config/
credentials.rs

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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::{collections::HashSet, fmt::Display, str::FromStr};

use nethsm::{Credentials, Passphrase, UserId, UserRole};
use serde::{Deserialize, Serialize};
use ssh_key::{authorized_keys::Entry, PublicKey};
use zeroize::Zeroize;

/// Errors related to credentials
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// There is a duplicate SSH public key in a list of SSH authorized keys
    #[error("The SSH authorized key is used multiple times: {ssh_authorized_key}")]
    DuplicateAuthorizedKeys {
        ssh_authorized_key: AuthorizedKeyEntry,
    },

    /// A system username is invalid
    #[error("Invalid system user name: {0}")]
    InvalidSystemUserName(String),

    /// There are no SSH authorized keys
    #[error("The SSH authorized key is not valid: {entry}")]
    InvalidAuthorizedKeyEntry { entry: String },

    /// There are no SSH authorized keys
    #[error("No SSH authorized key provided!")]
    NoAuthorizedKeys,

    /// An SSH key error
    #[error("SSH key error: {0}")]
    SshKey(#[from] ssh_key::Error),

    /// A system-wide [`UserId`] has a namespace
    #[error("The system-wide User ID has a namespace: {0}")]
    SystemWideUserIdWithNamespace(UserId),

    /// A [`NetHsm`][`nethsm::NetHsm`] user error
    #[error("NetHSM user error: {0}")]
    NetHsmUser(#[from] nethsm::UserError),
}

/// A set of credentials for a [`NetHsm`][`nethsm::NetHsm`]
///
/// Tracks the [`UserRole`], [`UserId`] and optionally the passphrase of the user.
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize, Zeroize)]
pub struct ConfigCredentials {
    #[zeroize(skip)]
    role: UserRole,
    #[zeroize(skip)]
    name: UserId,
    passphrase: Option<String>,
}

impl ConfigCredentials {
    /// Creates a new [`ConfigCredentials`]
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm::UserRole;
    /// use nethsm_config::{ConfigCredentials, ConfigInteractivity};
    ///
    /// # fn main() -> testresult::TestResult {
    /// // credentials for an Operator user with passphrase
    /// ConfigCredentials::new(
    ///     UserRole::Operator,
    ///     "user1".parse()?,
    ///     Some("my-passphrase".into()),
    /// );
    ///
    /// // credentials for an Administrator user without passphrase
    /// ConfigCredentials::new(UserRole::Administrator, "admin1".parse()?, None);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(role: UserRole, name: UserId, passphrase: Option<String>) -> Self {
        Self {
            role,
            name,
            passphrase,
        }
    }

    /// Returns the name (a [`UserId`])
    pub fn get_name(&self) -> UserId {
        self.name.clone()
    }

    /// Returns the role (a [`UserRole`])
    pub fn get_role(&self) -> UserRole {
        self.role
    }

    /// Returns the passphrase of the [`ConfigCredentials`]
    pub fn get_passphrase(&self) -> Option<&str> {
        self.passphrase.as_deref()
    }

    /// Sets the passphrase of the [`ConfigCredentials`]
    pub fn set_passphrase(&mut self, passphrase: String) {
        self.passphrase = Some(passphrase)
    }

    /// Returns whether a passphrase is set for the [`ConfigCredentials`]
    pub fn has_passphrase(&self) -> bool {
        self.passphrase.is_some()
    }
}

impl From<ConfigCredentials> for Credentials {
    fn from(value: ConfigCredentials) -> Self {
        Self::new(value.name, value.passphrase.map(Passphrase::new))
    }
}

/// The name of a user on a Unix system
///
/// The username may only contain characters in the set of alphanumeric characters and the `'_'`
/// character.
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Serialize, Zeroize)]
#[serde(into = "String", try_from = "String")]
pub struct SystemUserId(String);

impl SystemUserId {
    /// Creates a new [`SystemUserId`]
    ///
    /// # Errors
    ///
    /// Returns an error if `user` contains chars other than alphanumeric ones, `-`, or `_`.
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm_config::SystemUserId;
    ///
    /// # fn main() -> testresult::TestResult {
    /// SystemUserId::new("user1".to_string())?;
    /// SystemUserId::new("User_1".to_string())?;
    /// assert!(SystemUserId::new("?ser-1".to_string()).is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(user: String) -> Result<Self, Error> {
        if user.is_empty()
            || !(user
                .chars()
                .all(|char| char.is_alphanumeric() || char == '_' || char == '-'))
        {
            return Err(Error::InvalidSystemUserName(user));
        }
        Ok(Self(user))
    }
}

impl AsRef<str> for SystemUserId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for SystemUserId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl From<SystemUserId> for String {
    fn from(value: SystemUserId) -> Self {
        value.to_string()
    }
}

impl FromStr for SystemUserId {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s.to_string())
    }
}

impl TryFrom<String> for SystemUserId {
    type Error = Error;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// An entry of an authorized_keys file
///
/// This type ensures compliance with SSH's [AuhtorizedKeysFile] format.
///
/// [AuhtorizedKeysFile]: https://man.archlinux.org/man/sshd.8#AUTHORIZED_KEYS_FILE_FORMAT
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Serialize, Zeroize)]
#[serde(into = "String", try_from = "String")]
pub struct AuthorizedKeyEntry(String);

impl AuthorizedKeyEntry {
    /// Creates a new [`AuthorizedKeyEntry`]
    ///
    /// # Errors
    ///
    /// Returns an error, if `data` can not be converted to an
    /// [`ssh_key::authorized_keys::Entry`].
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm_config::AuthorizedKeyEntry;
    ///
    /// # fn main() -> testresult::TestResult {
    /// AuthorizedKeyEntry::new("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".to_string())?;
    ///
    /// // this fails because the empty string is not a valid AuthorizedKeyEntry
    /// assert!(AuthorizedKeyEntry::new("".to_string()).is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(entry: String) -> Result<Self, Error> {
        if Entry::from_str(&entry).is_err() {
            return Err(Error::InvalidAuthorizedKeyEntry { entry });
        }

        Ok(Self(entry))
    }
}

impl AsRef<str> for AuthorizedKeyEntry {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for AuthorizedKeyEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl From<AuthorizedKeyEntry> for String {
    fn from(value: AuthorizedKeyEntry) -> Self {
        value.to_string()
    }
}

impl FromStr for AuthorizedKeyEntry {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s.to_string())
    }
}

impl TryFrom<&AuthorizedKeyEntry> for Entry {
    type Error = Error;

    fn try_from(value: &AuthorizedKeyEntry) -> Result<Self, Error> {
        Entry::from_str(&value.0).map_err(Error::SshKey)
    }
}

impl TryFrom<String> for AuthorizedKeyEntry {
    type Error = Error;

    fn try_from(value: String) -> Result<Self, Error> {
        Self::new(value)
    }
}

/// A list of [`AuthorizedKeyEntry`]s
///
/// The list is guaranteed to contain at least one item and be unique (no duplicate SSH public key
/// can exist).
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Serialize)]
#[serde(into = "Vec<String>", try_from = "Vec<String>")]
pub struct AuthorizedKeyEntryList(Vec<AuthorizedKeyEntry>);

impl AuthorizedKeyEntryList {
    /// Creates a new [`AuthorizedKeyEntryList`]
    ///
    /// # Errors
    ///
    /// Returns an error, if a duplicate SSH public key exists in the provided list of
    /// [`AuthorizedKeyEntry`] objects or if the list is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm_config::AuthorizedKeyEntryList;
    ///
    /// # fn main() -> testresult::TestResult {
    /// AuthorizedKeyEntryList::new(vec!["ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINP4nWGVLC7kq4EdwgnJTXCjN0l32GL9ZxII6mx9uGqV user@host".parse()?])?;
    ///
    /// // this fails because the AuthorizedKeyEntry are duplicates
    /// assert!(AuthorizedKeyEntryList::new(vec!["ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?]).is_err());
    ///
    /// // this fails because there are no SSH authorized keys
    /// assert!(AuthorizedKeyEntryList::new(vec![]).is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(ssh_authorized_keys: Vec<AuthorizedKeyEntry>) -> Result<Self, Error> {
        if ssh_authorized_keys.is_empty() {
            return Err(Error::NoAuthorizedKeys);
        }

        let mut set = HashSet::new();
        for (ssh_authorized_key, pub_key) in ssh_authorized_keys
            .iter()
            .filter_map(|ssh_authorized_key| {
                if let Ok(entry) = Entry::try_from(ssh_authorized_key) {
                    Some((ssh_authorized_key.clone(), entry.public_key().clone()))
                } else {
                    None
                }
            })
            .collect::<Vec<(AuthorizedKeyEntry, PublicKey)>>()
        {
            if !set.insert(pub_key) {
                return Err(Error::DuplicateAuthorizedKeys { ssh_authorized_key });
            }
        }

        Ok(Self(ssh_authorized_keys))
    }
}

impl AsRef<[AuthorizedKeyEntry]> for AuthorizedKeyEntryList {
    fn as_ref(&self) -> &[AuthorizedKeyEntry] {
        &self.0
    }
}

impl From<AuthorizedKeyEntryList> for Vec<String> {
    fn from(value: AuthorizedKeyEntryList) -> Self {
        value
            .0
            .iter()
            .map(|authorized_key| authorized_key.to_string())
            .collect()
    }
}

impl From<&AuthorizedKeyEntryList> for Vec<AuthorizedKeyEntry> {
    fn from(value: &AuthorizedKeyEntryList) -> Self {
        value.0.to_vec()
    }
}

impl TryFrom<Vec<String>> for AuthorizedKeyEntryList {
    type Error = Error;

    fn try_from(value: Vec<String>) -> Result<Self, Self::Error> {
        let authorized_keys = {
            let mut authorized_keys: Vec<AuthorizedKeyEntry> = vec![];
            for authorized_key in value {
                authorized_keys.push(AuthorizedKeyEntry::new(authorized_key)?)
            }
            authorized_keys
        };

        Self::new(authorized_keys)
    }
}

/// A guaranteed to be system-wide [`NetHsm`][`nethsm::NetHsm`] user
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(into = "String", try_from = "String")]
pub struct SystemWideUserId(UserId);

impl SystemWideUserId {
    /// Creates a new [`SystemWideUserId`] from an owned string
    ///
    /// # Errors
    ///
    /// Returns an error, if the provided `user_id` contains a namespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm_config::SystemWideUserId;
    ///
    /// # fn main() -> testresult::TestResult {
    /// SystemWideUserId::new("user1".to_string())?;
    ///
    /// // this fails because the User ID contains a namespace
    /// assert!(SystemWideUserId::new("ns1~user1".to_string()).is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(user_id: String) -> Result<Self, Error> {
        let user_id = UserId::new(user_id)?;
        if user_id.is_namespaced() {
            return Err(Error::SystemWideUserIdWithNamespace(user_id));
        }
        Ok(Self(user_id))
    }
}

impl Display for SystemWideUserId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl FromStr for SystemWideUserId {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s.to_string())
    }
}

impl From<SystemWideUserId> for String {
    fn from(value: SystemWideUserId) -> Self {
        value.to_string()
    }
}

impl From<SystemWideUserId> for UserId {
    fn from(value: SystemWideUserId) -> Self {
        value.0
    }
}

impl TryFrom<String> for SystemWideUserId {
    type Error = Error;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}