ostrya 0.11.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
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
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
//! An in-process static file server over a repository directory, for the
//! tests of a pull from a remote. The module also builds the source and
//! destination repositories of these tests.
//!
//! The server records these values:
//!
//! - each request path that it receives, and its query
//! - the status of the answer to each request
//! - the largest number of requests in flight at the same time
//! - the number of connections that it accepts
//! - the number of TLS connections that negotiate `h2` through ALPN
//!
//! A TLS server can demand a client certificate that the fixture authority
//! signed, and any server can demand a bearer token. Any server can answer a
//! path with a fixed status.
//!
//! The pull tests declare this module with a `path` attribute, so the other
//! tests do not build the server.

#![allow(dead_code)]

use std::collections::{HashMap, HashSet};
use std::convert::Infallible;
use std::future::Future;
use std::io::{self, IoSlice};
use std::net::SocketAddr;
use std::os::fd::AsFd;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, ready};

use futures_io::{AsyncRead, AsyncWrite};
use hyper::body::{Bytes, Frame, SizeHint};
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use ostrya::fetch::{FetcherOptions, Proxy, TrustRoots};
use ostrya::{
    AdvertisedDelta, Checksum, CommitModifier, CommitModifierFlags, CommitOptions, CreateOptions,
    Error, MutableTree, PullOptions, Ref, Repo, RepoMode, SummaryOptions, Type, Value,
};
use ostrya_rt::{TcpListener, spawn};

pub const CA_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/ca.pem");
pub const SERVER_CERT_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/server.pem");
pub const SERVER_KEY_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/server.key.pem");
pub const OTHERNAME_CERT_PEM: &[u8] =
    include_bytes!("../../../../tests/fixtures/tls/server-othername.pem");
pub const OTHERNAME_KEY_PEM: &[u8] =
    include_bytes!("../../../../tests/fixtures/tls/server-othername.key.pem");
pub const UNTRUSTED_CERT_PEM: &[u8] =
    include_bytes!("../../../../tests/fixtures/tls/server-untrusted.pem");
pub const UNTRUSTED_KEY_PEM: &[u8] =
    include_bytes!("../../../../tests/fixtures/tls/server-untrusted.key.pem");
/// A client certificate that the fixture authority signed, and its key.
pub const CLIENT_CERT_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/client.pem");
pub const CLIENT_KEY_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/client.key.pem");

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

/// The `summary.sig` bytes that a remote publishes in the mirror tests.
///
/// A pull copies the file and does not read it, so any bytes are sufficient.
pub const SUMMARY_SIG: &[u8] = b"summary signature bytes";

// --- HTTP server -----------------------------------------------------------

/// A `futures-io` stream that hyper reads and writes.
pub struct TestIo<S> {
    inner: S,
    scratch: Vec<u8>,
}

impl<S: AsyncRead + Unpin> hyper::rt::Read for TestIo<S> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        mut buf: hyper::rt::ReadBufCursor<'_>,
    ) -> Poll<io::Result<()>> {
        let want = buf.remaining().min(16 * 1024);
        if want == 0 {
            return Poll::Ready(Ok(()));
        }
        let me = self.get_mut();
        if me.scratch.len() < want {
            me.scratch.resize(want, 0);
        }
        let n = ready!(Pin::new(&mut me.inner).poll_read(cx, &mut me.scratch[..want]))?;
        buf.put_slice(&me.scratch[..n]);
        Poll::Ready(Ok(()))
    }
}

impl<S: AsyncWrite + Unpin> hyper::rt::Write for TestIo<S> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_flush(cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_close(cx)
    }

    fn is_write_vectored(&self) -> bool {
        true
    }

    fn poll_write_vectored(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write_vectored(cx, bufs)
    }
}

#[derive(Clone, Copy)]
pub struct TestExecutor;

impl<F> hyper::rt::Executor<F> for TestExecutor
where
    F: Future + Send + 'static,
    F::Output: Send + 'static,
{
    fn execute(&self, future: F) {
        drop(spawn(future));
    }
}

/// A response body of prepared chunks.
///
/// If the declared length is more than the length of the chunks, hyper cuts
/// the connection in the middle of the response.
pub struct FileBody {
    chunks: Vec<Bytes>,
    declared: u64,
}

impl hyper::body::Body for FileBody {
    type Data = Bytes;
    type Error = Infallible;

    fn poll_frame(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, Infallible>>> {
        let me = self.get_mut();
        if me.chunks.is_empty() {
            return Poll::Ready(None);
        }
        Poll::Ready(Some(Ok(Frame::data(me.chunks.remove(0)))))
    }

    fn size_hint(&self) -> SizeHint {
        SizeHint::with_exact(self.declared)
    }
}

/// The rules that override the files of the served repository directory.
#[derive(Default)]
pub struct Policy {
    /// The request paths that get a 404 answer, whatever the directory holds.
    hidden: HashSet<String>,
    /// The request paths, each with the bytes that replace its body.
    tampered: HashMap<String, Vec<u8>>,
    /// The request paths that get a body shorter than its declared length, so
    /// hyper cuts the connection in the middle of the response.
    truncated: HashSet<String>,
    /// The request paths that get the same cut body, each with the number of
    /// cut answers left.
    ///
    /// If the count is 0, the server sends the full body.
    truncate_first: HashMap<String, usize>,
    /// The bearer token that each request must carry. A request without
    /// `Authorization: Bearer <token>` gets a 401 answer.
    bearer: Option<String>,
    /// The request paths, each with the status of its answer, which has an
    /// empty body.
    statuses: HashMap<String, u16>,
    /// Each request path with its query, or an empty query, in the order of
    /// the requests.
    queries: Vec<(String, String)>,
}

/// The server leaf certificate that a TLS [`RepoServer`] presents.
#[derive(Clone, Copy)]
pub enum Leaf {
    /// A valid leaf that the fixture authority signed, for `localhost` and
    /// `127.0.0.1`.
    Fixture,
    /// A valid leaf that the fixture authority signed, for neither
    /// `localhost` nor `127.0.0.1`.
    OtherName,
    /// A valid leaf for `localhost` and `127.0.0.1`, signed by an authority
    /// that no client trusts.
    Untrusted,
}

impl Leaf {
    /// Returns the certificate and the private key of the leaf, in PEM
    /// encoding.
    fn pem(self) -> (&'static [u8], &'static [u8]) {
        match self {
            Leaf::Fixture => (SERVER_CERT_PEM, SERVER_KEY_PEM),
            Leaf::OtherName => (OTHERNAME_CERT_PEM, OTHERNAME_KEY_PEM),
            Leaf::Untrusted => (UNTRUSTED_CERT_PEM, UNTRUSTED_KEY_PEM),
        }
    }
}

/// An in-process static file server over a repository directory.
pub struct RepoServer {
    addr: SocketAddr,
    tls: bool,
    seen: Arc<Mutex<Vec<String>>>,
    /// Each request path with the status of its answer, in the order of the
    /// answers.
    answered: Arc<Mutex<Vec<(String, u16)>>>,
    policy: Arc<Mutex<Policy>>,
    /// The largest number of requests in flight at the same time.
    peak: Arc<AtomicUsize>,
    /// The number of connections that the server accepted.
    connections: Arc<AtomicUsize>,
    /// The number of TLS connections that negotiated `h2` through ALPN.
    h2_connections: Arc<AtomicUsize>,
}

impl RepoServer {
    pub async fn start(root: &Path, tls: bool) -> RepoServer {
        RepoServer::start_with_leaf(root, tls, Leaf::Fixture).await
    }

    /// Starts a server that presents `leaf`.
    ///
    /// The leaf sets which server certificate checks a TLS client can
    /// complete.
    pub async fn start_with_leaf(root: &Path, tls: bool, leaf: Leaf) -> RepoServer {
        RepoServer::launch(root, tls, leaf, false).await
    }

    /// Starts a TLS server that presents [`Leaf::Fixture`] and demands a
    /// client certificate that the fixture authority signed.
    pub async fn start_demanding_client_certificate(root: &Path) -> RepoServer {
        RepoServer::launch(root, true, Leaf::Fixture, true).await
    }

    /// Starts a server that presents `leaf`. If `client_certificate` is
    /// `true`, a TLS server demands a client certificate that the fixture
    /// authority signed.
    async fn launch(root: &Path, tls: bool, leaf: Leaf, client_certificate: bool) -> RepoServer {
        let root = root.to_path_buf();
        let listener = TcpListener::bind("127.0.0.1:0".parse().unwrap())
            .await
            .unwrap();
        let addr = listener.local_addr().unwrap();
        let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let answered: Arc<Mutex<Vec<(String, u16)>>> = Arc::new(Mutex::new(Vec::new()));
        let policy: Arc<Mutex<Policy>> = Arc::new(Mutex::new(Policy::default()));
        let peak = Arc::new(AtomicUsize::new(0));
        let inflight = Arc::new(AtomicUsize::new(0));
        let connections = Arc::new(AtomicUsize::new(0));
        let h2_connections = Arc::new(AtomicUsize::new(0));
        let acceptor = tls.then(|| {
            futures_rustls::TlsAcceptor::from(Arc::new(server_config(
                &["h2", "http/1.1"],
                leaf,
                client_certificate,
            )))
        });

        let task = (
            root,
            seen.clone(),
            answered.clone(),
            policy.clone(),
            peak.clone(),
            inflight,
            connections.clone(),
            h2_connections.clone(),
        );
        drop(spawn(async move {
            let (root, seen, answered, policy, peak, inflight, connections, h2_connections) = task;
            loop {
                let Ok((stream, _peer)) = listener.accept().await else {
                    return;
                };
                connections.fetch_add(1, Ordering::SeqCst);
                let state = (
                    root.clone(),
                    seen.clone(),
                    answered.clone(),
                    policy.clone(),
                    peak.clone(),
                    inflight.clone(),
                );
                let acceptor = acceptor.clone();
                let h2_connections = h2_connections.clone();
                drop(spawn(async move {
                    match acceptor {
                        Some(acceptor) => {
                            let Ok(tls) = acceptor.accept(stream).await else {
                                return;
                            };
                            let h2 = tls.get_ref().1.alpn_protocol() == Some(b"h2");
                            if h2 {
                                h2_connections.fetch_add(1, Ordering::SeqCst);
                            }
                            serve(tls, h2, state).await;
                        }
                        None => serve(stream, false, state).await,
                    }
                }));
            }
        }));
        RepoServer {
            addr,
            tls,
            seen,
            answered,
            policy,
            peak,
            connections,
            h2_connections,
        }
    }

    pub fn url(&self) -> String {
        let scheme = if self.tls { "https" } else { "http" };
        // The fixture server certificate covers `localhost` and `127.0.0.1`.
        format!("{scheme}://localhost:{}", self.addr.port())
    }

    pub fn port(&self) -> u16 {
        self.addr.port()
    }

    /// Returns the request paths that the server received, in order, without
    /// the leading slash.
    pub fn seen(&self) -> Vec<String> {
        self.seen.lock().unwrap().clone()
    }

    /// Returns the request paths that the server received, as a set.
    pub fn seen_set(&self) -> HashSet<String> {
        self.seen().into_iter().collect()
    }

    pub fn peak_inflight(&self) -> usize {
        self.peak.load(Ordering::SeqCst)
    }

    pub fn connections(&self) -> usize {
        self.connections.load(Ordering::SeqCst)
    }

    /// Returns the number of TLS connections that negotiated `h2` through
    /// ALPN.
    pub fn h2_connections(&self) -> usize {
        self.h2_connections.load(Ordering::SeqCst)
    }

    /// Demands `Authorization: Bearer <token>` on each request. A request
    /// without it gets a 401 answer.
    pub fn require_bearer(&self, token: &str) {
        self.policy.lock().unwrap().bearer = Some(token.to_owned());
    }

    /// Answers each request for `path` with `status` and an empty body.
    pub fn answer_status(&self, path: &str, status: u16) {
        self.policy
            .lock()
            .unwrap()
            .statuses
            .insert(path.to_owned(), status);
    }

    /// Returns the query of each request for `path`, in order. A request
    /// with no query gives an empty string.
    pub fn queries_for(&self, path: &str) -> Vec<String> {
        self.policy
            .lock()
            .unwrap()
            .queries
            .iter()
            .filter(|(seen, _)| seen == path)
            .map(|(_, query)| query.clone())
            .collect()
    }

    pub fn hide(&self, path: &str) {
        self.policy.lock().unwrap().hidden.insert(path.to_owned());
    }

    pub fn tamper(&self, path: &str, bytes: Vec<u8>) {
        self.policy
            .lock()
            .unwrap()
            .tampered
            .insert(path.to_owned(), bytes);
    }

    pub fn truncate(&self, path: &str) {
        self.policy
            .lock()
            .unwrap()
            .truncated
            .insert(path.to_owned());
    }

    /// Cuts the next `times` responses for `path`, then serves the full body.
    pub fn truncate_times(&self, path: &str, times: usize) {
        self.policy
            .lock()
            .unwrap()
            .truncate_first
            .insert(path.to_owned(), times);
    }

    /// Returns the number of requests that the server received for `path`.
    pub fn requests_for(&self, path: &str) -> usize {
        self.seen().iter().filter(|seen| *seen == path).count()
    }

    /// Returns the statuses of the answers to the requests for `path`, in
    /// order.
    pub fn statuses_for(&self, path: &str) -> Vec<u16> {
        self.answered
            .lock()
            .unwrap()
            .iter()
            .filter(|(answered, _)| answered == path)
            .map(|(_, status)| *status)
            .collect()
    }

    pub fn forget(&self) {
        self.seen.lock().unwrap().clear();
        self.answered.lock().unwrap().clear();
        self.policy.lock().unwrap().queries.clear();
    }
}

pub type ServeState = (
    PathBuf,
    Arc<Mutex<Vec<String>>>,
    Arc<Mutex<Vec<(String, u16)>>>,
    Arc<Mutex<Policy>>,
    Arc<AtomicUsize>,
    Arc<AtomicUsize>,
);

/// Serves one connection from the repository directory.
pub async fn serve<S>(io: S, h2: bool, state: ServeState)
where
    S: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
    let io = TestIo {
        inner: io,
        scratch: Vec::new(),
    };
    let service = service_fn(move |request: Request<hyper::body::Incoming>| {
        let (root, seen, answered, policy, peak, inflight) = state.clone();
        async move {
            let path = request.uri().path().trim_start_matches('/').to_owned();
            let query = request.uri().query().unwrap_or_default().to_owned();
            policy.lock().unwrap().queries.push((path.clone(), query));
            let authorization = request
                .headers()
                .get(hyper::header::AUTHORIZATION)
                .and_then(|value| value.to_str().ok())
                .map(str::to_owned);
            seen.lock().unwrap().push(path.clone());
            let now = inflight.fetch_add(1, Ordering::SeqCst) + 1;
            peak.fetch_max(now, Ordering::SeqCst);
            // A small delay makes the overlap of concurrent requests longer,
            // so the counter sees the peak that the pull reaches.
            ostrya_rt::Timer::after(std::time::Duration::from_millis(5)).await;
            let response = answer(&root, &path, authorization.as_deref(), &policy);
            answered
                .lock()
                .unwrap()
                .push((path, response.status().as_u16()));
            inflight.fetch_sub(1, Ordering::SeqCst);
            Ok::<_, Infallible>(response)
        }
    });
    if h2 {
        let _ = hyper::server::conn::http2::Builder::new(TestExecutor)
            .serve_connection(io, service)
            .await;
    } else {
        let _ = hyper::server::conn::http1::Builder::new()
            .serve_connection(io, service)
            .await;
    }
}

/// Returns the response for one request path, with `authorization` as the
/// value of the `Authorization` header of the request.
pub fn answer(
    root: &Path,
    path: &str,
    authorization: Option<&str>,
    policy: &Mutex<Policy>,
) -> Response<FileBody> {
    let (hidden, replacement, truncated) = {
        let mut policy = policy.lock().unwrap();
        if let Some(token) = &policy.bearer
            && authorization != Some(format!("Bearer {token}").as_str())
        {
            return status_only(StatusCode::UNAUTHORIZED);
        }
        if let Some(status) = policy.statuses.get(path) {
            return status_only(StatusCode::from_u16(*status).unwrap());
        }
        let cut_once = match policy.truncate_first.get_mut(path) {
            Some(left) if *left > 0 => {
                *left -= 1;
                true
            }
            _ => false,
        };
        (
            policy.hidden.contains(path),
            policy.tampered.get(path).cloned(),
            cut_once || policy.truncated.contains(path),
        )
    };
    if hidden {
        return not_found();
    }
    let bytes = match replacement {
        Some(bytes) => bytes,
        None => match std::fs::read(root.join(path)) {
            Ok(bytes) => bytes,
            Err(_) => return not_found(),
        },
    };
    if truncated {
        // The declared length is more than the body holds, so hyper cuts the
        // connection when the body ends early.
        return Response::builder()
            .status(StatusCode::OK)
            .body(FileBody {
                chunks: vec![Bytes::copy_from_slice(&bytes[..bytes.len() / 2])],
                declared: bytes.len() as u64,
            })
            .unwrap();
    }
    Response::builder()
        .status(StatusCode::OK)
        .body(FileBody {
            declared: bytes.len() as u64,
            chunks: vec![Bytes::from(bytes)],
        })
        .unwrap()
}

pub fn not_found() -> Response<FileBody> {
    status_only(StatusCode::NOT_FOUND)
}

/// Returns a response with `status` and an empty body.
fn status_only(status: StatusCode) -> Response<FileBody> {
    Response::builder()
        .status(status)
        .body(FileBody {
            chunks: Vec::new(),
            declared: 0,
        })
        .unwrap()
}

/// Returns the rustls configuration of the fixture server. If
/// `client_certificate` is `true`, the server demands a client certificate
/// that the fixture authority signed.
pub fn server_config(alpn: &[&str], leaf: Leaf, client_certificate: bool) -> rustls::ServerConfig {
    let provider = Arc::new(rustls_graviola::default_provider());
    let (cert_pem, key_pem) = leaf.pem();
    let certs: Vec<_> = rustls_pemfile::certs(&mut io::BufReader::new(cert_pem))
        .collect::<Result<_, _>>()
        .unwrap();
    let key = rustls_pemfile::private_key(&mut io::BufReader::new(key_pem))
        .unwrap()
        .unwrap();
    let builder = rustls::ServerConfig::builder_with_provider(provider.clone())
        .with_safe_default_protocol_versions()
        .unwrap();
    let builder = if client_certificate {
        let mut roots = rustls::RootCertStore::empty();
        for cert in rustls_pemfile::certs(&mut io::BufReader::new(CA_PEM)) {
            roots.add(cert.unwrap()).unwrap();
        }
        let verifier =
            rustls::server::WebPkiClientVerifier::builder_with_provider(roots.into(), provider)
                .build()
                .unwrap();
        builder.with_client_cert_verifier(verifier)
    } else {
        builder.with_no_client_auth()
    };
    let mut config = builder.with_single_cert(certs, key).unwrap();
    config.alpn_protocols = alpn.iter().map(|p| p.as_bytes().to_vec()).collect();
    config
}

// --- repository helpers ----------------------------------------------------

/// Runs the `ostree` command, asserts that it succeeds, and returns its
/// standard output.
pub fn ostree(args: &[&str]) -> Vec<u8> {
    let out = Command::new("ostree")
        .args(args)
        .output()
        .expect("run ostree");
    assert!(
        out.status.success(),
        "ostree {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    out.stdout
}

/// Builds a small source tree under `dir`.
///
/// The tree holds two regular files with different modes, a symlink, and a
/// nested subdirectory.
pub fn build_tree(dir: &Path, marker: &[u8]) {
    use std::os::unix::fs::PermissionsExt;

    std::fs::create_dir_all(dir.join("subdir")).unwrap();
    std::fs::write(dir.join("hello.txt"), marker).unwrap();
    std::fs::write(dir.join("exec.sh"), b"#!/bin/sh\necho hi\n").unwrap();
    std::fs::write(dir.join("subdir/nested.txt"), b"nested\n").unwrap();
    symlink("hello.txt", dir.join("link")).unwrap();
    std::fs::set_permissions(
        dir.join("hello.txt"),
        std::fs::Permissions::from_mode(0o644),
    )
    .unwrap();
    std::fs::set_permissions(dir.join("exec.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
}

/// Returns `len` bytes of a fixed sequence that a compressor cannot make
/// smaller.
///
/// A content object goes on the wire in deflated form. If the body compresses
/// well, the payload on the wire is a small fraction of the size that its
/// header declares. The buffers of the receive path can then hold the full
/// payload, whatever the size of the object.
///
/// An xorshift sequence deflates to stored blocks, so the body is as long as
/// the payload.
pub fn incompressible(len: usize) -> Vec<u8> {
    let mut out = Vec::with_capacity(len + 8);
    let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
    while out.len() < len {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        out.extend_from_slice(&state.to_le_bytes());
    }
    out.truncate(len);
    out
}

/// Returns the size of the largest `.filez` object in the archive repository at
/// `repo`.
///
/// This size is the longest body that a pull from the repository reads from a
/// connection.
pub fn largest_filez(repo: &Path) -> u64 {
    let mut largest = 0;
    for shard in std::fs::read_dir(repo.join("objects")).unwrap() {
        for entry in std::fs::read_dir(shard.unwrap().path()).unwrap() {
            let entry = entry.unwrap();
            if entry.path().extension().is_some_and(|ext| ext == "filez") {
                largest = largest.max(entry.metadata().unwrap().len());
            }
        }
    }
    largest
}

/// Returns the `ostree.ref-binding` metadata dict that binds a commit to
/// `branch`.
pub fn ref_binding(branch: &str) -> Value {
    Value::Array(vec![Value::Tuple(vec![
        Value::Str("ostree.ref-binding".to_owned()),
        Value::Variant(Box::new((
            Type::parse("as").unwrap(),
            Value::Array(vec![Value::Str(branch.to_owned())]),
        ))),
    ])])
}

/// Returns a small `a{sv}` dict for the detached metadata of a commit.
pub fn detached_dict() -> Value {
    Value::Array(vec![Value::Tuple(vec![
        Value::Str("test.detached".to_owned()),
        Value::Variant(Box::new((
            Type::parse("s").unwrap(),
            Value::Str("present".to_owned()),
        ))),
    ])])
}

/// Commits the subtree `sub` of `base` into `repo` under `branch`.
///
/// The commit gets the timestamp `timestamp` and the ref binding of `branch`.
/// The import uses the modifier flags `SKIP_XATTRS` and
/// `CANONICAL_PERMISSIONS`. The function sets `branch` to the commit.
pub async fn commit_tree(
    repo: &Repo,
    base: &Path,
    sub: &str,
    branch: &str,
    parent: Option<Checksum>,
    timestamp: u64,
) -> Checksum {
    commit_tree_with(
        repo,
        base,
        sub,
        branch,
        parent,
        timestamp,
        CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
    )
    .await
}

/// Commits the subtree `sub` as [`commit_tree`] does, with the modifier flags
/// `flags`.
#[allow(clippy::too_many_arguments)]
pub async fn commit_tree_with(
    repo: &Repo,
    base: &Path,
    sub: &str,
    branch: &str,
    parent: Option<Checksum>,
    timestamp: u64,
    flags: CommitModifierFlags,
) -> Checksum {
    commit_tree_full(repo, base, sub, branch, parent, timestamp, flags, &[]).await
}

/// Commits the subtree `sub` as [`commit_tree`] does, with the dependencies
/// `related` in field 2.
///
/// The repository must hold each dependency complete.
pub async fn commit_tree_related(
    repo: &Repo,
    base: &Path,
    sub: &str,
    branch: &str,
    parent: Option<Checksum>,
    related: &[(&str, Checksum)],
) -> Checksum {
    commit_tree_full(
        repo,
        base,
        sub,
        branch,
        parent,
        FIXED_TS,
        CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
        related,
    )
    .await
}

/// Commits the subtree `sub` as [`commit_tree_with`] does, with the
/// dependencies `related` in field 2.
#[allow(clippy::too_many_arguments)]
async fn commit_tree_full(
    repo: &Repo,
    base: &Path,
    sub: &str,
    branch: &str,
    parent: Option<Checksum>,
    timestamp: u64,
    flags: CommitModifierFlags,
    related: &[(&str, Checksum)],
) -> Checksum {
    let txn = repo.transaction().await.unwrap();
    let mut mtree = MutableTree::new();
    let mut modifier = CommitModifier::new(flags);
    let dfd = std::fs::File::open(base).unwrap();
    txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(sub), &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(format!("{branch} {sub}")),
                timestamp: Some(timestamp),
                metadata: Some(ref_binding(branch)),
                related: related
                    .iter()
                    .map(|(name, checksum)| ((*name).to_owned(), *checksum))
                    .collect(),
                ..CommitOptions::default()
            },
            &root,
        )
        .await
        .unwrap();
    txn.set_ref(&branch.parse::<Ref>().unwrap(), Some(&commit));
    txn.commit().await.unwrap();
    commit
}

/// The commit metadata key that holds the composefs image digest.
pub const COMPOSEFS_DIGEST_KEY: &str = "ostree.composefs.digest.v0";

/// Commits the subtree `sub` of `base` into `repo` under `branch`, as
/// [`commit_tree_related`] does, with `ostree.composefs.digest.v0` in the
/// metadata.
///
/// The key holds the composefs digest of the tree. If `wrong` is set, it holds
/// 32 bytes that are not that digest. The function sets `branch` to the commit.
#[allow(clippy::too_many_arguments)]
pub async fn commit_tree_keyed(
    repo: &Repo,
    base: &Path,
    sub: &str,
    branch: &str,
    parent: Option<Checksum>,
    timestamp: u64,
    related: &[(&str, Checksum)],
    wrong: bool,
) -> Checksum {
    let txn = repo.transaction().await.unwrap();
    let mut mtree = MutableTree::new();
    let mut modifier = CommitModifier::new(
        CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
    );
    let dfd = std::fs::File::open(base).unwrap();
    txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(sub), &mut mtree, Some(&mut modifier))
        .await
        .unwrap();
    let root = txn.write_mtree(&mut mtree).await.unwrap();
    let digest = if wrong {
        [0x5a; 32]
    } else {
        txn.composefs_digest(&root).await.unwrap()
    };
    let Value::Array(mut metadata) = ref_binding(branch) else {
        unreachable!("the ref binding is an a{{sv}} array")
    };
    metadata.push(Value::Tuple(vec![
        Value::Str(COMPOSEFS_DIGEST_KEY.to_owned()),
        Value::Variant(Box::new((
            Type::parse("ay").unwrap(),
            Value::Bytes(digest.to_vec()),
        ))),
    ]));
    let commit = txn
        .write_commit(
            CommitOptions {
                parent,
                subject: Some(format!("{branch} {sub}")),
                timestamp: Some(timestamp),
                metadata: Some(Value::Array(metadata)),
                related: related
                    .iter()
                    .map(|(name, checksum)| ((*name).to_owned(), *checksum))
                    .collect(),
                ..CommitOptions::default()
            },
            &root,
        )
        .await
        .unwrap();
    txn.set_ref(&Ref::local(branch), Some(&commit));
    txn.commit().await.unwrap();
    commit
}

/// Builds a remote archive repository under `dir/remote`, with a summary.
///
/// The ref `test/main` names a commit of the small tree that `build_tree`
/// writes.
pub async fn build_remote(dir: &Path) -> (Repo, Checksum) {
    let src = dir.join("src");
    build_tree(&src, b"hello\n");
    let repo = Repo::create(&dir.join("remote"), CreateOptions::new(RepoMode::Archive))
        .await
        .unwrap();
    let commit = commit_tree(&repo, dir, "src", "test/main", None, FIXED_TS).await;
    repo.regenerate_summary(&SummaryOptions {
        last_modified: Some(FIXED_TS),
        ..SummaryOptions::default()
    })
    .await
    .unwrap();
    (repo, commit)
}

/// The collection id of the remote that [`build_collection_remote`] builds.
pub const REMOTE_ID: &str = "org.example.Remote";
/// A collection that the remote of [`build_collection_remote`] mirrors.
pub const ID_X: &str = "org.example.X";
/// A second collection that the remote of [`build_collection_remote`]
/// mirrors.
pub const ID_Y: &str = "org.example.Y";

/// Commits the subtree `sub` of `base` into `repo`, with the timestamp
/// [`FIXED_TS`], the ref binding of the name of `r`, and the collection
/// binding `collection` if it is set. The function sets `r` to the commit.
pub async fn commit_bound(
    repo: &Repo,
    base: &Path,
    sub: &str,
    r: &Ref,
    collection: Option<&str>,
) -> Checksum {
    let binding = collection.map(|id| ("s", Value::Str(id.to_owned())));
    commit_bound_value(repo, base, sub, r, binding).await
}

/// Commits the subtree `sub` as [`commit_bound`] does, with the
/// `ostree.collection-binding` value `binding`, a type and a value, if it is
/// set.
pub async fn commit_bound_value(
    repo: &Repo,
    base: &Path,
    sub: &str,
    r: &Ref,
    binding: Option<(&str, Value)>,
) -> Checksum {
    let txn = repo.transaction().await.unwrap();
    let mut mtree = MutableTree::new();
    let mut modifier = CommitModifier::new(
        CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS,
    );
    let dfd = std::fs::File::open(base).unwrap();
    txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(sub), &mut mtree, Some(&mut modifier))
        .await
        .unwrap();
    let root = txn.write_mtree(&mut mtree).await.unwrap();
    let Value::Array(mut metadata) = ref_binding(r.name()) else {
        unreachable!("the ref binding is an a{{sv}} array")
    };
    if let Some((ty, value)) = binding {
        metadata.push(Value::Tuple(vec![
            Value::Str("ostree.collection-binding".to_owned()),
            Value::Variant(Box::new((Type::parse(ty).unwrap(), value))),
        ]));
    }
    let commit = txn
        .write_commit(
            CommitOptions {
                subject: Some(r.to_string()),
                timestamp: Some(FIXED_TS),
                metadata: Some(Value::Array(metadata)),
                ..CommitOptions::default()
            },
            &root,
        )
        .await
        .unwrap();
    txn.set_ref(r, Some(&commit));
    txn.commit().await.unwrap();
    commit
}

/// Builds a remote archive repository under `dir/remote` with the collection
/// id [`REMOTE_ID`] and a summary.
///
/// Each commit binds the name of its ref, and holds the tree of `dir/src`:
///
/// - the local ref `main`, with no collection binding;
/// - the local ref `c`, bound to [`REMOTE_ID`];
/// - the collection ref `@ID_X:a`, bound to [`ID_X`];
/// - the collection ref `@ID_Y:b`, bound to [`ID_Y`].
///
/// Returns the repository and the commits in this order.
pub async fn build_collection_remote(dir: &Path) -> (Repo, [Checksum; 4]) {
    build_tree(&dir.join("src"), b"hello\n");
    let repo = Repo::create(
        &dir.join("remote"),
        CreateOptions::new(RepoMode::Archive).collection_id(REMOTE_ID),
    )
    .await
    .unwrap();
    let main = commit_bound(&repo, dir, "src", &Ref::local("main"), None).await;
    let c = commit_bound(&repo, dir, "src", &Ref::local("c"), Some(REMOTE_ID)).await;
    let a = commit_bound(&repo, dir, "src", &Ref::collection(ID_X, "a"), Some(ID_X)).await;
    let b = commit_bound(&repo, dir, "src", &Ref::collection(ID_Y, "b"), Some(ID_Y)).await;
    repo.regenerate_summary(&SummaryOptions {
        last_modified: Some(FIXED_TS),
        ..SummaryOptions::default()
    })
    .await
    .unwrap();
    (repo, [main, c, a, b])
}

/// Builds a remote archive repository under `dir/remote` with one commit and
/// two refs.
///
/// The refs `test/main` and `test/other` both name the commit. The
/// `ostree.ref-binding` of the commit lists only `test/main`. The summary lists
/// both refs.
pub async fn build_remote_two_refs(dir: &Path) -> (Repo, Checksum) {
    let src = dir.join("src");
    build_tree(&src, b"hello\n");
    let repo = Repo::create(&dir.join("remote"), CreateOptions::new(RepoMode::Archive))
        .await
        .unwrap();
    let commit = commit_tree(&repo, dir, "src", "test/main", None, FIXED_TS).await;
    let txn = repo.transaction().await.unwrap();
    txn.set_ref(&Ref::local("test/other"), Some(&commit));
    txn.commit().await.unwrap();
    repo.regenerate_summary(&SummaryOptions {
        last_modified: Some(FIXED_TS),
        ..SummaryOptions::default()
    })
    .await
    .unwrap();
    (repo, commit)
}

/// Creates a destination repository under `dir/dest` with the remote `origin`
/// at `url`.
///
/// The section of `origin` sets `gpg-verify=false`, because the default is on
/// and the test remotes publish unsigned commits. The function writes the extra
/// `[remote]` keys of `extra` after this key. A verification test sets its own
/// policy in `extra`, and the last value of a repeated key applies.
pub async fn build_dest(dir: &Path, mode: RepoMode, url: &str, extra: &str) -> Repo {
    let path = dir.join("dest");
    let repo = Repo::create(&path, CreateOptions::new(mode)).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={url}\ngpg-verify=false\n{extra}"
    ));
    std::fs::write(&config, text).unwrap();
    Repo::open(&path).await.unwrap()
}

/// Rewrites the `origin` section of the destination at `dir/dest` and opens
/// the repository again.
///
/// A test sets a second policy with this function on a repository that holds
/// the result of an earlier pull.
pub async fn reconfigure_dest(dir: &Path, url: &str, extra: &str) -> Repo {
    let path = dir.join("dest");
    let config = path.join("config");
    let text = std::fs::read_to_string(&config).unwrap();
    let core = text.split("\n[remote").next().unwrap().to_owned();
    std::fs::write(
        &config,
        format!("{core}\n[remote \"origin\"]\nurl={url}\ngpg-verify=false\n{extra}"),
    )
    .unwrap();
    Repo::open(&path).await.unwrap()
}

/// Returns the options of an HTTP endpoint for `server`, built in memory. The
/// endpoint trusts the fixture authority and connects with no proxy. The
/// other fields keep the defaults of [`FetcherOptions::new`].
pub fn https_endpoint(server: &RepoServer) -> FetcherOptions {
    let mut http = FetcherOptions::new(server.url());
    http.tls.roots = TrustRoots::Pem(CA_PEM.to_vec());
    http.proxy = Proxy::None;
    http
}

/// Returns the loose object path of a content object, as an archive remote
/// serves it.
pub fn filez_path(checksum: &str) -> String {
    format!("objects/{}/{}.filez", &checksum[..2], &checksum[2..])
}

/// Returns the loose object path of a metadata object.
pub fn meta_path(checksum: &Checksum, ext: &str) -> String {
    let hex = checksum.to_hex();
    format!("objects/{}/{}.{ext}", &hex[..2], &hex[2..])
}

/// Asserts that the repository holds no local ref under `refs/heads`.
///
/// The tests call it after a failed pull. The second assertion filters the same local
/// refs by the prefix `refs/remotes`, so it adds no check. The function does
/// not check the remote refs or the objects.
pub async fn assert_nothing_published(repo: &Repo) {
    assert!(repo.list_refs(None).await.unwrap().is_empty());
    assert!(
        repo.list_refs(Some("refs/remotes"))
            .await
            .unwrap()
            .is_empty()
    );
}

// --- static delta lists ----------------------------------------------------

/// The error that a pull gives for a `static_deltas` list.
pub enum ListRefusal {
    /// [`Error::InvalidInput`] with this message.
    InvalidInput(String),
}

/// Returns a listed delta. Each byte names the checksum of 32 equal bytes,
/// and `None` is a delta from scratch.
pub fn listed_delta(from: Option<u8>, to: u8, digest: u8) -> AdvertisedDelta {
    AdvertisedDelta {
        from: from.map(|byte| Checksum::from_bytes([byte; 32])),
        to: Checksum::from_bytes([to; 32]),
        superblock: Checksum::from_bytes([digest; 32]),
    }
}

/// Returns the options of each pull that its `static_deltas` list makes the
/// pull refuse with [`Error::InvalidInput`], with a tag and the error of the
/// pull. `base` gives the other options, with an empty subpath list.
pub fn static_delta_list_cases(
    base: impl Fn() -> PullOptions,
) -> Vec<(&'static str, PullOptions, ListRefusal)> {
    let (from, to) = (Checksum::from_bytes([1; 32]), Checksum::from_bytes([2; 32]));
    let two_digests = format!(
        "static delta {}-{} is listed with two superblock digests",
        from.to_hex(),
        to.to_hex()
    );
    vec![
        (
            "two digests",
            PullOptions {
                static_deltas: Some(vec![
                    listed_delta(None, 2, 5),
                    listed_delta(Some(1), 2, 3),
                    listed_delta(Some(1), 2, 4),
                ]),
                ..base()
            },
            ListRefusal::InvalidInput(two_digests),
        ),
        (
            "disable_static_deltas",
            PullOptions {
                static_deltas: Some(vec![listed_delta(Some(1), 2, 3)]),
                disable_static_deltas: true,
                ..base()
            },
            ListRefusal::InvalidInput(
                "a pull with static_deltas takes no disable_static_deltas option".to_owned(),
            ),
        ),
        (
            "subpaths",
            PullOptions {
                static_deltas: Some(Vec::new()),
                subpaths: vec!["/".to_owned()],
                ..base()
            },
            ListRefusal::InvalidInput("a pull with static_deltas takes no subpath".to_owned()),
        ),
    ]
}

/// Asserts that `err` is the error that `expected` states.
pub fn assert_list_refusal(tag: &str, err: &Error, expected: &ListRefusal) {
    match (expected, err) {
        (ListRefusal::InvalidInput(want), Error::InvalidInput(got)) => {
            assert_eq!(got, want, "{tag}")
        }
        _ => panic!("{tag}: {err:?}"),
    }
}

/// Returns the checksum of each content object of the tree that `build_tree`
/// writes, in sorted order.
///
/// The checksums are the names of the objects in the source repository.
pub async fn content_checksums(repo: &Repo, commit: &Checksum) -> Vec<Checksum> {
    let reachable = repo.traverse_commit(commit, -1).await.unwrap();
    let mut out: Vec<Checksum> = reachable
        .iter()
        .filter(|name| name.ty == ostrya::ObjectType::File)
        .map(|name| name.checksum)
        .collect();
    out.sort();
    out
}