Skip to main content

signstar_config/
test.rs

1//! Utilities used for test setups.
2
3#[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
4use std::collections::HashMap;
5use std::{
6    fs::{File, Permissions, create_dir_all, read_dir, set_permissions, write},
7    io::Write,
8    os::{linux::fs::MetadataExt, unix::fs::PermissionsExt},
9    path::{Path, PathBuf},
10    process::{Child, Command},
11    str::FromStr,
12    thread,
13    time,
14};
15
16use change_user_run::{create_users, get_command};
17use log::debug;
18#[cfg(feature = "nethsm")]
19use nethsm::{FullCredentials, UserId};
20use signstar_common::{backend::BackendType, system_user::get_home_base_dir_path};
21#[cfg(feature = "nethsm")]
22use signstar_crypto::AdministrativeSecretHandling;
23#[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
24use signstar_crypto::passphrase::Passphrase;
25use tempfile::NamedTempFile;
26
27use crate::config::{Config, ConfigSystemUserIds, MappingAuthorizedKeyEntry};
28#[cfg(feature = "nethsm")]
29use crate::{admin_credentials::AdminCredentials, nethsm::NetHsmAdminCredentials};
30/// When any of the HSM backends is present.
31#[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
32pub mod impl_any {
33    use super::*;
34    use crate::config::UserBackendConnectionFilter;
35
36    impl SystemUserConfig {
37        /// Creates a new [`SystemUserConfig`].
38        pub fn new(settings: SystemUserConfigSettings) -> Self {
39            Self {
40                backend_credentials: None,
41                create_secrets: settings.create_secrets,
42                create_ssh_authorized_keys: settings.create_ssh_authorized_keys,
43            }
44        }
45
46        /// Applies the chosen system user configuration items based on a [`Config`].
47        ///
48        /// # Errors
49        ///
50        /// Returns an error if secrets for a non-administrative backend user cannot be created.
51        pub fn apply(&mut self, config: &Config) -> Result<(), crate::Error> {
52            if self.create_secrets {
53                let user_backend_connections =
54                    config.user_backend_connections(&[UserBackendConnectionFilter::NonAdmin]);
55
56                let mut creds = HashMap::new();
57                for user_backend_connection in user_backend_connections {
58                    let Some(user_creds) =
59                        user_backend_connection.create_non_admin_backend_user_secrets()?
60                    else {
61                        continue;
62                    };
63
64                    for user_cred in user_creds.iter() {
65                        creds.insert(user_cred.user(), user_cred.passphrase().clone());
66                    }
67                }
68
69                self.backend_credentials = Some(creds);
70            }
71
72            if self.create_ssh_authorized_keys {
73                let user_backend_connections =
74                    config.user_backend_connections(&[UserBackendConnectionFilter::NonAdmin]);
75                for user_backend_connection in user_backend_connections {
76                    user_backend_connection.write_authorized_key_entry()?;
77                }
78
79                for mapping in config.system().mappings() {
80                    mapping.write_authorized_key_entry()?;
81                }
82            }
83
84            Ok(())
85        }
86
87        /// Returns a reference to the optional map of backend credentials.
88        ///
89        /// # Note
90        ///
91        /// This method returns [`None`] until [`Self::apply`] has run successfully.
92        pub fn backend_credentials(&self) -> Option<&HashMap<String, Passphrase>> {
93            self.backend_credentials.as_ref()
94        }
95    }
96
97    impl SystemPrepareConfig {
98        /// Applies the chosen system configuration items.
99        ///
100        /// Optionally returns the [`BackgroundProcess`] tracking an `io.systemd.Credentials`
101        /// socket.
102        ///
103        /// # Errors
104        ///
105        /// Returns an error if
106        ///
107        /// - an `/etc/machine-id` file should be written, but [`write_machine_id`] fails
108        /// - an `io.systemd.Credentials` socket should be created, but [`start_credentials_socket`]
109        ///   fails
110        /// - a configuration file should be created, but writing it fails
111        /// - the creation of system users and/or their home directories fails
112        /// - the creation of backend user secrets fails
113        pub fn apply(&mut self) -> Result<Option<BackgroundProcess>, crate::Error> {
114            if self.machine_id {
115                write_machine_id()?;
116            }
117
118            let background_process = if self.credentials_socket {
119                Some(start_credentials_socket()?)
120            } else {
121                None
122            };
123
124            if let Some(config_file_location) = self.signstar_config.location {
125                create_config(config_file_location, self.signstar_config.variant)?;
126
127                if let Some(mut system_user_config) = self.signstar_config.system_user_config.take()
128                {
129                    let config = Config::from_str(&String::from_utf8_lossy(
130                        self.signstar_config.variant.as_config_bytes(),
131                    ))?;
132                    create_unix_users_and_homes(&config)?;
133                    system_user_config.apply(&config)?;
134                    self.signstar_config.system_user_config = Some(system_user_config.clone())
135                }
136            }
137
138            Ok(background_process)
139        }
140    }
141}
142
143/// When no HSM backend is present.
144#[cfg(not(any(feature = "nethsm", feature = "yubihsm2")))]
145mod impl_none {
146    use super::*;
147
148    impl SystemUserConfig {
149        /// Creates a new [`SystemUserConfig`].
150        pub fn new(settings: SystemUserConfigSettings) -> Self {
151            Self {
152                create_ssh_authorized_keys: settings.create_ssh_authorized_keys,
153            }
154        }
155
156        /// Applies the chosen system user configuration items based on a [`Config`].
157        ///
158        /// # Note
159        ///
160        /// Without any HSM backends, no backend-related actions are taken.
161        ///
162        /// # Errors
163        ///
164        /// Returns an error if an `authorized_keys` file for a user cannot be written.
165        pub fn apply(&self, config: &Config) -> Result<(), crate::Error> {
166            if self.create_ssh_authorized_keys {
167                for mapping in config.system().mappings() {
168                    mapping.write_authorized_key_entry()?;
169                }
170            }
171
172            Ok(())
173        }
174    }
175
176    impl SystemPrepareConfig {
177        /// Applies the chosen system configuration items.
178        ///
179        /// Optionally returns the [`BackgroundProcess`] tracking an `io.systemd.Credentials`
180        /// socket.
181        ///
182        /// # Errors
183        ///
184        /// Returns an error if
185        ///
186        /// - an `/etc/machine-id` file should be written, but [`write_machine_id`] fails
187        /// - an `io.systemd.Credentials` socket should be created, but [`start_credentials_socket`]
188        ///   fails
189        /// - a configuration file should be created, but writing it fails
190        /// - the creation of system users and/or their home directories fails
191        /// - the creation of backend user secrets fails
192        pub fn apply(&self) -> Result<Option<BackgroundProcess>, crate::Error> {
193            if self.machine_id {
194                write_machine_id()?;
195            }
196
197            let background_process = if self.credentials_socket {
198                Some(start_credentials_socket()?)
199            } else {
200                None
201            };
202
203            if let Some(config_file_location) = self.signstar_config.location {
204                create_config(config_file_location, self.signstar_config.variant)?;
205
206                if let Some(system_user_config) = self.signstar_config.system_user_config.as_ref() {
207                    let config = Config::from_str(&String::from_utf8_lossy(
208                        self.signstar_config.variant.as_config_bytes(),
209                    ))?;
210                    create_unix_users_and_homes(&config)?;
211                    system_user_config.apply(&config)?;
212                }
213            }
214
215            Ok(background_process)
216        }
217    }
218}
219
220/// Config with no HSM backend.
221///
222/// - plaintext for administrative secrets
223/// - plaintext for non-administrative secrets
224const NO_BACKEND_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT: &[u8] =
225    include_bytes!("../../fixtures/config/no_backend/admin-plaintext-non-admin-plaintext.yaml");
226
227/// Config with no HSM backend.
228///
229/// - plaintext for administrative secrets
230/// - systemd-creds for non-administrative secrets
231const NO_BACKEND_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS: &[u8] =
232    include_bytes!("../../fixtures/config/no_backend/admin-plaintext-non-admin-systemd-creds.yaml");
233
234/// Config with no HSM backend.
235///
236/// - systemd-creds for administrative secrets
237/// - plaintext for non-administrative secrets
238const NO_BACKEND_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT: &[u8] =
239    include_bytes!("../../fixtures/config/no_backend/admin-systemd-creds-non-admin-plaintext.yaml");
240
241/// Config with no HSM backend.
242///
243/// - systemd-creds for administrative secrets
244/// - systemd-creds for non-administrative secrets
245const NO_BACKEND_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
246    "../../fixtures/config/no_backend/admin-systemd-creds-non-admin-systemd-creds.yaml"
247);
248
249/// Config with no HSM backend.
250///
251/// - Shamir's Secret Sharing for administrative secrets
252/// - plaintext for non-administrative secrets
253const NO_BACKEND_ADMIN_SSS_NON_ADMIN_PLAINTEXT: &[u8] =
254    include_bytes!("../../fixtures/config/no_backend/admin-sss-non-admin-plaintext.yaml");
255
256/// Config with no HSM backend.
257///
258/// - Shamir's Secret Sharing for administrative secrets
259/// - systemd-creds for non-administrative secrets
260const NO_BACKEND_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS: &[u8] =
261    include_bytes!("../../fixtures/config/no_backend/admin-sss-non-admin-systemd-creds.yaml");
262
263/// Config with NetHSM backend.
264///
265/// - plaintext for administrative secrets
266/// - plaintext for non-administrative secrets
267const ONLY_NETHSM_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT: &[u8] =
268    include_bytes!("../../fixtures/config/nethsm_backend/admin-plaintext-non-admin-plaintext.yaml");
269
270/// Config with NetHSM backend.
271///
272/// - plaintext for administrative secrets
273/// - systemd-creds for non-administrative secrets
274const ONLY_NETHSM_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
275    "../../fixtures/config/nethsm_backend/admin-plaintext-non-admin-systemd-creds.yaml"
276);
277
278/// Config with NetHSM backend with just one connection.
279///
280/// - plaintext for administrative secrets
281/// - systemd-creds for non-administrative secrets
282const ONLY_NETHSM_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS_SINGLE_CONNECTION: &[u8] = include_bytes!(
283    "../../fixtures/config/nethsm_backend/admin-plaintext-non-admin-systemd-creds-single-connection.yaml"
284);
285
286/// Config with NetHSM backend.
287///
288/// - systemd-creds for administrative secrets
289/// - plaintext for non-administrative secrets
290const ONLY_NETHSM_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT: &[u8] = include_bytes!(
291    "../../fixtures/config/nethsm_backend/admin-systemd-creds-non-admin-plaintext.yaml"
292);
293
294/// Config with NetHSM backend.
295///
296/// - systemd-creds for administrative secrets
297/// - systemd-creds for non-administrative secrets
298const ONLY_NETHSM_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
299    "../../fixtures/config/nethsm_backend/admin-systemd-creds-non-admin-systemd-creds.yaml"
300);
301
302/// Config with NetHSM backend.
303///
304/// - Shamir's Secret Sharing for administrative secrets
305/// - plaintext for non-administrative secrets
306const ONLY_NETHSM_ADMIN_SSS_NON_ADMIN_PLAINTEXT: &[u8] =
307    include_bytes!("../../fixtures/config/nethsm_backend/admin-sss-non-admin-plaintext.yaml");
308
309/// Config with NetHSM backend.
310///
311/// - Shamir's Secret Sharing for administrative secrets
312/// - systemd-creds for non-administrative secrets
313const ONLY_NETHSM_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS: &[u8] =
314    include_bytes!("../../fixtures/config/nethsm_backend/admin-sss-non-admin-systemd-creds.yaml");
315
316/// Config with YubiHSM2 backend.
317///
318/// - plaintext for administrative secrets
319/// - plaintext for non-administrative secrets
320const ONLY_YUBIHSM2_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT: &[u8] = include_bytes!(
321    "../../fixtures/config/yubihsm2_backend/admin-plaintext-non-admin-plaintext.yaml"
322);
323
324/// Config with YubiHSM2 backend.
325///
326/// - plaintext for administrative secrets
327/// - systemd-creds for non-administrative secrets
328const ONLY_YUBIHSM2_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
329    "../../fixtures/config/yubihsm2_backend/admin-plaintext-non-admin-systemd-creds.yaml"
330);
331
332/// Config with YubiHSM2 backend.
333///
334/// - systemd-creds for administrative secrets
335/// - plaintext for non-administrative secrets
336const ONLY_YUBIHSM2_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT: &[u8] = include_bytes!(
337    "../../fixtures/config/yubihsm2_backend/admin-systemd-creds-non-admin-plaintext.yaml"
338);
339
340/// Config with YubiHSM2 backend.
341///
342/// - systemd-creds for administrative secrets
343/// - systemd-creds for non-administrative secrets
344const ONLY_YUBIHSM2_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
345    "../../fixtures/config/yubihsm2_backend/admin-systemd-creds-non-admin-systemd-creds.yaml"
346);
347
348/// Config with YubiHSM2 backend.
349///
350/// - Shamir's Secret Sharing for administrative secrets
351/// - plaintext for non-administrative secrets
352const ONLY_YUBIHSM2_ADMIN_SSS_NON_ADMIN_PLAINTEXT: &[u8] =
353    include_bytes!("../../fixtures/config/yubihsm2_backend/admin-sss-non-admin-plaintext.yaml");
354
355/// Config with YubiHSM2 backend.
356///
357/// - Shamir's Secret Sharing for administrative secrets
358/// - systemd-creds for non-administrative secrets
359const ONLY_YUBIHSM2_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS: &[u8] =
360    include_bytes!("../../fixtures/config/yubihsm2_backend/admin-sss-non-admin-systemd-creds.yaml");
361
362/// Config with YubiHSM2 HTTP backend.
363///
364/// - plaintext for administrative secrets
365/// - plaintext for non-administrative secrets
366const ONLY_YUBIHSM2_HTTP_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT: &[u8] = include_bytes!(
367    "../../fixtures/config/yubihsm2_backend/admin-plaintext-non-admin-plaintext-http.yaml"
368);
369
370/// Config with YubiHSM2 mockhsm backend.
371///
372/// - plaintext for administrative secrets
373/// - plaintext for non-administrative secrets
374const ONLY_YUBIHSM2_MOCKHSM_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT: &[u8] = include_bytes!(
375    "../../fixtures/config/yubihsm2_mockhsm_backend/admin-plaintext-non-admin-plaintext.yaml"
376);
377
378/// Config with YubiHSM2 mockhsm backend.
379///
380/// - plaintext for administrative secrets
381/// - systemd-creds for non-administrative secrets
382const ONLY_YUBIHSM2_MOCKHSM_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
383    "../../fixtures/config/yubihsm2_mockhsm_backend/admin-plaintext-non-admin-systemd-creds.yaml"
384);
385
386/// Config with YubiHSM2 mockhsm backend.
387///
388/// - systemd-creds for administrative secrets
389/// - plaintext for non-administrative secrets
390const ONLY_YUBIHSM2_MOCKHSM_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT: &[u8] = include_bytes!(
391    "../../fixtures/config/yubihsm2_mockhsm_backend/admin-systemd-creds-non-admin-plaintext.yaml"
392);
393
394/// Config with YubiHSM2 mockhsm backend.
395///
396/// - systemd-creds for administrative secrets
397/// - systemd-creds for non-administrative secrets
398const ONLY_YUBIHSM2_MOCKHSM_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
399    "../../fixtures/config/yubihsm2_mockhsm_backend/admin-systemd-creds-non-admin-systemd-creds.yaml"
400);
401
402/// Config with YubiHSM2 mockhsm backend.
403///
404/// - Shamir's Secret Sharing for administrative secrets
405/// - plaintext for non-administrative secrets
406const ONLY_YUBIHSM2_MOCKHSM_ADMIN_SSS_NON_ADMIN_PLAINTEXT: &[u8] = include_bytes!(
407    "../../fixtures/config/yubihsm2_mockhsm_backend/admin-sss-non-admin-plaintext.yaml"
408);
409
410/// Config with YubiHSM2 mockhsm backend.
411///
412/// - Shamir's Secret Sharing for administrative secrets
413/// - systemd-creds for non-administrative secrets
414const ONLY_YUBIHSM2_MOCKHSM_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
415    "../../fixtures/config/yubihsm2_mockhsm_backend/admin-sss-non-admin-systemd-creds.yaml"
416);
417
418/// Config with NetHSM and YubiHSM2 backends.
419///
420/// - plaintext for administrative secrets
421/// - plaintext for non-administrative secrets
422const ALL_BACKENDS_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT: &[u8] =
423    include_bytes!("../../fixtures/config/all_backends/admin-plaintext-non-admin-plaintext.yaml");
424
425/// Config with NetHSM and YubiHSM2 backends.
426///
427/// - plaintext for administrative secrets
428/// - systemd-creds for non-administrative secrets
429const ALL_BACKENDS_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
430    "../../fixtures/config/all_backends/admin-plaintext-non-admin-systemd-creds.yaml"
431);
432
433/// Config with NetHSM and YubiHSM2 backends.
434///
435/// - systemd-creds for administrative secrets
436/// - plaintext for non-administrative secrets
437const ALL_BACKENDS_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT: &[u8] = include_bytes!(
438    "../../fixtures/config/all_backends/admin-systemd-creds-non-admin-plaintext.yaml"
439);
440
441/// Config with NetHSM and YubiHSM2 backends.
442///
443/// - systemd-creds for administrative secrets
444/// - systemd-creds for non-administrative secrets
445const ALL_BACKENDS_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS: &[u8] = include_bytes!(
446    "../../fixtures/config/all_backends/admin-systemd-creds-non-admin-systemd-creds.yaml"
447);
448
449/// Config with NetHSM and YubiHSM2 backends.
450///
451/// - Shamir's Secret Sharing for administrative secrets
452/// - plaintext for non-administrative secrets
453const ALL_BACKENDS_ADMIN_SSS_NON_ADMIN_PLAINTEXT: &[u8] =
454    include_bytes!("../../fixtures/config/all_backends/admin-sss-non-admin-plaintext.yaml");
455
456/// Config with NetHSM and YubiHSM2 backends.
457///
458/// - Shamir's Secret Sharing for administrative secrets
459/// - systemd-creds for non-administrative secrets
460const ALL_BACKENDS_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS: &[u8] =
461    include_bytes!("../../fixtures/config/all_backends/admin-sss-non-admin-systemd-creds.yaml");
462
463/// An error that may occur when using test utils.
464#[derive(Debug, thiserror::Error)]
465pub enum Error {
466    /// A timeout has been reached.
467    #[error("Timeout of {timeout}ms reached while {context}")]
468    Timeout {
469        /// The value of the timeout in milliseconds.
470        timeout: u64,
471
472        /// The short description of the operation.
473        context: String,
474    },
475}
476
477/// The targeted location for a Signstar configuration file.
478#[derive(Clone, Copy, Debug, Default)]
479pub enum ConfigFileLocation {
480    /// The override location in `/run/signstar/`.
481    Run,
482
483    /// The override location in `/etc/signstar/`.
484    Etc,
485
486    /// The default location in `/usr/share/signstar/`.
487    #[default]
488    UsrShare,
489}
490
491impl ConfigFileLocation {
492    /// Returns the path of the configuration file's parent directory.
493    pub fn to_parent_dir_path(&self) -> PathBuf {
494        match self {
495            ConfigFileLocation::Run => PathBuf::from(Config::RUN_OVERRIDE_CONFIG_DIR),
496            ConfigFileLocation::Etc => PathBuf::from(Config::ETC_OVERRIDE_CONFIG_DIR),
497            ConfigFileLocation::UsrShare => PathBuf::from(Config::DEFAULT_CONFIG_DIR),
498        }
499    }
500}
501
502impl From<ConfigFileLocation> for PathBuf {
503    fn from(value: ConfigFileLocation) -> Self {
504        value
505            .to_parent_dir_path()
506            .join(format!("{}.yaml", Config::CONFIG_NAME))
507    }
508}
509
510/// The Signstar configuration file variant used for the file contents.
511#[derive(Clone, Copy, Debug, Default)]
512pub enum ConfigFileVariant {
513    /// No HSM backend.
514    ///
515    /// - plaintext for administrative secrets
516    /// - plaintext for non-administrative secrets
517    NoBackendAdminPlaintextNonAdminPlaintext,
518
519    /// No HSM backend.
520    ///
521    /// - plaintext for administrative secrets
522    /// - systemd-creds for non-administrative secrets
523    NoBackendAdminPlaintextNonAdminSystemdCreds,
524
525    /// No HSM backend.
526    ///
527    /// - systemd-creds for administrative secrets
528    /// - plaintext for non-administrative secrets
529    NoBackendAdminSystemdCredsNonAdminPlaintext,
530
531    /// No HSM backend.
532    ///
533    /// - systemd-creds for administrative secrets
534    /// - systemd-creds for non-administrative secrets
535    NoBackendAdminSystemdCredsNonAdminSystemdCreds,
536
537    /// No HSM backend.
538    ///
539    /// - Shamir's Secret Sharing for administrative secrets
540    /// - plaintext for non-administrative secrets
541    NoBackendAdminSssNonAdminPlaintext,
542
543    /// No HSM backend.
544    ///
545    /// - Shamir's Secret Sharing for administrative secrets
546    /// - systemd-creds for non-administrative secrets
547    NoBackendAdminSssNonAdminSystemdCreds,
548
549    /// NetHSM backend.
550    ///
551    /// - plaintext for administrative secrets
552    /// - plaintext for non-administrative secrets
553    OnlyNetHsmBackendAdminPlaintextNonAdminPlaintext,
554
555    /// NetHSM backend.
556    ///
557    /// - plaintext for administrative secrets
558    /// - systemd-creds for non-administrative secrets
559    OnlyNetHsmBackendAdminPlaintextNonAdminSystemdCreds,
560
561    /// NetHSM backend with just one connection.
562    ///
563    /// - plaintext for administrative secrets
564    /// - systemd-creds for non-administrative secrets
565    OnlyNetHsmBackendAdminPlaintextNonAdminSystemdCredsSingleConnection,
566
567    /// NetHSM backend.
568    ///
569    /// - systemd-creds for administrative secrets
570    /// - plaintext for non-administrative secrets
571    OnlyNetHsmBackendAdminSystemdCredsNonAdminPlaintext,
572
573    /// NetHSM backend.
574    ///
575    /// - systemd-creds for administrative secrets
576    /// - systemd-creds for non-administrative secrets
577    OnlyNetHsmBackendAdminSystemdCredsNonAdminSystemdCreds,
578
579    /// NetHSM backend.
580    ///
581    /// - Shamir's Secret Sharing for administrative secrets
582    /// - plaintext for non-administrative secrets
583    OnlyNetHsmBackendAdminSssNonAdminPlaintext,
584
585    /// NetHSM backend.
586    ///
587    /// - Shamir's Secret Sharing for administrative secrets
588    /// - systemd-creds for non-administrative secrets
589    OnlyNetHsmBackendAdminSssNonAdminSystemdCreds,
590
591    /// YubiHSM2 backend.
592    ///
593    /// - plaintext for administrative secrets
594    /// - plaintext for non-administrative secrets
595    OnlyYubiHsm2BackendAdminPlaintextNonAdminPlaintext,
596
597    /// YubiHSM2 backend.
598    ///
599    /// - plaintext for administrative secrets
600    /// - systemd-creds for non-administrative secrets
601    OnlyYubiHsm2BackendAdminPlaintextNonAdminSystemdCreds,
602
603    /// YubiHSM2 backend.
604    ///
605    /// - systemd-creds for administrative secrets
606    /// - plaintext for non-administrative secrets
607    OnlyYubiHsm2BackendAdminSystemdCredsNonAdminPlaintext,
608
609    /// YubiHSM2 backend.
610    ///
611    /// - systemd-creds for administrative secrets
612    /// - systemd-creds for non-administrative secrets
613    OnlyYubiHsm2BackendAdminSystemdCredsNonAdminSystemdCreds,
614
615    /// YubiHSM2 backend.
616    ///
617    /// - Shamir's Secret Sharing for administrative secrets
618    /// - plaintext for non-administrative secrets
619    OnlyYubiHsm2BackendAdminSssNonAdminPlaintext,
620
621    /// YubiHSM2 backend.
622    ///
623    /// - Shamir's Secret Sharing for administrative secrets
624    /// - systemd-creds for non-administrative secrets
625    OnlyYubiHsm2BackendAdminSssNonAdminSystemdCreds,
626
627    /// YubiHSM2 HTTP backend.
628    ///
629    /// - plaintext for administrative secrets
630    /// - plaintext for non-administrative secrets
631    OnlyYubiHsm2HttpBackendAdminPlaintextNonAdminPlaintext,
632
633    /// YubiHSM2 mockhsm backend.
634    ///
635    /// - plaintext for administrative secrets
636    /// - plaintext for non-administrative secrets
637    OnlyYubiHsm2MockHsmBackendAdminPlaintextNonAdminPlaintext,
638
639    /// YubiHSM2 mockhsm backend.
640    ///
641    /// - plaintext for administrative secrets
642    /// - systemd-creds for non-administrative secrets
643    OnlyYubiHsm2MockHsmBackendAdminPlaintextNonAdminSystemdCreds,
644
645    /// YubiHSM2 mockhsm backend.
646    ///
647    /// - systemd-creds for administrative secrets
648    /// - plaintext for non-administrative secrets
649    OnlyYubiHsm2MockHsmBackendAdminSystemdCredsNonAdminPlaintext,
650
651    /// YubiHSM2 mockhsm backend.
652    ///
653    /// - systemd-creds for administrative secrets
654    /// - systemd-creds for non-administrative secrets
655    OnlyYubiHsm2MockHsmBackendAdminSystemdCredsNonAdminSystemdCreds,
656
657    /// YubiHSM2 mockhsm backend.
658    ///
659    /// - Shamir's Secret Sharing for administrative secrets
660    /// - plaintext for non-administrative secrets
661    OnlyYubiHsm2MockHsmBackendAdminSssNonAdminPlaintext,
662
663    /// YubiHSM2 mockhsm backend.
664    ///
665    /// - Shamir's Secret Sharing for administrative secrets
666    /// - systemd-creds for non-administrative secrets
667    OnlyYubiHsm2MockHsmBackendAdminSssNonAdminSystemdCreds,
668
669    /// NetHSM and YubiHSM2 backends.
670    ///
671    /// - plaintext for administrative secrets
672    /// - plaintext for non-administrative secrets
673    AllBackendsAdminPlaintextNonAdminPlaintext,
674
675    /// NetHSM and YubiHSM2 backends.
676    ///
677    /// - plaintext for administrative secrets
678    /// - systemd-creds for non-administrative secrets
679    AllBackendsAdminPlaintextNonAdminSystemdCreds,
680
681    /// NetHSM and YubiHSM2 backends.
682    ///
683    /// - systemd-creds for administrative secrets
684    /// - plaintext for non-administrative secrets
685    AllBackendsAdminSystemdCredsNonAdminPlaintext,
686
687    /// NetHSM and YubiHSM2 backends.
688    ///
689    /// - systemd-creds for administrative secrets
690    /// - systemd-creds for non-administrative secrets
691    AllBackendsAdminSystemdCredsNonAdminSystemdCreds,
692
693    /// NetHSM and YubiHSM2 backends.
694    ///
695    /// - Shamir's Secret Sharing for administrative secrets
696    /// - plaintext for non-administrative secrets
697    AllBackendsAdminSssNonAdminPlaintext,
698
699    /// NetHSM and YubiHSM2 backends.
700    ///
701    /// - Shamir's Secret Sharing for administrative secrets
702    /// - systemd-creds for non-administrative secrets
703    #[default]
704    AllBackendsAdminSssNonAdminSystemdCreds,
705}
706
707impl ConfigFileVariant {
708    /// Returns the bytes of a Signstar configuration matching the chosen variant.
709    pub fn as_config_bytes(&self) -> &[u8] {
710        match self {
711            ConfigFileVariant::NoBackendAdminPlaintextNonAdminPlaintext => {
712                NO_BACKEND_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT
713            }
714            ConfigFileVariant::NoBackendAdminPlaintextNonAdminSystemdCreds => {
715                NO_BACKEND_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS
716            }
717            ConfigFileVariant::NoBackendAdminSystemdCredsNonAdminPlaintext => {
718                NO_BACKEND_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT
719            }
720            ConfigFileVariant::NoBackendAdminSystemdCredsNonAdminSystemdCreds => {
721                NO_BACKEND_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS
722            }
723            ConfigFileVariant::NoBackendAdminSssNonAdminPlaintext => {
724                NO_BACKEND_ADMIN_SSS_NON_ADMIN_PLAINTEXT
725            }
726            ConfigFileVariant::NoBackendAdminSssNonAdminSystemdCreds => {
727                NO_BACKEND_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS
728            }
729            ConfigFileVariant::OnlyNetHsmBackendAdminPlaintextNonAdminPlaintext => {
730                ONLY_NETHSM_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT
731            }
732            ConfigFileVariant::OnlyNetHsmBackendAdminPlaintextNonAdminSystemdCreds => {
733                ONLY_NETHSM_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS
734            }
735            ConfigFileVariant::OnlyNetHsmBackendAdminPlaintextNonAdminSystemdCredsSingleConnection => {
736                ONLY_NETHSM_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS_SINGLE_CONNECTION
737            }
738            ConfigFileVariant::OnlyNetHsmBackendAdminSystemdCredsNonAdminPlaintext => {
739                ONLY_NETHSM_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT
740            }
741            ConfigFileVariant::OnlyNetHsmBackendAdminSystemdCredsNonAdminSystemdCreds => {
742                ONLY_NETHSM_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS
743            }
744            ConfigFileVariant::OnlyNetHsmBackendAdminSssNonAdminPlaintext => {
745                ONLY_NETHSM_ADMIN_SSS_NON_ADMIN_PLAINTEXT
746            }
747            ConfigFileVariant::OnlyNetHsmBackendAdminSssNonAdminSystemdCreds => {
748                ONLY_NETHSM_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS
749            }
750            ConfigFileVariant::OnlyYubiHsm2BackendAdminPlaintextNonAdminPlaintext => {
751                ONLY_YUBIHSM2_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT
752            }
753            ConfigFileVariant::OnlyYubiHsm2BackendAdminPlaintextNonAdminSystemdCreds => {
754                ONLY_YUBIHSM2_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS
755            }
756            ConfigFileVariant::OnlyYubiHsm2BackendAdminSystemdCredsNonAdminPlaintext => {
757                ONLY_YUBIHSM2_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT
758            }
759            ConfigFileVariant::OnlyYubiHsm2BackendAdminSystemdCredsNonAdminSystemdCreds => {
760                ONLY_YUBIHSM2_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS
761            }
762            ConfigFileVariant::OnlyYubiHsm2BackendAdminSssNonAdminPlaintext => {
763                ONLY_YUBIHSM2_ADMIN_SSS_NON_ADMIN_PLAINTEXT
764            }
765            ConfigFileVariant::OnlyYubiHsm2BackendAdminSssNonAdminSystemdCreds => {
766                ONLY_YUBIHSM2_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS
767            }
768            ConfigFileVariant::OnlyYubiHsm2HttpBackendAdminPlaintextNonAdminPlaintext => {
769                ONLY_YUBIHSM2_HTTP_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT
770            }
771            ConfigFileVariant::OnlyYubiHsm2MockHsmBackendAdminPlaintextNonAdminPlaintext => {
772                ONLY_YUBIHSM2_MOCKHSM_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT
773            }
774            ConfigFileVariant::OnlyYubiHsm2MockHsmBackendAdminPlaintextNonAdminSystemdCreds => {
775                ONLY_YUBIHSM2_MOCKHSM_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS
776            }
777            ConfigFileVariant::OnlyYubiHsm2MockHsmBackendAdminSystemdCredsNonAdminPlaintext => {
778                ONLY_YUBIHSM2_MOCKHSM_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT
779            }
780            ConfigFileVariant::OnlyYubiHsm2MockHsmBackendAdminSystemdCredsNonAdminSystemdCreds => {
781                ONLY_YUBIHSM2_MOCKHSM_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS
782            }
783            ConfigFileVariant::OnlyYubiHsm2MockHsmBackendAdminSssNonAdminPlaintext => {
784                ONLY_YUBIHSM2_MOCKHSM_ADMIN_SSS_NON_ADMIN_PLAINTEXT
785            }
786            ConfigFileVariant::OnlyYubiHsm2MockHsmBackendAdminSssNonAdminSystemdCreds => {
787                ONLY_YUBIHSM2_MOCKHSM_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS
788            }
789            ConfigFileVariant::AllBackendsAdminPlaintextNonAdminPlaintext => {
790                ALL_BACKENDS_ADMIN_PLAINTEXT_NON_ADMIN_PLAINTEXT
791            }
792            ConfigFileVariant::AllBackendsAdminPlaintextNonAdminSystemdCreds => {
793                ALL_BACKENDS_ADMIN_PLAINTEXT_NON_ADMIN_SYSTEMD_CREDS
794            }
795            ConfigFileVariant::AllBackendsAdminSystemdCredsNonAdminPlaintext => {
796                ALL_BACKENDS_ADMIN_SYSTEMD_CREDS_NON_ADMIN_PLAINTEXT
797            }
798            ConfigFileVariant::AllBackendsAdminSystemdCredsNonAdminSystemdCreds => {
799                ALL_BACKENDS_ADMIN_SYSTEMD_CREDS_NON_ADMIN_SYSTEMD_CREDS
800            }
801            ConfigFileVariant::AllBackendsAdminSssNonAdminPlaintext => {
802                ALL_BACKENDS_ADMIN_SSS_NON_ADMIN_PLAINTEXT
803            }
804            ConfigFileVariant::AllBackendsAdminSssNonAdminSystemdCreds => {
805                ALL_BACKENDS_ADMIN_SSS_NON_ADMIN_SYSTEMD_CREDS
806            }
807        }
808    }
809
810    /// Creates a [`Config`] from the selected configuration variant in `self`.
811    ///
812    /// # Errors
813    ///
814    /// Returns an error if
815    ///
816    /// - the bytes cannot be converted to a valid UTF-8 string
817    /// - a valid [`Config`] cannot be created from the variant
818    pub fn to_config(&self) -> Result<Config, crate::Error> {
819        Config::from_str(
820            &String::from_utf8(self.as_config_bytes().to_vec()).map_err(|source| {
821                crate::Error::Utf8String {
822                    path: PathBuf::from("/dev/null"),
823                    context: "creating a Signstar config object from config fixture bytes"
824                        .to_string(),
825                    source,
826                }
827            })?,
828        )
829    }
830
831    /// Returns `true`, if a [`BackendType`] is contained in this variant.
832    pub fn contains_backend(&self, backend_type: BackendType) -> bool {
833        match backend_type {
834            BackendType::NetHsm => matches!(
835                self,
836                Self::OnlyNetHsmBackendAdminPlaintextNonAdminPlaintext
837                    | Self::OnlyNetHsmBackendAdminPlaintextNonAdminSystemdCreds
838                    | Self::OnlyNetHsmBackendAdminPlaintextNonAdminSystemdCredsSingleConnection
839                    | Self::OnlyNetHsmBackendAdminSystemdCredsNonAdminPlaintext
840                    | Self::OnlyNetHsmBackendAdminSystemdCredsNonAdminSystemdCreds
841                    | Self::OnlyNetHsmBackendAdminSssNonAdminPlaintext
842                    | Self::OnlyNetHsmBackendAdminSssNonAdminSystemdCreds
843                    | Self::AllBackendsAdminPlaintextNonAdminPlaintext
844                    | Self::AllBackendsAdminPlaintextNonAdminSystemdCreds
845                    | Self::AllBackendsAdminSystemdCredsNonAdminPlaintext
846                    | Self::AllBackendsAdminSystemdCredsNonAdminSystemdCreds
847                    | Self::AllBackendsAdminSssNonAdminPlaintext
848                    | Self::AllBackendsAdminSssNonAdminSystemdCreds
849            ),
850            BackendType::YubiHsm2 => matches!(
851                self,
852                Self::OnlyYubiHsm2BackendAdminPlaintextNonAdminPlaintext
853                    | Self::OnlyYubiHsm2BackendAdminPlaintextNonAdminSystemdCreds
854                    | Self::OnlyYubiHsm2BackendAdminSystemdCredsNonAdminPlaintext
855                    | Self::OnlyYubiHsm2BackendAdminSystemdCredsNonAdminSystemdCreds
856                    | Self::OnlyYubiHsm2BackendAdminSssNonAdminPlaintext
857                    | Self::OnlyYubiHsm2BackendAdminSssNonAdminSystemdCreds
858                    | Self::OnlyYubiHsm2HttpBackendAdminPlaintextNonAdminPlaintext
859                    | Self::OnlyYubiHsm2MockHsmBackendAdminPlaintextNonAdminPlaintext
860                    | Self::OnlyYubiHsm2MockHsmBackendAdminPlaintextNonAdminSystemdCreds
861                    | Self::OnlyYubiHsm2MockHsmBackendAdminSystemdCredsNonAdminPlaintext
862                    | Self::OnlyYubiHsm2MockHsmBackendAdminSystemdCredsNonAdminSystemdCreds
863                    | Self::OnlyYubiHsm2MockHsmBackendAdminSssNonAdminPlaintext
864                    | Self::OnlyYubiHsm2MockHsmBackendAdminSssNonAdminSystemdCreds
865                    | Self::AllBackendsAdminPlaintextNonAdminPlaintext
866                    | Self::AllBackendsAdminPlaintextNonAdminSystemdCreds
867                    | Self::AllBackendsAdminSystemdCredsNonAdminPlaintext
868                    | Self::AllBackendsAdminSystemdCredsNonAdminSystemdCreds
869                    | Self::AllBackendsAdminSssNonAdminPlaintext
870                    | Self::AllBackendsAdminSssNonAdminSystemdCreds
871            ),
872        }
873    }
874}
875
876/// Settings for configuring a [`SystemUserConfig`].
877#[derive(Clone, Copy, Debug, Default)]
878pub struct SystemUserConfigSettings {
879    /// Whether to create the secrets for each system user with at least one backend user.
880    #[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
881    pub create_secrets: bool,
882
883    /// Whether to create the SSH authorized keys file for system users.
884    pub create_ssh_authorized_keys: bool,
885}
886
887/// Configuration for the creation of system users.
888#[derive(Clone, Debug, Default)]
889pub struct SystemUserConfig {
890    /// The optional backend credentials.
891    #[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
892    backend_credentials: Option<HashMap<String, Passphrase>>,
893
894    /// Whether to create the secrets for each system user with at least one backend user.
895    #[cfg(any(feature = "nethsm", feature = "yubihsm2"))]
896    create_secrets: bool,
897
898    /// Whether to create the SSH authorized keys file for system users.
899    create_ssh_authorized_keys: bool,
900}
901
902/// Configuration for how and where to provide a Signstar configuration file.
903#[derive(Clone, Debug, Default)]
904pub struct ConfigFileConfig {
905    /// The optional location in which the Signstar config is placed.
906    ///
907    /// If `location` is [`None`], the Signstar config is not written to a file.
908    pub location: Option<ConfigFileLocation>,
909
910    /// The variant of Signstar configuration that is added.
911    pub variant: ConfigFileVariant,
912
913    /// The optional configuration for system users.
914    ///
915    /// # Note
916    ///
917    /// When set, this implies the creation of all system users.
918    pub system_user_config: Option<SystemUserConfig>,
919}
920
921/// Creates a configuration file in a location based on [`ConfigFileLocation`] and
922/// [`ConfigFileVariant`].
923///
924/// Creates all parent directories.
925///
926/// # Errors
927///
928/// Returns an error if
929///
930/// - the creation of parent directories fails
931/// - the configuration file cannot be created
932/// - the configuration file cannot be written to
933fn create_config(
934    location: ConfigFileLocation,
935    variant: ConfigFileVariant,
936) -> Result<(), crate::Error> {
937    create_dir_all(location.to_parent_dir_path()).map_err(|source| crate::Error::IoPath {
938        path: location.to_parent_dir_path(),
939        context: "creating the parent directory for the Signstar config",
940        source,
941    })?;
942    let path = PathBuf::from(location);
943
944    let mut file = File::create(&path).map_err(|source| crate::Error::IoPath {
945        path: path.clone(),
946        context: "creating a Signstar configuration file",
947        source,
948    })?;
949    let config_bytes = variant.as_config_bytes();
950    file.write_all(config_bytes)
951        .map_err(|source| crate::Error::IoPath {
952            path,
953            context: "writing data to a Signstar configuration file",
954            source,
955        })?;
956
957    Ok(())
958}
959
960/// Creates all Unix users and their homes based on a [`Config`].
961///
962/// # Errors
963///
964/// Returns an error if any of the Unix users cannot be created.
965fn create_unix_users_and_homes(config: &Config) -> Result<(), crate::Error> {
966    let users = config
967        .system_user_ids()
968        .iter()
969        .cloned()
970        .map(|id| id.as_ref())
971        .collect::<Vec<_>>();
972    Ok(create_users(&users, Some(&get_home_base_dir_path()), None)?)
973}
974
975/// Configuration on how to prepare a system for a test setup.
976#[derive(Clone, Debug)]
977pub struct SystemPrepareConfig {
978    /// Whether to write an `/etc/machine-id`.
979    pub machine_id: bool,
980
981    /// Whether to start a socket for `io.systemd.Credentials`.
982    pub credentials_socket: bool,
983
984    /// How to handle the Signstar config file.
985    pub signstar_config: ConfigFileConfig,
986}
987
988impl Default for SystemPrepareConfig {
989    fn default() -> Self {
990        Self {
991            machine_id: true,
992            credentials_socket: true,
993            signstar_config: ConfigFileConfig::default(),
994        }
995    }
996}
997
998/// Recursively lists files, their permissions and ownership.
999pub fn list_files_in_dir(path: impl AsRef<Path>) -> Result<(), crate::Error> {
1000    let path = path.as_ref();
1001    let entries = read_dir(path).map_err(|source| crate::Error::IoPath {
1002        path: path.to_path_buf(),
1003        context: "reading its children",
1004        source,
1005    })?;
1006
1007    for entry in entries {
1008        let entry = entry.map_err(|source| crate::Error::IoPath {
1009            path: path.to_path_buf(),
1010            context: "getting an entry below it",
1011            source,
1012        })?;
1013        let meta = entry.metadata().map_err(|source| crate::Error::IoPath {
1014            path: path.to_path_buf(),
1015            context: "getting metadata",
1016            source,
1017        })?;
1018
1019        debug!(
1020            "{} {}/{} {entry:?}",
1021            meta.permissions().mode(),
1022            meta.st_uid(),
1023            meta.st_gid()
1024        );
1025
1026        if meta.is_dir() {
1027            list_files_in_dir(entry.path())?;
1028        }
1029    }
1030
1031    Ok(())
1032}
1033
1034/// Returns a configuration file with `data` as contents in a temporary location.
1035pub fn get_tmp_config(data: &[u8]) -> Result<NamedTempFile, crate::Error> {
1036    let tmp_config = NamedTempFile::new().map_err(|source| crate::Error::Io {
1037        context: "creating a temporary configuration file".to_string(),
1038        source,
1039    })?;
1040    write(&tmp_config, data).map_err(|source| crate::Error::IoPath {
1041        path: tmp_config.path().to_path_buf(),
1042        context: "writing full signstar configuration to temporary file",
1043        source,
1044    })?;
1045    Ok(tmp_config)
1046}
1047
1048/// Writes a dummy `/etc/machine-id`, which is required for systemd-creds.
1049///
1050/// # Errors
1051///
1052/// Returns an error if
1053///
1054/// - a static machine-id can not be written to `/etc/machine-id`,
1055/// - or metadata on the created `/etc/machine-id` can not be retrieved.
1056pub fn write_machine_id() -> Result<(), crate::Error> {
1057    debug!("Write dummy /etc/machine-id, required for systemd-creds");
1058    let machine_id = PathBuf::from("/etc/machine-id");
1059    std::fs::write(&machine_id, "d3b07384d113edec49eaa6238ad5ff00").map_err(|source| {
1060        crate::Error::IoPath {
1061            path: machine_id.to_path_buf(),
1062            context: "writing machine-id",
1063            source,
1064        }
1065    })?;
1066
1067    let metadata = machine_id
1068        .metadata()
1069        .map_err(|source| crate::Error::IoPath {
1070            path: machine_id,
1071            context: "getting metadata of file",
1072            source,
1073        })?;
1074    debug!(
1075        "/etc/machine-id\nmode: {}\nuid: {}\ngid: {}",
1076        metadata.permissions().mode(),
1077        metadata.st_uid(),
1078        metadata.st_gid()
1079    );
1080    Ok(())
1081}
1082
1083/// A background process.
1084///
1085/// Tracks a [`Child`] which represents a process that runs in the background.
1086/// The background process is automatically killed upon dropping the [`BackgroundProcess`].
1087#[derive(Debug)]
1088pub struct BackgroundProcess {
1089    child: Child,
1090    command: String,
1091}
1092
1093impl BackgroundProcess {
1094    /// Kills the tracked background process.
1095    ///
1096    /// # Errors
1097    ///
1098    /// Returns an error if the process could not be killed.
1099    pub fn kill(&mut self) -> Result<(), crate::Error> {
1100        self.child.kill().map_err(|source| crate::Error::Io {
1101            context: format!("killing process of command \"{}\"", self.command),
1102            source,
1103        })
1104    }
1105}
1106
1107impl Drop for BackgroundProcess {
1108    /// Kills the tracked background process when destructing the [`BackgroundProcess`].
1109    fn drop(&mut self) {
1110        if let Err(error) = self.child.kill() {
1111            log::debug!(
1112                "Unable to kill background process of command {}:\n{error}",
1113                self.command
1114            )
1115        }
1116    }
1117}
1118
1119/// Starts a socket for `io.systemd.Credentials` using `systemd-socket-activate`.
1120///
1121/// Sets the file mode of the socket to `666` so that all users on the system have access.
1122///
1123/// # Errors
1124///
1125/// Returns an error if
1126///
1127/// - `systemd-socket-activate` is unable to start the required socket,
1128/// - one or more files in `/run/systemd` can not be listed,
1129/// - applying of permissions on `/run/systemd/io.systemd.Credentials` fails,
1130/// - or the socket has not been made available within 10000ms.
1131pub fn start_credentials_socket() -> Result<BackgroundProcess, crate::Error> {
1132    let systemd_run_path = PathBuf::from("/run/systemd");
1133    let socket_path = PathBuf::from("/run/systemd/io.systemd.Credentials");
1134    create_dir_all(&systemd_run_path).map_err(|source| crate::Error::IoPath {
1135        path: systemd_run_path.clone(),
1136        context: "creating the directory",
1137        source,
1138    })?;
1139
1140    // Run systemd-socket-activate to provide /run/systemd/io.systemd.Credentials
1141    let mut command = Command::new(get_command("systemd-socket-activate")?);
1142    let command = command.args([
1143        "--listen",
1144        "/run/systemd/io.systemd.Credentials",
1145        "--accept",
1146        "--fdname=varlink",
1147        "systemd-creds",
1148    ]);
1149    let child = command.spawn().map_err(|source| crate::Error::IoPath {
1150        path: PathBuf::from("/run/systemd/io.systemd.Credentials"),
1151        context: "creating a socket using systemd-socket-activate",
1152        source,
1153    })?;
1154
1155    // Set the socket to be writable by all, once it's available.
1156    let timeout = 10000;
1157    let step = 100;
1158    let mut elapsed = 0;
1159    let mut permissions_set = false;
1160    while elapsed < timeout {
1161        if socket_path.exists() {
1162            debug!("Found {socket_path:?}");
1163            set_permissions(socket_path.as_path(), Permissions::from_mode(0o666)).map_err(
1164                |source| crate::Error::IoPath {
1165                    path: socket_path.to_path_buf(),
1166                    context: "applying permissions",
1167                    source,
1168                },
1169            )?;
1170            permissions_set = true;
1171            break;
1172        } else {
1173            thread::sleep(time::Duration::from_millis(step));
1174            elapsed += step;
1175        }
1176    }
1177    if !permissions_set {
1178        return Err(Error::Timeout {
1179            timeout,
1180            context: format!("waiting for {socket_path:?}"),
1181        }
1182        .into());
1183    }
1184
1185    Ok(BackgroundProcess {
1186        child,
1187        command: format!("{command:?}"),
1188    })
1189}
1190
1191/// Creates an [`AdminCredentials`] from config data.
1192///
1193/// Accepts a byte slice containing configuration data.
1194///
1195/// # Errors
1196///
1197/// Returns an error if
1198///
1199/// - a temporary config file can not be created from `config_data`,
1200/// - an [`AdminCredentials`] can not be created from the temporary config file.
1201#[cfg(feature = "nethsm")]
1202pub fn nethsm_admin_credentials(
1203    config_data: &[u8],
1204) -> Result<NetHsmAdminCredentials, crate::Error> {
1205    let config_file = get_tmp_config(config_data)?;
1206    NetHsmAdminCredentials::load_from_file(
1207        config_file.path(),
1208        AdministrativeSecretHandling::Plaintext,
1209    )
1210}
1211
1212/// Creates a list of [`FullCredentials`] for a list of [`UserId`]s.
1213///
1214/// Creates a 30-char long alphanumeric passphrase for each [`UserId`] in `users` and then
1215/// constructs a [`FullCredentials`].
1216#[cfg(feature = "nethsm")]
1217pub fn create_full_credentials(users: &[UserId]) -> Vec<FullCredentials> {
1218    users
1219        .iter()
1220        .map(|user| FullCredentials::new(user.clone(), Passphrase::generate(Some(30))))
1221        .collect()
1222}