hide-identity 0.9.0

Device enrollment, revocation and recovery for a HIDE identity. Experimental, unaudited.
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
//! Device enrollment, revocation and recovery for one identity.
//!
//! An identity is not a key. It is an ordered, hash-linked log of events, each
//! signed by a key that the log itself already authorised. Replaying the log
//! from its root yields the set of devices trusted *now*, and — because every
//! entry is bound to its predecessor — anyone can check that the history they
//! were shown is the history everyone else was shown.
//!
//! # The rule that makes revocation mean something
//!
//! Authority is evaluated **at the point in the log where the entry appears**,
//! never against the final state. A device revoked at entry *n* cannot sign
//! entry *n+1*, so it cannot re-enrol itself, revoke the device that removed
//! it, or rewrite anything after its removal. It also means entries it signed
//! *before* revocation stay valid: revocation is not retroactive, because
//! pretending otherwise would invalidate every message the device ever sent.
//!
//! # What this does not do
//!
//! Nothing here proves the log belongs to a particular person; that is what a
//! transparency log is for, and it lives in `hide-transparency`. Two divergent
//! copies of a log are both internally valid — detecting that split needs a
//! witness, not a signature. And a compromised device is trusted until someone
//! notices and revokes it; there is no automatic detection.

use hide_sign::{SIGNATURE_LENGTH, SigningIdentity, VERIFYING_KEY_LENGTH, VerifyingIdentity};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use thiserror::Error;

/// Domain separation for the signature over an entry. A signature made here can
/// never be replayed as a file signature or a challenge response.
const ENTRY_CONTEXT: &[u8] = b"HIDE/0.6 identity entry";

/// A log longer than this is refused before anything is allocated for it.
const MAX_ENTRIES: usize = 100_000;

/// Smallest plausible CBOR encoding of one entry: an array header plus seven
/// minimal items. Only used to bound a pre-reservation, so an underestimate
/// is safe.
const MIN_ENTRY_BYTES: usize = 8;

/// Items in one encoded entry: sequence, tag, payload, label, signer, link,
/// signature.
const ENTRY_FIELDS: u64 = 7;

/// Versions 0.6 to 0.8 wrote each entry as an array header claiming six items
/// followed by seven. Rust read it back symmetrically, so nothing noticed, but
/// any standard CBOR decoder misparses it. Such logs are still accepted for
/// reading because their signatures and links never covered the framing; they
/// are never written.
const LEGACY_ENTRY_HEADER: u64 = 6;

/// Which entry framing a log uses. Tracked per log so the canonical
/// re-encoding check can reproduce the input exactly, and so a log that mixes
/// both framings (which no writer ever produced) is refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Framing {
    Current,
    Legacy,
}

impl Framing {
    fn header(self) -> u64 {
        match self {
            Self::Current => ENTRY_FIELDS,
            Self::Legacy => LEGACY_ENTRY_HEADER,
        }
    }
}
/// Device labels are shown to humans; an unbounded one is a denial-of-service.
const MAX_LABEL_BYTES: usize = 256;

/// Position in the log. The root is zero.
pub type Sequence = u64;

/// A device's stable name: the hash of its verifying key, so it cannot be
/// chosen and cannot collide with another device's.
pub type DeviceId = [u8; 32];

pub fn device_id(key: &VerifyingIdentity) -> DeviceId {
    let mut hasher = Sha256::new();
    hasher.update(b"HIDE/0.6 device id");
    hasher.update(key.to_bytes());
    hasher.finalize().into()
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum IdentityError {
    #[error("the log is empty")]
    Empty,
    #[error("entry {0} is not signed by a device this log trusts at that point")]
    Unauthorised(Sequence),
    #[error("entry {0} has an invalid signature")]
    BadSignature(Sequence),
    #[error("entry {expected} was expected but the log contains {found}")]
    OutOfOrder { expected: Sequence, found: Sequence },
    #[error("entry {0} does not link to its predecessor")]
    BrokenLink(Sequence),
    #[error("the first entry must create the identity, not {0}")]
    BadRoot(&'static str),
    #[error("device is already enrolled at entry {0}")]
    AlreadyEnrolled(Sequence),
    #[error("entry {0} revokes a device that is not enrolled")]
    NotEnrolled(Sequence),
    #[error("entry {0} would revoke the last remaining device")]
    WouldOrphan(Sequence),
    #[error("the log is malformed")]
    Malformed,
    #[error("the log claims {0} entries, which exceeds the limit")]
    TooManyEntries(usize),
    #[error("a device label may not exceed {MAX_LABEL_BYTES} bytes")]
    LabelTooLong,
    #[error("signing failed: {0}")]
    Sign(String),
}

/// What an entry does.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
    /// The first entry: establishes the identity and its founding device.
    Create { device: Vec<u8>, label: String },
    /// Adds a device, signed by one already trusted.
    Enrol { device: Vec<u8>, label: String },
    /// Removes a device. Takes effect for every later entry.
    Revoke { device: DeviceId },
    /// Replaces the whole device set, signed by the recovery key. This is how a
    /// user who lost every device gets back in.
    Recover { device: Vec<u8>, label: String },
}

impl Event {
    fn tag(&self) -> u8 {
        match self {
            Self::Create { .. } => 1,
            Self::Enrol { .. } => 2,
            Self::Revoke { .. } => 3,
            Self::Recover { .. } => 4,
        }
    }

    fn label(&self) -> Option<&str> {
        match self {
            Self::Create { label, .. }
            | Self::Enrol { label, .. }
            | Self::Recover { label, .. } => Some(label),
            Self::Revoke { .. } => None,
        }
    }
}

/// One signed, linked record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    pub sequence: Sequence,
    pub event: Event,
    /// Which device signed this entry.
    pub signer: DeviceId,
    /// Binds this entry to the entire history before it.
    pub link: [u8; 32],
    pub signature: Vec<u8>,
}

impl Entry {
    /// The exact bytes this entry's signature covers, laid out as in
    /// `spec/hide-1.md` §10. Public so a second implementation can be checked
    /// against this one instead of against prose.
    pub fn signed_bytes(&self, previous: &[u8; 32]) -> Vec<u8> {
        signed_bytes(previous, self.sequence, &self.event, &self.signer)
    }
}

/// The bytes that are signed and linked. Every field is length-prefixed, so no
/// combination of a long label and a short key can be re-parsed as another.
fn signed_bytes(
    previous: &[u8; 32],
    sequence: Sequence,
    event: &Event,
    signer: &DeviceId,
) -> Vec<u8> {
    let mut out = Vec::new();
    out.extend_from_slice(previous);
    out.extend_from_slice(&sequence.to_be_bytes());
    out.push(event.tag());
    out.extend_from_slice(signer);

    let mut field = |bytes: &[u8]| {
        out.extend_from_slice(&(bytes.len() as u64).to_be_bytes());
        out.extend_from_slice(bytes);
    };
    match event {
        Event::Create { device, label }
        | Event::Enrol { device, label }
        | Event::Recover { device, label } => {
            field(device);
            field(label.as_bytes());
        }
        Event::Revoke { device } => field(device),
    }
    out
}

fn link_for(signed: &[u8], signature: &[u8]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(b"HIDE/0.6 identity link");
    hasher.update((signed.len() as u64).to_be_bytes());
    hasher.update(signed);
    hasher.update((signature.len() as u64).to_be_bytes());
    hasher.update(signature);
    hasher.finalize().into()
}

/// A device trusted at some point in the log.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Device {
    pub id: DeviceId,
    pub key: VerifyingIdentity,
    pub label: String,
    pub enrolled_at: Sequence,
}

/// The device set produced by replaying a log.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Membership {
    devices: BTreeMap<DeviceId, Device>,
    revoked: BTreeMap<DeviceId, Sequence>,
}

impl Membership {
    pub fn contains(&self, id: &DeviceId) -> bool {
        self.devices.contains_key(id)
    }

    pub fn get(&self, id: &DeviceId) -> Option<&Device> {
        self.devices.get(id)
    }

    /// Every currently trusted device, in a stable order.
    pub fn devices(&self) -> impl Iterator<Item = &Device> {
        self.devices.values()
    }

    pub fn len(&self) -> usize {
        self.devices.len()
    }

    pub fn is_empty(&self) -> bool {
        self.devices.is_empty()
    }

    /// When a device was revoked, if it was. Kept so a verifier can tell
    /// "never existed" from "existed and was removed" — the second is what a
    /// user needs to see after losing a phone.
    pub fn revoked_at(&self, id: &DeviceId) -> Option<Sequence> {
        self.revoked.get(id).copied()
    }
}

/// The identity itself: an append-only log plus the membership it implies.
pub struct IdentityLog {
    entries: Vec<Entry>,
    /// The key permitted to sign `Recover`. Held offline by the user.
    recovery: VerifyingIdentity,
}

impl IdentityLog {
    /// Starts an identity. The founding device signs its own creation, which is
    /// the one place a signature is not checked against prior membership.
    pub fn create(
        founder: &SigningIdentity,
        label: &str,
        recovery: &VerifyingIdentity,
    ) -> Result<Self, IdentityError> {
        check_label(label)?;
        let key = founder.verifying_key();
        let event = Event::Create {
            device: key.to_bytes().to_vec(),
            label: label.to_owned(),
        };
        let signer = device_id(&key);
        let signed = signed_bytes(&[0u8; 32], 0, &event, &signer);
        let signature = founder.sign(ENTRY_CONTEXT, &signed).to_vec();

        Ok(Self {
            entries: vec![Entry {
                sequence: 0,
                link: link_for(&signed, &signature),
                event,
                signer,
                signature,
            }],
            recovery: recovery.clone(),
        })
    }

    fn append(
        &mut self,
        author: &SigningIdentity,
        event: Event,
    ) -> Result<Sequence, IdentityError> {
        if self.entries.len() >= MAX_ENTRIES {
            return Err(IdentityError::TooManyEntries(self.entries.len()));
        }
        if let Some(label) = event.label() {
            check_label(label)?;
        }

        let sequence = self.entries.len() as Sequence;
        let previous = self.entries.last().map_or([0u8; 32], |entry| entry.link);
        let signer = device_id(&author.verifying_key());
        let signed = signed_bytes(&previous, sequence, &event, &signer);
        let signature = author.sign(ENTRY_CONTEXT, &signed).to_vec();

        let candidate = Entry {
            sequence,
            link: link_for(&signed, &signature),
            event,
            signer,
            signature,
        };

        // Validate exactly as a stranger would, so an invalid entry can never
        // be created locally and only discovered by a remote verifier.
        let mut membership = self.membership();
        apply(&mut membership, &candidate, &self.recovery, previous)?;

        self.entries.push(candidate);
        Ok(sequence)
    }

    /// Adds a device. The author must be trusted right now.
    pub fn enrol(
        &mut self,
        author: &SigningIdentity,
        device: &VerifyingIdentity,
        label: &str,
    ) -> Result<Sequence, IdentityError> {
        self.append(
            author,
            Event::Enrol {
                device: device.to_bytes().to_vec(),
                label: label.to_owned(),
            },
        )
    }

    /// Removes a device. A device may revoke itself — that is what "log out this
    /// phone" does — but may not revoke the last one.
    pub fn revoke(
        &mut self,
        author: &SigningIdentity,
        device: DeviceId,
    ) -> Result<Sequence, IdentityError> {
        self.append(author, Event::Revoke { device })
    }

    /// Replaces every device with one new device. Only the recovery key may
    /// sign this, which is why that key is kept offline.
    pub fn recover(
        &mut self,
        recovery_key: &SigningIdentity,
        device: &VerifyingIdentity,
        label: &str,
    ) -> Result<Sequence, IdentityError> {
        self.append(
            recovery_key,
            Event::Recover {
                device: device.to_bytes().to_vec(),
                label: label.to_owned(),
            },
        )
    }

    /// Rebuilds a log from entries received elsewhere. Verified first, so an
    /// invalid history can never become an appendable one.
    pub fn from_entries(
        entries: Vec<Entry>,
        recovery: VerifyingIdentity,
    ) -> Result<Self, IdentityError> {
        replay(&entries, &recovery)?;
        Ok(Self { entries, recovery })
    }

    pub fn entries(&self) -> &[Entry] {
        &self.entries
    }

    /// The head link, which identifies this exact history in one 32-byte value.
    pub fn head(&self) -> [u8; 32] {
        self.entries.last().map_or([0u8; 32], |entry| entry.link)
    }

    /// The devices trusted now.
    pub fn membership(&self) -> Membership {
        // The log was validated on the way in, so replay cannot fail here.
        replay(&self.entries, &self.recovery).unwrap_or_default()
    }

    /// Replays a log received from elsewhere, checking every signature, link
    /// and authority decision. This is the function a verifier actually runs.
    pub fn verify(
        entries: &[Entry],
        recovery: &VerifyingIdentity,
    ) -> Result<Membership, IdentityError> {
        replay(entries, recovery)
    }
}

fn check_label(label: &str) -> Result<(), IdentityError> {
    if label.len() > MAX_LABEL_BYTES {
        return Err(IdentityError::LabelTooLong);
    }
    Ok(())
}

/// Applies one entry to a membership, enforcing authority *as of that entry*.
fn apply(
    membership: &mut Membership,
    entry: &Entry,
    recovery: &VerifyingIdentity,
    previous: [u8; 32],
) -> Result<(), IdentityError> {
    if let Some(label) = entry.event.label()
        && label.len() > MAX_LABEL_BYTES
    {
        return Err(IdentityError::LabelTooLong);
    }

    let signed = signed_bytes(&previous, entry.sequence, &entry.event, &entry.signer);
    if link_for(&signed, &entry.signature) != entry.link {
        return Err(IdentityError::BrokenLink(entry.sequence));
    }
    let signature: [u8; SIGNATURE_LENGTH] = entry
        .signature
        .as_slice()
        .try_into()
        .map_err(|_| IdentityError::BadSignature(entry.sequence))?;

    // Which key is allowed to have signed this, given the state so far.
    let author: VerifyingIdentity = match &entry.event {
        Event::Create { device, .. } => {
            if entry.sequence != 0 {
                return Err(IdentityError::BadRoot("a later Create"));
            }
            let key = parse_key(device, entry.sequence)?;
            if device_id(&key) != entry.signer {
                return Err(IdentityError::Unauthorised(entry.sequence));
            }
            key
        }
        Event::Recover { .. } => {
            // Only the recovery key, and it is not a device.
            if device_id(recovery) != entry.signer {
                return Err(IdentityError::Unauthorised(entry.sequence));
            }
            recovery.clone()
        }
        Event::Enrol { .. } | Event::Revoke { .. } => membership
            .devices
            .get(&entry.signer)
            .map(|device| device.key.clone())
            .ok_or(IdentityError::Unauthorised(entry.sequence))?,
    };

    author
        .verify(ENTRY_CONTEXT, &signed, &signature)
        .map_err(|_| IdentityError::BadSignature(entry.sequence))?;

    match &entry.event {
        Event::Create { device, label } => {
            let key = parse_key(device, entry.sequence)?;
            let id = device_id(&key);
            membership.devices.insert(
                id,
                Device {
                    id,
                    key,
                    label: label.clone(),
                    enrolled_at: entry.sequence,
                },
            );
        }
        Event::Enrol { device, label } => {
            let key = parse_key(device, entry.sequence)?;
            let id = device_id(&key);
            if membership.devices.contains_key(&id) {
                return Err(IdentityError::AlreadyEnrolled(entry.sequence));
            }
            membership.revoked.remove(&id);
            membership.devices.insert(
                id,
                Device {
                    id,
                    key,
                    label: label.clone(),
                    enrolled_at: entry.sequence,
                },
            );
        }
        Event::Revoke { device } => {
            if !membership.devices.contains_key(device) {
                return Err(IdentityError::NotEnrolled(entry.sequence));
            }
            // An identity with no devices could only be rescued by recovery;
            // refuse to walk into that by accident.
            if membership.devices.len() == 1 {
                return Err(IdentityError::WouldOrphan(entry.sequence));
            }
            membership.devices.remove(device);
            membership.revoked.insert(*device, entry.sequence);
        }
        Event::Recover { device, label } => {
            let key = parse_key(device, entry.sequence)?;
            let id = device_id(&key);
            for old in membership.devices.keys() {
                membership.revoked.insert(*old, entry.sequence);
            }
            membership.devices.clear();
            membership.revoked.remove(&id);
            membership.devices.insert(
                id,
                Device {
                    id,
                    key,
                    label: label.clone(),
                    enrolled_at: entry.sequence,
                },
            );
        }
    }
    Ok(())
}

fn parse_key(bytes: &[u8], sequence: Sequence) -> Result<VerifyingIdentity, IdentityError> {
    if bytes.len() != VERIFYING_KEY_LENGTH {
        return Err(IdentityError::Malformed);
    }
    VerifyingIdentity::from_bytes(bytes).map_err(|_| IdentityError::BadSignature(sequence))
}

fn replay(entries: &[Entry], recovery: &VerifyingIdentity) -> Result<Membership, IdentityError> {
    if entries.is_empty() {
        return Err(IdentityError::Empty);
    }
    if entries.len() > MAX_ENTRIES {
        return Err(IdentityError::TooManyEntries(entries.len()));
    }
    if !matches!(entries[0].event, Event::Create { .. }) {
        return Err(IdentityError::BadRoot("another event"));
    }

    let mut membership = Membership::default();
    let mut previous = [0u8; 32];
    for (index, entry) in entries.iter().enumerate() {
        let expected = index as Sequence;
        if entry.sequence != expected {
            return Err(IdentityError::OutOfOrder {
                expected,
                found: entry.sequence,
            });
        }
        apply(&mut membership, entry, recovery, previous)?;
        previous = entry.link;
    }
    Ok(membership)
}

/// Encodes a log for transport. Only public material is ever encodable.
pub fn encode(entries: &[Entry]) -> Result<Vec<u8>, IdentityError> {
    encode_framed(entries, Framing::Current)
}

fn encode_framed(entries: &[Entry], framing: Framing) -> Result<Vec<u8>, IdentityError> {
    let mut out = Vec::new();
    let mut encoder = minicbor::Encoder::new(&mut out);
    encoder
        .array(entries.len() as u64)
        .map_err(|_| IdentityError::Malformed)?;
    for entry in entries {
        encoder
            .array(framing.header())
            .and_then(|e| e.u64(entry.sequence))
            .and_then(|e| e.u8(entry.event.tag()))
            .map_err(|_| IdentityError::Malformed)?;
        match &entry.event {
            Event::Create { device, label }
            | Event::Enrol { device, label }
            | Event::Recover { device, label } => {
                encoder
                    .bytes(device)
                    .and_then(|e| e.str(label))
                    .map_err(|_| IdentityError::Malformed)?;
            }
            Event::Revoke { device } => {
                encoder
                    .bytes(device)
                    .and_then(|e| e.str(""))
                    .map_err(|_| IdentityError::Malformed)?;
            }
        }
        encoder
            .bytes(&entry.signer)
            .and_then(|e| e.bytes(&entry.link))
            .and_then(|e| e.bytes(&entry.signature))
            .map_err(|_| IdentityError::Malformed)?;
    }
    Ok(out)
}

/// Decodes a log. Accepts the current framing and, for reading only, the
/// legacy 0.6–0.8 framing; see [`LEGACY_ENTRY_HEADER`].
pub fn decode(bytes: &[u8]) -> Result<Vec<Entry>, IdentityError> {
    let mut decoder = minicbor::Decoder::new(bytes);
    let count = decoder
        .array()
        .map_err(|_| IdentityError::Malformed)?
        .ok_or(IdentityError::Malformed)?;
    if count > MAX_ENTRIES as u64 {
        return Err(IdentityError::TooManyEntries(count as usize));
    }

    // The count comes from untrusted bytes, so reserving from it lets a few
    // bytes of input claim megabytes. Cap it by what the input could hold.
    let mut entries = Vec::with_capacity((count as usize).min(bytes.len() / MIN_ENTRY_BYTES));
    let mut framing: Option<Framing> = None;
    for _ in 0..count {
        let header = decoder
            .array()
            .map_err(|_| IdentityError::Malformed)?
            .ok_or(IdentityError::Malformed)?;
        // Both framings carry the same seven items; only the header differs.
        let this = match header {
            ENTRY_FIELDS => Framing::Current,
            LEGACY_ENTRY_HEADER => Framing::Legacy,
            _ => return Err(IdentityError::Malformed),
        };
        if framing.is_some_and(|seen| seen != this) {
            return Err(IdentityError::Malformed);
        }
        framing = Some(this);
        let sequence = decoder.u64().map_err(|_| IdentityError::Malformed)?;
        let tag = decoder.u8().map_err(|_| IdentityError::Malformed)?;
        let payload = decoder
            .bytes()
            .map_err(|_| IdentityError::Malformed)?
            .to_vec();
        // Length first: copying and then rejecting lets a malformed log make
        // us allocate an oversized label we were always going to refuse.
        let label = decoder.str().map_err(|_| IdentityError::Malformed)?;
        if label.len() > MAX_LABEL_BYTES {
            return Err(IdentityError::LabelTooLong);
        }
        let label = label.to_owned();

        let event = match tag {
            1 => Event::Create {
                device: payload,
                label,
            },
            2 => Event::Enrol {
                device: payload,
                label,
            },
            3 => Event::Revoke {
                device: payload
                    .as_slice()
                    .try_into()
                    .map_err(|_| IdentityError::Malformed)?,
            },
            4 => Event::Recover {
                device: payload,
                label,
            },
            _ => return Err(IdentityError::Malformed),
        };

        let signer: DeviceId = decoder
            .bytes()
            .map_err(|_| IdentityError::Malformed)?
            .try_into()
            .map_err(|_| IdentityError::Malformed)?;
        let link: [u8; 32] = decoder
            .bytes()
            .map_err(|_| IdentityError::Malformed)?
            .try_into()
            .map_err(|_| IdentityError::Malformed)?;
        let signature = decoder
            .bytes()
            .map_err(|_| IdentityError::Malformed)?
            .to_vec();
        if signature.len() != SIGNATURE_LENGTH {
            return Err(IdentityError::Malformed);
        }

        entries.push(Entry {
            sequence,
            event,
            signer,
            link,
            signature,
        });
    }
    if decoder.position() != bytes.len() {
        return Err(IdentityError::Malformed);
    }
    // One history, one encoding. A transparency log hashes these exact bytes,
    // so two encodings of the same entries would be two different leaves. This
    // also rejects a non-empty label smuggled into a Revoke, which the typed
    // event has no field for and would otherwise silently drop. A legacy log
    // is re-encoded in its own framing, so it gets the same guarantee.
    if encode_framed(&entries, framing.unwrap_or(Framing::Current))? != bytes {
        return Err(IdentityError::Malformed);
    }
    Ok(entries)
}

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

    /// A handful of bytes may claim a hundred thousand entries. Decoding must
    /// fail on the truncated body rather than reserving megabytes first.
    #[test]
    fn a_huge_declared_count_reserves_nothing() {
        let mut bytes = Vec::new();
        minicbor::Encoder::new(&mut bytes).array(99_999).unwrap();
        assert!(matches!(decode(&bytes), Err(IdentityError::Malformed)));

        let mut huge = Vec::new();
        minicbor::Encoder::new(&mut huge).array(u64::MAX).unwrap();
        assert!(matches!(
            decode(&huge),
            Err(IdentityError::TooManyEntries(_))
        ));
    }

    /// The label is rejected on its declared length, before it is copied.
    #[test]
    fn an_oversized_label_is_refused() {
        let label = "x".repeat(MAX_LABEL_BYTES + 1);
        let mut bytes = Vec::new();
        let mut encoder = minicbor::Encoder::new(&mut bytes);
        encoder
            .array(1)
            .and_then(|e| e.array(6))
            .and_then(|e| e.u64(0))
            .and_then(|e| e.u8(1))
            .and_then(|e| e.bytes(&[0u8; 32]))
            .and_then(|e| e.str(&label))
            .unwrap();
        assert!(matches!(decode(&bytes), Err(IdentityError::LabelTooLong)));
    }

    fn signer(seed: u8) -> SigningIdentity {
        SigningIdentity::from_bytes(&[seed; 32]).expect("32 bytes is a seed")
    }

    /// create, enrol, revoke: three entries covering both payload shapes.
    fn sample_log() -> IdentityLog {
        let founder = signer(1);
        let phone = signer(2);
        let recovery = signer(3);
        let mut log =
            IdentityLog::create(&founder, "desktop", &recovery.verifying_key()).expect("create");
        log.enrol(&founder, &phone.verifying_key(), "phone")
            .expect("enrol");
        log.revoke(&founder, device_id(&phone.verifying_key()))
            .expect("revoke");
        log
    }

    /// Offsets of each entry's array header, found by walking the encoding.
    fn entry_header_offsets(bytes: &[u8]) -> Vec<usize> {
        let mut decoder = minicbor::Decoder::new(bytes);
        let count = decoder.array().unwrap().unwrap();
        let mut offsets = Vec::new();
        for _ in 0..count {
            offsets.push(decoder.position());
            decoder.array().unwrap();
            for _ in 0..ENTRY_FIELDS {
                decoder.skip().unwrap();
            }
        }
        offsets
    }

    /// A generic CBOR reader must see seven items per entry. Pinned as bytes:
    /// a round trip cannot catch a symmetric framing change, which is exactly
    /// how the six-item header survived three releases.
    #[test]
    fn every_entry_is_written_as_an_array_of_seven() {
        let bytes = encode(sample_log().entries()).unwrap();
        // array(3), array(7), sequence 0, tag 1, bytes(1984)
        assert_eq!(&bytes[..7], &[0x83, 0x87, 0x00, 0x01, 0x59, 0x07, 0xc0]);
        for offset in entry_header_offsets(&bytes) {
            assert_eq!(bytes[offset], 0x87, "entry at {offset} is not array(7)");
        }
    }

    #[test]
    fn the_current_framing_round_trips_and_verifies() {
        let log = sample_log();
        let bytes = encode(log.entries()).unwrap();
        let decoded = decode(&bytes).unwrap();
        assert_eq!(decoded, log.entries());
        let membership = IdentityLog::verify(&decoded, &signer(3).verifying_key()).expect("verify");
        assert_eq!(membership.len(), 1);
    }

    /// Legacy logs stay readable, and the canonical check still holds for
    /// them: they re-encode to exactly the bytes received.
    #[test]
    fn a_legacy_log_decodes_to_the_same_entries() {
        let log = sample_log();
        let legacy = encode_framed(log.entries(), Framing::Legacy).unwrap();
        assert_eq!(&legacy[..2], &[0x83, 0x86]);
        let decoded = decode(&legacy).unwrap();
        assert_eq!(decoded, log.entries());
        IdentityLog::verify(&decoded, &signer(3).verifying_key()).expect("verify");
        // Framing is not signed, so upgrading a legacy log keeps its head.
        let upgraded = encode(&decoded).unwrap();
        assert_eq!(
            IdentityLog::from_entries(decode(&upgraded).unwrap(), signer(3).verifying_key())
                .unwrap()
                .head(),
            log.head()
        );
    }

    /// No writer ever produced a log with both framings, so one that has them
    /// is a constructed input, and accepting it would give one history two
    /// encodings.
    #[test]
    fn a_log_that_mixes_framings_is_refused() {
        let entries = sample_log().entries().to_vec();
        for framing in [Framing::Current, Framing::Legacy] {
            let mut bytes = encode_framed(&entries, framing).unwrap();
            let offsets = entry_header_offsets(&bytes);
            for &offset in &offsets {
                let original = bytes[offset];
                bytes[offset] = if original == 0x87 { 0x86 } else { 0x87 };
                assert_eq!(
                    decode(&bytes),
                    Err(IdentityError::Malformed),
                    "mixed framing accepted at {offset}"
                );
                bytes[offset] = original;
            }
        }
    }

    /// A header of six followed by only six items is not the legacy form; the
    /// legacy form always had seven.
    #[test]
    fn six_items_under_a_six_header_are_refused() {
        let entries = sample_log().entries()[..1].to_vec();
        let legacy = encode_framed(&entries, Framing::Legacy).unwrap();
        // Drop the signature: the last item, 3373 bytes plus a 3-byte header.
        let truncated = &legacy[..legacy.len() - (SIGNATURE_LENGTH + 3)];
        assert_eq!(decode(truncated), Err(IdentityError::Malformed));
        // And any other header count is refused outright.
        for header in [0x85u8, 0x88] {
            let mut other = legacy.clone();
            other[1] = header;
            assert_eq!(decode(&other), Err(IdentityError::Malformed));
        }
    }
}