Skip to main content

echovalidum_receipt/
lib.rs

1//! Check an Echovalidum receipt: on your own machine, in your browser as WebAssembly, or anywhere
2//! Rust runs.
3//!
4//! A receipt is an HTTP response echovalidum.com signed with ML-DSA (FIPS 204), the post-quantum
5//! signature standard, as an HTTP message signature (RFC 9421): a `Signature-Input` that names the
6//! parts it signs, a `Signature`, and a `Content-Digest` of the bytes. A visitor's card on the site
7//! holds one: a receipt for their visit. [Echovalidum Receipts 1.0](spec), for verifiers, says
8//! exactly what a receipt carries and how it is checked; this crate is that check:
9//!
10//! 1. the signature labelled `echovalidum`, tagged `echovalidum-content`, covering the five parts a
11//!    receipt signs;
12//! 2. the SHA-256 of its bytes against its `Content-Digest`;
13//! 3. the key, picked from the site's key directory by its thumbprint (RFC 7638), which the
14//!    signature names as its `keyid`, and in use when the receipt was signed;
15//! 4. the ML-DSA signature over the text rebuilt from the parts its `Signature-Input` names;
16//!
17//! and works out the receipt's number, which the visitor's card shows: the first 40 bits of the
18//! SHA-256 of its signature, in Crockford's base 32. When a check fails, [`Check::problems`] says
19//! which, each a [`Problem`] with a code the conformance vectors use and a reason in plain words.
20//!
21//! ```
22//! use echovalidum_receipt::{Directory, Problem, Response};
23//!
24//! // A receipt as your card keeps it (here, made up and unsigned), and the site's key directory as
25//! // /.well-known/http-message-signatures-directory publishes it.
26//! let headers = [("content-type", "application/json"), ("content-digest", "sha-256=:AAAA:"),
27//!                ("signature-input", "echovalidum=(\"@status\");created=1;keyid=\"abc\";tag=\"echovalidum-content\""),
28//!                ("signature", "echovalidum=:AAAA:")];
29//! let receipt = Response { status: 200, authority: "www.echovalidum.com", path: "/attest", headers: &headers, body: b"{}" };
30//! let directory = Directory::from_json(r#"{"keys": [{"kty": "AKP", "alg": "ML-DSA-65", "pub": "AAAA"}]}"#).unwrap();
31//!
32//! let found = directory.check(&receipt);
33//! assert!(!found.ok());
34//! assert_eq!(found.problems, [Problem::Uncovered]);   // made up: it signs only its status
35//! for why in found.why() {
36//!     println!("{why}");
37//! }
38//! ```
39//!
40//! [`check`] does the same with one key in hand, and [`Check::lines`] says what My Card prints.
41//! [`cite`] checks a citation, a receipt that proves a quote is on a page of the site (Echovalidum
42//! Citations 1.0). [`keylog`] checks the site's key log (Echovalidum Key Log 1.0), the public,
43//! append-only record of every key it signs with, and carries the log as it stood when this version
44//! was published, so a key the site's directory lists can be checked against a copy nobody can
45//! rewrite. It
46//! only verifies: nothing here signs, holds a secret or draws a random number, so it builds for
47//! `wasm32-unknown-unknown` as it is. My Card on echovalidum.com runs it there, and the program it
48//! makes of a visitor's card runs it natively, and the two must print the same lines.
49
50#![forbid(unsafe_code)]
51
52use sha2::{Digest, Sha256};
53
54#[doc = include_str!("../SPEC.md")]
55pub mod spec {
56    #[doc = include_str!("../CITATIONS.md")]
57    pub mod citations {}
58    #[doc = include_str!("../KEYLOG.md")]
59    pub mod keylog {}
60}
61
62pub mod cite;
63pub mod keylog;
64
65/// The label of a receipt's signature, in `Signature-Input` and `Signature`.
66pub const LABEL: &str = "echovalidum";
67/// The tag a receipt's signature carries: Echovalidum Receipts 1.x.
68pub const TAG: &str = "echovalidum-content";
69/// The parts a receipt's signature covers, in order, as `Signature-Input` serializes them.
70pub const COMPONENTS: [&str; 5] = ["\"@status\"", "\"content-type\"", "\"content-digest\"", "\"@authority\";req", "\"@path\";req"];
71/// The ML-DSA levels a receipt's key may have.
72pub const ALGORITHMS: [&str; 3] = ["ML-DSA-44", "ML-DSA-65", "ML-DSA-87"];
73
74/// A signed response as it arrived: its status, the host and path it answered, its headers (names
75/// in any case, a name more than once as more than one line) and its bytes.
76#[derive(Debug, Clone, Copy)]
77pub struct Response<'a> {
78    pub status: u16,
79    pub authority: &'a str,
80    pub path: &'a str,
81    pub headers: &'a [(&'a str, &'a str)],
82    pub body: &'a [u8],
83}
84
85impl Response<'_> {
86    /// A header's first value, by name in any case, or "" when it isn't there.
87    pub fn header(&self, name: &str) -> &str {
88        self.headers.iter().find(|h| h.0.eq_ignore_ascii_case(name)).map_or("", |h| h.1)
89    }
90
91    /// A header field as RFC 9421 reads it: each line's value trimmed, lines joined by ", ";
92    /// `None` when it isn't there.
93    pub fn field(&self, name: &str) -> Option<String> {
94        let values: Vec<&str> = self.headers.iter().filter(|h| h.0.eq_ignore_ascii_case(name)).map(|h| h.1.trim_matches([' ', '\t'])).collect();
95        (!values.is_empty()).then(|| values.join(", "))
96    }
97}
98
99/// A public key as a key directory publishes it: an AKP JSON Web Key's `alg` (`ML-DSA-44`,
100/// `ML-DSA-65` or `ML-DSA-87`) and `pub` (base64url).
101#[derive(Debug, Clone, Copy)]
102pub struct Key<'a> {
103    pub alg: &'a str,
104    pub public: &'a str,
105}
106
107/// A key in a key directory: an AKP JSON Web Key, and when it may sign, if the directory says.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct DirectoryKey {
110    /// Its key type: `AKP` for ML-DSA.
111    pub kty: String,
112    /// Its algorithm.
113    pub alg: String,
114    /// The public key (`pub`, base64url).
115    pub public: String,
116    /// Its `kid`, if it has one. A receipt's key is picked by thumbprint, never by `kid`.
117    pub kid: Option<String>,
118    /// Not before (`nbf`): the first moment it signs, in seconds since 1970.
119    pub nbf: Option<i64>,
120    /// Expires (`exp`): the last moment it signs, in seconds since 1970.
121    pub exp: Option<i64>,
122}
123
124impl DirectoryKey {
125    /// Its thumbprint (RFC 7638), which a receipt's `keyid` names.
126    pub fn thumbprint(&self) -> String {
127        jwk_thumbprint(&self.alg, &self.kty, &self.public)
128    }
129}
130
131/// A site's key directory, as `/.well-known/http-message-signatures-directory` serves it.
132#[derive(Debug, Clone, Default, PartialEq, Eq)]
133pub struct Directory {
134    /// Its keys, in order. Entries that aren't keys (no `kty`, `alg` or `pub` string, or an `nbf`
135    /// or `exp` that isn't a whole number) are left out.
136    pub keys: Vec<DirectoryKey>,
137}
138
139/// Why a key directory couldn't be read.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum DirectoryError {
142    /// It isn't JSON.
143    NotJson,
144    /// It is, but has no `keys` list.
145    NoKeys,
146}
147
148impl std::fmt::Display for DirectoryError {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        f.write_str(match self {
151            DirectoryError::NotJson => "the key directory isn't JSON",
152            DirectoryError::NoKeys => "the key directory has no \"keys\" list",
153        })
154    }
155}
156
157impl std::error::Error for DirectoryError {}
158
159impl Directory {
160    /// A key directory from its JSON: `{"keys": [...]}`.
161    pub fn from_json(text: &str) -> Result<Directory, DirectoryError> {
162        let value = json::parse(text).ok_or(DirectoryError::NotJson)?;
163        let keys = value.get("keys").and_then(json::Value::as_array).ok_or(DirectoryError::NoKeys)?;
164        let whole = |v: Option<&json::Value>| -> Result<Option<i64>, ()> {
165            match v {
166                None => Ok(None),
167                Some(json::Value::Number(n)) if n.fract() == 0.0 && n.abs() < 9.0e15 => Ok(Some(*n as i64)),
168                Some(_) => Err(()),
169            }
170        };
171        let keys = keys
172            .iter()
173            .filter_map(|k| {
174                let text = |name: &str| k.get(name).and_then(json::Value::as_str).map(str::to_string);
175                Some(DirectoryKey {
176                    kty: text("kty")?,
177                    alg: text("alg")?,
178                    public: text("pub")?,
179                    kid: text("kid"),
180                    nbf: whole(k.get("nbf")).ok()?,
181                    exp: whole(k.get("exp")).ok()?,
182                })
183            })
184            .collect();
185        Ok(Directory { keys })
186    }
187
188    /// The key a `keyid` names: the first AKP key whose thumbprint it is.
189    pub fn find(&self, keyid: &str) -> Option<&DirectoryKey> {
190        self.keys.iter().find(|k| k.kty == "AKP" && k.thumbprint() == keyid)
191    }
192
193    /// Check a receipt with this directory, as Echovalidum Receipts 1.0 says.
194    pub fn check(&self, response: &Response<'_>) -> Check {
195        examine(response, &self.keys, false)
196    }
197}
198
199/// Why a receipt doesn't check out, in the order [Echovalidum Receipts 1.0](spec) checks.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
201pub enum Problem {
202    /// No signature labelled `echovalidum`, in `Signature-Input` and `Signature` both.
203    NotSigned,
204    /// Its signature headers can't be read as a receipt's.
205    Malformed,
206    /// Its signature isn't tagged `echovalidum-content`: it isn't a receipt.
207    NotAReceipt,
208    /// Its signature doesn't cover exactly the five parts a receipt signs, in order.
209    Uncovered,
210    /// A header its signature covers isn't there.
211    MissingHeader,
212    /// Its `Content-Digest` isn't one SHA-256 digest.
213    UnsupportedDigest,
214    /// The SHA-256 of its bytes isn't its `Content-Digest`: the bytes were changed.
215    DigestMismatch,
216    /// No key has the thumbprint its signature names.
217    UnknownKey,
218    /// The key it names isn't ML-DSA-44, -65 or -87.
219    UnsupportedAlgorithm,
220    /// It was signed when its key, says the directory, wasn't in use.
221    KeyNotValidThen,
222    /// Its signature doesn't verify with that key.
223    BadSignature,
224}
225
226impl Problem {
227    /// Every problem, in the order they're checked and listed.
228    pub const ALL: [Problem; 11] = [
229        Problem::NotSigned,
230        Problem::Malformed,
231        Problem::NotAReceipt,
232        Problem::Uncovered,
233        Problem::MissingHeader,
234        Problem::UnsupportedDigest,
235        Problem::DigestMismatch,
236        Problem::UnknownKey,
237        Problem::UnsupportedAlgorithm,
238        Problem::KeyNotValidThen,
239        Problem::BadSignature,
240    ];
241
242    /// Its code, as the specification and its conformance vectors name it.
243    pub fn code(self) -> &'static str {
244        match self {
245            Problem::NotSigned => "not-signed",
246            Problem::Malformed => "malformed",
247            Problem::NotAReceipt => "not-a-receipt",
248            Problem::Uncovered => "uncovered",
249            Problem::MissingHeader => "missing-header",
250            Problem::UnsupportedDigest => "unsupported-digest",
251            Problem::DigestMismatch => "digest-mismatch",
252            Problem::UnknownKey => "unknown-key",
253            Problem::UnsupportedAlgorithm => "unsupported-algorithm",
254            Problem::KeyNotValidThen => "key-not-valid-then",
255            Problem::BadSignature => "bad-signature",
256        }
257    }
258
259    /// The problem a code names.
260    pub fn from_code(code: &str) -> Option<Problem> {
261        Problem::ALL.into_iter().find(|p| p.code() == code)
262    }
263
264    /// Why, in plain words.
265    pub fn explain(self) -> &'static str {
266        match self {
267            Problem::NotSigned => "It carries no signature labelled echovalidum, so it isn't a signed receipt.",
268            Problem::Malformed => "Its Signature-Input or Signature can't be read as a receipt's.",
269            Problem::NotAReceipt => "Its signature isn't tagged echovalidum-content: it's another kind of signature, not a receipt.",
270            Problem::Uncovered => "Its signature doesn't cover exactly the five parts a receipt signs: its status, Content-Type and Content-Digest, and the address it answered.",
271            Problem::MissingHeader => "A header its signature covers is missing, so what was signed can't be rebuilt.",
272            Problem::UnsupportedDigest => "Its Content-Digest isn't a single SHA-256 digest.",
273            Problem::DigestMismatch => "The SHA-256 of its bytes doesn't match its Content-Digest: the bytes were changed.",
274            Problem::UnknownKey => "No key in the site's key directory has the thumbprint its signature names.",
275            Problem::UnsupportedAlgorithm => "The key it names isn't an ML-DSA-44, ML-DSA-65 or ML-DSA-87 key.",
276            Problem::KeyNotValidThen => "It was signed at a time the key directory says its key wasn't in use.",
277            Problem::BadSignature => "Its signature doesn't verify with its key: what was signed isn't what it shows.",
278        }
279    }
280}
281
282impl std::fmt::Display for Problem {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.write_str(self.code())
285    }
286}
287
288/// The text a signature covers, rebuilt from a response as RFC 9421 says.
289#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct SignatureBase {
291    /// The signature's label in `Signature-Input` and `Signature`.
292    pub label: String,
293    /// How many of the response's parts it covers.
294    pub parts: usize,
295    /// The key it names (`keyid`).
296    pub keyid: String,
297    /// The text itself, the bytes that were signed.
298    pub text: String,
299}
300
301/// What a check found.
302#[derive(Debug, Clone, PartialEq, Eq)]
303pub struct Check {
304    /// How many bytes the response's body has.
305    pub bytes: usize,
306    pub status: u16,
307    pub authority: String,
308    pub path: String,
309    /// The key's algorithm ("" when no key was found).
310    pub alg: String,
311    /// The SHA-256 of the bytes matches their `Content-Digest`.
312    pub digest_matches: bool,
313    /// The key the signature names.
314    pub keyid: String,
315    /// The key's thumbprint is that `keyid`.
316    pub key_matches: bool,
317    /// How many signed parts.
318    pub parts: usize,
319    /// How long the signature is, in bytes.
320    pub signature_bytes: usize,
321    /// The signature verifies, with this key, over the text the parts make.
322    pub verified: bool,
323    /// The receipt's number: the first 40 bits of the SHA-256 of its signature, as XXXX-XXXX; ""
324    /// when there's no signature to read.
325    pub number: String,
326    /// When the site says it signed it (`created`, seconds since 1970).
327    pub created: Option<i64>,
328    /// What isn't as a receipt's should be, in the order they're checked: none when it checks out.
329    pub problems: Vec<Problem>,
330}
331
332impl Check {
333    /// It checks out: signed by the key it names, over these very bytes, as a receipt.
334    pub fn ok(&self) -> bool {
335        self.problems.is_empty()
336    }
337
338    /// Why it doesn't check out, a sentence per problem.
339    pub fn why(&self) -> Vec<&'static str> {
340        self.problems.iter().map(|p| p.explain()).collect()
341    }
342
343    /// What My Card prints about a receipt, line for line, in a browser and on a visitor's machine.
344    pub fn lines(&self) -> Vec<String> {
345        let short = &self.keyid[..self.keyid.len().min(12)];
346        let by = if self.alg.is_empty() { String::new() } else { format!(" with {}", self.alg) };
347        vec![
348            format!("Receipt: {} bytes from {}{}, HTTP {}, signed by the site{by}.", self.bytes, self.authority, self.path, self.status),
349            if self.digest_matches {
350                "Receipt digest: the SHA-256 of those bytes matches its Content-Digest.".to_string()
351            } else {
352                "Receipt digest: the SHA-256 of those bytes doesn't match its Content-Digest: they were changed.".to_string()
353            },
354            if self.key_matches {
355                format!("Receipt key: {short}..., echovalidum.com's {} key; its thumbprint matches.", self.alg)
356            } else if self.alg.is_empty() {
357                format!("Receipt key: the signature names {short}..., which the site's key directory doesn't list.")
358            } else {
359                format!("Receipt key: the signature names {short}..., not this key.")
360            },
361            format!("Receipt signature: {} bytes over {} signed parts: {}.", self.signature_bytes, self.parts,
362                if self.verified { "verified" } else { "doesn't verify" }),
363            format!("Receipt number: {}, from the SHA-256 of that signature: your card's.", self.number),
364        ]
365    }
366}
367
368/// Check a receipt with one key in hand: as [`Directory::check`] with that key alone, except that
369/// when it isn't the key the signature names, the signature is still tried with it, so
370/// [`Check::verified`] says whether this key signed it.
371pub fn check(response: &Response<'_>, key: &Key<'_>) -> Check {
372    let key = DirectoryKey { kty: "AKP".into(), alg: key.alg.into(), public: key.public.into(), kid: None, nbf: None, exp: None };
373    examine(response, std::slice::from_ref(&key), true)
374}
375
376/// The signature a response carries, read: its parts, its parameters, its bytes.
377struct Signed {
378    components: Vec<(String, Vec<(String, sf::Bare)>)>,
379    params: Vec<(String, sf::Bare)>,
380    signature: Vec<u8>,
381}
382
383impl Signed {
384    fn param(&self, name: &str) -> Option<&sf::Bare> {
385        self.params.iter().rev().find(|p| p.0 == name).map(|p| &p.1)
386    }
387    fn keyid(&self) -> String {
388        match self.param("keyid") {
389            Some(sf::Bare::String(s)) => s.clone(),
390            _ => String::new(),
391        }
392    }
393    fn created(&self) -> Option<i64> {
394        match self.param("created") {
395            Some(sf::Bare::Integer(n)) => Some(*n),
396            _ => None,
397        }
398    }
399    /// The covered components and the parameters, serialized as RFC 8941 does: `@signature-params`.
400    fn serialized(&self) -> String {
401        let items: Vec<String> = self.components.iter().map(|(name, params)| format!("{}{}", sf::string(name), sf::params(params))).collect();
402        format!("({}){}", items.join(" "), sf::params(&self.params))
403    }
404    fn component_ids(&self) -> Vec<String> {
405        self.components.iter().map(|(name, params)| format!("{}{}", sf::string(name), sf::params(params))).collect()
406    }
407}
408
409/// The `echovalidum` signature in a response, or why there isn't one to read.
410fn signed(response: &Response<'_>) -> Result<Signed, Problem> {
411    let (Some(input), Some(signature)) = (response.field("signature-input"), response.field("signature")) else {
412        return Err(Problem::NotSigned);
413    };
414    let (Some(input), Some(signature)) = (sf::dictionary(&input), sf::dictionary(&signature)) else {
415        return Err(Problem::Malformed);
416    };
417    let member = |d: &[(String, sf::Member)]| d.iter().rev().find(|m| m.0 == LABEL).map(|m| m.1.clone());
418    let (Some(input), Some(signature)) = (member(&input), member(&signature)) else {
419        return Err(Problem::NotSigned);
420    };
421    match (input, signature) {
422        (sf::Member::InnerList(components, params), sf::Member::Item(sf::Bare::Bytes(signature), _)) => {
423            let components = components
424                .into_iter()
425                .map(|(item, params)| match item {
426                    sf::Bare::String(name) => Ok((name, params)),
427                    _ => Err(Problem::Malformed),
428                })
429                .collect::<Result<Vec<_>, _>>()?;
430            Ok(Signed { components, params, signature })
431        }
432        _ => Err(Problem::Malformed),
433    }
434}
435
436/// A receipt's signature, read as far as a receipt's should be: its label, tag, parameters and parts.
437fn read_receipt(response: &Response<'_>) -> Result<Signed, (Problem, Option<Signed>)> {
438    let signed = signed(response).map_err(|p| (p, None))?;
439    if !matches!(signed.param("tag"), Some(sf::Bare::String(tag)) if tag == TAG) {
440        return Err((Problem::NotAReceipt, Some(signed)));
441    }
442    let names_ok = signed.params.iter().all(|(name, _)| ["created", "keyid", "tag"].contains(&name.as_str()));
443    let created_ok = matches!(signed.param("created"), Some(sf::Bare::Integer(n)) if *n >= 0);
444    let keyid_ok = matches!(signed.param("keyid"), Some(sf::Bare::String(_)));
445    if !(names_ok && created_ok && keyid_ok) {
446        return Err((Problem::Malformed, Some(signed)));
447    }
448    if signed.component_ids() != COMPONENTS {
449        return Err((Problem::Uncovered, Some(signed)));
450    }
451    Ok(signed)
452}
453
454/// The signature base, the text that was signed: each covered part, then `@signature-params`.
455/// `None` when a covered header isn't there, unless `lenient`, which takes its value as empty.
456fn base_of(response: &Response<'_>, signed: &Signed, lenient: bool) -> Option<String> {
457    let mut lines = Vec::new();
458    for (id, (name, _)) in signed.component_ids().iter().zip(&signed.components) {
459        let value = match name.as_str() {
460            "@status" => response.status.to_string(),
461            "@authority" => response.authority.to_string(),
462            "@path" => response.path.to_string(),
463            header => match response.field(header) {
464                Some(value) => value,
465                None if lenient => String::new(),
466                None => return None,
467            },
468        };
469        lines.push(format!("{id}: {value}"));
470    }
471    lines.push(format!("\"@signature-params\": {}", signed.serialized()));
472    Some(lines.join("\n"))
473}
474
475fn examine(response: &Response<'_>, keys: &[DirectoryKey], one_key: bool) -> Check {
476    let digest = format!("sha-256=:{}:", base64(&Sha256::digest(response.body), false));
477    let field = response.field("content-digest");
478    let mut found = Check {
479        bytes: response.body.len(),
480        status: response.status,
481        authority: response.authority.to_string(),
482        path: response.path.to_string(),
483        alg: if one_key { keys[0].alg.clone() } else { String::new() },
484        digest_matches: field.as_deref() == Some(digest.as_str()),
485        keyid: String::new(),
486        key_matches: false,
487        parts: 0,
488        signature_bytes: 0,
489        verified: false,
490        number: String::new(),
491        created: None,
492        problems: Vec::new(),
493    };
494    let signed = match read_receipt(response) {
495        Ok(signed) => signed,
496        Err((problem, signed)) => {
497            found.problems.push(problem);
498            if let Some(signed) = signed {
499                found.keyid = signed.keyid();
500                found.created = signed.created();
501                found.parts = signed.components.len();
502                found.signature_bytes = signed.signature.len();
503                found.number = number(&signed.signature);
504            }
505            return found;
506        }
507    };
508    found.keyid = signed.keyid();
509    found.created = signed.created();
510    found.parts = signed.components.len();
511    found.signature_bytes = signed.signature.len();
512    found.number = number(&signed.signature);
513
514    let base = base_of(response, &signed, false);
515    if base.is_none() {
516        found.problems.push(Problem::MissingHeader);
517    }
518    if let Some(field) = &field {
519        if !is_sha256_digest(field) {
520            found.problems.push(Problem::UnsupportedDigest);
521        } else if *field != digest {
522            found.problems.push(Problem::DigestMismatch);
523        }
524    }
525    let key = keys.iter().find(|k| k.kty == "AKP" && k.thumbprint() == found.keyid);
526    let mut try_with = None;
527    match key {
528        None => {
529            found.problems.push(Problem::UnknownKey);
530            if one_key {
531                try_with = keys.first().filter(|k| ALGORITHMS.contains(&k.alg.as_str()));
532            }
533        }
534        Some(key) => {
535            found.alg = key.alg.clone();
536            found.key_matches = true;
537            if !ALGORITHMS.contains(&key.alg.as_str()) {
538                found.problems.push(Problem::UnsupportedAlgorithm);
539            } else {
540                let created = found.created.unwrap_or(0);
541                if key.nbf.is_some_and(|nbf| created < nbf) || key.exp.is_some_and(|exp| created > exp) {
542                    found.problems.push(Problem::KeyNotValidThen);
543                }
544                try_with = Some(key);
545            }
546        }
547    }
548    if let (Some(base), Some(key)) = (&base, try_with) {
549        found.verified = verify(&key.alg, &unbase64(&key.public), base.as_bytes(), &signed.signature);
550        if !found.verified && found.key_matches {
551            found.problems.push(Problem::BadSignature);
552        }
553    }
554    found.problems.sort();
555    found
556}
557
558/// `sha-256=:` and the base 64 of 32 bytes, padded, `:`: the one digest a receipt carries.
559fn is_sha256_digest(field: &str) -> bool {
560    let Some(b64) = field.strip_prefix("sha-256=:").and_then(|s| s.strip_suffix(':')) else {
561        return false;
562    };
563    b64.len() == 44 && b64.ends_with('=') && !b64.ends_with("==") && b64[..43].bytes().all(|c| c.is_ascii_alphanumeric() || c == b'+' || c == b'/')
564}
565
566/// The text a response's `echovalidum` signature covers: each part its `Signature-Input` names, as
567/// `"name";flags: value`, then `"@signature-params"` (RFC 9421, section 2.5). Empty when there is
568/// no signature to read, and a missing header's value empty.
569pub fn signature_base(response: &Response<'_>) -> SignatureBase {
570    let Ok(signed) = signed(response) else {
571        return SignatureBase { label: String::new(), parts: 0, keyid: String::new(), text: String::new() };
572    };
573    let text = base_of(response, &signed, true).unwrap_or_default();
574    SignatureBase { label: LABEL.to_string(), parts: signed.components.len(), keyid: signed.keyid(), text }
575}
576
577/// A key's thumbprint (RFC 7638): the base64url SHA-256 of its required members, in order.
578pub fn thumbprint(key: &Key<'_>) -> String {
579    jwk_thumbprint(key.alg, "AKP", key.public)
580}
581
582fn jwk_thumbprint(alg: &str, kty: &str, public: &str) -> String {
583    let canonical = format!("{{\"alg\":{},\"kty\":{},\"pub\":{}}}", json::quote(alg), json::quote(kty), json::quote(public));
584    base64(&Sha256::digest(canonical.as_bytes()), true)
585}
586
587/// A receipt's number: the first 40 bits of the SHA-256 of its signature, in Crockford's base 32
588/// (no I, L, O or U to misread), as XXXX-XXXX.
589pub fn number(signature: &[u8]) -> String {
590    const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
591    let hash = Sha256::digest(signature);
592    let bits = hash[..5].iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b));
593    let out: String = (0..8).rev().map(|i| CROCKFORD[((bits >> (i * 5)) & 31) as usize] as char).collect();
594    format!("{}-{}", &out[..4], &out[4..])
595}
596
597/// An ML-DSA signature (no context) over a message, with a public key at the level `alg` names.
598pub fn verify(alg: &str, public: &[u8], message: &[u8], signature: &[u8]) -> bool {
599    match alg {
600        "ML-DSA-44" => verify_at::<ml_dsa::MlDsa44>(public, message, signature),
601        "ML-DSA-65" => verify_at::<ml_dsa::MlDsa65>(public, message, signature),
602        "ML-DSA-87" => verify_at::<ml_dsa::MlDsa87>(public, message, signature),
603        _ => false,
604    }
605}
606
607fn verify_at<P: ml_dsa::MlDsaParams>(public: &[u8], message: &[u8], signature: &[u8]) -> bool {
608    match (ml_dsa::EncodedVerifyingKey::<P>::try_from(public), ml_dsa::Signature::<P>::try_from(signature)) {
609        (Ok(encoded), Ok(signature)) => ml_dsa::VerifyingKey::<P>::decode(&encoded).verify_with_context(message, &[], &signature),
610        _ => false,
611    }
612}
613
614/// Base 64 (url: the URL-safe alphabet, unpadded).
615pub fn base64(bytes: &[u8], url: bool) -> String {
616    let alphabet: &[u8; 64] = if url {
617        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
618    } else {
619        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
620    };
621    let mut out = String::new();
622    for chunk in bytes.chunks(3) {
623        let n = chunk.iter().enumerate().fold(0u32, |acc, (i, &b)| acc | (u32::from(b) << (16 - 8 * i)));
624        for i in 0..=chunk.len() {
625            out.push(alphabet[((n >> (18 - 6 * i)) & 63) as usize] as char);
626        }
627        if !url {
628            out.push_str(&"=".repeat(3 - chunk.len()));
629        }
630    }
631    out
632}
633
634/// Base 64 back to bytes: either alphabet, padded or not; anything else is skipped.
635pub fn unbase64(text: &str) -> Vec<u8> {
636    let value = |c: u8| match c {
637        b'A'..=b'Z' => Some(c - b'A'),
638        b'a'..=b'z' => Some(c - b'a' + 26),
639        b'0'..=b'9' => Some(c - b'0' + 52),
640        b'+' | b'-' => Some(62),
641        b'/' | b'_' => Some(63),
642        _ => None,
643    };
644    let (mut out, mut acc, mut bits) = (Vec::new(), 0u32, 0);
645    for v in text.bytes().filter_map(value) {
646        acc = (acc << 6) | u32::from(v);
647        bits += 6;
648        if bits >= 8 {
649            bits -= 8;
650            out.push((acc >> bits) as u8);
651        }
652    }
653    out
654}
655
656/// Structured fields (RFC 8941), as far as a signature's headers need: dictionaries of inner lists
657/// and items, and serializing what was read back.
658mod sf {
659    #[derive(Debug, Clone, PartialEq)]
660    pub enum Bare {
661        Integer(i64),
662        Decimal(String),
663        String(String),
664        Token(String),
665        Bytes(Vec<u8>),
666        Boolean(bool),
667    }
668
669    pub type Params = Vec<(String, Bare)>;
670
671    /// An ordered map's insert: a key already there keeps its place and takes the new value.
672    fn put<T>(map: &mut Vec<(String, T)>, key: String, value: T) {
673        match map.iter_mut().find(|m| m.0 == key) {
674            Some(m) => m.1 = value,
675            None => map.push((key, value)),
676        }
677    }
678
679    #[derive(Debug, Clone, PartialEq)]
680    pub enum Member {
681        Item(Bare, Params),
682        InnerList(Vec<(Bare, Params)>, Params),
683    }
684
685    struct Reader<'a> {
686        s: &'a [u8],
687        i: usize,
688    }
689
690    impl Reader<'_> {
691        fn peek(&self) -> Option<u8> {
692            self.s.get(self.i).copied()
693        }
694        fn skip(&mut self, set: &[u8]) {
695            while self.peek().is_some_and(|c| set.contains(&c)) {
696                self.i += 1;
697            }
698        }
699        fn key(&mut self) -> Option<String> {
700            let start = self.i;
701            match self.peek() {
702                Some(c) if c.is_ascii_lowercase() || c == b'*' => self.i += 1,
703                _ => return None,
704            }
705            while self.peek().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_-.*".contains(&c)) {
706                self.i += 1;
707            }
708            Some(String::from_utf8_lossy(&self.s[start..self.i]).into_owned())
709        }
710        fn params(&mut self) -> Option<Params> {
711            let mut out: Params = Vec::new();
712            while self.peek() == Some(b';') {
713                self.i += 1;
714                self.skip(b" ");
715                let key = self.key()?;
716                let value = if self.peek() == Some(b'=') {
717                    self.i += 1;
718                    self.bare()?
719                } else {
720                    Bare::Boolean(true)
721                };
722                put(&mut out, key, value);
723            }
724            Some(out)
725        }
726        fn bare(&mut self) -> Option<Bare> {
727            match self.peek()? {
728                b'-' | b'0'..=b'9' => self.number(),
729                b'"' => self.string(),
730                b':' => self.bytes(),
731                b'?' => {
732                    self.i += 1;
733                    let b = match self.peek()? {
734                        b'1' => true,
735                        b'0' => false,
736                        _ => return None,
737                    };
738                    self.i += 1;
739                    Some(Bare::Boolean(b))
740                }
741                c if c.is_ascii_alphabetic() || c == b'*' => {
742                    let start = self.i;
743                    self.i += 1;
744                    while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~:/".contains(&c)) {
745                        self.i += 1;
746                    }
747                    Some(Bare::Token(String::from_utf8_lossy(&self.s[start..self.i]).into_owned()))
748                }
749                _ => None,
750            }
751        }
752        fn number(&mut self) -> Option<Bare> {
753            let start = self.i;
754            if self.peek() == Some(b'-') {
755                self.i += 1;
756            }
757            let digits = self.i;
758            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
759                self.i += 1;
760            }
761            let whole = self.i - digits;
762            if whole == 0 {
763                return None;
764            }
765            if self.peek() == Some(b'.') {
766                if whole > 12 {
767                    return None;
768                }
769                self.i += 1;
770                let frac = self.i;
771                while self.peek().is_some_and(|c| c.is_ascii_digit()) {
772                    self.i += 1;
773                }
774                if !(1..=3).contains(&(self.i - frac)) {
775                    return None;
776                }
777                return Some(Bare::Decimal(String::from_utf8_lossy(&self.s[start..self.i]).into_owned()));
778            }
779            if whole > 15 {
780                return None;
781            }
782            std::str::from_utf8(&self.s[start..self.i]).ok()?.parse().ok().map(Bare::Integer)
783        }
784        fn string(&mut self) -> Option<Bare> {
785            self.i += 1;
786            let mut out = String::new();
787            loop {
788                let c = self.peek()?;
789                self.i += 1;
790                match c {
791                    b'"' => return Some(Bare::String(out)),
792                    b'\\' => {
793                        let e = self.peek()?;
794                        if e != b'"' && e != b'\\' {
795                            return None;
796                        }
797                        self.i += 1;
798                        out.push(e as char);
799                    }
800                    0x20..=0x7e => out.push(c as char),
801                    _ => return None,
802                }
803            }
804        }
805        fn bytes(&mut self) -> Option<Bare> {
806            self.i += 1;
807            let start = self.i;
808            while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || b"+/=".contains(&c)) {
809                self.i += 1;
810            }
811            let text = std::str::from_utf8(&self.s[start..self.i]).ok()?;
812            if self.peek() != Some(b':') {
813                return None;
814            }
815            self.i += 1;
816            Some(Bare::Bytes(super::unbase64(text)))
817        }
818        fn member(&mut self) -> Option<Member> {
819            if self.peek() == Some(b'(') {
820                self.i += 1;
821                let mut items = Vec::new();
822                loop {
823                    self.skip(b" ");
824                    if self.peek() == Some(b')') {
825                        self.i += 1;
826                        return Some(Member::InnerList(items, self.params()?));
827                    }
828                    let item = self.bare()?;
829                    let params = self.params()?;
830                    items.push((item, params));
831                    if !matches!(self.peek(), Some(b' ' | b')')) {
832                        return None;
833                    }
834                }
835            }
836            let item = self.bare()?;
837            Some(Member::Item(item, self.params()?))
838        }
839    }
840
841    /// A dictionary field (RFC 8941, section 4.2.2): `None` when it doesn't parse.
842    pub fn dictionary(text: &str) -> Option<Vec<(String, Member)>> {
843        let mut r = Reader { s: text.as_bytes(), i: 0 };
844        let mut out: Vec<(String, Member)> = Vec::new();
845        r.skip(b" ");
846        if r.peek().is_none() {
847            return Some(out);
848        }
849        loop {
850            let key = r.key()?;
851            let member = if r.peek() == Some(b'=') {
852                r.i += 1;
853                r.member()?
854            } else {
855                Member::Item(Bare::Boolean(true), r.params()?)
856            };
857            put(&mut out, key, member);
858            r.skip(b" \t");
859            match r.peek() {
860                None => return Some(out),
861                Some(b',') => {
862                    r.i += 1;
863                    r.skip(b" \t");
864                    r.peek()?;
865                }
866                Some(_) => return None,
867            }
868        }
869    }
870
871    pub fn string(s: &str) -> String {
872        format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
873    }
874
875    fn bare(b: &Bare) -> String {
876        match b {
877            Bare::Integer(n) => n.to_string(),
878            Bare::Decimal(d) => d.clone(),
879            Bare::String(s) => string(s),
880            Bare::Token(t) => t.clone(),
881            Bare::Bytes(v) => format!(":{}:", super::base64(v, false)),
882            Bare::Boolean(b) => format!("?{}", u8::from(*b)),
883        }
884    }
885
886    pub fn params(params: &Params) -> String {
887        params
888            .iter()
889            .map(|(k, v)| match v {
890                Bare::Boolean(true) => format!(";{k}"),
891                v => format!(";{k}={}", bare(v)),
892            })
893            .collect()
894    }
895}
896
897/// Just enough JSON for a key directory.
898mod json {
899    #[derive(Debug, Clone, PartialEq)]
900    pub enum Value {
901        Null,
902        Bool(bool),
903        Number(f64),
904        String(String),
905        Array(Vec<Value>),
906        Object(Vec<(String, Value)>),
907    }
908
909    impl Value {
910        pub fn get(&self, name: &str) -> Option<&Value> {
911            match self {
912                Value::Object(members) => members.iter().rev().find(|m| m.0 == name).map(|m| &m.1),
913                _ => None,
914            }
915        }
916        pub fn as_str(&self) -> Option<&str> {
917            match self {
918                Value::String(s) => Some(s),
919                _ => None,
920            }
921        }
922        pub fn as_array(&self) -> Option<&[Value]> {
923            match self {
924                Value::Array(items) => Some(items),
925                _ => None,
926            }
927        }
928    }
929
930    pub fn quote(s: &str) -> String {
931        let mut out = String::from("\"");
932        for c in s.chars() {
933            match c {
934                '"' => out.push_str("\\\""),
935                '\\' => out.push_str("\\\\"),
936                '\u{8}' => out.push_str("\\b"),
937                '\u{c}' => out.push_str("\\f"),
938                '\n' => out.push_str("\\n"),
939                '\r' => out.push_str("\\r"),
940                '\t' => out.push_str("\\t"),
941                c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
942                c => out.push(c),
943            }
944        }
945        out.push('"');
946        out
947    }
948
949    struct Reader<'a> {
950        s: &'a [u8],
951        i: usize,
952        depth: usize,
953    }
954
955    pub fn parse(text: &str) -> Option<Value> {
956        let mut r = Reader { s: text.as_bytes(), i: 0, depth: 0 };
957        let v = r.value()?;
958        r.space();
959        (r.i == r.s.len()).then_some(v)
960    }
961
962    impl Reader<'_> {
963        fn space(&mut self) {
964            while self.s.get(self.i).is_some_and(|c| b" \t\r\n".contains(c)) {
965                self.i += 1;
966            }
967        }
968        fn literal(&mut self, word: &str, v: Value) -> Option<Value> {
969            self.s[self.i..].starts_with(word.as_bytes()).then(|| {
970                self.i += word.len();
971                v
972            })
973        }
974        fn value(&mut self) -> Option<Value> {
975            self.space();
976            match *self.s.get(self.i)? {
977                b'{' => self.nested(|r| {
978                    let mut members = Vec::new();
979                    r.space();
980                    if r.s.get(r.i) == Some(&b'}') {
981                        r.i += 1;
982                        return Some(Value::Object(members));
983                    }
984                    loop {
985                        r.space();
986                        let Value::String(name) = r.string()? else { return None };
987                        r.space();
988                        (r.s.get(r.i) == Some(&b':')).then_some(())?;
989                        r.i += 1;
990                        members.push((name, r.value()?));
991                        r.space();
992                        match r.s.get(r.i)? {
993                            b',' => r.i += 1,
994                            b'}' => {
995                                r.i += 1;
996                                return Some(Value::Object(members));
997                            }
998                            _ => return None,
999                        }
1000                    }
1001                }),
1002                b'[' => self.nested(|r| {
1003                    let mut items = Vec::new();
1004                    r.space();
1005                    if r.s.get(r.i) == Some(&b']') {
1006                        r.i += 1;
1007                        return Some(Value::Array(items));
1008                    }
1009                    loop {
1010                        items.push(r.value()?);
1011                        r.space();
1012                        match r.s.get(r.i)? {
1013                            b',' => r.i += 1,
1014                            b']' => {
1015                                r.i += 1;
1016                                return Some(Value::Array(items));
1017                            }
1018                            _ => return None,
1019                        }
1020                    }
1021                }),
1022                b'"' => self.string(),
1023                b't' => self.literal("true", Value::Bool(true)),
1024                b'f' => self.literal("false", Value::Bool(false)),
1025                b'n' => self.literal("null", Value::Null),
1026                _ => self.number(),
1027            }
1028        }
1029        fn nested(&mut self, inner: impl FnOnce(&mut Self) -> Option<Value>) -> Option<Value> {
1030            self.depth += 1;
1031            if self.depth > 64 {
1032                return None;
1033            }
1034            self.i += 1;
1035            let v = inner(self);
1036            self.depth -= 1;
1037            v
1038        }
1039        fn number(&mut self) -> Option<Value> {
1040            let start = self.i;
1041            while self.s.get(self.i).is_some_and(|c| c.is_ascii_digit() || b"+-.eE".contains(c)) {
1042                self.i += 1;
1043            }
1044            let text = std::str::from_utf8(&self.s[start..self.i]).ok()?;
1045            let valid = {
1046                let t = text.strip_prefix('-').unwrap_or(text);
1047                let (mantissa, exponent) = t.split_once(['e', 'E']).map_or((t, None), |(m, e)| (m, Some(e)));
1048                let (int, frac) = mantissa.split_once('.').map_or((mantissa, None), |(i, f)| (i, Some(f)));
1049                let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
1050                digits(int)
1051                    && (int == "0" || !int.starts_with('0'))
1052                    && frac.is_none_or(digits)
1053                    && exponent.is_none_or(|e| digits(e.strip_prefix(['+', '-']).unwrap_or(e)))
1054            };
1055            valid.then(|| text.parse().ok().map(Value::Number))?
1056        }
1057        fn hex4(&mut self) -> Option<u32> {
1058            let h = std::str::from_utf8(self.s.get(self.i..self.i + 4)?).ok()?;
1059            self.i += 4;
1060            u32::from_str_radix(h, 16).ok()
1061        }
1062        fn string(&mut self) -> Option<Value> {
1063            (self.s.get(self.i) == Some(&b'"')).then_some(())?;
1064            self.i += 1;
1065            let mut out: Vec<u8> = Vec::new();
1066            loop {
1067                let c = *self.s.get(self.i)?;
1068                self.i += 1;
1069                match c {
1070                    b'"' => return String::from_utf8(out).ok().map(Value::String),
1071                    b'\\' => {
1072                        let e = *self.s.get(self.i)?;
1073                        self.i += 1;
1074                        let ch = match e {
1075                            b'"' => '"',
1076                            b'\\' => '\\',
1077                            b'/' => '/',
1078                            b'b' => '\u{8}',
1079                            b'f' => '\u{c}',
1080                            b'n' => '\n',
1081                            b'r' => '\r',
1082                            b't' => '\t',
1083                            b'u' => {
1084                                let hi = self.hex4()?;
1085                                let code = if (0xD800..0xDC00).contains(&hi) {
1086                                    (self.s.get(self.i..self.i + 2) == Some(b"\\u")).then_some(())?;
1087                                    self.i += 2;
1088                                    let lo = self.hex4()?;
1089                                    (0xDC00..0xE000).contains(&lo).then_some(())?;
1090                                    0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00)
1091                                } else {
1092                                    hi
1093                                };
1094                                char::from_u32(code)?
1095                            }
1096                            _ => return None,
1097                        };
1098                        let mut buf = [0u8; 4];
1099                        out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
1100                    }
1101                    0x00..=0x1f => return None,
1102                    c => out.push(c),
1103                }
1104            }
1105        }
1106    }
1107}