Skip to main content

cbcl_core/
attest.rs

1//! R4 v2 attestation signing discipline (SPEC-015 REQ-701/REQ-708,
2//! ADR-700, CON-700).
3//!
4//! v2 signatures are computed over the RFC 9804 canonical bytes of a
5//! domain-tagged *attestation* committing to the signature suite, the
6//! content hash, and the message header:
7//!
8//! ```text
9//! (cbcl-attest-v2 <suite> <hash> <perf-name> <from-key> (<to-key>*)
10//!                 <thread> [<caused-ref>])
11//! ```
12//!
13//! The attestation is never transmitted; both verifier classes reconstruct
14//! the identical preimage — an envelope holder from the envelope's fields,
15//! a full-message holder from the message and its computed hash (REQ-701).
16//! Verification therefore never requires the payload.
17//!
18//! The legacy v1 discipline (sign the full canonical bytes) coexists:
19//! messages and envelopes carry an explicit [`SignatureDiscipline`] marker,
20//! and [`verify_with_discipline`] *dispatches* on it rather than guessing.
21//! A v1 signature can never satisfy an envelope (v2) verification call —
22//! the mismatch is the typed [`AttestError::DisciplineMismatch`], fail
23//! closed (REQ-701, review finding 6).
24//!
25//! The v3 discipline (SPEC-017 REQ-812, Stage 2) signs a domain-tagged,
26//! suite-named commitment to the *typed Merkle root* alone:
27//!
28//! ```text
29//! (cbcl-attest-v3 <suite> <root>)
30//! ```
31//!
32//! After the Stage 1 hub-flip the content address *is* that root, and the
33//! root commits every header field as an authenticated leaf — so one
34//! root-signature authenticates all fields at once, and v3 verification
35//! needs only `(suite, root, sig)`, no header. v1, v2 and v3 coexist under
36//! the same [`SignatureDiscipline`] marker and [`verify_with_discipline`]
37//! dispatch; every cross-version presentation is the same typed fail-closed
38//! rejection. Stage 3 migrates `envelope.rs` to v3; v2 retirement is later.
39//!
40//! Canonical encoding is `canonical.rs`'s — this module builds the
41//! attestation `SExpr` and defers all byte production to
42//! [`canonical_encode`]; there is exactly one canonicalizer.
43
44#![forbid(unsafe_code)]
45
46use crate::canonical::canonical_encode;
47use crate::keyid::{KeyId, SignatureSuite};
48use crate::message::CausedBy;
49use crate::protocol::BEGIN_KEYWORD;
50use crate::r4::Signer;
51use crate::sexpr::{Atom, SExpr};
52use alloc::collections::BTreeSet;
53use alloc::string::String;
54use alloc::vec::Vec;
55use core::fmt;
56
57/// Domain tag heading every v2 attestation preimage (ADR-700). The `-v2`
58/// version tag governs the *discipline* (what is signed); the suite field
59/// governs the *algorithm* (how); they vary independently.
60pub const ATTEST_DOMAIN_TAG: &str = "cbcl-attest-v2";
61
62/// Domain tag heading every v3 attestation preimage (SPEC-017 REQ-812,
63/// Stage 2). v3 signs a domain-tagged, suite-named commitment to the *typed
64/// Merkle root* (`typed_addr::typed_root`) rather than an unrolled header.
65///
66/// After the Stage 1 hub-flip the content address *is* that root, and the
67/// root already commits every field (performative, from, to, caused-by,
68/// thread, payload) as an authenticated leaf. So a v3 signature over
69/// `(cbcl-attest-v3 <suite> <root>)` authenticates all fields at once; each
70/// header field is recovered as a field-opening against the same root
71/// (Stage 3), so v3 verification needs *only* `(suite, root, sig)` — no
72/// header. The `-v3` tag governs the discipline; the suite field governs the
73/// algorithm; both retain ADR-700's cross-protocol-substitution resistance.
74pub const ATTEST_V3_DOMAIN_TAG: &str = "cbcl-attest-v3";
75
76/// The authenticated header a v2 signature commits to, alongside the
77/// content hash (REQ-700/REQ-701).
78///
79/// These are exactly the fields a redacted-envelope verifier reads; binding
80/// the hash alone would leave every one of them forgeable from gossiped
81/// (hash, signature) pairs (SPEC-015 review finding 1).
82///
83/// The suite named in the preimage is `from.suite` — the signing key's
84/// suite — so a signature can never be re-interpreted under a different
85/// suite (REQ-708) and suite/key consistency holds by construction.
86#[derive(Debug, Clone, PartialEq, Eq)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88pub struct AttestationHeader {
89    /// Content hash of the message being vouched for (`f1220<hex64>`).
90    pub content_hash: String,
91    /// Performative name.
92    pub performative: String,
93    /// Sender key (canonical identity; its suite names the signature suite).
94    pub from: KeyId,
95    /// Recipient set, canonically ordered by (suite, name).
96    pub to: BTreeSet<KeyId>,
97    /// Thread identifier.
98    pub thread: String,
99    /// `:caused-by` list; `None` when the message carries none (the
100    /// grammar's optional `[caused-ref]`, CON-700).
101    pub caused_by: Option<CausedBy>,
102}
103
104/// Build the attestation S-expression (CON-700 `attestation` production).
105///
106/// Pure; never transmitted. Keys are rendered in canonical suite-explicit
107/// spelling so any alias spelling of the same identity reconstructs
108/// identical bytes.
109pub fn attestation_sexpr(h: &AttestationHeader) -> SExpr {
110    use alloc::vec;
111    let mut items = vec![
112        SExpr::Atom(Atom::Symbol(String::from(ATTEST_DOMAIN_TAG))),
113        SExpr::Atom(Atom::Symbol(String::from(h.from.suite.as_str()))),
114        SExpr::Atom(Atom::Symbol(h.content_hash.clone())),
115        SExpr::Atom(Atom::Symbol(h.performative.clone())),
116        SExpr::Atom(Atom::Symbol(h.from.canonical_spelling())),
117        SExpr::List(
118            h.to.iter()
119                .map(|k| SExpr::Atom(Atom::Symbol(k.canonical_spelling())))
120                .collect(),
121        ),
122        SExpr::Atom(Atom::Str(h.thread.clone())),
123    ];
124    if let Some(cb) = &h.caused_by {
125        // Mirrors the `:caused-by` value encoding of `From<Message> for
126        // SExpr` (message.rs) so both verifier classes agree.
127        items.push(match cb {
128            CausedBy::Begin => SExpr::Atom(Atom::Symbol(String::from(BEGIN_KEYWORD))),
129            CausedBy::Single(hash) => SExpr::Atom(Atom::Symbol(hash.clone())),
130            CausedBy::Multiple(hashes) => SExpr::List(
131                hashes
132                    .iter()
133                    .map(|hash| SExpr::Atom(Atom::Symbol(hash.clone())))
134                    .collect(),
135            ),
136        });
137    }
138    SExpr::List(items)
139}
140
141/// The RFC 9804 canonical bytes of the attestation — the sole input to
142/// v2 signing and verification (ADR-700).
143pub fn attestation_preimage(h: &AttestationHeader) -> Vec<u8> {
144    canonical_encode(&attestation_sexpr(h))
145}
146
147/// Build the v3 attestation S-expression: a domain-tagged, suite-named
148/// commitment to the typed Merkle root (SPEC-017 REQ-812).
149///
150/// ```text
151/// (cbcl-attest-v3 <suite> <root>)
152/// ```
153///
154/// The suite is named explicitly (REQ-708): a v3 signature can never be
155/// re-interpreted under a different suite, and the two paths (sign, verify)
156/// reconstruct identical bytes from `(suite, root)` alone. `root` is the
157/// `f1220<hex64>` rendering of the typed root, carried verbatim as a
158/// symbol atom — the same spelling `typed_addr::typed_root` produces.
159pub fn attestation_v3_sexpr(suite: &SignatureSuite, root: &str) -> SExpr {
160    use alloc::vec;
161    SExpr::List(vec![
162        SExpr::Atom(Atom::Symbol(String::from(ATTEST_V3_DOMAIN_TAG))),
163        SExpr::Atom(Atom::Symbol(String::from(suite.as_str()))),
164        SExpr::Atom(Atom::Symbol(String::from(root))),
165    ])
166}
167
168/// The RFC 9804 canonical bytes of the v3 attestation — the sole input to
169/// v3 signing and verification (SPEC-017 REQ-812). No header is involved.
170pub fn attestation_v3_preimage(suite: &SignatureSuite, root: &str) -> Vec<u8> {
171    canonical_encode(&attestation_v3_sexpr(suite, root))
172}
173
174/// Explicit signing-discipline discriminator carried by messages and
175/// envelopes (REQ-701): verification *dispatches* on it, never guesses.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
178pub enum SignatureDiscipline {
179    /// Legacy v1: signature over the full canonical message bytes.
180    V1Full,
181    /// v2: signature over the attestation preimage (ADR-700).
182    V2Attested,
183    /// v3: signature over the typed-root commitment preimage
184    /// `(cbcl-attest-v3 <suite> <root>)` (SPEC-017 REQ-812).
185    V3Root,
186}
187
188impl SignatureDiscipline {
189    /// Canonical marker string as carried on the wire.
190    pub fn as_str(&self) -> &'static str {
191        match self {
192            SignatureDiscipline::V1Full => "v1",
193            SignatureDiscipline::V2Attested => ATTEST_DOMAIN_TAG,
194            SignatureDiscipline::V3Root => ATTEST_V3_DOMAIN_TAG,
195        }
196    }
197
198    /// Parse a marker string; anything unrecognised is a typed rejection
199    /// (never a fallback guess).
200    pub fn parse(s: &str) -> Result<Self, AttestError> {
201        match s {
202            "v1" => Ok(SignatureDiscipline::V1Full),
203            ATTEST_DOMAIN_TAG => Ok(SignatureDiscipline::V2Attested),
204            ATTEST_V3_DOMAIN_TAG => Ok(SignatureDiscipline::V3Root),
205            other => Err(AttestError::UnknownDiscipline(String::from(other))),
206        }
207    }
208}
209
210impl fmt::Display for SignatureDiscipline {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.write_str(self.as_str())
213    }
214}
215
216/// Typed rejection for the v2 attestation paths — fail closed, never a
217/// skipped check (REQ-701/REQ-708, LangSec discipline).
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub enum AttestError {
220    /// The named suite is not implemented by this verifier (REQ-708:
221    /// reject, don't repair — and never skip).
222    UnknownSuite(String),
223    /// An unrecognised discipline marker string.
224    UnknownDiscipline(String),
225    /// The signature's declared discipline does not match the discipline
226    /// of the verification call — e.g. a v1 signature presented to an
227    /// envelope (v2) path (REQ-701, review finding 6).
228    DisciplineMismatch {
229        /// Discipline the signature declares.
230        marker: SignatureDiscipline,
231        /// Discipline the verification input requires.
232        input: SignatureDiscipline,
233    },
234    /// The presented key is not the attestation's `from` key.
235    KeyMismatch,
236    /// Cryptographic verification failed over the reconstructed preimage.
237    InvalidSignature,
238}
239
240impl fmt::Display for AttestError {
241    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242        match self {
243            AttestError::UnknownSuite(s) => write!(f, "unknown signature suite '{s}'"),
244            AttestError::UnknownDiscipline(s) => {
245                write!(f, "unknown signature discipline marker '{s}'")
246            }
247            AttestError::DisciplineMismatch { marker, input } => write!(
248                f,
249                "signature discipline mismatch: signature declares '{marker}', \
250                 verification input requires '{input}'"
251            ),
252            AttestError::KeyMismatch => f.write_str("key does not match attestation's from key"),
253            AttestError::InvalidSignature => f.write_str("signature verification failed"),
254        }
255    }
256}
257
258/// Sign the v2 attestation for `header` (ADR-700).
259///
260/// `signer` embodies the private key named by `header.from`.
261// SIMPLIFY: `Signer` carries no key identity, so caller must pair signer
262// and `from` key correctly; a keyed multi-suite signer registry is the
263// upgrade path when a second suite lands (REQ-708 registry-entry rule).
264pub fn sign_attestation_v2(
265    signer: &dyn Signer,
266    header: &AttestationHeader,
267) -> Result<Vec<u8>, AttestError> {
268    match &header.from.suite {
269        SignatureSuite::Ed25519 => Ok(signer.sign(&attestation_preimage(header))),
270        SignatureSuite::Other(s) => Err(AttestError::UnknownSuite(s.clone())),
271    }
272}
273
274/// Verify a v2 signature from key + header fields + hash alone — the
275/// payload is never an input (REQ-701).
276///
277/// Order of checks: suite dispatch (typed rejection for unimplemented
278/// suites, REQ-708), key identity, then cryptographic verification over
279/// the reconstructed preimage.
280pub fn verify_attestation_v2(
281    signer: &dyn Signer,
282    key: &KeyId,
283    header: &AttestationHeader,
284    sig: &[u8],
285) -> Result<(), AttestError> {
286    // Suite dispatch first: an attestation (or presented key) naming an
287    // unimplemented suite is rejected before any guessy work. An ed25519
288    // signature thereby verifies only against an ed25519-naming
289    // attestation (TEST-708).
290    // SIMPLIFY: one dispatch arm; adding a suite is a `keyid.rs` registry
291    // entry plus an arm here, not a discipline version bump (REQ-708).
292    if let SignatureSuite::Other(s) = &header.from.suite {
293        return Err(AttestError::UnknownSuite(s.clone()));
294    }
295    if let SignatureSuite::Other(s) = &key.suite {
296        return Err(AttestError::UnknownSuite(s.clone()));
297    }
298    if key != &header.from {
299        return Err(AttestError::KeyMismatch);
300    }
301    if signer.verify(&attestation_preimage(header), sig) {
302        Ok(())
303    } else {
304        Err(AttestError::InvalidSignature)
305    }
306}
307
308/// Sign the v3 typed-root attestation (SPEC-017 REQ-812).
309///
310/// `signer` embodies the private key whose suite is `suite`; `root` is the
311/// typed content-address root (`f1220<hex64>`). The signature covers the
312/// domain-tagged, suite-named commitment `(cbcl-attest-v3 <suite> <root>)`
313/// and nothing else — because the root already commits every field, this one
314/// signature authenticates the whole message (header fields recoverable as
315/// field-openings against the same root, Stage 3).
316///
317/// Suite dispatch is a typed rejection for unimplemented suites (REQ-708):
318/// reject, don't repair, never skip.
319pub fn sign_attestation_v3(
320    suite: &SignatureSuite,
321    root: &str,
322    signer: &dyn Signer,
323) -> Result<Vec<u8>, AttestError> {
324    match suite {
325        SignatureSuite::Ed25519 => Ok(signer.sign(&attestation_v3_preimage(suite, root))),
326        SignatureSuite::Other(s) => Err(AttestError::UnknownSuite(s.clone())),
327    }
328}
329
330/// Verify a v3 signature from `(suite, root, sig)` alone — no header, no
331/// payload (SPEC-017 REQ-812).
332///
333/// Order of checks: suite dispatch (typed rejection for unimplemented
334/// suites, REQ-708), then cryptographic verification over the reconstructed
335/// commitment. A tampered root, a wrong suite, or a wrong signing key each
336/// fail closed: the root and suite are committed in the preimage, so any
337/// change moves the bytes and kills the signature (an unimplemented suite is
338/// rejected before any crypto work).
339pub fn verify_attestation_v3(
340    suite: &SignatureSuite,
341    root: &str,
342    sig: &[u8],
343    signer: &dyn Signer,
344) -> Result<(), AttestError> {
345    if let SignatureSuite::Other(s) = suite {
346        return Err(AttestError::UnknownSuite(s.clone()));
347    }
348    if signer.verify(&attestation_v3_preimage(suite, root), sig) {
349        Ok(())
350    } else {
351        Err(AttestError::InvalidSignature)
352    }
353}
354
355/// What a verification call holds: the discriminated counterpart to
356/// [`SignatureDiscipline`].
357#[derive(Debug, Clone, Copy)]
358pub enum SigningInput<'a> {
359    /// Full canonical message bytes (legacy v1 discipline).
360    V1Full(&'a [u8]),
361    /// Key + authenticated header (v2 discipline; payload-free).
362    V2Attested {
363        key: &'a KeyId,
364        header: &'a AttestationHeader,
365    },
366    /// Suite + typed root (v3 discipline; header-free and payload-free).
367    V3Root {
368        suite: &'a SignatureSuite,
369        root: &'a str,
370    },
371}
372
373impl SigningInput<'_> {
374    /// The discipline this input requires.
375    pub fn discipline(&self) -> SignatureDiscipline {
376        match self {
377            SigningInput::V1Full(_) => SignatureDiscipline::V1Full,
378            SigningInput::V2Attested { .. } => SignatureDiscipline::V2Attested,
379            SigningInput::V3Root { .. } => SignatureDiscipline::V3Root,
380        }
381    }
382}
383
384/// Verify a signature under its declared discipline marker (REQ-701).
385///
386/// Dispatches, never guesses: the marker must match the input's
387/// discipline, otherwise the typed [`AttestError::DisciplineMismatch`] —
388/// so a v1 full-bytes signature can never satisfy an envelope (v2)
389/// verification call, and vice versa. The v1 arm preserves the legacy
390/// semantics bit-for-bit (`Signer::verify` over the full bytes).
391pub fn verify_with_discipline(
392    marker: SignatureDiscipline,
393    input: &SigningInput<'_>,
394    signer: &dyn Signer,
395    sig: &[u8],
396) -> Result<(), AttestError> {
397    match (marker, input) {
398        (SignatureDiscipline::V1Full, SigningInput::V1Full(bytes)) => {
399            if signer.verify(bytes, sig) {
400                Ok(())
401            } else {
402                Err(AttestError::InvalidSignature)
403            }
404        }
405        (SignatureDiscipline::V2Attested, SigningInput::V2Attested { key, header }) => {
406            verify_attestation_v2(signer, key, header, sig)
407        }
408        (SignatureDiscipline::V3Root, SigningInput::V3Root { suite, root }) => {
409            verify_attestation_v3(suite, root, sig, signer)
410        }
411        (marker, input) => Err(AttestError::DisciplineMismatch {
412            marker,
413            input: input.discipline(),
414        }),
415    }
416}
417
418// ---------------------------------------------------------------------------
419// Tests (TEST-701; TEST-708 — suite-dispatch half)
420// ---------------------------------------------------------------------------
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425    use alloc::string::ToString;
426    use alloc::vec::Vec;
427
428    /// Data-dependent test signer: sig = SHA-256(secret ‖ data). Distinct
429    /// secrets model distinct keys; any change to the signed bytes changes
430    /// the expected signature, which is what TEST-701's tampering cases
431    /// need (the constant-signature mocks in `r4.rs` cannot express them).
432    struct TestSigner {
433        secret: &'static [u8],
434    }
435
436    impl Signer for TestSigner {
437        fn sign(&self, data: &[u8]) -> Vec<u8> {
438            use sha2::{Digest, Sha256};
439            let mut h = Sha256::new();
440            h.update(self.secret);
441            h.update(data);
442            h.finalize().to_vec()
443        }
444        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
445            self.sign(data) == sig
446        }
447    }
448
449    const ALICE: TestSigner = TestSigner { secret: b"alice" };
450    const BOB: TestSigner = TestSigner { secret: b"bob" };
451
452    fn key(s: &str) -> KeyId {
453        KeyId::parse(s).unwrap()
454    }
455
456    fn header() -> AttestationHeader {
457        let mut to = BTreeSet::new();
458        to.insert(key("@bob"));
459        to.insert(key("@carol"));
460        AttestationHeader {
461            content_hash: String::from(
462                "f1220aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
463            ),
464            performative: String::from("reveal-bid"),
465            from: key("@alice"),
466            to,
467            thread: String::from("conv-7"),
468            caused_by: Some(CausedBy::Single(String::from(
469                "f1220bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
470            ))),
471        }
472    }
473
474    // ---- preimage construction (ADR-700, CON-700) ----
475
476    #[test]
477    fn preimage_is_domain_tagged_and_names_the_suite() {
478        let bytes = attestation_preimage(&header());
479        let s = core::str::from_utf8(&bytes).unwrap();
480        // "cbcl-attest-v2" (14 chars) + 'S' tag = 15 octets.
481        assert!(s.starts_with("(15:Scbcl-attest-v2"), "got: {s}");
482        assert!(s.contains("8:Sed25519"), "suite must be committed: {s}");
483    }
484
485    #[test]
486    fn preimage_is_deterministic_across_reconstruction() {
487        // Both verifier classes rebuild the identical preimage (REQ-701).
488        assert_eq!(
489            attestation_preimage(&header()),
490            attestation_preimage(&header())
491        );
492    }
493
494    /// TEST-708 adjunct: alias spellings of one identity reconstruct
495    /// identical preimages, so canonicalisation cannot split signatures.
496    #[test]
497    fn alias_key_spellings_reconstruct_identical_preimage() {
498        let mut explicit = header();
499        explicit.from = key("@ed25519:alice");
500        assert_eq!(
501            attestation_preimage(&header()),
502            attestation_preimage(&explicit)
503        );
504    }
505
506    #[test]
507    fn caused_by_forms_encode_distinctly() {
508        let mut begin = header();
509        begin.caused_by = Some(CausedBy::Begin);
510        let mut multi = header();
511        multi.caused_by = Some(CausedBy::Multiple(alloc::vec![
512            "f1220b".to_string(),
513            "f1220c".to_string(),
514        ]));
515        let mut none = header();
516        none.caused_by = None;
517        let all = [
518            attestation_preimage(&header()),
519            attestation_preimage(&begin),
520            attestation_preimage(&multi),
521            attestation_preimage(&none),
522        ];
523        for i in 0..all.len() {
524            for j in (i + 1)..all.len() {
525                assert_ne!(all[i], all[j], "caused-by forms {i} and {j} collide");
526            }
527        }
528    }
529
530    // ---- TEST-701: verify from key + header + hash alone ----
531
532    #[test]
533    fn verify_succeeds_from_header_alone() {
534        let h = header();
535        let sig = sign_attestation_v2(&ALICE, &h).unwrap();
536        // No payload exists anywhere in this test — header fields and the
537        // content hash are the only verification inputs (REQ-701).
538        assert_eq!(
539            verify_attestation_v2(&ALICE, &key("@alice"), &h, &sig),
540            Ok(())
541        );
542    }
543
544    #[test]
545    fn key_substitution_fails() {
546        let h = header();
547        let sig = sign_attestation_v2(&ALICE, &h).unwrap();
548        // Presenting a different key than the attestation names: typed.
549        assert_eq!(
550            verify_attestation_v2(&ALICE, &key("@bob"), &h, &sig),
551            Err(AttestError::KeyMismatch)
552        );
553        // Rewriting the from-key (and presenting Bob's matching identity
554        // and verifier): the preimage changes, so the signature dies.
555        let mut forged = h.clone();
556        forged.from = key("@bob");
557        assert_eq!(
558            verify_attestation_v2(&BOB, &key("@bob"), &forged, &sig),
559            Err(AttestError::InvalidSignature)
560        );
561    }
562
563    #[test]
564    fn hash_substitution_fails() {
565        let h = header();
566        let sig = sign_attestation_v2(&ALICE, &h).unwrap();
567        let mut tampered = h.clone();
568        tampered.content_hash =
569            String::from("f1220cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
570        assert_eq!(
571            verify_attestation_v2(&ALICE, &key("@alice"), &tampered, &sig),
572            Err(AttestError::InvalidSignature)
573        );
574    }
575
576    #[test]
577    fn header_field_tampering_fails() {
578        let h = header();
579        let sig = sign_attestation_v2(&ALICE, &h).unwrap();
580
581        let mut perf = h.clone();
582        perf.performative = String::from("commit-bid");
583
584        let mut to_widened = h.clone();
585        to_widened.to.insert(key("@mallory"));
586
587        let mut to_narrowed = h.clone();
588        to_narrowed.to.remove(&key("@carol"));
589
590        let mut thread = h.clone();
591        thread.thread = String::from("conv-8");
592
593        let mut caused = h.clone();
594        caused.caused_by = Some(CausedBy::Single(String::from(
595            "f1220dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
596        )));
597
598        let mut caused_dropped = h.clone();
599        caused_dropped.caused_by = None;
600
601        for (label, tampered) in [
602            ("performative", perf),
603            ("to-set widened", to_widened),
604            ("to-set narrowed", to_narrowed),
605            ("thread", thread),
606            ("caused-by rewritten", caused),
607            ("caused-by dropped", caused_dropped),
608        ] {
609            assert_eq!(
610                verify_attestation_v2(&ALICE, &key("@alice"), &tampered, &sig),
611                Err(AttestError::InvalidSignature),
612                "tampered field must fail closed: {label}"
613            );
614        }
615    }
616
617    // ---- REQ-701: discipline dispatch, v1 coexistence ----
618
619    #[test]
620    fn v1_path_still_verifies_full_bytes() {
621        let bytes = b"(4:Stell4:Q@bob3:Qhi)";
622        let sig = ALICE.sign(bytes);
623        assert_eq!(
624            verify_with_discipline(
625                SignatureDiscipline::V1Full,
626                &SigningInput::V1Full(bytes),
627                &ALICE,
628                &sig
629            ),
630            Ok(())
631        );
632        assert_eq!(
633            verify_with_discipline(
634                SignatureDiscipline::V1Full,
635                &SigningInput::V1Full(b"(other)"),
636                &ALICE,
637                &sig
638            ),
639            Err(AttestError::InvalidSignature)
640        );
641    }
642
643    #[test]
644    fn v2_path_dispatches_through_discipline() {
645        let h = header();
646        let k = key("@alice");
647        let sig = sign_attestation_v2(&ALICE, &h).unwrap();
648        assert_eq!(
649            verify_with_discipline(
650                SignatureDiscipline::V2Attested,
651                &SigningInput::V2Attested {
652                    key: &k,
653                    header: &h
654                },
655                &ALICE,
656                &sig
657            ),
658            Ok(())
659        );
660    }
661
662    /// REQ-701 fail-closed: a v1-marked signature presented to an envelope
663    /// (v2) verification call is a typed mismatch — even if the bytes
664    /// would verify under some interpretation, no guess is attempted.
665    #[test]
666    fn v1_signature_never_satisfies_v2_call() {
667        let h = header();
668        let k = key("@alice");
669        // A genuine v1 signature over the full canonical message bytes.
670        let v1_sig = ALICE.sign(b"(full-message-bytes)");
671        assert_eq!(
672            verify_with_discipline(
673                SignatureDiscipline::V1Full,
674                &SigningInput::V2Attested {
675                    key: &k,
676                    header: &h
677                },
678                &ALICE,
679                &v1_sig
680            ),
681            Err(AttestError::DisciplineMismatch {
682                marker: SignatureDiscipline::V1Full,
683                input: SignatureDiscipline::V2Attested,
684            })
685        );
686    }
687
688    #[test]
689    fn v2_signature_never_satisfies_v1_call() {
690        let h = header();
691        let sig = sign_attestation_v2(&ALICE, &h).unwrap();
692        assert_eq!(
693            verify_with_discipline(
694                SignatureDiscipline::V2Attested,
695                &SigningInput::V1Full(b"(full-message-bytes)"),
696                &ALICE,
697                &sig
698            ),
699            Err(AttestError::DisciplineMismatch {
700                marker: SignatureDiscipline::V2Attested,
701                input: SignatureDiscipline::V1Full,
702            })
703        );
704    }
705
706    #[test]
707    fn discipline_marker_roundtrip_and_unknown_rejection() {
708        for d in [
709            SignatureDiscipline::V1Full,
710            SignatureDiscipline::V2Attested,
711            SignatureDiscipline::V3Root,
712        ] {
713            assert_eq!(SignatureDiscipline::parse(d.as_str()), Ok(d));
714        }
715        assert_eq!(
716            SignatureDiscipline::parse("v4-guess"),
717            Err(AttestError::UnknownDiscipline("v4-guess".to_string()))
718        );
719    }
720
721    // ---- TEST-708: suite dispatch ----
722
723    #[test]
724    fn unknown_suite_is_typed_rejection_not_pass_not_panic() {
725        let mut h = header();
726        h.from = key("@pq-frodo:alice");
727        let err = AttestError::UnknownSuite("pq-frodo".to_string());
728        assert_eq!(sign_attestation_v2(&ALICE, &h), Err(err.clone()));
729        assert_eq!(
730            verify_attestation_v2(&ALICE, &key("@pq-frodo:alice"), &h, b"sig"),
731            Err(err)
732        );
733    }
734
735    /// TEST-708: an ed25519 signature verifies only against an attestation
736    /// naming `ed25519` — the same header under another suite is a typed
737    /// rejection, and its preimage differs anyway (suite is committed).
738    #[test]
739    fn ed25519_sig_only_verifies_against_ed25519_attestation() {
740        let h = header();
741        let sig = sign_attestation_v2(&ALICE, &h).unwrap();
742        let mut resuited = h.clone();
743        resuited.from = key("@pq-frodo:alice");
744        assert_ne!(
745            attestation_preimage(&h),
746            attestation_preimage(&resuited),
747            "suite must be part of the committed bytes"
748        );
749        assert_eq!(
750            verify_attestation_v2(&ALICE, &key("@pq-frodo:alice"), &resuited, &sig),
751            Err(AttestError::UnknownSuite("pq-frodo".to_string()))
752        );
753    }
754
755    // ---- SPEC-017 REQ-812 Stage 2: v3 sign-the-root discipline ----
756
757    const ROOT: &str = "f12201234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
758
759    #[test]
760    fn v3_preimage_is_domain_tagged_and_names_the_suite() {
761        let bytes = attestation_v3_preimage(&SignatureSuite::Ed25519, ROOT);
762        let s = core::str::from_utf8(&bytes).unwrap();
763        // "cbcl-attest-v3" (14 chars) + 'S' tag = 15 octets, at the head.
764        assert!(s.starts_with("(15:Scbcl-attest-v3"), "got: {s}");
765        assert!(s.contains("8:Sed25519"), "suite must be committed: {s}");
766        // The root rides verbatim; no header field appears.
767        assert!(s.contains(ROOT), "root must be committed: {s}");
768    }
769
770    /// TEST-812: verification needs ONLY (suite, root, sig) — no header, no
771    /// payload exists anywhere in this test.
772    #[test]
773    fn v3_verify_succeeds_from_suite_and_root_alone() {
774        let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
775        assert_eq!(
776            verify_attestation_v3(&SignatureSuite::Ed25519, ROOT, &sig, &ALICE),
777            Ok(())
778        );
779    }
780
781    #[test]
782    fn v3_tampered_root_fails() {
783        let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
784        let other = "f1220ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
785        assert_eq!(
786            verify_attestation_v3(&SignatureSuite::Ed25519, other, &sig, &ALICE),
787            Err(AttestError::InvalidSignature)
788        );
789    }
790
791    #[test]
792    fn v3_wrong_key_fails() {
793        let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
794        // BOB is a distinct signing key; the signature does not carry over.
795        assert_eq!(
796            verify_attestation_v3(&SignatureSuite::Ed25519, ROOT, &sig, &BOB),
797            Err(AttestError::InvalidSignature)
798        );
799    }
800
801    /// TEST-708 for v3: an unimplemented suite is a typed rejection on both
802    /// sign and verify — reject, don't repair, never skip (REQ-708).
803    #[test]
804    fn v3_unknown_suite_is_typed_rejection() {
805        let pq = SignatureSuite::parse("pq-frodo");
806        let err = AttestError::UnknownSuite("pq-frodo".to_string());
807        assert_eq!(sign_attestation_v3(&pq, ROOT, &ALICE), Err(err.clone()));
808        assert_eq!(verify_attestation_v3(&pq, ROOT, b"sig", &ALICE), Err(err));
809    }
810
811    /// keyid canonical suite identity respected: the suite is committed into
812    /// the preimage, so an ed25519 signature can never be replayed under a
813    /// differently-named suite — the bytes differ.
814    #[test]
815    fn v3_suite_is_committed_to_preimage() {
816        let ed = attestation_v3_preimage(&SignatureSuite::Ed25519, ROOT);
817        let pq = attestation_v3_preimage(&SignatureSuite::parse("pq-frodo"), ROOT);
818        assert_ne!(ed, pq, "suite must be part of the committed bytes");
819    }
820
821    #[test]
822    fn v3_path_dispatches_through_discipline() {
823        let sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
824        let suite = SignatureSuite::Ed25519;
825        assert_eq!(
826            verify_with_discipline(
827                SignatureDiscipline::V3Root,
828                &SigningInput::V3Root {
829                    suite: &suite,
830                    root: ROOT
831                },
832                &ALICE,
833                &sig
834            ),
835            Ok(())
836        );
837    }
838
839    /// REQ-701/REQ-812 fail-closed, both directions: a v2 signature presented
840    /// to a v3 verification call (and vice versa) is the typed mismatch — no
841    /// guess is attempted, even if some interpretation might pass.
842    #[test]
843    fn v2_signature_never_satisfies_v3_call() {
844        let h = header();
845        let v2_sig = sign_attestation_v2(&ALICE, &h).unwrap();
846        let suite = SignatureSuite::Ed25519;
847        assert_eq!(
848            verify_with_discipline(
849                SignatureDiscipline::V2Attested,
850                &SigningInput::V3Root {
851                    suite: &suite,
852                    root: ROOT
853                },
854                &ALICE,
855                &v2_sig
856            ),
857            Err(AttestError::DisciplineMismatch {
858                marker: SignatureDiscipline::V2Attested,
859                input: SignatureDiscipline::V3Root,
860            })
861        );
862    }
863
864    #[test]
865    fn v3_signature_never_satisfies_v2_call() {
866        let h = header();
867        let k = key("@alice");
868        let v3_sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
869        assert_eq!(
870            verify_with_discipline(
871                SignatureDiscipline::V3Root,
872                &SigningInput::V2Attested {
873                    key: &k,
874                    header: &h
875                },
876                &ALICE,
877                &v3_sig
878            ),
879            Err(AttestError::DisciplineMismatch {
880                marker: SignatureDiscipline::V3Root,
881                input: SignatureDiscipline::V2Attested,
882            })
883        );
884    }
885
886    /// v3 also fails closed against the legacy v1 full-bytes discipline.
887    #[test]
888    fn v3_signature_never_satisfies_v1_call() {
889        let v3_sig = sign_attestation_v3(&SignatureSuite::Ed25519, ROOT, &ALICE).unwrap();
890        assert_eq!(
891            verify_with_discipline(
892                SignatureDiscipline::V3Root,
893                &SigningInput::V1Full(b"(full-message-bytes)"),
894                &ALICE,
895                &v3_sig
896            ),
897            Err(AttestError::DisciplineMismatch {
898                marker: SignatureDiscipline::V3Root,
899                input: SignatureDiscipline::V1Full,
900            })
901        );
902    }
903}