ostrya 0.19.1

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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
//! Tests of GPG verification in a pull.
//!
//! GPG verification is the same for each source of a pull. These tests use a
//! local pull, which needs no server. They test the sources of the trusted
//! keyrings and the error that each refusal reports. The test of an absent
//! `summary.sig` uses a pull over HTTP from an in-process server.
//!
//! Each test generates a temporary signing key in a private GnuPG home
//! directory under its scratch tree. ostrya signs a commit through the `gpg`
//! binary. The pull verifies the signature in the process against the
//! exported keyring. The tests do not use the GnuPG home or the agent of the
//! user.

#![cfg(feature = "sign-gpg")]

mod common;
#[path = "common/pull.rs"]
mod pull;

use std::os::fd::AsFd;
use std::path::{Path, PathBuf};
use std::process::Command;

use common::TmpDir;
use ostrya::{
    AdvertisedDelta, Checksum, CommitModifier, CommitModifierFlags, CommitOptions, CommitState,
    CreateOptions, DeltaOptions, Error, GpgSigner, MutableTree, OpenOptions, PullOptions,
    PullVerify, Ref, RemotesDir, Repo, RepoMode,
};
use ostrya_rt::block_on;

/// A fixed timestamp that makes the commit of a source repository
/// reproducible.
const FIXED_TS: u64 = 1_700_000_000;

/// Returns `true` if the `gpg` binary is available.
///
/// The GnuPG tests build their fixtures with `gpg`. If it is absent, these
/// tests skip: they return before an assertion runs.
/// [`common::REQUIRE_GNUPG`] changes the skip into a failure.
fn gpg_available() -> bool {
    common::gnupg_available(&["gpg"])
}

/// A private GnuPG home directory with one new ed25519 signing key.
///
/// The key has no passphrase. A drop of the fixture stops the GnuPG daemons
/// of the directory and removes their socket directory.
struct GpgHome {
    dir: PathBuf,
}

impl GpgHome {
    /// Generates a signing key for `uid` in a new home directory under `base`.
    fn create(base: &Path, name: &str, uid: &str) -> GpgHome {
        use std::os::unix::fs::DirBuilderExt;
        let dir = base.join(name);
        std::fs::DirBuilder::new().mode(0o700).create(&dir).unwrap();
        let home = GpgHome { dir };
        let status = home
            .gpg()
            .args(["--pinentry-mode", "loopback", "--passphrase", ""])
            .args(["--quick-gen-key", uid, "ed25519", "sign", "never"])
            .status()
            .unwrap();
        assert!(status.success(), "gpg --quick-gen-key failed");
        home
    }

    /// Returns a `gpg` command in batch mode for this home directory.
    fn gpg(&self) -> Command {
        let mut cmd = Command::new("gpg");
        cmd.arg("--homedir").arg(&self.dir).arg("--batch");
        cmd
    }

    /// Returns the fingerprint of the primary key as uppercase hex.
    fn fingerprint(&self) -> String {
        let out = self
            .gpg()
            .args(["--with-colons", "--list-keys"])
            .output()
            .unwrap();
        assert!(out.status.success());
        let text = String::from_utf8(out.stdout).unwrap();
        text.lines()
            .find_map(|line| {
                let mut fields = line.split(':');
                (fields.next() == Some("fpr")).then(|| fields.nth(8).unwrap().to_owned())
            })
            .expect("a fpr record in the key listing")
    }

    /// Writes the exported public keyring to `path`.
    fn export_to(&self, path: &Path) {
        let out = self.gpg().arg("--export").output().unwrap();
        assert!(out.status.success() && !out.stdout.is_empty());
        std::fs::write(path, out.stdout).unwrap();
    }

    /// Returns a signer for this key.
    fn signer(&self) -> GpgSigner {
        GpgSigner::new(self.fingerprint()).with_homedir(&self.dir)
    }
}

impl Drop for GpgHome {
    fn drop(&mut self) {
        common::remove_gnupg_sockets(&self.dir);
    }
}

/// Creates a source repository under `base/src` with the ref `main`.
///
/// The commit of `main` holds a tree with one file.
async fn source_repo(base: &Path) -> (Repo, Checksum) {
    let tree = base.join("tree");
    std::fs::create_dir_all(&tree).unwrap();
    std::fs::write(tree.join("hello.txt"), b"hello\n").unwrap();

    let repo = Repo::create(&base.join("src"), CreateOptions::new(RepoMode::Archive))
        .await
        .unwrap();
    let txn = repo.transaction().await.unwrap();
    let mut mtree = MutableTree::new();
    let mut modifier = CommitModifier::new(CommitModifierFlags::SKIP_XATTRS);
    let dfd = std::fs::File::open(base).unwrap();
    txn.write_dfd_to_mtree(
        dfd.as_fd(),
        Path::new("tree"),
        &mut mtree,
        Some(&mut modifier),
    )
    .await
    .unwrap();
    let root = txn.write_mtree(&mut mtree).await.unwrap();
    let commit = txn
        .write_commit(
            CommitOptions {
                subject: Some("main".to_owned()),
                timestamp: Some(FIXED_TS),
                ..CommitOptions::default()
            },
            &root,
        )
        .await
        .unwrap();
    txn.set_ref(&Ref::local("main"), Some(&commit));
    txn.commit().await.unwrap();
    (repo, commit)
}

/// Creates a destination repository under `base/<name>` with the remote
/// `origin`.
///
/// The `[remote "origin"]` group of the config gets the keys in `extra`.
async fn dest_with_remote(base: &Path, name: &str, extra: &str) -> (PathBuf, Repo) {
    let path = base.join(name);
    let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
        .await
        .unwrap();
    drop(repo);
    let config = path.join("config");
    let mut text = std::fs::read_to_string(&config).unwrap();
    text.push_str(&format!(
        "\n[remote \"origin\"]\nurl=file:///dev/null\n{extra}"
    ));
    std::fs::write(&config, text).unwrap();
    let repo = Repo::open(&path).await.unwrap();
    (path, repo)
}

/// Pulls `main` from `src` into `dst` with GPG verification turned on.
async fn gpg_pull(dst: &Repo, src: &Repo) -> Result<(), Error> {
    dst.pull_local(
        src,
        PullOptions {
            refs: vec!["main".to_owned()],
            remote: Some("origin".to_owned()),
            verify: PullVerify {
                gpg: Some(true),
                ..PullVerify::default()
            },
            ..PullOptions::default()
        },
    )
    .await
    .map(|_| ())
}

/// Commits the tree under `base/<name>` into `repo` on `main`, with `parent`.
/// The tree holds one file with the marker `<name>`.
async fn commit_marker(repo: &Repo, base: &Path, name: &str, parent: Option<Checksum>) -> Checksum {
    let tree = base.join(name);
    std::fs::create_dir_all(&tree).unwrap();
    std::fs::write(tree.join("marker.txt"), format!("{name}\n")).unwrap();
    let txn = repo.transaction().await.unwrap();
    let mut mtree = MutableTree::new();
    let mut modifier = CommitModifier::new(CommitModifierFlags::SKIP_XATTRS);
    let dfd = std::fs::File::open(base).unwrap();
    txn.write_dfd_to_mtree(
        dfd.as_fd(),
        Path::new(name),
        &mut mtree,
        Some(&mut modifier),
    )
    .await
    .unwrap();
    let root = txn.write_mtree(&mut mtree).await.unwrap();
    let commit = txn
        .write_commit(
            CommitOptions {
                parent,
                subject: Some(name.to_owned()),
                timestamp: Some(FIXED_TS),
                ..CommitOptions::default()
            },
            &root,
        )
        .await
        .unwrap();
    txn.set_ref(&Ref::local("main"), Some(&commit));
    txn.commit().await.unwrap();
    commit
}

/// Creates an archive source under `base/src` with the commit B and its
/// child C on `main`, and the deltas from scratch to B and from B to C.
///
/// Returns the source, B, C, and the list of the two deltas, each with the
/// SHA-256 of its superblock.
async fn chain_source(base: &Path) -> (Repo, Checksum, Checksum, Vec<AdvertisedDelta>) {
    let repo = Repo::create(&base.join("src"), CreateOptions::new(RepoMode::Archive))
        .await
        .unwrap();
    let b = commit_marker(&repo, base, "b", None).await;
    let c = commit_marker(&repo, base, "c", Some(b)).await;
    let mut list = Vec::new();
    for (from, to) in [(None, b), (Some(b), c)] {
        let dir = repo
            .generate_static_delta(from.as_ref(), &to, &DeltaOptions::default())
            .await
            .unwrap();
        let bytes = std::fs::read(repo.path().join(dir).join("superblock")).unwrap();
        list.push(AdvertisedDelta {
            from,
            to,
            superblock: Checksum::sha256(&bytes),
        });
    }
    (repo, b, c, list)
}

/// Pulls `main` from `src` into `dst` under the remote `origin`, with the
/// list `list`. GPG verification is on if `gpg` is `true`.
async fn gpg_chain_pull(
    dst: &Repo,
    src: &Repo,
    list: Vec<AdvertisedDelta>,
    gpg: bool,
) -> Result<(), Error> {
    dst.pull_local(
        src,
        PullOptions {
            refs: vec!["main".to_owned()],
            remote: Some("origin".to_owned()),
            static_deltas: Some(list),
            verify: PullVerify {
                gpg: Some(gpg),
                ..PullVerify::default()
            },
            ..PullOptions::default()
        },
    )
    .await
    .map(|_| ())
}

/// Asserts that the repository at `dir` keeps no `.commitpartial` marker and
/// no staging directory.
fn assert_no_markers(dir: &Path) {
    let markers: Vec<String> = std::fs::read_dir(dir.join("state"))
        .unwrap()
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .filter(|name| name.ends_with(".commitpartial"))
        .collect();
    assert!(markers.is_empty(), "{markers:?}");
    let staging: Vec<String> = std::fs::read_dir(dir.join("tmp"))
        .unwrap()
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .filter(|name| name.starts_with("staging-"))
        .collect();
    assert!(staging.is_empty(), "{staging:?}");
}

/// Asserts that `dst` holds `commit` complete: the commit has no
/// `.commitpartial` marker, and `dst` holds each object that `src` reaches
/// from it.
async fn assert_complete(src: &Repo, dst: &Repo, commit: &Checksum) {
    assert_eq!(dst.commit_state(commit).await.unwrap(), CommitState::Normal);
    for name in &src.traverse_commit(commit, 0).await.unwrap() {
        assert!(
            dst.has_object(name.ty, &name.checksum).await.unwrap(),
            "{name} missing from the destination"
        );
    }
}

/// GPG verification applies to the intermediate commit of a chain of static
/// deltas.
///
/// - The chain is the delta from scratch to B, then the delta from B to C.
///   The key signs C alone. The pull refuses B before the transaction opens:
///   it writes no ref, no object, no marker, and no staging directory.
/// - With GPG verification off, the same list passes into another
///   destination.
/// - After the key signs B, the list passes under GPG verification into the
///   first destination.
#[test]
fn an_unsigned_intermediate_commit_fails_gpg_verification() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-chain");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");

    block_on(async {
        let (src, b, c, list) = chain_source(base).await;
        let signer = signer_home.signer();
        src.sign_commit(&c, &signer).await.unwrap();

        let (path, dst) = dest_with_remote(base, "dst-gpg", "").await;
        signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
        let err = gpg_chain_pull(&dst, &src, list.clone(), true)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.starts_with(&format!("commit {b}: GPG "))),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());
        assert!(dst.list_objects().await.unwrap().is_empty());
        assert_no_markers(&path);

        let (off_path, off) = dest_with_remote(base, "dst-off", "").await;
        gpg_chain_pull(&off, &src, list.clone(), false)
            .await
            .unwrap();
        assert_eq!(off.resolve_rev("origin:main", true).await.unwrap(), Some(c));
        for commit in [b, c] {
            assert_complete(&src, &off, &commit).await;
        }
        assert_no_markers(&off_path);

        src.sign_commit(&b, &signer).await.unwrap();
        gpg_chain_pull(&dst, &src, list, true).await.unwrap();
        assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), Some(c));
        for commit in [b, c] {
            assert_complete(&src, &dst, &commit).await;
        }
        assert_no_markers(&path);
    });
}

/// The trusted set of a remote starts with `<remote>.trustedkeys.gpg` in the
/// repository.
///
/// - A commit that the key of this keyring signed passes.
/// - If the keyring of the destination holds a different key, the pull
///   refuses the same commit.
/// - The pull refuses an unsigned commit, because it has no signature to
///   verify.
#[test]
fn the_repository_keyring_is_what_a_remote_trusts() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-keyring");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
    let other_home = GpgHome::create(base, "gnupg-other", "Other <other@example.invalid>");

    block_on(async {
        let (src, commit) = source_repo(base).await;

        // An unsigned commit has no signature to verify.
        let (path, dst) = dest_with_remote(base, "dst-unsigned", "").await;
        signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("carries no signature")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());

        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();

        // A keyring with the signing key accepts the commit.
        let (path, dst) = dest_with_remote(base, "dst-trusted", "").await;
        signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
        gpg_pull(&dst, &src).await.unwrap();
        assert_eq!(
            dst.resolve_rev("origin:main", true).await.unwrap(),
            Some(commit)
        );

        // A keyring with a different key refuses the commit.
        let (path, dst) = dest_with_remote(base, "dst-other", "").await;
        other_home.export_to(&path.join("origin.trustedkeys.gpg"));
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("is from a trusted key")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());
    });
}

/// A remote with a GPG trust group takes the keys of the commits from the
/// keyrings that the group names alone. The repository keyring
/// `<repo>/origin.trustedkeys.gpg` does not verify a commit of the remote.
/// The GPG check of the summary still reads the repository keyring.
///
/// - The repository keyring holds the key of the commit, and the group names
///   a keyring of another key: the pull refuses the commit.
/// - The group names the keyring of the key of the commit, and the
///   repository holds no keyring: the pull takes the commit.
/// - The remote sets `gpg-verify-summary=true`, and the summary has a
///   signature of a key that the repository keyring alone holds: the pull
///   takes the commit and the summary. If the repository keyring holds the
///   key of the group in place of that key, the pull refuses the summary.
#[test]
fn a_gpg_trust_group_reads_no_repository_keyring() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-trust");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
    let other_home = GpgHome::create(base, "gnupg-other", "Other <other@example.invalid>");
    let signer_keyring = base.join("signer.gpg");
    let other_keyring = base.join("other.gpg");
    signer_home.export_to(&signer_keyring);
    other_home.export_to(&other_keyring);
    let trust = |keyring: &Path, extra: &str| {
        format!(
            "gpg-verify=false\ntrust=t\n{extra}[ex-ostrya trust \"t\"]\ngpg-verify=true\n\
             gpgkeypath={}\n",
            keyring.display()
        )
    };
    // The default policy: the remote and its trust group set the checks.
    let opts = PullOptions {
        refs: vec!["main".to_owned()],
        remote: Some("origin".to_owned()),
        ..PullOptions::default()
    };

    block_on(async {
        let (src, commit) = source_repo(base).await;
        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();

        let (path, dst) = dest_with_remote(base, "dst-keyring", &trust(&other_keyring, "")).await;
        signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
        let err = dst.pull_local(&src, opts.clone()).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("is from a trusted key")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());

        let (_path, dst) = dest_with_remote(base, "dst-group", &trust(&signer_keyring, "")).await;
        dst.pull_local(&src, opts.clone()).await.unwrap();
        assert_eq!(
            dst.resolve_rev("origin:main", true).await.unwrap(),
            Some(commit)
        );

        src.regenerate_summary(&ostrya::SummaryOptions {
            last_modified: Some(FIXED_TS),
            ..ostrya::SummaryOptions::default()
        })
        .await
        .unwrap();
        src.sign_summary(&other_home.signer()).await.unwrap();
        let (path, dst) = dest_with_remote(
            base,
            "dst-summary",
            &trust(&signer_keyring, "gpg-verify-summary=true\n"),
        )
        .await;
        // The repository keyring holds the key of the group alone, and the
        // summary check refuses the summary.
        signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
        let err = dst.pull_local(&src, opts.clone()).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("is from a trusted key")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());
        other_home.export_to(&path.join("origin.trustedkeys.gpg"));
        dst.pull_local(&src, opts.clone()).await.unwrap();
        assert_eq!(
            dst.resolve_rev("origin:main", true).await.unwrap(),
            Some(commit)
        );
    });
}

/// The pull follows a symlink at `<remote>.trustedkeys.gpg`.
///
/// The remote trusts the keyring that the symlink names. The `ostree` command
/// does the same in observation. If `origin.trustedkeys.gpg` is a symlink to
/// an exported keyring, the pull accepts a commit that the key of this keyring
/// signed.
#[test]
fn a_symlinked_repository_keyring_is_followed() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-symlink");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");

    block_on(async {
        let (src, commit) = source_repo(base).await;
        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();

        let keyring = base.join("elsewhere.gpg");
        signer_home.export_to(&keyring);
        let (path, dst) = dest_with_remote(base, "dst-symlink", "").await;
        std::os::unix::fs::symlink(&keyring, path.join("origin.trustedkeys.gpg")).unwrap();

        gpg_pull(&dst, &src).await.unwrap();
        assert_eq!(
            dst.resolve_rev("origin:main", true).await.unwrap(),
            Some(commit)
        );
    });
}

/// Opens the repository at `path` with the remotes directory `dir`.
async fn open_with_dir(path: &Path, dir: RemotesDir) -> Repo {
    OpenOptions::new()
        .remotes_dir(dir)
        .open(path)
        .await
        .unwrap()
}

/// When the repository holds no `<remote>.trustedkeys.gpg`, the trusted set
/// of a remote starts with the file of that name in the remotes directory of
/// the handle. A commit that the key of this keyring signed passes:
///
/// - for a remote of `config`, with a [`RemotesDir::Path`] value;
/// - for a remote of a `.conf` file of the remotes directory;
/// - with a [`RemotesDir::InRepo`] value;
/// - with a [`RemotesDir::Fd`] value.
#[test]
fn a_keyring_of_the_remotes_directory_is_what_a_remote_trusts() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-dir-keyring");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");

    block_on(async {
        let (src, commit) = source_repo(base).await;
        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();
        let mut handles = Vec::new();

        let (path, dst) = dest_with_remote(base, "dst-config", "").await;
        drop(dst);
        let dir = base.join("remotes-config.d");
        std::fs::create_dir(&dir).unwrap();
        signer_home.export_to(&dir.join("origin.trustedkeys.gpg"));
        handles.push(("config", open_with_dir(&path, RemotesDir::path(&dir)).await));

        let path = base.join("dst-file");
        Repo::create(&path, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let dir = base.join("remotes-file.d");
        std::fs::create_dir(&dir).unwrap();
        std::fs::write(
            dir.join("origin.conf"),
            "[remote \"origin\"]\nurl=file:///dev/null\n",
        )
        .unwrap();
        signer_home.export_to(&dir.join("origin.trustedkeys.gpg"));
        handles.push(("file", open_with_dir(&path, RemotesDir::path(&dir)).await));

        let (path, dst) = dest_with_remote(base, "dst-in-repo", "").await;
        drop(dst);
        std::fs::create_dir(path.join("remotes.d")).unwrap();
        signer_home.export_to(&path.join("remotes.d").join("origin.trustedkeys.gpg"));
        let in_repo = RemotesDir::InRepo(PathBuf::from("remotes.d"));
        handles.push(("in-repo", open_with_dir(&path, in_repo).await));

        let (path, dst) = dest_with_remote(base, "dst-fd", "").await;
        drop(dst);
        let dir = base.join("remotes-fd.d");
        std::fs::create_dir(&dir).unwrap();
        signer_home.export_to(&dir.join("origin.trustedkeys.gpg"));
        let fd = std::os::fd::OwnedFd::from(std::fs::File::open(&dir).unwrap());
        handles.push(("fd", open_with_dir(&path, RemotesDir::from(fd)).await));

        for (label, dst) in handles {
            gpg_pull(&dst, &src)
                .await
                .unwrap_or_else(|e| panic!("{label}: {e}"));
            assert_eq!(
                dst.resolve_rev("origin:main", true).await.unwrap(),
                Some(commit),
                "{label}"
            );
        }
    });
}

/// A repository keyring that exists hides the keyring of the remotes
/// directory. The keyring of the remotes directory holds the key of the
/// commit. The pull refuses the commit and writes no ref:
///
/// - when the repository keyring holds another key;
/// - when the repository keyring is empty.
#[test]
fn the_repository_keyring_hides_the_keyring_of_the_remotes_directory() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-dir-hidden");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
    let other_home = GpgHome::create(base, "gnupg-other", "Other <other@example.invalid>");
    let dir = base.join("remotes.d");
    std::fs::create_dir(&dir).unwrap();
    signer_home.export_to(&dir.join("origin.trustedkeys.gpg"));

    block_on(async {
        let (src, commit) = source_repo(base).await;
        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();
        for (name, other) in [("dst-other", true), ("dst-empty", false)] {
            let (path, dst) = dest_with_remote(base, name, "").await;
            drop(dst);
            let keyring = path.join("origin.trustedkeys.gpg");
            if other {
                other_home.export_to(&keyring);
            } else {
                std::fs::write(&keyring, b"").unwrap();
            }
            let dst = open_with_dir(&path, RemotesDir::path(&dir)).await;
            let err = gpg_pull(&dst, &src).await.unwrap_err();
            assert!(
                matches!(&err, Error::Signature(m) if m.contains("is from a trusted key")),
                "{name}: {err}"
            );
            assert!(dst.list_refs(None).await.unwrap().is_empty(), "{name}");
        }
    });
}

/// The environment variable that tells the child process of
/// [`a_handle_with_no_remotes_directory_reads_no_keyring_of_a_directory`]
/// where its scratch tree is.
const NO_DIR_CHILD_ENV: &str = "OSTRYA_NO_REMOTES_DIR_TEST";

/// A handle with no remotes directory reads no keyring of a directory.
///
/// The test runs this test binary again with `OSTREE_GPG_HOME` set to an
/// empty directory, so the global trusted directory of the host takes no
/// part. [`no_remotes_directory_subprocess`] does the pull.
#[test]
fn a_handle_with_no_remotes_directory_reads_no_keyring_of_a_directory() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-no-dir");
    let global = tmp.path().join("global");
    std::fs::create_dir(&global).unwrap();
    let child = Command::new(std::env::current_exe().unwrap())
        .args([
            "no_remotes_directory_subprocess",
            "--exact",
            "--ignored",
            "--nocapture",
        ])
        .env("OSTREE_GPG_HOME", &global)
        .env(NO_DIR_CHILD_ENV, tmp.path())
        .output()
        .expect("re-execute this test binary");
    let stdout = String::from_utf8_lossy(&child.stdout);
    assert!(
        child.status.success() && stdout.contains("1 passed"),
        "the child reported {}:\n{stdout}{}",
        child.status,
        String::from_utf8_lossy(&child.stderr),
    );
}

/// The half of
/// [`a_handle_with_no_remotes_directory_reads_no_keyring_of_a_directory`]
/// that does the pull. It runs only if this test binary runs again with the
/// environment set.
///
/// The repository holds no keyring of the remote, and the handle has no
/// remotes directory. `<repo>/remotes.d/origin.trustedkeys.gpg` holds the key
/// of the commit. A handle that took `remotes.d` in the repository as its
/// remotes directory when none is set would trust the commit, so the file
/// finds that fault. The trusted set is empty, so the pull refuses the commit
/// and writes no ref.
#[test]
#[ignore = "helper process for a_handle_with_no_remotes_directory_reads_no_keyring_of_a_directory"]
fn no_remotes_directory_subprocess() {
    let Some(base) = std::env::var_os(NO_DIR_CHILD_ENV).map(PathBuf::from) else {
        return;
    };
    let signer_home = GpgHome::create(&base, "gnupg", "Ostrya Pull <pull@example.invalid>");

    block_on(async {
        let (src, commit) = source_repo(&base).await;
        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();
        let (path, dst) = dest_with_remote(&base, "dst", "").await;
        std::fs::create_dir(path.join("remotes.d")).unwrap();
        signer_home.export_to(&path.join("remotes.d").join("origin.trustedkeys.gpg"));
        assert!(dst.remotes_dir().is_none());
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("is from a trusted key")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());
    });
}

/// `gpgkeypath` adds keyrings to the trusted set, as a file or as a directory.
/// The value is read with no escape decoding, so `k\sspace.gpg` names the file
/// with that name. One `;` at the end of the value gives no entry.
///
/// If an entry names no file and no directory, the pull fails. An empty entry
/// names no file. The trusted set does not silently become smaller.
#[test]
fn gpgkeypath_adds_keyrings_and_a_missing_entry_fails() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-keypath");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");

    block_on(async {
        let (src, commit) = source_repo(base).await;
        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();

        let keyring = base.join("trusted.gpg");
        signer_home.export_to(&keyring);
        let keydir = base.join("keydir");
        std::fs::create_dir(&keydir).unwrap();
        signer_home.export_to(&keydir.join("pull.gpg"));
        // The directory scan reads this file too. It is not an OpenPGP
        // keyring, so the load skips it and the pull does not fail.
        std::fs::write(keydir.join("notes.txt"), b"not a keyring\n").unwrap();
        let backslash = base.join(r"k\sspace.gpg");
        signer_home.export_to(&backslash);

        for (name, entry) in [
            ("dst-file", keyring.display().to_string()),
            ("dst-dir", keydir.display().to_string()),
            ("dst-backslash", backslash.display().to_string()),
            ("dst-trailing", format!("{};", keyring.display())),
        ] {
            let (_path, dst) = dest_with_remote(base, name, &format!("gpgkeypath={entry}\n")).await;
            gpg_pull(&dst, &src).await.unwrap();
            assert_eq!(
                dst.resolve_rev("origin:main", true).await.unwrap(),
                Some(commit),
                "gpgkeypath={entry}"
            );
        }

        let (_path, dst) = dest_with_remote(
            base,
            "dst-missing",
            &format!(
                "gpgkeypath={}/absent;{}\n",
                base.display(),
                keyring.display()
            ),
        )
        .await;
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("cannot be read")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());

        let (_path, dst) = dest_with_remote(
            base,
            "dst-empty-entry",
            &format!("gpgkeypath=;{}\n", keyring.display()),
        )
        .await;
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m)
                if m.starts_with("gpgkeypath entry '' cannot be read: ")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());
    });
}

/// A `gpgkeypath` directory gives each regular file in it, with any name. A
/// file that is not an OpenPGP keyring adds no key, and the pull does not
/// fail on it. The same rule applies to a file entry. A file that cannot be
/// read fails the pull by its name.
#[test]
fn a_gpgkeypath_directory_reads_each_regular_file() {
    use std::os::unix::fs::PermissionsExt;

    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-keypath-files");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
    let text = b"This directory holds the trusted keys of the remote.\n";

    block_on(async {
        let (src, commit) = source_repo(base).await;
        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();

        let keyring_alone = base.join("keyring-alone");
        std::fs::create_dir(&keyring_alone).unwrap();
        signer_home.export_to(&keyring_alone.join("a.keyring"));
        let junk_first = base.join("junk-first");
        std::fs::create_dir(&junk_first).unwrap();
        std::fs::write(junk_first.join("junk.gpg"), text).unwrap();
        signer_home.export_to(&junk_first.join("b.keyring"));
        let junk_file = base.join("junk.txt");
        std::fs::write(&junk_file, text).unwrap();
        let keyring = base.join("trusted.gpg");
        signer_home.export_to(&keyring);
        for (name, keypath) in [
            ("dst-keyring-alone", keyring_alone.display().to_string()),
            ("dst-junk-first", junk_first.display().to_string()),
            (
                "dst-junk-file",
                format!("{};{}", junk_file.display(), keyring.display()),
            ),
        ] {
            let (_path, dst) =
                dest_with_remote(base, name, &format!("gpgkeypath={keypath}\n")).await;
            gpg_pull(&dst, &src).await.unwrap();
            assert_eq!(
                dst.resolve_rev("origin:main", true).await.unwrap(),
                Some(commit),
                "gpgkeypath={keypath}"
            );
        }

        // A directory of text alone gives no key. The pull reads the
        // directory with no error, and then trusts no signature.
        let text_alone = base.join("text-alone");
        std::fs::create_dir(&text_alone).unwrap();
        std::fs::write(text_alone.join("README"), text).unwrap();
        let (_path, dst) = dest_with_remote(
            base,
            "dst-text-alone",
            &format!("gpgkeypath={}\n", text_alone.display()),
        )
        .await;
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m)
                if m.contains("no GPG signature is from a trusted key")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());

        // A file that cannot be opened fails the pull by its name, though the
        // directory holds the key in a second file.
        let unreadable = base.join("unreadable");
        std::fs::create_dir(&unreadable).unwrap();
        signer_home.export_to(&unreadable.join("a.gpg"));
        let locked = unreadable.join("z.gpg");
        signer_home.export_to(&locked);
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        // A process that holds the override of file permissions, as root
        // does, opens the file. The arm then has no refusal to observe.
        if std::fs::File::open(&locked).is_ok() {
            eprintln!("skipping the unreadable arm: the file opens with mode 000");
            return;
        }
        let (_path, dst) = dest_with_remote(
            base,
            "dst-unreadable",
            &format!("gpgkeypath={}\n", unreadable.display()),
        )
        .await;
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("z.gpg")
                && m.contains("cannot be opened")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());
    });
}

/// A revocation in an armored file of a `gpgkeypath` directory refuses the
/// commit, also when a second file trusts the key. A pull with
/// `remote=origin` reads the directory.
///
/// The directory holds the key in `a.gpg` and the revoked key in `b.asc`.
/// With the armor alone in `b.asc`, the pull reads the revocation and trusts
/// no signature. With a line of text before the armor, the pull cannot read
/// `b.asc` whole, and refuses it by its path. A skip of `b.asc` would trust
/// the revoked key, and the `ostree` command reads the revocation from both
/// forms of the file.
#[test]
fn a_revocation_in_armor_of_a_gpgkeypath_file_refuses_the_commit() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-keypath-revocation");
    let base = tmp.path();
    let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");

    block_on(async {
        let (src, commit) = source_repo(base).await;
        src.sign_commit(&commit, &signer_home.signer())
            .await
            .unwrap();
        let keyring = base.join("a.gpg");
        signer_home.export_to(&keyring);

        // `gpg` stores a revocation certificate when it generates a key. Its
        // armor lines start with `:`, so that an import needs an edit.
        let stored = signer_home
            .dir
            .join("openpgp-revocs.d")
            .join(format!("{}.rev", signer_home.fingerprint()));
        let certificate = std::fs::read_to_string(stored)
            .unwrap()
            .replace(":-----BEGIN", "-----BEGIN");
        let revocation = base.join("revocation.asc");
        std::fs::write(&revocation, certificate).unwrap();
        let status = signer_home
            .gpg()
            .arg("--import")
            .arg(&revocation)
            .status()
            .unwrap();
        assert!(status.success(), "gpg --import of the revocation failed");
        let out = signer_home
            .gpg()
            .args(["--armor", "--export"])
            .output()
            .unwrap();
        assert!(out.status.success() && !out.stdout.is_empty());
        let revoked = out.stdout;

        for (name, text) in [("plain", &b""[..]), ("after-text", &b"Trusted keys\n"[..])] {
            let keys = base.join(format!("keys-{name}"));
            std::fs::create_dir(&keys).unwrap();
            std::fs::copy(&keyring, keys.join("a.gpg")).unwrap();
            let armored = keys.join("b.asc");
            std::fs::write(&armored, [text, &revoked].concat()).unwrap();
            let (_path, dst) = dest_with_remote(
                base,
                &format!("dst-{name}"),
                &format!("gpgkeypath={}\n", keys.display()),
            )
            .await;
            let err = gpg_pull(&dst, &src).await.unwrap_err();
            let message = match &err {
                Error::Signature(m) => m.clone(),
                other => panic!("{name}: {other}"),
            };
            if text.is_empty() {
                assert!(
                    message.contains("no GPG signature is from a trusted key"),
                    "{name}: {message}"
                );
            } else {
                let named = format!("the keyring '{}'", armored.display());
                assert!(
                    message.contains(&named) && message.contains("armor"),
                    "{name}: {message}"
                );
            }
            assert!(dst.list_refs(None).await.unwrap().is_empty(), "{name}");
        }
    });
}

/// The pull refuses a fifo at a `gpgkeypath` entry, and the error names the
/// entry.
///
/// A read of a fifo returns the data that its writers sent. If the pull read
/// a fifo, its writers set the trusted set. This test returns only
/// because the pull refuses the file type before a read. No `gpg` binary runs,
/// because the pull builds the trusted set before it examines a signature.
#[test]
fn a_fifo_gpgkeypath_entry_is_refused_by_name() {
    let tmp = TmpDir::new("pull-verify-gpg-keypath-fifo");
    let base = tmp.path();

    block_on(async {
        let (src, _commit) = source_repo(base).await;
        let entry = base.join("fifo.gpg");
        rustix::fs::mknodat(
            rustix::fs::CWD,
            &entry,
            rustix::fs::FileType::Fifo,
            rustix::fs::Mode::from_raw_mode(0o600),
            0,
        )
        .unwrap();

        let (_path, dst) = dest_with_remote(
            base,
            "dst-fifo",
            &format!("gpgkeypath={}\n", entry.display()),
        )
        .await;
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("fifo.gpg")
                && m.contains("regular file")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());
    });
}

/// The pull refuses a `gpgkeypath` entry that is larger than the keyring
/// ceiling, and the error names the entry.
///
/// A read of only the part under the ceiling gives a trusted set that the
/// operator did not put there, and no message reports it.
#[test]
fn an_oversized_gpgkeypath_entry_is_refused_by_name() {
    /// The keyring ceiling, `MAX_KEYRING` of `ostrya-sign`, that applies to
    /// each keyring source.
    const MAX_KEYRING: u64 = 4 * 1024 * 1024;

    let tmp = TmpDir::new("pull-verify-gpg-keypath-size");
    let base = tmp.path();

    block_on(async {
        let (src, _commit) = source_repo(base).await;
        let entry = base.join("huge.gpg");
        std::fs::File::create(&entry)
            .unwrap()
            .set_len(MAX_KEYRING + 1)
            .unwrap();

        let (_path, dst) = dest_with_remote(
            base,
            "dst-huge",
            &format!("gpgkeypath={}\n", entry.display()),
        )
        .await;
        let err = gpg_pull(&dst, &src).await.unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("huge.gpg")
                && m.contains("ceiling")),
            "{err}"
        );
        assert!(dst.list_refs(None).await.unwrap().is_empty());
    });
}

/// `gpg-verify-summary=true` needs `summary.sig`. A pull over HTTP from a
/// remote that answers 403 or 410 for it fails with the message of a missing
/// signature, and writes no ref.
#[test]
fn gpg_verify_summary_refuses_a_403_or_410_for_summary_sig() {
    if !gpg_available() {
        return;
    }
    let tmp = TmpDir::new("pull-verify-gpg-absent-sig");
    let base = tmp.path();
    let home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
    let keyring = base.join("signer.gpg");
    home.export_to(&keyring);

    block_on(async {
        let (src, _) = source_repo(base).await;
        src.regenerate_summary(&ostrya::SummaryOptions {
            last_modified: Some(FIXED_TS),
            ..ostrya::SummaryOptions::default()
        })
        .await
        .unwrap();
        src.sign_summary(&home.signer()).await.unwrap();
        assert!(base.join("src/summary.sig").exists());
        let server = pull::RepoServer::start(&base.join("src"), false).await;
        for status in [403u16, 410] {
            server.answer_status("summary.sig", status);
            let path = base.join(format!("dst-{status}"));
            drop(
                Repo::create(&path, CreateOptions::new(RepoMode::Archive))
                    .await
                    .unwrap(),
            );
            let config = path.join("config");
            let mut text = std::fs::read_to_string(&config).unwrap();
            text.push_str(&format!(
                "\n[remote \"origin\"]\nurl={}\ngpg-verify=false\ngpg-verify-summary=true\n\
                 gpgkeypath={}\n",
                server.url(),
                keyring.display()
            ));
            std::fs::write(&config, text).unwrap();
            let dst = Repo::open(&path).await.unwrap();

            let err = dst
                .pull(
                    "origin",
                    PullOptions {
                        refs: vec!["main".to_owned()],
                        ..PullOptions::default()
                    },
                )
                .await
                .unwrap_err();
            assert!(
                matches!(&err, Error::Signature(m)
                    if m == "summary verification is enabled, but no summary.sig is published"),
                "{status}: {err}"
            );
            assert!(dst.list_refs(None).await.unwrap().is_empty());
            assert!(dst.list_remote_refs().await.unwrap().is_empty());
        }
    });
}