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
#![forbid(unsafe_code)]

//! Tests of a pull from an `s3://` address.
//!
//! Each test serves a repository with `rclone serve s3` on a scratch
//! directory. The test of an attachment serves a repository that ostrya
//! builds. Each other test serves a copy of the `archive` fixture of the
//! `ostree` command. The `ostree` command signs the summary of the copy with
//! a new GPG key, before the server starts.
//!
//! A pull through `Repo::pull` reads the key pair from the environment of the
//! process. The test sets the variables only in a child process, so it needs
//! no in-process `set_var`, and the keys do not reach other tests. The child
//! also gets the two shared AWS files at absent paths, and no proxy
//! variable.
//!
//! A test skips when `rclone`, the `ostree` command, or `gpg` is absent.
//! `OSTRYA_REQUIRE_S3`, `OSTRYA_REQUIRE_OSTREE`, and `OSTRYA_REQUIRE_GNUPG`
//! turn each skip into a failure.

#![cfg(all(feature = "s3", feature = "verify-gpg"))]

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

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

use common::TmpDir;
use common::s3::{ACCESS_KEY, Rclone, SECRET_KEY, StandIn, rclone_available};
use ostrya::endpoint::EndpointOverrides;
use ostrya::remote::s3::{Address, Credentials, Location, S3Endpoint};
use ostrya::remote::{Endpoint, PullSession, StreamSessionOptions};
use ostrya::verify::PullTrust;
use ostrya::{
    Checksum, CommitState, CreateOptions, Error, Proxy, PullOptions, Repo, RepoMode, SummaryOptions,
};
use ostrya_rt::block_on;
use pull::{FIXED_TS, ID_X, build_tree, commit_bound, commit_tree, commit_tree_related};

/// The variable that names the case of the child process.
const CASE: &str = "OSTRYA_TEST_S3_CASE";
/// The variable that names the scratch directory of the parent test.
const SCRATCH: &str = "OSTRYA_TEST_S3_SCRATCH";
/// The variable that holds the endpoint URL of the server.
const ENDPOINT: &str = "OSTRYA_TEST_S3_ENDPOINT";

/// The proxy variables that the fetcher reads. The child process gets none
/// of them, so it connects to the server directly.
const PROXY_VARIABLES: [&str; 7] = [
    "http_proxy",
    "HTTP_PROXY",
    "https_proxy",
    "HTTPS_PROXY",
    "all_proxy",
    "ALL_PROXY",
    "no_proxy",
];

/// 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 the new home directory `dir`.
    fn create(dir: PathBuf, uid: &str) -> GpgHome {
        use std::os::unix::fs::DirBuilderExt;
        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();
    }
}

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

/// Copies the directory `from` to `to` with `cp -r`.
fn copy_tree(from: &Path, to: &Path) {
    std::fs::create_dir_all(to.parent().unwrap()).unwrap();
    let status = Command::new("cp")
        .arg("-r")
        .arg(from)
        .arg(to)
        .status()
        .unwrap();
    assert!(status.success(), "cp -r {}", from.display());
}

/// The ref of the fixture.
const REF: &str = "test/main";

/// Returns the commit of the ref [`REF`] of the fixture.
fn fixture_commit() -> Checksum {
    Checksum::from_hex(common::COMMIT).unwrap()
}

/// Returns the names of the object files under `repo`, sorted.
fn object_names(repo: &Path) -> Vec<String> {
    common::file_inventory(repo, "objects")
        .into_iter()
        .map(|(name, _)| name)
        .collect()
}

/// The port pulls an `archive` fixture of the `ostree` command over
/// `s3://`, and verifies the summary that the `ostree` command signed. A
/// changed byte of the summary fails the pull, and a wrong secret key gives
/// the S3 error `SignatureDoesNotMatch`. Neither failure writes a ref or an
/// object.
#[test]
fn the_port_pulls_a_signed_archive_fixture_over_s3() {
    let test = "the_port_pulls_a_signed_archive_fixture_over_s3";
    if !rclone_available(test) {
        return;
    }
    if !common::ostree_available() {
        eprintln!("skipping {test}: ostree is not installed");
        return;
    }
    if !common::gnupg_available(&["gpg"]) {
        return;
    }
    let scratch = TmpDir::new("pull-s3");
    let root = scratch.path().join("root");
    let repo = root.join("bkt").join("repo");
    copy_tree(&common::fixture_repo("archive"), &repo);
    common::add_empty_ref_dirs(&repo);
    let home = GpgHome::create(scratch.path().join("gnupg"), "S3 Pull <s3@example.com>");
    let out = Command::new("ostree")
        .arg("summary")
        .arg("-u")
        .arg(format!("--repo={}", repo.display()))
        .arg(format!("--gpg-sign={}", home.fingerprint()))
        .arg(format!("--gpg-homedir={}", home.dir.display()))
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "ostree summary -u: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    home.export_to(&scratch.path().join("key.gpg"));
    // A copy of the bucket repository with one changed byte of its summary.
    let tampered = root.join("tampered").join("repo");
    copy_tree(&repo, &tampered);
    let mut summary = std::fs::read(tampered.join("summary")).unwrap();
    let middle = summary.len() / 2;
    summary[middle] ^= 0x01;
    std::fs::write(tampered.join("summary"), summary).unwrap();

    let server = Rclone::start(scratch.path(), &root);
    for (case, secret) in [("pull", SECRET_KEY), ("wrong-secret", "wrong-secret-key")] {
        let mut child = Command::new(std::env::current_exe().unwrap());
        child
            .args(["pull_s3_subprocess", "--exact", "--ignored", "--nocapture"])
            .env(CASE, case)
            .env(SCRATCH, scratch.path())
            .env(ENDPOINT, server.endpoint())
            .env("AWS_ACCESS_KEY_ID", ACCESS_KEY)
            .env("AWS_SECRET_ACCESS_KEY", secret)
            .env("AWS_CONFIG_FILE", scratch.path().join("absent-aws-config"))
            .env(
                "AWS_SHARED_CREDENTIALS_FILE",
                scratch.path().join("absent-aws-credentials"),
            );
        for (name, _) in std::env::vars_os() {
            let text = name.to_string_lossy();
            if text.starts_with("AWS_") && !child.get_envs().any(|(set, _)| set == name) {
                child.env_remove(&name);
            }
        }
        for name in PROXY_VARIABLES {
            child.env_remove(name);
        }
        let output = child.output().expect("re-execute this test binary");
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("1 passed"),
            "the child of the case {case} reported {}:\n{stdout}{}",
            output.status,
            String::from_utf8_lossy(&output.stderr),
        );
    }
}

/// Runs a case of `the_port_pulls_a_signed_archive_fixture_over_s3`.
///
/// This test does its work only when the parent test runs this binary again
/// with the variables set.
#[test]
#[ignore = "helper process for the_port_pulls_a_signed_archive_fixture_over_s3"]
fn pull_s3_subprocess() {
    let Some(case) = std::env::var_os(CASE) else {
        return;
    };
    let scratch = PathBuf::from(std::env::var_os(SCRATCH).unwrap());
    let endpoint = std::env::var(ENDPOINT).unwrap();
    block_on(async {
        match case.to_str().unwrap() {
            "pull" => pull_and_verify(&scratch, &endpoint).await,
            "wrong-secret" => pull_with_a_wrong_secret(&scratch, &endpoint).await,
            other => panic!("unknown case {other}"),
        }
    });
}

/// Creates the repository `scratch/<name>` with `min-free-space-percent=0`
/// and the remotes `origin` and `tampered` of the server at `endpoint`. Each
/// remote trusts the exported key of the parent test.
async fn dest(scratch: &Path, name: &str, endpoint: &str) -> (PathBuf, Repo) {
    let path = scratch.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();
    // The host of the tests has little free space.
    text.push_str("min-free-space-percent=0\n");
    for (remote, bucket) in [("origin", "bkt"), ("tampered", "tampered")] {
        text.push_str(&format!(
            "\n[remote \"{remote}\"]\npull-url=s3://{bucket}/repo\ns3-endpoint={endpoint}\n\
             gpg-verify=false\ngpg-verify-summary=true\n"
        ));
    }
    std::fs::write(&config, text).unwrap();
    let repo = Repo::open(&path).await.unwrap();
    let keys = std::fs::read(scratch.join("key.gpg")).unwrap();
    for remote in ["origin", "tampered"] {
        assert_eq!(
            repo.gpg_import_keys(remote, &[&keys], &[]).await.unwrap(),
            1
        );
    }
    (path, repo)
}

/// Returns the options of a pull of [`REF`] over cleartext HTTP.
fn options() -> PullOptions {
    PullOptions {
        refs: vec![REF.to_owned()],
        overrides: EndpointOverrides {
            allow_cleartext_credentials: true,
            ..EndpointOverrides::default()
        },
        ..PullOptions::default()
    }
}

/// The pull from `origin` writes the ref and the objects of the fixture,
/// after the check of the summary signature. The pull from `tampered` fails
/// the check and writes nothing.
async fn pull_and_verify(scratch: &Path, endpoint: &str) {
    let bucket = scratch.join("root").join("bkt").join("repo");
    let (path, repo) = dest(scratch, "dest", endpoint).await;
    let stats = repo.pull("origin", options()).await.unwrap();
    assert!(stats.bytes_transferred > 0);
    assert_eq!(
        repo.resolve_rev(&format!("origin:{REF}"), false)
            .await
            .unwrap(),
        Some(fixture_commit())
    );
    assert_eq!(object_names(&path), object_names(&bucket));
    common::tool_fsck(&path);

    match repo.pull("tampered", options()).await {
        Err(Error::Signature(message)) => assert!(message.contains("summary"), "{message}"),
        other => panic!("a pull of a changed summary: {other:?}"),
    }
    assert_eq!(
        repo.resolve_rev(&format!("tampered:{REF}"), true)
            .await
            .unwrap(),
        None
    );
}

/// A wrong secret key gives the S3 error `SignatureDoesNotMatch`, and the
/// pull writes no ref and no object.
async fn pull_with_a_wrong_secret(scratch: &Path, endpoint: &str) {
    let (path, repo) = dest(scratch, "dest-wrong-secret", endpoint).await;
    let error = repo.pull("origin", options()).await.unwrap_err();
    let message = error.to_string();
    assert!(message.contains("SignatureDoesNotMatch"), "{message}");
    assert!(matches!(error, Error::Remote(_)), "{error:?}");
    assert!(repo.list_refs(None).await.unwrap().is_empty());
    assert!(
        repo.list_refs(Some("refs/remotes"))
            .await
            .unwrap()
            .is_empty()
    );
    assert!(object_names(&path).is_empty());
}

/// A pull session that `PullSession::connect` opens to an `Endpoint::S3`
/// pulls the fixture through `Repo::pull_with_session`.
#[test]
fn a_session_to_an_s3_endpoint_pulls_with_the_session() {
    if !rclone_available("a_session_to_an_s3_endpoint_pulls_with_the_session") {
        return;
    }
    let scratch = TmpDir::new("pull-s3-session");
    let root = scratch.path().join("root");
    let bucket = root.join("bkt").join("repo");
    copy_tree(&common::fixture_repo("archive"), &bucket);
    let server = Rclone::start(scratch.path(), &root);
    block_on(async {
        let location = Location::new(
            Address::parse("s3://bkt/repo").unwrap(),
            "us-east-1",
            Some(&server.endpoint()),
            None,
        )
        .unwrap();
        let credentials = Credentials::new(ACCESS_KEY.into(), SECRET_KEY.into(), None).unwrap();
        let mut s3 = S3Endpoint::new(location, credentials);
        s3.http.allow_cleartext_credentials = true;
        s3.http.proxy = Proxy::None;
        let session = PullSession::connect(Endpoint::S3(s3), StreamSessionOptions::default())
            .await
            .unwrap();
        let path = scratch.path().join("dest");
        let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let opts = PullOptions {
            refs: vec![REF.to_owned()],
            ..PullOptions::default()
        };
        repo.pull_with_session(session, PullTrust::unverified(), opts)
            .await
            .unwrap();
        assert_eq!(
            repo.resolve_rev(REF, false).await.unwrap(),
            Some(fixture_commit())
        );
        assert_eq!(object_names(&path), object_names(&bucket));
    });
}

/// A pull through a session to an `Endpoint::S3` fetches the attachment that
/// field 2 of the pulled commit names, complete, and writes no ref for it.
#[test]
fn a_session_to_an_s3_endpoint_fetches_an_attachment() {
    if !rclone_available("a_session_to_an_s3_endpoint_fetches_an_attachment") {
        return;
    }
    let scratch = TmpDir::new("pull-s3-dependency");
    let root = scratch.path().join("root");
    let bucket = root.join("bkt").join("repo");
    std::fs::create_dir_all(bucket.parent().unwrap()).unwrap();
    let (tip, att) = block_on(async {
        build_tree(&scratch.path().join("uki"), b"uki\n");
        build_tree(&scratch.path().join("main"), b"main\n");
        let remote = Repo::create(&bucket, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let att = commit_tree(&remote, scratch.path(), "uki", "dep/uki", None, FIXED_TS).await;
        let tip = commit_tree_related(
            &remote,
            scratch.path(),
            "main",
            REF,
            None,
            &[("boot/uki", att)],
        )
        .await;
        remote
            .regenerate_summary(&SummaryOptions {
                last_modified: Some(FIXED_TS),
                ..SummaryOptions::default()
            })
            .await
            .unwrap();
        (tip, att)
    });
    let server = Rclone::start(scratch.path(), &root);
    block_on(async {
        let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
        let session = PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
            .await
            .unwrap();
        let path = scratch.path().join("dest");
        let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let opts = PullOptions {
            refs: vec![REF.to_owned()],
            ..PullOptions::default()
        };
        repo.pull_with_session(session, PullTrust::unverified(), opts)
            .await
            .unwrap();
        assert_eq!(repo.list_refs(None).await.unwrap(), [(REF.to_owned(), tip)]);
        assert!(repo.list_remote_refs().await.unwrap().is_empty());
        assert_eq!(repo.commit_state(&att).await.unwrap(), CommitState::Normal);
        assert_eq!(object_names(&path), object_names(&bucket));
    });
}

/// A pull through a session to an `Endpoint::S3` takes the full set of
/// attachments of the pulled commit: a pull of R of the chain R -> C -> D
/// takes C and D, complete, and writes no ref for either.
#[test]
fn a_session_to_an_s3_endpoint_takes_the_full_set_of_attachments() {
    if !rclone_available("a_session_to_an_s3_endpoint_takes_the_full_set_of_attachments") {
        return;
    }
    let scratch = TmpDir::new("pull-s3-attachment-chain");
    let root = scratch.path().join("root");
    let bucket = root.join("bkt").join("repo");
    std::fs::create_dir_all(bucket.parent().unwrap()).unwrap();
    let chain = block_on(async {
        let remote = Repo::create(&bucket, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let chain = common::write_chain(&remote, &scratch.path().join("trees"), REF).await;
        remote
            .regenerate_summary(&SummaryOptions {
                last_modified: Some(FIXED_TS),
                ..SummaryOptions::default()
            })
            .await
            .unwrap();
        chain
    });
    let server = Rclone::start(scratch.path(), &root);
    block_on(async {
        let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
        let session = PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
            .await
            .unwrap();
        let path = scratch.path().join("dest");
        let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let opts = PullOptions {
            refs: vec![REF.to_owned()],
            ..PullOptions::default()
        };
        repo.pull_with_session(session, PullTrust::unverified(), opts)
            .await
            .unwrap();
        assert_eq!(
            repo.list_refs(None).await.unwrap(),
            [(REF.to_owned(), chain.r)]
        );
        assert!(repo.list_remote_refs().await.unwrap().is_empty());
        for commit in [chain.r, chain.c, chain.d] {
            assert_eq!(
                repo.commit_state(&commit).await.unwrap(),
                CommitState::Normal
            );
        }
        assert_eq!(object_names(&path), object_names(&bucket));
    });
}

// --- commit operands ---------------------------------------------------------

/// Builds an archive repository at `repo` with two commits on [`REF`], the
/// second a child of the first, and a commit of the collection ref
/// `@ID_X:a`, bound to that collection. The trees are under `base`. The
/// repository has a summary. Returns the three commits in this order.
async fn build_operand_remote(repo: &Path, base: &Path) -> [Checksum; 3] {
    build_tree(&base.join("one"), b"one\n");
    build_tree(&base.join("two"), b"two\n");
    let remote = Repo::create(repo, CreateOptions::new(RepoMode::Archive))
        .await
        .unwrap();
    let first = commit_tree(&remote, base, "one", REF, None, FIXED_TS).await;
    let second = commit_tree(&remote, base, "two", REF, Some(first), FIXED_TS + 1).await;
    let a = commit_bound(
        &remote,
        base,
        "one",
        &ostrya::Ref::collection(ID_X, "a"),
        Some(ID_X),
    )
    .await;
    remote
        .regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_TS),
            ..SummaryOptions::default()
        })
        .await
        .unwrap();
    [first, second, a]
}

/// Returns the options of a pull of the three forms of a commit operand:
/// the `CHECKSUM` of `second`, [`REF`] at `first`, and `@ID_X:a` at `a`.
fn operand_options([first, second, a]: [Checksum; 3]) -> PullOptions {
    PullOptions {
        refs: vec![
            second.to_hex(),
            format!("{REF}@{first}"),
            format!("@{ID_X}:a@{a}"),
        ],
        ..PullOptions::default()
    }
}

/// Asserts the result of a pull with [`operand_options`] into `repo`: the
/// ref [`REF`] at `first`, the collection ref at `a`, and `second` complete
/// with no ref.
async fn assert_operands_pulled(repo: &Repo, [first, second, a]: [Checksum; 3]) {
    assert_eq!(
        repo.list_refs(None).await.unwrap(),
        [(REF.to_owned(), first)]
    );
    assert_eq!(
        repo.list_mirror_refs().await.unwrap(),
        [(ID_X.to_owned(), "a".to_owned(), a)]
    );
    assert!(repo.list_remote_refs().await.unwrap().is_empty());
    for commit in [first, second, a] {
        assert_eq!(
            repo.commit_state(&commit).await.unwrap(),
            CommitState::Normal
        );
    }
}

/// A pull through a session to an `Endpoint::S3` takes each form of a commit
/// operand: `CHECKSUM`, `REF@CHECKSUM`, and `@ID:REF@CHECKSUM`. The bucket
/// holds a `summary` that does not parse, and the pull passes, because it
/// reads no summary.
#[test]
fn a_session_to_an_s3_endpoint_takes_commit_operands() {
    if !rclone_available("a_session_to_an_s3_endpoint_takes_commit_operands") {
        return;
    }
    let scratch = TmpDir::new("pull-s3-checksum-forms");
    let root = scratch.path().join("root");
    let bucket = root.join("bkt").join("repo");
    std::fs::create_dir_all(bucket.parent().unwrap()).unwrap();
    let commits = block_on(build_operand_remote(&bucket, scratch.path()));
    std::fs::write(bucket.join("summary"), b"not a summary").unwrap();
    let server = Rclone::start(scratch.path(), &root);
    block_on(async {
        let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
        let session = PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
            .await
            .unwrap();
        let path = scratch.path().join("dest");
        let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        repo.pull_with_session(session, PullTrust::unverified(), operand_options(commits))
            .await
            .unwrap();
        assert_operands_pulled(&repo, commits).await;
        assert_eq!(object_names(&path), object_names(&bucket));
    });
}

/// A pull of commit operands alone from a bucket repository sends no `GET`
/// for `summary` or `summary.sig`, and no request for a ref file. It reads
/// the `config` of the bucket repository.
#[test]
fn a_pull_of_commit_operands_from_a_bucket_requests_no_summary() {
    let scratch = TmpDir::new("pull-s3-checksum-requests");
    let source = scratch.path().join("remote");
    let commits = block_on(build_operand_remote(&source, scratch.path()));
    let server = StandIn::start();
    let mut pending = vec![source.clone()];
    while let Some(at) = pending.pop() {
        for entry in std::fs::read_dir(&at).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                pending.push(path);
            } else {
                let key = path.strip_prefix(&source).unwrap().to_str().unwrap();
                let bytes = std::fs::read(&path).unwrap();
                server.state().store(&format!("repo/{key}"), &bytes);
            }
        }
    }
    block_on(async {
        let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
        let session = PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
            .await
            .unwrap();
        let repo = Repo::create(
            &scratch.path().join("dest"),
            CreateOptions::new(RepoMode::Archive),
        )
        .await
        .unwrap();
        repo.pull_with_session(session, PullTrust::unverified(), operand_options(commits))
            .await
            .unwrap();
        assert_operands_pulled(&repo, commits).await;
    });
    let requests = server.state().requests.clone();
    assert!(
        requests
            .iter()
            .any(|(method, target)| method == "GET" && target == "/bkt/repo/config"),
        "{requests:?}"
    );
    assert!(
        !requests
            .iter()
            .any(|(_, target)| target.contains("summary") || target.contains("/refs/")),
        "{requests:?}"
    );
}

/// The repository holds R and C of the chain R -> C -> D complete, and does
/// not hold the commit object of D. A pull of R through a session to an
/// `Endpoint::S3` reads field 2 of C from the repository, and fetches D.
#[test]
fn a_session_to_an_s3_endpoint_fetches_an_attachment_below_a_held_attachment() {
    let name = "a_session_to_an_s3_endpoint_fetches_an_attachment_below_a_held_attachment";
    if !rclone_available(name) {
        return;
    }
    let scratch = TmpDir::new("pull-s3-below-held");
    let root = scratch.path().join("root");
    let bucket = root.join("bkt").join("repo");
    std::fs::create_dir_all(bucket.parent().unwrap()).unwrap();
    let chain = block_on(async {
        let remote = Repo::create(&bucket, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let chain = common::write_chain(&remote, &scratch.path().join("trees"), REF).await;
        remote
            .regenerate_summary(&SummaryOptions {
                last_modified: Some(FIXED_TS),
                ..SummaryOptions::default()
            })
            .await
            .unwrap();
        chain
    });
    let server = Rclone::start(scratch.path(), &root);
    block_on(async {
        let path = scratch.path().join("dest");
        let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let pull = || async {
            let endpoint = common::s3::endpoint(&server.endpoint(), "s3://bkt/repo");
            let session =
                PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
                    .await
                    .unwrap();
            let opts = PullOptions {
                refs: vec![REF.to_owned()],
                ..PullOptions::default()
            };
            repo.pull_with_session(session, PullTrust::unverified(), opts)
                .await
                .unwrap();
        };
        pull().await;
        let hex = chain.d.to_hex();
        let object = path.join(format!("objects/{}/{}.commit", &hex[..2], &hex[2..]));
        std::fs::remove_file(&object).unwrap();
        assert_eq!(
            repo.commit_state(&chain.c).await.unwrap(),
            CommitState::Normal
        );

        pull().await;

        assert!(object.exists());
        for commit in [chain.r, chain.c, chain.d] {
            assert_eq!(
                repo.commit_state(&commit).await.unwrap(),
                CommitState::Normal
            );
        }
        assert_eq!(object_names(&path), object_names(&bucket));
    });
}

// --- absent files ------------------------------------------------------------

/// A session to an `Endpoint::S3` reads a 403 for an optional file as an
/// absent file. The stand-in answers 403 `AccessDenied` for each absent key,
/// as S3 answers a caller with no `s3:ListBucket`, and the pull takes the
/// ref. A 403 for `config` stops the pull with `Error::HttpStatus`.
#[test]
fn a_session_to_a_bucket_reads_a_403_as_absent() {
    let scratch = TmpDir::new("pull-s3-session-absent");
    let source = scratch.path().join("remote");
    let server = StandIn::start();
    let tip = block_on(async {
        build_tree(&scratch.path().join("tree"), b"tree\n");
        let remote = Repo::create(&source, CreateOptions::new(RepoMode::Archive))
            .await
            .unwrap();
        let tip = commit_tree(&remote, scratch.path(), "tree", REF, None, FIXED_TS).await;
        remote
            .regenerate_summary(&SummaryOptions {
                last_modified: Some(FIXED_TS),
                ..SummaryOptions::default()
            })
            .await
            .unwrap();
        tip
    });
    let mut pending = vec![source.clone()];
    while let Some(at) = pending.pop() {
        for entry in std::fs::read_dir(&at).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                pending.push(path);
            } else {
                let key = path.strip_prefix(&source).unwrap().to_str().unwrap();
                let bytes = std::fs::read(&path).unwrap();
                server.state().store(&format!("repo/{key}"), &bytes);
            }
        }
    }
    server.state().forbid_absent = true;
    let pull = |name: &'static str| {
        let path = scratch.path().join(name);
        let url = server.endpoint();
        async move {
            let endpoint = common::s3::endpoint(&url, "s3://bkt/repo");
            let session =
                PullSession::connect(Endpoint::S3(endpoint), StreamSessionOptions::default())
                    .await
                    .unwrap();
            let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
            let opts = PullOptions {
                refs: vec![REF.to_owned()],
                ..PullOptions::default()
            };
            let result = repo
                .pull_with_session(session, PullTrust::unverified(), opts)
                .await;
            (repo, result)
        }
    };
    block_on(async {
        let (repo, result) = pull("dest").await;
        result.unwrap();
        assert_eq!(repo.resolve_rev(REF, false).await.unwrap(), Some(tip));
    });
    assert!(
        server
            .state()
            .requests
            .iter()
            .any(|(method, target)| method == "GET" && target == "/bkt/repo/summary.sig")
    );

    server.state().refuse = Some(("GET", "repo/config".to_owned()));
    block_on(async {
        let (repo, result) = pull("dest-config").await;
        let err = result.unwrap_err();
        assert!(
            matches!(&err, Error::HttpStatus { status: 403, url } if url.ends_with("/repo/config")),
            "{err}"
        );
        assert!(repo.list_refs(None).await.unwrap().is_empty());
    });
}