Skip to main content

decision_cert/
inclusion.rs

1//! `decision-cert-inclusion.v1`: a tenant's transparency log, checked offline
2//! (spec/decision-cert-inclusion.v1.md).
3//!
4//! A log is an RFC 9162 Merkle tree over JCS-encoded leaves ([`Leaf`], [`leaf_hash`]). Its
5//! checkpoints are C2SP signed notes ([`parse_checkpoint`]) signed by the log's Ed25519 key and
6//! cosigned by witnesses (`cosignature/v1`). A bundle carries a leaf, its audit path and a cosigned
7//! checkpoint, and a consumer checks it against its log trust configuration ([`LogTrust`]) with
8//! [`verify_bundle`], in the order of the spec's §10, refusing at the first failure with that
9//! check's error name ([`ErrorName`]). [`verify_consistency`] checks a consistency proof document
10//! between two checkpoints of one log, and [`apply_policy`] applies the configuration's `policy` to
11//! a certificate with or without a bundle.
12//!
13//! A bundle does not replace the certificate's own verification: for a certificate leaf, verify the
14//! bundle's certificate with [`crate::verify_for_tenant`] (or [`crate::verify`]) as well.
15//!
16//! The functions here take parsed JSON. A JSON document's I-JSON rules (no member named twice)
17//! cannot be checked once it is parsed into a [`serde_json::Value`], so read documents from text
18//! with [`parse_ijson`].
19
20use std::collections::{BTreeMap, BTreeSet};
21use std::fmt;
22
23use base64::{
24    engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
25    Engine,
26};
27use ed25519_dalek::{Signature, VerifyingKey};
28use serde_json::{Map, Value};
29use sha2::{Digest, Sha256};
30
31/// The `spec` of a bundle (§8).
32/// The certificate `spec` values a certificate leaf may name (spec decision-cert-inclusion.v1 §3.2,
33/// frozen): v1 to v1.5. A v1.6 certificate has no leaf in inclusion v1.
34const LEAF_SPECS: [&str; 6] = [
35    crate::SPEC,
36    crate::SPEC_V1_1,
37    crate::SPEC_V1_2,
38    crate::SPEC_V1_3,
39    crate::SPEC_V1_4,
40    crate::SPEC_V1_5,
41];
42
43pub const SPEC_BUNDLE: &str = "decision-cert-inclusion.v1";
44/// The `spec` of a consistency proof document (§7.2).
45pub const SPEC_CONSISTENCY: &str = "decision-cert-consistency.v1";
46/// The `spec` of a log trust configuration (§9).
47pub const SPEC_LOG_TRUST: &str = "decision-cert-log-trust.v1";
48/// The five leaf kinds of v1 (§3.2).
49pub const LEAF_KINDS: [&str; 5] = [
50    "certificate",
51    "ledger_entry",
52    "keyset",
53    "attestation",
54    "audit_head",
55];
56/// The C2SP signed-note signature type of an Ed25519 log signature (§5.2).
57pub const SIG_TYPE_ED25519: u8 = 0x01;
58/// The C2SP signed-note signature type of an Ed25519 `cosignature/v1` (§5.3).
59pub const SIG_TYPE_COSIGNATURE_V1: u8 = 0x04;
60/// The latest cosignature timestamp v1 accepts, 9999-12-31T23:59:59Z (§5.3).
61pub const MAX_COSIGNATURE_TIME: u64 = 253_402_300_799;
62/// The most signature lines a checkpoint may carry (§5.1).
63pub const MAX_SIGNATURE_LINES: usize = 100;
64/// The most node hashes an audit or consistency path may carry (§6, §7).
65pub const MAX_PATH: usize = 64;
66/// The largest integer a document may carry, 2^53 − 1 (§0).
67pub const MAX_INT: u64 = (1 << 53) - 1;
68
69/// A 32-byte SHA-256 hash: a leaf hash, a node hash or a root.
70pub type Hash = [u8; 32];
71
72// ---------------------------------------------------------------------------------------------
73// Errors
74// ---------------------------------------------------------------------------------------------
75
76/// The spec's error names (§14), one per check.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
78pub enum ErrorName {
79    TrustForm,
80    TrustCrossTenant,
81    BundleForm,
82    LeafForm,
83    LeafMismatch,
84    TenantMismatch,
85    UnknownLog,
86    CheckpointForm,
87    OriginMismatch,
88    BadProof,
89    LogSignatureMissing,
90    BadLogSignature,
91    BadCosignature,
92    TooFewCosignatures,
93    ConsistencyForm,
94    SizeRegression,
95    SplitView,
96    BadConsistencyProof,
97    InclusionMissing,
98}
99
100impl ErrorName {
101    /// Every error name, in §14's order.
102    pub const ALL: [ErrorName; 19] = [
103        Self::TrustForm,
104        Self::TrustCrossTenant,
105        Self::BundleForm,
106        Self::LeafForm,
107        Self::LeafMismatch,
108        Self::TenantMismatch,
109        Self::UnknownLog,
110        Self::CheckpointForm,
111        Self::OriginMismatch,
112        Self::BadProof,
113        Self::LogSignatureMissing,
114        Self::BadLogSignature,
115        Self::BadCosignature,
116        Self::TooFewCosignatures,
117        Self::ConsistencyForm,
118        Self::SizeRegression,
119        Self::SplitView,
120        Self::BadConsistencyProof,
121        Self::InclusionMissing,
122    ];
123
124    /// The name as §14 writes it, for example `bad_proof`.
125    pub fn as_str(self) -> &'static str {
126        match self {
127            Self::TrustForm => "trust_form",
128            Self::TrustCrossTenant => "trust_cross_tenant",
129            Self::BundleForm => "bundle_form",
130            Self::LeafForm => "leaf_form",
131            Self::LeafMismatch => "leaf_mismatch",
132            Self::TenantMismatch => "tenant_mismatch",
133            Self::UnknownLog => "unknown_log",
134            Self::CheckpointForm => "checkpoint_form",
135            Self::OriginMismatch => "origin_mismatch",
136            Self::BadProof => "bad_proof",
137            Self::LogSignatureMissing => "log_signature_missing",
138            Self::BadLogSignature => "bad_log_signature",
139            Self::BadCosignature => "bad_cosignature",
140            Self::TooFewCosignatures => "too_few_cosignatures",
141            Self::ConsistencyForm => "consistency_form",
142            Self::SizeRegression => "size_regression",
143            Self::SplitView => "split_view",
144            Self::BadConsistencyProof => "bad_consistency_proof",
145            Self::InclusionMissing => "inclusion_missing",
146        }
147    }
148}
149
150impl fmt::Display for ErrorName {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        f.write_str(self.as_str())
153    }
154}
155
156/// A refusal: the failing check's error name (§14) and a message for people.
157#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
158#[error("{name}: {detail}")]
159pub struct InclusionError {
160    pub name: ErrorName,
161    pub detail: String,
162}
163
164impl InclusionError {
165    pub fn new(name: ErrorName, detail: impl Into<String>) -> Self {
166        Self {
167            name,
168            detail: detail.into(),
169        }
170    }
171}
172
173fn fail<T>(name: ErrorName, detail: impl Into<String>) -> Result<T, InclusionError> {
174    Err(InclusionError::new(name, detail))
175}
176
177// ---------------------------------------------------------------------------------------------
178// I-JSON
179// ---------------------------------------------------------------------------------------------
180
181/// Parse JSON text as I-JSON (§0): as [`serde_json::from_str`], and also refusing an object with
182/// two members of one name, which a [`Value`] would silently collapse. Integers that are written
183/// with a fraction or an exponent parse as floats, and the checks here refuse them where an integer
184/// is due.
185pub fn parse_ijson(text: &str) -> Result<Value, String> {
186    serde_json::from_str::<Strict>(text)
187        .map(|s| s.0)
188        .map_err(|e| e.to_string())
189}
190
191struct Strict(Value);
192
193impl<'de> serde::Deserialize<'de> for Strict {
194    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
195        d.deserialize_any(StrictVisitor)
196    }
197}
198
199struct StrictVisitor;
200
201impl<'de> serde::de::Visitor<'de> for StrictVisitor {
202    type Value = Strict;
203
204    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        f.write_str("a JSON value")
206    }
207    fn visit_bool<E>(self, v: bool) -> Result<Strict, E> {
208        Ok(Strict(Value::Bool(v)))
209    }
210    fn visit_i64<E>(self, v: i64) -> Result<Strict, E> {
211        Ok(Strict(Value::from(v)))
212    }
213    fn visit_u64<E>(self, v: u64) -> Result<Strict, E> {
214        Ok(Strict(Value::from(v)))
215    }
216    fn visit_f64<E>(self, v: f64) -> Result<Strict, E> {
217        Ok(Strict(
218            serde_json::Number::from_f64(v).map_or(Value::Null, Value::Number),
219        ))
220    }
221    fn visit_str<E>(self, v: &str) -> Result<Strict, E> {
222        Ok(Strict(Value::String(v.to_string())))
223    }
224    fn visit_string<E>(self, v: String) -> Result<Strict, E> {
225        Ok(Strict(Value::String(v)))
226    }
227    fn visit_unit<E>(self) -> Result<Strict, E> {
228        Ok(Strict(Value::Null))
229    }
230    fn visit_none<E>(self) -> Result<Strict, E> {
231        Ok(Strict(Value::Null))
232    }
233    fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Strict, A::Error> {
234        let mut out = Vec::new();
235        while let Some(Strict(v)) = seq.next_element()? {
236            out.push(v);
237        }
238        Ok(Strict(Value::Array(out)))
239    }
240    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Strict, A::Error> {
241        let mut out = Map::new();
242        while let Some(k) = map.next_key::<String>()? {
243            if out.contains_key(&k) {
244                return Err(serde::de::Error::custom(format!(
245                    "member {k:?} appears twice in one object (not I-JSON)"
246                )));
247            }
248            let Strict(v) = map.next_value()?;
249            out.insert(k, v);
250        }
251        Ok(Strict(Value::Object(out)))
252    }
253}
254
255// ---------------------------------------------------------------------------------------------
256// The tree (§4, §6, §7.1): RFC 9162 §2.1
257// ---------------------------------------------------------------------------------------------
258
259/// RFC 9162 §2.1.1's leaf hash of raw leaf bytes: SHA-256(0x00 || data). [`leaf_hash`] applies it
260/// to a leaf's JCS bytes.
261pub fn hash_leaf_bytes(data: &[u8]) -> Hash {
262    let mut h = Sha256::new();
263    h.update([0x00]);
264    h.update(data);
265    h.finalize().into()
266}
267
268/// An inner node: SHA-256(0x01 || left || right).
269pub fn node_hash(left: &Hash, right: &Hash) -> Hash {
270    let mut h = Sha256::new();
271    h.update([0x01]);
272    h.update(left);
273    h.update(right);
274    h.finalize().into()
275}
276
277/// The largest power of two smaller than `n` (n ≥ 2).
278fn split_point(n: usize) -> usize {
279    let mut k = 1;
280    while k << 1 < n {
281        k <<= 1;
282    }
283    k
284}
285
286/// RFC 9162 §2.1.1's MTH over leaf hashes; None for no leaves (the spec defines no empty tree).
287pub fn root_hash(leaf_hashes: &[Hash]) -> Option<Hash> {
288    match leaf_hashes.len() {
289        0 => None,
290        1 => Some(leaf_hashes[0]),
291        n => {
292            let k = split_point(n);
293            Some(node_hash(
294                &root_hash(&leaf_hashes[..k])?,
295                &root_hash(&leaf_hashes[k..])?,
296            ))
297        }
298    }
299}
300
301/// RFC 9162 §2.1.3.1's audit path for the leaf at `index` in the tree over `leaf_hashes`, from the
302/// leaf's sibling upward; None when `index` is out of range. A log computes these; a verifier only
303/// checks them ([`verify_inclusion_path`]).
304pub fn audit_path(leaf_hashes: &[Hash], index: usize) -> Option<Vec<Hash>> {
305    let n = leaf_hashes.len();
306    if index >= n {
307        return None;
308    }
309    if n == 1 {
310        return Some(Vec::new());
311    }
312    let k = split_point(n);
313    let (mut path, other) = if index < k {
314        (
315            audit_path(&leaf_hashes[..k], index)?,
316            root_hash(&leaf_hashes[k..])?,
317        )
318    } else {
319        (
320            audit_path(&leaf_hashes[k..], index - k)?,
321            root_hash(&leaf_hashes[..k])?,
322        )
323    };
324    path.push(other);
325    Some(path)
326}
327
328/// RFC 9162 §2.1.4.1's consistency path from the tree of the first `older` leaves to the tree over
329/// all of `leaf_hashes`; None unless 1 ≤ `older` ≤ the number of leaves.
330pub fn consistency_path(leaf_hashes: &[Hash], older: usize) -> Option<Vec<Hash>> {
331    fn sub(m: usize, d: &[Hash], whole: bool) -> Option<Vec<Hash>> {
332        let n = d.len();
333        if m == n {
334            return Some(if whole {
335                Vec::new()
336            } else {
337                vec![root_hash(d)?]
338            });
339        }
340        let k = split_point(n);
341        let (mut path, other) = if m <= k {
342            (sub(m, &d[..k], whole)?, root_hash(&d[k..])?)
343        } else {
344            (sub(m - k, &d[k..], false)?, root_hash(&d[..k])?)
345        };
346        path.push(other);
347        Some(path)
348    }
349    if older == 0 || older > leaf_hashes.len() {
350        return None;
351    }
352    sub(older, leaf_hashes, true)
353}
354
355/// RFC 9162 §2.1.3.2 (the spec's §6): does `path` lead from `leaf_hash` at `index` to `root` in a
356/// tree of `size` leaves?
357pub fn verify_inclusion_path(
358    index: u64,
359    size: u64,
360    leaf_hash: &Hash,
361    path: &[Hash],
362    root: &Hash,
363) -> bool {
364    if index >= size {
365        return false;
366    }
367    let (mut fnode, mut snode, mut r) = (index, size - 1, *leaf_hash);
368    for p in path {
369        if snode == 0 {
370            return false;
371        }
372        if fnode & 1 == 1 || fnode == snode {
373            r = node_hash(p, &r);
374            if fnode & 1 == 0 {
375                while fnode & 1 == 0 && fnode != 0 {
376                    fnode >>= 1;
377                    snode >>= 1;
378                }
379            }
380        } else {
381            r = node_hash(&r, p);
382        }
383        fnode >>= 1;
384        snode >>= 1;
385    }
386    snode == 0 && r == *root
387}
388
389/// RFC 9162 §2.1.4.2 (the spec's §7.1): is the tree of `older` leaves with `older_root` a prefix of
390/// the tree of `newer` leaves with `newer_root`, by `path`? For `older` = `newer`, only an empty
391/// path between equal roots; `older` = 0 or `older` > `newer` never.
392pub fn verify_consistency_path(
393    older: u64,
394    newer: u64,
395    older_root: &Hash,
396    newer_root: &Hash,
397    path: &[Hash],
398) -> bool {
399    if older == 0 || older > newer {
400        return false;
401    }
402    if older == newer {
403        return path.is_empty() && older_root == newer_root;
404    }
405    if path.is_empty() {
406        return false;
407    }
408    let mut nodes: Vec<Hash> = Vec::with_capacity(path.len() + 1);
409    if older.is_power_of_two() {
410        nodes.push(*older_root);
411    }
412    nodes.extend_from_slice(path);
413    let (mut fnode, mut snode) = (older - 1, newer - 1);
414    if fnode & 1 == 1 {
415        while fnode & 1 == 1 {
416            fnode >>= 1;
417            snode >>= 1;
418        }
419    }
420    let (mut fr, mut sr) = (nodes[0], nodes[0]);
421    for c in &nodes[1..] {
422        if snode == 0 {
423            return false;
424        }
425        if fnode & 1 == 1 || fnode == snode {
426            fr = node_hash(c, &fr);
427            sr = node_hash(c, &sr);
428            if fnode & 1 == 0 {
429                while fnode & 1 == 0 && fnode != 0 {
430                    fnode >>= 1;
431                    snode >>= 1;
432                }
433            }
434        } else {
435            sr = node_hash(&sr, c);
436        }
437        fnode >>= 1;
438        snode >>= 1;
439    }
440    fr == *older_root && sr == *newer_root && snode == 0
441}
442
443// ---------------------------------------------------------------------------------------------
444// Leaves (§3)
445// ---------------------------------------------------------------------------------------------
446
447/// A leaf (§3) whose form has been checked: one of [`LEAF_KINDS`] with exactly its members, each in
448/// its form.
449#[derive(Clone, Debug, PartialEq)]
450pub struct Leaf(Map<String, Value>);
451
452impl Leaf {
453    /// Check a leaf's form (§3), refusing it as `leaf_form`.
454    pub fn from_json(v: &Value) -> Result<Leaf, InclusionError> {
455        let bad = |m: String| fail(ErrorName::LeafForm, m);
456        let Some(obj) = v.as_object() else {
457            return bad("a leaf is a JSON object".into());
458        };
459        let Some(kind) = obj.get("kind").and_then(Value::as_str) else {
460            return bad("a leaf needs a string kind".into());
461        };
462        type Check = fn(&Value) -> bool;
463        let members: &[(&str, Check)] = match kind {
464            "certificate" => &[
465                ("certificate_id", |v| str_is(v, doc_hash_ok)),
466                ("signer_key_id", |v| str_is(v, crate::key_id_form)),
467                ("spec", |v| str_is(v, |s| LEAF_SPECS.contains(&s))),
468                ("fitted_at", |v| str_is(v, time_ok)),
469                ("tenant", |v| str_is(v, crate::tenant_ok)),
470            ],
471            "ledger_entry" => &[
472                ("ledger_id", |v| {
473                    str_is(v, |s| prefixed_hex(s, "ledger:", 32))
474                }),
475                ("seq", |v| uint(v).is_some()),
476                ("entry", |v| str_is(v, doc_hash_ok)),
477            ],
478            "keyset" => &[
479                ("keyset_id", |v| {
480                    str_is(v, |s| prefixed_hex(s, "keyset:", 32))
481                }),
482                ("seq", |v| uint(v).is_some()),
483                ("keyset", |v| str_is(v, doc_hash_ok)),
484            ],
485            "attestation" => &[
486                ("attestation", |v| str_is(v, doc_hash_ok)),
487                ("certificate_id", |v| str_is(v, doc_hash_ok)),
488            ],
489            "audit_head" => &[
490                ("tenant", |v| str_is(v, crate::tenant_ok)),
491                ("chain", |v| str_is(v, crate::tenant_ok)),
492                ("seq", |v| uint(v).is_some_and(|n| n >= 1)),
493                ("digest", |v| str_is(v, doc_hash_ok)),
494                ("observed_at", |v| str_is(v, time_ok)),
495            ],
496            other => return bad(format!("unknown leaf kind {other:?}")),
497        };
498        // `tenant` is a certificate leaf's member exactly for a v1.5 certificate (§3.2).
499        let v15 = kind == "certificate"
500            && obj.get("spec").and_then(Value::as_str) == Some(crate::SPEC_V1_5);
501        let required = |name: &str| !(kind == "certificate" && name == "tenant") || v15;
502        for k in obj.keys() {
503            if k != "kind" && !members.iter().any(|(m, _)| m == k) {
504                return bad(format!("unknown member {k:?} in a {kind} leaf"));
505            }
506        }
507        for (name, ok) in members {
508            match obj.get(*name) {
509                None if required(name) => {
510                    return bad(format!("a {kind} leaf needs {name:?}"));
511                }
512                None => {}
513                Some(_) if !required(name) => {
514                    return bad(format!(
515                        "a certificate leaf carries tenant only for a {} certificate",
516                        crate::SPEC_V1_5
517                    ));
518                }
519                Some(v) if !ok(v) => {
520                    return bad(format!("{name:?} of a {kind} leaf is out of its form"));
521                }
522                Some(_) => {}
523            }
524        }
525        Ok(Leaf(obj.clone()))
526    }
527
528    /// The leaf's kind, one of [`LEAF_KINDS`].
529    pub fn kind(&self) -> &str {
530        self.0["kind"].as_str().unwrap_or_default()
531    }
532
533    /// A member's string value (None for an absent or non-string member).
534    pub fn get_str(&self, member: &str) -> Option<&str> {
535        self.0.get(member).and_then(Value::as_str)
536    }
537
538    /// The leaf as JSON.
539    pub fn to_json(&self) -> Value {
540        Value::Object(self.0.clone())
541    }
542
543    /// The leaf's canonical bytes, its JCS bytes (§3.1).
544    pub fn canonical(&self) -> Vec<u8> {
545        // every member is a string or an integer at most 2^53 − 1: JCS cannot fail
546        crate::canonical(&self.to_json()).unwrap_or_default()
547    }
548}
549
550/// The leaf hash of a leaf (§4): SHA-256(0x00 || JCS(leaf)).
551pub fn leaf_hash(leaf: &Leaf) -> Hash {
552    hash_leaf_bytes(&leaf.canonical())
553}
554
555fn str_is(v: &Value, f: impl Fn(&str) -> bool) -> bool {
556    v.as_str().is_some_and(f)
557}
558
559/// An integer written as one, 0 to 2^53 − 1 (§0).
560fn uint(v: &Value) -> Option<u64> {
561    v.as_u64().filter(|&n| n <= MAX_INT)
562}
563
564fn prefixed_hex(s: &str, prefix: &str, len: usize) -> bool {
565    s.strip_prefix(prefix)
566        .is_some_and(|h| h.len() == len && crate::lower_hex(h))
567}
568
569fn doc_hash_ok(s: &str) -> bool {
570    prefixed_hex(s, "sha256:", 64)
571}
572
573/// §0's time: `YYYY-MM-DDTHH:MM:SSZ` naming a real date, seconds 00 to 59.
574fn time_ok(s: &str) -> bool {
575    crate::timestamp(s).is_ok() && s.get(17..19).is_some_and(|ss| ss <= "59")
576}
577
578/// The latest POSIX second [`time_of`] writes, 262142-12-31T23:59:59Z; after it, the empty string.
579const LAST_TIME_OF: u64 = 8_210_266_876_799;
580
581/// §0's time of POSIX seconds. A counted cosignature time is at most [`MAX_COSIGNATURE_TIME`], so
582/// four digits of year; for the public fields' larger values, the year is written with its sign
583/// (`+10000-01-01T00:00:00Z`) up to [`LAST_TIME_OF`], and a later time is the empty string.
584fn time_of(secs: u64) -> String {
585    if secs > LAST_TIME_OF {
586        return String::new();
587    }
588    // Days since 1970-01-01 to a proleptic Gregorian date (H. Hinnant's civil_from_days).
589    let (days, rem) = (secs / 86_400, secs % 86_400);
590    let z = days + 719_468;
591    let (era, doe) = (z / 146_097, z % 146_097);
592    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
593    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
594    let mp = (5 * doy + 2) / 153;
595    let day = doy - (153 * mp + 2) / 5 + 1;
596    let month = if mp < 10 { mp + 3 } else { mp - 9 };
597    let year = yoe + era * 400 + u64::from(month <= 2);
598    let year = if year <= 9_999 {
599        format!("{year:04}")
600    } else {
601        format!("+{year}")
602    };
603    format!(
604        "{year}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
605        rem / 3_600,
606        rem / 60 % 60,
607        rem % 60
608    )
609}
610
611// ---------------------------------------------------------------------------------------------
612// Checkpoints (§5)
613// ---------------------------------------------------------------------------------------------
614
615/// One signature line of a signed note: the key name, the 4-byte C2SP key ID, and the bytes after
616/// the key ID (a log signature, or a cosignature's timestamp and signature).
617#[derive(Clone, Debug, PartialEq, Eq)]
618pub struct SignatureLine {
619    pub key_name: String,
620    pub key_hash: [u8; 4],
621    pub value: Vec<u8>,
622}
623
624/// A checkpoint parsed from its signed note (§5.1). Nothing in it is trusted yet.
625#[derive(Clone, Debug, PartialEq, Eq)]
626pub struct Checkpoint {
627    pub origin: String,
628    pub tree_size: u64,
629    pub root_hash: Hash,
630    /// The note text: the three lines, each with its newline. The log signs these bytes.
631    pub note_text: String,
632    pub signatures: Vec<SignatureLine>,
633}
634
635/// Parse a checkpoint's full signed-note text (§5.1), without trusting it: refused as
636/// `checkpoint_form` when it breaks any rule of §5.1, two signature lines from one key included.
637pub fn parse_checkpoint(note: &str) -> Result<Checkpoint, InclusionError> {
638    let bad = |m: &str| fail(ErrorName::CheckpointForm, m.to_string());
639    if note.chars().any(|c| c.is_control() && c != '\n') {
640        return bad("a checkpoint has no control character other than a newline");
641    }
642    let Some(body) = note.strip_suffix('\n') else {
643        return bad("a checkpoint ends with a newline");
644    };
645    let lines: Vec<&str> = body.split('\n').collect();
646    if lines.len() < 5 || !lines[3].is_empty() {
647        return bad(
648            "a checkpoint is three text lines, an empty line, then one or more signature lines",
649        );
650    }
651    let (origin, size, root) = (lines[0], lines[1], lines[2]);
652    if origin.is_empty() {
653        return bad("the origin line is empty");
654    }
655    let tree_size =
656        (size.len() <= 20 && size.bytes().all(|b| b.is_ascii_digit()) && !size.starts_with('0'))
657            .then(|| size.parse::<u64>().ok())
658            .flatten()
659            .filter(|&n| n >= 1);
660    let Some(tree_size) = tree_size else {
661        return bad("the tree size is 1 to 2^64 − 1 in decimal, without leading zeros");
662    };
663    let Some(root_hash) = b64_hash(root) else {
664        return bad("the root hash is 32 bytes in canonical base64");
665    };
666    let sig_lines = &lines[4..];
667    if sig_lines.len() > MAX_SIGNATURE_LINES {
668        return bad("a checkpoint has at most 100 signature lines");
669    }
670    let mut signatures = Vec::with_capacity(sig_lines.len());
671    let mut seen = BTreeSet::new();
672    for line in sig_lines {
673        let Some((name, value)) = line
674            .strip_prefix("\u{2014} ")
675            .and_then(|r| r.split_once(' '))
676        else {
677            return bad(
678                "a signature line is an em dash, a space, a key name, a space and a base64 value",
679            );
680        };
681        if !key_name_ok(name) {
682            return bad("a key name is 1 to 255 printable ASCII characters other than +");
683        }
684        let Some(bytes) = b64(value).filter(|b| b.len() >= 5) else {
685            return bad("a signature value is canonical base64 of at least 5 bytes");
686        };
687        let key_hash: [u8; 4] = [bytes[0], bytes[1], bytes[2], bytes[3]];
688        if !seen.insert((name, key_hash)) {
689            return bad("two signature lines from one key (the same key name and key ID)");
690        }
691        signatures.push(SignatureLine {
692            key_name: name.to_string(),
693            key_hash,
694            value: bytes[4..].to_vec(),
695        });
696    }
697    Ok(Checkpoint {
698        origin: origin.to_string(),
699        tree_size,
700        root_hash,
701        note_text: format!("{origin}\n{size}\n{root}\n"),
702        signatures,
703    })
704}
705
706/// A C2SP key name or cosigner name: 1 to 255 printable ASCII characters other than `+` (§5.1).
707fn key_name_ok(s: &str) -> bool {
708    (1..=255).contains(&s.len()) && s.bytes().all(|b| (0x21..=0x7e).contains(&b) && b != b'+')
709}
710
711/// Canonical standard base64 (RFC 4648 §4 with padding, §3.5): decodes and re-encodes to itself.
712fn b64(s: &str) -> Option<Vec<u8>> {
713    STANDARD.decode(s).ok().filter(|b| STANDARD.encode(b) == s)
714}
715
716fn b64_hash(s: &str) -> Option<Hash> {
717    b64(s).and_then(|b| b.try_into().ok())
718}
719
720/// The C2SP key ID (§5.2, §5.3): the first 4 bytes of SHA-256(key name || 0x0A || type || public key).
721pub fn c2sp_key_hash(key_name: &str, sig_type: u8, key: &VerifyingKey) -> [u8; 4] {
722    let mut h = Sha256::new();
723    h.update(key_name.as_bytes());
724    h.update([0x0a, sig_type]);
725    h.update(key.as_bytes());
726    let d = h.finalize();
727    [d[0], d[1], d[2], d[3]]
728}
729
730/// The message a `cosignature/v1` signs (§5.3): `"cosignature/v1\ntime <timestamp>\n"` then the
731/// checkpoint's note text.
732pub fn cosignature_message(note_text: &str, timestamp: u64) -> Vec<u8> {
733    format!("cosignature/v1\ntime {timestamp}\n{note_text}").into_bytes()
734}
735
736fn verify_sig(key: &VerifyingKey, msg: &[u8], sig: &[u8]) -> bool {
737    Signature::from_slice(sig).is_ok_and(|s| key.verify_strict(msg, &s).is_ok())
738}
739
740// ---------------------------------------------------------------------------------------------
741// The log trust configuration (§9)
742// ---------------------------------------------------------------------------------------------
743
744/// The consumer's `policy` for a certificate without a bundle (§11).
745#[derive(Clone, Copy, Debug, PartialEq, Eq)]
746pub enum Policy {
747    Off,
748    Warn,
749    Refuse,
750}
751
752impl Policy {
753    pub fn as_str(self) -> &'static str {
754        match self {
755            Self::Off => "off",
756            Self::Warn => "warn",
757            Self::Refuse => "refuse",
758        }
759    }
760}
761
762/// A trusted log: its id, its C2SP key name, and its key.
763#[derive(Clone, Debug, PartialEq, Eq)]
764pub struct TrustedLog {
765    pub log_id: String,
766    pub key_name: String,
767    /// The key's id in this repository's form, `ed25519:<16 hex>`.
768    pub key_id: String,
769    pub key: VerifyingKey,
770    /// The time of the log's first entry (§9), if the configuration gives it: a certificate whose
771    /// `fitted_at` is earlier is marked backfilled (§10, "Backfilled").
772    pub started_at: Option<String>,
773}
774
775/// A trusted witness: its C2SP cosigner name, and its key.
776#[derive(Clone, Debug, PartialEq, Eq)]
777pub struct TrustedWitness {
778    pub name: String,
779    pub key_id: String,
780    pub key: VerifyingKey,
781}
782
783/// One tenant's log trust configuration (§9), checked as a whole by [`LogTrust::from_json`].
784#[derive(Clone, Debug, PartialEq, Eq)]
785pub struct LogTrust {
786    tenant: String,
787    logs: Vec<TrustedLog>,
788    witnesses: Vec<TrustedWitness>,
789    m: usize,
790    policy: Policy,
791}
792
793impl LogTrust {
794    /// Read and check a log trust configuration (§9), refusing it as `trust_form`.
795    pub fn from_json(v: &Value) -> Result<LogTrust, InclusionError> {
796        let bad = |m: &str| fail(ErrorName::TrustForm, m.to_string());
797        let Some(obj) = v.as_object() else {
798            return bad("the log trust configuration is a JSON object");
799        };
800        if !only(
801            obj,
802            &["spec", "tenant", "logs", "witnesses"],
803            &["m", "policy"],
804        ) {
805            return bad("the log trust configuration has exactly spec, tenant, logs, witnesses and optionally m and policy");
806        }
807        if obj["spec"] != SPEC_LOG_TRUST {
808            return bad("spec is not decision-cert-log-trust.v1");
809        }
810        let Some(tenant) = obj["tenant"].as_str().filter(|t| crate::tenant_ok(t)) else {
811            return bad("tenant is 1 to 128 characters of A-Z a-z 0-9 . _ : -");
812        };
813        let (Some(logs_in), Some(witnesses_in)) =
814            (obj["logs"].as_array(), obj["witnesses"].as_array())
815        else {
816            return bad("logs and witnesses are arrays");
817        };
818        if logs_in.is_empty() || witnesses_in.is_empty() {
819            return bad("logs and witnesses each have at least one entry");
820        }
821        let mut logs = Vec::new();
822        for l in logs_in {
823            let e = l
824                .as_object()
825                .filter(|e| only(e, &["log_id", "key_name", "key_id", "key"], &["started_at"]));
826            let Some(e) = e else {
827                return bad(
828                    "a log entry has exactly log_id, key_name, key_id, key and optionally started_at",
829                );
830            };
831            let Some(log_id) = e["log_id"].as_str().filter(|s| prefixed_hex(s, "log:", 32)) else {
832                return bad("a log_id is log: and 32 lowercase hex characters");
833            };
834            let Some(key_name) = e["key_name"].as_str().filter(|s| key_name_ok(s)) else {
835                return bad("a key_name is 1 to 255 printable ASCII characters other than +");
836            };
837            let started_at = match e.get("started_at") {
838                None => None,
839                Some(v) => match v.as_str().filter(|s| time_ok(s)) {
840                    Some(s) => Some(s.to_string()),
841                    None => return bad("started_at is a time YYYY-MM-DDTHH:MM:SSZ"),
842                },
843            };
844            let (key_id, key) = trusted_key(e)?;
845            logs.push(TrustedLog {
846                log_id: log_id.to_string(),
847                key_name: key_name.to_string(),
848                key_id,
849                key,
850                started_at,
851            });
852        }
853        let mut witnesses = Vec::new();
854        for w in witnesses_in {
855            let e = w
856                .as_object()
857                .filter(|e| only(e, &["name", "key_id", "key"], &[]));
858            let Some(e) = e else {
859                return bad("a witness entry has exactly name, key_id and key");
860            };
861            let Some(name) = e["name"].as_str().filter(|s| key_name_ok(s)) else {
862                return bad("a witness name is 1 to 255 printable ASCII characters other than +");
863            };
864            let (key_id, key) = trusted_key(e)?;
865            witnesses.push(TrustedWitness {
866                name: name.to_string(),
867                key_id,
868                key,
869            });
870        }
871        let m = match obj.get("m") {
872            None => 1,
873            Some(v) => match uint(v) {
874                Some(n) if n >= 1 && n <= witnesses.len() as u64 => n as usize,
875                _ => return bad("m is an integer from 1 to the number of witnesses"),
876            },
877        };
878        let policy = match obj.get("policy").map(Value::as_str) {
879            None => Policy::Warn,
880            Some(Some("off")) => Policy::Off,
881            Some(Some("warn")) => Policy::Warn,
882            Some(Some("refuse")) => Policy::Refuse,
883            Some(_) => return bad("policy is off, warn or refuse"),
884        };
885        let distinct = |xs: Vec<&[u8]>| xs.iter().collect::<BTreeSet<_>>().len() == xs.len();
886        if !distinct(logs.iter().map(|l| l.log_id.as_bytes()).collect())
887            || !distinct(logs.iter().map(|l| l.key.as_bytes().as_slice()).collect())
888        {
889            return bad("two logs share a log_id or a key");
890        }
891        if !distinct(witnesses.iter().map(|w| w.name.as_bytes()).collect())
892            || !distinct(
893                witnesses
894                    .iter()
895                    .map(|w| w.key.as_bytes().as_slice())
896                    .collect(),
897            )
898        {
899            return bad("two witnesses share a name or a key");
900        }
901        if witnesses
902            .iter()
903            .any(|w| logs.iter().any(|l| l.key == w.key))
904        {
905            return bad("a witness's key is also a log's key");
906        }
907        Ok(LogTrust {
908            tenant: tenant.to_string(),
909            logs,
910            witnesses,
911            m,
912            policy,
913        })
914    }
915
916    /// The expected tenant.
917    pub fn tenant(&self) -> &str {
918        &self.tenant
919    }
920    pub fn logs(&self) -> &[TrustedLog] {
921        &self.logs
922    }
923    pub fn witnesses(&self) -> &[TrustedWitness] {
924        &self.witnesses
925    }
926    /// The number of distinct trusted witnesses a checkpoint needs (default 1).
927    pub fn m(&self) -> usize {
928        self.m
929    }
930    /// The policy for a certificate without a bundle (default `warn`).
931    pub fn policy(&self) -> Policy {
932        self.policy
933    }
934
935    fn log(&self, log_id: &str) -> Result<&TrustedLog, InclusionError> {
936        self.logs
937            .iter()
938            .find(|l| l.log_id == log_id)
939            .ok_or_else(|| {
940                InclusionError::new(
941                    ErrorName::UnknownLog,
942                    format!("{log_id} is not one of tenant {}'s logs", self.tenant),
943                )
944            })
945    }
946}
947
948/// The required members, and optional ones, and nothing else.
949fn only(obj: &Map<String, Value>, required: &[&str], optional: &[&str]) -> bool {
950    required.iter().all(|k| obj.contains_key(*k))
951        && obj
952            .keys()
953            .all(|k| required.contains(&k.as_str()) || optional.contains(&k.as_str()))
954}
955
956/// An entry's `key` (base64url, a valid Ed25519 key under strict verification) and its `key_id`,
957/// which must be the key's id.
958fn trusted_key(e: &Map<String, Value>) -> Result<(String, VerifyingKey), InclusionError> {
959    let key = e["key"]
960        .as_str()
961        .and_then(|s| {
962            URL_SAFE_NO_PAD
963                .decode(s)
964                .ok()
965                .filter(|b| URL_SAFE_NO_PAD.encode(b) == s)
966        })
967        .and_then(|b| <[u8; 32]>::try_from(b).ok())
968        .and_then(|b| VerifyingKey::from_bytes(&b).ok())
969        .filter(|k| !k.is_weak());
970    let Some(key) = key else {
971        return fail(
972            ErrorName::TrustForm,
973            "a key is a valid Ed25519 public key in base64url (43 characters), not of small order",
974        );
975    };
976    let id = crate::key_id(&key);
977    if e["key_id"].as_str() != Some(id.as_str()) {
978        return fail(
979            ErrorName::TrustForm,
980            format!("key_id is not the key id of its key ({id})"),
981        );
982    }
983    Ok((id, key))
984}
985
986/// Several tenants' configurations held together (§2, §9): refused as `trust_cross_tenant` when one
987/// `log_id`, or one log key, appears under two tenants. Witnesses may serve several tenants.
988pub fn check_tenants(configs: &[LogTrust]) -> Result<(), InclusionError> {
989    let mut ids: BTreeMap<&str, &str> = BTreeMap::new();
990    let mut keys: BTreeMap<&[u8; 32], &str> = BTreeMap::new();
991    for c in configs {
992        for l in &c.logs {
993            for owner in [
994                *ids.entry(&l.log_id).or_insert(&c.tenant),
995                *keys.entry(l.key.as_bytes()).or_insert(&c.tenant),
996            ] {
997                if owner != c.tenant {
998                    return fail(
999                        ErrorName::TrustCrossTenant,
1000                        format!(
1001                            "log {} (or its key) appears under tenants {owner} and {}",
1002                            l.log_id, c.tenant
1003                        ),
1004                    );
1005                }
1006            }
1007        }
1008    }
1009    Ok(())
1010}
1011
1012// ---------------------------------------------------------------------------------------------
1013// The bundle (§8) and the consumer's checks (§10)
1014// ---------------------------------------------------------------------------------------------
1015
1016/// A witness counted for a checkpoint: a trusted witness whose cosignature verified.
1017#[derive(Clone, Debug, PartialEq, Eq)]
1018pub struct CountedWitness {
1019    pub name: String,
1020    pub key_id: String,
1021    /// The cosignature time, POSIX seconds.
1022    pub time: u64,
1023}
1024
1025/// What a verified bundle shows (§10, "The verdict").
1026#[derive(Clone, Debug, PartialEq, Eq)]
1027pub struct InclusionVerdict {
1028    pub log_id: String,
1029    pub tree_size: u64,
1030    pub root_hash: Hash,
1031    pub leaf_index: u64,
1032    pub kind: String,
1033    /// For a certificate leaf, the certificate's id.
1034    pub certificate_id: Option<String>,
1035    /// For a certificate leaf, the bases on which it is marked backfilled, in this order: `bundle`
1036    /// (the bundle's `backfilled`, the bundler's statement) and `started_at` (its `fitted_at` is
1037    /// earlier than the configuration's `started_at` for the log). Empty when it is not marked.
1038    pub backfilled_by: Option<Vec<&'static str>>,
1039    /// The counted witnesses, by cosignature time, then name.
1040    pub witnesses: Vec<CountedWitness>,
1041    /// The `m`-th earliest counted cosignature time, POSIX seconds.
1042    pub t_proven: u64,
1043}
1044
1045impl InclusionVerdict {
1046    /// `t_proven` as a time (§0).
1047    pub fn t_proven_time(&self) -> String {
1048        time_of(self.t_proven)
1049    }
1050
1051    /// For a certificate leaf, whether it is marked backfilled (§10, "Backfilled"): a mark, never a
1052    /// reason to refuse.
1053    pub fn backfilled(&self) -> Option<bool> {
1054        self.backfilled_by.as_ref().map(|by| !by.is_empty())
1055    }
1056
1057    /// The verdict as JSON: hashes in base64, times in §0's form.
1058    pub fn to_json(&self) -> Value {
1059        let mut v = serde_json::json!({
1060            "log_id": self.log_id,
1061            "tree_size": self.tree_size,
1062            "root_hash": STANDARD.encode(self.root_hash),
1063            "leaf_index": self.leaf_index,
1064            "kind": self.kind,
1065            "witnesses": self.witnesses.iter().map(|w| serde_json::json!({
1066                "name": w.name,
1067                "key_id": w.key_id,
1068                "time": time_of(w.time),
1069            })).collect::<Vec<_>>(),
1070            "t_proven": self.t_proven_time(),
1071        });
1072        if let Some(id) = &self.certificate_id {
1073            v["certificate_id"] = Value::String(id.clone());
1074        }
1075        if let Some(by) = &self.backfilled_by {
1076            v["backfilled"] = Value::Bool(!by.is_empty());
1077            v["backfilled_by"] = serde_json::json!(by);
1078        }
1079        v
1080    }
1081}
1082
1083/// Check a bundle against the expected tenant's configuration, in §10's order (checks 2 to 12; check
1084/// 1 is [`LogTrust::from_json`]), refusing at the first failure with that check's error name.
1085///
1086/// For a certificate leaf this does not verify the certificate itself: verify it under its own spec
1087/// as well ([`crate::verify_for_tenant`] with `trust.tenant()`).
1088pub fn verify_bundle(bundle: &Value, trust: &LogTrust) -> Result<InclusionVerdict, InclusionError> {
1089    // 2. the bundle's form
1090    let bad = |m: &str| fail(ErrorName::BundleForm, m.to_string());
1091    let Some(obj) = bundle.as_object() else {
1092        return bad("a bundle is a JSON object");
1093    };
1094    let members = [
1095        "spec",
1096        "log_id",
1097        "leaf_index",
1098        "leaf",
1099        "proof",
1100        "checkpoint",
1101    ];
1102    if !only(obj, &members, &["certificate", "backfilled"]) {
1103        return bad("a bundle has exactly spec, log_id, leaf_index, leaf, proof, checkpoint, and certificate (and optionally backfilled) for a certificate leaf");
1104    }
1105    if obj["spec"] != SPEC_BUNDLE {
1106        return bad("spec is not decision-cert-inclusion.v1");
1107    }
1108    let Some(log_id) = obj["log_id"]
1109        .as_str()
1110        .filter(|s| prefixed_hex(s, "log:", 32))
1111    else {
1112        return bad("log_id is log: and 32 lowercase hex characters");
1113    };
1114    let Some(leaf_index) = uint(&obj["leaf_index"]) else {
1115        return bad("leaf_index is an integer from 0 to 2^53 − 1");
1116    };
1117    let Some(leaf_value) = obj["leaf"].as_object() else {
1118        return bad("leaf is a JSON object");
1119    };
1120    let Some(proof) = path_of(&obj["proof"]) else {
1121        return bad("proof is an array of at most 64 base64 32-byte hashes");
1122    };
1123    let Some(checkpoint_text) = obj["checkpoint"].as_str() else {
1124        return bad("checkpoint is a string, the checkpoint's signed note");
1125    };
1126    let is_cert = leaf_value.get("kind").and_then(Value::as_str) == Some("certificate");
1127    let certificate = match (is_cert, obj.get("certificate")) {
1128        (true, Some(c)) if c.is_object() => Some(c),
1129        (false, None) => None,
1130        _ => {
1131            return bad(
1132                "certificate is a JSON object, present if and only if leaf.kind is certificate",
1133            )
1134        }
1135    };
1136    let bundle_backfilled = match obj.get("backfilled") {
1137        None => false,
1138        Some(Value::Bool(true)) if is_cert => true,
1139        _ => return bad("backfilled is true, and present only beside a certificate leaf"),
1140    };
1141
1142    // 3. the leaf's form
1143    let leaf = Leaf::from_json(&obj["leaf"])?;
1144
1145    // 4. a certificate leaf matches its certificate
1146    let mut certificate_id = None;
1147    if let Some(cert) = certificate {
1148        let id = crate::certificate_id(cert)
1149            .map_err(|e| InclusionError::new(ErrorName::LeafMismatch, e.to_string()))?;
1150        if leaf.get_str("certificate_id") != Some(id.as_str()) {
1151            return fail(
1152                ErrorName::LeafMismatch,
1153                format!("the leaf's certificate_id is not the certificate's id {id}"),
1154            );
1155        }
1156        for m in ["signer_key_id", "spec", "fitted_at", "tenant"] {
1157            if leaf.0.get(m) != cert.get(m) {
1158                return fail(
1159                    ErrorName::LeafMismatch,
1160                    format!("the leaf's {m} is not the certificate's"),
1161                );
1162            }
1163        }
1164        certificate_id = Some(id);
1165    }
1166
1167    // 5. the leaf's tenant (a v1.5 certificate leaf's, an audit_head's) is the expected tenant
1168    if let Some(t) = leaf.get_str("tenant") {
1169        if t != trust.tenant {
1170            return fail(
1171                ErrorName::TenantMismatch,
1172                format!("the leaf is for tenant {t}, not {}", trust.tenant),
1173            );
1174        }
1175    }
1176
1177    // 6. a log of the expected tenant
1178    let log = trust.log(log_id)?;
1179
1180    // 7, 8. the checkpoint's form and origin
1181    let cp = parse_checkpoint(checkpoint_text)?;
1182    if cp.origin != log_id {
1183        return fail(
1184            ErrorName::OriginMismatch,
1185            format!("the checkpoint's origin is not {log_id}"),
1186        );
1187    }
1188
1189    // 9. the audit path
1190    if !verify_inclusion_path(
1191        leaf_index,
1192        cp.tree_size,
1193        &leaf_hash(&leaf),
1194        &proof,
1195        &cp.root_hash,
1196    ) {
1197        return fail(
1198            ErrorName::BadProof,
1199            format!(
1200                "the audit path does not lead from the leaf at {leaf_index} to the root of the tree of {} leaves",
1201                cp.tree_size
1202            ),
1203        );
1204    }
1205
1206    // 10. the log's signature
1207    check_log_signature(&cp, log)?;
1208
1209    // 11, 12. the witnesses' cosignatures
1210    let witnesses = cosigners(&cp, trust)?;
1211    if witnesses.len() < trust.m {
1212        return fail(
1213            ErrorName::TooFewCosignatures,
1214            format!(
1215                "{} trusted witnesses cosigned, the configuration needs {}",
1216                witnesses.len(),
1217                trust.m
1218            ),
1219        );
1220    }
1221    let t_proven = witnesses[trust.m - 1].time;
1222
1223    // the backfilled mark (§10, "Backfilled"): reported, never refused
1224    let backfilled_by = certificate_id.as_ref().map(|_| {
1225        let mut by = Vec::new();
1226        if bundle_backfilled {
1227            by.push("bundle");
1228        }
1229        if let (Some(start), Some(fitted)) = (&log.started_at, leaf.get_str("fitted_at")) {
1230            if fitted < start.as_str() {
1231                by.push("started_at");
1232            }
1233        }
1234        by
1235    });
1236    Ok(InclusionVerdict {
1237        log_id: log_id.to_string(),
1238        tree_size: cp.tree_size,
1239        root_hash: cp.root_hash,
1240        leaf_index,
1241        kind: leaf.kind().to_string(),
1242        certificate_id,
1243        backfilled_by,
1244        witnesses,
1245        t_proven,
1246    })
1247}
1248
1249/// A JSON array of at most 64 canonical base64 32-byte hashes.
1250fn path_of(v: &Value) -> Option<Vec<Hash>> {
1251    let a = v.as_array().filter(|a| a.len() <= MAX_PATH)?;
1252    a.iter().map(|h| h.as_str().and_then(b64_hash)).collect()
1253}
1254
1255/// Check 10 (§5.2, §5.4): a line matches the log's key, and it verifies.
1256fn check_log_signature(cp: &Checkpoint, log: &TrustedLog) -> Result<(), InclusionError> {
1257    let want = c2sp_key_hash(&log.key_name, SIG_TYPE_ED25519, &log.key);
1258    let mut matched = false;
1259    for s in &cp.signatures {
1260        if s.key_name == log.key_name && s.key_hash == want {
1261            matched = true;
1262            if s.value.len() != 64 || !verify_sig(&log.key, cp.note_text.as_bytes(), &s.value) {
1263                return fail(
1264                    ErrorName::BadLogSignature,
1265                    format!("the log signature of {} does not verify", log.log_id),
1266                );
1267            }
1268        }
1269    }
1270    if !matched {
1271        return fail(
1272            ErrorName::LogSignatureMissing,
1273            format!("no signature line matches the key of log {}", log.log_id),
1274        );
1275    }
1276    Ok(())
1277}
1278
1279/// Check 11 (§5.3, §5.4): every line matching a trusted witness verifies, with a timestamp at most
1280/// [`MAX_COSIGNATURE_TIME`]. The counted witnesses, by time then name. Each trusted witness has at
1281/// most one line (§5.1, [`parse_checkpoint`]).
1282fn cosigners(cp: &Checkpoint, trust: &LogTrust) -> Result<Vec<CountedWitness>, InclusionError> {
1283    let mut out = Vec::new();
1284    for w in &trust.witnesses {
1285        let want = c2sp_key_hash(&w.name, SIG_TYPE_COSIGNATURE_V1, &w.key);
1286        for s in &cp.signatures {
1287            if s.key_name != w.name || s.key_hash != want {
1288                continue;
1289            }
1290            let time = (s.value.len() == 72)
1291                .then(|| s.value[..8].try_into().ok().map(u64::from_be_bytes))
1292                .flatten()
1293                .filter(|&t| t <= MAX_COSIGNATURE_TIME);
1294            let verified = time.filter(|&t| {
1295                verify_sig(
1296                    &w.key,
1297                    &cosignature_message(&cp.note_text, t),
1298                    &s.value[8..],
1299                )
1300            });
1301            let Some(time) = verified else {
1302                return fail(
1303                    ErrorName::BadCosignature,
1304                    format!(
1305                        "the cosignature of witness {} does not verify, or its time is out of range",
1306                        w.name
1307                    ),
1308                );
1309            };
1310            out.push(CountedWitness {
1311                name: w.name.clone(),
1312                key_id: w.key_id.clone(),
1313                time,
1314            });
1315        }
1316    }
1317    out.sort_by(|a, b| (a.time, &a.name).cmp(&(b.time, &b.name)));
1318    Ok(out)
1319}
1320
1321// ---------------------------------------------------------------------------------------------
1322// The consistency proof document (§7)
1323// ---------------------------------------------------------------------------------------------
1324
1325/// What a verified consistency proof document shows (§7.2).
1326#[derive(Clone, Debug, PartialEq, Eq)]
1327pub struct ConsistencyVerdict {
1328    pub log_id: String,
1329    pub older_size: u64,
1330    pub newer_size: u64,
1331}
1332
1333impl ConsistencyVerdict {
1334    pub fn to_json(&self) -> Value {
1335        serde_json::json!({
1336            "log_id": self.log_id,
1337            "older_size": self.older_size,
1338            "newer_size": self.newer_size,
1339        })
1340    }
1341}
1342
1343/// Check a consistency proof document against the expected tenant's configuration, in §7.2's order:
1344/// its form, its log, each checkpoint's form and origin, each checkpoint's log signature, then the
1345/// sizes and the path. Cosignatures are not required, and witness lines are not checked.
1346pub fn verify_consistency(
1347    doc: &Value,
1348    trust: &LogTrust,
1349) -> Result<ConsistencyVerdict, InclusionError> {
1350    let bad = |m: &str| fail(ErrorName::ConsistencyForm, m.to_string());
1351    let Some(obj) = doc.as_object() else {
1352        return bad("a consistency proof document is a JSON object");
1353    };
1354    if !only(obj, &["spec", "log_id", "older", "newer", "proof"], &[]) {
1355        return bad(
1356            "a consistency proof document has exactly spec, log_id, older, newer and proof",
1357        );
1358    }
1359    if obj["spec"] != SPEC_CONSISTENCY {
1360        return bad("spec is not decision-cert-consistency.v1");
1361    }
1362    let Some(log_id) = obj["log_id"]
1363        .as_str()
1364        .filter(|s| prefixed_hex(s, "log:", 32))
1365    else {
1366        return bad("log_id is log: and 32 lowercase hex characters");
1367    };
1368    let (Some(older_text), Some(newer_text)) = (obj["older"].as_str(), obj["newer"].as_str())
1369    else {
1370        return bad("older and newer are strings, checkpoints' signed notes");
1371    };
1372    let Some(proof) = path_of(&obj["proof"]) else {
1373        return bad("proof is an array of at most 64 base64 32-byte hashes");
1374    };
1375    let log = trust.log(log_id)?;
1376    let mut cps = Vec::with_capacity(2);
1377    for text in [older_text, newer_text] {
1378        let cp = parse_checkpoint(text)?;
1379        if cp.origin != log_id {
1380            return fail(
1381                ErrorName::OriginMismatch,
1382                format!("a checkpoint's origin is not {log_id}"),
1383            );
1384        }
1385        cps.push(cp);
1386    }
1387    for cp in &cps {
1388        check_log_signature(cp, log)?;
1389    }
1390    let (older, newer) = (&cps[0], &cps[1]);
1391    if newer.tree_size < older.tree_size {
1392        return fail(
1393            ErrorName::SizeRegression,
1394            format!(
1395                "the newer checkpoint ({}) is smaller than the older ({})",
1396                newer.tree_size, older.tree_size
1397            ),
1398        );
1399    }
1400    if newer.tree_size == older.tree_size && newer.root_hash != older.root_hash {
1401        return fail(
1402            ErrorName::SplitView,
1403            format!(
1404                "two checkpoints of log {log_id} with size {} and different roots",
1405                older.tree_size
1406            ),
1407        );
1408    }
1409    if !verify_consistency_path(
1410        older.tree_size,
1411        newer.tree_size,
1412        &older.root_hash,
1413        &newer.root_hash,
1414        &proof,
1415    ) {
1416        return fail(
1417            ErrorName::BadConsistencyProof,
1418            format!(
1419                "the consistency path does not connect sizes {} and {}",
1420                older.tree_size, newer.tree_size
1421            ),
1422        );
1423    }
1424    Ok(ConsistencyVerdict {
1425        log_id: log_id.to_string(),
1426        older_size: older.tree_size,
1427        newer_size: newer.tree_size,
1428    })
1429}
1430
1431// ---------------------------------------------------------------------------------------------
1432// Policy (§11)
1433// ---------------------------------------------------------------------------------------------
1434
1435/// What a consumer does with a certificate, under its policy (§11). The certificate must pass its
1436/// own verification in every case.
1437#[derive(Clone, Debug, PartialEq, Eq)]
1438pub enum PolicyOutcome {
1439    /// Load it; the verdict when a bundle was checked (`warn` and `refuse`), None under `off`.
1440    Load(Option<InclusionVerdict>),
1441    /// Load it, with the warning `inclusion_missing` (`warn`, no bundle).
1442    LoadWithWarning(InclusionError),
1443    /// Refuse it: `inclusion_missing` under `refuse`, or the failing check's error.
1444    Refuse(InclusionError),
1445}
1446
1447/// Apply `policy` to a certificate's bundle check: None when it has no bundle, else the result of
1448/// [`verify_bundle`]. `warn` softens only a missing bundle; a bundle that fails is refused under
1449/// `warn` and `refuse` alike. Under `off` nothing is checked and any result is ignored.
1450pub fn apply_policy(
1451    result: Option<Result<InclusionVerdict, InclusionError>>,
1452    policy: Policy,
1453) -> PolicyOutcome {
1454    let missing = || {
1455        InclusionError::new(
1456            ErrorName::InclusionMissing,
1457            "the certificate has no inclusion bundle",
1458        )
1459    };
1460    match (policy, result) {
1461        (Policy::Off, _) => PolicyOutcome::Load(None),
1462        (Policy::Warn, None) => PolicyOutcome::LoadWithWarning(missing()),
1463        (Policy::Refuse, None) => PolicyOutcome::Refuse(missing()),
1464        (_, Some(Ok(v))) => PolicyOutcome::Load(Some(v)),
1465        (_, Some(Err(e))) => PolicyOutcome::Refuse(e),
1466    }
1467}
1468
1469#[cfg(test)]
1470mod tests {
1471    use super::*;
1472    use ed25519_dalek::{Signer, SigningKey};
1473    use serde_json::json;
1474
1475    fn unhex(s: &str) -> Vec<u8> {
1476        (0..s.len() / 2)
1477            .map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap())
1478            .collect()
1479    }
1480    fn h(s: &str) -> Hash {
1481        unhex(s).try_into().unwrap()
1482    }
1483
1484    // RFC 6962 / RFC 9162 reference test data, from transparency-dev/merkle at tag v0.0.2 (commit
1485    // 036047b5d2f7faf3b1ee643d391e60fe5b1defcf): testonly/constants.go (LeafInputs, NodeHashes,
1486    // RootHashes) and proof/verify_test.go (inclusionProofs, consistencyProofs). The same values are
1487    // in google/certificate-transparency's merkle tree tests. These vectors hash the raw leaf
1488    // inputs, so they test the RFC 9162 layer ([`hash_leaf_bytes`]) beneath the JCS leaf encoding.
1489    const INPUTS: [&str; 8] = [
1490        "",
1491        "00",
1492        "10",
1493        "2021",
1494        "3031",
1495        "40414243",
1496        "5051525354555657",
1497        "606162636465666768696a6b6c6d6e6f",
1498    ];
1499    /// NodeHashes: level 0 (the leaf hashes) to level 3 (the root of all eight).
1500    const LEVELS: [&[&str]; 4] = [
1501        &[
1502            "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d",
1503            "96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7",
1504            "0298d122906dcfc10892cb53a73992fc5b9f493ea4c9badb27b791b4127a7fe7",
1505            "07506a85fd9dd2f120eb694f86011e5bb4662e5c415a62917033d4a9624487e7",
1506            "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b",
1507            "4271a26be0d8a84f0bd54c8c302e7cb3a3b5d1fa6780a40bcce2873477dab658",
1508            "b08693ec2e721597130641e8211e7eedccb4c26413963eee6c1e2ed16ffb1a5f",
1509            "46f6ffadd3d06a09ff3c5860d2755c8b9819db7df44251788c7d8e3180de8eb1",
1510        ],
1511        &[
1512            "fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125",
1513            "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e",
1514            "0ebc5d3437fbe2db158b9f126a1d118e308181031d0a949f8dededebc558ef6a",
1515            "ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0",
1516        ],
1517        &[
1518            "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7",
1519            "6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4",
1520        ],
1521        &["5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328"],
1522    ];
1523    /// RootHashes: the MTH of the first 1 to 8 leaves.
1524    const ROOTS: [&str; 8] = [
1525        "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d",
1526        "fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125",
1527        "aeb6bcfe274b70a14fb067a5e5578264db0fa9b51af5e0ba159158f329e06e77",
1528        "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7",
1529        "4e3bbb1f7b478dcfe71fb631631519a3bca12c9aefca1612bfce4c13a86264d4",
1530        "76e67dadbcdf1e10e1b74ddc608abd2f98dfb16fbce75277b5232a127f2087ef",
1531        "ddb89be403809e325750d3d263cd78929c2942b7942a34b77e122c9594a74c8c",
1532        "5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328",
1533    ];
1534    /// inclusionProofs: (0-based leaf index, tree size, audit path). The source numbers leaves from
1535    /// 1; its {0, 0, nil} entry is an invalid probe, not a vector.
1536    const INCLUSION: [(u64, u64, &[&str]); 5] = [
1537        (0, 1, &[]),
1538        (
1539            0,
1540            8,
1541            &[
1542                "96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7",
1543                "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e",
1544                "6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4",
1545            ],
1546        ),
1547        (
1548            5,
1549            8,
1550            &[
1551                "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b",
1552                "ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0",
1553                "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7",
1554            ],
1555        ),
1556        (
1557            2,
1558            3,
1559            &["fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125"],
1560        ),
1561        (
1562            1,
1563            5,
1564            &[
1565                "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d",
1566                "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e",
1567                "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b",
1568            ],
1569        ),
1570    ];
1571    /// consistencyProofs: (older size, newer size, consistency path).
1572    const CONSISTENCY: [(u64, u64, &[&str]); 5] = [
1573        (1, 1, &[]),
1574        (
1575            1,
1576            8,
1577            &[
1578                "96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7",
1579                "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e",
1580                "6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4",
1581            ],
1582        ),
1583        (
1584            6,
1585            8,
1586            &[
1587                "0ebc5d3437fbe2db158b9f126a1d118e308181031d0a949f8dededebc558ef6a",
1588                "ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0",
1589                "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7",
1590            ],
1591        ),
1592        (
1593            2,
1594            5,
1595            &[
1596                "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e",
1597                "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b",
1598            ],
1599        ),
1600        (
1601            6,
1602            7,
1603            &[
1604                "0ebc5d3437fbe2db158b9f126a1d118e308181031d0a949f8dededebc558ef6a",
1605                "b08693ec2e721597130641e8211e7eedccb4c26413963eee6c1e2ed16ffb1a5f",
1606                "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7",
1607            ],
1608        ),
1609    ];
1610
1611    fn reference_leaves() -> Vec<Hash> {
1612        INPUTS.iter().map(|x| hash_leaf_bytes(&unhex(x))).collect()
1613    }
1614
1615    #[test]
1616    fn rfc6962_leaf_and_node_hashes() {
1617        let leaves = reference_leaves();
1618        for (level, hashes) in LEVELS.iter().enumerate() {
1619            let width = 1 << level;
1620            for (i, want) in hashes.iter().enumerate() {
1621                let got = root_hash(&leaves[i * width..(i + 1) * width]).unwrap();
1622                assert_eq!(got, h(want), "level {level} node {i}");
1623            }
1624        }
1625        assert_eq!(
1626            node_hash(&leaves[0], &leaves[1]),
1627            h(LEVELS[1][0]),
1628            "node_hash"
1629        );
1630    }
1631
1632    #[test]
1633    fn rfc6962_roots_for_every_size() {
1634        let leaves = reference_leaves();
1635        for (n, want) in ROOTS.iter().enumerate() {
1636            assert_eq!(root_hash(&leaves[..=n]), Some(h(want)), "size {}", n + 1);
1637        }
1638        assert_eq!(root_hash(&[]), None);
1639    }
1640
1641    #[test]
1642    fn rfc6962_inclusion_vectors() {
1643        let leaves = reference_leaves();
1644        for (index, size, path) in INCLUSION {
1645            let path: Vec<Hash> = path.iter().map(|x| h(x)).collect();
1646            let root = h(ROOTS[size as usize - 1]);
1647            assert!(
1648                verify_inclusion_path(index, size, &leaves[index as usize], &path, &root),
1649                "{index} in {size}"
1650            );
1651            assert_eq!(
1652                audit_path(&leaves[..size as usize], index as usize).unwrap(),
1653                path,
1654                "audit_path {index} in {size}"
1655            );
1656        }
1657    }
1658
1659    #[test]
1660    fn rfc6962_consistency_vectors() {
1661        let leaves = reference_leaves();
1662        for (older, newer, path) in CONSISTENCY {
1663            let path: Vec<Hash> = path.iter().map(|x| h(x)).collect();
1664            let (r1, r2) = (h(ROOTS[older as usize - 1]), h(ROOTS[newer as usize - 1]));
1665            assert!(
1666                verify_consistency_path(older, newer, &r1, &r2, &path),
1667                "{older} -> {newer}"
1668            );
1669            assert_eq!(
1670                consistency_path(&leaves[..newer as usize], older as usize).unwrap(),
1671                path,
1672                "consistency_path {older} -> {newer}"
1673            );
1674        }
1675    }
1676
1677    /// Hand-built small trees, sizes 1 to 9, every index and every pair of sizes: the paths this
1678    /// module computes verify, and every short, long, altered or misplaced one fails.
1679    #[test]
1680    fn small_trees_every_index_and_every_pair() {
1681        let mut leaves = reference_leaves();
1682        leaves.push(hash_leaf_bytes(&[0x70]));
1683        let flip = |p: &mut Vec<Hash>, i: usize| p[i][0] ^= 1;
1684        for n in 1..=9usize {
1685            let d = &leaves[..n];
1686            let root = root_hash(d).unwrap();
1687            let size = n as u64;
1688            for i in 0..n {
1689                let path = audit_path(d, i).unwrap();
1690                let ok = |idx: u64, sz: u64, p: &[Hash], r: &Hash| {
1691                    verify_inclusion_path(idx, sz, &d[i], p, r)
1692                };
1693                assert!(ok(i as u64, size, &path, &root), "{i} in {n}");
1694                for j in (0..n).filter(|&j| j != i) {
1695                    assert!(!ok(j as u64, size, &path, &root), "{i} as {j} in {n}");
1696                }
1697                // a path for another tree size, against that tree's root: it fails unless the
1698                // two trees give that leaf the same path
1699                for m in (i + 1..=9).filter(|&m| m != n) {
1700                    let theirs = audit_path(&leaves[..m], i).unwrap();
1701                    let their_root = root_hash(&leaves[..m]).unwrap();
1702                    let fits = verify_inclusion_path(i as u64, m as u64, &d[i], &path, &their_root);
1703                    assert_eq!(fits, theirs == path, "{i} in {n} as {m}");
1704                }
1705                assert!(!ok(i as u64, i as u64, &path, &root), "index = size");
1706                let mut long = path.clone();
1707                long.push(root);
1708                assert!(!ok(i as u64, size, &long, &root), "long {i} in {n}");
1709                if !path.is_empty() {
1710                    let short = &path[..path.len() - 1];
1711                    assert!(!ok(i as u64, size, short, &root), "short {i} in {n}");
1712                    for k in 0..path.len() {
1713                        let mut bad = path.clone();
1714                        flip(&mut bad, k);
1715                        assert!(!ok(i as u64, size, &bad, &root), "altered {k}");
1716                    }
1717                }
1718                let mut other = root;
1719                other[31] ^= 1;
1720                assert!(!ok(i as u64, size, &path, &other), "other root");
1721            }
1722            for m in 1..=n {
1723                let r1 = root_hash(&d[..m]).unwrap();
1724                let path = consistency_path(d, m).unwrap();
1725                let (m64, n64) = (m as u64, n as u64);
1726                assert!(
1727                    verify_consistency_path(m64, n64, &r1, &root, &path),
1728                    "{m} -> {n}"
1729                );
1730                assert!(!verify_consistency_path(n64, m64, &root, &r1, &path) || m == n);
1731                let mut wrong = r1;
1732                wrong[0] ^= 1;
1733                assert!(!verify_consistency_path(m64, n64, &wrong, &root, &path));
1734                assert!(!verify_consistency_path(m64, n64, &r1, &wrong, &path));
1735                let mut long = path.clone();
1736                long.push(root);
1737                assert!(
1738                    !verify_consistency_path(m64, n64, &r1, &root, &long),
1739                    "long {m} -> {n}"
1740                );
1741                if !path.is_empty() {
1742                    let short = &path[..path.len() - 1];
1743                    assert!(
1744                        !verify_consistency_path(m64, n64, &r1, &root, short),
1745                        "short"
1746                    );
1747                    for k in 0..path.len() {
1748                        let mut bad = path.clone();
1749                        flip(&mut bad, k);
1750                        assert!(
1751                            !verify_consistency_path(m64, n64, &r1, &root, &bad),
1752                            "altered"
1753                        );
1754                    }
1755                }
1756                if m < n {
1757                    assert!(!verify_consistency_path(m64, n64, &r1, &root, &[]));
1758                }
1759                // a path to another newer size, against that tree's root
1760                for k in (m..=9).filter(|&k| k != n) {
1761                    let theirs = consistency_path(&leaves[..k], m).unwrap();
1762                    let their_root = root_hash(&leaves[..k]).unwrap();
1763                    let fits = verify_consistency_path(m64, k as u64, &r1, &their_root, &path);
1764                    assert_eq!(fits, theirs == path, "{m} -> {n} as {m} -> {k}");
1765                }
1766            }
1767        }
1768        assert!(!verify_consistency_path(0, 1, &leaves[0], &leaves[0], &[]));
1769    }
1770
1771    // -----------------------------------------------------------------------------------------
1772    // A test log: deterministic keys from fixed seeds, never fixture files.
1773    // -----------------------------------------------------------------------------------------
1774
1775    type Edit = Box<dyn Fn(&mut Value)>;
1776
1777    const LOG: &str = "log:00112233445566778899aabbccddeeff";
1778    const OTHER_LOG: &str = "log:ffeeddccbbaa99887766554433221100";
1779    const TENANT: &str = "acme-eu";
1780
1781    fn key(seed: u8) -> SigningKey {
1782        SigningKey::from_bytes(&[seed; 32])
1783    }
1784    fn log_key() -> SigningKey {
1785        key(1)
1786    }
1787    fn witness_name(i: u8) -> String {
1788        format!("witness.example/w{i}")
1789    }
1790    fn witness_key(i: u8) -> SigningKey {
1791        key(10 + i)
1792    }
1793    fn b64url(k: &SigningKey) -> String {
1794        URL_SAFE_NO_PAD.encode(k.verifying_key().as_bytes())
1795    }
1796
1797    fn trust_json(witnesses: u8, m: u64) -> Value {
1798        json!({
1799            "spec": SPEC_LOG_TRUST,
1800            "tenant": TENANT,
1801            "logs": [{
1802                "log_id": LOG,
1803                "key_name": LOG,
1804                "key_id": crate::key_id(&log_key().verifying_key()),
1805                "key": b64url(&log_key()),
1806            }],
1807            "witnesses": (0..witnesses).map(|i| json!({
1808                "name": witness_name(i),
1809                "key_id": crate::key_id(&witness_key(i).verifying_key()),
1810                "key": b64url(&witness_key(i)),
1811            })).collect::<Vec<_>>(),
1812            "m": m,
1813        })
1814    }
1815    fn trust(witnesses: u8, m: u64) -> LogTrust {
1816        LogTrust::from_json(&trust_json(witnesses, m)).unwrap()
1817    }
1818
1819    fn note(origin: &str, size: u64, root: &Hash) -> String {
1820        format!("{origin}\n{size}\n{}\n", STANDARD.encode(root))
1821    }
1822    fn log_line(name: &str, k: &SigningKey, note_text: &str) -> String {
1823        let mut v = c2sp_key_hash(name, SIG_TYPE_ED25519, &k.verifying_key()).to_vec();
1824        v.extend(k.sign(note_text.as_bytes()).to_bytes());
1825        format!("\u{2014} {name} {}\n", STANDARD.encode(v))
1826    }
1827    fn cosig_line(name: &str, k: &SigningKey, note_text: &str, time: u64) -> String {
1828        let mut v = c2sp_key_hash(name, SIG_TYPE_COSIGNATURE_V1, &k.verifying_key()).to_vec();
1829        v.extend(time.to_be_bytes());
1830        v.extend(k.sign(&cosignature_message(note_text, time)).to_bytes());
1831        format!("\u{2014} {name} {}\n", STANDARD.encode(v))
1832    }
1833    /// A checkpoint signed by the log, cosigned by trusted witnesses `(index, time)`.
1834    fn checkpoint(note_text: &str, cosigs: &[(u8, u64)]) -> String {
1835        let mut s = format!("{note_text}\n{}", log_line(LOG, &log_key(), note_text));
1836        for &(i, t) in cosigs {
1837            s += &cosig_line(&witness_name(i), &witness_key(i), note_text, t);
1838        }
1839        s
1840    }
1841
1842    fn certificate() -> Value {
1843        json!({
1844            "spec": "decision-certificate.v1.5",
1845            "signer_key_id": "ed25519:0c6e5b7d2a913f84",
1846            "fitted_at": "2026-11-16T09:31:10Z",
1847            "tenant": TENANT,
1848            "signature": "test",
1849        })
1850    }
1851    fn certificate_leaf(c: &Value) -> Value {
1852        let mut l = json!({
1853            "kind": "certificate",
1854            "certificate_id": crate::certificate_id(c).unwrap(),
1855            "signer_key_id": c["signer_key_id"],
1856            "spec": c["spec"],
1857            "fitted_at": c["fitted_at"],
1858        });
1859        if c.get("tenant").is_some() {
1860            l["tenant"] = c["tenant"].clone();
1861        }
1862        l
1863    }
1864    fn ledger_leaf(seq: u64) -> Value {
1865        json!({
1866            "kind": "ledger_entry",
1867            "ledger_id": format!("ledger:{}", "ab".repeat(16)),
1868            "seq": seq,
1869            "entry": format!("sha256:{seq:064x}"),
1870        })
1871    }
1872
1873    /// A seven-leaf log whose leaf `at` is `leaf`, and a bundle for it cosigned as `cosigs`.
1874    fn bundle_for(leaf: Value, cert: Option<Value>, at: usize, cosigs: &[(u8, u64)]) -> Value {
1875        let mut leaves: Vec<Value> = (0..7).map(ledger_leaf).collect();
1876        leaves[at] = leaf;
1877        let hashes: Vec<Hash> = leaves
1878            .iter()
1879            .map(|l| leaf_hash(&Leaf::from_json(l).unwrap()))
1880            .collect();
1881        let root = root_hash(&hashes).unwrap();
1882        let mut b = json!({
1883            "spec": SPEC_BUNDLE,
1884            "log_id": LOG,
1885            "leaf_index": at,
1886            "leaf": leaves[at],
1887            "proof": audit_path(&hashes, at).unwrap().iter().map(|p| STANDARD.encode(p)).collect::<Vec<_>>(),
1888            "checkpoint": checkpoint(&note(LOG, 7, &root), cosigs),
1889        });
1890        if let Some(c) = cert {
1891            b["certificate"] = c;
1892        }
1893        b
1894    }
1895    fn bundle() -> Value {
1896        let c = certificate();
1897        bundle_for(certificate_leaf(&c), Some(c), 3, &[(0, 1_800_000_000)])
1898    }
1899    fn note_of(b: &Value) -> String {
1900        let cp = parse_checkpoint(b["checkpoint"].as_str().unwrap()).unwrap();
1901        cp.note_text
1902    }
1903
1904    fn refused(b: &Value, t: &LogTrust) -> ErrorName {
1905        verify_bundle(b, t).expect_err("expected a refusal").name
1906    }
1907
1908    /// The times written are the ones the 0.7.0 crate wrote (`chrono`'s `%Y-%m-%dT%H:%M:%SZ`).
1909    #[test]
1910    fn times_are_written_in_the_spec_form() {
1911        let cases: [(u64, &str); 9] = [
1912            (0, "1970-01-01T00:00:00Z"),
1913            (951_782_400, "2000-02-29T00:00:00Z"),
1914            (1_709_164_800, "2024-02-29T00:00:00Z"),
1915            (1_800_000_000, "2027-01-15T08:00:00Z"),
1916            (4_107_542_400, "2100-03-01T00:00:00Z"),
1917            (MAX_COSIGNATURE_TIME, "9999-12-31T23:59:59Z"),
1918            (MAX_COSIGNATURE_TIME + 1, "+10000-01-01T00:00:00Z"),
1919            (LAST_TIME_OF, "+262142-12-31T23:59:59Z"),
1920            (86_399, "1970-01-01T23:59:59Z"),
1921        ];
1922        for (secs, want) in cases {
1923            assert_eq!(time_of(secs), want, "{secs}");
1924        }
1925        for secs in [
1926            LAST_TIME_OF + 1,
1927            i64::MAX as u64,
1928            i64::MAX as u64 + 1,
1929            u64::MAX,
1930        ] {
1931            assert_eq!(time_of(secs), "", "{secs}");
1932        }
1933        // every written time up to the cosignature limit reads back as itself
1934        let mut secs = 0;
1935        while secs <= MAX_COSIGNATURE_TIME {
1936            let t = time_of(secs);
1937            assert!(time_ok(&t), "{t}");
1938            let back = crate::timestamp(&t).unwrap().unix_timestamp();
1939            assert_eq!(u64::try_from(back).unwrap(), secs, "{t}");
1940            secs += 9_876_543;
1941        }
1942    }
1943
1944    #[test]
1945    fn times_are_the_certificate_form_with_seconds_to_59() {
1946        assert!(time_ok("2026-12-31T23:59:59Z"));
1947        assert!(time_ok("0000-02-29T00:00:00Z"));
1948        for s in [
1949            "2026-12-31T23:59:60Z",
1950            "2026-12-31T23:59:61Z",
1951            "2023-02-29T00:00:00Z",
1952            "2026-12-31t23:59:59Z",
1953            "2026-12-31T23:59:59z",
1954            "2026-12-31T23:59:59+00:00",
1955            "2026-12-31T23:59:59.0Z",
1956            "",
1957        ] {
1958            assert!(!time_ok(s), "{s}");
1959        }
1960    }
1961
1962    #[test]
1963    fn a_good_bundle_verifies() {
1964        let v = verify_bundle(&bundle(), &trust(1, 1)).unwrap();
1965        assert_eq!(v.log_id, LOG);
1966        assert_eq!((v.tree_size, v.leaf_index), (7, 3));
1967        assert_eq!(v.kind, "certificate");
1968        assert_eq!(
1969            v.certificate_id,
1970            Some(crate::certificate_id(&certificate()).unwrap())
1971        );
1972        assert_eq!(v.witnesses.len(), 1);
1973        assert_eq!(v.t_proven, 1_800_000_000);
1974        assert_eq!(v.t_proven_time(), "2027-01-15T08:00:00Z");
1975        assert_eq!(v.backfilled(), Some(false));
1976        let j = v.to_json();
1977        assert_eq!(j["t_proven"], "2027-01-15T08:00:00Z");
1978        assert_eq!(
1979            (&j["backfilled"], &j["backfilled_by"]),
1980            (&json!(false), &json!([]))
1981        );
1982        assert_eq!(j["witnesses"][0]["name"], witness_name(0));
1983        // every index of the tree, other leaf kinds, and the bundle's JSON text round trip
1984        for at in 0..7 {
1985            let b = bundle_for(ledger_leaf(at as u64), None, at, &[(0, 5)]);
1986            let text = serde_json::to_string(&b).unwrap();
1987            let v = verify_bundle(&parse_ijson(&text).unwrap(), &trust(1, 1)).unwrap();
1988            assert_eq!(v.backfilled(), None);
1989            assert!(v.to_json().get("backfilled").is_none());
1990            assert_eq!((v.leaf_index, v.certificate_id), (at as u64, None));
1991        }
1992        let head = json!({"kind": "audit_head", "tenant": TENANT, "chain": "audit", "seq": 1,
1993            "digest": format!("sha256:{}", "0".repeat(64)), "observed_at": "2026-11-16T09:31:10Z"});
1994        assert!(verify_bundle(&bundle_for(head, None, 6, &[(0, 5)]), &trust(1, 1)).is_ok());
1995        let c14 = json!({"spec": "decision-certificate.v1.4", "signer_key_id": "ed25519:0c6e5b7d2a913f84",
1996            "fitted_at": "2026-11-16T09:31:10Z", "signature": "x"});
1997        let b = bundle_for(certificate_leaf(&c14), Some(c14), 0, &[(0, 5)]);
1998        assert!(verify_bundle(&b, &trust(1, 1)).is_ok());
1999    }
2000
2001    #[test]
2002    fn leaf_hash_is_rfc9162_over_the_jcs_bytes() {
2003        let leaf = Leaf::from_json(&ledger_leaf(7)).unwrap();
2004        let jcs = format!(
2005            "{{\"entry\":\"sha256:{:064x}\",\"kind\":\"ledger_entry\",\"ledger_id\":\"ledger:{}\",\"seq\":7}}",
2006            7,
2007            "ab".repeat(16)
2008        );
2009        assert_eq!(leaf.canonical(), jcs.as_bytes());
2010        let mut pre = vec![0u8];
2011        pre.extend(jcs.as_bytes());
2012        assert_eq!(leaf_hash(&leaf), <[u8; 32]>::from(Sha256::digest(&pre)));
2013        assert_ne!(
2014            leaf_hash(&leaf),
2015            <[u8; 32]>::from(Sha256::digest(jcs.as_bytes()))
2016        );
2017    }
2018
2019    #[test]
2020    fn trust_form() {
2021        assert_eq!(trust(3, 2).m(), 2);
2022        assert_eq!(trust(1, 1).policy(), Policy::Warn);
2023        let edits: Vec<Edit> = vec![
2024            Box::new(|t| t["spec"] = json!("decision-cert-inclusion.v1")),
2025            Box::new(|t| t["extra"] = json!(1)),
2026            Box::new(|t| t["m"] = json!(3)),
2027            Box::new(|t| t["m"] = json!(0)),
2028            Box::new(|t| t["m"] = json!(1.0)),
2029            Box::new(|t| t["policy"] = json!("loud")),
2030            Box::new(|t| t["tenant"] = json!("acme eu")),
2031            Box::new(|t| t["logs"] = json!([])),
2032            Box::new(|t| t["witnesses"] = json!([])),
2033            Box::new(|t| t["logs"][0]["key_id"] = json!("ed25519:0000000000000000")),
2034            Box::new(|t| t["logs"][0]["key_name"] = json!("a+b")),
2035            Box::new(|t| t["logs"][0]["log_id"] = json!("log:XYZ")),
2036            Box::new(|t| t["witnesses"][0]["extra"] = json!(1)),
2037            Box::new(|t| {
2038                // a small-order key (and its own id)
2039                let weak = [1u8]
2040                    .iter()
2041                    .chain([0u8; 31].iter())
2042                    .copied()
2043                    .collect::<Vec<_>>();
2044                t["witnesses"][0]["key"] = json!(URL_SAFE_NO_PAD.encode(&weak));
2045                t["witnesses"][0]["key_id"] = json!(format!(
2046                    "ed25519:{}",
2047                    &crate::hex(&Sha256::digest(&weak))[..16]
2048                ));
2049            }),
2050            Box::new(|t| {
2051                let w = t["witnesses"][0].clone();
2052                t["witnesses"].as_array_mut().unwrap().push(w);
2053            }),
2054            Box::new(|t| {
2055                let mut w = t["witnesses"][1].clone();
2056                w["name"] = t["witnesses"][0]["name"].clone();
2057                t["witnesses"][0] = w.clone();
2058            }),
2059            Box::new(|t| {
2060                t["witnesses"][0]["key"] = t["logs"][0]["key"].clone();
2061                t["witnesses"][0]["key_id"] = t["logs"][0]["key_id"].clone();
2062            }),
2063            Box::new(|t| {
2064                let mut l = t["logs"][0].clone();
2065                l["log_id"] = json!(OTHER_LOG);
2066                t["logs"].as_array_mut().unwrap().push(l);
2067            }),
2068        ];
2069        for (i, edit) in edits.iter().enumerate() {
2070            let mut t = trust_json(2, 1);
2071            edit(&mut t);
2072            let e = LogTrust::from_json(&t).expect_err(&format!("edit {i}"));
2073            assert_eq!(e.name, ErrorName::TrustForm, "edit {i}: {e}");
2074        }
2075    }
2076
2077    #[test]
2078    fn trust_cross_tenant() {
2079        let a = trust(1, 1);
2080        let mut other = trust_json(1, 1);
2081        other["tenant"] = json!("beta");
2082        let b = LogTrust::from_json(&other).unwrap();
2083        assert_eq!(
2084            check_tenants(&[a.clone(), b]).unwrap_err().name,
2085            ErrorName::TrustCrossTenant
2086        );
2087        // the same key under another log_id is still one log under two tenants
2088        other["logs"][0]["log_id"] = json!(OTHER_LOG);
2089        let b = LogTrust::from_json(&other).unwrap();
2090        assert_eq!(
2091            check_tenants(&[a.clone(), b]).unwrap_err().name,
2092            ErrorName::TrustCrossTenant
2093        );
2094        // a witness may serve several tenants
2095        let mut c = trust_json(1, 1);
2096        c["tenant"] = json!("gamma");
2097        c["logs"][0]["log_id"] = json!(OTHER_LOG);
2098        c["logs"][0]["key"] = json!(b64url(&key(2)));
2099        c["logs"][0]["key_id"] = json!(crate::key_id(&key(2).verifying_key()));
2100        assert!(check_tenants(&[a, LogTrust::from_json(&c).unwrap()]).is_ok());
2101    }
2102
2103    #[test]
2104    fn bundle_form() {
2105        let t = trust(1, 1);
2106        let edits: Vec<Edit> = vec![
2107            Box::new(|b| b["spec"] = json!("decision-cert-consistency.v1")),
2108            Box::new(|b| b["extra"] = json!(1)),
2109            Box::new(|b| {
2110                b.as_object_mut().unwrap().remove("proof");
2111            }),
2112            Box::new(|b| {
2113                b.as_object_mut().unwrap().remove("certificate");
2114            }),
2115            Box::new(|b| b["certificate"] = json!("not an object")),
2116            Box::new(|b| b["leaf_index"] = json!(3.0)),
2117            Box::new(|b| b["leaf_index"] = json!(-1)),
2118            Box::new(|b| b["leaf_index"] = json!(1u64 << 53)),
2119            Box::new(|b| b["log_id"] = json!("log:1")),
2120            Box::new(|b| b["leaf"] = json!("a leaf")),
2121            Box::new(|b| b["checkpoint"] = json!(7)),
2122            Box::new(|b| b["proof"] = json!(["AAAA"])),
2123            Box::new(|b| b["proof"] = json!(vec![STANDARD.encode([0u8; 32]); 65])),
2124            // a non-canonical base64 node hash: the last character's unused bits set
2125            Box::new(|b| {
2126                let mut s = STANDARD.encode([0u8; 32]);
2127                s.replace_range(42..43, "B");
2128                b["proof"][0] = json!(s);
2129            }),
2130        ];
2131        for (i, edit) in edits.iter().enumerate() {
2132            let mut b = bundle();
2133            edit(&mut b);
2134            assert_eq!(refused(&b, &t), ErrorName::BundleForm, "edit {i}");
2135        }
2136        // a certificate with a leaf of another kind
2137        let mut b = bundle_for(ledger_leaf(3), None, 3, &[(0, 5)]);
2138        b["certificate"] = certificate();
2139        assert_eq!(refused(&b, &t), ErrorName::BundleForm);
2140        // backfilled: true only, and only beside a certificate leaf
2141        for v in [json!(false), json!("true"), json!(1), json!(null)] {
2142            let mut b = bundle();
2143            b["backfilled"] = v;
2144            assert_eq!(refused(&b, &t), ErrorName::BundleForm);
2145        }
2146        let mut b = bundle_for(ledger_leaf(3), None, 3, &[(0, 5)]);
2147        b["backfilled"] = json!(true);
2148        assert_eq!(refused(&b, &t), ErrorName::BundleForm);
2149    }
2150
2151    #[test]
2152    fn backfilled_mark() {
2153        // the certificate's fitted_at is 2026-11-16T09:31:10Z
2154        let with_start = |start: Option<&str>| {
2155            let mut t = trust_json(1, 1);
2156            if let Some(s) = start {
2157                t["logs"][0]["started_at"] = json!(s);
2158            }
2159            LogTrust::from_json(&t).unwrap()
2160        };
2161        let mut marked = bundle();
2162        marked["backfilled"] = json!(true);
2163        for (b, start, by) in [
2164            (bundle(), None, vec![]),
2165            (marked.clone(), None, vec!["bundle"]),
2166            (bundle(), Some("2026-11-17T00:00:00Z"), vec!["started_at"]),
2167            (bundle(), Some("2026-11-16T09:31:10Z"), vec![]),
2168            (bundle(), Some("2026-11-01T00:00:00Z"), vec![]),
2169            (
2170                marked.clone(),
2171                Some("2026-11-17T00:00:00Z"),
2172                vec!["bundle", "started_at"],
2173            ),
2174            (marked, Some("2026-11-01T00:00:00Z"), vec!["bundle"]),
2175        ] {
2176            let v = verify_bundle(&b, &with_start(start)).unwrap();
2177            assert_eq!(v.backfilled(), Some(!by.is_empty()), "{start:?}");
2178            assert_eq!(v.backfilled_by, Some(by));
2179        }
2180        for bad in [
2181            json!("2026-11-17"),
2182            json!("2026-11-17T00:00:60Z"),
2183            json!(null),
2184            json!(1),
2185        ] {
2186            let mut t = trust_json(1, 1);
2187            t["logs"][0]["started_at"] = bad;
2188            assert_eq!(
2189                LogTrust::from_json(&t).unwrap_err().name,
2190                ErrorName::TrustForm
2191            );
2192        }
2193    }
2194
2195    #[test]
2196    fn leaf_form() {
2197        let t = trust(1, 1);
2198        let mut b = bundle_for(ledger_leaf(3), None, 3, &[(0, 5)]);
2199        b["leaf"]["kind"] = json!("receipt");
2200        assert_eq!(refused(&b, &t), ErrorName::LeafForm, "unknown kind");
2201        let edits: Vec<Edit> = vec![
2202            Box::new(|l| l["extra"] = json!(1)),
2203            Box::new(|l| {
2204                l.as_object_mut().unwrap().remove("fitted_at");
2205            }),
2206            Box::new(|l| {
2207                l.as_object_mut().unwrap().remove("tenant");
2208            }),
2209            Box::new(|l| l["spec"] = json!("decision-certificate.v1.4")),
2210            Box::new(|l| l["spec"] = json!("decision-certificate.v2")),
2211            Box::new(|l| l["fitted_at"] = json!("2026-11-16T09:31:60Z")),
2212            Box::new(|l| l["fitted_at"] = json!("2026-02-30T09:31:10Z")),
2213            Box::new(|l| l["certificate_id"] = json!("sha256:ABC")),
2214            Box::new(|l| l["signer_key_id"] = json!("ed25519:short")),
2215            Box::new(|l| l["tenant"] = json!("")),
2216        ];
2217        for (i, edit) in edits.iter().enumerate() {
2218            let mut b = bundle();
2219            edit(&mut b["leaf"]);
2220            assert_eq!(refused(&b, &t), ErrorName::LeafForm, "edit {i}");
2221        }
2222        for bad in [
2223            json!({"kind": "ledger_entry", "ledger_id": "ledger:x", "seq": 0, "entry": format!("sha256:{}", "0".repeat(64))}),
2224            json!({"kind": "keyset", "keyset_id": format!("keyset:{}", "0".repeat(32)), "seq": 1.5, "keyset": format!("sha256:{}", "0".repeat(64))}),
2225            json!({"kind": "attestation", "attestation": format!("sha256:{}", "0".repeat(64))}),
2226            json!({"kind": "audit_head", "tenant": TENANT, "chain": "a", "seq": 0, "digest": format!("sha256:{}", "0".repeat(64)), "observed_at": "2026-11-16T09:31:10Z"}),
2227        ] {
2228            assert_eq!(
2229                Leaf::from_json(&bad).unwrap_err().name,
2230                ErrorName::LeafForm,
2231                "{bad}"
2232            );
2233        }
2234    }
2235
2236    #[test]
2237    fn leaf_mismatch() {
2238        let t = trust(1, 1);
2239        // another certificate's leaf
2240        let mut other = certificate();
2241        other["fitted_at"] = json!("2026-11-16T09:31:11Z");
2242        let mut b = bundle();
2243        b["leaf"] = certificate_leaf(&other);
2244        assert_eq!(refused(&b, &t), ErrorName::LeafMismatch);
2245        // a member that does not match its certificate (with the right id)
2246        for (m, v) in [
2247            ("signer_key_id", json!("ed25519:0000000000000000")),
2248            ("fitted_at", json!("2026-01-01T00:00:00Z")),
2249            ("tenant", json!("beta")),
2250        ] {
2251            let mut b = bundle();
2252            b["leaf"][m] = v;
2253            assert_eq!(refused(&b, &t), ErrorName::LeafMismatch, "{m}");
2254        }
2255    }
2256
2257    #[test]
2258    fn tenant_mismatch() {
2259        let t = trust(1, 1);
2260        let mut c = certificate();
2261        c["tenant"] = json!("beta");
2262        let b = bundle_for(certificate_leaf(&c), Some(c), 3, &[(0, 5)]);
2263        assert_eq!(refused(&b, &t), ErrorName::TenantMismatch);
2264        let head = json!({"kind": "audit_head", "tenant": "beta", "chain": "audit", "seq": 1,
2265            "digest": format!("sha256:{}", "0".repeat(64)), "observed_at": "2026-11-16T09:31:10Z"});
2266        assert_eq!(
2267            refused(&bundle_for(head, None, 0, &[(0, 5)]), &t),
2268            ErrorName::TenantMismatch
2269        );
2270    }
2271
2272    #[test]
2273    fn unknown_log_and_origin_mismatch() {
2274        let t = trust(1, 1);
2275        let mut b = bundle();
2276        b["log_id"] = json!(OTHER_LOG);
2277        assert_eq!(refused(&b, &t), ErrorName::UnknownLog);
2278        // the checkpoint of another log under this bundle's log_id
2279        let mut b = bundle();
2280        let text = b["checkpoint"].as_str().unwrap().replace(LOG, OTHER_LOG);
2281        b["checkpoint"] = json!(text);
2282        assert_eq!(refused(&b, &t), ErrorName::OriginMismatch);
2283    }
2284
2285    #[test]
2286    fn checkpoint_form() {
2287        let good = bundle()["checkpoint"].as_str().unwrap().to_string();
2288        let cp = parse_checkpoint(&good).unwrap();
2289        assert_eq!((cp.origin.as_str(), cp.tree_size), (LOG, 7));
2290        let sig_lines: Vec<&str> = good.split_inclusive('\n').skip(4).collect();
2291        let note_text = cp.note_text.clone();
2292        let root = note_text.lines().nth(2).unwrap().to_string();
2293        let mut noncanonical = root.clone();
2294        let last = noncanonical.len() - 2;
2295        let c = noncanonical.as_bytes()[last];
2296        let bumped = if c == b'/' { '+' } else { (c + 1) as char };
2297        noncanonical.replace_range(last..last + 1, &bumped.to_string());
2298        let cases: Vec<String> = vec![
2299            good.strip_suffix('\n').unwrap().to_string(), // no final newline
2300            good.replacen('\n', "\nextra\n", 1),          // an extra text line
2301            good.replacen(&format!("{root}\n\n"), &format!("{root}\n"), 1), // no blank line
2302            good.replace(&root, &noncanonical),           // non-canonical base64 root
2303            good.replacen("\n7\n", "\n07\n", 1),          // a leading zero
2304            good.replacen("\n7\n", "\n0\n", 1),           // size 0
2305            good.replacen("\n7\n", "\n18446744073709551616\n", 1), // over 2^64 - 1
2306            good.replacen("\n7\n", "\n+7\n", 1),
2307            good.replace('\n', "\r\n"),                 // carriage returns
2308            good.replacen(LOG, &format!("{LOG}\t"), 1), // a tab
2309            note_text.clone() + "\n",                   // no signature line
2310            good.replacen('\u{2014}', "-", 1),          // not an em dash
2311            good.replacen(&format!("\u{2014} {LOG} "), "\u{2014} a+b ", 1), // + in a key name
2312            good.clone() + "\n",                        // a trailing blank line
2313            good.clone() + sig_lines[0],                // the log's line twice
2314            good.clone() + sig_lines[1],                // one witness's line twice
2315            format!("{note_text}\n{}", "\u{2014} x AAAA\n"), // a value under 5 bytes
2316            format!("{note_text}\n{}", "\u{2014} x AAAAAAAA\n".repeat(101)),
2317        ];
2318        for (i, c) in cases.iter().enumerate() {
2319            let e = parse_checkpoint(c).expect_err(&format!("case {i}: {c:?}"));
2320            assert_eq!(e.name, ErrorName::CheckpointForm, "case {i}");
2321            let mut b = bundle();
2322            b["checkpoint"] = json!(c);
2323            assert_eq!(
2324                refused(&b, &trust(1, 1)),
2325                ErrorName::CheckpointForm,
2326                "case {i}"
2327            );
2328        }
2329        // two lines with one name and different key IDs are two keys
2330        let mut b = bundle();
2331        let other = cosig_line(&witness_name(0), &key(99), &note_text, 5);
2332        b["checkpoint"] = json!(good.clone() + &other);
2333        assert!(verify_bundle(&b, &trust(1, 1)).is_ok());
2334    }
2335
2336    #[test]
2337    fn bad_proof() {
2338        let t = trust(1, 1);
2339        let mut b = bundle();
2340        b["leaf_index"] = json!(4);
2341        assert_eq!(refused(&b, &t), ErrorName::BadProof);
2342        let mut b = bundle();
2343        b["leaf_index"] = json!(7);
2344        assert_eq!(refused(&b, &t), ErrorName::BadProof);
2345        let mut b = bundle();
2346        b["proof"].as_array_mut().unwrap().pop();
2347        assert_eq!(refused(&b, &t), ErrorName::BadProof);
2348        let mut b = bundle();
2349        b["proof"]
2350            .as_array_mut()
2351            .unwrap()
2352            .push(json!(STANDARD.encode([7u8; 32])));
2353        assert_eq!(refused(&b, &t), ErrorName::BadProof);
2354        // a path for another tree size: the seven-leaf path, an eight-leaf checkpoint
2355        let mut b = bundle();
2356        let mut leaves: Vec<Value> = (0..8).map(ledger_leaf).collect();
2357        leaves[3] = b["leaf"].clone();
2358        let hashes: Vec<Hash> = leaves
2359            .iter()
2360            .map(|l| leaf_hash(&Leaf::from_json(l).unwrap()))
2361            .collect();
2362        let root8 = root_hash(&hashes).unwrap();
2363        b["checkpoint"] = json!(checkpoint(&note(LOG, 8, &root8), &[(0, 5)]));
2364        assert_eq!(refused(&b, &t), ErrorName::BadProof);
2365        b["proof"] = json!(audit_path(&hashes, 3)
2366            .unwrap()
2367            .iter()
2368            .map(|p| STANDARD.encode(p))
2369            .collect::<Vec<_>>());
2370        assert!(verify_bundle(&b, &t).is_ok());
2371    }
2372
2373    #[test]
2374    fn log_signatures() {
2375        let t = trust(1, 1);
2376        let b = bundle();
2377        let n = note_of(&b);
2378        let w = cosig_line(&witness_name(0), &witness_key(0), &n, 5);
2379        let with = |log: String| json!(format!("{n}\n{log}{w}"));
2380        let mut b2 = b.clone();
2381        // no line from the log's key: one from another key under its name, none at all
2382        b2["checkpoint"] = with(log_line(LOG, &key(42), &n));
2383        assert_eq!(refused(&b2, &t), ErrorName::LogSignatureMissing);
2384        b2["checkpoint"] = json!(format!("{n}\n{w}"));
2385        assert_eq!(refused(&b2, &t), ErrorName::LogSignatureMissing);
2386        // the log's line over another note
2387        b2["checkpoint"] = with(log_line(LOG, &log_key(), &note(LOG, 7, &[0; 32])));
2388        assert_eq!(refused(&b2, &t), ErrorName::BadLogSignature);
2389        // the log's key ID with a value of the wrong length
2390        let mut v = c2sp_key_hash(LOG, SIG_TYPE_ED25519, &log_key().verifying_key()).to_vec();
2391        v.extend([0u8; 10]);
2392        b2["checkpoint"] = with(format!("\u{2014} {LOG} {}\n", STANDARD.encode(v)));
2393        assert_eq!(refused(&b2, &t), ErrorName::BadLogSignature);
2394    }
2395
2396    #[test]
2397    fn cosignatures() {
2398        let b = bundle();
2399        let n = note_of(&b);
2400        let log = log_line(LOG, &log_key(), &n);
2401        let with = |lines: &[String]| json!(format!("{n}\n{log}{}", lines.concat()));
2402        let mut b2 = b.clone();
2403        // a cosignature over another checkpoint
2404        let other = note(LOG, 7, &[0; 32]);
2405        b2["checkpoint"] = with(&[cosig_line(&witness_name(0), &witness_key(0), &other, 5)]);
2406        assert_eq!(refused(&b2, &trust(1, 1)), ErrorName::BadCosignature);
2407        // a time past 9999-12-31T23:59:59Z
2408        b2["checkpoint"] = with(&[cosig_line(
2409            &witness_name(0),
2410            &witness_key(0),
2411            &n,
2412            MAX_COSIGNATURE_TIME + 1,
2413        )]);
2414        assert_eq!(refused(&b2, &trust(1, 1)), ErrorName::BadCosignature);
2415        b2["checkpoint"] = with(&[cosig_line(
2416            &witness_name(0),
2417            &witness_key(0),
2418            &n,
2419            MAX_COSIGNATURE_TIME,
2420        )]);
2421        assert_eq!(
2422            verify_bundle(&b2, &trust(1, 1)).unwrap().t_proven_time(),
2423            "9999-12-31T23:59:59Z"
2424        );
2425        // a trusted witness's line that fails is refused even when m others verify
2426        b2["checkpoint"] = with(&[
2427            cosig_line(&witness_name(0), &witness_key(0), &n, 5),
2428            cosig_line(&witness_name(1), &witness_key(1), &other, 5),
2429        ]);
2430        assert_eq!(refused(&b2, &trust(2, 1)), ErrorName::BadCosignature);
2431    }
2432
2433    #[test]
2434    fn too_few_cosignatures_and_untrusted_witnesses() {
2435        let b = bundle();
2436        let n = note_of(&b);
2437        let log = log_line(LOG, &log_key(), &n);
2438        let with = |lines: &[String]| json!(format!("{n}\n{log}{}", lines.concat()));
2439        let untrusted = cosig_line("witness.example/other", &key(77), &n, 1);
2440        let w0 = cosig_line(&witness_name(0), &witness_key(0), &n, 9);
2441        let mut b2 = b.clone();
2442        // no cosignature; only an untrusted witness's (ignored, so none)
2443        b2["checkpoint"] = with(&[]);
2444        assert_eq!(refused(&b2, &trust(1, 1)), ErrorName::TooFewCosignatures);
2445        b2["checkpoint"] = with(std::slice::from_ref(&untrusted));
2446        assert_eq!(refused(&b2, &trust(1, 1)), ErrorName::TooFewCosignatures);
2447        // an untrusted line beside a trusted one is ignored: one counted, at its own time
2448        b2["checkpoint"] = with(&[untrusted.clone(), w0.clone()]);
2449        let v = verify_bundle(&b2, &trust(1, 1)).unwrap();
2450        assert_eq!((v.witnesses.len(), v.t_proven), (1, 9));
2451        // m = 2 with one trusted cosignature and one untrusted
2452        assert_eq!(refused(&b2, &trust(2, 2)), ErrorName::TooFewCosignatures);
2453        // a trusted witness's name with another key, and its key under another name: ignored
2454        b2["checkpoint"] = with(&[
2455            w0,
2456            cosig_line(&witness_name(1), &key(78), &n, 1),
2457            cosig_line("witness.example/renamed", &witness_key(1), &n, 1),
2458        ]);
2459        assert_eq!(refused(&b2, &trust(2, 2)), ErrorName::TooFewCosignatures);
2460    }
2461
2462    #[test]
2463    fn t_proven_is_the_mth_earliest_counted_time() {
2464        let c = certificate();
2465        let b = bundle_for(
2466            certificate_leaf(&c),
2467            Some(c),
2468            3,
2469            &[(0, 300), (1, 100), (2, 200)],
2470        );
2471        let at = |m| verify_bundle(&b, &trust(3, m)).unwrap();
2472        assert_eq!(at(1).t_proven, 100);
2473        assert_eq!(at(2).t_proven, 200);
2474        assert_eq!(at(3).t_proven, 300);
2475        let names: Vec<_> = at(2).witnesses.into_iter().map(|w| w.time).collect();
2476        assert_eq!(names, [100, 200, 300]);
2477        // two of three cosign, m = 2: the later of the two
2478        let c = certificate();
2479        let b = bundle_for(certificate_leaf(&c), Some(c), 3, &[(0, 300), (2, 200)]);
2480        assert_eq!(verify_bundle(&b, &trust(3, 2)).unwrap().t_proven, 300);
2481        assert_eq!(refused(&b, &trust(3, 3)), ErrorName::TooFewCosignatures);
2482    }
2483
2484    #[test]
2485    fn checks_run_in_order() {
2486        // a bundle broken at checks 5 and 9: check 5's error
2487        let t = trust(1, 1);
2488        let mut c = certificate();
2489        c["tenant"] = json!("beta");
2490        let mut b = bundle_for(certificate_leaf(&c), Some(c), 3, &[(0, 5)]);
2491        b["leaf_index"] = json!(2);
2492        assert_eq!(refused(&b, &t), ErrorName::TenantMismatch);
2493        // broken at checks 9 and 10: bad_proof
2494        let mut b = bundle();
2495        let n = note_of(&b);
2496        b["leaf_index"] = json!(2);
2497        b["checkpoint"] = json!(format!(
2498            "{n}\n{}",
2499            cosig_line(&witness_name(0), &witness_key(0), &n, 5)
2500        ));
2501        assert_eq!(refused(&b, &t), ErrorName::BadProof);
2502    }
2503
2504    fn consistency_doc(older: usize, newer: usize) -> Value {
2505        let leaves: Vec<Hash> = (0..9)
2506            .map(|i| leaf_hash(&Leaf::from_json(&ledger_leaf(i)).unwrap()))
2507            .collect();
2508        let r = |n: usize| root_hash(&leaves[..n]).unwrap();
2509        json!({
2510            "spec": SPEC_CONSISTENCY,
2511            "log_id": LOG,
2512            "older": checkpoint(&note(LOG, older as u64, &r(older)), &[]),
2513            "newer": checkpoint(&note(LOG, newer as u64, &r(newer)), &[(0, 5)]),
2514            "proof": consistency_path(&leaves[..newer], older).unwrap().iter().map(|p| STANDARD.encode(p)).collect::<Vec<_>>(),
2515        })
2516    }
2517
2518    #[test]
2519    fn consistency() {
2520        let t = trust(1, 1);
2521        for (m, n) in [(1, 2), (3, 7), (7, 8), (4, 4), (1, 9)] {
2522            let v = verify_consistency(&consistency_doc(m, n), &t).unwrap();
2523            assert_eq!(
2524                (v.log_id.as_str(), v.older_size, v.newer_size),
2525                (LOG, m as u64, n as u64)
2526            );
2527        }
2528        let err = |d: &Value| verify_consistency(d, &t).unwrap_err().name;
2529        // newer smaller than older
2530        let mut d = consistency_doc(3, 7);
2531        let older = d["older"].clone();
2532        d["older"] = d["newer"].clone();
2533        d["newer"] = older;
2534        assert_eq!(err(&d), ErrorName::SizeRegression);
2535        // one size, two roots
2536        let mut d = consistency_doc(4, 4);
2537        d["newer"] = json!(checkpoint(&note(LOG, 4, &[9; 32]), &[]));
2538        d["proof"] = json!([]);
2539        assert_eq!(err(&d), ErrorName::SplitView);
2540        // one size, one root, a path
2541        let mut d = consistency_doc(4, 4);
2542        d["proof"] = json!([STANDARD.encode([1u8; 32])]);
2543        assert_eq!(err(&d), ErrorName::BadConsistencyProof);
2544        // a newer tree that does not extend the older
2545        let mut d = consistency_doc(3, 7);
2546        d["newer"] = json!(checkpoint(&note(LOG, 7, &[9; 32]), &[]));
2547        assert_eq!(err(&d), ErrorName::BadConsistencyProof);
2548        let mut d = consistency_doc(3, 7);
2549        d["proof"].as_array_mut().unwrap().pop();
2550        assert_eq!(err(&d), ErrorName::BadConsistencyProof);
2551        // form, log, checkpoint and signature
2552        let mut d = consistency_doc(3, 7);
2553        d["spec"] = json!(SPEC_BUNDLE);
2554        assert_eq!(err(&d), ErrorName::ConsistencyForm);
2555        let mut d = consistency_doc(3, 7);
2556        d["extra"] = json!(1);
2557        assert_eq!(err(&d), ErrorName::ConsistencyForm);
2558        let mut d = consistency_doc(3, 7);
2559        d["log_id"] = json!(OTHER_LOG);
2560        assert_eq!(err(&d), ErrorName::UnknownLog);
2561        let mut d = consistency_doc(3, 7);
2562        d["older"] = json!(d["older"].as_str().unwrap().trim_end());
2563        assert_eq!(err(&d), ErrorName::CheckpointForm);
2564        let mut d = consistency_doc(3, 7);
2565        d["newer"] = json!(d["newer"].as_str().unwrap().replace(LOG, OTHER_LOG));
2566        assert_eq!(err(&d), ErrorName::OriginMismatch);
2567        let mut d = consistency_doc(3, 7);
2568        let n = note(LOG, 3, &[1; 32]);
2569        d["older"] = json!(format!("{n}\n{}", log_line(LOG, &key(42), &n)));
2570        assert_eq!(err(&d), ErrorName::LogSignatureMissing);
2571        let mut d = consistency_doc(3, 7);
2572        let n = parse_checkpoint(d["older"].as_str().unwrap())
2573            .unwrap()
2574            .note_text;
2575        d["older"] = json!(format!(
2576            "{n}\n{}",
2577            log_line(LOG, &log_key(), "another note\n1\nAA==\n")
2578        ));
2579        assert_eq!(err(&d), ErrorName::BadLogSignature);
2580    }
2581
2582    #[test]
2583    fn policy() {
2584        let ok = || Some(Ok(verify_bundle(&bundle(), &trust(1, 1)).unwrap()));
2585        let failed = || Some(Err(InclusionError::new(ErrorName::BadProof, "x")));
2586        use PolicyOutcome::*;
2587        assert_eq!(apply_policy(None, Policy::Off), Load(None));
2588        assert_eq!(apply_policy(ok(), Policy::Off), Load(None));
2589        assert_eq!(apply_policy(failed(), Policy::Off), Load(None));
2590        assert!(
2591            matches!(apply_policy(None, Policy::Warn), LoadWithWarning(e) if e.name == ErrorName::InclusionMissing)
2592        );
2593        assert!(matches!(apply_policy(ok(), Policy::Warn), Load(Some(_))));
2594        assert!(
2595            matches!(apply_policy(failed(), Policy::Warn), Refuse(e) if e.name == ErrorName::BadProof)
2596        );
2597        assert!(
2598            matches!(apply_policy(None, Policy::Refuse), Refuse(e) if e.name == ErrorName::InclusionMissing)
2599        );
2600        assert!(matches!(apply_policy(ok(), Policy::Refuse), Load(Some(_))));
2601        assert!(
2602            matches!(apply_policy(failed(), Policy::Refuse), Refuse(e) if e.name == ErrorName::BadProof)
2603        );
2604    }
2605
2606    #[test]
2607    fn ijson() {
2608        assert!(parse_ijson(r#"{"a": 1, "b": {"c": [1, 2.5, null, true, "x"]}}"#).is_ok());
2609        assert!(parse_ijson(r#"{"a": 1, "a": 1}"#).is_err());
2610        assert!(parse_ijson(r#"{"a": [{"b": 1, "b": 2}]}"#).is_err());
2611        assert!(parse_ijson(r#""\ud800""#).is_err());
2612        assert!(parse_ijson(r#"{"leaf_index": 1e0}"#).unwrap()["leaf_index"]
2613            .as_u64()
2614            .is_none());
2615        let names: BTreeSet<_> = ErrorName::ALL.iter().map(|e| e.as_str()).collect();
2616        assert_eq!(names.len(), 19);
2617    }
2618}