Skip to main content

signstar_config/config/file/
mod.rs

1//! Configuration file handling.
2
3#[cfg(all(feature = "nethsm", feature = "yubihsm2"))]
4pub mod impl_all;
5#[cfg(all(feature = "nethsm", not(feature = "yubihsm2")))]
6pub mod impl_nethsm;
7#[cfg(not(any(feature = "nethsm", feature = "yubihsm2")))]
8pub mod impl_none;
9#[cfg(all(feature = "yubihsm2", not(feature = "nethsm")))]
10pub mod impl_yubihsm2;
11
12#[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
13use std::collections::BTreeSet;
14use std::{
15    collections::HashSet,
16    fs::read_to_string,
17    path::{Path, PathBuf},
18    str::FromStr,
19};
20
21use garde::Validate;
22use log::info;
23#[cfg(feature = "nethsm")]
24use nethsm::Connection;
25use serde::{Deserialize, Serialize};
26use serde_saphyr::{ser_options, to_string_with_options};
27use signstar_common::backend::BackendType;
28#[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
29use signstar_crypto::{AdministrativeSecretHandling, NonAdministrativeSecretHandling};
30#[cfg(feature = "yubihsm2")]
31use signstar_yubihsm2::Connection as YubiHsm2Connection;
32use strum::{AsRefStr, VariantNames};
33
34#[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
35use crate::config::{ConfigAuthorizedKeyEntries, ConfigSystemUserIds};
36#[cfg(feature = "nethsm")]
37use crate::nethsm::{NetHsmConfig, NetHsmUserMapping};
38#[cfg(feature = "yubihsm2")]
39use crate::yubihsm2::{YubiHsm2Config, YubiHsm2UserMapping};
40use crate::{
41    config::{ConfigSystemUserData, Error, SystemConfig, SystemUserData},
42    state::{StateOrigin, StateOriginInfo},
43};
44
45/// Backend specific data for a user mapping.
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub enum UserBackendConnection {
48    /// The connection configuration for a user of a NetHSM backend.
49    ///
50    /// # Note
51    ///
52    /// Only supported when using the `nethsm` feature.
53    #[cfg(feature = "nethsm")]
54    NetHsm {
55        /// Administrative credentials handling.
56        admin_secret_handling: AdministrativeSecretHandling,
57
58        /// Non-administrative credentials handling.
59        non_admin_secret_handling: NonAdministrativeSecretHandling,
60
61        /// The available connections to the NetHSM backend.
62        connections: BTreeSet<Connection>,
63
64        /// A specific NetHSM user mapping.
65        mapping: NetHsmUserMapping,
66    },
67
68    /// The connection configuration for a user of a YubiHSM2 backend.
69    ///
70    /// # Note
71    ///
72    /// Only supported when using the `yubihsm2` feature.
73    #[cfg(feature = "yubihsm2")]
74    YubiHsm2 {
75        /// Administrative credentials handling.
76        admin_secret_handling: AdministrativeSecretHandling,
77
78        /// Non-administrative credentials handling.
79        non_admin_secret_handling: NonAdministrativeSecretHandling,
80
81        /// The available connections to the YubiHSM2 backend.
82        connections: BTreeSet<YubiHsm2Connection>,
83
84        /// A specific YubiHSM2 user mapping.
85        mapping: YubiHsm2UserMapping,
86    },
87}
88
89/// A filter for the retrieval of lists of [`UserBackendConnection`] from a [`Config`].
90#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
91pub enum UserBackendConnectionFilter {
92    /// Only target administrative backend users.
93    Admin,
94
95    /// Only target non-administrative backend users.
96    NonAdmin,
97
98    /// Only target a specific type of backend.
99    Backend(BackendType),
100}
101
102/// Validates overlapping assumptions of two configuration objects.
103///
104/// Ensures that `config_a` and `config_b` have no overlapping system user IDs or SSH
105/// authorized_keys.
106///
107/// # Errors
108///
109/// Returns an error if there are
110///
111/// - duplicate system users
112/// - duplicate SSH authorized keys (by comparing the actual SSH public keys)
113#[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
114fn validate_confs<T, U>(config_a: &T, config_b: &U) -> garde::Result
115where
116    T: ConfigAuthorizedKeyEntries + ConfigSystemUserIds,
117    U: ConfigAuthorizedKeyEntries + ConfigSystemUserIds,
118{
119    // Collect duplicate system user IDs.
120    let duplicate_system_user_ids = {
121        let system_config_user_ids = config_a.system_user_ids();
122        let config_user_ids = config_b.system_user_ids();
123        let duplicates = system_config_user_ids
124            .intersection(&config_user_ids)
125            .map(|system_user_id| system_user_id.to_string())
126            .collect::<HashSet<_>>();
127
128        if duplicates.is_empty() {
129            None
130        } else {
131            let mut duplicates = Vec::from_iter(duplicates);
132            duplicates.sort();
133            Some(format!(
134                "the duplicate system user ID{} {}",
135                if duplicates.len() > 1 { "s" } else { "" },
136                duplicates.join(", ")
137            ))
138        }
139    };
140
141    // Collect all duplicate SSH public keys in authorized_keys.
142    let duplicate_public_keys = {
143        let system_config_public_keys: HashSet<_> = config_a
144            .authorized_key_entries()
145            .iter()
146            .cloned()
147            .map(|authorized_key| authorized_key.as_ref().public_key())
148            .collect();
149        let config_public_keys: HashSet<_> = config_b
150            .authorized_key_entries()
151            .iter()
152            .cloned()
153            .map(|authorized_key| authorized_key.as_ref().public_key())
154            .collect();
155        let duplicates: HashSet<_> = system_config_public_keys
156            .intersection(&config_public_keys)
157            .cloned()
158            .map(|public_key| {
159                let mut public_key = public_key.clone();
160                // Unset the comment as it may be set to different values.
161                public_key.set_comment("");
162                format!("\"{}\"", public_key.to_string())
163            })
164            .collect();
165
166        if duplicates.is_empty() {
167            None
168        } else {
169            let mut duplicates = Vec::from_iter(duplicates);
170            duplicates.sort();
171            Some(format!(
172                "the duplicate SSH public key{} {}",
173                if duplicates.len() > 1 { "s" } else { "" },
174                duplicates.join(", ")
175            ))
176        }
177    };
178
179    let messages = [duplicate_system_user_ids, duplicate_public_keys];
180    let error_messages = {
181        let mut error_messages = Vec::new();
182
183        for message in messages.iter().flatten() {
184            error_messages.push(message.as_str());
185        }
186
187        error_messages
188    };
189
190    match error_messages.len() {
191        0 => Ok(()),
192        1 => Err(garde::Error::new(format!(
193            "contains {}",
194            error_messages.join("\n")
195        ))),
196        _ => Err(garde::Error::new(format!(
197            "contains multiple issues:\n⤷ {}",
198            error_messages.join("\n⤷ ")
199        ))),
200    }
201}
202
203/// Validates a required config object against an optional one.
204///
205/// Ensures that the the two configuration objects have no overlapping system user IDs or SSH
206/// authorized_keys.
207///
208/// # Errors
209///
210/// Returns an error if there are
211///
212/// - duplicate system users
213/// - duplicate SSH authorized keys (by comparing the actual SSH public keys)
214#[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
215fn validate_config_against_optional_config<T, U>(
216    config_a: &Option<T>,
217) -> impl FnOnce(&U, &()) -> garde::Result + '_
218where
219    T: ConfigAuthorizedKeyEntries + ConfigSystemUserIds,
220    U: ConfigAuthorizedKeyEntries + ConfigSystemUserIds,
221{
222    move |config_b, _| {
223        let Some(config_a) = config_a else {
224            return Ok(());
225        };
226
227        validate_confs(config_a, config_b)
228    }
229}
230
231/// Validates two optional config objects against each other.
232///
233/// Ensures that - if both config objects are present - they have no overlapping system user IDs or
234/// SSH authorized_keys.
235///
236/// # Errors
237///
238/// Returns an error if there are
239///
240/// - duplicate system users
241/// - duplicate SSH authorized keys (by comparing the actual SSH public keys)
242#[cfg(all(feature = "nethsm", feature = "yubihsm2"))]
243fn validate_two_optional_configs<T, U>(
244    backend_config_a: &Option<T>,
245) -> impl FnOnce(&Option<U>, &()) -> garde::Result + '_
246where
247    T: ConfigAuthorizedKeyEntries + ConfigSystemUserIds,
248    U: ConfigAuthorizedKeyEntries + ConfigSystemUserIds,
249{
250    move |backend_config_b, _| {
251        if let Some(backend_config_a) = backend_config_a
252            && let Some(backend_config_b) = backend_config_b
253        {
254            validate_confs(backend_config_a, backend_config_b)?;
255        }
256
257        Ok(())
258    }
259}
260
261/// The supported configuration file formats.
262#[derive(AsRefStr, Clone, Copy, Debug, Default, strum::Display, VariantNames)]
263#[strum(serialize_all = "lowercase")]
264enum ConfigFileFormat {
265    #[default]
266    Yaml,
267}
268
269/// The configuration of a Signstar system.
270///
271/// Tracks system-wide configuration items, as well as configurations for specific backends.
272#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize, Validate)]
273#[serde(rename_all = "snake_case")]
274pub struct Config {
275    /// System configuration object.
276    // Validate against NetHsmConfig if support is compiled in.
277    #[cfg_attr(
278        feature = "nethsm",
279        garde(custom(validate_config_against_optional_config(&self.nethsm)))
280    )]
281    // Validate against YubiHsm2Config if support is compiled in.
282    #[cfg_attr(
283        feature = "yubihsm2",
284        garde(custom(validate_config_against_optional_config(&self.yubihsm2)))
285    )]
286    #[garde(dive)]
287    system: SystemConfig,
288
289    /// Optional configuration object for NetHSM backends.
290    ///
291    /// # Note
292    ///
293    /// Only supported when using the `nethsm` feature.
294    #[cfg(feature = "nethsm")]
295    // Validate against YubiHsm2Config if support is compiled in.
296    #[cfg_attr(
297        all(feature = "nethsm", feature = "yubihsm2"),
298        garde(custom(validate_two_optional_configs(&self.yubihsm2)))
299    )]
300    #[garde(dive)]
301    #[serde(skip_serializing_if = "Option::is_none")]
302    nethsm: Option<NetHsmConfig>,
303
304    /// Optional configuration object for YubiHSM2 backends.
305    ///
306    /// # Note
307    ///
308    /// Only supported when using the `yubihsm2` feature.
309    #[cfg(feature = "yubihsm2")]
310    // Validate against NetHsmConfig if support is compiled in.
311    #[cfg_attr(
312        all(feature = "nethsm", feature = "yubihsm2"),
313        garde(custom(validate_two_optional_configs(&self.nethsm)))
314    )]
315    #[garde(dive)]
316    #[serde(skip_serializing_if = "Option::is_none")]
317    yubihsm2: Option<YubiHsm2Config>,
318}
319
320impl Config {
321    /// The default config directory below "/usr/".
322    pub const DEFAULT_CONFIG_DIR: &str = "/usr/share/signstar/";
323
324    /// The override config directory below "/run/".
325    pub const RUN_OVERRIDE_CONFIG_DIR: &str = "/run/signstar/";
326
327    /// The override config directory below "/etc/".
328    pub const ETC_OVERRIDE_CONFIG_DIR: &str = "/etc/signstar/";
329
330    /// The configuration file name (without file type suffix).
331    pub const CONFIG_NAME: &str = "config";
332
333    /// Returns the default location of the Signstar configuration file on a system.
334    pub fn default_system_path() -> PathBuf {
335        PathBuf::from(Self::DEFAULT_CONFIG_DIR).join(PathBuf::from(format!(
336            "{}.{}",
337            Self::CONFIG_NAME,
338            ConfigFileFormat::default()
339        )))
340    }
341
342    /// Returns the first found path of a Signstar configuratino on the system.
343    ///
344    /// # Errors
345    ///
346    /// Returns an error if no configuration file is found.
347    pub fn first_existing_system_path() -> Result<PathBuf, crate::Error> {
348        let path = Self::list_config_file_paths()
349            .into_iter()
350            .find(|path| path.is_file());
351        path.ok_or(Error::ConfigIsMissing.into())
352    }
353
354    /// Returns the list of supported directory paths in which configuration files may reside.
355    ///
356    /// The returned list of paths is sorted in increasing precedence.
357    pub fn list_config_dirs() -> Vec<PathBuf> {
358        [
359            Self::DEFAULT_CONFIG_DIR,
360            Self::RUN_OVERRIDE_CONFIG_DIR,
361            Self::ETC_OVERRIDE_CONFIG_DIR,
362        ]
363        .iter()
364        .map(PathBuf::from)
365        .collect()
366    }
367
368    /// Returns the list of supported configuration file paths.
369    ///
370    /// The returned list of paths is sorted in increasing precedence.
371    pub fn list_config_file_paths() -> Vec<PathBuf> {
372        Self::list_config_dirs()
373            .into_iter()
374            .map(|dir| {
375                dir.join(
376                    PathBuf::from(Self::CONFIG_NAME)
377                        .with_added_extension(ConfigFileFormat::default().as_ref()),
378                )
379            })
380            .collect()
381    }
382
383    /// Creates a new [`Config`] from a string slice containing YAML data.
384    ///
385    /// # Errors
386    ///
387    /// Returns an error if deserialization or validation fails.
388    fn from_yaml_str(s: &str) -> Result<Self, crate::Error> {
389        let config: Self = serde_saphyr::from_str(s).map_err(|source| Error::YamlDeserialize {
390            context: "creating a Signstar configuration object".to_string(),
391            source: Box::new(source),
392        })?;
393
394        config
395            .validate()
396            .map_err(|source| crate::Error::Validation {
397                context: "validating a Signstar configuration object".to_string(),
398                source,
399            })?;
400
401        Ok(config)
402    }
403
404    /// Creates a new [`Config`] from a file containing YAML data.
405    ///
406    /// # Errors
407    ///
408    /// Returns an error if
409    /// - the file does not exist
410    /// - deserialization or validation fails.
411    fn from_yaml_file(path: impl AsRef<Path>) -> Result<Self, crate::Error> {
412        let path = path.as_ref();
413        info!("Reading Signstar configuration file {path:?}");
414
415        let config_data = read_to_string(path).map_err(|source| crate::Error::IoPath {
416            path: path.to_path_buf(),
417            context: "reading it to string",
418            source,
419        })?;
420        Self::from_yaml_str(&config_data)
421    }
422
423    /// Creates a new [`Config`] from a file `path`.
424    ///
425    /// # Errors
426    ///
427    /// Returns an error if
428    ///
429    /// - `path` has no file extension
430    /// - `path` does not use one of the supported file extensions
431    /// - creating a [`Config`] from the data fails
432    /// - validating a [`Config`] created from the data fails
433    pub fn from_file_path(path: impl AsRef<Path>) -> Result<Self, crate::Error> {
434        let path = path.as_ref();
435        let extension = {
436            let Some(extension) = path.extension() else {
437                return Err(Error::MissingFileExtension {
438                    path: path.to_path_buf(),
439                }
440                .into());
441            };
442            extension.to_string_lossy().to_string()
443        };
444
445        if !ConfigFileFormat::VARIANTS.contains(&extension.as_ref()) {
446            return Err(Error::UnsupportedFileExtension {
447                path: path.to_path_buf(),
448                extension,
449            }
450            .into());
451        }
452
453        Self::from_yaml_file(path)
454    }
455
456    /// Creates a new [`Config`] from the first found Signstar configuration file path on the
457    /// system.
458    ///
459    /// # Note
460    ///
461    /// Uses [`Config::first_existing_system_path`] to determine the first existing Signstar
462    /// configuration file path.
463    ///
464    /// # Errors
465    ///
466    /// Returns an error if [`Config`] creation from the found path fails.
467    pub fn from_system_path() -> Result<Self, crate::Error> {
468        Self::from_yaml_file(Self::first_existing_system_path()?)
469    }
470
471    /// Serializes `self` as a YAML string.
472    ///
473    /// # Errors
474    ///
475    /// Returns an error if serialization fails.
476    pub fn to_yaml_string(&self) -> Result<String, crate::Error> {
477        let options = ser_options! {
478            compact_list_indent: false,
479            prefer_block_scalars: false,
480            indent_step: 2,
481        };
482
483        to_string_with_options(&self, options).map_err(|source| {
484            Error::YamlSerialize {
485                context: "serializing Signstar config",
486                source: Box::new(source),
487            }
488            .into()
489        })
490    }
491
492    /// Returns a reference to the [`SystemConfig`].
493    pub fn system(&self) -> &SystemConfig {
494        &self.system
495    }
496
497    /// Returns a reference to the [`NetHsmConfig`].
498    #[cfg(feature = "nethsm")]
499    pub fn nethsm(&self) -> Option<&NetHsmConfig> {
500        self.nethsm.as_ref()
501    }
502
503    /// Returns a reference to the [`YubiHsm2Config`].
504    #[cfg(feature = "yubihsm2")]
505    pub fn yubihsm2(&self) -> Option<&YubiHsm2Config> {
506        self.yubihsm2.as_ref()
507    }
508}
509
510impl FromStr for Config {
511    type Err = crate::Error;
512
513    /// Creates a new [`Config`] from a string slice containing valid YAML.
514    ///
515    /// # Errors
516    ///
517    /// Returns an error if no [`Config`] can be created from `s`.
518    fn from_str(s: &str) -> Result<Self, Self::Err> {
519        Config::from_yaml_str(s)
520    }
521}
522
523/// A builder for [`Config`].
524#[derive(Clone, Debug)]
525pub struct ConfigBuilder(Config);
526
527impl ConfigBuilder {
528    /// Adds a [`NetHsmConfig`] to the builder.
529    #[cfg(feature = "nethsm")]
530    pub fn set_nethsm_config(mut self, nethsm: NetHsmConfig) -> Self {
531        self.0.nethsm = Some(nethsm);
532        self
533    }
534
535    /// Adds a [`YubiHsm2Config`] to the builder.
536    #[cfg(feature = "yubihsm2")]
537    pub fn set_yubihsm2_config(mut self, yubihsm2: YubiHsm2Config) -> Self {
538        self.0.yubihsm2 = Some(yubihsm2);
539        self
540    }
541
542    /// Creates a [`Config`] from the builder.
543    ///
544    /// # Errors
545    ///
546    /// Returns an error if validation for the [`Config`] fails.
547    pub fn finish(self) -> Result<Config, crate::Error> {
548        self.0
549            .validate()
550            .map_err(|source| crate::Error::Validation {
551                context: "validating a configuration object".to_string(),
552                source,
553            })?;
554
555        Ok(self.0)
556    }
557}
558
559/// The state of system users according to a Signstar configuration.
560#[derive(Clone, Debug, Eq, PartialEq)]
561pub struct SystemUserConfigState<'a> {
562    pub(crate) system_user_data: HashSet<SystemUserData<'a>>,
563}
564
565impl<'a> SystemUserConfigState<'a> {
566    /// The name of the origin for the state.
567    pub const STATE_NAME: &'static str = "config";
568}
569
570impl<'a> From<&'a Config> for SystemUserConfigState<'a> {
571    fn from(value: &'a Config) -> Self {
572        Self {
573            system_user_data: value.system_user_data(),
574        }
575    }
576}
577
578impl<'a> StateOriginInfo for SystemUserConfigState<'a> {
579    fn state_name(&self) -> &str {
580        Self::STATE_NAME
581    }
582
583    fn state_origin(&self) -> StateOrigin {
584        StateOrigin::Config
585    }
586}
587
588#[cfg(test)]
589mod tests {
590    use std::{collections::BTreeSet, num::NonZeroUsize, thread::current};
591
592    use insta::{assert_snapshot, with_settings};
593    #[cfg(feature = "nethsm")]
594    use nethsm::ConnectionSecurity;
595    use pretty_assertions::assert_eq;
596    use rstest::{fixture, rstest};
597    use signstar_crypto::{AdministrativeSecretHandling, NonAdministrativeSecretHandling};
598    #[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
599    use signstar_crypto::{
600        key::{CryptographicKeyContext, KeyMechanism, KeyType, SignatureType, SigningKeySetup},
601        openpgp::OpenPgpUserIdList,
602    };
603    #[cfg(feature = "yubihsm2")]
604    use signstar_yubihsm2::object::Domain;
605    use tempfile::{NamedTempFile, TempDir};
606    use testresult::TestResult;
607
608    use super::*;
609    use crate::config::{AuthorizedKeyEntry, SystemUserId, SystemUserMapping};
610    #[cfg(feature = "nethsm")]
611    use crate::nethsm::NetHsmMetricsUsers;
612
613    const SNAPSHOT_PATH: &str = "fixtures/file/";
614
615    /// Creates a default [`SystemConfig`] for testing purposes.
616    #[fixture]
617    fn default_system_config() -> TestResult<SystemConfig> {
618        Ok(SystemConfig::new(
619            1,
620            AdministrativeSecretHandling::ShamirsSecretSharing {
621                number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
622                threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
623            },
624            NonAdministrativeSecretHandling::SystemdCreds,
625            BTreeSet::from_iter([
626                SystemUserMapping::ShareHolder {
627                    system_user: "signstar-share-holder1".parse()?,
628                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAN54Gd1jMz+yNDjBRwX1SnOtWuUsVF64RJIeYJ8DI7b user@host".parse()?,
629                },
630                SystemUserMapping::ShareHolder {
631                    system_user: "signstar-share-holder2".parse()?,
632                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
633                },
634                SystemUserMapping::ShareHolder {
635                    system_user: "signstar-share-holder3".parse()?,
636                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?
637                },
638                SystemUserMapping::WireguardDownload {
639                    system_user: "signstar-wireguard-download".parse()?,
640                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh9BTe81DC6A0YZALsq9dWcyl6xjjqlxWPwlExTFgBt user@host".parse()?,
641                },
642            ]),
643        )?)
644    }
645
646    /// List of raw data required to create [`SystemUserData`] for each item in the default
647    /// [`SystemConfig`].
648    #[fixture]
649    fn raw_user_data_system() -> TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>> {
650        Ok(vec![
651                (
652                    "signstar-share-holder1".parse()?,
653                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAN54Gd1jMz+yNDjBRwX1SnOtWuUsVF64RJIeYJ8DI7b user@host".parse()?),
654                ),
655                (
656                    "signstar-share-holder2".parse()?,
657                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?),
658                ),
659                (
660                    "signstar-share-holder3".parse()?,
661                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?),
662                ),
663                (
664                    "signstar-wireguard-download".parse()?,
665                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh9BTe81DC6A0YZALsq9dWcyl6xjjqlxWPwlExTFgBt user@host".parse()?),
666                ),
667            ])
668    }
669
670    /// Creates a default [`NetHsmConfig`] for testing purposes.
671    #[cfg(feature = "nethsm")]
672    #[fixture]
673    fn default_nethsm_config() -> TestResult<NetHsmConfig> {
674        Ok(NetHsmConfig::new(
675            BTreeSet::from_iter([
676                Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
677                Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
678            ]),
679            BTreeSet::from_iter([
680                NetHsmUserMapping::Admin("admin".parse()?),
681                NetHsmUserMapping::Backup{
682                    backend_user: "backup".parse()?,
683                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
684                    system_user: "nethsm-backup".parse()?,
685                },
686                NetHsmUserMapping::HermeticMetrics {
687                    backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
688                    system_user: "nethsm-hermetic-metrics".parse()?,
689                },
690                NetHsmUserMapping::Metrics {
691                    backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
692                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
693                    system_user: "nethsm-metrics".parse()?,
694                },
695                NetHsmUserMapping::Signing {
696                    backend_user: "signing".parse()?,
697                    signing_key_id: "signing1".parse()?,
698                    key_setup: SigningKeySetup::new(
699                        KeyType::Curve25519,
700                        vec![KeyMechanism::EdDsaSignature],
701                        None,
702                        SignatureType::EdDsa,
703                        CryptographicKeyContext::OpenPgp {
704                            user_ids: OpenPgpUserIdList::new(vec![
705                                "Foobar McFooface <foobar@mcfooface.org>".parse()?,
706                            ])?,
707                            version: "v4".parse()?,
708                            notations: Default::default(),
709                        },
710                    )?,
711                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
712                    system_user: "nethsm-signing".parse()?,
713                    tag: "signing1".to_string(),
714                }
715            ]),
716        )?)
717    }
718
719    /// List of raw data required to create [`SystemUserData`] for each item in the default
720    /// [`NetHsmConfig`].
721    #[cfg(feature = "nethsm")]
722    #[fixture]
723    fn raw_user_data_nethsm() -> TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>> {
724        Ok(vec![
725                (
726                    SystemUserId::root(),
727                    None,
728                ),
729                (
730                    "nethsm-backup".parse()?,
731                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?),
732                ),
733                (
734                    "nethsm-hermetic-metrics".parse()?,
735                    None,
736                ),
737                (
738                    "nethsm-metrics".parse()?,
739                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?),
740                ),
741                (
742                    "nethsm-signing".parse()?,
743                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?),
744                ),
745            ])
746    }
747
748    /// Creates a default [`YubiHsm2Config`] for testing purposes.
749    #[cfg(feature = "yubihsm2")]
750    #[fixture]
751    fn default_yubihsm2_config() -> TestResult<YubiHsm2Config> {
752        Ok(YubiHsm2Config::new(
753            BTreeSet::from_iter([
754                YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
755                YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
756            ]),
757            BTreeSet::from_iter([
758                YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
759                YubiHsm2UserMapping::AuditLog {
760                    authentication_key_id: "3".parse()?,
761                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
762                    system_user: "yubihsm2-audit-log".parse()?,
763                },
764                YubiHsm2UserMapping::Backup{
765                    authentication_key_id: "2".parse()?,
766                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
767                    system_user: "yubihsm2-backup".parse()?,
768                },
769                YubiHsm2UserMapping::HermeticAuditLog {
770                    authentication_key_id: "4".parse()?,
771                    system_user: "yubihsm2-hermetic-audit-log".parse()?,
772                },
773                YubiHsm2UserMapping::Signing {
774                    authentication_key_id: "5".parse()?,
775                    signing_key_id: "1".parse()?,
776                    key_setup: SigningKeySetup::new(
777                        KeyType::Curve25519,
778                        vec![KeyMechanism::EdDsaSignature],
779                        None,
780                        SignatureType::EdDsa,
781                        CryptographicKeyContext::OpenPgp {
782                            user_ids: OpenPgpUserIdList::new(vec![
783                                "Foobar McFooface <foobar@mcfooface.org>".parse()?,
784                            ])?,
785                            version: "v4".parse()?,
786                            notations: Default::default(),
787                        },
788                    )?,
789                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
790                    system_user: "yubihsm2-signing".parse()?,
791                    domain: Domain::One,
792                }
793            ]),
794        )?)
795    }
796
797    /// List of raw data required to create [`SystemUserData`] for each item in the default
798    /// [`YubiHsm2Config`].
799    #[cfg(feature = "yubihsm2")]
800    #[fixture]
801    fn raw_user_data_yubihsm2() -> TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>> {
802        Ok(vec![
803                (
804                    SystemUserId::root(),
805                    None,
806                ),
807                (
808                    "yubihsm2-audit-log".parse()?,
809                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?),
810                ),
811                (
812                    "yubihsm2-backup".parse()?,
813                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?),
814                ),
815                (
816                    "yubihsm2-hermetic-audit-log".parse()?,
817                    None,
818                ),
819                (
820                    "yubihsm2-signing".parse()?,
821                    Some("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?),
822                ),
823            ])
824    }
825
826    /// Ensures, that [`Config::default_system_path`] always returns the same path.
827    #[test]
828    fn config_default_system_path() {
829        assert_eq!(
830            Config::default_system_path(),
831            PathBuf::from("/usr/share/signstar/config.yaml")
832        )
833    }
834
835    /// Ensures, that [`Config::list_config_file_paths`] always returns the same list of paths.
836    #[test]
837    fn config_list_config_file_paths() {
838        assert_eq!(
839            Config::list_config_file_paths(),
840            vec![
841                PathBuf::from("/usr/share/signstar/config.yaml"),
842                PathBuf::from("/run/signstar/config.yaml"),
843                PathBuf::from("/etc/signstar/config.yaml"),
844            ]
845        )
846    }
847
848    /// Ensures, that [`Config::from_file_path`] fails on missing file extensions.
849    #[rstest]
850    fn config_from_file_path_fails_on_missing_file_extension() -> TestResult {
851        let temp_dir = TempDir::new()?;
852
853        match Config::from_file_path(temp_dir.path().join("config")) {
854            Ok(config) => panic!(
855                "Should have failed to create a Config object, but succeeded instead: {config:?}"
856            ),
857            Err(crate::Error::Config(Error::MissingFileExtension { .. })) => {}
858            Err(error) => panic!(
859                "Should have failed with a ConfigError::MissingFileExtension, but failed with a different error instead: {error}"
860            ),
861        }
862
863        Ok(())
864    }
865
866    /// Ensures, that [`Config::from_file_path`] fails on unsupported file extensions.
867    #[rstest]
868    fn config_from_file_path_fails_on_unsupported_file_extension() -> TestResult {
869        let temp_file = NamedTempFile::with_suffix(".toml")?;
870
871        match Config::from_file_path(temp_file.path()) {
872            Ok(config) => panic!(
873                "Should have failed to create a Config object, but succeeded instead: {config:?}"
874            ),
875            Err(crate::Error::Config(Error::UnsupportedFileExtension { .. })) => {}
876            Err(error) => panic!(
877                "Should have failed with a ConfigError::UnsupportedFileExtension, but failed with a different error instead: {error}"
878            ),
879        }
880
881        Ok(())
882    }
883
884    /// Tests, that are only available when using no backend.
885    #[cfg(not(any(feature = "nethsm", feature = "yubihsm2")))]
886    mod no_backend {
887        use std::collections::HashSet;
888
889        use pretty_assertions::assert_eq;
890
891        use super::*;
892        use crate::config::{
893            ConfigAuthorizedKeyEntries,
894            ConfigSystemUserIds,
895            SystemUserData,
896            traits::ConfigSystemUserData,
897        };
898
899        /// Creates a default [`Config`] for testing purposes.
900        #[fixture]
901        fn default_config(default_system_config: TestResult<SystemConfig>) -> TestResult<Config> {
902            Ok(ConfigBuilder::new(default_system_config?).finish()?)
903        }
904
905        /// Create a [`Config`] using [`ConfigBuilder`].
906        #[rstest]
907        fn config_builder_new(default_system_config: TestResult<SystemConfig>) -> TestResult {
908            let _config = ConfigBuilder::new(default_system_config?).finish()?;
909
910            Ok(())
911        }
912
913        /// Ensures that a reference to the [`SystemConfig`] can be retrieved from [`Config`].
914        #[rstest]
915        fn config_system(default_system_config: TestResult<SystemConfig>) -> TestResult {
916            let system_config = default_system_config?;
917            let config = ConfigBuilder::new(system_config.clone()).finish()?;
918            assert_eq!(config.system(), &system_config);
919
920            Ok(())
921        }
922
923        /// Ensures, that a [`Config`] object leads to a specific YAML output.
924        ///
925        /// In this particular case, only a [`SystemConfig`] object are present.
926        #[rstest]
927        fn config_to_yaml_string(default_system_config: TestResult<SystemConfig>) -> TestResult {
928            let config = ConfigBuilder::new(default_system_config?).finish()?;
929            let config_str = config.to_yaml_string()?;
930
931            with_settings!({
932                description => "Configuration with only system-wide configuration",
933                snapshot_path => SNAPSHOT_PATH,
934                prepend_module_to_snapshot => false,
935            }, {
936                assert_snapshot!(current().name().expect("current thread should have a name").to_string().replace("::", "__"), config_str);
937            });
938
939            Ok(())
940        }
941
942        /// Ensures, that a valid [`Config`] can be created from a YAML file and turned back into
943        /// the same YAML string.
944        ///
945        /// The configuration file only describes a [`SystemConfig`] object.
946        #[rstest]
947        fn roundtrip_yaml_config(
948            #[files("../fixtures/config/no_backend/*.yaml")] path: PathBuf,
949        ) -> TestResult {
950            let config_string = read_to_string(&path)?;
951            let config = Config::from_file_path(&path)?;
952
953            assert_eq!(config.to_yaml_string()?, config_string);
954
955            Ok(())
956        }
957
958        /// Ensures, that [`Config::authorized_key_entries`] returns SSH authorized key entries
959        /// correctly.
960        #[rstest]
961        fn config_authorized_key_entries(default_config: TestResult<Config>) -> TestResult {
962            let config = default_config?;
963            let expected: HashSet<AuthorizedKeyEntry> = HashSet::from_iter([
964                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAN54Gd1jMz+yNDjBRwX1SnOtWuUsVF64RJIeYJ8DI7b user@host".parse()?,
965                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
966                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
967                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh9BTe81DC6A0YZALsq9dWcyl6xjjqlxWPwlExTFgBt user@host".parse()?,
968            ]);
969
970            assert_eq!(
971                config.authorized_key_entries(),
972                expected.iter().collect::<HashSet<_>>()
973            );
974            Ok(())
975        }
976
977        /// Ensures, that [`Config::system_user_data`] returns [`SystemUserData`] entries correctly.
978        #[rstest]
979        fn config_system_user_data(
980            default_config: TestResult<Config>,
981            raw_user_data_system: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
982        ) -> TestResult {
983            let config = default_config?;
984            let raw_user_data = raw_user_data_system?;
985            let expected: HashSet<SystemUserData> = HashSet::from_iter([
986                SystemUserData::HostShareholder {
987                    system_user: &raw_user_data[0].0,
988                    ssh_authorized_key: raw_user_data[0]
989                        .1
990                        .as_ref()
991                        .expect("to have SSH authorized key"),
992                },
993                SystemUserData::HostShareholder {
994                    system_user: &raw_user_data[1].0,
995                    ssh_authorized_key: raw_user_data[1]
996                        .1
997                        .as_ref()
998                        .expect("to have SSH authorized key"),
999                },
1000                SystemUserData::HostShareholder {
1001                    system_user: &raw_user_data[2].0,
1002                    ssh_authorized_key: raw_user_data[2]
1003                        .1
1004                        .as_ref()
1005                        .expect("to have SSH authorized key"),
1006                },
1007                SystemUserData::HostDownloadNetworkConfig {
1008                    system_user: &raw_user_data[3].0,
1009                    ssh_authorized_key: raw_user_data[3]
1010                        .1
1011                        .as_ref()
1012                        .expect("to have SSH authorized key"),
1013                },
1014            ]);
1015
1016            assert_eq!(config.system_user_data(), expected);
1017            Ok(())
1018        }
1019
1020        /// Ensures, that [`Config::system_user_ids`] returns system user IDs correctly.
1021        #[rstest]
1022        fn config_system_user_ids(default_config: TestResult<Config>) -> TestResult {
1023            let config = default_config?;
1024            let expected: HashSet<SystemUserId> = HashSet::from_iter([
1025                "signstar-share-holder1".parse()?,
1026                "signstar-share-holder2".parse()?,
1027                "signstar-share-holder3".parse()?,
1028                "signstar-wireguard-download".parse()?,
1029            ]);
1030
1031            assert_eq!(
1032                config.system_user_ids(),
1033                expected.iter().collect::<HashSet<_>>()
1034            );
1035            Ok(())
1036        }
1037
1038        /// Ensures, that [`SystemUserConfigState`] can be created from [`Config`].
1039        #[rstest]
1040        fn system_user_config_state_from_config(default_config: TestResult<Config>) -> TestResult {
1041            let config = default_config?;
1042            let state = SystemUserConfigState::from(&config);
1043
1044            assert_eq!(state.system_user_data, config.system_user_data(),);
1045            Ok(())
1046        }
1047    }
1048
1049    /// Tests, that are only available when using the NetHSM (and no other) backend.
1050    #[cfg(all(feature = "nethsm", not(feature = "yubihsm2")))]
1051    mod nethsm_backend {
1052        use pretty_assertions::assert_eq;
1053
1054        use super::*;
1055        use crate::config::{
1056            SystemUserData,
1057            traits::{ConfigSystemUserData, MappingAuthorizedKeyEntry, MappingSystemUserId},
1058        };
1059
1060        /// Creates a default [`Config`] for testing purposes.
1061        #[fixture]
1062        fn default_config(
1063            default_system_config: TestResult<SystemConfig>,
1064            default_nethsm_config: TestResult<NetHsmConfig>,
1065        ) -> TestResult<Config> {
1066            Ok(ConfigBuilder::new(default_system_config?)
1067                .set_nethsm_config(default_nethsm_config?)
1068                .finish()?)
1069        }
1070
1071        /// List of raw data required to create [`SystemUserData`] for each item in the default
1072        /// [`Config`].
1073        #[fixture]
1074        fn raw_user_data(
1075            raw_user_data_system: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1076            raw_user_data_nethsm: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1077        ) -> TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>> {
1078            let mut data = raw_user_data_system?;
1079            data.extend(raw_user_data_nethsm?);
1080            Ok(data)
1081        }
1082
1083        /// Ensures that [`MappingSystemUserId`] for [`UserBackendConnection`] works as intended.
1084        #[rstest]
1085        fn user_backend_connection_system_user_id(
1086            raw_user_data_nethsm: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1087        ) -> TestResult {
1088            let raw_user_data_nethsm = raw_user_data_nethsm?;
1089            let data = UserBackendConnection::NetHsm {
1090                admin_secret_handling: AdministrativeSecretHandling::Plaintext,
1091                non_admin_secret_handling: NonAdministrativeSecretHandling::Plaintext,
1092                connections: BTreeSet::from_iter([Connection::new(
1093                    "https://nethsm1.example.org/".parse()?,
1094                    ConnectionSecurity::Unsafe,
1095                )]),
1096                mapping: NetHsmUserMapping::Backup {
1097                    backend_user: "backup".parse()?,
1098                    ssh_authorized_key: raw_user_data_nethsm[1]
1099                        .1
1100                        .clone()
1101                        .expect("to have an SSH authorized key"),
1102                    system_user: raw_user_data_nethsm[1].0.clone(),
1103                },
1104            };
1105            assert_eq!(data.system_user_id(), Some(&raw_user_data_nethsm[1].0));
1106
1107            Ok(())
1108        }
1109
1110        /// Ensures that [`MappingAuthorizedKeyEntry`] for [`UserBackendConnection`] works as
1111        /// intended.
1112        #[rstest]
1113        fn user_backend_connection_authorized_key_entry(
1114            raw_user_data_nethsm: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1115        ) -> TestResult {
1116            let raw_user_data_nethsm = raw_user_data_nethsm?;
1117            let data = UserBackendConnection::NetHsm {
1118                admin_secret_handling: AdministrativeSecretHandling::Plaintext,
1119                non_admin_secret_handling: NonAdministrativeSecretHandling::Plaintext,
1120                connections: BTreeSet::from_iter([Connection::new(
1121                    "https://nethsm1.example.org/".parse()?,
1122                    ConnectionSecurity::Unsafe,
1123                )]),
1124                mapping: NetHsmUserMapping::Backup {
1125                    backend_user: "backup".parse()?,
1126                    ssh_authorized_key: raw_user_data_nethsm[1]
1127                        .1
1128                        .clone()
1129                        .expect("to have an SSH authorized key"),
1130                    system_user: raw_user_data_nethsm[1].0.clone(),
1131                },
1132            };
1133            assert_eq!(
1134                data.authorized_key_entry(),
1135                Some(
1136                    raw_user_data_nethsm[1]
1137                        .1
1138                        .as_ref()
1139                        .expect("to have an SSH authorized key")
1140                )
1141            );
1142
1143            Ok(())
1144        }
1145
1146        /// Ensures, that [`ConfigBuilder::finish`] fails on issues with overlapping data in
1147        /// configuration components.
1148        ///
1149        /// Here, a custom [`NetHsmConfig`] is staged together with a default [`SystemConfig`]
1150        /// (created by [`default_system_config`]) to create a failure scenario.
1151        #[rstest]
1152        #[case::two_duplicate_system_users_two_duplicate_ssh_public_keys(
1153            "Configuration with system-wide and NetHSM configuration has two duplicate system users and two duplicate SSH public keys",
1154            NetHsmConfig::new(
1155                BTreeSet::from_iter([
1156                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1157                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1158                ]),
1159                BTreeSet::from_iter([
1160                    NetHsmUserMapping::Admin("admin".parse()?),
1161                    NetHsmUserMapping::Backup{
1162                        backend_user: "backup".parse()?,
1163                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
1164                        system_user: "signstar-share-holder1".parse()?,
1165                    },
1166                    NetHsmUserMapping::HermeticMetrics {
1167                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
1168                        system_user: "nethsm-hermetic-metrics".parse()?,
1169                    },
1170                    NetHsmUserMapping::Metrics {
1171                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
1172                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
1173                        system_user: "signstar-share-holder2".parse()?,
1174                    },
1175                    NetHsmUserMapping::Signing {
1176                        backend_user: "signing".parse()?,
1177                        signing_key_id: "signing1".parse()?,
1178                        key_setup: SigningKeySetup::new(
1179                            KeyType::Curve25519,
1180                            vec![KeyMechanism::EdDsaSignature],
1181                            None,
1182                            SignatureType::EdDsa,
1183                            CryptographicKeyContext::OpenPgp {
1184                                user_ids: OpenPgpUserIdList::new(vec![
1185                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
1186                                ])?,
1187                                notations: Default::default(),
1188                                version: "v4".parse()?,
1189                            },
1190                        )?,
1191                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
1192                        system_user: "nethsm-signing".parse()?,
1193                        tag: "signing1".to_string(),
1194                    }
1195                ]),
1196            )?
1197        )]
1198        #[case::one_duplicate_system_user_two_duplicate_ssh_public_keys(
1199            "Configuration with system-wide and NetHSM configuration has one duplicate system user and two duplicate SSH public keys",
1200            NetHsmConfig::new(
1201                BTreeSet::from_iter([
1202                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1203                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1204                ]),
1205                BTreeSet::from_iter([
1206                    NetHsmUserMapping::Admin("admin".parse()?),
1207                    NetHsmUserMapping::Backup{
1208                        backend_user: "backup".parse()?,
1209                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
1210                        system_user: "signstar-share-holder1".parse()?,
1211                    },
1212                    NetHsmUserMapping::HermeticMetrics {
1213                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
1214                        system_user: "nethsm-hermetic-metrics".parse()?,
1215                    },
1216                    NetHsmUserMapping::Metrics {
1217                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
1218                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
1219                        system_user: "nethsm-metrics".parse()?,
1220                    },
1221                    NetHsmUserMapping::Signing {
1222                        backend_user: "signing".parse()?,
1223                        signing_key_id: "signing1".parse()?,
1224                        key_setup: SigningKeySetup::new(
1225                            KeyType::Curve25519,
1226                            vec![KeyMechanism::EdDsaSignature],
1227                            None,
1228                            SignatureType::EdDsa,
1229                            CryptographicKeyContext::OpenPgp {
1230                                user_ids: OpenPgpUserIdList::new(vec![
1231                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
1232                                ])?,
1233                                notations: Default::default(),
1234                                version: "v4".parse()?,
1235                            },
1236                        )?,
1237                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
1238                        system_user: "nethsm-signing".parse()?,
1239                        tag: "signing1".to_string(),
1240                    }
1241                ]),
1242            )?
1243        )]
1244        #[case::one_duplicate_system_user_one_duplicate_ssh_public_key(
1245            "Configuration with system-wide and NetHSM configuration has one duplicate system user and one duplicate SSH public key",
1246            NetHsmConfig::new(
1247                BTreeSet::from_iter([
1248                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1249                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1250                ]),
1251                BTreeSet::from_iter([
1252                    NetHsmUserMapping::Admin("admin".parse()?),
1253                    NetHsmUserMapping::Backup{
1254                        backend_user: "backup".parse()?,
1255                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
1256                        system_user: "signstar-share-holder1".parse()?,
1257                    },
1258                    NetHsmUserMapping::HermeticMetrics {
1259                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
1260                        system_user: "nethsm-hermetic-metrics".parse()?,
1261                    },
1262                    NetHsmUserMapping::Metrics {
1263                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
1264                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
1265                        system_user: "nethsm-metrics".parse()?,
1266                    },
1267                    NetHsmUserMapping::Signing {
1268                        backend_user: "signing".parse()?,
1269                        signing_key_id: "signing1".parse()?,
1270                        key_setup: SigningKeySetup::new(
1271                            KeyType::Curve25519,
1272                            vec![KeyMechanism::EdDsaSignature],
1273                            None,
1274                            SignatureType::EdDsa,
1275                            CryptographicKeyContext::OpenPgp {
1276                                user_ids: OpenPgpUserIdList::new(vec![
1277                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
1278                                ])?,
1279                                notations: Default::default(),
1280                                version: "v4".parse()?,
1281                            },
1282                        )?,
1283                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
1284                        system_user: "nethsm-signing".parse()?,
1285                        tag: "signing1".to_string(),
1286                    }
1287                ]),
1288            )?
1289        )]
1290        #[case::one_duplicate_ssh_public_key(
1291            "Configuration with system-wide and NetHSM configuration has one duplicate SSH public key",
1292            NetHsmConfig::new(
1293                BTreeSet::from_iter([
1294                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1295                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1296                ]),
1297                BTreeSet::from_iter([
1298                    NetHsmUserMapping::Admin("admin".parse()?),
1299                    NetHsmUserMapping::Backup{
1300                        backend_user: "backup".parse()?,
1301                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
1302                        system_user: "nethsm-backup".parse()?,
1303                    },
1304                    NetHsmUserMapping::HermeticMetrics {
1305                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
1306                        system_user: "nethsm-hermetic-metrics".parse()?,
1307                    },
1308                    NetHsmUserMapping::Metrics {
1309                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
1310                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
1311                        system_user: "nethsm-metrics".parse()?,
1312                    },
1313                    NetHsmUserMapping::Signing {
1314                        backend_user: "signing".parse()?,
1315                        signing_key_id: "signing1".parse()?,
1316                        key_setup: SigningKeySetup::new(
1317                            KeyType::Curve25519,
1318                            vec![KeyMechanism::EdDsaSignature],
1319                            None,
1320                            SignatureType::EdDsa,
1321                            CryptographicKeyContext::OpenPgp {
1322                                user_ids: OpenPgpUserIdList::new(vec![
1323                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
1324                                ])?,
1325                                notations: Default::default(),
1326                                version: "v4".parse()?,
1327                            },
1328                        )?,
1329                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
1330                        system_user: "nethsm-signing".parse()?,
1331                        tag: "signing1".to_string(),
1332                    }
1333                ]),
1334            )?
1335        )]
1336        #[case::one_duplicate_system_user(
1337            "Configuration with system-wide and NetHSM configuration has one duplicate system user",
1338            NetHsmConfig::new(
1339                BTreeSet::from_iter([
1340                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1341                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1342                ]),
1343                BTreeSet::from_iter([
1344                    NetHsmUserMapping::Admin("admin".parse()?),
1345                    NetHsmUserMapping::Backup{
1346                        backend_user: "backup".parse()?,
1347                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
1348                        system_user: "signstar-share-holder1".parse()?,
1349                    },
1350                    NetHsmUserMapping::HermeticMetrics {
1351                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
1352                        system_user: "nethsm-hermetic-metrics".parse()?,
1353                    },
1354                    NetHsmUserMapping::Metrics {
1355                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
1356                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
1357                        system_user: "nethsm-metrics".parse()?,
1358                    },
1359                    NetHsmUserMapping::Signing {
1360                        backend_user: "signing".parse()?,
1361                        signing_key_id: "signing1".parse()?,
1362                        key_setup: SigningKeySetup::new(
1363                            KeyType::Curve25519,
1364                            vec![KeyMechanism::EdDsaSignature],
1365                            None,
1366                            SignatureType::EdDsa,
1367                            CryptographicKeyContext::OpenPgp {
1368                                user_ids: OpenPgpUserIdList::new(vec![
1369                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
1370                                ])?,
1371                                notations: Default::default(),
1372                                version: "v4".parse()?,
1373                            },
1374                        )?,
1375                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
1376                        system_user: "nethsm-signing".parse()?,
1377                        tag: "signing1".to_string(),
1378                    }
1379                ]),
1380            )?
1381        )]
1382        fn config_builder_fails_validation(
1383            default_system_config: TestResult<SystemConfig>,
1384            #[case] description: &str,
1385            #[case] nethsm_config: NetHsmConfig,
1386        ) -> TestResult {
1387            let error_message = match ConfigBuilder::new(default_system_config?)
1388                .set_nethsm_config(nethsm_config)
1389                .finish()
1390            {
1391                Err(error) => error.to_string(),
1392                Ok(config) => panic!(
1393                    "Expected to fail with Error::Validation, but succeeded instead: {}",
1394                    config.to_yaml_string()?
1395                ),
1396            };
1397
1398            with_settings!({
1399                description => description,
1400                snapshot_path => SNAPSHOT_PATH,
1401                prepend_module_to_snapshot => false,
1402            }, {
1403                assert_snapshot!(current().name().expect("current thread should have a name").to_string().replace("::", "__"), error_message);
1404            });
1405
1406            Ok(())
1407        }
1408
1409        /// Ensures, that [`Config::nethsm`] returns the original input.
1410        #[rstest]
1411        fn config_nethsm(
1412            default_system_config: TestResult<SystemConfig>,
1413            default_nethsm_config: TestResult<NetHsmConfig>,
1414        ) -> TestResult {
1415            let nethsm_config = default_nethsm_config?;
1416
1417            let config = ConfigBuilder::new(default_system_config?)
1418                .set_nethsm_config(nethsm_config.clone())
1419                .finish()?;
1420
1421            assert_eq!(
1422                &nethsm_config,
1423                config.nethsm().expect("a NetHsmConfig reference")
1424            );
1425
1426            Ok(())
1427        }
1428
1429        /// Ensures, that an optional [`UserBackendConnection`] can be retrieved from a [`Config`].
1430        #[rstest]
1431        #[case::nethsm_signing(
1432            "nethsm-signing",
1433            Some(UserBackendConnection::NetHsm {
1434                admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1435                    number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1436                    threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1437                },
1438                non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1439                connections: BTreeSet::from_iter([
1440                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1441                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1442                ]),
1443                mapping: NetHsmUserMapping::Signing {
1444                    backend_user: "signing".parse()?,
1445                    signing_key_id: "signing1".parse()?,
1446                    key_setup: SigningKeySetup::new(
1447                        KeyType::Curve25519,
1448                        vec![KeyMechanism::EdDsaSignature],
1449                        None,
1450                        SignatureType::EdDsa,
1451                        CryptographicKeyContext::OpenPgp {
1452                            user_ids: OpenPgpUserIdList::new(vec![
1453                                "Foobar McFooface <foobar@mcfooface.org>".parse()?,
1454                            ])?,
1455                            notations: Default::default(),
1456                            version: "v4".parse()?,
1457                        },
1458                    )?,
1459                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
1460                    system_user: "nethsm-signing".parse()?,
1461                    tag: "signing1".to_string(),
1462                }
1463            })
1464        )]
1465        #[case::none("foo", None)]
1466        fn config_user_backend_connection(
1467            default_config: TestResult<Config>,
1468            #[case] system_user: &str,
1469            #[case] expected_connection: Option<UserBackendConnection>,
1470        ) -> TestResult {
1471            let config = default_config?;
1472            assert_eq!(
1473                expected_connection,
1474                config.user_backend_connection(&system_user.parse()?)
1475            );
1476
1477            Ok(())
1478        }
1479
1480        /// Ensures, that [`Config::user_backend_connections`] returns the correct list of
1481        /// [`UserBackendConnection`] items according to a [`UserBackendConnectionFilter`].
1482        #[rstest]
1483        #[case::no_filter(
1484            &[],
1485            vec![
1486                UserBackendConnection::NetHsm {
1487                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1488                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1489                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1490                    },
1491                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1492                    connections: BTreeSet::from_iter([
1493                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1494                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1495                    ]),
1496                    mapping: NetHsmUserMapping::Admin("admin".parse()?)
1497                },
1498                UserBackendConnection::NetHsm {
1499                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1500                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1501                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1502                    },
1503                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1504                    connections: BTreeSet::from_iter([
1505                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1506                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1507                    ]),
1508                    mapping: NetHsmUserMapping::Backup{
1509                        backend_user: "backup".parse()?,
1510                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
1511                        system_user: "nethsm-backup".parse()?,
1512                    }
1513                },
1514                UserBackendConnection::NetHsm {
1515                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1516                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1517                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1518                    },
1519                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1520                    connections: BTreeSet::from_iter([
1521                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1522                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1523                    ]),
1524                    mapping: NetHsmUserMapping::HermeticMetrics {
1525                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
1526                        system_user: "nethsm-hermetic-metrics".parse()?,
1527                    }
1528                },
1529                UserBackendConnection::NetHsm {
1530                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1531                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1532                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1533                    },
1534                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1535                    connections: BTreeSet::from_iter([
1536                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1537                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1538                    ]),
1539                    mapping: NetHsmUserMapping::Metrics {
1540                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
1541                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
1542                        system_user: "nethsm-metrics".parse()?,
1543                    }
1544                },
1545                UserBackendConnection::NetHsm {
1546                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1547                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1548                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1549                    },
1550                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1551                    connections: BTreeSet::from_iter([
1552                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1553                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1554                    ]),
1555                    mapping: NetHsmUserMapping::Signing {
1556                        backend_user: "signing".parse()?,
1557                        signing_key_id: "signing1".parse()?,
1558                        key_setup: SigningKeySetup::new(
1559                            KeyType::Curve25519,
1560                            vec![KeyMechanism::EdDsaSignature],
1561                            None,
1562                            SignatureType::EdDsa,
1563                            CryptographicKeyContext::OpenPgp {
1564                                user_ids: OpenPgpUserIdList::new(vec![
1565                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
1566                                ])?,
1567                                notations: Default::default(),
1568                                version: "v4".parse()?,
1569                            },
1570                        )?,
1571                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
1572                        system_user: "nethsm-signing".parse()?,
1573                        tag: "signing1".to_string(),
1574                    }
1575                },
1576            ],
1577        )]
1578        #[case::filter_admin(
1579            &[UserBackendConnectionFilter::Admin],
1580            vec![
1581                UserBackendConnection::NetHsm {
1582                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1583                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1584                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1585                    },
1586                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1587                    connections: BTreeSet::from_iter([
1588                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1589                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1590                    ]),
1591                    mapping: NetHsmUserMapping::Admin("admin".parse()?)
1592                },
1593            ],
1594        )]
1595        #[case::filter_non_admin(
1596            &[UserBackendConnectionFilter::NonAdmin],
1597            vec![
1598                UserBackendConnection::NetHsm {
1599                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1600                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1601                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1602                    },
1603                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1604                    connections: BTreeSet::from_iter([
1605                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1606                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1607                    ]),
1608                    mapping: NetHsmUserMapping::Backup{
1609                        backend_user: "backup".parse()?,
1610                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
1611                        system_user: "nethsm-backup".parse()?,
1612                    }
1613                },
1614                UserBackendConnection::NetHsm {
1615                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1616                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1617                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1618                    },
1619                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1620                    connections: BTreeSet::from_iter([
1621                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1622                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1623                    ]),
1624                    mapping: NetHsmUserMapping::HermeticMetrics {
1625                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
1626                        system_user: "nethsm-hermetic-metrics".parse()?,
1627                    }
1628                },
1629                UserBackendConnection::NetHsm {
1630                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1631                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1632                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1633                    },
1634                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1635                    connections: BTreeSet::from_iter([
1636                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1637                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1638                    ]),
1639                    mapping: NetHsmUserMapping::Metrics {
1640                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
1641                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
1642                        system_user: "nethsm-metrics".parse()?,
1643                    }
1644                },
1645                UserBackendConnection::NetHsm {
1646                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
1647                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1648                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1649                    },
1650                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
1651                    connections: BTreeSet::from_iter([
1652                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
1653                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
1654                    ]),
1655                    mapping: NetHsmUserMapping::Signing {
1656                        backend_user: "signing".parse()?,
1657                        signing_key_id: "signing1".parse()?,
1658                        key_setup: SigningKeySetup::new(
1659                            KeyType::Curve25519,
1660                            vec![KeyMechanism::EdDsaSignature],
1661                            None,
1662                            SignatureType::EdDsa,
1663                            CryptographicKeyContext::OpenPgp {
1664                                user_ids: OpenPgpUserIdList::new(vec![
1665                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
1666                                ])?,
1667                                notations: Default::default(),
1668                                version: "v4".parse()?,
1669                            },
1670                        )?,
1671                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
1672                        system_user: "nethsm-signing".parse()?,
1673                        tag: "signing1".to_string(),
1674                    }
1675                },
1676            ],
1677        )]
1678        fn config_user_backend_connections(
1679            default_config: TestResult<Config>,
1680            #[case] filters: &[UserBackendConnectionFilter],
1681            #[case] expected_connections: Vec<UserBackendConnection>,
1682        ) -> TestResult {
1683            let config = default_config?;
1684
1685            assert_eq!(
1686                expected_connections,
1687                config.user_backend_connections(filters)
1688            );
1689
1690            Ok(())
1691        }
1692
1693        /// Ensures, that [`Config::authorized_key_entries`] returns SSH authorized key entries
1694        /// correctly.
1695        #[rstest]
1696        fn config_authorized_key_entries(default_config: TestResult<Config>) -> TestResult {
1697            let config = default_config?;
1698            let expected: HashSet<AuthorizedKeyEntry> = HashSet::from_iter([
1699                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAN54Gd1jMz+yNDjBRwX1SnOtWuUsVF64RJIeYJ8DI7b user@host".parse()?,
1700                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
1701                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
1702                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh9BTe81DC6A0YZALsq9dWcyl6xjjqlxWPwlExTFgBt user@host".parse()?,
1703                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
1704                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
1705                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
1706            ]);
1707
1708            assert_eq!(
1709                config.authorized_key_entries(),
1710                expected.iter().collect::<HashSet<_>>()
1711            );
1712            Ok(())
1713        }
1714
1715        /// Ensures, that [`Config::system_user_data`] returns [`SystemUserData`] entries correctly.
1716        #[rstest]
1717        fn config_system_user_data(
1718            default_config: TestResult<Config>,
1719            raw_user_data: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1720        ) -> TestResult {
1721            let config = default_config?;
1722            let raw_user_data = raw_user_data?;
1723            let expected: HashSet<SystemUserData> = HashSet::from_iter([
1724                SystemUserData::HostShareholder {
1725                    system_user: &raw_user_data[0].0,
1726                    ssh_authorized_key: raw_user_data[0]
1727                        .1
1728                        .as_ref()
1729                        .expect("to have SSH authorized key"),
1730                },
1731                SystemUserData::HostShareholder {
1732                    system_user: &raw_user_data[1].0,
1733                    ssh_authorized_key: raw_user_data[1]
1734                        .1
1735                        .as_ref()
1736                        .expect("to have SSH authorized key"),
1737                },
1738                SystemUserData::HostShareholder {
1739                    system_user: &raw_user_data[2].0,
1740                    ssh_authorized_key: raw_user_data[2]
1741                        .1
1742                        .as_ref()
1743                        .expect("to have SSH authorized key"),
1744                },
1745                SystemUserData::HostDownloadNetworkConfig {
1746                    system_user: &raw_user_data[3].0,
1747                    ssh_authorized_key: raw_user_data[3]
1748                        .1
1749                        .as_ref()
1750                        .expect("to have SSH authorized key"),
1751                },
1752                SystemUserData::BackendAdmin {
1753                    system_user: raw_user_data[4].0.clone(),
1754                },
1755                SystemUserData::BackendBackup {
1756                    system_user: &raw_user_data[5].0,
1757                    ssh_authorized_key: raw_user_data[5]
1758                        .1
1759                        .as_ref()
1760                        .expect("to have SSH authorized key"),
1761                },
1762                SystemUserData::BackendHermeticMetrics {
1763                    system_user: &raw_user_data[6].0,
1764                },
1765                SystemUserData::BackendMetrics {
1766                    system_user: &raw_user_data[7].0,
1767                    ssh_authorized_key: raw_user_data[7]
1768                        .1
1769                        .as_ref()
1770                        .expect("to have SSH authorized key"),
1771                },
1772                SystemUserData::BackendSign {
1773                    system_user: &raw_user_data[8].0,
1774                    ssh_authorized_key: raw_user_data[8]
1775                        .1
1776                        .as_ref()
1777                        .expect("to have SSH authorized key"),
1778                },
1779            ]);
1780
1781            assert_eq!(config.system_user_data(), expected);
1782            Ok(())
1783        }
1784
1785        /// Ensures, that [`Config::system_user_ids`] returns system user IDs correctly.
1786        #[rstest]
1787        fn config_system_user_ids(default_config: TestResult<Config>) -> TestResult {
1788            let config = default_config?;
1789            let expected: HashSet<SystemUserId> = HashSet::from_iter([
1790                "signstar-share-holder1".parse()?,
1791                "signstar-share-holder2".parse()?,
1792                "signstar-share-holder3".parse()?,
1793                "signstar-wireguard-download".parse()?,
1794                "nethsm-backup".parse()?,
1795                "nethsm-hermetic-metrics".parse()?,
1796                "nethsm-metrics".parse()?,
1797                "nethsm-signing".parse()?,
1798            ]);
1799
1800            assert_eq!(
1801                config.system_user_ids(),
1802                expected.iter().collect::<HashSet<_>>()
1803            );
1804            Ok(())
1805        }
1806
1807        /// Ensures, that a [`Config`] object leads to a specific YAML output.
1808        ///
1809        /// In this particular case, a [`SystemConfig`] and a [`NetHsmConfig`] object are present.
1810        #[rstest]
1811        fn config_to_yaml_string(
1812            default_system_config: TestResult<SystemConfig>,
1813            default_nethsm_config: TestResult<NetHsmConfig>,
1814        ) -> TestResult {
1815            let config = ConfigBuilder::new(default_system_config?)
1816                .set_nethsm_config(default_nethsm_config?)
1817                .finish()?;
1818            let config_str = config.to_yaml_string()?;
1819
1820            with_settings!({
1821                description => "Configuration with system-wide and NetHSM configuration",
1822                snapshot_path => SNAPSHOT_PATH,
1823                prepend_module_to_snapshot => false,
1824            }, {
1825                assert_snapshot!(current().name().expect("current thread should have a name").to_string().replace("::", "__"), config_str);
1826            });
1827
1828            Ok(())
1829        }
1830
1831        /// Ensures, that a valid [`Config`] can be created from a YAML file and turned back into
1832        /// the same YAML string.
1833        ///
1834        /// The configuration file describes a [`SystemConfig`] and a [`NetHsmConfig`] object.
1835        #[rstest]
1836        fn roundtrip_yaml_config(
1837            #[files("../fixtures/config/nethsm_backend/*.yaml")] path: PathBuf,
1838        ) -> TestResult {
1839            let config_string = read_to_string(&path)?;
1840            let config = Config::from_file_path(&path)?;
1841
1842            assert_eq!(config.to_yaml_string()?, config_string);
1843
1844            Ok(())
1845        }
1846
1847        /// Ensures, that [`AdministrativeSecretHandling`] and
1848        /// [`NonAdministrativeSecretHandling`]can be retrieved from a
1849        /// [`UserBackendConnection`].
1850        #[rstest]
1851        fn user_backend_connection_secret_handling(
1852            default_config: TestResult<Config>,
1853        ) -> TestResult {
1854            let config = default_config?;
1855            let admin_secret_handling = AdministrativeSecretHandling::ShamirsSecretSharing {
1856                number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
1857                threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
1858            };
1859            let non_admin_secret_handling = NonAdministrativeSecretHandling::SystemdCreds;
1860
1861            let user_backend_connection = config
1862                .user_backend_connection(&"nethsm-signing".parse()?)
1863                .expect("there to be a mapping of the requested name");
1864
1865            assert_eq!(
1866                user_backend_connection.admin_secret_handling(),
1867                admin_secret_handling
1868            );
1869            assert_eq!(
1870                user_backend_connection.non_admin_secret_handling(),
1871                non_admin_secret_handling
1872            );
1873
1874            Ok(())
1875        }
1876
1877        /// Ensures, that [`SystemUserConfigState`] can be created from [`Config`].
1878        #[rstest]
1879        fn system_user_config_state_from_config(default_config: TestResult<Config>) -> TestResult {
1880            let config = default_config?;
1881            let state = SystemUserConfigState::from(&config);
1882
1883            assert_eq!(state.system_user_data, config.system_user_data(),);
1884            Ok(())
1885        }
1886    }
1887
1888    /// Tests, that are only available when using the YubiHSM2 (and no other) backend.
1889    #[cfg(all(feature = "yubihsm2", not(feature = "nethsm")))]
1890    mod yubihsm2_backend {
1891        use pretty_assertions::assert_eq;
1892
1893        use super::*;
1894        use crate::config::{
1895            SystemUserData,
1896            traits::{ConfigSystemUserData, MappingAuthorizedKeyEntry, MappingSystemUserId},
1897        };
1898
1899        /// Creates a default [`Config`] for testing purposes.
1900        #[fixture]
1901        fn default_config(
1902            default_system_config: TestResult<SystemConfig>,
1903            default_yubihsm2_config: TestResult<YubiHsm2Config>,
1904        ) -> TestResult<Config> {
1905            Ok(ConfigBuilder::new(default_system_config?)
1906                .set_yubihsm2_config(default_yubihsm2_config?)
1907                .finish()?)
1908        }
1909
1910        /// List of raw data required to create [`SystemUserData`] for each item in the default
1911        /// [`Config`].
1912        #[fixture]
1913        fn raw_user_data(
1914            raw_user_data_system: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1915            raw_user_data_yubihsm2: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1916        ) -> TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>> {
1917            let mut data = raw_user_data_system?;
1918            data.extend(raw_user_data_yubihsm2?);
1919            Ok(data)
1920        }
1921
1922        /// Ensures that [`MappingSystemUserId`] for [`UserBackendConnection`] works as intended.
1923        #[rstest]
1924        fn user_backend_connection_system_user_id(
1925            raw_user_data_yubihsm2: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1926        ) -> TestResult {
1927            let raw_user_data_yubihsm2 = raw_user_data_yubihsm2?;
1928            let data = UserBackendConnection::YubiHsm2 {
1929                admin_secret_handling: AdministrativeSecretHandling::Plaintext,
1930                non_admin_secret_handling: NonAdministrativeSecretHandling::Plaintext,
1931                connections: BTreeSet::from_iter([YubiHsm2Connection::Usb {
1932                    serial_number: "0123456789".parse()?,
1933                }]),
1934                mapping: YubiHsm2UserMapping::AuditLog {
1935                    authentication_key_id: "1".parse()?,
1936                    ssh_authorized_key: raw_user_data_yubihsm2[1]
1937                        .1
1938                        .clone()
1939                        .expect("to have an SSH authorized key"),
1940                    system_user: raw_user_data_yubihsm2[1].0.clone(),
1941                },
1942            };
1943            assert_eq!(data.system_user_id(), Some(&raw_user_data_yubihsm2[1].0));
1944
1945            Ok(())
1946        }
1947
1948        /// Ensures that [`MappingAuthorizedKeyEntry`] for [`UserBackendConnection`] works as
1949        /// intended.
1950        #[rstest]
1951        fn user_backend_connection_authorized_key_entry(
1952            raw_user_data_yubihsm2: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
1953        ) -> TestResult {
1954            let raw_user_data_yubihsm2 = raw_user_data_yubihsm2?;
1955            let data = UserBackendConnection::YubiHsm2 {
1956                admin_secret_handling: AdministrativeSecretHandling::Plaintext,
1957                non_admin_secret_handling: NonAdministrativeSecretHandling::Plaintext,
1958                connections: BTreeSet::from_iter([YubiHsm2Connection::Usb {
1959                    serial_number: "0123456789".parse()?,
1960                }]),
1961                mapping: YubiHsm2UserMapping::AuditLog {
1962                    authentication_key_id: "1".parse()?,
1963                    ssh_authorized_key: raw_user_data_yubihsm2[1]
1964                        .1
1965                        .clone()
1966                        .expect("to have an SSH authorized key"),
1967                    system_user: raw_user_data_yubihsm2[1].0.clone(),
1968                },
1969            };
1970            assert_eq!(
1971                data.authorized_key_entry(),
1972                Some(
1973                    raw_user_data_yubihsm2[1]
1974                        .1
1975                        .as_ref()
1976                        .expect("to have an SSH authorized key")
1977                )
1978            );
1979
1980            Ok(())
1981        }
1982
1983        /// Ensures, that [`ConfigBuilder::finish`] fails on issues with overlapping data in
1984        /// configuration components.
1985        ///
1986        /// Here, a custom [`YubiHsm2Config`] is staged together with a default [`SystemConfig`]
1987        /// (created by [`default_system_config`]) to create a failure scenario.
1988        #[rstest]
1989        #[case::two_duplicate_system_users_two_duplicate_ssh_public_keys(
1990            "Configuration with system-wide and YubiHSM2 configuration has two duplicate system users and two duplicate SSH public keys",
1991            YubiHsm2Config::new(
1992                BTreeSet::from_iter([
1993                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
1994                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
1995                ]),
1996                BTreeSet::from_iter([
1997                    YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
1998                    YubiHsm2UserMapping::AuditLog {
1999                        authentication_key_id: "3".parse()?,
2000                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
2001                        system_user: "signstar-share-holder2".parse()?,
2002                    },
2003                    YubiHsm2UserMapping::Backup{
2004                        authentication_key_id: "2".parse()?,
2005                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
2006                        system_user: "signstar-share-holder1".parse()?,
2007                    },
2008                    YubiHsm2UserMapping::HermeticAuditLog {
2009                        authentication_key_id: "4".parse()?,
2010                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
2011                    },
2012                    YubiHsm2UserMapping::Signing {
2013                        authentication_key_id: "5".parse()?,
2014                        signing_key_id: "1".parse()?,
2015                        key_setup: SigningKeySetup::new(
2016                            KeyType::Curve25519,
2017                            vec![KeyMechanism::EdDsaSignature],
2018                            None,
2019                            SignatureType::EdDsa,
2020                            CryptographicKeyContext::OpenPgp {
2021                                user_ids: OpenPgpUserIdList::new(vec![
2022                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2023                                ])?,
2024                                notations: Default::default(),
2025                                version: "v4".parse()?,
2026                            },
2027                        )?,
2028                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh9BTe81DC6A0YZALsq9dWcyl6xjjqlxWPwlExTFgBt user@host".parse()?,
2029                        system_user: "yubihsm2-signing".parse()?,
2030                        domain: Domain::One,
2031                    }
2032                ]),
2033            )?
2034         )]
2035        #[case::one_duplicate_system_user_two_duplicate_ssh_public_keys(
2036            "Configuration with system-wide and YubiHSM2 configuration has one duplicate system user and two duplicate SSH public keys",
2037            YubiHsm2Config::new(
2038                BTreeSet::from_iter([
2039                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2040                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2041                ]),
2042                BTreeSet::from_iter([
2043                    YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
2044                    YubiHsm2UserMapping::AuditLog {
2045                        authentication_key_id: "3".parse()?,
2046                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
2047                        system_user: "yubihsm2-audit-log".parse()?,
2048                    },
2049                    YubiHsm2UserMapping::Backup{
2050                        authentication_key_id: "2".parse()?,
2051                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
2052                        system_user: "signstar-share-holder1".parse()?,
2053                    },
2054                    YubiHsm2UserMapping::HermeticAuditLog {
2055                        authentication_key_id: "4".parse()?,
2056                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
2057                    },
2058                    YubiHsm2UserMapping::Signing {
2059                        authentication_key_id: "5".parse()?,
2060                        signing_key_id: "1".parse()?,
2061                        key_setup: SigningKeySetup::new(
2062                            KeyType::Curve25519,
2063                            vec![KeyMechanism::EdDsaSignature],
2064                            None,
2065                            SignatureType::EdDsa,
2066                            CryptographicKeyContext::OpenPgp {
2067                                user_ids: OpenPgpUserIdList::new(vec![
2068                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2069                                ])?,
2070                                notations: Default::default(),
2071                                version: "v4".parse()?,
2072                            },
2073                        )?,
2074                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh9BTe81DC6A0YZALsq9dWcyl6xjjqlxWPwlExTFgBt user@host".parse()?,
2075                        system_user: "yubihsm2-signing".parse()?,
2076                        domain: Domain::One,
2077                    }
2078                ]),
2079            )?
2080         )]
2081        #[case::one_duplicate_system_user_one_duplicate_ssh_public_key(
2082            "Configuration with system-wide and YubiHSM2 configuration has one duplicate system user and one duplicate SSH public key",
2083            YubiHsm2Config::new(
2084                BTreeSet::from_iter([
2085                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2086                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2087                ]),
2088                BTreeSet::from_iter([
2089                    YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
2090                    YubiHsm2UserMapping::AuditLog {
2091                        authentication_key_id: "3".parse()?,
2092                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
2093                        system_user: "yubihsm2-audit-log".parse()?,
2094                    },
2095                    YubiHsm2UserMapping::Backup{
2096                        authentication_key_id: "2".parse()?,
2097                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
2098                        system_user: "signstar-share-holder1".parse()?,
2099                    },
2100                    YubiHsm2UserMapping::HermeticAuditLog {
2101                        authentication_key_id: "4".parse()?,
2102                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
2103                    },
2104                    YubiHsm2UserMapping::Signing {
2105                        authentication_key_id: "5".parse()?,
2106                        signing_key_id: "1".parse()?,
2107                        key_setup: SigningKeySetup::new(
2108                            KeyType::Curve25519,
2109                            vec![KeyMechanism::EdDsaSignature],
2110                            None,
2111                            SignatureType::EdDsa,
2112                            CryptographicKeyContext::OpenPgp {
2113                                user_ids: OpenPgpUserIdList::new(vec![
2114                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2115                                ])?,
2116                                notations: Default::default(),
2117                                version: "v4".parse()?,
2118                            },
2119                        )?,
2120                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
2121                        system_user: "yubihsm2-signing".parse()?,
2122                        domain: Domain::One,
2123                    }
2124                ]),
2125            )?
2126         )]
2127        #[case::one_duplicate_ssh_public_key(
2128            "Configuration with system-wide and YubiHSM2 configuration has one duplicate SSH public key",
2129            YubiHsm2Config::new(
2130                BTreeSet::from_iter([
2131                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2132                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2133                ]),
2134                BTreeSet::from_iter([
2135                    YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
2136                    YubiHsm2UserMapping::AuditLog {
2137                        authentication_key_id: "3".parse()?,
2138                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
2139                        system_user: "yubihsm2-audit-log".parse()?,
2140                    },
2141                    YubiHsm2UserMapping::Backup{
2142                        authentication_key_id: "2".parse()?,
2143                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
2144                        system_user: "yubihsm2-backup".parse()?,
2145                    },
2146                    YubiHsm2UserMapping::HermeticAuditLog {
2147                        authentication_key_id: "4".parse()?,
2148                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
2149                    },
2150                    YubiHsm2UserMapping::Signing {
2151                        authentication_key_id: "5".parse()?,
2152                        signing_key_id: "1".parse()?,
2153                        key_setup: SigningKeySetup::new(
2154                            KeyType::Curve25519,
2155                            vec![KeyMechanism::EdDsaSignature],
2156                            None,
2157                            SignatureType::EdDsa,
2158                            CryptographicKeyContext::OpenPgp {
2159                                user_ids: OpenPgpUserIdList::new(vec![
2160                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2161                                ])?,
2162                                notations: Default::default(),
2163                                version: "v4".parse()?,
2164                            },
2165                        )?,
2166                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
2167                        system_user: "yubihsm2-signing".parse()?,
2168                        domain: Domain::One,
2169                    }
2170                ]),
2171            )?
2172         )]
2173        #[case::one_duplicate_system_user(
2174            "Configuration with system-wide and YubiHSM2 configuration has one duplicate system user",
2175            YubiHsm2Config::new(
2176                BTreeSet::from_iter([
2177                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2178                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2179                ]),
2180                BTreeSet::from_iter([
2181                    YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
2182                    YubiHsm2UserMapping::AuditLog {
2183                        authentication_key_id: "3".parse()?,
2184                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
2185                        system_user: "yubihsm2-audit-log".parse()?,
2186                    },
2187                    YubiHsm2UserMapping::Backup{
2188                        authentication_key_id: "2".parse()?,
2189                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
2190                        system_user: "signstar-share-holder1".parse()?,
2191                    },
2192                    YubiHsm2UserMapping::HermeticAuditLog {
2193                        authentication_key_id: "4".parse()?,
2194                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
2195                    },
2196                    YubiHsm2UserMapping::Signing {
2197                        authentication_key_id: "5".parse()?,
2198                        signing_key_id: "1".parse()?,
2199                        key_setup: SigningKeySetup::new(
2200                            KeyType::Curve25519,
2201                            vec![KeyMechanism::EdDsaSignature],
2202                            None,
2203                            SignatureType::EdDsa,
2204                            CryptographicKeyContext::OpenPgp {
2205                                user_ids: OpenPgpUserIdList::new(vec![
2206                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2207                                ])?,
2208                                notations: Default::default(),
2209                                version: "v4".parse()?,
2210                            },
2211                        )?,
2212                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
2213                        system_user: "yubihsm2-signing".parse()?,
2214                        domain: Domain::One,
2215                    }
2216                ]),
2217            )?
2218         )]
2219        fn config_builder_fails_validation(
2220            default_system_config: TestResult<SystemConfig>,
2221            #[case] description: &str,
2222            #[case] yubihsm2_config: YubiHsm2Config,
2223        ) -> TestResult {
2224            let error_message = match ConfigBuilder::new(default_system_config?)
2225                .set_yubihsm2_config(yubihsm2_config)
2226                .finish()
2227            {
2228                Err(error) => error.to_string(),
2229                Ok(config) => panic!(
2230                    "Expected to fail with Error::Validation, but succeeded instead: {}",
2231                    config.to_yaml_string()?
2232                ),
2233            };
2234
2235            with_settings!({
2236                description => description,
2237                snapshot_path => SNAPSHOT_PATH,
2238                prepend_module_to_snapshot => false,
2239            }, {
2240                assert_snapshot!(current().name().expect("current thread should have a name").to_string().replace("::", "__"), error_message);
2241            });
2242
2243            Ok(())
2244        }
2245
2246        /// Ensures, that [`Config::yubihsm2`] returns the original input.
2247        #[rstest]
2248        fn config_yubihsm2(
2249            default_system_config: TestResult<SystemConfig>,
2250            default_yubihsm2_config: TestResult<YubiHsm2Config>,
2251        ) -> TestResult {
2252            let yubihsm2_config = default_yubihsm2_config?;
2253
2254            let config = ConfigBuilder::new(default_system_config?)
2255                .set_yubihsm2_config(yubihsm2_config.clone())
2256                .finish()?;
2257
2258            assert_eq!(
2259                &yubihsm2_config,
2260                config.yubihsm2().expect("a YubiHsm2Config reference")
2261            );
2262
2263            Ok(())
2264        }
2265
2266        /// Ensures, that an optional [`UserBackendConnection`] can be retrieved from a [`Config`].
2267        #[rstest]
2268        #[case::yubihsm2_signing(
2269            "yubihsm2-signing",
2270            Some(UserBackendConnection::YubiHsm2 {
2271                admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2272                    number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2273                    threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2274                },
2275                non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2276                connections: BTreeSet::from_iter([
2277                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2278                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2279                ]),
2280                mapping: YubiHsm2UserMapping::Signing {
2281                    authentication_key_id: "5".parse()?,
2282                    signing_key_id: "1".parse()?,
2283                    key_setup: SigningKeySetup::new(
2284                        KeyType::Curve25519,
2285                        vec![KeyMechanism::EdDsaSignature],
2286                        None,
2287                        SignatureType::EdDsa,
2288                        CryptographicKeyContext::OpenPgp {
2289                            user_ids: OpenPgpUserIdList::new(vec![
2290                                "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2291                            ])?,
2292                            notations: Default::default(),
2293                            version: "v4".parse()?,
2294                        },
2295                    )?,
2296                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
2297                    system_user: "yubihsm2-signing".parse()?,
2298                    domain: Domain::One,
2299                }
2300            })
2301        )]
2302        #[case::none("foo", None)]
2303        fn config_user_backend_connection(
2304            default_config: TestResult<Config>,
2305            #[case] system_user: &str,
2306            #[case] expected_connection: Option<UserBackendConnection>,
2307        ) -> TestResult {
2308            let config = default_config?;
2309            assert_eq!(
2310                expected_connection,
2311                config.user_backend_connection(&system_user.parse()?)
2312            );
2313
2314            Ok(())
2315        }
2316
2317        /// Ensures, that [`Config::user_backend_connections`] returns the correct list of
2318        /// [`UserBackendConnection`] items according to a [`UserBackendConnectionFilter`].
2319        #[rstest]
2320        #[case::no_filter(
2321            &[],
2322            vec![
2323                UserBackendConnection::YubiHsm2 {
2324                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2325                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2326                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2327                    },
2328                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2329                    connections: BTreeSet::from_iter([
2330                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2331                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2332                    ]),
2333                    mapping: YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
2334                },
2335                UserBackendConnection::YubiHsm2 {
2336                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2337                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2338                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2339                    },
2340                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2341                    connections: BTreeSet::from_iter([
2342                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2343                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2344                    ]),
2345                    mapping: YubiHsm2UserMapping::AuditLog {
2346                        authentication_key_id: "3".parse()?,
2347                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
2348                        system_user: "yubihsm2-audit-log".parse()?,
2349                    },
2350                },
2351                UserBackendConnection::YubiHsm2 {
2352                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2353                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2354                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2355                    },
2356                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2357                    connections: BTreeSet::from_iter([
2358                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2359                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2360                    ]),
2361                    mapping: YubiHsm2UserMapping::Backup{
2362                        authentication_key_id: "2".parse()?,
2363                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
2364                        system_user: "yubihsm2-backup".parse()?,
2365                    },
2366                },
2367                UserBackendConnection::YubiHsm2 {
2368                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2369                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2370                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2371                    },
2372                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2373                    connections: BTreeSet::from_iter([
2374                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2375                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2376                    ]),
2377                    mapping: YubiHsm2UserMapping::HermeticAuditLog {
2378                        authentication_key_id: "4".parse()?,
2379                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
2380                    },
2381                },
2382                UserBackendConnection::YubiHsm2 {
2383                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2384                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2385                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2386                    },
2387                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2388                    connections: BTreeSet::from_iter([
2389                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2390                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2391                    ]),
2392                    mapping: YubiHsm2UserMapping::Signing {
2393                        authentication_key_id: "5".parse()?,
2394                        signing_key_id: "1".parse()?,
2395                        key_setup: SigningKeySetup::new(
2396                            KeyType::Curve25519,
2397                            vec![KeyMechanism::EdDsaSignature],
2398                            None,
2399                            SignatureType::EdDsa,
2400                            CryptographicKeyContext::OpenPgp {
2401                                user_ids: OpenPgpUserIdList::new(vec![
2402                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2403                                ])?,
2404                                notations: Default::default(),
2405                                version: "v4".parse()?,
2406                            },
2407                        )?,
2408                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
2409                        system_user: "yubihsm2-signing".parse()?,
2410                        domain: Domain::One,
2411                    }
2412                },
2413            ],
2414        )]
2415        #[case::filter_admin(
2416            &[UserBackendConnectionFilter::Admin],
2417            vec![
2418                UserBackendConnection::YubiHsm2 {
2419                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2420                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2421                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2422                    },
2423                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2424                    connections: BTreeSet::from_iter([
2425                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2426                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2427                    ]),
2428                    mapping: YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
2429                },
2430            ],
2431        )]
2432        #[case::filter_non_admin(
2433            &[UserBackendConnectionFilter::NonAdmin],
2434            vec![
2435                UserBackendConnection::YubiHsm2 {
2436                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2437                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2438                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2439                    },
2440                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2441                    connections: BTreeSet::from_iter([
2442                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2443                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2444                    ]),
2445                    mapping: YubiHsm2UserMapping::AuditLog {
2446                        authentication_key_id: "3".parse()?,
2447                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
2448                        system_user: "yubihsm2-audit-log".parse()?,
2449                    },
2450                },
2451                UserBackendConnection::YubiHsm2 {
2452                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2453                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2454                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2455                    },
2456                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2457                    connections: BTreeSet::from_iter([
2458                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2459                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2460                    ]),
2461                    mapping: YubiHsm2UserMapping::Backup{
2462                        authentication_key_id: "2".parse()?,
2463                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
2464                        system_user: "yubihsm2-backup".parse()?,
2465                    },
2466                },
2467                UserBackendConnection::YubiHsm2 {
2468                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2469                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2470                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2471                    },
2472                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2473                    connections: BTreeSet::from_iter([
2474                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2475                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2476                    ]),
2477                    mapping: YubiHsm2UserMapping::HermeticAuditLog {
2478                        authentication_key_id: "4".parse()?,
2479                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
2480                    },
2481                },
2482                UserBackendConnection::YubiHsm2 {
2483                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
2484                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2485                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2486                    },
2487                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
2488                    connections: BTreeSet::from_iter([
2489                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2490                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2491                    ]),
2492                    mapping: YubiHsm2UserMapping::Signing {
2493                        authentication_key_id: "5".parse()?,
2494                        signing_key_id: "1".parse()?,
2495                        key_setup: SigningKeySetup::new(
2496                            KeyType::Curve25519,
2497                            vec![KeyMechanism::EdDsaSignature],
2498                            None,
2499                            SignatureType::EdDsa,
2500                            CryptographicKeyContext::OpenPgp {
2501                                user_ids: OpenPgpUserIdList::new(vec![
2502                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2503                                ])?,
2504                                notations: Default::default(),
2505                                version: "v4".parse()?,
2506                            },
2507                        )?,
2508                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
2509                        system_user: "yubihsm2-signing".parse()?,
2510                        domain: Domain::One,
2511                    }
2512                },
2513            ],
2514        )]
2515        fn config_user_backend_connections(
2516            default_config: TestResult<Config>,
2517            #[case] filters: &[UserBackendConnectionFilter],
2518            #[case] expected_connections: Vec<UserBackendConnection>,
2519        ) -> TestResult {
2520            let config = default_config?;
2521
2522            assert_eq!(
2523                expected_connections,
2524                config.user_backend_connections(filters)
2525            );
2526
2527            Ok(())
2528        }
2529
2530        /// Ensures, that a [`Config`] object leads to a specific YAML output.
2531        ///
2532        /// In this particular case, a [`SystemConfig`] and a [`YubiHsm2Config`] object are present.
2533        #[rstest]
2534        fn config_to_yaml_string(
2535            default_system_config: TestResult<SystemConfig>,
2536            default_yubihsm2_config: TestResult<YubiHsm2Config>,
2537        ) -> TestResult {
2538            let config = ConfigBuilder::new(default_system_config?)
2539                .set_yubihsm2_config(default_yubihsm2_config?)
2540                .finish()?;
2541            let config_str = config.to_yaml_string()?;
2542
2543            with_settings!({
2544                description => "Configuration with system-wide and YubiHSM2 configuration",
2545                snapshot_path => SNAPSHOT_PATH,
2546                prepend_module_to_snapshot => false,
2547            }, {
2548                assert_snapshot!(current().name().expect("current thread should have a name").to_string().replace("::", "__"), config_str);
2549            });
2550
2551            Ok(())
2552        }
2553
2554        /// Ensures, that [`Config::authorized_key_entries`] returns SSH authorized key entries
2555        /// correctly.
2556        #[rstest]
2557        fn config_authorized_key_entries(default_config: TestResult<Config>) -> TestResult {
2558            let config = default_config?;
2559            let expected: HashSet<AuthorizedKeyEntry> = HashSet::from_iter([
2560                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAN54Gd1jMz+yNDjBRwX1SnOtWuUsVF64RJIeYJ8DI7b user@host".parse()?,
2561                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
2562                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
2563                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh9BTe81DC6A0YZALsq9dWcyl6xjjqlxWPwlExTFgBt user@host".parse()?,
2564                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
2565                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
2566                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
2567            ]);
2568
2569            assert_eq!(
2570                config.authorized_key_entries(),
2571                expected.iter().collect::<HashSet<_>>()
2572            );
2573            Ok(())
2574        }
2575
2576        /// Ensures, that [`Config::system_user_data`] returns [`SystemUserData`] entries correctly.
2577        #[rstest]
2578        fn config_system_user_data(
2579            default_config: TestResult<Config>,
2580            raw_user_data: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
2581        ) -> TestResult {
2582            let config = default_config?;
2583            let raw_user_data = raw_user_data?;
2584            let expected: HashSet<SystemUserData> = HashSet::from_iter([
2585                SystemUserData::HostShareholder {
2586                    system_user: &raw_user_data[0].0,
2587                    ssh_authorized_key: raw_user_data[0]
2588                        .1
2589                        .as_ref()
2590                        .expect("to have SSH authorized key"),
2591                },
2592                SystemUserData::HostShareholder {
2593                    system_user: &raw_user_data[1].0,
2594                    ssh_authorized_key: raw_user_data[1]
2595                        .1
2596                        .as_ref()
2597                        .expect("to have SSH authorized key"),
2598                },
2599                SystemUserData::HostShareholder {
2600                    system_user: &raw_user_data[2].0,
2601                    ssh_authorized_key: raw_user_data[2]
2602                        .1
2603                        .as_ref()
2604                        .expect("to have SSH authorized key"),
2605                },
2606                SystemUserData::HostDownloadNetworkConfig {
2607                    system_user: &raw_user_data[3].0,
2608                    ssh_authorized_key: raw_user_data[3]
2609                        .1
2610                        .as_ref()
2611                        .expect("to have SSH authorized key"),
2612                },
2613                SystemUserData::BackendAdmin {
2614                    system_user: raw_user_data[4].0.clone(),
2615                },
2616                SystemUserData::BackendMetrics {
2617                    system_user: &raw_user_data[5].0,
2618                    ssh_authorized_key: raw_user_data[5]
2619                        .1
2620                        .as_ref()
2621                        .expect("to have SSH authorized key"),
2622                },
2623                SystemUserData::BackendBackup {
2624                    system_user: &raw_user_data[6].0,
2625                    ssh_authorized_key: raw_user_data[6]
2626                        .1
2627                        .as_ref()
2628                        .expect("to have SSH authorized key"),
2629                },
2630                SystemUserData::BackendHermeticMetrics {
2631                    system_user: &raw_user_data[7].0,
2632                },
2633                SystemUserData::BackendSign {
2634                    system_user: &raw_user_data[8].0,
2635                    ssh_authorized_key: raw_user_data[8]
2636                        .1
2637                        .as_ref()
2638                        .expect("to have SSH authorized key"),
2639                },
2640            ]);
2641
2642            assert_eq!(config.system_user_data(), expected);
2643            Ok(())
2644        }
2645
2646        /// Ensures, that [`Config::system_user_ids`] returns system user IDs correctly.
2647        #[rstest]
2648        fn config_system_user_ids(default_config: TestResult<Config>) -> TestResult {
2649            let config = default_config?;
2650            let expected: HashSet<SystemUserId> = HashSet::from_iter([
2651                "signstar-share-holder1".parse()?,
2652                "signstar-share-holder2".parse()?,
2653                "signstar-share-holder3".parse()?,
2654                "signstar-wireguard-download".parse()?,
2655                "yubihsm2-audit-log".parse()?,
2656                "yubihsm2-backup".parse()?,
2657                "yubihsm2-hermetic-audit-log".parse()?,
2658                "yubihsm2-signing".parse()?,
2659            ]);
2660
2661            assert_eq!(
2662                config.system_user_ids(),
2663                expected.iter().collect::<HashSet<_>>()
2664            );
2665            Ok(())
2666        }
2667
2668        /// Ensures, that a valid [`Config`] can be created from a YAML file and turned back into
2669        /// the same YAML string.
2670        ///
2671        /// The configuration file describes a [`SystemConfig`] and a [`YubiHsm2Config`] object.
2672        #[rstest]
2673        #[cfg(not(feature = "_yubihsm2-mockhsm"))]
2674        fn roundtrip_yaml_config(
2675            #[files("../fixtures/config/yubihsm2_backend/*.yaml")] path: PathBuf,
2676        ) -> TestResult {
2677            let config_string = read_to_string(&path)?;
2678            let config = Config::from_file_path(&path)?;
2679
2680            assert_eq!(config.to_yaml_string()?, config_string);
2681
2682            Ok(())
2683        }
2684
2685        /// Ensures, that a valid [`Config`] can be created from a YAML file and turned back into
2686        /// the same YAML string.
2687        ///
2688        /// The configuration file describes a [`SystemConfig`] and a [`YubiHsm2Config`] object.
2689        #[rstest]
2690        #[cfg(feature = "_yubihsm2-mockhsm")]
2691        fn roundtrip_yaml_config_mockhsm(
2692            #[files("../fixtures/config/yubihsm2_mockhsm_backend/*.yaml")] path: PathBuf,
2693        ) -> TestResult {
2694            let config_string = read_to_string(&path)?;
2695            let config = Config::from_file_path(&path)?;
2696
2697            assert_eq!(config.to_yaml_string()?, config_string);
2698
2699            Ok(())
2700        }
2701
2702        /// Ensures, that [`AdministrativeSecretHandling`] and
2703        /// [`NonAdministrativeSecretHandling`]can be retrieved from a
2704        /// [`UserBackendConnection`].
2705        #[rstest]
2706        fn user_backend_connection_secret_handling(
2707            default_config: TestResult<Config>,
2708        ) -> TestResult {
2709            let config = default_config?;
2710            let admin_secret_handling = AdministrativeSecretHandling::ShamirsSecretSharing {
2711                number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
2712                threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
2713            };
2714            let non_admin_secret_handling = NonAdministrativeSecretHandling::SystemdCreds;
2715
2716            let user_backend_connection = config
2717                .user_backend_connection(&"yubihsm2-signing".parse()?)
2718                .expect("there to be a mapping of the requested name");
2719
2720            assert_eq!(
2721                user_backend_connection.admin_secret_handling(),
2722                admin_secret_handling
2723            );
2724            assert_eq!(
2725                user_backend_connection.non_admin_secret_handling(),
2726                non_admin_secret_handling
2727            );
2728
2729            Ok(())
2730        }
2731
2732        /// Ensures, that [`SystemUserConfigState`] can be created from [`Config`].
2733        #[rstest]
2734        fn system_user_config_state_from_config(default_config: TestResult<Config>) -> TestResult {
2735            let config = default_config?;
2736            let state = SystemUserConfigState::from(&config);
2737
2738            assert_eq!(state.system_user_data, config.system_user_data(),);
2739            Ok(())
2740        }
2741    }
2742
2743    /// Tests, that are only available when using all available backends.
2744    #[cfg(all(feature = "nethsm", feature = "yubihsm2"))]
2745    mod all_backends {
2746        use log::LevelFilter;
2747        use pretty_assertions::assert_eq;
2748        use signstar_common::logging::setup_terminal_logging;
2749
2750        use super::*;
2751        use crate::config::{
2752            MappingAuthorizedKeyEntry,
2753            MappingSystemUserId,
2754            SystemUserData,
2755            traits::ConfigSystemUserData,
2756        };
2757
2758        /// Creates a default [`Config`] for testing purposes.
2759        #[fixture]
2760        fn default_config(
2761            default_system_config: TestResult<SystemConfig>,
2762            default_nethsm_config: TestResult<NetHsmConfig>,
2763            default_yubihsm2_config: TestResult<YubiHsm2Config>,
2764        ) -> TestResult<Config> {
2765            Ok(ConfigBuilder::new(default_system_config?)
2766                .set_nethsm_config(default_nethsm_config?)
2767                .set_yubihsm2_config(default_yubihsm2_config?)
2768                .finish()?)
2769        }
2770
2771        /// List of raw data required to create [`SystemUserData`] for each item in the default
2772        /// [`Config`].
2773        #[fixture]
2774        fn raw_user_data(
2775            raw_user_data_system: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
2776            raw_user_data_nethsm: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
2777            raw_user_data_yubihsm2: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
2778        ) -> TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>> {
2779            let mut data = raw_user_data_system?;
2780            data.extend(raw_user_data_nethsm?);
2781            data.extend(raw_user_data_yubihsm2?);
2782            Ok(data)
2783        }
2784
2785        /// Ensures that [`MappingSystemUserId`] for [`UserBackendConnection`] works as intended.
2786        #[rstest]
2787        fn user_backend_connection_system_user_id(
2788            raw_user_data_nethsm: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
2789            raw_user_data_yubihsm2: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
2790        ) -> TestResult {
2791            let raw_user_data_nethsm = raw_user_data_nethsm?;
2792            let data = UserBackendConnection::NetHsm {
2793                admin_secret_handling: AdministrativeSecretHandling::Plaintext,
2794                non_admin_secret_handling: NonAdministrativeSecretHandling::Plaintext,
2795                connections: BTreeSet::from_iter([Connection::new(
2796                    "https://nethsm1.example.org/".parse()?,
2797                    ConnectionSecurity::Unsafe,
2798                )]),
2799                mapping: NetHsmUserMapping::Backup {
2800                    backend_user: "backup".parse()?,
2801                    ssh_authorized_key: raw_user_data_nethsm[1]
2802                        .1
2803                        .clone()
2804                        .expect("to have an SSH authorized key"),
2805                    system_user: raw_user_data_nethsm[1].0.clone(),
2806                },
2807            };
2808            assert_eq!(data.system_user_id(), Some(&raw_user_data_nethsm[1].0));
2809
2810            let raw_user_data_yubihsm2 = raw_user_data_yubihsm2?;
2811            let data = UserBackendConnection::YubiHsm2 {
2812                admin_secret_handling: AdministrativeSecretHandling::Plaintext,
2813                non_admin_secret_handling: NonAdministrativeSecretHandling::Plaintext,
2814                connections: BTreeSet::from_iter([YubiHsm2Connection::Usb {
2815                    serial_number: "0123456789".parse()?,
2816                }]),
2817                mapping: YubiHsm2UserMapping::AuditLog {
2818                    authentication_key_id: "1".parse()?,
2819                    ssh_authorized_key: raw_user_data_yubihsm2[1]
2820                        .1
2821                        .clone()
2822                        .expect("to have an SSH authorized key"),
2823                    system_user: raw_user_data_yubihsm2[1].0.clone(),
2824                },
2825            };
2826            assert_eq!(data.system_user_id(), Some(&raw_user_data_yubihsm2[1].0));
2827
2828            Ok(())
2829        }
2830
2831        /// Ensures that [`MappingAuthorizedKeyEntry`] for [`UserBackendConnection`] works as
2832        /// intended.
2833        #[rstest]
2834        fn user_backend_connection_authorized_key_entry(
2835            raw_user_data_nethsm: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
2836            raw_user_data_yubihsm2: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
2837        ) -> TestResult {
2838            let raw_user_data_nethsm = raw_user_data_nethsm?;
2839            let data = UserBackendConnection::NetHsm {
2840                admin_secret_handling: AdministrativeSecretHandling::Plaintext,
2841                non_admin_secret_handling: NonAdministrativeSecretHandling::Plaintext,
2842                connections: BTreeSet::from_iter([Connection::new(
2843                    "https://nethsm1.example.org/".parse()?,
2844                    ConnectionSecurity::Unsafe,
2845                )]),
2846                mapping: NetHsmUserMapping::Backup {
2847                    backend_user: "backup".parse()?,
2848                    ssh_authorized_key: raw_user_data_nethsm[1]
2849                        .1
2850                        .clone()
2851                        .expect("to have an SSH authorized key"),
2852                    system_user: raw_user_data_nethsm[1].0.clone(),
2853                },
2854            };
2855            assert_eq!(
2856                data.authorized_key_entry(),
2857                Some(
2858                    raw_user_data_nethsm[1]
2859                        .1
2860                        .as_ref()
2861                        .expect("to have an SSH authorized key")
2862                )
2863            );
2864
2865            let raw_user_data_yubihsm2 = raw_user_data_yubihsm2?;
2866            let data = UserBackendConnection::YubiHsm2 {
2867                admin_secret_handling: AdministrativeSecretHandling::Plaintext,
2868                non_admin_secret_handling: NonAdministrativeSecretHandling::Plaintext,
2869                connections: BTreeSet::from_iter([YubiHsm2Connection::Usb {
2870                    serial_number: "0123456789".parse()?,
2871                }]),
2872                mapping: YubiHsm2UserMapping::AuditLog {
2873                    authentication_key_id: "1".parse()?,
2874                    ssh_authorized_key: raw_user_data_yubihsm2[1]
2875                        .1
2876                        .clone()
2877                        .expect("to have an SSH authorized key"),
2878                    system_user: raw_user_data_yubihsm2[1].0.clone(),
2879                },
2880            };
2881            assert_eq!(
2882                data.authorized_key_entry(),
2883                Some(
2884                    raw_user_data_yubihsm2[1]
2885                        .1
2886                        .as_ref()
2887                        .expect("to have an SSH authorized key")
2888                )
2889            );
2890
2891            Ok(())
2892        }
2893
2894        /// Ensures, that [`ConfigBuilder::finish`] fails on issues with overlapping data in
2895        /// configuration components.
2896        ///
2897        /// Here, custom [`NetHsmConfig`] and [`YubiHsm2Config`] objects are staged together with a
2898        /// default [`SystemConfig`] (created by [`default_system_config`]) to create a failure
2899        /// scenario.
2900        #[rstest]
2901        #[case::backend_overlap_duplicate_system_users_two_duplicate_ssh_public_keys(
2902            "Configuration with system-wide, NetHSM and YubiHSM2 configuration has two duplicate system users and two duplicate SSH public keys in the backends",
2903            NetHsmConfig::new(
2904                BTreeSet::from_iter([
2905                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
2906                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
2907                ]),
2908                BTreeSet::from_iter([
2909                    NetHsmUserMapping::Admin("admin".parse()?),
2910                    NetHsmUserMapping::Backup{
2911                        backend_user: "backup".parse()?,
2912                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
2913                        system_user: "duplicate-backup".parse()?,
2914                    },
2915                    NetHsmUserMapping::HermeticMetrics {
2916                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
2917                        system_user: "nethsm-hermetic-metrics".parse()?,
2918                    },
2919                    NetHsmUserMapping::Metrics {
2920                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
2921                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
2922                        system_user: "duplicate-metrics".parse()?,
2923                    },
2924                    NetHsmUserMapping::Signing {
2925                        backend_user: "signing".parse()?,
2926                        signing_key_id: "signing1".parse()?,
2927                        key_setup: SigningKeySetup::new(
2928                            KeyType::Curve25519,
2929                            vec![KeyMechanism::EdDsaSignature],
2930                            None,
2931                            SignatureType::EdDsa,
2932                            CryptographicKeyContext::OpenPgp {
2933                                user_ids: OpenPgpUserIdList::new(vec![
2934                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2935                                ])?,
2936                                version: "v4".parse()?,
2937                                notations: Default::default(),
2938                            },
2939                        )?,
2940                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
2941                        system_user: "nethsm-signing".parse()?,
2942                        tag: "nethsm-signing1".to_string(),
2943                    }
2944                ]),
2945            )?,
2946            YubiHsm2Config::new(
2947                BTreeSet::from_iter([
2948                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
2949                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
2950                ]),
2951                BTreeSet::from_iter([
2952                    YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
2953                    YubiHsm2UserMapping::AuditLog {
2954                        authentication_key_id: "3".parse()?,
2955                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
2956                        system_user: "duplicate-metrics".parse()?,
2957                    },
2958                    YubiHsm2UserMapping::Backup {
2959                        authentication_key_id: "2".parse()?,
2960                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
2961                        system_user: "duplicate-backup".parse()?,
2962                    },
2963                    YubiHsm2UserMapping::HermeticAuditLog {
2964                        authentication_key_id: "4".parse()?,
2965                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
2966                    },
2967                    YubiHsm2UserMapping::Signing {
2968                        authentication_key_id: "5".parse()?,
2969                        key_setup: SigningKeySetup::new(
2970                            KeyType::Curve25519,
2971                            vec![KeyMechanism::EdDsaSignature],
2972                            None,
2973                            SignatureType::EdDsa,
2974                            CryptographicKeyContext::OpenPgp {
2975                                user_ids: OpenPgpUserIdList::new(vec![
2976                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
2977                                ])?,
2978                                version: "v4".parse()?,
2979                                notations: Default::default(),
2980                            },
2981                        )?,
2982                        signing_key_id: "1".parse()?,
2983                        domain: Domain::One,
2984                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
2985                        system_user: "yubihsm2-signing".parse()? }
2986                ]),
2987            )?,
2988        )]
2989        #[case::backend_overlap_one_duplicate_system_user(
2990            "Configuration with system-wide, NetHSM and YubiHSM2 configuration has one duplicate system user in the backends",
2991            NetHsmConfig::new(
2992                BTreeSet::from_iter([
2993                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
2994                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
2995                ]),
2996                BTreeSet::from_iter([
2997                    NetHsmUserMapping::Admin("admin".parse()?),
2998                    NetHsmUserMapping::Backup{
2999                        backend_user: "backup".parse()?,
3000                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
3001                        system_user: "duplicate-backup".parse()?,
3002                    },
3003                    NetHsmUserMapping::HermeticMetrics {
3004                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
3005                        system_user: "nethsm-hermetic-metrics".parse()?,
3006                    },
3007                    NetHsmUserMapping::Metrics {
3008                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
3009                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
3010                        system_user: "nethsm-metrics".parse()?,
3011                    },
3012                    NetHsmUserMapping::Signing {
3013                        backend_user: "signing".parse()?,
3014                        signing_key_id: "signing1".parse()?,
3015                        key_setup: SigningKeySetup::new(
3016                            KeyType::Curve25519,
3017                            vec![KeyMechanism::EdDsaSignature],
3018                            None,
3019                            SignatureType::EdDsa,
3020                            CryptographicKeyContext::OpenPgp {
3021                                user_ids: OpenPgpUserIdList::new(vec![
3022                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3023                                ])?,
3024                                version: "v4".parse()?,
3025                                notations: Default::default(),
3026                            },
3027                        )?,
3028                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
3029                        system_user: "nethsm-signing".parse()?,
3030                        tag: "nethsm-signing1".to_string(),
3031                    }
3032                ]),
3033            )?,
3034            YubiHsm2Config::new(
3035                BTreeSet::from_iter([
3036                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3037                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3038                ]),
3039                BTreeSet::from_iter([
3040                    YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
3041                    YubiHsm2UserMapping::AuditLog {
3042                        authentication_key_id: "3".parse()?,
3043                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
3044                        system_user: "yubihsm2-audit-log".parse()?,
3045                    },
3046                    YubiHsm2UserMapping::Backup {
3047                        authentication_key_id: "2".parse()?,
3048                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
3049                        system_user: "duplicate-backup".parse()?,
3050                    },
3051                    YubiHsm2UserMapping::HermeticAuditLog {
3052                        authentication_key_id: "4".parse()?,
3053                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
3054                    },
3055                    YubiHsm2UserMapping::Signing {
3056                        authentication_key_id: "5".parse()?,
3057                        key_setup: SigningKeySetup::new(
3058                            KeyType::Curve25519,
3059                            vec![KeyMechanism::EdDsaSignature],
3060                            None,
3061                            SignatureType::EdDsa,
3062                            CryptographicKeyContext::OpenPgp {
3063                                user_ids: OpenPgpUserIdList::new(vec![
3064                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3065                                ])?,
3066                                version: "v4".parse()?,
3067                                notations: Default::default(),
3068                            },
3069                        )?,
3070                        signing_key_id: "1".parse()?,
3071                        domain: Domain::One,
3072                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
3073                        system_user: "yubihsm2-signing".parse()? }
3074                ]),
3075            )?,
3076        )]
3077        #[case::system_overlap_duplicate_system_users_two_duplicate_ssh_public_keys(
3078            "Configuration with system-wide, NetHSM and YubiHSM2 configuration has two duplicate system users and two duplicate SSH public keys in the system and the backends",
3079            NetHsmConfig::new(
3080                BTreeSet::from_iter([
3081                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3082                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3083                ]),
3084                BTreeSet::from_iter([
3085                    NetHsmUserMapping::Admin("admin".parse()?),
3086                    NetHsmUserMapping::Backup{
3087                        backend_user: "backup".parse()?,
3088                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAN54Gd1jMz+yNDjBRwX1SnOtWuUsVF64RJIeYJ8DI7b user@host".parse()?,
3089                        system_user: "duplicate-backup".parse()?,
3090                    },
3091                    NetHsmUserMapping::Metrics {
3092                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
3093                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
3094                        system_user: "duplicate-metrics".parse()?,
3095                    },
3096                    NetHsmUserMapping::HermeticMetrics {
3097                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
3098                        system_user: "nethsm-hermetic-metrics".parse()?,
3099                    },
3100                    NetHsmUserMapping::Signing {
3101                        backend_user: "signing".parse()?,
3102                        signing_key_id: "signing1".parse()?,
3103                        key_setup: SigningKeySetup::new(
3104                            KeyType::Curve25519,
3105                            vec![KeyMechanism::EdDsaSignature],
3106                            None,
3107                            SignatureType::EdDsa,
3108                            CryptographicKeyContext::OpenPgp {
3109                                user_ids: OpenPgpUserIdList::new(vec![
3110                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3111                                ])?,
3112                                version: "v4".parse()?,
3113                                notations: Default::default(),
3114                            },
3115                        )?,
3116                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
3117                        system_user: "nethsm-signing".parse()?,
3118                        tag: "nethsm-signing1".to_string(),
3119                    }
3120                ]),
3121            )?,
3122            YubiHsm2Config::new(
3123                BTreeSet::from_iter([
3124                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3125                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3126                ]),
3127                BTreeSet::from_iter([
3128                    YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
3129                    YubiHsm2UserMapping::Backup {
3130                        authentication_key_id: "2".parse()?,
3131                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAN54Gd1jMz+yNDjBRwX1SnOtWuUsVF64RJIeYJ8DI7b user@host".parse()?,
3132                        system_user: "duplicate-backup".parse()?,
3133                    },
3134                    YubiHsm2UserMapping::AuditLog {
3135                        authentication_key_id: "3".parse()?,
3136                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
3137                        system_user: "duplicate-metrics".parse()?,
3138                    },
3139                    YubiHsm2UserMapping::HermeticAuditLog {
3140                        authentication_key_id: "4".parse()?,
3141                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
3142                    },
3143                    YubiHsm2UserMapping::Signing {
3144                        authentication_key_id: "5".parse()?,
3145                        key_setup: SigningKeySetup::new(
3146                            KeyType::Curve25519,
3147                            vec![KeyMechanism::EdDsaSignature],
3148                            None,
3149                            SignatureType::EdDsa,
3150                            CryptographicKeyContext::OpenPgp {
3151                                user_ids: OpenPgpUserIdList::new(vec![
3152                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3153                                ])?,
3154                                version: "v4".parse()?,
3155                                notations: Default::default(),
3156                            },
3157                        )?,
3158                        signing_key_id: "1".parse()?,
3159                        domain: Domain::One,
3160                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
3161                        system_user: "yubihsm2-signing".parse()? }
3162                ]),
3163            )?,
3164        )]
3165        fn config_fails_validation(
3166            default_system_config: TestResult<SystemConfig>,
3167            #[case] description: &str,
3168            #[case] nethsm_config: NetHsmConfig,
3169            #[case] yubihsm2_config: YubiHsm2Config,
3170        ) -> TestResult {
3171            let error_message = match ConfigBuilder::new(default_system_config?)
3172                .set_nethsm_config(nethsm_config)
3173                .set_yubihsm2_config(yubihsm2_config)
3174                .finish()
3175            {
3176                Err(error) => error.to_string(),
3177                Ok(config) => panic!(
3178                    "Expected to fail with Error::Validation, but succeeded instead: {}",
3179                    config.to_yaml_string()?
3180                ),
3181            };
3182
3183            with_settings!({
3184                description => description,
3185                snapshot_path => SNAPSHOT_PATH,
3186                prepend_module_to_snapshot => false,
3187            }, {
3188                assert_snapshot!(current().name().expect("current thread should have a name").to_string().replace("::", "__"), error_message);
3189            });
3190
3191            Ok(())
3192        }
3193
3194        /// Ensures, that an optional [`UserBackendConnection`] can be retrieved from a [`Config`].
3195        #[rstest]
3196        #[case::nethsm_signing(
3197            "nethsm-signing",
3198            Some(UserBackendConnection::NetHsm {
3199                admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3200                    number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3201                    threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3202                },
3203                non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3204                connections: BTreeSet::from_iter([
3205                    Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3206                    Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3207                ]),
3208                mapping: NetHsmUserMapping::Signing {
3209                    backend_user: "signing".parse()?,
3210                    signing_key_id: "signing1".parse()?,
3211                    key_setup: SigningKeySetup::new(
3212                        KeyType::Curve25519,
3213                        vec![KeyMechanism::EdDsaSignature],
3214                        None,
3215                        SignatureType::EdDsa,
3216                        CryptographicKeyContext::OpenPgp {
3217                            user_ids: OpenPgpUserIdList::new(vec![
3218                                "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3219                            ])?,
3220                            version: "v4".parse()?,
3221                            notations: Default::default(),
3222                        },
3223                    )?,
3224                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
3225                    system_user: "nethsm-signing".parse()?,
3226                    tag: "signing1".to_string(),
3227                }
3228            })
3229        )]
3230        #[case::yubihsm2_signing(
3231            "yubihsm2-signing",
3232            Some(UserBackendConnection::YubiHsm2 {
3233                admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3234                    number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3235                    threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3236                },
3237                non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3238                connections: BTreeSet::from_iter([
3239                    YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3240                    YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3241                ]),
3242                mapping: YubiHsm2UserMapping::Signing {
3243                    authentication_key_id: "5".parse()?,
3244                    signing_key_id: "1".parse()?,
3245                    key_setup: SigningKeySetup::new(
3246                        KeyType::Curve25519,
3247                        vec![KeyMechanism::EdDsaSignature],
3248                        None,
3249                        SignatureType::EdDsa,
3250                        CryptographicKeyContext::OpenPgp {
3251                            user_ids: OpenPgpUserIdList::new(vec![
3252                                "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3253                            ])?,
3254                            version: "v4".parse()?,
3255                            notations: Default::default(),
3256                        },
3257                    )?,
3258                    ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
3259                    system_user: "yubihsm2-signing".parse()?,
3260                    domain: Domain::One,
3261                }
3262            })
3263        )]
3264        #[case::none("foo", None)]
3265        fn config_user_backend_connection(
3266            default_config: TestResult<Config>,
3267            #[case] system_user: &str,
3268            #[case] expected_connection: Option<UserBackendConnection>,
3269        ) -> TestResult {
3270            let config = default_config?;
3271            assert_eq!(
3272                expected_connection,
3273                config.user_backend_connection(&system_user.parse()?)
3274            );
3275
3276            Ok(())
3277        }
3278
3279        /// Ensures, that [`Config::user_backend_connections`] returns the correct list of
3280        /// [`UserBackendConnection`] items according to a set of [`UserBackendConnectionFilter`].
3281        #[rstest]
3282        #[case::no_filter(
3283            &[],
3284            vec![
3285                UserBackendConnection::NetHsm {
3286                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3287                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3288                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3289                    },
3290                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3291                    connections: BTreeSet::from_iter([
3292                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3293                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3294                    ]),
3295                    mapping: NetHsmUserMapping::Admin("admin".parse()?)
3296                },
3297                UserBackendConnection::NetHsm {
3298                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3299                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3300                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3301                    },
3302                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3303                    connections: BTreeSet::from_iter([
3304                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3305                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3306                    ]),
3307                    mapping: NetHsmUserMapping::Backup{
3308                        backend_user: "backup".parse()?,
3309                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
3310                        system_user: "nethsm-backup".parse()?,
3311                    }
3312                },
3313                UserBackendConnection::NetHsm {
3314                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3315                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3316                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3317                    },
3318                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3319                    connections: BTreeSet::from_iter([
3320                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3321                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3322                    ]),
3323                    mapping: NetHsmUserMapping::HermeticMetrics {
3324                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
3325                        system_user: "nethsm-hermetic-metrics".parse()?,
3326                    }
3327                },
3328                UserBackendConnection::NetHsm {
3329                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3330                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3331                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3332                    },
3333                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3334                    connections: BTreeSet::from_iter([
3335                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3336                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3337                    ]),
3338                    mapping: NetHsmUserMapping::Metrics {
3339                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
3340                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
3341                        system_user: "nethsm-metrics".parse()?,
3342                    }
3343                },
3344                UserBackendConnection::NetHsm {
3345                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3346                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3347                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3348                    },
3349                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3350                    connections: BTreeSet::from_iter([
3351                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3352                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3353                    ]),
3354                    mapping: NetHsmUserMapping::Signing {
3355                        backend_user: "signing".parse()?,
3356                        signing_key_id: "signing1".parse()?,
3357                        key_setup: SigningKeySetup::new(
3358                            KeyType::Curve25519,
3359                            vec![KeyMechanism::EdDsaSignature],
3360                            None,
3361                            SignatureType::EdDsa,
3362                            CryptographicKeyContext::OpenPgp {
3363                                user_ids: OpenPgpUserIdList::new(vec![
3364                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3365                                ])?,
3366                                version: "v4".parse()?,
3367                                notations: Default::default(),
3368                            },
3369                        )?,
3370                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
3371                        system_user: "nethsm-signing".parse()?,
3372                        tag: "signing1".to_string(),
3373                    }
3374                },
3375                UserBackendConnection::YubiHsm2 {
3376                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3377                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3378                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3379                    },
3380                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3381                    connections: BTreeSet::from_iter([
3382                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3383                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3384                    ]),
3385                    mapping: YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
3386                },
3387                UserBackendConnection::YubiHsm2 {
3388                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3389                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3390                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3391                    },
3392                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3393                    connections: BTreeSet::from_iter([
3394                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3395                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3396                    ]),
3397                    mapping: YubiHsm2UserMapping::AuditLog {
3398                        authentication_key_id: "3".parse()?,
3399                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
3400                        system_user: "yubihsm2-audit-log".parse()?,
3401                    },
3402                },
3403                UserBackendConnection::YubiHsm2 {
3404                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3405                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3406                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3407                    },
3408                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3409                    connections: BTreeSet::from_iter([
3410                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3411                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3412                    ]),
3413                    mapping: YubiHsm2UserMapping::Backup{
3414                        authentication_key_id: "2".parse()?,
3415                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
3416                        system_user: "yubihsm2-backup".parse()?,
3417                    },
3418                },
3419                UserBackendConnection::YubiHsm2 {
3420                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3421                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3422                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3423                    },
3424                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3425                    connections: BTreeSet::from_iter([
3426                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3427                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3428                    ]),
3429                    mapping: YubiHsm2UserMapping::HermeticAuditLog {
3430                        authentication_key_id: "4".parse()?,
3431                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
3432                    },
3433                },
3434                UserBackendConnection::YubiHsm2 {
3435                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3436                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3437                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3438                    },
3439                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3440                    connections: BTreeSet::from_iter([
3441                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3442                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3443                    ]),
3444                    mapping: YubiHsm2UserMapping::Signing {
3445                        authentication_key_id: "5".parse()?,
3446                        signing_key_id: "1".parse()?,
3447                        key_setup: SigningKeySetup::new(
3448                            KeyType::Curve25519,
3449                            vec![KeyMechanism::EdDsaSignature],
3450                            None,
3451                            SignatureType::EdDsa,
3452                            CryptographicKeyContext::OpenPgp {
3453                                user_ids: OpenPgpUserIdList::new(vec![
3454                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3455                                ])?,
3456                                version: "v4".parse()?,
3457                                notations: Default::default(),
3458                            },
3459                        )?,
3460                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
3461                        system_user: "yubihsm2-signing".parse()?,
3462                        domain: Domain::One,
3463                    }
3464                },
3465            ],
3466        )]
3467        #[case::filter_admin(
3468            &[UserBackendConnectionFilter::Admin],
3469            vec![
3470                UserBackendConnection::NetHsm {
3471                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3472                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3473                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3474                    },
3475                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3476                    connections: BTreeSet::from_iter([
3477                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3478                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3479                    ]),
3480                    mapping: NetHsmUserMapping::Admin("admin".parse()?)
3481                },
3482                UserBackendConnection::YubiHsm2 {
3483                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3484                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3485                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3486                    },
3487                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3488                    connections: BTreeSet::from_iter([
3489                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3490                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3491                    ]),
3492                    mapping: YubiHsm2UserMapping::Admin { authentication_key_id: "1".parse()? },
3493                },
3494            ],
3495        )]
3496        #[case::filter_non_admin(
3497            &[UserBackendConnectionFilter::NonAdmin],
3498            vec![
3499                UserBackendConnection::NetHsm {
3500                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3501                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3502                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3503                    },
3504                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3505                    connections: BTreeSet::from_iter([
3506                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3507                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3508                    ]),
3509                    mapping: NetHsmUserMapping::Backup{
3510                        backend_user: "backup".parse()?,
3511                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
3512                        system_user: "nethsm-backup".parse()?,
3513                    }
3514                },
3515                UserBackendConnection::NetHsm {
3516                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3517                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3518                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3519                    },
3520                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3521                    connections: BTreeSet::from_iter([
3522                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3523                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3524                    ]),
3525                    mapping: NetHsmUserMapping::HermeticMetrics {
3526                        backend_users: NetHsmMetricsUsers::new("hermeticmetrics".parse()?, vec!["hermetickeymetrics".parse()?])?,
3527                        system_user: "nethsm-hermetic-metrics".parse()?,
3528                    }
3529                },
3530                UserBackendConnection::NetHsm {
3531                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3532                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3533                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3534                    },
3535                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3536                    connections: BTreeSet::from_iter([
3537                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3538                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3539                    ]),
3540                    mapping: NetHsmUserMapping::Metrics {
3541                        backend_users: NetHsmMetricsUsers::new("metrics".parse()?, vec!["keymetrics".parse()?])?,
3542                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
3543                        system_user: "nethsm-metrics".parse()?,
3544                    }
3545                },
3546                UserBackendConnection::NetHsm {
3547                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3548                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3549                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3550                    },
3551                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3552                    connections: BTreeSet::from_iter([
3553                        Connection::new("https://nethsm1.example.org/".parse()?, ConnectionSecurity::Unsafe),
3554                        Connection::new("https://nethsm2.example.org/".parse()?, ConnectionSecurity::Unsafe),
3555                    ]),
3556                    mapping: NetHsmUserMapping::Signing {
3557                        backend_user: "signing".parse()?,
3558                        signing_key_id: "signing1".parse()?,
3559                        key_setup: SigningKeySetup::new(
3560                            KeyType::Curve25519,
3561                            vec![KeyMechanism::EdDsaSignature],
3562                            None,
3563                            SignatureType::EdDsa,
3564                            CryptographicKeyContext::OpenPgp {
3565                                user_ids: OpenPgpUserIdList::new(vec![
3566                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3567                                ])?,
3568                                version: "v4".parse()?,
3569                                notations: Default::default(),
3570                            },
3571                        )?,
3572                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
3573                        system_user: "nethsm-signing".parse()?,
3574                        tag: "signing1".to_string(),
3575                    }
3576                },
3577                UserBackendConnection::YubiHsm2 {
3578                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3579                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3580                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3581                    },
3582                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3583                    connections: BTreeSet::from_iter([
3584                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3585                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3586                    ]),
3587                    mapping: YubiHsm2UserMapping::AuditLog {
3588                        authentication_key_id: "3".parse()?,
3589                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
3590                        system_user: "yubihsm2-audit-log".parse()?,
3591                    },
3592                },
3593                UserBackendConnection::YubiHsm2 {
3594                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3595                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3596                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3597                    },
3598                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3599                    connections: BTreeSet::from_iter([
3600                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3601                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3602                    ]),
3603                    mapping: YubiHsm2UserMapping::Backup{
3604                        authentication_key_id: "2".parse()?,
3605                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
3606                        system_user: "yubihsm2-backup".parse()?,
3607                    },
3608                },
3609                UserBackendConnection::YubiHsm2 {
3610                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3611                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3612                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3613                    },
3614                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3615                    connections: BTreeSet::from_iter([
3616                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3617                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3618                    ]),
3619                    mapping: YubiHsm2UserMapping::HermeticAuditLog {
3620                        authentication_key_id: "4".parse()?,
3621                        system_user: "yubihsm2-hermetic-audit-log".parse()?,
3622                    },
3623                },
3624                UserBackendConnection::YubiHsm2 {
3625                    admin_secret_handling: AdministrativeSecretHandling::ShamirsSecretSharing {
3626                        number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3627                        threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3628                    },
3629                    non_admin_secret_handling: NonAdministrativeSecretHandling::SystemdCreds,
3630                    connections: BTreeSet::from_iter([
3631                        YubiHsm2Connection::Usb {serial_number: "0012345678".parse()? },
3632                        YubiHsm2Connection::Usb {serial_number: "0087654321".parse()? },
3633                    ]),
3634                    mapping: YubiHsm2UserMapping::Signing {
3635                        authentication_key_id: "5".parse()?,
3636                        signing_key_id: "1".parse()?,
3637                        key_setup: SigningKeySetup::new(
3638                            KeyType::Curve25519,
3639                            vec![KeyMechanism::EdDsaSignature],
3640                            None,
3641                            SignatureType::EdDsa,
3642                            CryptographicKeyContext::OpenPgp {
3643                                user_ids: OpenPgpUserIdList::new(vec![
3644                                    "Foobar McFooface <foobar@mcfooface.org>".parse()?,
3645                                ])?,
3646                                version: "v4".parse()?,
3647                                notations: Default::default(),
3648                            },
3649                        )?,
3650                        ssh_authorized_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
3651                        system_user: "yubihsm2-signing".parse()?,
3652                        domain: Domain::One,
3653                    }
3654                },
3655            ],
3656        )]
3657        fn config_user_backend_connections(
3658            default_config: TestResult<Config>,
3659            #[case] filters: &[UserBackendConnectionFilter],
3660            #[case] expected_connections: Vec<UserBackendConnection>,
3661        ) -> TestResult {
3662            setup_terminal_logging(LevelFilter::Debug)?;
3663            let config = default_config?;
3664
3665            assert_eq!(
3666                expected_connections,
3667                config.user_backend_connections(filters)
3668            );
3669
3670            Ok(())
3671        }
3672
3673        /// Ensures, that a [`Config`] object leads to a specific YAML output.
3674        ///
3675        /// In this particular case, a [`SystemConfig`], a [`NetHsmConfig`] and a [`YubiHsm2Config`]
3676        /// object are present.
3677        #[rstest]
3678        fn config_to_yaml_string(
3679            default_system_config: TestResult<SystemConfig>,
3680            default_nethsm_config: TestResult<NetHsmConfig>,
3681            default_yubihsm2_config: TestResult<YubiHsm2Config>,
3682        ) -> TestResult {
3683            let config = ConfigBuilder::new(default_system_config?)
3684                .set_nethsm_config(default_nethsm_config?)
3685                .set_yubihsm2_config(default_yubihsm2_config?)
3686                .finish()?;
3687            let config_str = config.to_yaml_string()?;
3688
3689            with_settings!({
3690                description => "Configuration with system-wide, NetHSM and YubiHSM2 configuration",
3691                snapshot_path => SNAPSHOT_PATH,
3692                prepend_module_to_snapshot => false,
3693            }, {
3694                assert_snapshot!(current().name().expect("current thread should have a name").to_string().replace("::", "__"), config_str);
3695            });
3696
3697            Ok(())
3698        }
3699
3700        /// Ensures, that [`Config::authorized_key_entries`] returns SSH authorized key entries
3701        /// correctly.
3702        #[rstest]
3703        fn config_authorized_key_entries(default_config: TestResult<Config>) -> TestResult {
3704            let config = default_config?;
3705            let expected: HashSet<AuthorizedKeyEntry> = HashSet::from_iter([
3706                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAN54Gd1jMz+yNDjBRwX1SnOtWuUsVF64RJIeYJ8DI7b user@host".parse()?,
3707                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPDgwGfIRBAsOUuDEZw/uJQZSwOYr4sg2DAZpcc7MfOj user@host".parse()?,
3708                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILWqWyMCk5BdSl1c3KYoLEokKr7qNVPbI1IbBhgEBQj5 user@host".parse()?,
3709                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh9BTe81DC6A0YZALsq9dWcyl6xjjqlxWPwlExTFgBt user@host".parse()?,
3710                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHxR0Oc+SWXkEvvZPitc6NvjvykgiKc9iauRI7tLYvcp user@host".parse()?,
3711                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIETxhCqeZhfzFLfH0KFyw3u/w/dkRBUrft8tQm7DEVzY user@host".parse()?,
3712                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIClIXZdx0aDOPcIQA+6Qx68cwSUgGTL3TWzDSX3qUEOQ user@host".parse()?,
3713                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPkpXKiNhy39A3bZ1u19a5d4sFwYMBkWQyCbzgUfdKBm user@host".parse()?,
3714                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOOCMo+ODRchqIiXm89TxF7avi+LXRtqWZdBAvJ1SG5g user@host".parse()?,
3715                "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOh96uFTnvX6P1ebbLxXFvy6sK7qFqlMHDOuJ0TmuXQQ user@host".parse()?,
3716            ]);
3717
3718            assert_eq!(
3719                config.authorized_key_entries(),
3720                expected.iter().collect::<HashSet<_>>()
3721            );
3722            Ok(())
3723        }
3724
3725        /// Ensures, that [`Config::system_user_data`] returns [`SystemUserData`] entries correctly.
3726        #[rstest]
3727        fn config_system_user_data(
3728            default_config: TestResult<Config>,
3729            raw_user_data: TestResult<Vec<(SystemUserId, Option<AuthorizedKeyEntry>)>>,
3730        ) -> TestResult {
3731            let config = default_config?;
3732            let raw_user_data = raw_user_data?;
3733            let expected: HashSet<SystemUserData> = HashSet::from_iter([
3734                SystemUserData::HostShareholder {
3735                    system_user: &raw_user_data[0].0,
3736                    ssh_authorized_key: raw_user_data[0]
3737                        .1
3738                        .as_ref()
3739                        .expect("to have SSH authorized key"),
3740                },
3741                SystemUserData::HostShareholder {
3742                    system_user: &raw_user_data[1].0,
3743                    ssh_authorized_key: raw_user_data[1]
3744                        .1
3745                        .as_ref()
3746                        .expect("to have SSH authorized key"),
3747                },
3748                SystemUserData::HostShareholder {
3749                    system_user: &raw_user_data[2].0,
3750                    ssh_authorized_key: raw_user_data[2]
3751                        .1
3752                        .as_ref()
3753                        .expect("to have SSH authorized key"),
3754                },
3755                SystemUserData::HostDownloadNetworkConfig {
3756                    system_user: &raw_user_data[3].0,
3757                    ssh_authorized_key: raw_user_data[3]
3758                        .1
3759                        .as_ref()
3760                        .expect("to have SSH authorized key"),
3761                },
3762                SystemUserData::BackendAdmin {
3763                    system_user: raw_user_data[4].0.clone(),
3764                },
3765                SystemUserData::BackendBackup {
3766                    system_user: &raw_user_data[5].0,
3767                    ssh_authorized_key: raw_user_data[5]
3768                        .1
3769                        .as_ref()
3770                        .expect("to have SSH authorized key"),
3771                },
3772                SystemUserData::BackendHermeticMetrics {
3773                    system_user: &raw_user_data[6].0,
3774                },
3775                SystemUserData::BackendMetrics {
3776                    system_user: &raw_user_data[7].0,
3777                    ssh_authorized_key: raw_user_data[7]
3778                        .1
3779                        .as_ref()
3780                        .expect("to have SSH authorized key"),
3781                },
3782                SystemUserData::BackendSign {
3783                    system_user: &raw_user_data[8].0,
3784                    ssh_authorized_key: raw_user_data[8]
3785                        .1
3786                        .as_ref()
3787                        .expect("to have SSH authorized key"),
3788                },
3789                SystemUserData::BackendMetrics {
3790                    system_user: &raw_user_data[10].0,
3791                    ssh_authorized_key: raw_user_data[10]
3792                        .1
3793                        .as_ref()
3794                        .expect("to have SSH authorized key"),
3795                },
3796                SystemUserData::BackendBackup {
3797                    system_user: &raw_user_data[11].0,
3798                    ssh_authorized_key: raw_user_data[11]
3799                        .1
3800                        .as_ref()
3801                        .expect("to have SSH authorized key"),
3802                },
3803                SystemUserData::BackendHermeticMetrics {
3804                    system_user: &raw_user_data[12].0,
3805                },
3806                SystemUserData::BackendSign {
3807                    system_user: &raw_user_data[13].0,
3808                    ssh_authorized_key: raw_user_data[13]
3809                        .1
3810                        .as_ref()
3811                        .expect("to have SSH authorized key"),
3812                },
3813            ]);
3814
3815            assert_eq!(config.system_user_data(), expected);
3816            Ok(())
3817        }
3818
3819        /// Ensures, that [`Config::system_user_ids`] returns system user IDs correctly.
3820        #[rstest]
3821        fn config_system_user_ids(default_config: TestResult<Config>) -> TestResult {
3822            let config = default_config?;
3823            let expected: HashSet<SystemUserId> = HashSet::from_iter([
3824                "signstar-share-holder1".parse()?,
3825                "signstar-share-holder2".parse()?,
3826                "signstar-share-holder3".parse()?,
3827                "signstar-wireguard-download".parse()?,
3828                "nethsm-backup".parse()?,
3829                "nethsm-hermetic-metrics".parse()?,
3830                "nethsm-metrics".parse()?,
3831                "nethsm-signing".parse()?,
3832                "yubihsm2-audit-log".parse()?,
3833                "yubihsm2-backup".parse()?,
3834                "yubihsm2-hermetic-audit-log".parse()?,
3835                "yubihsm2-signing".parse()?,
3836            ]);
3837
3838            assert_eq!(
3839                config.system_user_ids(),
3840                expected.iter().collect::<HashSet<_>>()
3841            );
3842            Ok(())
3843        }
3844
3845        /// Create a [`Config`] using [`ConfigBuilder`].
3846        #[rstest]
3847        fn config_builder_new(
3848            default_system_config: TestResult<SystemConfig>,
3849            default_nethsm_config: TestResult<NetHsmConfig>,
3850            default_yubihsm2_config: TestResult<YubiHsm2Config>,
3851        ) -> TestResult {
3852            let _config = ConfigBuilder::new(default_system_config?)
3853                .set_nethsm_config(default_nethsm_config?)
3854                .set_yubihsm2_config(default_yubihsm2_config?)
3855                .finish()?;
3856
3857            Ok(())
3858        }
3859
3860        /// Ensures, that a valid [`Config`] can be created from a YAML file and turned back into
3861        /// the same YAML string.
3862        ///
3863        /// The configuration file describes a [`SystemConfig`], [`NetHsmConfig`] and a
3864        /// [`YubiHsm2Config`] object.
3865        #[rstest]
3866        fn roundtrip_yaml_config(
3867            #[files("../fixtures/config/all_backends/*.yaml")] path: PathBuf,
3868        ) -> TestResult {
3869            let config_string = read_to_string(&path)?;
3870            let config = Config::from_file_path(&path)?;
3871
3872            assert_eq!(config.to_yaml_string()?, config_string);
3873
3874            Ok(())
3875        }
3876
3877        /// Ensures, that [`AdministrativeSecretHandling`] and
3878        /// [`NonAdministrativeSecretHandling`]can be retrieved from a
3879        /// [`UserBackendConnection`].
3880        #[rstest]
3881        fn user_backend_connection_secret_handling(
3882            default_config: TestResult<Config>,
3883        ) -> TestResult {
3884            let config = default_config?;
3885            let admin_secret_handling = AdministrativeSecretHandling::ShamirsSecretSharing {
3886                number_of_shares: NonZeroUsize::new(3).expect("3 is larger than 0"),
3887                threshold: NonZeroUsize::new(2).expect("2 is larger than 0"),
3888            };
3889            let non_admin_secret_handling = NonAdministrativeSecretHandling::SystemdCreds;
3890
3891            for user in ["nethsm-signing", "yubihsm2-signing"] {
3892                let user_backend_connection = config
3893                    .user_backend_connection(&user.parse()?)
3894                    .expect("there to be a mapping of the requested name");
3895
3896                assert_eq!(
3897                    user_backend_connection.admin_secret_handling(),
3898                    admin_secret_handling
3899                );
3900                assert_eq!(
3901                    user_backend_connection.non_admin_secret_handling(),
3902                    non_admin_secret_handling
3903                );
3904            }
3905
3906            Ok(())
3907        }
3908    }
3909}