ostrya 0.18.0

Pure-Rust async reimplementation of the ostree repository library
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
//! The typed reads: the reads of `RepoConfig`, the extension traits of a
//! section of a remote and of a client group, and the checks of a section.

use std::path::PathBuf;

use ostrya_core::KeyFile;
use ostrya_core::config::{
    ConfigView, is_section_name, lookup, read_file, read_in_effect, section_header, section_name,
};

use super::{
    ConfigPath, Group, GroupRef, Key, KeyOrigin, KeyPath, Lookup, OutputOf, RemoteFile,
    RemoteSource, RepoConfig, Section, SingleKey, TextInEffect, Value, ValueOf, client,
    encode_string_list, key, lists, remote, str_eq, trust,
};
use crate::error::{Error, Result};

mod sealed {
    /// The seal of the extension traits of a section.
    pub trait Sealed {}

    impl<G: super::Group> Sealed for super::Section<'_, G> {}
}

/// The reads of a section of [`remote::Group`] that the key types do not
/// give alone.
///
/// The trait is sealed. The crate implements it for
/// `Section<'_, remote::Group>`. A caller imports it to call its method.
pub trait RemoteSectionExt: sealed::Sealed {
    /// Returns the ids of [`remote::MirroredCollectionIds`], or an empty list
    /// if the key is absent.
    ///
    /// The call also refuses an id that is the [`remote::CollectionId`] of
    /// the section. It reads `collection-id` after the list.
    ///
    /// # Errors
    ///
    /// - The errors of a read of [`remote::MirroredCollectionIds`].
    /// - [`Error::Core`] if `collection-id` holds a malformed escape
    ///   sequence.
    /// - [`Error::InvalidFormat`] if an id is the `collection-id` of the
    ///   section. The text is `[remote "NAME"] mirrored-collection-ids holds
    ///   'ID', the collection-id of the remote`.
    fn mirrored_collection_ids(&self) -> Result<Vec<String>>;
}

impl RemoteSectionExt for Section<'_, remote::Group> {
    fn mirrored_collection_ids(&self) -> Result<Vec<String>> {
        let Some(ids) = self.file_value::<remote::MirroredCollectionIds>()? else {
            return Ok(Vec::new());
        };
        let ids = ids.into_ids();
        if let Some(own) = self.get::<remote::CollectionId>()?
            && let Some(id) = ids.iter().find(|id| **id == own)
        {
            return Err(Error::InvalidFormat(format!(
                "[{}] {} holds '{id}', the collection-id of the remote",
                self.header(),
                <remote::MirroredCollectionIds as Key<remote::Group>>::NAME
            )));
        }
        Ok(ids)
    }
}

/// The reads of a section of [`client::Group`] that the key types do not
/// give alone.
///
/// The trait is sealed. The crate implements it for
/// `Section<'_, client::Group>`. A caller imports it to call its method.
pub trait ClientSectionExt: sealed::Sealed {
    /// Returns the value in effect of [`client::AllowUnsigned`].
    ///
    /// The value of the file applies when the section sets the key. Else the
    /// value is `true` if the section does not set [`client::Verify`], and
    /// `false` if it does. The call reads `verify` only when the section does
    /// not set `allow-unsigned`. It does not apply the rule of
    /// [`ClientAccess::from_config`](crate::access::ClientAccess::from_config)
    /// that `allow-unsigned=false` needs `verify`.
    ///
    /// # Errors
    ///
    /// The errors of a read of [`client::AllowUnsigned`], and of a read of
    /// [`client::Verify`] when the section does not set `allow-unsigned`.
    fn allow_unsigned(&self) -> Result<bool>;
}

impl ClientSectionExt for Section<'_, client::Group> {
    fn allow_unsigned(&self) -> Result<bool> {
        match self.get::<client::AllowUnsigned>()? {
            Some(value) => Ok(value),
            None => Ok(self.get::<client::Verify>()?.is_none()),
        }
    }
}

/// The reads of a section that the crate uses alone.
pub(crate) trait SectionExt<'a, G: Group> {
    /// Returns the raw text of the key `K`, or `None` if the key is absent.
    fn raw_value<K: Key<G>>(&self) -> Option<&'a str>;

    /// Returns `true` if the section sets the key `K`.
    fn contains<K: Key<G>>(&self) -> bool;

    /// Returns the names of the keys of the section, in the order of the
    /// file.
    fn key_names(&self) -> impl Iterator<Item = &'a str> + use<'a, G, Self>;

    /// Returns the path of the key `K`, with the source of the section, or
    /// `None` if the key is absent.
    ///
    /// # Errors
    ///
    /// The errors of a read of `K`.
    fn key_path<K>(&self) -> Result<Option<KeyPath>>
    where
        K: Key<G, Value = ConfigPath>;

    /// Returns the entries of [`remote::GpgKeyPath`] as paths with the source
    /// of the section.
    ///
    /// # Errors
    ///
    /// The errors of a read of [`remote::GpgKeyPath`].
    #[cfg(feature = "verify-gpg")]
    fn gpgkeypath_paths(&self) -> Result<Vec<KeyPath>>
    where
        remote::GpgKeyPath: Key<G, Value = super::KeyringPaths, Output = super::KeyringPaths>;

    /// Returns the inline trusted key of the sign-api engine `engine`: the
    /// key `verification-ENGINE-key`, or `None` if the key is absent or the
    /// port has no key type for the engine.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    fn verification_key(&self, engine: &str) -> Result<Option<String>>
    where
        remote::VerificationEd25519Key: Key<G, Output = Option<String>>,
        remote::VerificationSpkiKey: Key<G, Output = Option<String>>;

    /// Returns the path of the file of trusted keys of the sign-api engine
    /// `engine`: the key `verification-ENGINE-file`, with the source of the
    /// section, or `None` if the key is absent or the port has no key type
    /// for the engine.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    fn verification_file(&self, engine: &str) -> Result<Option<KeyPath>>
    where
        remote::VerificationEd25519File: Key<G, Value = ConfigPath>,
        remote::VerificationSpkiFile: Key<G, Value = ConfigPath>;

    /// Checks the rules of the X.509 keys of the spki engine that need more
    /// than the value of one key.
    ///
    /// An anchor source is [`remote::VerificationSpkiCaFile`] or
    /// [`remote::VerificationSpkiIdentity`]. The call reads no file.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] with one of these texts, where `HEADER` is the
    /// header of the section:
    ///
    /// - `[HEADER] holds 'verification-spki-ca-file', and no
    ///   verification-spki-identity: an anchor needs an identity` if the
    ///   section sets the CA file and no identity.
    /// - `[HEADER] holds 'KEY', and no anchor source: set
    ///   verification-spki-ca-file or verification-spki-identity` if the
    ///   section sets `verification-spki-intermediates-file`,
    ///   `verification-spki-eku`, `verification-spki-crl-file`, or
    ///   `verification-spki-revocation` and no anchor source.
    fn check_x509(&self) -> Result<()>
    where
        remote::VerificationSpkiCaFile: Key<G>,
        remote::VerificationSpkiIdentity: Key<G>,
        remote::VerificationSpkiIntermediatesFile: Key<G>,
        remote::VerificationSpkiEku: Key<G>,
        remote::VerificationSpkiCrlFile: Key<G>,
        remote::VerificationSpkiRevocation: Key<G>;
}

impl<'a, G: Group> SectionExt<'a, G> for Section<'a, G> {
    fn raw_value<K: Key<G>>(&self) -> Option<&'a str> {
        const {
            assert!(
                lists(G::KEYS, K::NAME),
                "the key is not in the key list of its group"
            )
        };
        self.keyfile().get_value(self.header(), K::NAME)
    }

    fn contains<K: Key<G>>(&self) -> bool {
        self.raw_value::<K>().is_some()
    }

    fn key_names(&self) -> impl Iterator<Item = &'a str> + use<'a, G> {
        self.keyfile().keys(self.header())
    }

    fn key_path<K>(&self) -> Result<Option<KeyPath>>
    where
        K: Key<G, Value = ConfigPath>,
    {
        Ok(self
            .file_value::<K>()?
            .map(|path| key_path_of(self, path.into_string())))
    }

    #[cfg(feature = "verify-gpg")]
    fn gpgkeypath_paths(&self) -> Result<Vec<KeyPath>>
    where
        remote::GpgKeyPath: Key<G, Value = super::KeyringPaths, Output = super::KeyringPaths>,
    {
        Ok(self
            .get::<remote::GpgKeyPath>()?
            .into_entries()
            .into_iter()
            .map(|entry| key_path_of(self, entry))
            .collect())
    }

    fn verification_key(&self, engine: &str) -> Result<Option<String>>
    where
        remote::VerificationEd25519Key: Key<G, Output = Option<String>>,
        remote::VerificationSpkiKey: Key<G, Output = Option<String>>,
    {
        match engine {
            "ed25519" => Ok(self.get::<remote::VerificationEd25519Key>()?),
            "spki" => Ok(self.get::<remote::VerificationSpkiKey>()?),
            _ => Ok(None),
        }
    }

    fn verification_file(&self, engine: &str) -> Result<Option<KeyPath>>
    where
        remote::VerificationEd25519File: Key<G, Value = ConfigPath>,
        remote::VerificationSpkiFile: Key<G, Value = ConfigPath>,
    {
        match engine {
            "ed25519" => self.key_path::<remote::VerificationEd25519File>(),
            "spki" => self.key_path::<remote::VerificationSpkiFile>(),
            _ => Ok(None),
        }
    }

    fn check_x509(&self) -> Result<()>
    where
        remote::VerificationSpkiCaFile: Key<G>,
        remote::VerificationSpkiIdentity: Key<G>,
        remote::VerificationSpkiIntermediatesFile: Key<G>,
        remote::VerificationSpkiEku: Key<G>,
        remote::VerificationSpkiCrlFile: Key<G>,
        remote::VerificationSpkiRevocation: Key<G>,
    {
        let header = self.header();
        let ca_file = self.contains::<remote::VerificationSpkiCaFile>();
        let identity = self.contains::<remote::VerificationSpkiIdentity>();
        if ca_file && !identity {
            return Err(Error::InvalidFormat(format!(
                "[{header}] holds '{}', and no {}: an anchor needs an identity",
                <remote::VerificationSpkiCaFile as Key<G>>::NAME,
                <remote::VerificationSpkiIdentity as Key<G>>::NAME,
            )));
        }
        if !ca_file && !identity {
            for key in [
                <remote::VerificationSpkiIntermediatesFile as Key<G>>::NAME,
                <remote::VerificationSpkiEku as Key<G>>::NAME,
                <remote::VerificationSpkiCrlFile as Key<G>>::NAME,
                <remote::VerificationSpkiRevocation as Key<G>>::NAME,
            ] {
                if self.keyfile().get_value(header, key).is_some() {
                    return Err(Error::InvalidFormat(format!(
                        "[{header}] holds '{key}', and no anchor source: set \
                         verification-spki-ca-file or verification-spki-identity"
                    )));
                }
            }
        }
        Ok(())
    }
}

/// Returns `value`, a path of a key of `section`, with the source of the
/// section.
fn key_path_of<G: Group>(section: &Section<'_, G>, value: String) -> KeyPath {
    KeyPath {
        value: PathBuf::from(value),
        origin: match section.source() {
            RemoteSource::Config => KeyOrigin::Config,
            RemoteSource::File(_) => KeyOrigin::RemotesFile,
        },
    }
}

/// The checks of a section, and the text in effect of one of its keys.
pub(crate) trait SectionCheck {
    /// Checks the section.
    ///
    /// # Errors
    ///
    /// The first error that the call finds.
    fn check(&self) -> Result<()>;

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    fn text_in_effect(&self, key: &str) -> Result<TextInEffect>;
}

/// The checks of a remote section.
impl SectionCheck for Section<'_, remote::Group> {
    /// Checks the value of each key of [`remote::Group`] that the section
    /// sets, in the order of the definition, then the rule of
    /// [`mirrored_collection_ids`](RemoteSectionExt::mirrored_collection_ids),
    /// then the rules of [`check_x509`](SectionExt::check_x509).
    ///
    /// The group is open, so the call does not read a key that the group
    /// does not list.
    ///
    /// # Errors
    ///
    /// The error of the first key whose value does not parse, or the error of
    /// [`mirrored_collection_ids`](RemoteSectionExt::mirrored_collection_ids)
    /// or of [`check_x509`](SectionExt::check_x509).
    fn check(&self) -> Result<()> {
        remote::check_file(self.keyfile(), self.header())?;
        self.mirrored_collection_ids()?;
        self.check_x509()
    }

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key, and the errors of
    /// [`mirrored_collection_ids`](RemoteSectionExt::mirrored_collection_ids)
    /// for `mirrored-collection-ids`.
    fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
        let text = if key == <remote::MirroredCollectionIds as Key<remote::Group>>::NAME {
            if !self.contains::<remote::MirroredCollectionIds>() {
                return Ok(TextInEffect::NoKey);
            }
            Some(encode_string_list(&self.mirrored_collection_ids()?))
        } else {
            match remote::text_in_effect(self.keyfile(), self.header(), None, key) {
                Some(text) => text?,
                None => self
                    .keyfile()
                    .get_value(self.header(), key)
                    .map(str::to_owned),
            }
        };
        Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
    }
}

/// Refuses the key `collection` of a client section, which the group does
/// not take.
///
/// # Errors
///
/// [`Error::InvalidFormat`] with a text that names the form `@ID:PATTERN` of
/// an allow item and a deny item.
pub(crate) fn refuse_removed_keys(section: &Section<'_, client::Group>) -> Result<()> {
    if section
        .keyfile()
        .get_value(section.header(), "collection")
        .is_some()
    {
        return Err(Error::InvalidFormat(format!(
            "[{}] holds the removed key 'collection'; an allow item or a deny item \
             names the refs of a collection as @ID:PATTERN",
            section.header()
        )));
    }
    Ok(())
}

/// The checks of a client section.
impl SectionCheck for Section<'_, client::Group> {
    /// Checks the section: first the key `collection`, as
    /// [`refuse_removed_keys`] does, then a key that [`client::Group`] does
    /// not list, then the value of each key of the group that the section
    /// sets, in the order of the definition.
    ///
    /// # Errors
    ///
    /// The first error that the call finds.
    fn check(&self) -> Result<()> {
        refuse_removed_keys(self)?;
        client::check_file(self.keyfile(), self.header()).map_err(Error::from)
    }

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key, and the errors of
    /// [`allow_unsigned`](ClientSectionExt::allow_unsigned) for
    /// `allow-unsigned`.
    fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
        let text = if key == <client::AllowUnsigned as Key<client::Group>>::NAME {
            Some(self.allow_unsigned()?.format())
        } else {
            match client::text_in_effect(self.keyfile(), self.header(), None, key) {
                Some(text) => text?,
                None => self
                    .keyfile()
                    .get_value(self.header(), key)
                    .map(str::to_owned),
            }
        };
        Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
    }
}

/// The sign-api engines that a trust group can name.
pub(crate) const TRUST_ENGINES: &[&str] = &["ed25519", "spki"];

/// The keys of the X.509 trust of the spki engine.
pub(crate) const SPKI_X509_KEYS: &[&str] = &[
    "verification-spki-ca-file",
    "verification-spki-intermediates-file",
    "verification-spki-eku",
    "verification-spki-identity",
    "verification-spki-crl-file",
    "verification-spki-revocation",
];

/// Returns the engine that a `verification-ENGINE-key` or
/// `verification-ENGINE-file` key names, or `None` for another key. A key of
/// the X.509 trust of the spki engine, such as
/// `verification-spki-ca-file`, names `spki`.
pub(crate) fn verification_engine(key: &str) -> Option<&str> {
    if SPKI_X509_KEYS.contains(&key) {
        return Some("spki");
    }
    let rest = key.strip_prefix("verification-")?;
    rest.strip_suffix("-key")
        .or_else(|| rest.strip_suffix("-file"))
}

/// Refuses a key of a trust section that [`trust::Group`] does not list.
/// The call names the first such key in the order of the file.
///
/// # Errors
///
/// [`Error::InvalidFormat`] with one of these texts, where `HEADER` is the
/// header of the section:
///
/// - `[HEADER] holds 'KEY', and a trust group sets a commit policy alone`
///   for `gpg-verify-summary` and `sign-verify-summary`.
/// - `[HEADER] holds 'KEY', and 'ENGINE' is not ed25519 or spki` for a key
///   `verification-ENGINE-key` or `verification-ENGINE-file`.
/// - `[HEADER] holds the unknown key 'KEY'` for each other key.
pub(crate) fn refuse_foreign_keys(section: &Section<'_, trust::Group>) -> Result<()> {
    let header = section.header();
    for key in section.key_names() {
        if <trust::Group as Group>::KEYS.contains(&key) {
            continue;
        }
        let reason = match key {
            "gpg-verify-summary" | "sign-verify-summary" => {
                "a trust group sets a commit policy alone".to_owned()
            }
            _ => match verification_engine(key) {
                Some(engine) if !TRUST_ENGINES.contains(&engine) => {
                    format!("'{engine}' is not ed25519 or spki")
                }
                _ => {
                    return Err(Error::InvalidFormat(format!(
                        "[{header}] holds the unknown key '{key}'"
                    )));
                }
            },
        };
        return Err(Error::InvalidFormat(format!(
            "[{header}] holds '{key}', and {reason}"
        )));
    }
    Ok(())
}

/// The checks of a trust section.
impl SectionCheck for Section<'_, trust::Group> {
    /// Checks the section: first a key that [`trust::Group`] does not list,
    /// as [`refuse_foreign_keys`] does, then the value of each key of the
    /// group that the section sets, in the order of the definition, then the
    /// rules of [`check_x509`](SectionExt::check_x509), with the texts of a
    /// remote section.
    ///
    /// The call does not refuse [`trust::VerificationSpkiIdentity`] with no
    /// [`trust::VerificationSpkiCaFile`]. The reader of the group refuses it.
    ///
    /// # Errors
    ///
    /// The first error that the call finds.
    fn check(&self) -> Result<()> {
        refuse_foreign_keys(self)?;
        trust::check_file(self.keyfile(), self.header())?;
        self.check_x509()
    }

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
        let text = match trust::text_in_effect(self.keyfile(), self.header(), None, key) {
            Some(text) => text?,
            None => self
                .keyfile()
                .get_value(self.header(), key)
                .map(str::to_owned),
        };
        Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
    }
}

/// The checks of a key section.
impl SectionCheck for Section<'_, key::Group> {
    /// Checks the section: first a key that [`key::Group`] does not list,
    /// then the value of each key of the group that the section sets, in the
    /// order of the definition.
    ///
    /// # Errors
    ///
    /// The first error that the call finds.
    fn check(&self) -> Result<()> {
        key::check_file(self.keyfile(), self.header()).map_err(Error::from)
    }

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
        let text = match key::text_in_effect(self.keyfile(), self.header(), None, key) {
            Some(text) => text?,
            None => self
                .keyfile()
                .get_value(self.header(), key)
                .map(str::to_owned),
        };
        Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
    }
}

/// Typed reads of the keys of `config`.
impl RepoConfig {
    /// Returns the value in effect of the key `K` of a single group.
    ///
    /// The value comes from the first source that gives one, in the order of
    /// [`Lookup`]: a forced value of the handle, the value of `config`, a
    /// fallback value of the handle, and the default of the key. A config
    /// with no handle has no override.
    ///
    /// The result type is [`Key::Output`]. It is `Option<V>` for a key with
    /// no default that is not required. The call parses the value each time
    /// that it is called. A forced value applies with no parse of the value
    /// of the file.
    ///
    /// # Errors
    ///
    /// - The error of the value type if the value does not parse.
    ///   [`ValueError`](super::ValueError) states the text.
    /// - [`Error::InvalidFormat`] if the key is required and absent.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::{RepoConfig, repo};
    ///
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nfsync=false\n")?;
    /// assert!(!cfg.get::<repo::Fsync>()?);
    /// assert_eq!(cfg.get::<repo::TmpExpirySecs>()?, 86400);
    /// assert_eq!(cfg.get::<repo::CollectionId>()?, None);
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn get<K>(&self) -> Result<OutputOf<K>>
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
    {
        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
        read_in_effect::<K::Group, K>(
            &self.keyfile,
            <K as SingleKey>::Group::NAME,
            Some(&self.overrides),
        )
        .map_err(Error::from)
    }

    /// Returns the value of the key `K` of a single group in `config`, or
    /// `None` if `config` does not set it. The overrides of the handle and
    /// the default of the key do not apply.
    ///
    /// # Errors
    ///
    /// The error of the value type if the value does not parse.
    /// [`ValueError`](super::ValueError) states the text.
    pub fn file_value<K>(&self) -> Result<Option<ValueOf<K>>>
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
    {
        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
        read_file::<K::Group, K>(&self.keyfile, <K as SingleKey>::Group::NAME).map_err(Error::from)
    }

    /// Returns the value in effect of the key `K` of a single group and its
    /// source, or `None` if no source gives a value.
    ///
    /// The call takes the sources in the order of [`Lookup`]. A config with
    /// no handle has no override, so the source is [`Lookup::File`] or
    /// [`Lookup::Default`]. A forced value applies with no parse of the value
    /// of the file.
    ///
    /// # Errors
    ///
    /// The error of the value type if the value does not parse.
    /// [`ValueError`](super::ValueError) states the text.
    pub fn lookup<K>(&self) -> Result<Option<Lookup<ValueOf<K>>>>
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
    {
        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
        lookup::<K::Group, K>(
            &self.keyfile,
            <K as SingleKey>::Group::NAME,
            Some(&self.overrides),
        )
        .map_err(Error::from)
    }

    /// Returns the section `name` of the named group `G`, or `None` if no
    /// source has such a section.
    ///
    /// A section of [`remote::Group`] comes from `config`, or else from the
    /// first `.conf` file of the remotes directory that holds it, in the
    /// order of [`sections`](RepoConfig::sections). A section of each other
    /// group comes from `config`.
    ///
    /// The call gives `None` for an empty `name` and for a `name` that
    /// holds `"`. [`sections`](RepoConfig::sections) skips the headers of
    /// such sections, so they are not sections of the group.
    pub fn section<G: Group>(&self, name: &str) -> Option<Section<'_, G>> {
        const { assert!(G::NAMED, "a single group has no section") };
        if !is_section_name(name) {
            return None;
        }
        let header = section_header::<G>(name);
        self.sources::<G>().find_map(|(keyfile, file)| {
            let header = keyfile.group_name(&header)?;
            Some(Section::from_parts(keyfile, header, file))
        })
    }

    /// Returns each section of the named group `G`.
    ///
    /// The sections of `config` come first, in the order of the file. For
    /// [`remote::Group`], the sections of each `.conf` file of the remotes
    /// directory follow: the files in the byte order of their names, and the
    /// sections of each file in the order of the file. The `.conf` files
    /// give no section of another group.
    ///
    /// The call skips a header of the group whose section name is empty or
    /// holds `"`, for example `[NAME ""]` or `[NAME "a" "b"]`.
    pub fn sections<G: Group>(&self) -> impl Iterator<Item = Section<'_, G>> {
        const { assert!(G::NAMED, "a single group has no section") };
        self.sources::<G>().flat_map(|(keyfile, file)| {
            keyfile.groups().filter_map(move |header| {
                section_name::<G>(header)?;
                Some(Section::from_parts(keyfile, header, file))
            })
        })
    }

    /// Returns the section that `reference` names.
    ///
    /// The call finds the section as [`section`](RepoConfig::section) does.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] if no source has such a section. A name that
    /// holds `"` names no section, as [`section`](RepoConfig::section)
    /// states.
    pub fn resolve<G: Group>(&self, reference: &GroupRef<G>) -> Result<Section<'_, G>> {
        self.section::<G>(reference.name()).ok_or_else(|| {
            Error::InvalidFormat(format!(
                "the config has no [{}] group",
                section_header::<G>(reference.name())
            ))
        })
    }

    /// Refuses a key of the group `G` that the closed group does not list.
    ///
    /// For a single group, the call checks the group `[NAME]` of `config`.
    /// For a named group, it checks each section of the group in `config`,
    /// in the order of the file, as [`Section::refuse_unknown_keys`] does.
    /// The call checks nothing if
    /// [`Group::CLOSED`] of `G` is `false`. It checks each key against the key
    /// list of `G` alone, and gives the unknown-key text for a key outside
    /// the list. It names the first such key in the order of the file.
    ///
    /// For the removed key `collection` of a client group, the call gives
    /// the unknown-key text. [`check`](RepoConfig::check) gives a text that
    /// starts with `[HEADER] holds the removed key 'collection'` for this
    /// key.
    ///
    /// For the keys `gpg-verify-summary`, `sign-verify-summary`, and
    /// `verification-ENGINE-key` and `verification-ENGINE-file` of an engine
    /// other than `ed25519` and `spki` in a trust group, the call also gives
    /// the unknown-key text. [`check`](RepoConfig::check) and the readers of a
    /// trust group give a text that states the reason, as [`trust`] states.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] with the text `[HEADER] holds the unknown key
    /// 'KEY'`, where `HEADER` is the header of the group.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::RepoConfig;
    ///
    /// ostrya::config_group! {
    ///     pub group tool = "ex-tool", closed {
    ///         Jobs: Option<u32> = "jobs";
    ///     }
    /// }
    ///
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n[ex-tool]\njobs=4\n")?;
    /// cfg.refuse_unknown_keys::<tool::Group>()?;
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n[ex-tool]\nzzz=1\n")?;
    /// assert_eq!(
    ///     cfg.refuse_unknown_keys::<tool::Group>().unwrap_err().to_string(),
    ///     "invalid format: [ex-tool] holds the unknown key 'zzz'"
    /// );
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn refuse_unknown_keys<G: Group>(&self) -> Result<()> {
        ConfigView::new(&self.keyfile)
            .refuse_unknown_keys::<G>()
            .map_err(Error::from)
    }

    /// Returns the key files that hold the sections of the group `G`, each
    /// with the name of its `.conf` file, or `None` for `config`.
    fn sources<G: Group>(&self) -> impl Iterator<Item = (&KeyFile, Option<&str>)> {
        let is_remote = const { str_eq(G::NAME, <remote::Group as Group>::NAME) };
        let files: &[RemoteFile] = if is_remote { &self.remote_files } else { &[] };
        std::iter::once((&self.keyfile, None)).chain(
            files
                .iter()
                .map(|file| (&file.keyfile, Some(file.name.as_str()))),
        )
    }
}