Skip to main content

hide_identity/
lib.rs

1//! Device enrollment, revocation and recovery for one identity.
2//!
3//! An identity is not a key. It is an ordered, hash-linked log of events, each
4//! signed by a key that the log itself already authorised. Replaying the log
5//! from its root yields the set of devices trusted *now*, and — because every
6//! entry is bound to its predecessor — anyone can check that the history they
7//! were shown is the history everyone else was shown.
8//!
9//! # The rule that makes revocation mean something
10//!
11//! Authority is evaluated **at the point in the log where the entry appears**,
12//! never against the final state. A device revoked at entry *n* cannot sign
13//! entry *n+1*, so it cannot re-enrol itself, revoke the device that removed
14//! it, or rewrite anything after its removal. It also means entries it signed
15//! *before* revocation stay valid: revocation is not retroactive, because
16//! pretending otherwise would invalidate every message the device ever sent.
17//!
18//! # What this does not do
19//!
20//! Nothing here proves the log belongs to a particular person; that is what a
21//! transparency log is for, and it lives in `hide-transparency`. Two divergent
22//! copies of a log are both internally valid — detecting that split needs a
23//! witness, not a signature. And a compromised device is trusted until someone
24//! notices and revokes it; there is no automatic detection.
25
26use hide_sign::{SIGNATURE_LENGTH, SigningIdentity, VERIFYING_KEY_LENGTH, VerifyingIdentity};
27use sha2::{Digest, Sha256};
28use std::collections::BTreeMap;
29use thiserror::Error;
30
31mod bindings;
32pub use bindings::{
33    EPOCH_BINDING_CONTEXT, EPOCH_BINDING_LENGTH, EpochBinding, RECOVERY_BINDING_CONTEXT,
34    RECOVERY_BINDING_LENGTH, RecoveryBinding,
35};
36
37/// Domain separation for the signature over an entry. A signature made here can
38/// never be replayed as a file signature or a challenge response.
39const ENTRY_CONTEXT: &[u8] = b"HIDE/0.6 identity entry";
40
41/// A log longer than this is refused before anything is allocated for it.
42const MAX_ENTRIES: usize = 100_000;
43
44/// Smallest plausible CBOR encoding of one entry: an array header plus seven
45/// minimal items. Only used to bound a pre-reservation, so an underestimate
46/// is safe.
47const MIN_ENTRY_BYTES: usize = 8;
48
49/// Items in one encoded entry: sequence, tag, payload, label, signer, link,
50/// signature.
51const ENTRY_FIELDS: u64 = 7;
52
53/// Versions 0.6 to 0.8 wrote each entry as an array header claiming six items
54/// followed by seven. Rust read it back symmetrically, so nothing noticed, but
55/// any standard CBOR decoder misparses it. Such logs are still accepted for
56/// reading because their signatures and links never covered the framing; they
57/// are never written.
58const LEGACY_ENTRY_HEADER: u64 = 6;
59
60/// Which entry framing a log uses. Tracked per log so the canonical
61/// re-encoding check can reproduce the input exactly, and so a log that mixes
62/// both framings (which no writer ever produced) is refused.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64enum Framing {
65    Current,
66    Legacy,
67}
68
69impl Framing {
70    fn header(self) -> u64 {
71        match self {
72            Self::Current => ENTRY_FIELDS,
73            Self::Legacy => LEGACY_ENTRY_HEADER,
74        }
75    }
76}
77/// Device labels are shown to humans; an unbounded one is a denial-of-service.
78const MAX_LABEL_BYTES: usize = 256;
79
80/// Position in the log. The root is zero.
81pub type Sequence = u64;
82
83/// A device's stable name: the hash of its verifying key, so it cannot be
84/// chosen and cannot collide with another device's.
85pub type DeviceId = [u8; 32];
86
87pub fn device_id(key: &VerifyingIdentity) -> DeviceId {
88    let mut hasher = Sha256::new();
89    hasher.update(b"HIDE/0.6 device id");
90    hasher.update(key.to_bytes());
91    hasher.finalize().into()
92}
93
94#[derive(Debug, Error, PartialEq, Eq)]
95pub enum IdentityError {
96    #[error("the log is empty")]
97    Empty,
98    #[error("entry {0} is not signed by a device this log trusts at that point")]
99    Unauthorised(Sequence),
100    #[error("entry {0} has an invalid signature")]
101    BadSignature(Sequence),
102    #[error("entry {expected} was expected but the log contains {found}")]
103    OutOfOrder { expected: Sequence, found: Sequence },
104    #[error("entry {0} does not link to its predecessor")]
105    BrokenLink(Sequence),
106    #[error("the first entry must create the identity, not {0}")]
107    BadRoot(&'static str),
108    #[error("device is already enrolled at entry {0}")]
109    AlreadyEnrolled(Sequence),
110    #[error("entry {0} revokes a device that is not enrolled")]
111    NotEnrolled(Sequence),
112    #[error("entry {0} would revoke the last remaining device")]
113    WouldOrphan(Sequence),
114    #[error("the log is malformed")]
115    Malformed,
116    #[error("the log claims {0} entries, which exceeds the limit")]
117    TooManyEntries(usize),
118    #[error("a device label may not exceed {MAX_LABEL_BYTES} bytes")]
119    LabelTooLong,
120    #[error("signing failed: {0}")]
121    Sign(String),
122    #[error("the log's root is not the identity that was pinned")]
123    WrongIdentity,
124    #[error("the binding does not verify")]
125    BadBinding,
126    #[error("the binding names a history or chain that is not the one supplied")]
127    StaleBinding,
128    #[error("more than one recovery binding verifies for this identity")]
129    ConflictingBindings,
130}
131
132/// What an entry does.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub enum Event {
135    /// The first entry: establishes the identity and its founding device.
136    Create { device: Vec<u8>, label: String },
137    /// Adds a device, signed by one already trusted.
138    Enrol { device: Vec<u8>, label: String },
139    /// Removes a device. Takes effect for every later entry.
140    Revoke { device: DeviceId },
141    /// Replaces the whole device set, signed by the recovery key. This is how a
142    /// user who lost every device gets back in.
143    Recover { device: Vec<u8>, label: String },
144}
145
146impl Event {
147    fn tag(&self) -> u8 {
148        match self {
149            Self::Create { .. } => 1,
150            Self::Enrol { .. } => 2,
151            Self::Revoke { .. } => 3,
152            Self::Recover { .. } => 4,
153        }
154    }
155
156    fn label(&self) -> Option<&str> {
157        match self {
158            Self::Create { label, .. }
159            | Self::Enrol { label, .. }
160            | Self::Recover { label, .. } => Some(label),
161            Self::Revoke { .. } => None,
162        }
163    }
164}
165
166/// One signed, linked record.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct Entry {
169    pub sequence: Sequence,
170    pub event: Event,
171    /// Which device signed this entry.
172    pub signer: DeviceId,
173    /// Binds this entry to the entire history before it.
174    pub link: [u8; 32],
175    pub signature: Vec<u8>,
176}
177
178impl Entry {
179    /// The exact bytes this entry's signature covers, laid out as in
180    /// `spec/hide-1.md` §10. Public so a second implementation can be checked
181    /// against this one instead of against prose.
182    pub fn signed_bytes(&self, previous: &[u8; 32]) -> Vec<u8> {
183        signed_bytes(previous, self.sequence, &self.event, &self.signer)
184    }
185}
186
187/// The bytes that are signed and linked. Every field is length-prefixed, so no
188/// combination of a long label and a short key can be re-parsed as another.
189fn signed_bytes(
190    previous: &[u8; 32],
191    sequence: Sequence,
192    event: &Event,
193    signer: &DeviceId,
194) -> Vec<u8> {
195    let mut out = Vec::new();
196    out.extend_from_slice(previous);
197    out.extend_from_slice(&sequence.to_be_bytes());
198    out.push(event.tag());
199    out.extend_from_slice(signer);
200
201    let mut field = |bytes: &[u8]| {
202        out.extend_from_slice(&(bytes.len() as u64).to_be_bytes());
203        out.extend_from_slice(bytes);
204    };
205    match event {
206        Event::Create { device, label }
207        | Event::Enrol { device, label }
208        | Event::Recover { device, label } => {
209            field(device);
210            field(label.as_bytes());
211        }
212        Event::Revoke { device } => field(device),
213    }
214    out
215}
216
217fn link_for(signed: &[u8], signature: &[u8]) -> [u8; 32] {
218    let mut hasher = Sha256::new();
219    hasher.update(b"HIDE/0.6 identity link");
220    hasher.update((signed.len() as u64).to_be_bytes());
221    hasher.update(signed);
222    hasher.update((signature.len() as u64).to_be_bytes());
223    hasher.update(signature);
224    hasher.finalize().into()
225}
226
227/// A device trusted at some point in the log.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct Device {
230    pub id: DeviceId,
231    pub key: VerifyingIdentity,
232    pub label: String,
233    pub enrolled_at: Sequence,
234}
235
236/// The device set produced by replaying a log.
237#[derive(Debug, Clone, Default, PartialEq, Eq)]
238pub struct Membership {
239    devices: BTreeMap<DeviceId, Device>,
240    revoked: BTreeMap<DeviceId, Sequence>,
241}
242
243impl Membership {
244    pub fn contains(&self, id: &DeviceId) -> bool {
245        self.devices.contains_key(id)
246    }
247
248    pub fn get(&self, id: &DeviceId) -> Option<&Device> {
249        self.devices.get(id)
250    }
251
252    /// Every currently trusted device, in a stable order.
253    pub fn devices(&self) -> impl Iterator<Item = &Device> {
254        self.devices.values()
255    }
256
257    pub fn len(&self) -> usize {
258        self.devices.len()
259    }
260
261    pub fn is_empty(&self) -> bool {
262        self.devices.is_empty()
263    }
264
265    /// When a device was revoked, if it was. Kept so a verifier can tell
266    /// "never existed" from "existed and was removed" — the second is what a
267    /// user needs to see after losing a phone.
268    pub fn revoked_at(&self, id: &DeviceId) -> Option<Sequence> {
269        self.revoked.get(id).copied()
270    }
271}
272
273/// The identity itself: an append-only log plus the membership it implies.
274pub struct IdentityLog {
275    entries: Vec<Entry>,
276    /// The key permitted to sign `Recover`. Held offline by the user.
277    recovery: VerifyingIdentity,
278}
279
280impl IdentityLog {
281    /// Starts an identity. The founding device signs its own creation, which is
282    /// the one place a signature is not checked against prior membership.
283    pub fn create(
284        founder: &SigningIdentity,
285        label: &str,
286        recovery: &VerifyingIdentity,
287    ) -> Result<Self, IdentityError> {
288        check_label(label)?;
289        let key = founder.verifying_key();
290        let event = Event::Create {
291            device: key.to_bytes().to_vec(),
292            label: label.to_owned(),
293        };
294        let signer = device_id(&key);
295        let signed = signed_bytes(&[0u8; 32], 0, &event, &signer);
296        let signature = founder.sign(ENTRY_CONTEXT, &signed).to_vec();
297
298        Ok(Self {
299            entries: vec![Entry {
300                sequence: 0,
301                link: link_for(&signed, &signature),
302                event,
303                signer,
304                signature,
305            }],
306            recovery: recovery.clone(),
307        })
308    }
309
310    fn append(
311        &mut self,
312        author: &SigningIdentity,
313        event: Event,
314    ) -> Result<Sequence, IdentityError> {
315        if self.entries.len() >= MAX_ENTRIES {
316            return Err(IdentityError::TooManyEntries(self.entries.len()));
317        }
318        if let Some(label) = event.label() {
319            check_label(label)?;
320        }
321
322        let sequence = self.entries.len() as Sequence;
323        let previous = self.entries.last().map_or([0u8; 32], |entry| entry.link);
324        let signer = device_id(&author.verifying_key());
325        let signed = signed_bytes(&previous, sequence, &event, &signer);
326        let signature = author.sign(ENTRY_CONTEXT, &signed).to_vec();
327
328        let candidate = Entry {
329            sequence,
330            link: link_for(&signed, &signature),
331            event,
332            signer,
333            signature,
334        };
335
336        // Validate exactly as a stranger would, so an invalid entry can never
337        // be created locally and only discovered by a remote verifier.
338        let mut membership = self.membership();
339        apply(&mut membership, &candidate, &self.recovery, previous)?;
340
341        self.entries.push(candidate);
342        Ok(sequence)
343    }
344
345    /// Adds a device. The author must be trusted right now.
346    pub fn enrol(
347        &mut self,
348        author: &SigningIdentity,
349        device: &VerifyingIdentity,
350        label: &str,
351    ) -> Result<Sequence, IdentityError> {
352        self.append(
353            author,
354            Event::Enrol {
355                device: device.to_bytes().to_vec(),
356                label: label.to_owned(),
357            },
358        )
359    }
360
361    /// Removes a device. A device may revoke itself — that is what "log out this
362    /// phone" does — but may not revoke the last one.
363    pub fn revoke(
364        &mut self,
365        author: &SigningIdentity,
366        device: DeviceId,
367    ) -> Result<Sequence, IdentityError> {
368        self.append(author, Event::Revoke { device })
369    }
370
371    /// Replaces every device with one new device. Only the recovery key may
372    /// sign this, which is why that key is kept offline.
373    pub fn recover(
374        &mut self,
375        recovery_key: &SigningIdentity,
376        device: &VerifyingIdentity,
377        label: &str,
378    ) -> Result<Sequence, IdentityError> {
379        self.append(
380            recovery_key,
381            Event::Recover {
382                device: device.to_bytes().to_vec(),
383                label: label.to_owned(),
384            },
385        )
386    }
387
388    /// Rebuilds a log from entries received elsewhere. Verified first, so an
389    /// invalid history can never become an appendable one.
390    pub fn from_entries(
391        entries: Vec<Entry>,
392        recovery: VerifyingIdentity,
393    ) -> Result<Self, IdentityError> {
394        replay(&entries, &recovery)?;
395        Ok(Self { entries, recovery })
396    }
397
398    pub fn entries(&self) -> &[Entry] {
399        &self.entries
400    }
401
402    /// The head link, which identifies this exact history in one 32-byte value.
403    pub fn head(&self) -> [u8; 32] {
404        self.entries.last().map_or([0u8; 32], |entry| entry.link)
405    }
406
407    /// The root link: entry 0's link. It never changes as the log grows, so
408    /// it is the identity's stable 32-byte name, the value a relying party
409    /// pins (spec §16.1).
410    pub fn root(&self) -> [u8; 32] {
411        self.entries.first().map_or([0u8; 32], |entry| entry.link)
412    }
413
414    /// The recovery key this log was constructed with.
415    pub fn recovery_key(&self) -> &VerifyingIdentity {
416        &self.recovery
417    }
418
419    /// The devices trusted now.
420    pub fn membership(&self) -> Membership {
421        // The log was validated on the way in, so replay cannot fail here.
422        replay(&self.entries, &self.recovery).unwrap_or_default()
423    }
424
425    /// Replays a log received from elsewhere, checking every signature, link
426    /// and authority decision. This is the function a verifier actually runs.
427    pub fn verify(
428        entries: &[Entry],
429        recovery: &VerifyingIdentity,
430    ) -> Result<Membership, IdentityError> {
431        replay(entries, recovery)
432    }
433}
434
435fn check_label(label: &str) -> Result<(), IdentityError> {
436    if label.len() > MAX_LABEL_BYTES {
437        return Err(IdentityError::LabelTooLong);
438    }
439    Ok(())
440}
441
442/// Applies one entry to a membership, enforcing authority *as of that entry*.
443fn apply(
444    membership: &mut Membership,
445    entry: &Entry,
446    recovery: &VerifyingIdentity,
447    previous: [u8; 32],
448) -> Result<(), IdentityError> {
449    if let Some(label) = entry.event.label()
450        && label.len() > MAX_LABEL_BYTES
451    {
452        return Err(IdentityError::LabelTooLong);
453    }
454
455    let signed = signed_bytes(&previous, entry.sequence, &entry.event, &entry.signer);
456    if link_for(&signed, &entry.signature) != entry.link {
457        return Err(IdentityError::BrokenLink(entry.sequence));
458    }
459    let signature: [u8; SIGNATURE_LENGTH] = entry
460        .signature
461        .as_slice()
462        .try_into()
463        .map_err(|_| IdentityError::BadSignature(entry.sequence))?;
464
465    // Which key is allowed to have signed this, given the state so far.
466    let author: VerifyingIdentity = match &entry.event {
467        Event::Create { device, .. } => {
468            if entry.sequence != 0 {
469                return Err(IdentityError::BadRoot("a later Create"));
470            }
471            let key = parse_key(device, entry.sequence)?;
472            if device_id(&key) != entry.signer {
473                return Err(IdentityError::Unauthorised(entry.sequence));
474            }
475            key
476        }
477        Event::Recover { .. } => {
478            // Only the recovery key, and it is not a device.
479            if device_id(recovery) != entry.signer {
480                return Err(IdentityError::Unauthorised(entry.sequence));
481            }
482            recovery.clone()
483        }
484        Event::Enrol { .. } | Event::Revoke { .. } => membership
485            .devices
486            .get(&entry.signer)
487            .map(|device| device.key.clone())
488            .ok_or(IdentityError::Unauthorised(entry.sequence))?,
489    };
490
491    author
492        .verify(ENTRY_CONTEXT, &signed, &signature)
493        .map_err(|_| IdentityError::BadSignature(entry.sequence))?;
494
495    match &entry.event {
496        Event::Create { device, label } => {
497            let key = parse_key(device, entry.sequence)?;
498            let id = device_id(&key);
499            membership.devices.insert(
500                id,
501                Device {
502                    id,
503                    key,
504                    label: label.clone(),
505                    enrolled_at: entry.sequence,
506                },
507            );
508        }
509        Event::Enrol { device, label } => {
510            let key = parse_key(device, entry.sequence)?;
511            let id = device_id(&key);
512            if membership.devices.contains_key(&id) {
513                return Err(IdentityError::AlreadyEnrolled(entry.sequence));
514            }
515            membership.revoked.remove(&id);
516            membership.devices.insert(
517                id,
518                Device {
519                    id,
520                    key,
521                    label: label.clone(),
522                    enrolled_at: entry.sequence,
523                },
524            );
525        }
526        Event::Revoke { device } => {
527            if !membership.devices.contains_key(device) {
528                return Err(IdentityError::NotEnrolled(entry.sequence));
529            }
530            // An identity with no devices could only be rescued by recovery;
531            // refuse to walk into that by accident.
532            if membership.devices.len() == 1 {
533                return Err(IdentityError::WouldOrphan(entry.sequence));
534            }
535            membership.devices.remove(device);
536            membership.revoked.insert(*device, entry.sequence);
537        }
538        Event::Recover { device, label } => {
539            let key = parse_key(device, entry.sequence)?;
540            let id = device_id(&key);
541            for old in membership.devices.keys() {
542                membership.revoked.insert(*old, entry.sequence);
543            }
544            membership.devices.clear();
545            membership.revoked.remove(&id);
546            membership.devices.insert(
547                id,
548                Device {
549                    id,
550                    key,
551                    label: label.clone(),
552                    enrolled_at: entry.sequence,
553                },
554            );
555        }
556    }
557    Ok(())
558}
559
560fn parse_key(bytes: &[u8], sequence: Sequence) -> Result<VerifyingIdentity, IdentityError> {
561    if bytes.len() != VERIFYING_KEY_LENGTH {
562        return Err(IdentityError::Malformed);
563    }
564    VerifyingIdentity::from_bytes(bytes).map_err(|_| IdentityError::BadSignature(sequence))
565}
566
567fn replay(entries: &[Entry], recovery: &VerifyingIdentity) -> Result<Membership, IdentityError> {
568    if entries.is_empty() {
569        return Err(IdentityError::Empty);
570    }
571    if entries.len() > MAX_ENTRIES {
572        return Err(IdentityError::TooManyEntries(entries.len()));
573    }
574    if !matches!(entries[0].event, Event::Create { .. }) {
575        return Err(IdentityError::BadRoot("another event"));
576    }
577
578    let mut membership = Membership::default();
579    let mut previous = [0u8; 32];
580    for (index, entry) in entries.iter().enumerate() {
581        let expected = index as Sequence;
582        if entry.sequence != expected {
583            return Err(IdentityError::OutOfOrder {
584                expected,
585                found: entry.sequence,
586            });
587        }
588        apply(&mut membership, entry, recovery, previous)?;
589        previous = entry.link;
590    }
591    Ok(membership)
592}
593
594/// Encodes a log for transport. Only public material is ever encodable.
595pub fn encode(entries: &[Entry]) -> Result<Vec<u8>, IdentityError> {
596    encode_framed(entries, Framing::Current)
597}
598
599fn encode_framed(entries: &[Entry], framing: Framing) -> Result<Vec<u8>, IdentityError> {
600    let mut out = Vec::new();
601    let mut encoder = minicbor::Encoder::new(&mut out);
602    encoder
603        .array(entries.len() as u64)
604        .map_err(|_| IdentityError::Malformed)?;
605    for entry in entries {
606        encoder
607            .array(framing.header())
608            .and_then(|e| e.u64(entry.sequence))
609            .and_then(|e| e.u8(entry.event.tag()))
610            .map_err(|_| IdentityError::Malformed)?;
611        match &entry.event {
612            Event::Create { device, label }
613            | Event::Enrol { device, label }
614            | Event::Recover { device, label } => {
615                encoder
616                    .bytes(device)
617                    .and_then(|e| e.str(label))
618                    .map_err(|_| IdentityError::Malformed)?;
619            }
620            Event::Revoke { device } => {
621                encoder
622                    .bytes(device)
623                    .and_then(|e| e.str(""))
624                    .map_err(|_| IdentityError::Malformed)?;
625            }
626        }
627        encoder
628            .bytes(&entry.signer)
629            .and_then(|e| e.bytes(&entry.link))
630            .and_then(|e| e.bytes(&entry.signature))
631            .map_err(|_| IdentityError::Malformed)?;
632    }
633    Ok(out)
634}
635
636/// Decodes a log. Accepts the current framing and, for reading only, the
637/// legacy 0.6–0.8 framing; see [`LEGACY_ENTRY_HEADER`].
638pub fn decode(bytes: &[u8]) -> Result<Vec<Entry>, IdentityError> {
639    let mut decoder = minicbor::Decoder::new(bytes);
640    let count = decoder
641        .array()
642        .map_err(|_| IdentityError::Malformed)?
643        .ok_or(IdentityError::Malformed)?;
644    if count > MAX_ENTRIES as u64 {
645        return Err(IdentityError::TooManyEntries(count as usize));
646    }
647
648    // The count comes from untrusted bytes, so reserving from it lets a few
649    // bytes of input claim megabytes. Cap it by what the input could hold.
650    let mut entries = Vec::with_capacity((count as usize).min(bytes.len() / MIN_ENTRY_BYTES));
651    let mut framing: Option<Framing> = None;
652    for _ in 0..count {
653        let header = decoder
654            .array()
655            .map_err(|_| IdentityError::Malformed)?
656            .ok_or(IdentityError::Malformed)?;
657        // Both framings carry the same seven items; only the header differs.
658        let this = match header {
659            ENTRY_FIELDS => Framing::Current,
660            LEGACY_ENTRY_HEADER => Framing::Legacy,
661            _ => return Err(IdentityError::Malformed),
662        };
663        if framing.is_some_and(|seen| seen != this) {
664            return Err(IdentityError::Malformed);
665        }
666        framing = Some(this);
667        let sequence = decoder.u64().map_err(|_| IdentityError::Malformed)?;
668        let tag = decoder.u8().map_err(|_| IdentityError::Malformed)?;
669        let payload = decoder
670            .bytes()
671            .map_err(|_| IdentityError::Malformed)?
672            .to_vec();
673        // Length first: copying and then rejecting lets a malformed log make
674        // us allocate an oversized label we were always going to refuse.
675        let label = decoder.str().map_err(|_| IdentityError::Malformed)?;
676        if label.len() > MAX_LABEL_BYTES {
677            return Err(IdentityError::LabelTooLong);
678        }
679        let label = label.to_owned();
680
681        let event = match tag {
682            1 => Event::Create {
683                device: payload,
684                label,
685            },
686            2 => Event::Enrol {
687                device: payload,
688                label,
689            },
690            3 => Event::Revoke {
691                device: payload
692                    .as_slice()
693                    .try_into()
694                    .map_err(|_| IdentityError::Malformed)?,
695            },
696            4 => Event::Recover {
697                device: payload,
698                label,
699            },
700            _ => return Err(IdentityError::Malformed),
701        };
702
703        let signer: DeviceId = decoder
704            .bytes()
705            .map_err(|_| IdentityError::Malformed)?
706            .try_into()
707            .map_err(|_| IdentityError::Malformed)?;
708        let link: [u8; 32] = decoder
709            .bytes()
710            .map_err(|_| IdentityError::Malformed)?
711            .try_into()
712            .map_err(|_| IdentityError::Malformed)?;
713        let signature = decoder
714            .bytes()
715            .map_err(|_| IdentityError::Malformed)?
716            .to_vec();
717        if signature.len() != SIGNATURE_LENGTH {
718            return Err(IdentityError::Malformed);
719        }
720
721        entries.push(Entry {
722            sequence,
723            event,
724            signer,
725            link,
726            signature,
727        });
728    }
729    if decoder.position() != bytes.len() {
730        return Err(IdentityError::Malformed);
731    }
732    // One history, one encoding. A transparency log hashes these exact bytes,
733    // so two encodings of the same entries would be two different leaves. This
734    // also rejects a non-empty label smuggled into a Revoke, which the typed
735    // event has no field for and would otherwise silently drop. A legacy log
736    // is re-encoded in its own framing, so it gets the same guarantee.
737    if encode_framed(&entries, framing.unwrap_or(Framing::Current))? != bytes {
738        return Err(IdentityError::Malformed);
739    }
740    Ok(entries)
741}
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746
747    /// A handful of bytes may claim a hundred thousand entries. Decoding must
748    /// fail on the truncated body rather than reserving megabytes first.
749    #[test]
750    fn a_huge_declared_count_reserves_nothing() {
751        let mut bytes = Vec::new();
752        minicbor::Encoder::new(&mut bytes).array(99_999).unwrap();
753        assert!(matches!(decode(&bytes), Err(IdentityError::Malformed)));
754
755        let mut huge = Vec::new();
756        minicbor::Encoder::new(&mut huge).array(u64::MAX).unwrap();
757        assert!(matches!(
758            decode(&huge),
759            Err(IdentityError::TooManyEntries(_))
760        ));
761    }
762
763    /// The label is rejected on its declared length, before it is copied.
764    #[test]
765    fn an_oversized_label_is_refused() {
766        let label = "x".repeat(MAX_LABEL_BYTES + 1);
767        let mut bytes = Vec::new();
768        let mut encoder = minicbor::Encoder::new(&mut bytes);
769        encoder
770            .array(1)
771            .and_then(|e| e.array(6))
772            .and_then(|e| e.u64(0))
773            .and_then(|e| e.u8(1))
774            .and_then(|e| e.bytes(&[0u8; 32]))
775            .and_then(|e| e.str(&label))
776            .unwrap();
777        assert!(matches!(decode(&bytes), Err(IdentityError::LabelTooLong)));
778    }
779
780    fn signer(seed: u8) -> SigningIdentity {
781        SigningIdentity::from_bytes(&[seed; 32]).expect("32 bytes is a seed")
782    }
783
784    /// create, enrol, revoke: three entries covering both payload shapes.
785    fn sample_log() -> IdentityLog {
786        let founder = signer(1);
787        let phone = signer(2);
788        let recovery = signer(3);
789        let mut log =
790            IdentityLog::create(&founder, "desktop", &recovery.verifying_key()).expect("create");
791        log.enrol(&founder, &phone.verifying_key(), "phone")
792            .expect("enrol");
793        log.revoke(&founder, device_id(&phone.verifying_key()))
794            .expect("revoke");
795        log
796    }
797
798    /// Offsets of each entry's array header, found by walking the encoding.
799    fn entry_header_offsets(bytes: &[u8]) -> Vec<usize> {
800        let mut decoder = minicbor::Decoder::new(bytes);
801        let count = decoder.array().unwrap().unwrap();
802        let mut offsets = Vec::new();
803        for _ in 0..count {
804            offsets.push(decoder.position());
805            decoder.array().unwrap();
806            for _ in 0..ENTRY_FIELDS {
807                decoder.skip().unwrap();
808            }
809        }
810        offsets
811    }
812
813    /// A generic CBOR reader must see seven items per entry. Pinned as bytes:
814    /// a round trip cannot catch a symmetric framing change, which is exactly
815    /// how the six-item header survived three releases.
816    #[test]
817    fn every_entry_is_written_as_an_array_of_seven() {
818        let bytes = encode(sample_log().entries()).unwrap();
819        // array(3), array(7), sequence 0, tag 1, bytes(1984)
820        assert_eq!(&bytes[..7], &[0x83, 0x87, 0x00, 0x01, 0x59, 0x07, 0xc0]);
821        for offset in entry_header_offsets(&bytes) {
822            assert_eq!(bytes[offset], 0x87, "entry at {offset} is not array(7)");
823        }
824    }
825
826    #[test]
827    fn the_current_framing_round_trips_and_verifies() {
828        let log = sample_log();
829        let bytes = encode(log.entries()).unwrap();
830        let decoded = decode(&bytes).unwrap();
831        assert_eq!(decoded, log.entries());
832        let membership = IdentityLog::verify(&decoded, &signer(3).verifying_key()).expect("verify");
833        assert_eq!(membership.len(), 1);
834    }
835
836    /// Legacy logs stay readable, and the canonical check still holds for
837    /// them: they re-encode to exactly the bytes received.
838    #[test]
839    fn a_legacy_log_decodes_to_the_same_entries() {
840        let log = sample_log();
841        let legacy = encode_framed(log.entries(), Framing::Legacy).unwrap();
842        assert_eq!(&legacy[..2], &[0x83, 0x86]);
843        let decoded = decode(&legacy).unwrap();
844        assert_eq!(decoded, log.entries());
845        IdentityLog::verify(&decoded, &signer(3).verifying_key()).expect("verify");
846        // Framing is not signed, so upgrading a legacy log keeps its head.
847        let upgraded = encode(&decoded).unwrap();
848        assert_eq!(
849            IdentityLog::from_entries(decode(&upgraded).unwrap(), signer(3).verifying_key())
850                .unwrap()
851                .head(),
852            log.head()
853        );
854    }
855
856    /// No writer ever produced a log with both framings, so one that has them
857    /// is a constructed input, and accepting it would give one history two
858    /// encodings.
859    #[test]
860    fn a_log_that_mixes_framings_is_refused() {
861        let entries = sample_log().entries().to_vec();
862        for framing in [Framing::Current, Framing::Legacy] {
863            let mut bytes = encode_framed(&entries, framing).unwrap();
864            let offsets = entry_header_offsets(&bytes);
865            for &offset in &offsets {
866                let original = bytes[offset];
867                bytes[offset] = if original == 0x87 { 0x86 } else { 0x87 };
868                assert_eq!(
869                    decode(&bytes),
870                    Err(IdentityError::Malformed),
871                    "mixed framing accepted at {offset}"
872                );
873                bytes[offset] = original;
874            }
875        }
876    }
877
878    /// A header of six followed by only six items is not the legacy form; the
879    /// legacy form always had seven.
880    #[test]
881    fn six_items_under_a_six_header_are_refused() {
882        let entries = sample_log().entries()[..1].to_vec();
883        let legacy = encode_framed(&entries, Framing::Legacy).unwrap();
884        // Drop the signature: the last item, 3373 bytes plus a 3-byte header.
885        let truncated = &legacy[..legacy.len() - (SIGNATURE_LENGTH + 3)];
886        assert_eq!(decode(truncated), Err(IdentityError::Malformed));
887        // And any other header count is refused outright.
888        for header in [0x85u8, 0x88] {
889            let mut other = legacy.clone();
890            other[1] = header;
891            assert_eq!(decode(&other), Err(IdentityError::Malformed));
892        }
893    }
894}