hanko 1.1.1

Keeps your Git allowed signers file up to date with signing keys configured on software development platforms like GitHub and GitLab.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//! Types used to configure hanko.
//!
//! Configuration is handled by two cooperating types: [`TomlFile`] and [`Configuration`].
//!
//! [`TomlFile`] holds the raw [`toml_edit::DocumentMut`] and is responsible for format-preserving
//! load, mutation, and atomic save operations. [`toml_edit`] is used to ensure that user formatting,
//! comments, and key ordering are not destroyed when hanko writes back to the config file.
//!
//! [`Configuration`] is the typed, validated domain object. It is derived from [`TomlFile`] and
//! owns the parsed signers and sources. [`TomlFile`] is retained as a field on [`Configuration`]
//! so that mutations made through the public API can be written back to disk through the
//! original document, preserving formatting.
//!
//! Keeping the two types separate rather than collapsing them into one also means
//! [`Configuration`] can be constructed from an in-memory document without a real file path,
//! which keeps unit tests independent of the filesystem.
//!
//! Fallible functions return [`anyhow::Result`] since errors here are reported directly to the
//! user without further programmatic handling.

use crate::{Github, Gitlab, Protocol, Source, allowed_signers::Signer, parent_dir};
use anyhow::{Context, Error, Result, bail};
use reqwest::Url;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{
    collections::{HashMap, HashSet},
    fs,
    io::{self, Write},
    path::{Path, PathBuf},
    sync::Arc,
};
use tempfile::NamedTempFile;
use tracing::{info, trace};

/// A mutable and format preserving representation of a TOML file.
#[derive(Debug, Default)]
struct TomlFile {
    path: PathBuf,
    document: toml_edit::DocumentMut,
}

impl TomlFile {
    /// Add an allowed signer to the file.
    fn add_signer(&mut self, signer: &SignerConfiguration) {
        use toml_edit::{ArrayOfTables, Item, Value};

        let table = toml_edit::ser::to_document(signer)
            .expect("SignerConfiguration is always serializable")
            .as_table()
            .clone();

        match self.document.get_mut("signers") {
            None => {
                let mut item = ArrayOfTables::new();
                item.push(table);
                self.document.insert("signers", Item::ArrayOfTables(item));
            }
            Some(Item::Value(Value::Array(a))) if a.iter().all(Value::is_inline_table) => {
                a.push(table.into_inline_table());
            }
            Some(Item::ArrayOfTables(a)) => a.push(table),
            _ => unreachable!("signers key has invalid format"),
        }
    }

    /// Load from a TOML file.
    fn load(path: PathBuf) -> Result<Self> {
        info!("Loading TOML configuration file");
        let content = fs::read_to_string(&path)?;
        let document = content.parse()?;
        Ok(Self { path, document })
    }

    /// Save back to TOML file.
    fn save(&self) -> Result<()> {
        info!("Saving TOML configuration file");
        let dir = parent_dir(&self.path)?;
        let mut file = NamedTempFile::new_in(dir)?;
        write!(file, "{}", self.document)?;
        file.persist(&self.path)?;
        Ok(())
    }
}

/// The main configuration.
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Configuration {
    /// The configured signers.
    signers: Vec<SignerConfiguration>,
    /// The configured sources.
    sources: Vec<SourceConfiguration>,
    /// The file representing the configuration on disk.
    /// Invariant: Any mutation of the above fields must be reflected here as well.
    #[serde(skip)]
    file: TomlFile,
}

impl TryFrom<TomlFile> for Configuration {
    type Error = Error;

    /// Create a configuration from a TOML file without performing any semantic validation.
    fn try_from(file: TomlFile) -> Result<Self> {
        let deserializer = toml_edit::de::Deserializer::from(file.document.clone());
        let mut s = Self::deserialize(deserializer)?;
        s.file = file;
        Ok(s)
    }
}

/// A `HashMap` containing sources by name.
/// Since signers need to contain references to sources and can move between threads,
/// an Arc is used for sources.
type NamedSources = HashMap<String, Arc<dyn Source>>;

impl Configuration {
    /// Returns configuration for the default GitHub and GitLab sources.
    fn default_sources() -> Vec<SourceConfiguration> {
        vec![
            SourceConfiguration {
                name: "github".to_string(),
                provider: SourceType::Github,
                url: "https://api.github.com".parse().unwrap(),
                protocol: Protocol::Http2,
            },
            SourceConfiguration {
                name: "gitlab".to_string(),
                provider: SourceType::Gitlab,
                url: "https://gitlab.com".parse().unwrap(),
                protocol: Protocol::Http2,
            },
        ]
    }

    /// Returns all, the default and user provided source configurations.
    fn all_source_configurations(&self) -> Vec<SourceConfiguration> {
        Self::default_sources()
            .into_iter()
            .chain(self.sources.iter().cloned())
            .collect()
    }

    /// Returns the initialized sources generated from configuration.
    #[must_use]
    pub fn sources(&self) -> NamedSources {
        self.all_source_configurations()
            .into_iter()
            .map(|c| {
                let source = Arc::from(c.build_source());
                (c.name, source)
            })
            .collect()
    }

    /// Add an allowed signer to the configuration.
    /// Returns `true` if the signer was added and `false` if an identical signer already exists.
    ///
    /// # Errors
    ///
    /// Returns an error if any of the given sources don't exist, or if the signer already exists
    /// with different attributes.
    pub fn add_signer(
        &mut self,
        name: String,
        principals: Vec<String>,
        source_names: Vec<String>,
    ) -> Result<bool> {
        let signer = SignerConfiguration {
            name,
            principals,
            source_names,
        };
        self.check_sources_exist(signer.source_names.iter().map(String::as_str))?;
        if self.check_signer_already_exists(&signer)? {
            return Ok(false);
        }

        self.file.add_signer(&signer);
        self.signers.push(signer);

        Ok(true)
    }

    /// Returns signers generated from their configuration.
    ///
    /// # Panics
    ///
    /// Will panic if the given sources are missing a source configured within a signer.
    #[must_use]
    pub fn signers(&self, sources: &NamedSources) -> Vec<Signer> {
        let configs = &self.signers;
        configs
            .iter()
            .map(|c| {
                Signer {
                    name: c.name.clone(),
                    principals: c.principals.clone(),
                    sources: c
                        .source_names
                        .iter()
                        .map(|name| {
                            sources
                                .get(name)
                                .expect("signer references source that does not exist, config not validated correctly")
                                .clone()
                        })
                        .collect(),
                }
            })
            .collect()
    }

    /// Load the configuration from a TOML file.
    /// Extends the configuration by default sources and performs semantic validation before returning.
    ///
    /// # Errors
    ///
    /// When the file fails to load or it's content is invalid.
    #[tracing::instrument]
    pub fn load(path: &Path) -> Result<Self> {
        let file = TomlFile::load(path.to_path_buf())?;

        let c = Self::try_from(file)?;
        c.validate_semantics()?;

        Ok(c)
    }

    /// Load the configuration from a TOML file, returning a default instance if it doesn't exist.
    ///
    /// # Errors
    ///
    /// When the file at the given path has invalid content.
    pub fn load_or_default(path: &Path) -> Result<Self> {
        Self::load(path).or_else(|err| match err.downcast_ref::<io::Error>() {
            Some(io_err) if io_err.kind() == io::ErrorKind::NotFound => {
                info!("Configuration file does not exist yet and will be created");
                let dir = parent_dir(path)?;
                fs::create_dir_all(dir).context(format!(
                    "Failed to create configuration directory {}",
                    dir.display()
                ))?;
                Ok(Configuration {
                    file: TomlFile {
                        path: path.to_path_buf(),
                        ..Default::default()
                    },
                    ..Default::default()
                })
            }
            _ => Err(err),
        })
    }

    /// Save the configuration back to file.
    ///
    /// # Errors
    ///
    /// When an IO error occurs while trying to write the underlying file to disk.
    pub fn save(&self) -> Result<()> {
        self.file.save()
    }

    /// Perform semantic validation of the configuration.
    fn validate_semantics(&self) -> Result<()> {
        trace!(?self, "Validating configuration semantics");

        self.check_no_sources_conflict_w_default()?;
        self.check_sources_exist(
            self.signers
                .iter()
                .flat_map(|c| c.source_names.iter().map(String::as_str)),
        )?;
        self.check_signers_have_one_or_more_principals()?;

        Ok(())
    }

    /// Check if the given sources exist, returning an error if not.
    fn check_sources_exist<'a>(
        &self,
        source_names: impl IntoIterator<Item = &'a str>,
    ) -> Result<()> {
        let a = self.all_source_configurations();

        let existing_sources: HashSet<&str> = a.iter().map(|c| c.name.as_str()).collect();
        let mut missing_sources: Vec<&str> = source_names
            .into_iter()
            .filter(|name| !existing_sources.contains(name))
            .collect();
        if !missing_sources.is_empty() {
            missing_sources.sort_unstable();
            bail!("Missing sources: {}", missing_sources.join(", "))
        }
        Ok(())
    }

    /// Check if the given signer already exists.
    ///
    /// Returns `Ok(true)` for an identical signer, `Ok(false)` if no signer with the same name
    /// exists and an error if one exists with different attributes.
    fn check_signer_already_exists(&self, signer: &SignerConfiguration) -> Result<bool> {
        if let Some(existing) = self.signers.iter().find(|s| s.name == signer.name) {
            if existing == signer {
                return Ok(true);
            }
            bail!(
                "Signer {} already exists with different attributes, please update the configuration manually",
                signer.name
            );
        }
        Ok(false)
    }

    /// Check that no user configured sources conflict with the default sources.
    fn check_no_sources_conflict_w_default(&self) -> Result<()> {
        let d = Self::default_sources();
        let reserved: HashSet<&str> = d.iter().map(|s| s.name.as_str()).collect();

        for source in &self.sources {
            if reserved.contains(source.name.as_str()) {
                bail!(
                    "\"{}\" is a built-in source name and cannot be redefined in configuration",
                    source.name
                );
            }
        }
        Ok(())
    }

    /// Check that all signers have at least one principal configured.
    fn check_signers_have_one_or_more_principals(&self) -> Result<()> {
        for config in &self.signers {
            if config.principals.is_empty() {
                bail!("Signer {} missing principals", config.name)
            }
        }
        Ok(())
    }
}

/// The type of source.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum SourceType {
    Github,
    Gitlab,
}

#[must_use]
pub fn default_user_source() -> Vec<String> {
    vec!["github".to_string()]
}

fn is_default_sources(sources: &[String]) -> bool {
    // We don't need to be order insensitive here since adding any sources would be a
    // breaking change and there currently is only one.
    sources == default_user_source()
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(default, deny_unknown_fields)]
pub struct SignerConfiguration {
    pub name: String,
    pub principals: Vec<String>,
    #[serde(rename = "sources", skip_serializing_if = "is_default_sources")]
    pub source_names: Vec<String>,
}

impl Default for SignerConfiguration {
    fn default() -> Self {
        Self {
            name: String::default(),
            principals: Vec::default(),
            source_names: default_user_source(),
        }
    }
}

/// The representation of a [`Source`] in configuration.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
struct SourceConfiguration {
    name: String,
    provider: SourceType,
    #[serde(serialize_with = "serialize_url", deserialize_with = "deserialize_url")]
    url: Url,
    /// The HTTP protocol version to use when connecting to this source.
    #[serde(default)]
    protocol: Protocol,
}

fn deserialize_url<'de, D>(deserializer: D) -> Result<Url, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    let url = reqwest::Url::parse(&s).map_err(serde::de::Error::custom)?;
    Ok(url)
}

fn serialize_url<U, S>(url: U, serializer: S) -> Result<S::Ok, S::Error>
where
    U: AsRef<str>,
    S: Serializer,
{
    serializer.serialize_str(url.as_ref())
}

impl SourceConfiguration {
    fn build_source(&self) -> Box<dyn Source> {
        let url = self.url.clone();
        match self.provider {
            SourceType::Github => Box::new(Github::new(url, self.protocol)),
            SourceType::Gitlab => Box::new(Gitlab::new(url, self.protocol)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use indoc::indoc;
    use rstest::*;
    use std::io::Write;
    use tempfile::{NamedTempFile, TempDir};

    #[fixture]
    fn tmp_config_toml() -> NamedTempFile {
        tempfile::Builder::new()
            .prefix("config")
            .suffix(".toml")
            .tempfile()
            .unwrap()
    }

    /// When loading a configuration, the returned instance always contains the default sources.
    #[rstest]
    #[case(
        indoc!{r#"
            signers = [
                { name = "torvalds", principals = ["torvalds@linux-foundation.org"], sources = ["github"] },
            ]
        "#}
    )]
    fn loaded_configuration_has_default_sources(
        mut tmp_config_toml: NamedTempFile,
        #[case] config: &str,
    ) {
        writeln!(tmp_config_toml, "{config}").unwrap();

        let config = Configuration::load(tmp_config_toml.path()).unwrap();
        for default_source in Configuration::default_sources() {
            assert!(config.sources().contains_key(&default_source.name));
        }
    }

    /// When loading configuration from a path that doesn't exist without using the
    /// explicit `load_or_default` constructor, an error is returned.
    #[rstest]
    fn loading_non_existent_configuration_returns_error() {
        let tmpdir = TempDir::new().unwrap();
        let path = tmpdir.path().join("config.toml");
        assert!(!path.exists());

        let err = Configuration::load(&path).unwrap_err();

        assert_eq!(
            err.downcast_ref::<io::Error>().unwrap().kind(),
            io::ErrorKind::NotFound
        );
    }

    /// Loading a configuration that redefines a built-in source name returns an appropriate error.
    #[rstest]
    #[case(
        indoc!{r#"
            [[sources]]
            name = "github"
            provider = "github"
            url = "https://github.example.com"
        "#},
        "\"github\" is a built-in source name and cannot be redefined in configuration"
    )]
    #[case(
        indoc!{r#"
            [[sources]]
            name = "gitlab"
            provider = "gitlab"
            url = "https://gitlab.example.com"
        "#},
        "\"gitlab\" is a built-in source name and cannot be redefined in configuration"
    )]
    fn loading_configuration_with_reserved_source_name_returns_error(
        mut tmp_config_toml: NamedTempFile,
        #[case] config: &str,
        #[case] expected_msg: &str,
    ) {
        writeln!(tmp_config_toml, "{config}").unwrap();
        let err = Configuration::load(tmp_config_toml.path()).unwrap_err();
        assert_eq!(err.to_string(), expected_msg);
    }

    /// Loading configuration missing sources returns an appropriate error.
    #[rstest]
    #[case(
        indoc!{r#"
            signers = [
                { name = "cwoods", principals = ["cwoods@acme.corp"], sources = ["acme-corp"] },
                { name = "rdavis", principals = ["rdavis@lumon.industries"], sources = ["lumon-industries"] }
            ]

            [[sources]]
            name = "acme-corp"
            provider = "gitlab"
            url = "https://git.acme.corp"
        "#},
        vec!["lumon-industries".to_string()]
    )]
    #[case(
        indoc!{r#"
            signers = [
                { name = "cwoods", principals = ["cwoods@acme.corp"], sources = ["acme-corp"] },
                { name = "rdavis", principals = ["rdavis@lumon.industries"], sources = ["lumon-industries"] }
            ]
        "#},
        vec!["acme-corp".to_string(), "lumon-industries".to_string()]
    )]
    fn loading_configuration_with_missing_source_returns_error(
        mut tmp_config_toml: NamedTempFile,
        #[case] config: &str,
        #[case] mut expected_missing: Vec<String>,
    ) {
        expected_missing.sort();
        writeln!(tmp_config_toml, "{config}").unwrap();

        let err = Configuration::load(tmp_config_toml.path()).unwrap_err();

        assert_eq!(
            err.to_string(),
            format!("Missing sources: {}", expected_missing.join(", "))
        );
    }

    /// Loading configuration containing a signer without at least one principal returns an appropriate error.
    #[rstest]
    #[case(
        indoc!{r#"
            [[signers]]
            name = "octocat"
        "#},
    )]
    #[case(
        indoc!{r#"
            [[signers]]
            name = "octocat"
            principals = []
        "#},
    )]
    fn loading_configuration_with_signer_missing_principal_returns_error(
        mut tmp_config_toml: NamedTempFile,
        #[case] config: &str,
    ) {
        writeln!(tmp_config_toml, "{config}").unwrap();

        let err = Configuration::load(tmp_config_toml.path()).unwrap_err();

        assert_eq!(err.to_string(), "Signer octocat missing principals");
    }

    #[rstest]
    #[case(
        indoc!{r#"
            [[signers]]
            name = "cwoods"
            principals = ["cwoods@acme.corp"]
            nonsense = ["acme-corp"]

            [[sources]]
            name = "acme-corp"
            provider = "gitlab"
            url = "https://git.acme.corp"
        "#},
        "unknown field `nonsense`"
    )]
    fn loading_configuration_with_unknown_field_returns_error(
        mut tmp_config_toml: NamedTempFile,
        #[case] config: &str,
        #[case] expected_msg: &str,
    ) {
        writeln!(tmp_config_toml, "{config}").unwrap();

        let err = Configuration::load(tmp_config_toml.path()).unwrap_err();

        assert!(err.to_string().contains(expected_msg));
    }

    /// Signers have a default GitHub source if no sources were configured explicitly.
    #[rstest]
    #[case(
        indoc! {r#"
            signers = [
                { name = "torvalds", principals = ["torvalds@linux-foundation.org"] },
            ]
        "#}
    )]
    fn signers_have_default_github_source(
        mut tmp_config_toml: NamedTempFile,
        #[case] config: &str,
    ) {
        writeln!(tmp_config_toml, "{config}").unwrap();

        let mut config = Configuration::load(tmp_config_toml.path()).unwrap();
        let signer_sources = config.signers.pop().unwrap().source_names;

        assert_eq!(signer_sources, vec!["github"]);
    }

    /// When saving a configuration back to file, the TOML formatting matches that of the original file.
    #[rstest]
    #[case(
        indoc! {r#"
            [[signers]]
            name = "octocat"
            principals = ["octocat@github.com"]
        "#}
    )]
    #[case(
        indoc! {r#"
            signers = [
                { name = "torvalds", principals = ["torvalds@linux-foundation.org"] },
            ]
        "#}
    )]
    fn saving_configuration_preserves_formatting(
        mut tmp_config_toml: NamedTempFile,
        #[case] content: &str,
    ) {
        write!(tmp_config_toml, "{content}").unwrap();
        let config = Configuration::load(tmp_config_toml.path()).unwrap();
        tmp_config_toml.as_file().set_len(0).unwrap();

        config.save().unwrap();
        let result = fs::read_to_string(tmp_config_toml.path()).unwrap();

        assert_eq!(result, content);
    }

    /// When adding a signer to a configuration, it is added to the contained signers.
    #[rstest]
    #[case(
        SignerConfiguration {
            name: "octocat".to_string(),
            principals: vec!["octocat@github.com".to_string()],
            ..Default::default()
        }
    )]
    fn adding_signer_adds_to_signers(#[case] signer: SignerConfiguration) {
        let mut config = Configuration::default();

        assert!(
            config
                .add_signer(
                    signer.name.clone(),
                    signer.principals.clone(),
                    signer.source_names.clone(),
                )
                .unwrap()
        );

        assert!(config.signers.contains(&signer));
    }

    /// When adding a signer to a configuration, it is added to the TOML configuration file contained within.
    #[rstest]
    #[case(
        "",
        SignerConfiguration {
            name: "octocat".to_string(),
            principals: vec!["octocat@github.com".to_string()],
            ..Default::default()
        },
        indoc! {r#"
            [[signers]]
            name = "octocat"
            principals = ["octocat@github.com"]
        "#},
    )]
    #[case(
        indoc! {r#"
            [[signers]]
            name = "torvalds"
            principals = ["torvalds@linux-foundation.org"]
        "#},
        SignerConfiguration {
            name: "octocat".to_string(),
            principals: vec!["octocat@github.com".to_string()],
            ..Default::default()
        },
        indoc! {r#"
            [[signers]]
            name = "torvalds"
            principals = ["torvalds@linux-foundation.org"]

            [[signers]]
            name = "octocat"
            principals = ["octocat@github.com"]
        "#},
    )]
    #[case(
        indoc! {r#"
            [[signers]]
            name = "torvalds"
            principals = ["torvalds@linux-foundation.org"]

            [[sources]]
            name = "acme-corp"
            provider = "gitlab"
            url = "https://git.acme.corp"
        "#},
        SignerConfiguration {
            name: "octocat".to_string(),
            principals: vec!["octocat@github.com".to_string()],
            source_names: vec!["acme-corp".to_string()],
        },
        indoc! {r#"
            [[signers]]
            name = "torvalds"
            principals = ["torvalds@linux-foundation.org"]

            [[signers]]
            name = "octocat"
            principals = ["octocat@github.com"]
            sources = ["acme-corp"]

            [[sources]]
            name = "acme-corp"
            provider = "gitlab"
            url = "https://git.acme.corp"
        "#},
    )]
    #[case(
        indoc! {r#"
            signers = [
                { name = "torvalds", principals = ["torvalds@linux-foundation.org"] },
                { name = "cwoods", principals = ["cwoods@acme.corp"] },
            ]
        "#},
        SignerConfiguration {
            name: "octocat".to_string(),
            principals: vec!["octocat@github.com".to_string()],
            ..Default::default()
        },
        indoc! {r#"
            signers = [
                { name = "torvalds", principals = ["torvalds@linux-foundation.org"] },
                { name = "cwoods", principals = ["cwoods@acme.corp"] }, { name = "octocat", principals = ["octocat@github.com"] },
            ]
        "#},
    )]
    fn adding_signer_adds_to_file(
        #[case] toml: &str,
        #[case] signer: SignerConfiguration,
        #[case] expected: &str,
    ) {
        let mut config = Configuration::try_from(TomlFile {
            document: toml.parse().unwrap(),
            ..Default::default()
        })
        .unwrap();

        assert!(
            config
                .add_signer(signer.name, signer.principals, signer.source_names)
                .unwrap()
        );

        assert_eq!(config.file.document.to_string(), expected);
    }

    #[rstest]
    #[case(
        Configuration::default(),
        SignerConfiguration {
            name: "cwoods".to_string(),
            principals: vec!["cwoods@acme.corp".to_string()],
            source_names: vec!["acme-corp".to_string()],
        },
        vec!["acme-corp".to_string()]
    )]
    fn adding_signer_with_missing_source_returns_error(
        #[case] mut config: Configuration,
        #[case] signer: SignerConfiguration,
        #[case] mut expected_missing: Vec<String>,
    ) {
        expected_missing.sort();

        let err = config
            .add_signer(signer.name, signer.principals, signer.source_names)
            .unwrap_err();

        assert_eq!(
            err.to_string(),
            format!("Missing sources: {}", expected_missing.join(", "))
        );
    }
}