ostrya 0.19.1

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
//! The union merge of an incoming detached-metadata dict into the dict that
//! the receiving repository holds for the same commit.
//!
//! The public text of the merge rules is on `Repo::receive`, under
//! `# Detached metadata merge`.

use std::collections::{HashMap, HashSet};

use ostrya_core::{ArrayIter, GvDecode, GvEncode, GvType, Type, Value, VariantBytes};

use crate::error::{Error, Result};
use crate::sign::X509Attachments;

/// The detached-metadata keys whose value is a list of signatures, an `aay`.
///
/// Under these keys, the merge takes the union of the stored list and the
/// incoming list. The list is the same in each build. A build without
/// `sign-spki` keeps the stored `ostree.sign.spki` signatures and adds the
/// incoming ones.
pub(crate) const SIGNATURE_KEYS: [&str; 4] = [
    "ostree.gpgsigs",
    "ostree.sign.ed25519",
    "ostree.sign.spki",
    "ostree.sign.dummy",
];

/// The detached-metadata keys of the X.509 chains and CRLs, each with the
/// GVariant type of its value.
///
/// Under these keys, the merge appends each incoming element that the stored
/// list does not hold, the append rule of `append_x509` of `ostrya-sign`. The
/// list is the same in each build.
pub(crate) const X509_KEYS: [(&str, &str); 2] = [
    (crate::sign::X509_CHAINS_KEY, "aaay"),
    (crate::sign::X509_CRLS_KEY, "aay"),
];

/// The GVariant type of a signature list.
const SIGNATURE_ARRAY: &str = "aay";
/// The name of the merge of the two dicts in an error message.
const MERGED: &str = "the merged detached metadata";
/// The name of the incoming dict in an error message.
const INCOMING: &str = "the incoming detached metadata";
/// The name of the stored dict in an error message.
const STORED: &str = "the stored detached metadata";
/// The name of a host entry in an error message.
const HOST: &str = "a detached-metadata entry of the host";

/// Merges the `a{sv}` dict `incoming` into `stored` and returns the merged dict.
///
/// `stored` is the dict that the repository holds for the same commit. It is
/// `None` if the repository holds no detached metadata for the commit, or
/// holds the zero-length "no metadata" marker.
///
/// # Merge rules
///
/// The merged dict has the stored keys first, in the stored order. Then it
/// has each key that only the incoming dict holds, in the incoming order.
///
/// - Under a key of [`SIGNATURE_KEYS`], the value is the union of the two
///   lists. The union holds the stored blobs in the stored order. Then it
///   holds each incoming blob that is not byte-equal to a blob already in the
///   list. A duplicate in the stored list stays.
/// - Under a key of [`X509_KEYS`], the value is the union of the two lists
///   by the same rule: the stored chains or CRLs, then each incoming element
///   that is not equal to an element already in the list. Two chains are
///   equal when they hold the same certificates in the same order. The union
///   holds at most [`MAX_X509_CHAINS`](crate::sign::MAX_X509_CHAINS) chains
///   and [`MAX_X509_CRLS`](crate::sign::MAX_X509_CRLS) CRLs.
/// - Under a key of `keep` that the stored dict holds, the stored value stays
///   and the merge drops the incoming value. If the stored dict does not hold
///   a key of `keep`, the merge adds the incoming entry as for each other new
///   key.
/// - Under each other key, the incoming value replaces the stored value, at
///   the position of the stored key.
/// - A key that only the stored dict holds stays.
///
/// # Size and filter
///
/// The merged dict can be larger than either input. If its serialized form is
/// over [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE), the caller refuses it
/// before the write. This function applies no filter. The caller applies the
/// rule of `[ex-ostrya] keep-detached-related` to the incoming dict before
/// the merge.
///
/// # Cost
///
/// The merge moves the entries and the blobs of both inputs into the merged
/// dict. It copies no blob. Its time is linear in the number of keys and blobs
/// of the two inputs.
///
/// # Errors
///
/// The function returns [`Error::InvalidFormat`] for each of these inputs:
///
/// - an input that is not an array of `{sv}` entries
/// - an incoming dict that holds one key twice
/// - a value under a signature key that is not an `aay`, in either dict
/// - a value under a key of [`X509_KEYS`] that is not of the type of the key,
///   in either dict
/// - a union of the chains or the CRLs over its limit
///
/// The merge checks the type of a stored signature value too. It refuses a
/// stored list that it cannot extend, and does not replace it.
pub(crate) fn merge_detached(
    stored: Option<Value>,
    incoming: Value,
    keep: &[String],
) -> Result<Value> {
    let incoming = dict_entries(incoming, INCOMING)?;
    let mut seen = HashSet::with_capacity(incoming.len());
    for (key, _) in &incoming {
        if !seen.insert(key.as_str()) {
            return Err(Error::InvalidFormat(format!(
                "the incoming detached metadata holds the key '{key}' more than once"
            )));
        }
    }
    drop(seen);
    let mut merged = match stored {
        Some(stored) => dict_entries(stored, STORED)?,
        None => Vec::new(),
    };
    // The position of each stored key in `merged`. A key that the stored dict
    // holds twice maps to its first entry. The incoming keys are distinct, so
    // the loop never looks up a key that it appends.
    let mut positions: HashMap<String, usize> = HashMap::with_capacity(merged.len());
    for (position, (key, _)) in merged.iter().enumerate() {
        positions.entry(key.clone()).or_insert(position);
    }
    let keep: HashSet<&str> = keep.iter().map(String::as_str).collect();
    for (key, value) in incoming {
        let signatures = SIGNATURE_KEYS.contains(&key.as_str());
        if let Some(&(_, ty)) = X509_KEYS.iter().find(|(k, _)| *k == key) {
            let fresh = x509_list(value, &key, ty, INCOMING)?;
            match positions.get(&key) {
                Some(&position) => {
                    // The merged dict is a local value that an error drops,
                    // so the stored list moves out with no copy.
                    let value = &mut merged[position].1;
                    let stored = std::mem::replace(value, Value::Array(Vec::new()));
                    let mut list = x509_list(stored, &key, ty, STORED)?;
                    x509_union(&mut list, fresh, &key)?;
                    *value = x509_value(list, ty)?;
                }
                None => {
                    let mut list = Vec::new();
                    x509_union(&mut list, fresh, &key)?;
                    merged.push((key, x509_value(list, ty)?));
                }
            }
            continue;
        }
        match positions.get(&key) {
            Some(&position) if signatures => {
                let list = signature_list(&mut merged[position].1, &key, STORED)?;
                union(list, signature_blobs(value, &key, INCOMING)?);
            }
            Some(_) if keep.contains(key.as_str()) => {}
            Some(&position) => merged[position].1 = value,
            None if signatures => {
                let mut list = Vec::new();
                union(&mut list, signature_blobs(value, &key, INCOMING)?);
                merged.push((key, signature_value(list)?));
            }
            None => merged.push((key, value)),
        }
    }
    Ok(Value::Array(
        merged
            .into_iter()
            .map(|(key, value)| Value::Tuple(vec![Value::Str(key), value]))
            .collect(),
    ))
}

/// Returns the serialized dict `incoming` with the `host` entries in place of
/// the entries of the same keys.
///
/// `incoming` is `None` if there is no incoming dict. Each dict of `host`
/// holds one entry. The function builds no value.
///
/// The output holds each entry of `incoming` whose key no dict of `host`
/// holds, in the incoming order. Then it holds the entries of `host`, in
/// order. The function copies each entry as its bytes, in one pass over the
/// inputs. The output bytes are the bytes of the serialization of the same
/// dict.
///
/// The caller checked each dict of `host` as an `a{sv}` in normal form, so
/// the function reads it with no second check. If `incoming` is not an
/// `a{sv}` in normal form, the function returns [`Error::InvalidFormat`].
pub(crate) fn replace_entries(incoming: Option<&[u8]>, host: &[Vec<u8>]) -> Result<Vec<u8>> {
    let mut replacing = Vec::with_capacity(host.len());
    for dict in host {
        let entries: ArrayIter<(&str, VariantBytes)> =
            ArrayIter::decode(dict).map_err(|e| not_a_dict(HOST, e))?;
        for entry in entries {
            replacing.push(entry.map_err(|e| not_a_dict(HOST, e))?);
        }
    }
    let keys: HashSet<&str> = replacing.iter().map(|(key, _)| *key).collect();
    let kept = match incoming {
        Some(bytes) => Some((entries_in_place(bytes, INCOMING)?, entry_count(bytes))),
        None => None,
    };
    let count = kept.as_ref().map_or(0, |(_, count)| *count);
    let mut entries: Vec<(&str, VariantBytes)> = Vec::with_capacity(count + replacing.len());
    if let Some((kept, _)) = kept {
        for entry in kept {
            let (key, value) = entry.map_err(|e| not_a_dict(INCOMING, e))?;
            if !keys.contains(key) {
                entries.push((key, value));
            }
        }
    }
    entries.extend(replacing);
    let size = incoming.map_or(0, <[u8]>::len) + host.iter().map(Vec::len).sum::<usize>();
    let mut out = Vec::with_capacity(size);
    ostrya_core::write_array(
        &mut out,
        <(&str, VariantBytes) as GvType>::ALIGNMENT,
        false,
        entries.len(),
        |out, i| entries[i].encode(out),
    )
    .map_err(ostrya_core::Error::from)?;
    Ok(out)
}

/// Returns the number of entries of `bytes`, from its framing offsets.
///
/// `bytes` is a serialized `a{sv}` that the caller checked in normal form. The
/// last offset is the end of the last entry. The offsets take the bytes after
/// that end, one offset for each entry.
fn entry_count(bytes: &[u8]) -> usize {
    let z = ostrya_core::offset_size_for(bytes.len());
    let Some(last) = bytes.len().checked_sub(z) else {
        return 0;
    };
    let mut end = [0u8; 8];
    end[..z].copy_from_slice(&bytes[last..]);
    let end = u64::from_le_bytes(end) as usize;
    bytes.len().saturating_sub(end) / z
}

/// Checks that [`merge_detached`] accepts the serialized dict `bytes` as its
/// incoming dict.
///
/// The dict must be an `a{sv}` in normal form that holds each key once, with
/// an `aay` under each key of [`SIGNATURE_KEYS`]. Under each key of
/// [`X509_KEYS`], the value must be of the type of the key and hold at most
/// [`MAX_X509_CHAINS`](crate::sign::MAX_X509_CHAINS) different chains or
/// [`MAX_X509_CRLS`](crate::sign::MAX_X509_CRLS) different CRLs. If a check
/// fails, the function returns [`Error::InvalidFormat`].
///
/// The check builds no value. It applies the limits of the parser. Its memory
/// grows with the number of keys only.
pub(crate) fn check_incoming(bytes: &[u8]) -> Result<()> {
    let mut seen = HashSet::new();
    for entry in entries_in_place(bytes, INCOMING)? {
        let (key, value) = entry.map_err(|e| not_a_dict(INCOMING, e))?;
        if !seen.insert(key) {
            return Err(Error::InvalidFormat(format!(
                "the incoming detached metadata holds the key '{key}' more than once"
            )));
        }
        if SIGNATURE_KEYS.contains(&key) && value.signature() != SIGNATURE_ARRAY {
            return Err(not_aay(key, INCOMING));
        }
        if let Some(&(_, ty)) = X509_KEYS.iter().find(|(k, _)| *k == key) {
            if value.signature() != ty {
                return Err(not_of_type(key, ty, INCOMING));
            }
            check_x509_count(key, &[value.child()], INCOMING)?;
        }
    }
    Ok(())
}

/// Checks that the merge of the serialized dict `incoming` accepts `stored`,
/// the serialized dict that the repository holds, under the keys of
/// [`X509_KEYS`].
///
/// For each key of [`X509_KEYS`] that `incoming` holds, the first entry of
/// `stored` under the key must hold the type of the key, and the union of the
/// two lists must hold at most the limit of the key. The check builds no
/// value. If a check fails, the function returns [`Error::InvalidFormat`].
pub(crate) fn check_stored_x509(stored: &[u8], incoming: &[u8]) -> Result<()> {
    let mut touched: [Option<&[u8]>; X509_KEYS.len()] = [None; X509_KEYS.len()];
    for entry in entries_in_place(incoming, INCOMING)? {
        let (key, value) = entry.map_err(|e| not_a_dict(INCOMING, e))?;
        if let Some(i) = X509_KEYS.iter().position(|(k, _)| *k == key) {
            touched[i] = Some(value.child());
        }
    }
    let mut checked = [false; X509_KEYS.len()];
    for entry in entries_in_place(stored, STORED)? {
        let (key, value) = entry.map_err(|e| not_a_dict(STORED, e))?;
        if let Some(i) = X509_KEYS.iter().position(|(k, _)| *k == key)
            && let Some(incoming) = touched[i]
            && !std::mem::replace(&mut checked[i], true)
        {
            if value.signature() != X509_KEYS[i].1 {
                return Err(not_of_type(key, X509_KEYS[i].1, STORED));
            }
            check_x509_count(key, &[value.child(), incoming], MERGED)?;
        }
    }
    Ok(())
}

/// Refuses `lists`, each the serialized list of a value under the key `key`
/// of [`X509_KEYS`], if the lists together hold more different elements than
/// the limit of the key.
///
/// The caller validated each dict in normal form, so two elements are equal
/// when their serialized bytes are equal. The count stops at the first
/// element over the limit, so its work is bounded by the size of the lists.
/// `subject` names the dict in an error message.
fn check_x509_count(key: &str, lists: &[&[u8]], subject: &str) -> Result<()> {
    let limit = x509_limit(key);
    let mut seen: Vec<&[u8]> = Vec::with_capacity(limit);
    for list in lists {
        for element in ArrayIter::<&[u8]>::decode(list).map_err(|e| not_a_dict(subject, e))? {
            let element = element.map_err(|e| not_a_dict(subject, e))?;
            if !seen.contains(&element) {
                if seen.len() == limit {
                    return Err(over_x509_limit(key, subject));
                }
                seen.push(element);
            }
        }
    }
    Ok(())
}

/// Checks that the merge of the serialized dict `incoming` into the
/// serialized dict `stored`, and then the append of the X.509 chains and
/// CRLs of each of `server`, accept the dicts under the keys of
/// [`X509_KEYS`].
///
/// The rules are the rules of [`merge_detached`] and of
/// [`append_x509`](crate::sign::append_x509). The check applies to a key
/// that `incoming` holds, or that an element of `server` adds to. The first
/// entry of each dict under the key must hold the type of the key. The list
/// of the key is the stored elements, then each incoming element and each
/// element of `server` that is not equal to an element before it. The list
/// must hold at most the limit of the key.
///
/// The check builds no value, and copies no certificate and no CRL. The
/// count stops at the first element over the limit. If a check fails, the
/// function returns [`Error::InvalidFormat`].
pub(crate) fn check_x509_union<'a>(
    stored: Option<&'a [u8]>,
    incoming: Option<&'a [u8]>,
    server: &'a [X509Attachments],
) -> Result<()> {
    let stored = match stored {
        Some(bytes) => x509_values(bytes, STORED)?,
        None => [None; X509_KEYS.len()],
    };
    let incoming = match incoming {
        Some(bytes) => x509_values(bytes, INCOMING)?,
        None => [None; X509_KEYS.len()],
    };
    for (i, &(key, ty)) in X509_KEYS.iter().enumerate() {
        let chains = key == crate::sign::X509_CHAINS_KEY;
        let added: Vec<Vec<&'a [u8]>> = if chains {
            server
                .iter()
                .flat_map(X509Attachments::chains)
                .map(|chain| chain.iter().map(Vec::as_slice).collect())
                .collect()
        } else {
            server
                .iter()
                .flat_map(X509Attachments::crls)
                .map(|crl| vec![crl.as_slice()])
                .collect()
        };
        if incoming[i].is_none() && added.is_empty() {
            continue;
        }
        let limit = x509_limit(key);
        // The list holds each stored element, also a duplicate, as the merge
        // and the append count them. `held` holds each different element
        // once.
        let mut len = 0;
        let mut held: Vec<Vec<&'a [u8]>> = Vec::with_capacity(limit);
        let mut add = |element: Vec<&'a [u8]>, stored: bool| -> Result<()> {
            let new = !held.contains(&element);
            if stored || new {
                if len == limit {
                    return Err(over_x509_limit(key, MERGED));
                }
                len += 1;
            }
            if new {
                held.push(element);
            }
            Ok(())
        };
        for (value, subject, stored) in [(stored[i], STORED, true), (incoming[i], INCOMING, false)]
        {
            let Some(value) = value else {
                continue;
            };
            if value.signature() != ty {
                return Err(not_of_type(key, ty, subject));
            }
            for element in
                ArrayIter::<&[u8]>::decode(value.child()).map_err(|e| not_a_dict(subject, e))?
            {
                let element = element.map_err(|e| not_a_dict(subject, e))?;
                let element = match chains {
                    true => ArrayIter::<&[u8]>::decode(element)
                        .map_err(|e| not_a_dict(subject, e))?
                        .collect::<std::result::Result<Vec<_>, _>>()
                        .map_err(|e| not_a_dict(subject, e))?,
                    false => vec![element],
                };
                add(element, stored)?;
            }
        }
        for element in added {
            add(element, false)?;
        }
    }
    Ok(())
}

/// Returns the value of the first entry of the serialized dict `bytes` under
/// each key of [`X509_KEYS`], in the order of the list.
///
/// `subject` names the dict in an error message.
fn x509_values<'a>(
    bytes: &'a [u8],
    subject: &str,
) -> Result<[Option<VariantBytes<'a>>; X509_KEYS.len()]> {
    let mut values = [None; X509_KEYS.len()];
    for entry in entries_in_place(bytes, subject)? {
        let (key, value) = entry.map_err(|e| not_a_dict(subject, e))?;
        if let Some(i) = X509_KEYS.iter().position(|(k, _)| *k == key)
            && values[i].is_none()
        {
            values[i] = Some(value);
        }
    }
    Ok(values)
}

/// Returns the number of elements that a dict holds at most under `key`, a
/// key of [`X509_KEYS`].
fn x509_limit(key: &str) -> usize {
    if key == crate::sign::X509_CHAINS_KEY {
        crate::sign::MAX_X509_CHAINS
    } else {
        crate::sign::MAX_X509_CRLS
    }
}

/// Returns the error for more different elements under `key`, a key of
/// [`X509_KEYS`], than its limit.
///
/// `subject` names the dict in an error message.
fn over_x509_limit(key: &str, subject: &str) -> Error {
    Error::InvalidFormat(format!(
        "{subject} holds more than {} different elements under '{key}'",
        x509_limit(key)
    ))
}

/// Returns the keys of [`SIGNATURE_KEYS`] that the serialized incoming dict
/// `bytes` holds.
///
/// The result has one flag for each key, in the order of the list. If the dict
/// is not an `a{sv}` in normal form, the function returns
/// [`Error::InvalidFormat`].
pub(crate) fn signature_keys_in(bytes: &[u8]) -> Result<[bool; SIGNATURE_KEYS.len()]> {
    let mut held = [false; SIGNATURE_KEYS.len()];
    for entry in entries_in_place(bytes, INCOMING)? {
        let (key, _) = entry.map_err(|e| not_a_dict(INCOMING, e))?;
        if let Some(i) = SIGNATURE_KEYS.iter().position(|k| *k == key) {
            held[i] = true;
        }
    }
    Ok(held)
}

/// Checks that an edit accepts `stored`, the serialized dict that the
/// repository holds.
///
/// The dict must be an `a{sv}` in normal form. For each key of
/// [`SIGNATURE_KEYS`] that `touched` flags, the first entry under the key must
/// hold an `aay`. A key is touched if the incoming dict holds it, or if the
/// edit appends a signature under it. These are the two steps that extend the
/// stored list.
///
/// The check builds no value. It applies the stored-dict refusals of
/// [`merge_detached`] and of the signature append. An edit that passes the
/// check does not fail on the stored dict at the write. If a check fails, the
/// function returns [`Error::InvalidFormat`].
pub(crate) fn check_stored(stored: &[u8], touched: [bool; SIGNATURE_KEYS.len()]) -> Result<()> {
    let mut checked = [false; SIGNATURE_KEYS.len()];
    for entry in entries_in_place(stored, STORED)? {
        let (key, value) = entry.map_err(|e| not_a_dict(STORED, e))?;
        if let Some(i) = SIGNATURE_KEYS.iter().position(|k| *k == key)
            && touched[i]
            && !std::mem::replace(&mut checked[i], true)
            && value.signature() != SIGNATURE_ARRAY
        {
            return Err(not_aay(key, STORED));
        }
    }
    Ok(())
}

/// Returns the `{sv}` entries of the serialized dict `bytes`, read in place.
///
/// The function checks the whole dict before it reads the entries. `subject`
/// names the dict in an error message.
fn entries_in_place<'a>(
    bytes: &'a [u8],
    subject: &str,
) -> Result<ArrayIter<'a, (&'a str, VariantBytes<'a>)>> {
    let ty = Type::parse("a{sv}").map_err(ostrya_core::Error::from)?;
    ostrya_core::validate(&ty, bytes).map_err(|e| not_a_dict(subject, e))?;
    ArrayIter::decode(bytes).map_err(|e| not_a_dict(subject, e))
}

/// Returns the error for a dict that is not an `a{sv}` in normal form.
fn not_a_dict(subject: &str, e: impl std::fmt::Display) -> Error {
    Error::InvalidFormat(format!("{subject} is not a dict `a{{sv}}`: {e}"))
}

/// Moves the `{sv}` entries out of an `a{sv}` dict, each as its key and its
/// variant.
///
/// `subject` names the dict in an error message.
fn dict_entries(dict: Value, subject: &str) -> Result<Vec<(String, Value)>> {
    let Value::Array(entries) = dict else {
        return Err(Error::InvalidFormat(format!("{subject} is not a dict")));
    };
    entries
        .into_iter()
        .map(|entry| {
            if let Value::Tuple(fields) = entry
                && let Ok([Value::Str(key), value @ Value::Variant(_)]) =
                    <[Value; 2]>::try_from(fields)
            {
                return Ok((key, value));
            }
            Err(Error::InvalidFormat(format!(
                "{subject} holds an entry that is not `{{sv}}`"
            )))
        })
        .collect()
}

/// Returns the error for a signature value that is not an `aay`.
///
/// `subject` names the dict that holds the value.
fn not_aay(key: &str, subject: &str) -> Error {
    Error::InvalidFormat(format!(
        "{subject} holds '{key}' as a value that is not `aay`"
    ))
}

/// Returns the error for a value under `key` that is not of the type `ty`.
///
/// `subject` names the dict that holds the value.
fn not_of_type(key: &str, ty: &str, subject: &str) -> Error {
    Error::InvalidFormat(format!(
        "{subject} holds '{key}' as a value that is not `{ty}`"
    ))
}

/// Moves the elements out of the value under a key of [`X509_KEYS`], a
/// variant of the type `ty`: an array of arrays of byte strings for `aaay`,
/// and an array of byte strings for `aay`.
fn x509_list(value: Value, key: &str, ty: &str, subject: &str) -> Result<Vec<Value>> {
    if let Value::Variant(inner) = value
        && let (vty, Value::Array(elements)) = *inner
        && vty.signature() == ty
    {
        let blobs = |v: &Value| matches!(v, Value::Bytes(_));
        let fits = elements.iter().all(|element| match element {
            Value::Array(certificates) if ty == "aaay" => certificates.iter().all(blobs),
            other => ty == "aay" && blobs(other),
        });
        if fits {
            return Ok(elements);
        }
    }
    Err(not_of_type(key, ty, subject))
}

/// Appends to `list` each element of `incoming` that is not equal to an
/// element of `list`, in the incoming order, and refuses a list over the
/// limit of `key`.
///
/// The call stops at the first element over the limit, so it compares each
/// element with at most the limit of elements.
fn x509_union(list: &mut Vec<Value>, incoming: Vec<Value>, key: &str) -> Result<()> {
    let limit = x509_limit(key);
    if list.len() > limit {
        return Err(over_x509_limit(key, MERGED));
    }
    for element in incoming {
        if !list.contains(&element) {
            if list.len() == limit {
                return Err(over_x509_limit(key, MERGED));
            }
            list.push(element);
        }
    }
    Ok(())
}

/// Returns the list of a key of [`X509_KEYS`] as the variant of the type
/// `ty` that a dict entry holds.
fn x509_value(list: Vec<Value>, ty: &str) -> Result<Value> {
    let ty = Type::parse(ty).map_err(ostrya_core::Error::from)?;
    Ok(Value::variant(ty, Value::Array(list)))
}

/// Returns the blobs of one signature list, for the merge to extend in place.
///
/// The list is a variant that holds an `aay`.
fn signature_list<'a>(
    value: &'a mut Value,
    key: &str,
    subject: &str,
) -> Result<&'a mut Vec<Value>> {
    if let Value::Variant(inner) = value
        && inner.0.signature() == SIGNATURE_ARRAY
        && let Value::Array(blobs) = &mut inner.1
        && blobs.iter().all(|blob| matches!(blob, Value::Bytes(_)))
    {
        return Ok(blobs);
    }
    Err(not_aay(key, subject))
}

/// Moves the blobs out of one signature list, a variant that holds an `aay`.
fn signature_blobs(value: Value, key: &str, subject: &str) -> Result<Vec<Vec<u8>>> {
    if let Value::Variant(inner) = value
        && let (ty, Value::Array(blobs)) = *inner
        && ty.signature() == SIGNATURE_ARRAY
    {
        return blobs
            .into_iter()
            .map(|blob| match blob {
                Value::Bytes(bytes) => Ok(bytes),
                _ => Err(not_aay(key, subject)),
            })
            .collect();
    }
    Err(not_aay(key, subject))
}

/// Appends to `list` each blob of `incoming` that is not byte-equal to a blob
/// of `list`.
///
/// The function appends the blobs in the incoming order. If two incoming
/// blobs are byte-equal, it appends the first one only. A duplicate that
/// `list` already holds stays.
fn union(list: &mut Vec<Value>, incoming: Vec<Vec<u8>>) {
    let fresh: Vec<bool> = {
        let mut seen: HashSet<&[u8]> = list
            .iter()
            .filter_map(|blob| match blob {
                Value::Bytes(bytes) => Some(bytes.as_slice()),
                _ => None,
            })
            .collect();
        incoming.iter().map(|blob| seen.insert(blob)).collect()
    };
    list.extend(
        incoming
            .into_iter()
            .zip(fresh)
            .filter_map(|(blob, fresh)| fresh.then_some(Value::Bytes(blob))),
    );
}

/// Returns a signature list as the variant that a dict entry holds.
fn signature_value(list: Vec<Value>) -> Result<Value> {
    let ty = Type::parse(SIGNATURE_ARRAY).map_err(ostrya_core::Error::from)?;
    Ok(Value::variant(ty, Value::Array(list)))
}

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

    /// A signature list of `blobs`.
    fn sigs(blobs: &[&[u8]]) -> Value {
        signature_value(
            blobs
                .iter()
                .map(|blob| Value::Bytes(blob.to_vec()))
                .collect(),
        )
        .unwrap()
    }

    /// A `u` value, which stands for any key that is not a signature list.
    fn number(n: u32) -> Value {
        Value::variant(Type::parse("u").unwrap(), Value::U32(n))
    }

    /// An `a{sv}` dict of `entries`, in order.
    fn dict(entries: Vec<(&str, Value)>) -> Value {
        Value::Array(
            entries
                .into_iter()
                .map(|(key, value)| Value::Tuple(vec![Value::Str(key.to_owned()), value]))
                .collect(),
        )
    }

    /// The keys of a dict, in order.
    fn keys(dict: &Value) -> Vec<String> {
        dict_entries(dict.clone(), "the dict")
            .unwrap()
            .into_iter()
            .map(|(key, _)| key)
            .collect()
    }

    /// The blobs under `key`.
    fn blobs(dict: &Value, key: &str) -> Vec<Vec<u8>> {
        crate::sign::signatures_for(dict, key).unwrap()
    }

    const ED: &str = "ostree.sign.ed25519";

    /// A stored signature A and an incoming signature B give [A, B].
    #[test]
    fn a_stored_and_an_incoming_signature_give_both() {
        let merged = merge_detached(
            Some(dict(vec![(ED, sigs(&[b"A"]))])),
            dict(vec![(ED, sigs(&[b"B"]))]),
            &[],
        )
        .unwrap();
        assert_eq!(blobs(&merged, ED), [b"A".to_vec(), b"B".to_vec()]);
    }

    /// The union holds one copy of a signature that is byte-equal to a stored
    /// one or to another incoming one.
    #[test]
    fn a_byte_equal_signature_is_added_once() {
        let merged = merge_detached(
            Some(dict(vec![(ED, sigs(&[b"A"]))])),
            dict(vec![(ED, sigs(&[b"A", b"B"]))]),
            &[],
        )
        .unwrap();
        assert_eq!(blobs(&merged, ED), [b"A".to_vec(), b"B".to_vec()]);

        let merged = merge_detached(
            Some(dict(vec![(ED, sigs(&[b"A"]))])),
            dict(vec![(ED, sigs(&[b"B", b"B"]))]),
            &[],
        )
        .unwrap();
        assert_eq!(blobs(&merged, ED), [b"A".to_vec(), b"B".to_vec()]);

        // A duplicate that the stored list holds stays.
        let merged = merge_detached(
            Some(dict(vec![(ED, sigs(&[b"A", b"A"]))])),
            dict(vec![(ED, sigs(&[b"A"]))]),
            &[],
        )
        .unwrap();
        assert_eq!(blobs(&merged, ED), [b"A".to_vec(), b"A".to_vec()]);
    }

    /// Every signature key takes the union, also a key that this build has no
    /// engine for.
    #[test]
    fn every_signature_key_takes_the_union() {
        for key in SIGNATURE_KEYS {
            let merged = merge_detached(
                Some(dict(vec![(key, sigs(&[b"A"]))])),
                dict(vec![(key, sigs(&[b"B"]))]),
                &[],
            )
            .unwrap();
            assert_eq!(blobs(&merged, key), [b"A".to_vec(), b"B".to_vec()], "{key}");
        }
    }

    /// A list of chains, each chain a list of certificates.
    fn chains(list: &[&[&[u8]]]) -> Value {
        x509_value(
            list.iter()
                .map(|chain| Value::Array(chain.iter().map(|c| Value::Bytes(c.to_vec())).collect()))
                .collect(),
            "aaay",
        )
        .unwrap()
    }

    const CHAINS: &str = crate::sign::X509_CHAINS_KEY;
    const CRLS: &str = crate::sign::X509_CRLS_KEY;

    /// The chains and the CRLs take the union of the stored and the incoming
    /// lists, by the append rule.
    #[test]
    fn the_chains_and_the_crls_take_the_union() {
        let stored = dict(vec![
            (CHAINS, chains(&[&[b"leaf", b"ca"]])),
            (CRLS, sigs(&[b"C1"])),
        ]);
        let incoming = dict(vec![
            (CRLS, sigs(&[b"C2", b"C1", b"C2"])),
            (CHAINS, chains(&[&[b"leaf"], &[b"leaf", b"ca"], &[b"leaf"]])),
        ]);
        let merged = merge_detached(Some(stored), incoming.clone(), &[]).unwrap();
        assert_eq!(keys(&merged), [CHAINS, CRLS]);
        assert_eq!(
            merged.dict_get(CHAINS),
            Some(&chains(&[&[b"leaf", b"ca"], &[b"leaf"]]))
        );
        assert_eq!(blobs(&merged, CRLS), [b"C1".to_vec(), b"C2".to_vec()]);
        // With no stored dict, the incoming duplicates go.
        let merged = merge_detached(None, incoming.clone(), &[]).unwrap();
        assert_eq!(
            merged.dict_get(CHAINS),
            Some(&chains(&[&[b"leaf"], &[b"leaf", b"ca"]]))
        );
        assert_eq!(blobs(&merged, CRLS), [b"C2".to_vec(), b"C1".to_vec()]);
        check_incoming(&bytes(&incoming)).unwrap();
    }

    /// A chain or a CRL value of another type is refused in each dict, and a
    /// union over the limit is refused.
    #[test]
    fn a_chain_value_of_another_type_or_over_the_limit_is_refused() {
        let wrong = dict(vec![(CHAINS, sigs(&[b"A"]))]);
        let good = dict(vec![(CHAINS, chains(&[&[b"A"]]))]);
        let err = merge_detached(None, wrong.clone(), &[]).unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the incoming detached metadata holds 'ostrya.x509.chains' as a \
             value that is not `aaay`"
        );
        let err = merge_detached(Some(wrong.clone()), good.clone(), &[]).unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the stored detached metadata holds 'ostrya.x509.chains' as a \
             value that is not `aaay`"
        );
        let err = check_incoming(&bytes(&wrong)).unwrap_err();
        assert!(err.to_string().contains("is not `aaay`"), "{err}");
        let err = check_stored_x509(&bytes(&wrong), &bytes(&good)).unwrap_err();
        assert!(
            err.to_string().contains("the stored detached metadata"),
            "{err}"
        );
        check_stored_x509(&bytes(&wrong), &bytes(&dict(vec![("x", number(1))]))).unwrap();
        let crls = dict(vec![(CRLS, chains(&[&[b"A"]]))]);
        assert!(check_incoming(&bytes(&crls)).is_err());

        let names: Vec<Vec<u8>> = (0..17u8).map(|i| vec![i]).collect();
        let stored = dict(vec![(
            CRLS,
            sigs(&names[..16].iter().map(Vec::as_slice).collect::<Vec<_>>()),
        )]);
        let incoming = dict(vec![(CRLS, sigs(&[&names[16]]))]);
        let err = merge_detached(Some(stored.clone()), incoming, &[]).unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the merged detached metadata holds more than 16 different \
             elements under 'ostrya.x509.crls'"
        );
        let incoming = dict(vec![(CRLS, sigs(&[&names[3]]))]);
        merge_detached(Some(stored.clone()), incoming.clone(), &[]).unwrap();
        check_stored_x509(&bytes(&stored), &bytes(&incoming)).unwrap();

        // The check of an incoming dict counts the different elements.
        let all: Vec<&[u8]> = names.iter().map(Vec::as_slice).collect();
        let seventeen = dict(vec![(CRLS, sigs(&all))]);
        let err = check_incoming(&bytes(&seventeen)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the incoming detached metadata holds more than 16 different \
             elements under 'ostrya.x509.crls'"
        );
        let mut repeated = all[..16].to_vec();
        repeated.push(all[0]);
        check_incoming(&bytes(&dict(vec![(CRLS, sigs(&repeated))]))).unwrap();
        let many: Vec<Vec<&[u8]>> = all.iter().map(|c| vec![*c]).collect();
        let many: Vec<&[&[u8]]> = many.iter().map(Vec::as_slice).collect();
        let err = check_incoming(&bytes(&dict(vec![(CHAINS, chains(&many))]))).unwrap_err();
        assert!(err.to_string().contains("'ostrya.x509.chains'"), "{err}");
        // The check of the stored dict counts the union with the incoming dict.
        let err = check_stored_x509(
            &bytes(&stored),
            &bytes(&dict(vec![(CRLS, sigs(&[&names[16]]))])),
        )
        .unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the merged detached metadata holds more than 16 different \
             elements under 'ostrya.x509.crls'"
        );
    }

    /// The check of the union counts the stored, the incoming, and the server
    /// elements, each element that is equal to one before it one time, and
    /// each stored duplicate as the append counts it. It checks the type of
    /// a stored value that a server element adds to.
    #[test]
    fn the_union_check_counts_the_server_elements() {
        let chain = |i: u8| vec![vec![i], b"ca".to_vec()];
        let server = |chains: Vec<Vec<Vec<u8>>>, crls: Vec<Vec<u8>>| {
            vec![crate::sign::X509Attachments::new(chains, crls).unwrap()]
        };
        let stored_chains: Vec<Vec<Vec<u8>>> = (0..15).map(chain).collect();
        let stored_chains: Vec<Vec<&[u8]>> = stored_chains
            .iter()
            .map(|c| c.iter().map(Vec::as_slice).collect())
            .collect();
        let stored_chains: Vec<&[&[u8]]> = stored_chains.iter().map(Vec::as_slice).collect();
        let stored = bytes(&dict(vec![(CHAINS, chains(&stored_chains))]));
        let incoming = bytes(&dict(vec![(CHAINS, chains(&[&[&[15], b"ca"]]))]));
        // 15 stored, 1 incoming, and a server chain equal to a stored one.
        check_x509_union(
            Some(&stored),
            Some(&incoming),
            &server(vec![chain(3)], Vec::new()),
        )
        .unwrap();
        let err = check_x509_union(
            Some(&stored),
            Some(&incoming),
            &server(vec![chain(16)], Vec::new()),
        )
        .unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the merged detached metadata holds more than 16 different \
             elements under 'ostrya.x509.chains'"
        );
        // The server elements alone count, with no dict.
        let names: Vec<Vec<u8>> = (0..17u8).map(|i| vec![i]).collect();
        let two = [
            server(Vec::new(), names[..9].to_vec()),
            server(Vec::new(), names[8..].to_vec()),
        ]
        .concat();
        let err = check_x509_union(None, None, &two).unwrap_err();
        assert!(err.to_string().contains("'ostrya.x509.crls'"), "{err}");
        check_x509_union(None, None, &two[..1]).unwrap();
        // A stored duplicate counts, as the append counts it.
        let mut repeated: Vec<&[u8]> = names[..15].iter().map(Vec::as_slice).collect();
        repeated.push(&names[0]);
        let stored = bytes(&dict(vec![(CRLS, sigs(&repeated))]));
        let err = check_x509_union(
            Some(&stored),
            None,
            &server(Vec::new(), vec![names[16].clone()]),
        )
        .unwrap_err();
        assert!(err.to_string().contains("'ostrya.x509.crls'"), "{err}");
        // A stored value of another type is refused when a server CRL adds to
        // it, and stays when nothing adds to it.
        let wrong = bytes(&dict(vec![(CRLS, chains(&[&[b"A"]]))]));
        let err = check_x509_union(Some(&wrong), None, &server(Vec::new(), vec![b"C".to_vec()]))
            .unwrap_err();
        assert!(
            err.to_string().contains("the stored detached metadata"),
            "{err}"
        );
        check_x509_union(Some(&wrong), None, &server(vec![chain(1)], Vec::new())).unwrap();
    }

    /// Another key takes the incoming value at the stored position. A key that
    /// only the stored dict holds stays. A key that only the incoming dict
    /// holds comes after the stored keys, in the incoming order.
    #[test]
    fn other_keys_take_the_incoming_value() {
        let stored = dict(vec![
            ("x", number(1)),
            (ED, sigs(&[b"A"])),
            ("kept", number(7)),
        ]);
        let incoming = dict(vec![
            ("new.b", number(3)),
            ("x", number(2)),
            ("ostree.gpgsigs", sigs(&[b"G", b"G"])),
            ("new.a", number(4)),
        ]);
        let merged = merge_detached(Some(stored), incoming, &[]).unwrap();
        assert_eq!(
            keys(&merged),
            ["x", ED, "kept", "new.b", "ostree.gpgsigs", "new.a"]
        );
        assert_eq!(merged.dict_get("x"), Some(&number(2)));
        assert_eq!(merged.dict_get("kept"), Some(&number(7)));
        assert_eq!(blobs(&merged, ED), [b"A".to_vec()]);
        assert_eq!(blobs(&merged, "ostree.gpgsigs"), [b"G".to_vec()]);
    }

    /// With no stored dict, the merge gives the incoming dict.
    #[test]
    fn no_stored_dict_gives_the_incoming_dict() {
        let incoming = dict(vec![(ED, sigs(&[b"A"])), ("x", number(1))]);
        let merged = merge_detached(None, incoming.clone(), &[]).unwrap();
        assert_eq!(merged, incoming);
    }

    /// The merged dict serializes as an `a{sv}` and reads back the same.
    #[test]
    fn the_merged_dict_serializes() {
        let merged = merge_detached(
            Some(dict(vec![(ED, sigs(&[b"A"]))])),
            dict(vec![(ED, sigs(&[b"B"])), ("x", number(1))]),
            &[],
        )
        .unwrap();
        let bytes = crate::summary::serialize_signature_dict(&merged).unwrap();
        let back = crate::summary::parse_signature_dict(&bytes)
            .unwrap()
            .unwrap();
        assert_eq!(back, merged);
    }

    /// Under a key of `keep` that the stored dict holds, the stored value
    /// stays. The merge adds a key of `keep` that the stored dict does not
    /// hold. Each other key takes the incoming value.
    #[test]
    fn a_kept_key_keeps_the_stored_value() {
        let stored = dict(vec![("u", number(1)), ("o", number(2))]);
        let incoming = dict(vec![("u", number(3)), ("o", number(4)), ("n", number(5))]);
        let keep = ["u".to_owned(), "n".to_owned()];
        let merged = merge_detached(Some(stored), incoming, &keep).unwrap();
        assert_eq!(keys(&merged), ["u", "o", "n"]);
        assert_eq!(merged.dict_get("u"), Some(&number(1)));
        assert_eq!(merged.dict_get("o"), Some(&number(4)));
        assert_eq!(merged.dict_get("n"), Some(&number(5)));
    }

    /// The serialized `a{sv}` of `dict`.
    fn bytes(dict: &Value) -> Vec<u8> {
        crate::summary::serialize_signature_dict(dict).unwrap()
    }

    /// A blob of `len` bytes, as a variant.
    fn blob(len: usize, fill: u8) -> Value {
        Value::variant(Type::parse("ay").unwrap(), Value::Bytes(vec![fill; len]))
    }

    /// The dict that [`replace_entries`] writes is the serialization of the
    /// same dict. The test covers three cases: no incoming dict, each incoming
    /// key replaced, and the kept incoming entries first. Each case runs for
    /// dicts whose framing offsets take 1, 2, and 4 bytes. The count of
    /// entries read from the framing offsets is exact for each dict.
    #[test]
    fn replaced_entries_give_the_serialized_dict() {
        for len in [0, 1, 7, 100, 200, 300, 70_000] {
            let host_entries = vec![("a", blob(len, 1)), ("z", number(9))];
            let host: Vec<Vec<u8>> = host_entries
                .iter()
                .map(|(key, value)| bytes(&dict(vec![(key, value.clone())])))
                .collect();

            let out = replace_entries(None, &host).unwrap();
            assert_eq!(out, bytes(&dict(host_entries.clone())), "len {len}");

            let incoming = bytes(&dict(vec![("z", number(1)), ("a", blob(len / 2, 2))]));
            let out = replace_entries(Some(&incoming), &host).unwrap();
            assert_eq!(out, bytes(&dict(host_entries.clone())), "len {len}");

            let incoming = bytes(&dict(vec![
                ("x", blob(len, 3)),
                ("a", number(2)),
                ("y", number(3)),
            ]));
            let out = replace_entries(Some(&incoming), &host).unwrap();
            let expected = dict(vec![
                ("x", blob(len, 3)),
                ("y", number(3)),
                ("a", blob(len, 1)),
                ("z", number(9)),
            ]);
            assert_eq!(out, bytes(&expected), "len {len}");
            assert_eq!(entry_count(&incoming), 3, "len {len}");
            assert_eq!(entry_count(&out), 4, "len {len}");
        }
        assert_eq!(entry_count(&bytes(&dict(Vec::new()))), 0);
        // No incoming dict and no host entry give the empty dict.
        assert_eq!(
            replace_entries(None, &[]).unwrap(),
            bytes(&dict(Vec::new()))
        );
        // The function refuses an input that is not an `a{sv}`.
        assert!(matches!(
            replace_entries(Some(b"\x01"), &[]),
            Err(Error::InvalidFormat(_))
        ));
    }

    /// The merge refuses each malformed input with a message that names the
    /// fault.
    #[test]
    fn malformed_inputs_are_refused() {
        let refused = |stored: Option<Value>, incoming: Value, part: &str| {
            let err = merge_detached(stored, incoming, &[]).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m) if m.contains(part)),
                "{err}"
            );
        };
        // A signature value that is not `aay`, on either side.
        refused(None, dict(vec![(ED, number(1))]), "not `aay`");
        refused(
            Some(dict(vec![(ED, number(1))])),
            dict(vec![(ED, sigs(&[b"A"]))]),
            "the stored detached metadata holds",
        );
        let as_strings = Value::variant(
            Type::parse("as").unwrap(),
            Value::Array(vec![Value::Str("A".into())]),
        );
        refused(None, dict(vec![(ED, as_strings)]), "not `aay`");
        // Not a dict, and an entry that is not `{sv}`.
        refused(None, Value::U32(1), "is not a dict");
        refused(
            None,
            Value::Array(vec![Value::Tuple(vec![
                Value::Str("x".into()),
                Value::U32(1),
            ])]),
            "not `{sv}`",
        );
        // A key that the incoming dict holds twice.
        refused(
            None,
            dict(vec![("x", number(1)), ("x", number(2))]),
            "more than once",
        );
    }
}