ostrya 0.2.2

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
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
//! Typed view of the repository `config` file.
//!
//! [`RepoConfig`] wraps the [`KeyFile`] parsed from `<repo>/config` and applies
//! the value-level conventions the `ostree` tool uses: the `[core]` group with
//! `repo_version` and `mode`, the documented `[core]` tunables with their
//! defaults, the `[archive]` group, and `[remote "<name>"]` sections. The
//! `[ex-ostrya]` group carries the two keys that are ostrya extensions.
//!
//! The `repo_version` and `mode` keys are validated when the config is loaded,
//! matching the tool, which refuses to open a repository whose version is not
//! `1`. The remaining tunables are read on demand through accessors that apply
//! the documented default when the key is absent and surface a malformed value
//! as an error, the same way the tool reports a value it cannot interpret.
//!
//! The parsed [`KeyFile`] is retained so a caller can read keys this view does
//! not model and so the document reserializes in the order it was written.
//!
//! The write side is [`Repo::write_config`]: it replaces `config` atomically
//! with the document a caller edited through [`KeyFile`]'s own setters and
//! removers.

use ostrya_core::{KeyFile, RepoMode};

use crate::error::{Error, Result};
use crate::repo::Repo;

const CORE: &str = "core";
const ARCHIVE: &str = "archive";
const EX_INTEGRITY: &str = "ex-integrity";
const EX_OSTRYA: &str = "ex-ostrya";
/// The name of the repository file holding `config`.
const CONFIG_FILE: &str = "config";

/// A parsed repository configuration.
#[derive(Debug, Clone)]
pub struct RepoConfig {
    keyfile: KeyFile,
    mode: RepoMode,
    repo_version: i64,
    collection_id: Option<String>,
    remotes: Vec<String>,
}

/// The minimum free space a write must leave, as configured. A size, when set,
/// takes precedence over a percentage.
///
/// The byte value of a [`Size`](MinFreeSpace::Size) spec is applied by the
/// write path; this type carries the parsed magnitude and unit verbatim.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MinFreeSpace {
    /// `min-free-space-percent`, `0`-`100`. The default is `3`.
    Percent(u32),
    /// `min-free-space-size`, a magnitude with a binary unit suffix.
    Size(SizeSpec),
}

/// A `min-free-space-size` value: a magnitude and one of the `MB`, `GB`, `TB`
/// unit suffixes the tool accepts (regex `^([0-9]+)(G|M|T)B$`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SizeSpec {
    /// The numeric magnitude.
    pub value: u64,
    /// The unit suffix.
    pub unit: SizeUnit,
}

/// The unit suffix on a `min-free-space-size` value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeUnit {
    /// `MB`.
    Mega,
    /// `GB`.
    Giga,
    /// `TB`.
    Tera,
}

impl SizeUnit {
    /// The byte multiplier for this unit. The `MB`/`GB`/`TB` suffixes denote
    /// binary multiples (2^20, 2^30, 2^40).
    pub fn multiplier(self) -> u64 {
        match self {
            SizeUnit::Mega => 1 << 20,
            SizeUnit::Giga => 1 << 30,
            SizeUnit::Tera => 1 << 40,
        }
    }
}

impl SizeSpec {
    /// The value in bytes, saturating on overflow.
    pub fn bytes(self) -> u64 {
        self.value.saturating_mul(self.unit.multiplier())
    }
}

/// The `sign-verify` remote setting: which sign-api engines a pull checks the
/// signatures of the commits it fetches with.
///
/// The value is either a boolean, spelled the way the key file spells one, or a
/// list of engine names separated by `,` or `;`. A name is taken as written: the
/// space in `ed25519, ed25519` belongs to the second name, which no engine
/// answers to, and the tool refuses that value as well.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignVerify {
    /// No sign-api check: the key is absent, `false`, or names nothing.
    Off,
    /// Every engine this build has, which is what `true` selects.
    All,
    /// The engines the value names, in the order it names them.
    Engines(Vec<String>),
}

/// A tri-state repository setting, spelled `no`, `maybe`, or `yes`.
///
/// The `[ex-integrity]` keys use this form: `No` disables the feature, `Maybe`
/// enables it best-effort (ignoring a filesystem that cannot provide it), and
/// `Yes` requires it (failing where it cannot be provided).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tristate {
    /// The feature is disabled.
    No,
    /// Best effort: enable where supported, ignore where not.
    Maybe,
    /// Required: fail where the feature cannot be provided.
    Yes,
}

impl Tristate {
    /// Parse the `no`/`maybe`/`yes` spelling the tool writes.
    fn parse(raw: &str) -> Option<Tristate> {
        match raw {
            "no" => Some(Tristate::No),
            "maybe" => Some(Tristate::Maybe),
            "yes" => Some(Tristate::Yes),
            _ => None,
        }
    }
}

impl RepoConfig {
    /// Build a typed view over an already-parsed [`KeyFile`], validating the
    /// `[core]` `repo_version` and `mode` keys.
    pub fn from_keyfile(keyfile: KeyFile) -> Result<RepoConfig> {
        if !keyfile.has_group(CORE) {
            return Err(Error::InvalidFormat("config has no [core] group".into()));
        }

        let repo_version = keyfile
            .get_integer(CORE, "repo_version")?
            .ok_or_else(|| Error::InvalidFormat("config [core] has no repo_version".into()))?;
        if repo_version != 1 {
            return Err(Error::InvalidFormat(format!(
                "unsupported repository version {repo_version}"
            )));
        }

        let mode_str = keyfile
            .get_string(CORE, "mode")?
            .ok_or_else(|| Error::InvalidFormat("config [core] has no mode".into()))?;
        let mode = RepoMode::from_mode_str(&mode_str)
            .ok_or_else(|| Error::InvalidFormat(format!("unknown repository mode '{mode_str}'")))?;

        let collection_id = keyfile.get_string(CORE, "collection-id")?;

        // A repeated group header merges into one group during parsing, so
        // each remote name appears once already.
        let remotes: Vec<String> = keyfile
            .groups()
            .filter_map(remote_group_name)
            .map(str::to_owned)
            .collect();

        Ok(RepoConfig {
            keyfile,
            mode,
            repo_version,
            collection_id,
            remotes,
        })
    }

    /// Parse a config document from its text.
    pub fn parse(text: &str) -> Result<RepoConfig> {
        RepoConfig::from_keyfile(KeyFile::parse(text)?)
    }

    /// The repository storage mode.
    pub fn mode(&self) -> RepoMode {
        self.mode
    }

    /// The `[core] repo_version`. Always `1` for a config this type accepts.
    pub fn repo_version(&self) -> i64 {
        self.repo_version
    }

    /// The repository collection id, if `[core] collection-id` is set.
    pub fn collection_id(&self) -> Option<&str> {
        self.collection_id.as_deref()
    }

    /// The names of the configured remotes, in the order their sections appear.
    pub fn remotes(&self) -> impl Iterator<Item = &str> {
        self.remotes.iter().map(String::as_str)
    }

    /// A typed accessor for one remote, or `None` if no such section exists.
    pub fn remote(&self, name: &str) -> Option<Remote<'_>> {
        let group = remote_group(name);
        self.keyfile.has_group(&group).then_some(Remote {
            keyfile: &self.keyfile,
            group,
        })
    }

    /// Whether `fsync` durability is enabled. Default `true`.
    pub fn fsync(&self) -> Result<bool> {
        Ok(self.keyfile.get_bool(CORE, "fsync")?.unwrap_or(true))
    }

    /// Whether each object is fsynced individually. Default `false`.
    pub fn per_object_fsync(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "per-object-fsync")?
            .unwrap_or(false))
    }

    /// Whether repository locking is enabled. Default `true`.
    pub fn locking(&self) -> Result<bool> {
        Ok(self.keyfile.get_bool(CORE, "locking")?.unwrap_or(true))
    }

    /// The lock-acquisition timeout in seconds. Default `300`.
    pub fn lock_timeout_secs(&self) -> Result<i64> {
        Ok(self
            .keyfile
            .get_integer(CORE, "lock-timeout-secs")?
            .unwrap_or(300))
    }

    /// The staging-directory expiry in seconds. Default `86400`.
    pub fn tmp_expiry_secs(&self) -> Result<i64> {
        Ok(self
            .keyfile
            .get_integer(CORE, "tmp-expiry-secs")?
            .unwrap_or(86400))
    }

    /// Whether the repository advertises tombstone commits in its summary.
    /// Default `false`. The summary emits `ostree.summary.tombstone-commits`
    /// with this value.
    pub fn tombstone_commits(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "tombstone-commits")?
            .unwrap_or(false))
    }

    /// Whether the repository indexes its static deltas. Default `true`. The
    /// summary emits `ostree.summary.indexed-deltas` with this value.
    pub fn indexed_deltas(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "indexed-deltas")?
            .unwrap_or(true))
    }

    /// Whether xattr storage is disabled. Default `false`.
    pub fn disable_xattrs(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "disable-xattrs")?
            .unwrap_or(false))
    }

    /// The `[core] parent` repository path, if set.
    pub fn parent(&self) -> Result<Option<String>> {
        self.keyfile.get_string(CORE, "parent").map_err(Error::from)
    }

    /// The configured repo finders. Default `["config", "mount"]`.
    pub fn default_repo_finders(&self) -> Result<Vec<String>> {
        Ok(self
            .keyfile
            .get_string_list(CORE, "default-repo-finders")?
            .unwrap_or_else(|| vec!["config".to_owned(), "mount".to_owned()]))
    }

    /// The minimum free space a write must leave. A `min-free-space-size` value
    /// takes precedence; otherwise `min-free-space-percent` applies, defaulting
    /// to `3`.
    pub fn min_free_space(&self) -> Result<MinFreeSpace> {
        if let Some(raw) = self.keyfile.get_value(CORE, "min-free-space-size") {
            let spec = parse_size(raw).ok_or_else(|| {
                Error::InvalidFormat(format!("malformed min-free-space-size '{raw}'"))
            })?;
            return Ok(MinFreeSpace::Size(spec));
        }
        let percent = self
            .keyfile
            .get_integer(CORE, "min-free-space-percent")?
            .unwrap_or(3);
        if !(0..=100).contains(&percent) {
            return Err(Error::InvalidFormat(format!(
                "min-free-space-percent {percent} is out of the range 0-100"
            )));
        }
        Ok(MinFreeSpace::Percent(percent as u32))
    }

    /// The `[archive] zlib-level` compression level. Default `6`.
    pub fn zlib_level(&self) -> Result<i64> {
        Ok(self
            .keyfile
            .get_integer(ARCHIVE, "zlib-level")?
            .unwrap_or(6))
    }

    /// The `[ex-ostrya] gc-root-metadata-keys` setting: the metadata keys a
    /// prune reads for further reachable commits. Empty by default.
    ///
    /// The `ostrya prune` command puts this list into
    /// [`PruneOptions::gc_root_metadata_keys`](crate::PruneOptions::gc_root_metadata_keys).
    /// The list adds roots and removes none, and it carries no counterpart for
    /// [`traverse_parent`](crate::PruneOptions::traverse_parent), so a
    /// configured prune keeps at least what a prune with the tool's own
    /// reachability keeps.
    ///
    /// The library reads this key nowhere: [`Repo::prune`](crate::Repo::prune)
    /// acts on the options its caller supplies.
    pub fn gc_root_metadata_keys(&self) -> Result<Vec<String>> {
        self.string_list(EX_OSTRYA, "gc-root-metadata-keys")
    }

    /// The `[ex-ostrya] detached-metadata-exclude` setting: the detached
    /// metadata keys this repository does not store when it receives a commit,
    /// and does not send when it serves one. Empty by default.
    ///
    /// The `ostrya pull` and `ostrya pull-local` commands put this list into
    /// [`PullOptions::detached_metadata_filter`](crate::PullOptions::detached_metadata_filter)
    /// through
    /// [`DetachedMetadataFilter::excluding`](crate::DetachedMetadataFilter::excluding).
    /// Push is not implemented, so today the key acts on the receiving side
    /// alone.
    ///
    /// This list is never derived from
    /// [`gc_root_metadata_keys`](RepoConfig::gc_root_metadata_keys), even when
    /// the two lists are identical. A repository that roots on a key and does
    /// not list it in the exclude list keeps transferring it.
    ///
    /// The list governs what a pull stores, not what the repository already
    /// holds. A commit whose every detached-metadata key the list names leaves
    /// the copy the destination already holds where it stands, so setting this
    /// key and pulling again does not remove a copy an earlier pull stored.
    pub fn detached_metadata_exclude(&self) -> Result<Vec<String>> {
        self.string_list(EX_OSTRYA, "detached-metadata-exclude")
    }

    /// Read a `;`-separated list key, empty when the key is absent. A value the
    /// key-file syntax cannot split is reported as an error.
    fn string_list(&self, group: &str, key: &str) -> Result<Vec<String>> {
        Ok(self
            .keyfile
            .get_string_list(group, key)?
            .unwrap_or_default())
    }

    /// The `[ex-integrity] composefs` setting. Default `No`.
    ///
    /// This is read to compute the [`fsverity`](RepoConfig::fsverity) default.
    /// The composefs deployment behavior the key otherwise governs is out of
    /// scope for the write path.
    pub fn composefs(&self) -> Result<Tristate> {
        Ok(self
            .tristate(EX_INTEGRITY, "composefs")?
            .unwrap_or(Tristate::No))
    }

    /// The `[ex-integrity] fsverity` setting: whether loose objects are sealed
    /// with fs-verity as they are written.
    ///
    /// An explicit value is honored as written. When the key is absent it
    /// defaults to `No`, raised to `Maybe` when
    /// [`composefs`](RepoConfig::composefs) is `Yes` or `Maybe`; `composefs` is
    /// read only in that fallback.
    pub fn fsverity(&self) -> Result<Tristate> {
        if let Some(explicit) = self.tristate(EX_INTEGRITY, "fsverity")? {
            return Ok(explicit);
        }
        Ok(match self.composefs()? {
            Tristate::No => Tristate::No,
            Tristate::Maybe | Tristate::Yes => Tristate::Maybe,
        })
    }

    /// Read a tri-state key, returning `None` when it is absent and reporting a
    /// value that is not `no`/`maybe`/`yes` as a malformed config error.
    fn tristate(&self, group: &str, key: &str) -> Result<Option<Tristate>> {
        match self.keyfile.get_string(group, key)? {
            None => Ok(None),
            Some(raw) => Tristate::parse(&raw).map(Some).ok_or_else(|| {
                Error::InvalidFormat(format!("malformed [{group}] {key} value '{raw}'"))
            }),
        }
    }

    /// The parsed key file backing this view.
    pub fn keyfile(&self) -> &KeyFile {
        &self.keyfile
    }
}

impl Repo {
    /// Replace the repository `config` with the document `keyfile` holds.
    ///
    /// The file is written the way the rest of the write path writes a
    /// repository-root file: a fresh temporary file at mode `0644`,
    /// `fdatasync`ed when `[core] fsync` is set, renamed over `config`, with the
    /// repository directory synced after the rename. A reader therefore sees
    /// either the old document or the new one.
    ///
    /// The document is written as given. A caller that removes `[core] mode` or
    /// `[core] repo_version` writes a file [`Repo::open`] refuses, so read the
    /// current document through [`RepoConfig::keyfile`], edit it, and write it
    /// back.
    ///
    /// This handle keeps the configuration it was opened with; reopen the
    /// repository to read the new values.
    pub async fn write_config(&self, keyfile: &KeyFile) -> Result<()> {
        let fsync = self.config().fsync()?;
        self.write_root_file(CONFIG_FILE, keyfile.to_string().into_bytes(), fsync)
            .await
    }

    /// Remove a remote's trusted GPG keyring, `<remote>.trustedkeys.gpg`, at the
    /// repository root. An already-absent keyring is success.
    ///
    /// A remote's keyring belongs to its configuration section, so deleting the
    /// section deletes this file with it.
    pub async fn remove_remote_keyring(&self, remote: &str) -> Result<()> {
        self.remove_root_file(&remote_keyring_name(remote)).await
    }
}

/// The name of a remote's trusted keyring at the repository root.
pub(crate) fn remote_keyring_name(remote: &str) -> String {
    format!("{remote}.trustedkeys.gpg")
}

/// A typed accessor for one `[remote "<name>"]` section.
#[derive(Debug, Clone)]
pub struct Remote<'a> {
    keyfile: &'a KeyFile,
    group: String,
}

impl Remote<'_> {
    /// The base URL for objects and refs.
    pub fn url(&self) -> Result<Option<String>> {
        self.string("url")
    }

    /// The URL for content objects, when it differs from `url`.
    pub fn contenturl(&self) -> Result<Option<String>> {
        self.string("contenturl")
    }

    /// The metalink URL, when the remote is described by a metalink.
    pub fn metalink(&self) -> Result<Option<String>> {
        self.string("metalink")
    }

    /// Whether commits pulled from this remote are GPG-verified. Default
    /// `true`.
    pub fn gpg_verify(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(&self.group, "gpg-verify")?
            .unwrap_or(true))
    }

    /// Whether the summary of this remote is GPG-verified. Default `false`.
    pub fn gpg_verify_summary(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(&self.group, "gpg-verify-summary")?
            .unwrap_or(false))
    }

    /// The GPG keyrings this remote trusts beyond the repository's own
    /// `<remote>.trustedkeys.gpg` and the system trusted set: the `;`-separated
    /// entries of `gpgkeypath`, each a keyring file or a directory of them.
    pub fn gpgkeypath(&self) -> Result<Vec<String>> {
        Ok(self
            .string("gpgkeypath")?
            .map(|raw| {
                raw.split(';')
                    .filter(|entry| !entry.is_empty())
                    .map(str::to_owned)
                    .collect()
            })
            .unwrap_or_default())
    }

    /// Which sign-api engines a pull checks the commits of this remote with.
    /// Default [`SignVerify::Off`].
    pub fn sign_verify(&self) -> Result<SignVerify> {
        Ok(parse_sign_verify(self.string("sign-verify")?.as_deref()))
    }

    /// Which sign-api engines a pull checks this remote's summary with. Default
    /// [`SignVerify::Off`]. This is read on its own: `sign-verify=false` leaves
    /// a summary check the key asks for in place.
    pub fn sign_verify_summary(&self) -> Result<SignVerify> {
        Ok(parse_sign_verify(
            self.string("sign-verify-summary")?.as_deref(),
        ))
    }

    /// The inline trusted key for one sign-api engine,
    /// `verification-<engine>-key`. One key, not a list.
    pub fn verification_key(&self, engine: &str) -> Result<Option<String>> {
        self.string(&format!("verification-{engine}-key"))
    }

    /// The path to a file of trusted keys for one sign-api engine,
    /// `verification-<engine>-file`, holding one key per line.
    pub fn verification_file(&self, engine: &str) -> Result<Option<String>> {
        self.string(&format!("verification-{engine}-file"))
    }

    /// The collection id bound to this remote, if set.
    pub fn collection_id(&self) -> Result<Option<String>> {
        self.string("collection-id")
    }

    /// The refs a pull of this remote takes when it is asked for none.
    pub fn branches(&self) -> Result<Option<Vec<String>>> {
        self.keyfile
            .get_string_list(&self.group, "branches")
            .map_err(Error::from)
    }

    /// The path to a PEM file of trust anchors for this remote's TLS, replacing
    /// the host trust store.
    pub fn tls_ca_path(&self) -> Result<Option<String>> {
        self.string("tls-ca-path")
    }

    /// The path to the PEM client certificate chain presented to this remote.
    pub fn tls_client_cert_path(&self) -> Result<Option<String>> {
        self.string("tls-client-cert-path")
    }

    /// The path to the PEM private key of
    /// [`tls_client_cert_path`](Remote::tls_client_cert_path).
    pub fn tls_client_key_path(&self) -> Result<Option<String>> {
        self.string("tls-client-key-path")
    }

    /// Whether this remote's TLS certificate is accepted unverified. Default
    /// `false`. The fetcher has no way to skip verification, so a pull refuses a
    /// remote that sets this rather than verifying against the configuration.
    pub fn tls_permissive(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(&self.group, "tls-permissive")?
            .unwrap_or(false))
    }

    /// The raw value of an arbitrary key in this remote's section.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.keyfile.get_value(&self.group, key)
    }

    fn string(&self, key: &str) -> Result<Option<String>> {
        self.keyfile
            .get_string(&self.group, key)
            .map_err(Error::from)
    }
}

/// Read a `sign-verify` or `sign-verify-summary` value: a boolean in the key
/// file's own spelling, or a list of engine names separated by `,` or `;`.
fn parse_sign_verify(raw: Option<&str>) -> SignVerify {
    let Some(raw) = raw else {
        return SignVerify::Off;
    };
    match raw {
        "true" | "1" => return SignVerify::All,
        "false" | "0" => return SignVerify::Off,
        _ => {}
    }
    let engines: Vec<String> = raw
        .split([',', ';'])
        .filter(|name| !name.is_empty())
        .map(str::to_owned)
        .collect();
    if engines.is_empty() {
        return SignVerify::Off;
    }
    SignVerify::Engines(engines)
}

/// The key-file group name for a remote: `remote "<name>"`.
fn remote_group(name: &str) -> String {
    format!("remote \"{name}\"")
}

/// The remote name in a `remote "<name>"` group header, or `None` for any other
/// group.
fn remote_group_name(group: &str) -> Option<&str> {
    group
        .strip_prefix("remote \"")
        .and_then(|rest| rest.strip_suffix('"'))
}

/// Parse a `min-free-space-size` value against `^([0-9]+)(G|M|T)B$`.
fn parse_size(raw: &str) -> Option<SizeSpec> {
    let digits = raw
        .strip_suffix("MB")
        .map(|d| (d, SizeUnit::Mega))
        .or_else(|| {
            raw.strip_suffix("GB")
                .map(|d| (d, SizeUnit::Giga))
                .or_else(|| raw.strip_suffix("TB").map(|d| (d, SizeUnit::Tera)))
        });
    let (digits, unit) = digits?;
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let value = digits.parse::<u64>().ok()?;
    Some(SizeSpec { value, unit })
}

#[cfg(test)]
mod tests {
    use super::*;

    const ARCHIVE_CONFIG: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";

    #[test]
    fn parses_core_mode_and_version() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert_eq!(cfg.mode(), RepoMode::Archive);
        assert_eq!(cfg.repo_version(), 1);
        assert_eq!(cfg.collection_id(), None);
        assert_eq!(cfg.remotes().count(), 0);
    }

    #[test]
    fn rejects_unsupported_repo_version() {
        let err = RepoConfig::parse("[core]\nrepo_version=2\nmode=bare\n").unwrap_err();
        assert!(matches!(err, Error::InvalidFormat(_)));
        assert!(err.to_string().contains("version 2"));
    }

    #[test]
    fn rejects_missing_core_group_and_keys() {
        assert!(RepoConfig::parse("[other]\nx=1\n").is_err());
        assert!(RepoConfig::parse("[core]\nmode=bare\n").is_err());
        assert!(RepoConfig::parse("[core]\nrepo_version=1\n").is_err());
    }

    #[test]
    fn rejects_unknown_mode() {
        let err = RepoConfig::parse("[core]\nrepo_version=1\nmode=bogus\n").unwrap_err();
        assert!(err.to_string().contains("unknown repository mode 'bogus'"));
    }

    #[test]
    fn reads_collection_id() {
        let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\ncollection-id=org.ex.C\n")
            .unwrap();
        assert_eq!(cfg.collection_id(), Some("org.ex.C"));
    }

    #[test]
    fn tunables_default_when_absent() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert!(cfg.fsync().unwrap());
        assert!(!cfg.per_object_fsync().unwrap());
        assert!(cfg.locking().unwrap());
        assert_eq!(cfg.lock_timeout_secs().unwrap(), 300);
        assert_eq!(cfg.tmp_expiry_secs().unwrap(), 86400);
        assert!(!cfg.disable_xattrs().unwrap());
        assert_eq!(cfg.parent().unwrap(), None);
        assert_eq!(
            cfg.default_repo_finders().unwrap(),
            vec!["config".to_owned(), "mount".to_owned()]
        );
        assert_eq!(cfg.zlib_level().unwrap(), 6);
        assert_eq!(cfg.min_free_space().unwrap(), MinFreeSpace::Percent(3));
    }

    #[test]
    fn tunables_read_configured_values() {
        let text = "[core]\nrepo_version=1\nmode=bare\nfsync=false\n\
                    per-object-fsync=1\nlock-timeout-secs=30\nmin-free-space-percent=5\n\
                    [archive]\nzlib-level=9\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert!(!cfg.fsync().unwrap());
        assert!(cfg.per_object_fsync().unwrap());
        assert_eq!(cfg.lock_timeout_secs().unwrap(), 30);
        assert_eq!(cfg.min_free_space().unwrap(), MinFreeSpace::Percent(5));
        assert_eq!(cfg.zlib_level().unwrap(), 9);
    }

    #[test]
    fn bad_boolean_value_is_an_error() {
        let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nfsync=yes\n").unwrap();
        assert!(cfg.fsync().is_err());
    }

    #[test]
    fn min_free_space_size_wins_over_percent() {
        let text = "[core]\nrepo_version=1\nmode=bare\n\
                    min-free-space-percent=5\nmin-free-space-size=2GB\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(
            cfg.min_free_space().unwrap(),
            MinFreeSpace::Size(SizeSpec {
                value: 2,
                unit: SizeUnit::Giga
            })
        );
    }

    #[test]
    fn rejects_out_of_range_min_free_space_percent() {
        for bad in ["-1", "101"] {
            let text = format!("[core]\nrepo_version=1\nmode=bare\nmin-free-space-percent={bad}\n");
            let cfg = RepoConfig::parse(&text).unwrap();
            assert!(cfg.min_free_space().is_err(), "should reject {bad}");
        }
    }

    #[test]
    fn min_free_space_size_units_and_rejection() {
        for (raw, unit) in [
            ("500MB", SizeUnit::Mega),
            ("1GB", SizeUnit::Giga),
            ("3TB", SizeUnit::Tera),
        ] {
            assert_eq!(parse_size(raw).unwrap().unit, unit);
        }
        for bad in ["1G", "GB", "1KB", "1gb", "1GB ", "", "1.5GB"] {
            assert!(parse_size(bad).is_none(), "should reject {bad:?}");
        }
    }

    #[test]
    fn ex_integrity_defaults_off() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert_eq!(cfg.composefs().unwrap(), Tristate::No);
        assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
    }

    #[test]
    fn composefs_raises_fsverity_default_to_maybe() {
        for composefs in ["yes", "maybe"] {
            let text = format!(
                "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\ncomposefs={composefs}\n"
            );
            let cfg = RepoConfig::parse(&text).unwrap();
            assert_eq!(
                cfg.fsverity().unwrap(),
                Tristate::Maybe,
                "composefs={composefs}"
            );
        }
        // composefs=no leaves fsverity off.
        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\ncomposefs=no\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
    }

    #[test]
    fn explicit_fsverity_overrides_the_composefs_default() {
        // An explicit fsverity value wins over the composefs-derived default.
        let text = "[core]\nrepo_version=1\nmode=bare\n\
                    [ex-integrity]\ncomposefs=yes\nfsverity=no\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.fsverity().unwrap(), Tristate::No);

        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\nfsverity=yes\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.fsverity().unwrap(), Tristate::Yes);
    }

    #[test]
    fn malformed_tristate_is_an_error() {
        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\nfsverity=true\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert!(cfg.fsverity().is_err());
    }

    #[test]
    fn explicit_fsverity_ignores_a_malformed_composefs() {
        // An explicit fsverity value is honored without consulting composefs, so
        // a malformed composefs does not fail the fsverity read.
        let text = "[core]\nrepo_version=1\nmode=bare\n\
                    [ex-integrity]\ncomposefs=perhaps\nfsverity=no\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
    }

    #[test]
    fn ex_ostrya_lists_are_empty_when_absent() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert!(cfg.gc_root_metadata_keys().unwrap().is_empty());
        assert!(cfg.detached_metadata_exclude().unwrap().is_empty());
    }

    #[test]
    fn ex_ostrya_lists_parse_their_values() {
        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-ostrya]\n\
                    gc-root-metadata-keys=app.roots;app.caches\n\
                    detached-metadata-exclude=app.roots\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(
            cfg.gc_root_metadata_keys().unwrap(),
            vec!["app.roots".to_owned(), "app.caches".to_owned()]
        );
        assert_eq!(
            cfg.detached_metadata_exclude().unwrap(),
            vec!["app.roots".to_owned()]
        );
    }

    #[test]
    fn an_ex_ostrya_list_takes_a_trailing_separator() {
        // The key-file list convention writes a trailing `;`, which adds no
        // empty element.
        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-ostrya]\n\
                    gc-root-metadata-keys=app.roots;app.caches;\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(
            cfg.gc_root_metadata_keys().unwrap(),
            vec!["app.roots".to_owned(), "app.caches".to_owned()]
        );
    }

    #[test]
    fn a_malformed_ex_ostrya_list_is_an_error() {
        // A value ending in a lone backslash is not a list the key-file syntax
        // can split.
        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-ostrya]\n\
                    detached-metadata-exclude=app.roots\\\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert!(cfg.detached_metadata_exclude().is_err());
    }

    #[test]
    fn parses_remote_sections() {
        let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
                    [remote \"origin\"]\nurl=https://example.com/repo\nbranches=main;\n\
                    gpg-verify=false\n\n\
                    [remote \"withkey\"]\nurl=https://ex2.com/r\ncollection-id=org.ex.C\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.remotes().collect::<Vec<_>>(), ["origin", "withkey"]);

        let origin = cfg.remote("origin").unwrap();
        assert_eq!(
            origin.url().unwrap().as_deref(),
            Some("https://example.com/repo")
        );
        assert!(!origin.gpg_verify().unwrap());
        assert!(!origin.gpg_verify_summary().unwrap());
        assert_eq!(origin.get("branches"), Some("main;"));
        assert_eq!(origin.branches().unwrap(), Some(vec!["main".to_owned()]));
        assert!(!origin.tls_permissive().unwrap());
        assert_eq!(origin.tls_ca_path().unwrap(), None);

        let withkey = cfg.remote("withkey").unwrap();
        assert!(withkey.gpg_verify().unwrap()); // default true
        assert_eq!(
            withkey.collection_id().unwrap().as_deref(),
            Some("org.ex.C")
        );

        assert!(cfg.remote("absent").is_none());
    }

    /// The verification keys a pull reads its policy from: the two sign-api
    /// switches, the per-engine key sources, and the GPG keyring list.
    #[test]
    fn reads_remote_verification_keys() {
        let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
                    [remote \"signed\"]\nurl=https://ex.com/r\nsign-verify=ed25519\n\
                    sign-verify-summary=true\nverification-ed25519-key=AAAA\n\
                    verification-ed25519-file=/etc/keys.ed25519\n\
                    gpgkeypath=/etc/one.gpg;/etc/keys.d\n";
        let cfg = RepoConfig::parse(text).unwrap();
        let remote = cfg.remote("signed").unwrap();
        assert_eq!(
            remote.sign_verify().unwrap(),
            SignVerify::Engines(vec!["ed25519".to_owned()])
        );
        assert_eq!(remote.sign_verify_summary().unwrap(), SignVerify::All);
        assert_eq!(
            remote.verification_key("ed25519").unwrap().as_deref(),
            Some("AAAA")
        );
        assert_eq!(
            remote.verification_file("ed25519").unwrap().as_deref(),
            Some("/etc/keys.ed25519")
        );
        assert_eq!(remote.verification_key("spki").unwrap(), None);
        assert_eq!(
            remote.gpgkeypath().unwrap(),
            vec!["/etc/one.gpg".to_owned(), "/etc/keys.d".to_owned()]
        );

        // The defaults: no sign-api check and no extra keyring.
        let plain = cfg.remote("signed").unwrap();
        assert!(plain.gpg_verify().unwrap());
        let bare = RepoConfig::parse(
            "[core]\nrepo_version=1\nmode=bare\n\n[remote \"plain\"]\nurl=http://ex/r\n",
        )
        .unwrap();
        let bare = bare.remote("plain").unwrap();
        assert_eq!(bare.sign_verify().unwrap(), SignVerify::Off);
        assert_eq!(bare.sign_verify_summary().unwrap(), SignVerify::Off);
        assert!(bare.gpgkeypath().unwrap().is_empty());
    }

    /// `sign-verify` is a boolean or a list of engine names, split on `,` and
    /// `;`, each name taken as written.
    #[test]
    fn parses_the_sign_verify_spellings() {
        assert_eq!(parse_sign_verify(None), SignVerify::Off);
        assert_eq!(parse_sign_verify(Some("true")), SignVerify::All);
        assert_eq!(parse_sign_verify(Some("1")), SignVerify::All);
        assert_eq!(parse_sign_verify(Some("false")), SignVerify::Off);
        assert_eq!(parse_sign_verify(Some("0")), SignVerify::Off);
        assert_eq!(parse_sign_verify(Some("")), SignVerify::Off);
        assert_eq!(
            parse_sign_verify(Some("ed25519")),
            SignVerify::Engines(vec!["ed25519".to_owned()])
        );
        // Both separators, and an empty element dropped.
        assert_eq!(
            parse_sign_verify(Some("ed25519;spki,")),
            SignVerify::Engines(vec!["ed25519".to_owned(), "spki".to_owned()])
        );
        // A name is not trimmed: the tool refuses this value too.
        assert_eq!(
            parse_sign_verify(Some("ed25519, ed25519")),
            SignVerify::Engines(vec!["ed25519".to_owned(), " ed25519".to_owned()])
        );
    }

    /// The TLS keys a pull fills its fetcher's options from, and the one it
    /// refuses rather than misrepresent.
    #[test]
    fn reads_remote_tls_keys() {
        let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
                    [remote \"secure\"]\nurl=https://ex.com/r\ntls-ca-path=/etc/ca.pem\n\
                    tls-client-cert-path=/etc/client.pem\ntls-client-key-path=/etc/client.key\n\
                    tls-permissive=true\n";
        let cfg = RepoConfig::parse(text).unwrap();
        let remote = cfg.remote("secure").unwrap();
        assert_eq!(
            remote.tls_ca_path().unwrap().as_deref(),
            Some("/etc/ca.pem")
        );
        assert_eq!(
            remote.tls_client_cert_path().unwrap().as_deref(),
            Some("/etc/client.pem")
        );
        assert_eq!(
            remote.tls_client_key_path().unwrap().as_deref(),
            Some("/etc/client.key")
        );
        assert!(remote.tls_permissive().unwrap());
    }
}