ostrya-remote 0.3.1

The push and pull protocol of ostrya: the wire codec, the push client session, and the ssh and HTTP transports
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
//! The commit of a tree push.
//!
//! The functions of this module make these parts of the commit:
//!
//! - the parent
//! - the metadata dict
//! - the check of the states of the target refs
//! - the signatures
//! - the ref updates

use std::sync::LazyLock;

use ostrya_core::{
    Checksum, Commit, MAX_METADATA_SIZE, Type, Value, choose_offset_size, commit_metadata, to_bytes,
};
use ostrya_sign::Signer;

use crate::error::{Error, Result};
use crate::proto::{Expected, RefUpdate};
use crate::push_tree::ParentPolicy;
use crate::session::{ServerInfo, invalid};

/// The `a{sv}` type of a metadata dict.
static DICT_TYPE: LazyLock<Type> =
    LazyLock::new(|| Type::parse("a{sv}").expect("a{sv} is a valid signature"));

/// The type of the signature array of an engine in a detached dict.
const SIGNATURE_ARRAY: &str = "aay";

/// Returns the entries of an `a{sv}` dict and the size of the serialized dict.
///
/// The entries keep their order, as `(key, value)` tuples. These are
/// [`Error::InvalidInput`]:
///
/// - an empty key
/// - entries that do not serialize as an `a{sv}` dict
/// - a dict of more than [`MAX_METADATA_SIZE`] bytes
///
/// The object that holds the dict is never smaller than the dict, so an object
/// that holds a refused dict is also over the limit. `what` names the dict in
/// the message.
pub(crate) fn entry_dict(entries: Vec<(String, Value)>, what: &str) -> Result<(Vec<Value>, u64)> {
    if entries.iter().any(|(key, _)| key.is_empty()) {
        return Err(invalid(format!("the {what} holds an empty key")));
    }
    let dict = Value::Array(
        entries
            .into_iter()
            .map(|(key, value)| Value::Tuple(vec![Value::Str(key), value]))
            .collect(),
    );
    let len = to_bytes(&DICT_TYPE, &dict)
        .map_err(|e| invalid(format!("the {what} is not an a{{sv}} dict: {e}")))?
        .len() as u64;
    if len > MAX_METADATA_SIZE {
        return Err(invalid(format!(
            "the {what} is {len} bytes, over the limit of {MAX_METADATA_SIZE}"
        )));
    }
    match dict {
        Value::Array(items) => Ok((items, len)),
        _ => unreachable!("the dict is an array"),
    }
}

/// Returns the key and the value of an entry from [`entry_dict`].
fn split_entry(entry: Value) -> (String, Value) {
    match entry {
        Value::Tuple(fields) => match <[Value; 2]>::try_from(fields) {
            Ok([Value::Str(key), value]) => (key, value),
            _ => unreachable!("an entry is a key and a value"),
        },
        _ => unreachable!("an entry is a tuple"),
    }
}

/// Returns the parent of the commit under `policy`.
///
/// For `CurrentTip`, the parent is the server tip of the first target ref. If
/// that ref is absent, the parent is `None`.
pub(crate) fn resolve_parent(
    policy: ParentPolicy,
    server: &ServerInfo,
    refs: &[String],
) -> Option<Checksum> {
    match policy {
        ParentPolicy::CurrentTip => refs.first().and_then(|name| server.tip(name)),
        ParentPolicy::None => None,
        ParentPolicy::Commit(commit) => Some(commit),
    }
}

/// Refuses target refs in mixed states with [`Error::InvalidInput`].
///
/// Each target ref must have the state of the first one: all absent, or all at
/// one tip. The message names each ref and its tip.
pub(crate) fn check_ref_states(server: &ServerInfo, refs: &[String]) -> Result<()> {
    debug_assert!(names_match(server, refs));
    let Some((first, rest)) = server.refs.split_first() else {
        return Ok(());
    };
    if rest.iter().all(|state| state.commit == first.commit) {
        return Ok(());
    }
    let states = server
        .refs
        .iter()
        .map(|state| match state.commit {
            Some(tip) => format!("'{}' is at {tip}", state.name),
            None => format!("'{}' is absent", state.name),
        })
        .collect::<Vec<_>>()
        .join(", ");
    Err(invalid(format!(
        "the target refs are in mixed states on the server: {states}; without force each \
         target ref must be absent, or each must be at one commit"
    )))
}

/// Returns `true` if the session reported the state of each ref of `refs`, in
/// order.
///
/// The session open refuses a `HelloReply` whose refs differ from these names
/// or from their order.
fn names_match(server: &ServerInfo, refs: &[String]) -> bool {
    server.refs.len() == refs.len() && server.refs.iter().zip(refs).all(|(s, n)| s.name == *n)
}

/// The inputs of the commit object of a tree push.
pub(crate) struct CommitInputs<'a> {
    pub(crate) parent: Option<Checksum>,
    pub(crate) subject: String,
    pub(crate) body: String,
    pub(crate) timestamp: u64,
    /// The entries of the caller, from [`entry_dict`].
    pub(crate) metadata: Vec<Value>,
    /// The target refs, which the ref binding names.
    pub(crate) refs: &'a [String],
    /// If `true`, the metadata holds no ref binding and no collection binding.
    pub(crate) no_bindings: bool,
    /// The collection id of the server.
    pub(crate) collection_id: Option<&'a str>,
    pub(crate) root_dirtree: Checksum,
    pub(crate) root_dirmeta: Checksum,
}

/// Returns the checksum and the serialized bytes of the commit object.
///
/// The metadata dict holds these entries, in this order:
///
/// 1. the entries of the caller, in their order
/// 2. `ostree.ref-binding`, with the target refs sorted
/// 3. `ostree.collection-binding`, if the server has a collection id
///
/// If `no_bindings` is `true`, the dict holds the entries of the caller alone.
/// If the commit does not serialize, or is more than [`MAX_METADATA_SIZE`]
/// bytes, the error is [`Error::InvalidInput`].
pub(crate) fn build_commit(inputs: CommitInputs<'_>) -> Result<(Checksum, Vec<u8>)> {
    let names: Vec<&str> = inputs.refs.iter().map(String::as_str).collect();
    let bindings = (!inputs.no_bindings).then_some(names.as_slice());
    let metadata = commit_metadata(
        inputs.metadata.into_iter().map(split_entry),
        bindings,
        inputs.collection_id,
    );
    let bytes = Commit {
        metadata,
        parent: inputs.parent,
        related: Vec::new(),
        subject: inputs.subject,
        body: inputs.body,
        timestamp: inputs.timestamp,
        root_dirtree: inputs.root_dirtree,
        root_dirmeta: inputs.root_dirmeta,
    }
    .serialize()
    .map_err(|e| invalid(format!("the commit does not serialize: {e}")))?;
    if bytes.len() as u64 > MAX_METADATA_SIZE {
        return Err(invalid(format!(
            "the commit object is {} bytes, over the limit of {MAX_METADATA_SIZE}",
            bytes.len()
        )));
    }
    Ok((Checksum::sha256(&bytes), bytes))
}

/// The number of framing offsets in a commit object.
///
/// A commit object has one offset for each member of variable size other than
/// the last. These members are:
///
/// - the metadata dict
/// - the parent
/// - the related objects
/// - the subject
/// - the body
/// - the root dirtree
const COMMIT_FRAMING_OFFSETS: usize = 6;

/// Returns a lower bound of the size of the commit object of [`build_commit`].
///
/// The bound uses only the inputs that do not depend on `HelloReply`.
/// `metadata_len` is the size of the serialized dict of the caller. The bound
/// counts these parts:
///
/// - the dict of the caller
/// - the parent of [`ParentPolicy::Commit`]
/// - the subject and the body, with their NUL terminators
/// - the padding before the timestamp, and the timestamp
/// - the two root checksums
/// - the framing offsets
///
/// The bindings and a parent from the server only add bytes. If the commit has
/// no bindings and its parent does not come from the server, the bound is
/// equal to the size of the commit object.
pub(crate) fn commit_size_floor(
    metadata_len: u64,
    subject: &str,
    body: &str,
    parent: ParentPolicy,
) -> u64 {
    let parent_len = match parent {
        ParentPolicy::Commit(_) => 32,
        ParentPolicy::CurrentTip | ParentPolicy::None => 0,
    };
    let before_timestamp = metadata_len + parent_len + subject.len() as u64 + body.len() as u64 + 2;
    let data = before_timestamp.next_multiple_of(8) + 8 + 32 + 32;
    let offset =
        usize::try_from(data).map_or(8, |len| choose_offset_size(len, COMMIT_FRAMING_OFFSETS));
    data + (COMMIT_FRAMING_OFFSETS * offset) as u64
}

/// Refuses a commit object whose lower bound is more than `limit` bytes.
///
/// `floor` is the bound from [`commit_size_floor`]. The error is
/// [`Error::InvalidInput`].
pub(crate) fn check_commit_floor(floor: u64, limit: u64) -> Result<()> {
    if floor > limit {
        return Err(invalid(format!(
            "the commit object is at least {floor} bytes, over the limit of {limit}"
        )));
    }
    Ok(())
}

/// Returns the detached metadata dict of the commit `bytes`.
///
/// The dict holds the entries of the caller, in their order. Then it holds the
/// signature of each signer of `signers`, in order, under the `metadata_key`
/// of the signer. If the dict is empty, the result is `None`.
///
/// A signature goes at the end of the `aay` array of its key, after the blobs
/// that the array already holds. This is also true for the array of an entry
/// of the caller. The function checks the key of each signer before the first
/// signer signs.
///
/// # Errors
///
/// - [`Error::Sign`] with `InvalidFormat` if a value of the caller under the
///   key of a signer is not an `aay`.
/// - [`Error::Sign`] with the error of the signer if a signer fails, and with
///   the error of `append_signature` if the append of a signature fails.
/// - [`Error::InvalidInput`] if the dict does not serialize, or is more than
///   [`MAX_METADATA_SIZE`] bytes.
pub(crate) async fn detached_dict(
    entries: Vec<Value>,
    signers: &[Box<dyn Signer>],
    bytes: &[u8],
) -> Result<Option<Value>> {
    let mut dict = Value::Array(entries);
    for signer in signers {
        let key = signer.metadata_key();
        if let Some((ty, _)) = dict.dict_get(key).and_then(Value::as_variant)
            && ty.signature() != SIGNATURE_ARRAY
        {
            return Err(Error::Sign(ostrya_sign::Error::InvalidFormat(format!(
                "the detached metadata holds '{key}' of type {}, not {SIGNATURE_ARRAY}",
                ty.signature()
            ))));
        }
    }
    for signer in signers {
        let signature = signer.sign(bytes).await.map_err(Error::Sign)?;
        ostrya_sign::append_signature(&mut dict, signer.metadata_key(), signature)
            .map_err(Error::Sign)?;
    }
    if dict.as_array().is_some_and(<[Value]>::is_empty) {
        return Ok(None);
    }
    let len = to_bytes(&DICT_TYPE, &dict)
        .map_err(|e| invalid(format!("the detached metadata does not serialize: {e}")))?
        .len();
    if len as u64 > MAX_METADATA_SIZE {
        return Err(invalid(format!(
            "the detached metadata is {len} bytes, over the limit of {MAX_METADATA_SIZE}"
        )));
    }
    Ok(Some(dict))
}

/// Returns the ref updates that set each target ref to `commit`.
///
/// Each update expects the state that the server reported. If `force` is
/// `true`, each update expects any state.
pub(crate) fn ref_updates(
    server: &ServerInfo,
    refs: &[String],
    commit: Checksum,
    force: bool,
) -> Vec<RefUpdate> {
    debug_assert!(names_match(server, refs));
    server
        .refs
        .iter()
        .map(|state| RefUpdate {
            name: state.name.clone(),
            expected: match (force, state.commit) {
                (true, _) => Expected::Any,
                (false, Some(tip)) => Expected::Commit(tip),
                (false, None) => Expected::Absent,
            },
            new: Some(commit),
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    use ostrya_core::base64;
    use ostrya_sign::{DummySigner, Ed25519Signer, Ed25519Verifier, Verifier};

    use super::*;
    use crate::proto::{Encoding, RefState};

    fn csum(byte: u8) -> Checksum {
        Checksum::from_bytes([byte; 32])
    }

    fn strings(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    fn string(s: &str) -> Value {
        Value::variant(Type::Str, Value::Str(s.to_owned()))
    }

    fn server(collection_id: Option<&str>, refs: &[(&str, Option<Checksum>)]) -> ServerInfo {
        ServerInfo {
            version: 1,
            mode: "archive".into(),
            collection_id: collection_id.map(str::to_owned),
            max_frame: 1 << 20,
            max_have: 16_384,
            encodings: vec![Encoding::Raw],
            parallel_uploads: 1,
            refs: refs
                .iter()
                .map(|(name, commit)| RefState {
                    name: (*name).to_owned(),
                    commit: *commit,
                })
                .collect(),
        }
    }

    fn inputs<'a>(metadata: Vec<Value>, refs: &'a [String]) -> CommitInputs<'a> {
        CommitInputs {
            parent: None,
            subject: "subject".into(),
            body: "body".into(),
            timestamp: 1_700_000_000,
            metadata,
            refs,
            no_bindings: false,
            collection_id: None,
            root_dirtree: csum(1),
            root_dirmeta: csum(2),
        }
    }

    /// Returns the keys of a dict, in order.
    fn keys(dict: &Value) -> Vec<String> {
        dict.as_array()
            .unwrap()
            .iter()
            .map(|entry| entry.as_tuple().unwrap()[0].as_str().unwrap().to_owned())
            .collect()
    }

    fn caller_entries() -> Vec<Value> {
        entry_dict(
            vec![
                ("zz.last".into(), string("1")),
                ("aa.first".into(), string("2")),
            ],
            "metadata",
        )
        .unwrap()
        .0
    }

    #[test]
    fn the_metadata_holds_the_caller_entries_then_the_bindings() {
        let refs = strings(&["b", "a"]);
        let (checksum, bytes) = build_commit(CommitInputs {
            collection_id: Some("org.example.C"),
            ..inputs(caller_entries(), &refs)
        })
        .unwrap();
        assert_eq!(checksum, Checksum::sha256(&bytes));
        let commit = Commit::parse(&bytes).unwrap();
        assert_eq!(
            keys(&commit.metadata),
            [
                "zz.last",
                "aa.first",
                "ostree.ref-binding",
                "ostree.collection-binding"
            ]
        );
        assert_eq!(commit.ref_bindings(), ["a", "b"]);
        assert_eq!(commit.collection_binding(), Some("org.example.C"));
        let want = commit_metadata(
            [
                ("zz.last".to_owned(), string("1")),
                ("aa.first".to_owned(), string("2")),
            ],
            Some(&["b", "a"]),
            Some("org.example.C"),
        );
        assert_eq!(commit.metadata, want);
    }

    #[test]
    fn no_bindings_leaves_out_both_bindings() {
        let refs = strings(&["main"]);
        let (_, bytes) = build_commit(CommitInputs {
            no_bindings: true,
            collection_id: Some("org.example.C"),
            ..inputs(caller_entries(), &refs)
        })
        .unwrap();
        let commit = Commit::parse(&bytes).unwrap();
        assert_eq!(keys(&commit.metadata), ["zz.last", "aa.first"]);
    }

    #[test]
    fn the_collection_binding_needs_a_server_collection_id() {
        let refs = strings(&["main"]);
        let (_, bytes) = build_commit(inputs(Vec::new(), &refs)).unwrap();
        let commit = Commit::parse(&bytes).unwrap();
        assert_eq!(keys(&commit.metadata), ["ostree.ref-binding"]);
        assert_eq!(commit.collection_binding(), None);
    }

    #[test]
    fn the_commit_carries_its_fields() {
        let refs = strings(&["main"]);
        let (_, bytes) = build_commit(CommitInputs {
            parent: Some(csum(9)),
            ..inputs(Vec::new(), &refs)
        })
        .unwrap();
        let commit = Commit::parse(&bytes).unwrap();
        assert_eq!(commit.parent, Some(csum(9)));
        assert_eq!(commit.subject, "subject");
        assert_eq!(commit.body, "body");
        assert_eq!(commit.timestamp, 1_700_000_000);
        assert_eq!(commit.root_dirtree, csum(1));
        assert_eq!(commit.root_dirmeta, csum(2));
        assert!(commit.related.is_empty());
    }

    /// Returns the dict of [`caller_entries`] and its size.
    fn measured_caller_entries() -> (Vec<Value>, u64) {
        let (entries, len) = entry_dict(
            vec![
                ("zz.last".into(), string("1")),
                ("aa.first".into(), string("2")),
            ],
            "metadata",
        )
        .unwrap();
        assert_eq!(entries, caller_entries());
        (entries, len)
    }

    #[test]
    fn the_commit_size_floor_is_the_commit_size_without_the_server_inputs() {
        let refs = strings(&["main"]);
        // The body lengths move the padding before the timestamp. They also
        // cross the sizes where the framing offsets grow from one byte to two.
        for body_len in (0..=300).chain(65_380..=65_480) {
            let body = "b".repeat(body_len);
            for parent in [None, Some(csum(9))] {
                let (entries, len) = measured_caller_entries();
                let (_, bytes) = build_commit(CommitInputs {
                    parent,
                    body: body.clone(),
                    no_bindings: true,
                    ..inputs(entries, &refs)
                })
                .unwrap();
                let policy = parent.map_or(ParentPolicy::None, ParentPolicy::Commit);
                let floor = commit_size_floor(len, "subject", &body, policy);
                assert_eq!(floor, bytes.len() as u64, "{body_len} {parent:?}");
                check_commit_floor(floor, floor).unwrap();
                match check_commit_floor(floor, floor - 1) {
                    Err(Error::InvalidInput(m)) => {
                        assert!(m.contains("the commit object is at least"), "{m}")
                    }
                    other => panic!("{body_len} {parent:?}: {other:?}"),
                }
            }
        }
    }

    #[test]
    fn the_server_inputs_only_add_to_the_commit_size_floor() {
        let refs = strings(&["main", "other"]);
        for (tip, collection_id) in [(None, None), (Some(csum(9)), Some("org.example.C"))] {
            let (entries, len) = measured_caller_entries();
            let floor = commit_size_floor(len, "subject", "body", ParentPolicy::CurrentTip);
            let (_, bytes) = build_commit(CommitInputs {
                parent: tip,
                collection_id,
                ..inputs(entries, &refs)
            })
            .unwrap();
            assert!(floor < bytes.len() as u64, "{floor} {}", bytes.len());
        }
    }

    #[test]
    fn a_metadata_dict_with_an_empty_key_or_a_bare_value_is_refused() {
        let empty = entry_dict(vec![(String::new(), string("x"))], "metadata");
        assert!(
            matches!(&empty, Err(Error::InvalidInput(m)) if m.contains("empty key")),
            "{empty:?}"
        );
        let bare = entry_dict(
            vec![("k".into(), Value::Str("not a variant".into()))],
            "detached metadata",
        );
        assert!(
            matches!(&bare, Err(Error::InvalidInput(m)) if m.contains("detached metadata")),
            "{bare:?}"
        );
    }

    #[test]
    fn the_parent_follows_the_policy() {
        let refs = strings(&["a", "b"]);
        let at = server(None, &[("a", Some(csum(5))), ("b", Some(csum(5)))]);
        let absent = server(None, &[("a", None), ("b", None)]);
        assert_eq!(
            resolve_parent(ParentPolicy::CurrentTip, &at, &refs),
            Some(csum(5))
        );
        assert_eq!(
            resolve_parent(ParentPolicy::CurrentTip, &absent, &refs),
            None
        );
        assert_eq!(resolve_parent(ParentPolicy::None, &at, &refs), None);
        assert_eq!(
            resolve_parent(ParentPolicy::Commit(csum(7)), &absent, &refs),
            Some(csum(7))
        );
    }

    #[test]
    fn target_refs_in_mixed_states_are_refused() {
        let refs = strings(&["a", "b"]);
        let accepted = [
            server(None, &[("a", None), ("b", None)]),
            server(None, &[("a", Some(csum(5))), ("b", Some(csum(5)))]),
        ];
        for info in &accepted {
            check_ref_states(info, &refs).unwrap();
        }
        let refused = [
            server(None, &[("a", None), ("b", Some(csum(5)))]),
            server(None, &[("a", Some(csum(5))), ("b", None)]),
            server(None, &[("a", Some(csum(5))), ("b", Some(csum(6)))]),
        ];
        for info in &refused {
            match check_ref_states(info, &refs) {
                Err(Error::InvalidInput(m)) => {
                    for state in &info.refs {
                        let want = match state.commit {
                            Some(tip) => format!("'{}' is at {tip}", state.name),
                            None => format!("'{}' is absent", state.name),
                        };
                        assert!(m.contains(&want), "{m}");
                    }
                }
                other => panic!("{:?}: {other:?}", info.refs),
            }
        }
        check_ref_states(&server(None, &[("a", Some(csum(5)))]), &refs[..1]).unwrap();
    }

    #[test]
    fn each_update_expects_the_reported_state_or_any_with_force() {
        let refs = strings(&["a", "b"]);
        let info = server(None, &[("a", Some(csum(5))), ("b", None)]);
        let updates = ref_updates(&info, &refs, csum(8), false);
        assert_eq!(
            updates,
            [
                RefUpdate {
                    name: "a".into(),
                    expected: Expected::Commit(csum(5)),
                    new: Some(csum(8)),
                },
                RefUpdate {
                    name: "b".into(),
                    expected: Expected::Absent,
                    new: Some(csum(8)),
                },
            ]
        );
        for update in ref_updates(&info, &refs, csum(8), true) {
            assert_eq!(update.expected, Expected::Any);
        }
    }

    /// The base64 of a 64-byte ed25519 secret key (seed, then public key).
    const SECRET_B64: &str =
        "o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";

    /// Returns the blobs of the `aay` under `key`.
    fn blobs(dict: &Value, key: &str) -> Vec<Vec<u8>> {
        let (_, inner) = dict.dict_get(key).unwrap().as_variant().unwrap();
        inner
            .as_array()
            .unwrap()
            .iter()
            .map(|blob| blob.as_bytes().unwrap().to_vec())
            .collect()
    }

    #[test]
    fn signatures_follow_the_caller_entries_in_signer_order() {
        let secret = base64::decode(SECRET_B64).unwrap();
        let signers: Vec<Box<dyn Signer>> = vec![
            Box::new(DummySigner::new(b"dummy-key".to_vec())),
            Box::new(Ed25519Signer::from_secret_key(&secret).unwrap()),
        ];
        let entries = entry_dict(vec![("xa.k".into(), string("v"))], "detached")
            .unwrap()
            .0;
        let payload = b"commit bytes";
        let dict = futures_lite::future::block_on(detached_dict(entries, &signers, payload))
            .unwrap()
            .unwrap();
        assert_eq!(
            keys(&dict),
            ["xa.k", "ostree.sign.dummy", "ostree.sign.ed25519"]
        );
        assert_eq!(blobs(&dict, "ostree.sign.dummy"), [b"dummy-key".to_vec()]);
        let verifier = Ed25519Verifier::new([&secret[32..]], Vec::<Vec<u8>>::new()).unwrap();
        let outcome = futures_lite::future::block_on(
            verifier.verify(payload, &blobs(&dict, "ostree.sign.ed25519")),
        )
        .unwrap();
        assert!(outcome.valid);
    }

    #[test]
    fn a_caller_signature_array_gets_the_signature_appended() {
        let signers: Vec<Box<dyn Signer>> = vec![Box::new(DummySigner::new(b"new".to_vec()))];
        let array = Value::variant(
            Type::parse(SIGNATURE_ARRAY).unwrap(),
            Value::Array(vec![Value::Bytes(b"old".to_vec())]),
        );
        let entries = entry_dict(vec![("ostree.sign.dummy".into(), array)], "detached")
            .unwrap()
            .0;
        let dict = futures_lite::future::block_on(detached_dict(entries, &signers, b"x"))
            .unwrap()
            .unwrap();
        assert_eq!(keys(&dict), ["ostree.sign.dummy"]);
        assert_eq!(
            blobs(&dict, "ostree.sign.dummy"),
            [b"old".to_vec(), b"new".to_vec()]
        );
    }

    #[test]
    fn a_caller_value_of_another_type_under_a_signer_key_is_invalid_format() {
        let signers: Vec<Box<dyn Signer>> = vec![Box::new(DummySigner::new(b"new".to_vec()))];
        for value in [
            string("x"),
            Value::variant(Type::parse("as").unwrap(), Value::Array(Vec::new())),
        ] {
            let entries = entry_dict(vec![("ostree.sign.dummy".into(), value)], "detached")
                .unwrap()
                .0;
            let r = futures_lite::future::block_on(detached_dict(entries, &signers, b"x"));
            assert!(
                matches!(r, Err(Error::Sign(ostrya_sign::Error::InvalidFormat(_)))),
                "{r:?}"
            );
        }
    }

    /// A signer that records a call of `sign`.
    struct Recording {
        called: Arc<AtomicBool>,
    }

    impl Signer for Recording {
        fn name(&self) -> &str {
            "recording"
        }

        fn metadata_key(&self) -> &str {
            "ostree.sign.recording"
        }

        fn sign<'a>(&'a self, _data: &'a [u8]) -> ostrya_sign::SignFuture<'a> {
            self.called.store(true, Ordering::SeqCst);
            Box::pin(async { Ok(b"recorded".to_vec()) })
        }
    }

    #[test]
    fn the_key_of_each_signer_is_checked_before_the_first_signs() {
        let called = Arc::new(AtomicBool::new(false));
        let signers: Vec<Box<dyn Signer>> = vec![
            Box::new(Recording {
                called: called.clone(),
            }),
            Box::new(DummySigner::new(b"new".to_vec())),
        ];
        let entries = entry_dict(vec![("ostree.sign.dummy".into(), string("x"))], "detached")
            .unwrap()
            .0;
        let r = futures_lite::future::block_on(detached_dict(entries, &signers, b"x"));
        assert!(
            matches!(r, Err(Error::Sign(ostrya_sign::Error::InvalidFormat(_)))),
            "{r:?}"
        );
        assert!(!called.load(Ordering::SeqCst));
    }

    #[test]
    fn an_empty_detached_dict_is_none() {
        let r = futures_lite::future::block_on(detached_dict(Vec::new(), &[], b"x")).unwrap();
        assert_eq!(r, None);
    }
}