Skip to main content

cbcl_core/
envelope.rs

1//! Redacted envelopes (SPEC-015 REQ-700..703, NFR-700..702, CON-700,
2//! ADR-702).
3//!
4//! A *redacted envelope* is the payload-free derivative of a signed
5//! message: exactly its content hash, performative name, sender key,
6//! recipient set, thread identifier, signature material, and `:caused-by`
7//! list — and no payload fields (REQ-700). It widens the *evidence*, not
8//! the message: a widened recipient's safety-level verification reads a
9//! predecessor's hash, type, endpoints, and signature — never its payload —
10//! so the envelope satisfies those needs at zero payload disclosure
11//! (ADR-702, NFR-701) and constant size in the payload it redacts
12//! (NFR-700).
13//!
14//! What an envelope *does* reveal is exactly its declared fields: content
15//! hash, performative name, sender key, recipient set, thread, signature,
16//! `:caused-by` references. That is metadata-only disclosure, never *none*
17//! (NFR-702): type, speaker, audience, and causal position remain visible —
18//! usually the knowledge-of-choice being delivered, occasionally the leak.
19//!
20//! Every field a verifier reads is authenticated: the envelope's signature
21//! is the R4 v2 attestation signature (ADR-700), computed over the
22//! canonical preimage of exactly these header fields, so [`RedactedEnvelope::verify`]
23//! needs the envelope's own fields and nothing else (REQ-701). A v1
24//! full-bytes signature can never satisfy an envelope path: the envelope
25//! form *is* the v2 discipline, and a presented v1 marker is the typed
26//! [`AttestError::DisciplineMismatch`] via [`RedactedEnvelope::verify_under_marker`]
27//! (fail closed, review finding 6).
28//!
29//! Grammar (CON-700) — full recognition before any semantic action; an
30//! envelope whose hash fails to parse, whose recipient set exceeds the
31//! caller's R2-derived bound, or which carries any additional field is
32//! rejected, never repaired:
33//!
34//! ```text
35//! envelope    := "(" "envelope" hash perf-name "(" key ")" "(" key* ")"
36//!                    thread sig [":caused-by" caused-ref] ")"
37//! hash        := "f1220" hex64
38//! thread      := string | symbol
39//! key         := "@" [suite ":"] symbol   ; omitted suite → ed25519 (REQ-708)
40//! sig         := string                   ; lowercase hex of the v2 signature
41//! caused-ref  := hash | "(" hash+ ")" | "begin"
42//! ```
43//!
44//! The completion boundary (REQ-703) lives elsewhere by design: this module
45//! makes envelopes *available* to the safety-level lookups of
46//! `protocol::verify_causal` (via `store::MessageStore::envelope_in_thread`),
47//! while the completion-level occupant fan-in of `projection.rs` (REQ-618)
48//! never consults them — full validity includes payload grammaticality, so
49//! fan-in deciders still require full messages.
50
51#![forbid(unsafe_code)]
52
53use crate::attest::{
54    sign_attestation_v3, verify_attestation_v2, verify_attestation_v3, verify_with_discipline,
55    AttestError, AttestationHeader, SignatureDiscipline, SigningInput,
56};
57use crate::equivocation::{attestation_header_for, MemberDefect};
58use crate::keyid::{KeyId, KeyIdError, SignatureSuite};
59use crate::message::{CausedBy, Message};
60use crate::protocol::BEGIN_KEYWORD;
61use crate::r4::Signer;
62use crate::sexpr::{Atom, SExpr};
63use crate::typed_addr::{self, FieldId, Opening};
64use alloc::collections::BTreeSet;
65use alloc::string::String;
66use alloc::vec::Vec;
67use core::fmt;
68
69/// Head symbol of the CON-700 envelope production.
70pub const ENVELOPE_HEAD: &str = "envelope";
71
72/// A redacted envelope (REQ-700): the authenticated header of a signed
73/// message plus the R4 v2 signature over that header's attestation
74/// preimage — and nothing else. Its size is bounded by role-set size and
75/// `:caused-by` arity, independent of the redacted payload (NFR-700).
76///
77/// Field trustworthiness: the header fields are *claims* until
78/// [`RedactedEnvelope::verify`] succeeds; after that, every field is
79/// exactly what the sender's key vouched for (REQ-701). Store acceptance
80/// goes through `ThreadedMessageStore::append_envelope`, which verifies
81/// first and places the envelope in the thread its authenticated thread
82/// field names (REQ-702).
83#[derive(Debug, Clone, PartialEq, Eq)]
84#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
85pub struct RedactedEnvelope {
86    /// The authenticated header: content hash, performative, sender key,
87    /// recipient set, thread, `:caused-by` — the exact fields the v2
88    /// attestation preimage commits to (ADR-700).
89    pub header: AttestationHeader,
90    /// R4 v2 signature over `attest::attestation_preimage(&header)`.
91    pub signature: Vec<u8>,
92}
93
94impl RedactedEnvelope {
95    /// Content hash of the message this envelope redacts (`f1220<hex64>`).
96    pub fn content_hash(&self) -> &str {
97        &self.header.content_hash
98    }
99
100    /// Performative name of the redacted message.
101    pub fn performative(&self) -> &str {
102        &self.header.performative
103    }
104
105    /// Thread identifier — the envelope carries its thread, and store
106    /// placement is by this authenticated field (REQ-702).
107    pub fn thread(&self) -> &str {
108        &self.header.thread
109    }
110
111    /// REQ-701: verify the envelope from its own fields alone — the payload
112    /// is never an input. Reconstructs the identical attestation preimage a
113    /// full-message holder would, and dispatches on the key's signature
114    /// suite (typed rejection for unimplemented suites, REQ-708).
115    pub fn verify(&self, signer: &dyn Signer) -> Result<(), AttestError> {
116        verify_attestation_v2(signer, &self.header.from, &self.header, &self.signature)
117    }
118
119    /// Verify under an explicitly presented discipline marker (REQ-701).
120    ///
121    /// The envelope form *is* the v2 discipline, so a signature declaring
122    /// `v1` is the typed [`AttestError::DisciplineMismatch`] — a v1
123    /// full-bytes signature never satisfies an envelope path, and no guess
124    /// is attempted (fail closed, review finding 6).
125    pub fn verify_under_marker(
126        &self,
127        marker: SignatureDiscipline,
128        signer: &dyn Signer,
129    ) -> Result<(), AttestError> {
130        verify_with_discipline(
131            marker,
132            &SigningInput::V2Attested {
133                key: &self.header.from,
134                header: &self.header,
135            },
136            signer,
137            &self.signature,
138        )
139    }
140
141    /// Serialise to the CON-700 `envelope` production.
142    ///
143    /// Canonical choices: keys in suite-explicit spelling, the recipient
144    /// set in its canonical (suite, name) order, the thread as a string,
145    /// the signature as lowercase hex — so serialise ∘ parse is identity
146    /// and any holder re-derives identical bytes.
147    pub fn to_sexpr(&self) -> SExpr {
148        use alloc::vec;
149        let h = &self.header;
150        let mut items = vec![
151            SExpr::Atom(Atom::Symbol(String::from(ENVELOPE_HEAD))),
152            SExpr::Atom(Atom::Symbol(h.content_hash.clone())),
153            SExpr::Atom(Atom::Symbol(h.performative.clone())),
154            SExpr::List(vec![SExpr::Atom(Atom::Symbol(h.from.canonical_spelling()))]),
155            SExpr::List(
156                h.to.iter()
157                    .map(|k| SExpr::Atom(Atom::Symbol(k.canonical_spelling())))
158                    .collect(),
159            ),
160            SExpr::Atom(Atom::Str(h.thread.clone())),
161            SExpr::Atom(Atom::Str(hex_encode(&self.signature))),
162        ];
163        if let Some(cb) = &h.caused_by {
164            items.push(SExpr::Atom(Atom::Keyword(String::from("caused-by"))));
165            items.push(match cb {
166                CausedBy::Begin => SExpr::Atom(Atom::Symbol(String::from(BEGIN_KEYWORD))),
167                CausedBy::Single(hash) => SExpr::Atom(Atom::Symbol(hash.clone())),
168                CausedBy::Multiple(hashes) => SExpr::List(
169                    hashes
170                        .iter()
171                        .map(|hash| SExpr::Atom(Atom::Symbol(hash.clone())))
172                        .collect(),
173                ),
174            });
175        }
176        SExpr::List(items)
177    }
178}
179
180/// REQ-700: redaction — the pure function from a signed message (message +
181/// its detached R4 v2 attestation signature) to its redacted envelope.
182///
183/// The envelope identifies the message it redacts by content hash: the
184/// header is `attestation_header_for(message)`, whose `content_hash` is
185/// computed from the message's canonical bytes, so redaction and the
186/// original message name the same hash by construction (TEST-700).
187///
188/// Rejects (typed) a message missing any committed header field — an
189/// envelope that cannot carry its full authenticated header is never
190/// produced partially (LangSec: reject, don't repair).
191pub fn redact(message: &Message, signature: Vec<u8>) -> Result<RedactedEnvelope, MemberDefect> {
192    Ok(RedactedEnvelope {
193        header: attestation_header_for(message)?,
194        signature,
195    })
196}
197
198/// Typed rejection for the CON-700 envelope parser — full recognition
199/// before any semantic action; nothing is repaired.
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub enum EnvelopeParseError {
202    /// The input is not a list headed by the `envelope` symbol.
203    NotAnEnvelopeForm,
204    /// Wrong number of items: 7 (no `:caused-by`) or 9 (with it).
205    WrongArity { found: usize },
206    /// The `hash` position is not a well-formed `f1220<hex64>` symbol.
207    MalformedHash,
208    /// The `perf-name` position is not a symbol.
209    MalformedPerformative,
210    /// The sender position is not a list of exactly one key.
211    MalformedFromList,
212    /// A key does not parse as `@[suite:]name` (REQ-708).
213    MalformedKey(KeyIdError),
214    /// The recipient position is not a list of keys.
215    MalformedToList,
216    /// The recipient set exceeds the caller's R2-derived bound (CON-700).
217    RecipientBoundExceeded { count: usize, max: usize },
218    /// The `thread` position is neither a string nor a symbol.
219    MalformedThread,
220    /// The `sig` position is not a non-empty lowercase-hex string.
221    MalformedSignature,
222    /// Item 7 of a 9-item form is not the `:caused-by` keyword — any other
223    /// additional field is rejected, never repaired (CON-700).
224    UnexpectedField,
225    /// The `caused-ref` is not `begin`, a hash, or a non-empty hash list.
226    MalformedCausedBy,
227}
228
229impl fmt::Display for EnvelopeParseError {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        match self {
232            Self::NotAnEnvelopeForm => f.write_str("not an (envelope …) form"),
233            Self::WrongArity { found } => {
234                write!(f, "envelope must have 7 or 9 items, found {found}")
235            }
236            Self::MalformedHash => f.write_str("envelope hash is not f1220<hex64>"),
237            Self::MalformedPerformative => f.write_str("envelope performative is not a symbol"),
238            Self::MalformedFromList => {
239                f.write_str("envelope sender is not a list of exactly one key")
240            }
241            Self::MalformedKey(e) => write!(f, "envelope key is malformed: {e}"),
242            Self::MalformedToList => f.write_str("envelope recipients are not a list of keys"),
243            Self::RecipientBoundExceeded { count, max } => {
244                write!(
245                    f,
246                    "envelope recipient set of {count} exceeds the bound {max}"
247                )
248            }
249            Self::MalformedThread => f.write_str("envelope thread is not a string or symbol"),
250            Self::MalformedSignature => {
251                f.write_str("envelope signature is not a non-empty lowercase-hex string")
252            }
253            Self::UnexpectedField => {
254                f.write_str("envelope carries an additional field (only :caused-by is legal)")
255            }
256            Self::MalformedCausedBy => {
257                f.write_str("envelope :caused-by is not begin, a hash, or a hash list")
258            }
259        }
260    }
261}
262
263/// Whether `s` is a CON-700 `hash`: `f1220` followed by exactly 64
264/// lowercase hex digits.
265pub fn is_content_hash(s: &str) -> bool {
266    match s.strip_prefix("f1220") {
267        Some(hex) => {
268            hex.len() == 64
269                && hex
270                    .bytes()
271                    .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
272        }
273        None => false,
274    }
275}
276
277fn hex_encode(bytes: &[u8]) -> String {
278    const HEX: &[u8; 16] = b"0123456789abcdef";
279    let mut out = String::with_capacity(bytes.len() * 2);
280    for b in bytes {
281        out.push(HEX[(b >> 4) as usize] as char);
282        out.push(HEX[(b & 0x0f) as usize] as char);
283    }
284    out
285}
286
287/// Strict lowercase-hex decode; anything else is `None` (reject, don't
288/// repair — an uppercase or odd-length spelling is not normalised).
289fn hex_decode(s: &str) -> Option<Vec<u8>> {
290    if s.is_empty() || s.len() % 2 != 0 {
291        return None;
292    }
293    let nibble = |b: u8| -> Option<u8> {
294        match b {
295            b'0'..=b'9' => Some(b - b'0'),
296            b'a'..=b'f' => Some(b - b'a' + 10),
297            _ => None,
298        }
299    };
300    let bytes = s.as_bytes();
301    let mut out = Vec::with_capacity(bytes.len() / 2);
302    for pair in bytes.chunks_exact(2) {
303        out.push(nibble(pair[0])? << 4 | nibble(pair[1])?);
304    }
305    Some(out)
306}
307
308fn parse_key(item: &SExpr) -> Result<KeyId, EnvelopeParseError> {
309    match item {
310        SExpr::Atom(Atom::Symbol(s)) => KeyId::parse(s).map_err(EnvelopeParseError::MalformedKey),
311        _ => Err(EnvelopeParseError::MalformedKey(KeyIdError::MissingSigil)),
312    }
313}
314
315fn parse_caused_ref(item: &SExpr) -> Result<CausedBy, EnvelopeParseError> {
316    let as_hash = |s: &str| -> Result<String, EnvelopeParseError> {
317        if is_content_hash(s) {
318            Ok(String::from(s))
319        } else {
320            Err(EnvelopeParseError::MalformedCausedBy)
321        }
322    };
323    match item {
324        SExpr::Atom(Atom::Symbol(s)) if s == BEGIN_KEYWORD => Ok(CausedBy::Begin),
325        SExpr::Atom(Atom::Symbol(s)) | SExpr::Atom(Atom::Str(s)) => {
326            Ok(CausedBy::Single(as_hash(s)?))
327        }
328        SExpr::List(items) if !items.is_empty() => {
329            let mut hashes = Vec::with_capacity(items.len());
330            for it in items {
331                match it {
332                    SExpr::Atom(Atom::Symbol(s)) | SExpr::Atom(Atom::Str(s)) => {
333                        hashes.push(as_hash(s)?);
334                    }
335                    _ => return Err(EnvelopeParseError::MalformedCausedBy),
336                }
337            }
338            // Canonical ordering, mirroring the message layer's REQ-202
339            // canonicalisation — both verifier classes rebuild identical
340            // attestation preimages.
341            hashes.sort();
342            Ok(CausedBy::Multiple(hashes))
343        }
344        _ => Err(EnvelopeParseError::MalformedCausedBy),
345    }
346}
347
348/// Parse the CON-700 `envelope` production — full recognition, reject-never
349/// -repair. `max_recipients` is the caller's R2-derived bound on the
350/// recipient set (role sets are already bounded by R2; an envelope claiming
351/// more recipients than the deployment admits is rejected structurally,
352/// before any signature work).
353pub fn parse_envelope(
354    sexpr: &SExpr,
355    max_recipients: usize,
356) -> Result<RedactedEnvelope, EnvelopeParseError> {
357    let SExpr::List(items) = sexpr else {
358        return Err(EnvelopeParseError::NotAnEnvelopeForm);
359    };
360    if items.first().map(|h| h.is_symbol(ENVELOPE_HEAD)) != Some(true) {
361        return Err(EnvelopeParseError::NotAnEnvelopeForm);
362    }
363    if items.len() != 7 && items.len() != 9 {
364        return Err(EnvelopeParseError::WrongArity { found: items.len() });
365    }
366
367    // hash
368    let content_hash = match &items[1] {
369        SExpr::Atom(Atom::Symbol(s)) if is_content_hash(s) => s.clone(),
370        _ => return Err(EnvelopeParseError::MalformedHash),
371    };
372    // perf-name
373    let performative = match &items[2] {
374        SExpr::Atom(Atom::Symbol(s)) => s.clone(),
375        _ => return Err(EnvelopeParseError::MalformedPerformative),
376    };
377    // "(" key ")" — exactly one sender key
378    let from = match &items[3] {
379        SExpr::List(ks) if ks.len() == 1 => parse_key(&ks[0])?,
380        _ => return Err(EnvelopeParseError::MalformedFromList),
381    };
382    // "(" key* ")" — recipient set, bounded
383    let to: BTreeSet<KeyId> = match &items[4] {
384        SExpr::List(ks) => {
385            if ks.len() > max_recipients {
386                return Err(EnvelopeParseError::RecipientBoundExceeded {
387                    count: ks.len(),
388                    max: max_recipients,
389                });
390            }
391            let mut set = BTreeSet::new();
392            for k in ks {
393                set.insert(parse_key(k)?);
394            }
395            set
396        }
397        _ => return Err(EnvelopeParseError::MalformedToList),
398    };
399    // thread := string | symbol
400    let thread = match &items[5] {
401        SExpr::Atom(Atom::Str(s)) | SExpr::Atom(Atom::Symbol(s)) => s.clone(),
402        _ => return Err(EnvelopeParseError::MalformedThread),
403    };
404    // sig := string (lowercase hex of the v2 signature bytes)
405    let signature = match &items[6] {
406        SExpr::Atom(Atom::Str(s)) => hex_decode(s).ok_or(EnvelopeParseError::MalformedSignature)?,
407        _ => return Err(EnvelopeParseError::MalformedSignature),
408    };
409    // optional [":caused-by" caused-ref]; any other trailing field rejected
410    let caused_by = if items.len() == 9 {
411        match &items[7] {
412            SExpr::Atom(Atom::Keyword(k)) if k == "caused-by" => {}
413            _ => return Err(EnvelopeParseError::UnexpectedField),
414        }
415        Some(parse_caused_ref(&items[8])?)
416    } else {
417        None
418    };
419
420    Ok(RedactedEnvelope {
421        header: AttestationHeader {
422            content_hash,
423            performative,
424            from,
425            to,
426            thread,
427            caused_by,
428        },
429        signature,
430    })
431}
432
433// ---------------------------------------------------------------------------
434// SPEC-017 REQ-813 Stage 3: opened envelopes — native field-openings
435// ---------------------------------------------------------------------------
436
437/// The SPEC-015 envelope header fields (leaves 0–4), in canonical order.
438///
439/// Opening exactly these reproduces a redacted envelope's disclosure —
440/// performative, from, to, `:caused-by`, thread — while leaf 5 (payload)
441/// stays sealed (NFR-701). This is the field set redacted delivery opens.
442pub const HEADER_FIELDS: [FieldId; 5] = [
443    FieldId::Performative,
444    FieldId::From,
445    FieldId::To,
446    FieldId::CausedBy,
447    FieldId::Thread,
448];
449
450/// An **opened envelope** (SPEC-017 REQ-813): the typed content address
451/// (`root`), a v3 root-signature over it, and a set of authenticated
452/// field-openings against that root.
453///
454/// This is the Stage-3 successor to [`RedactedEnvelope`]. Where a redacted
455/// envelope *reconstructs* a header and re-binds it with a v2 attestation,
456/// an opened envelope carries each header field as a self-authenticating
457/// [`Opening`] of the *same* Merkle root the single v3 signature vouches for
458/// ([`crate::attest::sign_attestation_v3`]): the header authentication is
459/// now the content address's own read-out, not a separate signed object.
460///
461/// Redacted delivery opens leaves 0–4 (the [`HEADER_FIELDS`]) and seals
462/// leaf 5, so a widened recipient learns the predecessor's type, endpoints,
463/// causal position and thread at zero payload disclosure (NFR-701). Opening
464/// the payload leaf as well is the full-content path a completion decider
465/// needs ([[SPEC-015 REQ-703]]); an opened envelope built for redacted
466/// delivery deliberately omits it, preserving the safety/completion boundary.
467///
468/// Constant size: each opening is a fixed ≤3-sibling path (NFR-700), so the
469/// envelope is bounded by the header-field count, independent of the
470/// redacted payload.
471///
472/// Trust: `root`, `suite`, and the opening *values* are claims until
473/// [`verify_opened`] succeeds; after that, the v3 signature vouches for the
474/// root and every opening authenticates a field value against it. Any party
475/// can forward a genuine opened envelope; only the signer can *produce* one
476/// (the v3 signature needs the private key), and forging any field fails
477/// [`verify_opened`].
478#[derive(Debug, Clone, PartialEq, Eq)]
479#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
480pub struct OpenedEnvelope {
481    /// The typed Merkle root — the message's content address
482    /// (`f1220<hex64>`), which the v3 signature commits to.
483    pub root: String,
484    /// Signature suite named in the v3 attestation preimage (REQ-708): a v3
485    /// signature can never be re-read under a different suite.
486    pub suite: SignatureSuite,
487    /// v3 root-signature over `(cbcl-attest-v3 <suite> <root>)` (REQ-812).
488    pub signature: Vec<u8>,
489    /// Authenticated field-openings against `root`. For redacted delivery
490    /// these are the [`HEADER_FIELDS`]; the payload leaf is absent.
491    pub openings: Vec<Opening>,
492}
493
494impl OpenedEnvelope {
495    /// The content address the v3 signature vouches for (`f1220<hex64>`).
496    pub fn content_hash(&self) -> &str {
497        &self.root
498    }
499
500    /// The opening for `field`, if this envelope discloses it.
501    pub fn opening(&self, field: FieldId) -> Option<&Opening> {
502        self.openings.iter().find(|o| o.field == field)
503    }
504
505    /// Authenticated performative type, from the Performative opening
506    /// (leaf 0). `None` if that leaf is not opened or is malformed.
507    pub fn performative(&self) -> Option<&str> {
508        match &self.opening(FieldId::Performative)?.value {
509            SExpr::Atom(Atom::Symbol(s)) => Some(s.as_str()),
510            _ => None,
511        }
512    }
513
514    /// Authenticated causal reference, distinguishing a sealed/malformed leaf
515    /// (`None`) from an authenticated absence (`Some(None)`).
516    pub(crate) fn causal_reference(&self) -> Option<Option<CausedBy>> {
517        match &self.opening(FieldId::CausedBy)?.value {
518            SExpr::List(items) if items.is_empty() => Some(None),
519            SExpr::List(items) if items.len() == 1 => parse_caused_ref(&items[0]).ok().map(Some),
520            _ => None,
521        }
522    }
523
524    /// Authenticated thread identifier, from the Thread opening (leaf 4).
525    pub fn thread(&self) -> Option<&str> {
526        opt_leaf_str(&self.opening(FieldId::Thread)?.value)
527    }
528
529    /// Authenticated sender spelling, from the From opening (leaf 1).
530    pub fn from_spelling(&self) -> Option<&str> {
531        opt_leaf_str(&self.opening(FieldId::From)?.value)
532    }
533
534    /// Authenticated recipient spellings, from the To opening (leaf 2).
535    pub fn to_spellings(&self) -> Option<Vec<&str>> {
536        match &self.opening(FieldId::To)?.value {
537            SExpr::List(items) => items
538                .iter()
539                .map(|i| match i {
540                    SExpr::Atom(Atom::Symbol(s)) => Some(s.as_str()),
541                    _ => None,
542                })
543                .collect(),
544            _ => None,
545        }
546    }
547}
548
549/// Read an `opt`-wrapped leaf value (`typed_addr::field_sexpr`'s `Some(v) →
550/// (v)`, `None → ()`): `(s)` → `Some(s)`, `()` → `None`.
551fn opt_leaf_str(v: &SExpr) -> Option<&str> {
552    match v {
553        SExpr::List(items) if items.len() == 1 => match &items[0] {
554            SExpr::Atom(Atom::Str(s)) | SExpr::Atom(Atom::Symbol(s)) => Some(s.as_str()),
555            _ => None,
556        },
557        _ => None,
558    }
559}
560
561/// Typed rejection for [`verify_opened`] — fail closed, LangSec discipline
562/// (reject, never repair; never a skipped check).
563#[derive(Debug, Clone, PartialEq, Eq)]
564pub enum OpenedError {
565    /// The v3 root-signature did not verify: a tampered root, a wrong suite,
566    /// an unimplemented suite, or a wrong signing key (fail closed).
567    Attestation(AttestError),
568    /// A field-opening did not authenticate against the signed root — a
569    /// forged or corrupted field value, path, or side.
570    OpeningFailed { field: FieldId },
571    /// A required header field was not disclosed by this envelope.
572    MissingField { field: FieldId },
573}
574
575impl fmt::Display for OpenedError {
576    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577        match self {
578            Self::Attestation(e) => write!(f, "opened-envelope root-signature invalid: {e}"),
579            Self::OpeningFailed { field } => {
580                write!(
581                    f,
582                    "opened-envelope field {field:?} fails to open against the root"
583                )
584            }
585            Self::MissingField { field } => {
586                write!(f, "opened-envelope does not disclose field {field:?}")
587            }
588        }
589    }
590}
591
592/// Build an opened envelope for `msg` (REQ-813): sign its typed root under
593/// the v3 discipline and open exactly `fields` against that root.
594///
595/// `fields` selects which leaves to disclose — redacted delivery passes
596/// [`HEADER_FIELDS`] (payload sealed); a full-content path additionally
597/// passes [`FieldId::Payload`]. Only the holder of the signing key can
598/// produce one (the v3 signature); any relay can forward the result.
599///
600/// Suite dispatch is a typed rejection for unimplemented suites (REQ-708),
601/// inherited from [`sign_attestation_v3`].
602pub fn build_opened(
603    msg: &Message,
604    fields: &[FieldId],
605    suite: &SignatureSuite,
606    signer: &dyn Signer,
607) -> Result<OpenedEnvelope, AttestError> {
608    let root = typed_addr::typed_root(msg);
609    let signature = sign_attestation_v3(suite, &root, signer)?;
610    let openings = fields.iter().map(|&f| typed_addr::open(msg, f)).collect();
611    Ok(OpenedEnvelope {
612        root,
613        suite: suite.clone(),
614        signature,
615        openings,
616    })
617}
618
619/// Verify an opened envelope (REQ-813), in two steps and fail-closed:
620///
621/// 1. the v3 root-signature via [`verify_attestation_v3`] — this
622///    authenticates `root` under the sender's key (`signer` embodies that
623///    key's verification, the R4 convention);
624/// 2. every field-opening against that now-signed root via
625///    [`typed_addr::verify_opening`].
626///
627/// Order is load-bearing: the signature authenticates the root first, so a
628/// passing opening then proves its value under a root the sender vouched
629/// for. A relay that only forwards a genuine envelope passes; a forger who
630/// edits any field (value, path, or side) fails at step 2, and one who
631/// edits the root fails at step 1 — no payload is ever an input (NFR-701).
632pub fn verify_opened(env: &OpenedEnvelope, signer: &dyn Signer) -> Result<(), OpenedError> {
633    verify_attestation_v3(&env.suite, &env.root, &env.signature, signer)
634        .map_err(OpenedError::Attestation)?;
635    for op in &env.openings {
636        if !typed_addr::verify_opening(&env.root, op.field, &op.value, op) {
637            return Err(OpenedError::OpeningFailed { field: op.field });
638        }
639    }
640    Ok(())
641}
642
643// ---------------------------------------------------------------------------
644// Tests (TEST-700; TEST-701 — envelope half; CON-700 recognition)
645// ---------------------------------------------------------------------------
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650    use crate::attest::sign_attestation_v2;
651    use crate::equivocation::message_content_hash;
652    use crate::message::{Performative, Recipients};
653    use alloc::format;
654    use alloc::string::ToString;
655    use alloc::vec;
656
657    /// Data-dependent test signer (same construction as `attest.rs` tests):
658    /// sig = SHA-256(secret ‖ data), so any preimage change kills the
659    /// signature and distinct secrets model distinct keys.
660    struct TestSigner {
661        secret: &'static [u8],
662    }
663
664    impl Signer for TestSigner {
665        fn sign(&self, data: &[u8]) -> Vec<u8> {
666            use sha2::{Digest, Sha256};
667            let mut h = Sha256::new();
668            h.update(self.secret);
669            h.update(data);
670            h.finalize().to_vec()
671        }
672        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
673            self.sign(data) == sig
674        }
675    }
676
677    const ALICE: TestSigner = TestSigner { secret: b"alice" };
678    const BOB: TestSigner = TestSigner { secret: b"bob" };
679
680    fn key(s: &str) -> KeyId {
681        KeyId::parse(s).unwrap()
682    }
683
684    fn hash64(c: char) -> String {
685        format!("f1220{}", c.to_string().repeat(64))
686    }
687
688    fn sample_message(caused_by: Option<CausedBy>) -> Message {
689        let mut to = alloc::collections::BTreeSet::new();
690        to.insert("@bob".to_string());
691        to.insert("@carol".to_string());
692        Message::Simple {
693            performative: Performative::Custom("reveal-bid".to_string()),
694            recipient: Some(Recipients::Set(to)),
695            content: SExpr::Atom(Atom::Str("the secret payload".to_string())),
696            params: Vec::new(),
697            thread: Some("conv-7".to_string()),
698            sender: Some("@alice".to_string()),
699            caused_by,
700        }
701    }
702
703    fn signed_envelope(msg: &Message, signer: &dyn Signer) -> RedactedEnvelope {
704        let header = attestation_header_for(msg).unwrap();
705        let sig = sign_attestation_v2(signer, &header).unwrap();
706        redact(msg, sig).unwrap()
707    }
708
709    // ---- TEST-700: redaction round-trip ----
710
711    #[test]
712    fn redaction_names_the_same_content_hash() {
713        let m = sample_message(Some(CausedBy::Single(hash64('b'))));
714        let env = signed_envelope(&m, &ALICE);
715        assert_eq!(env.content_hash(), message_content_hash(&m));
716        assert_eq!(env.performative(), "reveal-bid");
717        assert_eq!(env.thread(), "conv-7");
718    }
719
720    #[test]
721    fn redaction_is_pure_and_deterministic() {
722        let m = sample_message(Some(CausedBy::Begin));
723        let sig = vec![1u8, 2, 3];
724        assert_eq!(redact(&m, sig.clone()), redact(&m, sig));
725    }
726
727    #[test]
728    fn redaction_rejects_a_message_missing_committed_fields() {
729        let mut m = sample_message(None);
730        if let Message::Simple { sender, .. } = &mut m {
731            *sender = None;
732        }
733        assert_eq!(redact(&m, Vec::new()), Err(MemberDefect::MissingSender));
734    }
735
736    /// TEST-700 property: over generated messages, the envelope names the
737    /// message's own content hash, verifies from its fields alone, and the
738    /// CON-700 serialisation round-trips exactly.
739    #[test]
740    fn test_700_property_roundtrip_over_generated_messages() {
741        use proptest::prelude::*;
742        use proptest::test_runner::TestRunner;
743
744        let strategy = (
745            "[a-z][a-z0-9-]{0,12}",                                  // performative
746            "[a-z][a-z0-9]{0,8}",                                    // sender name
747            prop::collection::btree_set("[a-z][a-z0-9]{0,8}", 0..4), // recipients
748            "[a-z0-9-]{1,12}",                                       // thread
749            "[ -~]{0,24}",                                           // payload text
750            prop_oneof![
751                Just(None),
752                Just(Some(CausedBy::Begin)),
753                prop::collection::vec("[0-9a-f]{64}", 1..4).prop_map(|hs| {
754                    let mut hashes: Vec<String> =
755                        hs.into_iter().map(|h| format!("f1220{h}")).collect();
756                    hashes.sort();
757                    Some(if hashes.len() == 1 {
758                        CausedBy::Single(hashes.pop().unwrap())
759                    } else {
760                        CausedBy::Multiple(hashes)
761                    })
762                }),
763            ],
764        );
765
766        let mut runner = TestRunner::default();
767        runner
768            .run(
769                &strategy,
770                |(perf, sender, to, thread, payload, caused_by)| {
771                    let recipient = if to.is_empty() {
772                        None
773                    } else {
774                        Some(Recipients::Set(
775                            to.iter().map(|r| format!("@{r}")).collect(),
776                        ))
777                    };
778                    let m = Message::Simple {
779                        performative: Performative::Custom(perf),
780                        recipient,
781                        content: SExpr::Atom(Atom::Str(payload)),
782                        params: Vec::new(),
783                        thread: Some(thread),
784                        sender: Some(format!("@{sender}")),
785                        caused_by,
786                    };
787                    let env = signed_envelope(&m, &ALICE);
788                    // Same content hash as the message it redacts (REQ-700).
789                    let expected_hash = message_content_hash(&m);
790                    prop_assert_eq!(env.content_hash(), expected_hash.as_str());
791                    // Verifies from its own fields alone (REQ-701).
792                    prop_assert_eq!(env.verify(&ALICE), Ok(()));
793                    // CON-700 serialise ∘ parse is identity.
794                    let reparsed = parse_envelope(&env.to_sexpr(), 8).unwrap();
795                    prop_assert_eq!(&reparsed, &env);
796                    Ok(())
797                },
798            )
799            .unwrap();
800    }
801
802    // ---- TEST-701 (envelope half): verification without the payload ----
803
804    #[test]
805    fn envelope_verifies_without_the_payload() {
806        let m = sample_message(Some(CausedBy::Single(hash64('b'))));
807        let env = signed_envelope(&m, &ALICE);
808        // The payload exists nowhere in the envelope: its serialisation
809        // does not contain the message's content (NFR-701).
810        let wire = env.to_sexpr().to_string();
811        assert!(
812            !wire.contains("the secret payload"),
813            "payload leaked: {wire}"
814        );
815        assert_eq!(env.verify(&ALICE), Ok(()));
816    }
817
818    #[test]
819    fn envelope_field_tampering_fails_closed() {
820        let m = sample_message(Some(CausedBy::Single(hash64('b'))));
821        let env = signed_envelope(&m, &ALICE);
822
823        let mut hash = env.clone();
824        hash.header.content_hash = hash64('c');
825
826        let mut perf = env.clone();
827        perf.header.performative = "commit-bid".to_string();
828
829        let mut thread = env.clone();
830        thread.header.thread = "conv-8".to_string();
831
832        let mut widened = env.clone();
833        widened.header.to.insert(key("@mallory"));
834
835        let mut caused = env.clone();
836        caused.header.caused_by = Some(CausedBy::Begin);
837
838        for (label, tampered) in [
839            ("hash substitution", hash),
840            ("performative", perf),
841            ("thread relabelling", thread),
842            ("recipient widening", widened),
843            ("caused-by rewrite", caused),
844        ] {
845            assert_eq!(
846                tampered.verify(&ALICE),
847                Err(AttestError::InvalidSignature),
848                "{label} must fail closed"
849            );
850        }
851    }
852
853    #[test]
854    fn envelope_key_substitution_fails() {
855        let m = sample_message(None);
856        let mut env = signed_envelope(&m, &ALICE);
857        env.header.from = key("@bob");
858        // Bob's own verifier and identity: the preimage changed, so the
859        // signature is dead — a genuine envelope cannot be re-attributed.
860        assert_eq!(env.verify(&BOB), Err(AttestError::InvalidSignature));
861    }
862
863    /// REQ-701 fail-closed: a v1 marker on an envelope path is the typed
864    /// discipline mismatch; a v1 full-bytes signature never verifies.
865    #[test]
866    fn v1_signature_never_satisfies_an_envelope() {
867        let m = sample_message(None);
868        let mut env = signed_envelope(&m, &ALICE);
869        assert_eq!(
870            env.verify_under_marker(SignatureDiscipline::V1Full, &ALICE),
871            Err(AttestError::DisciplineMismatch {
872                marker: SignatureDiscipline::V1Full,
873                input: SignatureDiscipline::V2Attested,
874            })
875        );
876        // Even smuggled under the v2 marker, a signature over the full
877        // canonical message bytes is not a signature over the attestation.
878        env.signature = ALICE.sign(&crate::canonical::canonical_encode(&SExpr::from(&m)));
879        assert_eq!(
880            env.verify_under_marker(SignatureDiscipline::V2Attested, &ALICE),
881            Err(AttestError::InvalidSignature)
882        );
883    }
884
885    #[test]
886    fn unknown_suite_is_typed_rejection() {
887        let m = sample_message(None);
888        let mut env = signed_envelope(&m, &ALICE);
889        env.header.from = key("@pq-frodo:alice");
890        assert_eq!(
891            env.verify(&ALICE),
892            Err(AttestError::UnknownSuite("pq-frodo".to_string()))
893        );
894    }
895
896    // ---- CON-700: grammar recognition ----
897
898    #[test]
899    fn serialised_envelope_matches_the_grammar_shape() {
900        let m = sample_message(Some(CausedBy::Single(hash64('b'))));
901        let env = signed_envelope(&m, &ALICE);
902        let SExpr::List(items) = env.to_sexpr() else {
903            panic!("envelope serialises to a list");
904        };
905        assert_eq!(items.len(), 9);
906        assert!(items[0].is_symbol("envelope"));
907        assert!(matches!(&items[3], SExpr::List(ks) if ks.len() == 1));
908        assert!(matches!(&items[5], SExpr::Atom(Atom::Str(_))));
909        assert!(matches!(&items[7], SExpr::Atom(Atom::Keyword(k)) if k == "caused-by"));
910    }
911
912    #[test]
913    fn parse_roundtrips_all_caused_by_forms() {
914        for cb in [
915            None,
916            Some(CausedBy::Begin),
917            Some(CausedBy::Single(hash64('b'))),
918            Some(CausedBy::Multiple(vec![hash64('b'), hash64('c')])),
919        ] {
920            let env = signed_envelope(&sample_message(cb), &ALICE);
921            assert_eq!(parse_envelope(&env.to_sexpr(), 8), Ok(env));
922        }
923    }
924
925    #[test]
926    fn alias_key_spellings_parse_to_one_identity() {
927        // `@bob` and `@ed25519:bob` are one canonical identity (REQ-708):
928        // the parsed envelope equals the canonically-spelled one.
929        let env = signed_envelope(&sample_message(None), &ALICE);
930        let mut sexpr = env.to_sexpr();
931        if let SExpr::List(items) = &mut sexpr {
932            items[3] = SExpr::List(vec![SExpr::Atom(Atom::Symbol("@alice".to_string()))]);
933        }
934        let parsed = parse_envelope(&sexpr, 8).unwrap();
935        assert_eq!(parsed, env);
936        assert_eq!(parsed.verify(&ALICE), Ok(()));
937    }
938
939    fn valid_items() -> Vec<SExpr> {
940        let env = signed_envelope(&sample_message(Some(CausedBy::Begin)), &ALICE);
941        let SExpr::List(items) = env.to_sexpr() else {
942            unreachable!()
943        };
944        items
945    }
946
947    #[test]
948    fn malformed_hash_is_rejected_never_repaired() {
949        for bad in [
950            "f1220abc",                          // short
951            "md5:0000",                          // wrong algo
952            &format!("f1220{}", "A".repeat(64)), // uppercase
953            &format!("f1220{}", "g".repeat(64)), // non-hex
954        ] {
955            let mut items = valid_items();
956            items[1] = SExpr::Atom(Atom::Symbol(bad.to_string()));
957            assert_eq!(
958                parse_envelope(&SExpr::List(items), 8),
959                Err(EnvelopeParseError::MalformedHash),
960                "hash '{bad}' must be rejected"
961            );
962        }
963    }
964
965    #[test]
966    fn extra_fields_are_rejected() {
967        // Trailing junk after the sig (8 items — neither legal arity).
968        let mut items = valid_items();
969        items.push(SExpr::Atom(Atom::Symbol("junk".to_string())));
970        assert_eq!(
971            parse_envelope(&SExpr::List(items), 8),
972            Err(EnvelopeParseError::WrongArity { found: 10 })
973        );
974        // A 9-item form whose keyword is not :caused-by.
975        let mut items = valid_items();
976        items[7] = SExpr::Atom(Atom::Keyword("payload".to_string()));
977        assert_eq!(
978            parse_envelope(&SExpr::List(items), 8),
979            Err(EnvelopeParseError::UnexpectedField)
980        );
981    }
982
983    #[test]
984    fn recipient_bound_is_enforced_structurally() {
985        let items = valid_items();
986        assert_eq!(
987            parse_envelope(&SExpr::List(items), 1),
988            Err(EnvelopeParseError::RecipientBoundExceeded { count: 2, max: 1 })
989        );
990    }
991
992    #[test]
993    fn malformed_positions_are_typed_rejections() {
994        // Sender list of two keys.
995        let mut items = valid_items();
996        items[3] = SExpr::List(vec![
997            SExpr::Atom(Atom::Symbol("@a".to_string())),
998            SExpr::Atom(Atom::Symbol("@b".to_string())),
999        ]);
1000        assert_eq!(
1001            parse_envelope(&SExpr::List(items), 8),
1002            Err(EnvelopeParseError::MalformedFromList)
1003        );
1004        // A recipient without the sigil.
1005        let mut items = valid_items();
1006        items[4] = SExpr::List(vec![SExpr::Atom(Atom::Symbol("bob".to_string()))]);
1007        assert_eq!(
1008            parse_envelope(&SExpr::List(items), 8),
1009            Err(EnvelopeParseError::MalformedKey(KeyIdError::MissingSigil))
1010        );
1011        // Thread as a number.
1012        let mut items = valid_items();
1013        items[5] = SExpr::Atom(Atom::Num(7));
1014        assert_eq!(
1015            parse_envelope(&SExpr::List(items), 8),
1016            Err(EnvelopeParseError::MalformedThread)
1017        );
1018        // Signature: empty, odd length, uppercase.
1019        for bad in ["", "abc", "AB"] {
1020            let mut items = valid_items();
1021            items[6] = SExpr::Atom(Atom::Str(bad.to_string()));
1022            assert_eq!(
1023                parse_envelope(&SExpr::List(items), 8),
1024                Err(EnvelopeParseError::MalformedSignature),
1025                "sig '{bad}' must be rejected"
1026            );
1027        }
1028        // caused-ref that is not a hash.
1029        let mut items = valid_items();
1030        items[8] = SExpr::Atom(Atom::Symbol("h0".to_string()));
1031        assert_eq!(
1032            parse_envelope(&SExpr::List(items), 8),
1033            Err(EnvelopeParseError::MalformedCausedBy)
1034        );
1035        // Not an envelope at all.
1036        assert_eq!(
1037            parse_envelope(&"(tell @bob \"hi\")".parse::<SExpr>().unwrap(), 8),
1038            Err(EnvelopeParseError::NotAnEnvelopeForm)
1039        );
1040    }
1041
1042    /// NFR-700: envelope size is constant in the payload it redacts.
1043    #[test]
1044    fn envelope_size_is_independent_of_payload_size() {
1045        let mut small = sample_message(None);
1046        let mut large = sample_message(None);
1047        if let Message::Simple { content, .. } = &mut small {
1048            *content = SExpr::Atom(Atom::Str("x".to_string()));
1049        }
1050        if let Message::Simple { content, .. } = &mut large {
1051            *content = SExpr::Atom(Atom::Str("y".repeat(64 * 1024)));
1052        }
1053        let e_small = signed_envelope(&small, &ALICE);
1054        let e_large = signed_envelope(&large, &ALICE);
1055        assert_eq!(
1056            e_small.to_sexpr().byte_size(),
1057            e_large.to_sexpr().byte_size(),
1058            "envelope size must not scale with the payload"
1059        );
1060    }
1061
1062    // -----------------------------------------------------------------------
1063    // SPEC-017 REQ-813 Stage 3: opened envelopes (native field-openings)
1064    // -----------------------------------------------------------------------
1065
1066    use crate::keyid::SignatureSuite;
1067    use crate::typed_addr::{self, FieldId};
1068
1069    fn opened(m: &Message, signer: &dyn Signer) -> OpenedEnvelope {
1070        build_opened(m, &HEADER_FIELDS, &SignatureSuite::Ed25519, signer).unwrap()
1071    }
1072
1073    /// REQ-813: the opened header set verifies — the v3 root-signature plus
1074    /// every header opening against that signed root — and the disclosed
1075    /// values read back as the message's authenticated fields.
1076    #[test]
1077    fn opened_header_verifies_and_reads_back() {
1078        let m = sample_message(Some(CausedBy::Single(hash64('b'))));
1079        let env = opened(&m, &ALICE);
1080        assert_eq!(verify_opened(&env, &ALICE), Ok(()));
1081        assert_eq!(env.performative(), Some("reveal-bid"));
1082        assert_eq!(env.thread(), Some("conv-7"));
1083        assert_eq!(env.from_spelling(), Some("@alice"));
1084        assert_eq!(env.content_hash(), message_content_hash(&m));
1085        let to = env.to_spellings().unwrap();
1086        assert!(to.contains(&"@bob") && to.contains(&"@carol"));
1087    }
1088
1089    /// A relay that is not the signer can forward a genuine opened envelope:
1090    /// forwarding is a pure copy, and it still verifies under the sender's
1091    /// key. (Producing one needs the signing key; forwarding does not.)
1092    #[test]
1093    fn relay_can_forward_a_genuine_opened_envelope() {
1094        let m = sample_message(None);
1095        let env = opened(&m, &ALICE);
1096        // The relay (BOB) holds no signing key for alice; it merely relays.
1097        let forwarded = env.clone();
1098        // Any holder verifies against alice's public verification (ALICE).
1099        assert_eq!(verify_opened(&forwarded, &ALICE), Ok(()));
1100    }
1101
1102    /// Relay-unforgeability (REQ-813): forging any opened field value fails
1103    /// `verify_opening` against the signed root — the forger cannot mint a
1104    /// matching opening without re-rooting, and the v3 signature is over the
1105    /// genuine root.
1106    #[test]
1107    fn forging_an_opened_field_fails_verification() {
1108        let m = sample_message(None);
1109        let genuine = opened(&m, &ALICE);
1110
1111        // Forge the performative: swap in a different type's opening value.
1112        let mut forged = genuine.clone();
1113        for op in &mut forged.openings {
1114            if op.field == FieldId::Performative {
1115                op.value = SExpr::Atom(Atom::Symbol("commit-bid".to_string()));
1116            }
1117        }
1118        assert_eq!(
1119            verify_opened(&forged, &ALICE),
1120            Err(OpenedError::OpeningFailed {
1121                field: FieldId::Performative
1122            })
1123        );
1124
1125        // Forge the To set by lifting a genuine opening from a *widened*
1126        // message: it reconstructs a different root, so it fails here.
1127        let mut widened_to = alloc::collections::BTreeSet::new();
1128        widened_to.insert("@bob".to_string());
1129        widened_to.insert("@carol".to_string());
1130        widened_to.insert("@mallory".to_string());
1131        let widened = Message::Simple {
1132            performative: Performative::Custom("reveal-bid".to_string()),
1133            recipient: Some(Recipients::Set(widened_to)),
1134            content: SExpr::Atom(Atom::Str("the secret payload".to_string())),
1135            params: Vec::new(),
1136            thread: Some("conv-7".to_string()),
1137            sender: Some("@alice".to_string()),
1138            caused_by: None,
1139        };
1140        let mut forged2 = genuine.clone();
1141        for op in &mut forged2.openings {
1142            if op.field == FieldId::To {
1143                *op = typed_addr::open(&widened, FieldId::To);
1144            }
1145        }
1146        assert_eq!(
1147            verify_opened(&forged2, &ALICE),
1148            Err(OpenedError::OpeningFailed { field: FieldId::To })
1149        );
1150    }
1151
1152    /// A tampered root fails at the v3 signature (step 1), before any
1153    /// opening is even considered.
1154    #[test]
1155    fn tampered_root_fails_at_the_signature() {
1156        let m = sample_message(None);
1157        let mut env = opened(&m, &ALICE);
1158        env.root =
1159            "f12200000000000000000000000000000000000000000000000000000000000000000".to_string();
1160        assert_eq!(
1161            verify_opened(&env, &ALICE),
1162            Err(OpenedError::Attestation(AttestError::InvalidSignature))
1163        );
1164    }
1165
1166    /// A different key's verifier cannot validate the v3 signature.
1167    #[test]
1168    fn wrong_signer_fails_the_opened_envelope() {
1169        let m = sample_message(None);
1170        let env = opened(&m, &ALICE);
1171        assert_eq!(
1172            verify_opened(&env, &BOB),
1173            Err(OpenedError::Attestation(AttestError::InvalidSignature))
1174        );
1175    }
1176
1177    /// NFR-701: the redacted opened envelope carries no payload field — no
1178    /// opening is the Payload leaf, and no disclosed value carries the
1179    /// payload bytes. The performative (metadata) stays visible (NFR-702).
1180    #[test]
1181    fn opened_header_seals_the_payload() {
1182        let m = sample_message(None); // content: "the secret payload"
1183        let env = opened(&m, &ALICE);
1184        assert!(
1185            env.opening(FieldId::Payload).is_none(),
1186            "redacted delivery must not open the payload leaf"
1187        );
1188        for op in &env.openings {
1189            let bytes = crate::canonical::canonical_encode(&op.value);
1190            let s = core::str::from_utf8(&bytes).unwrap();
1191            assert!(
1192                !s.contains("the secret payload"),
1193                "payload leaked via {:?}",
1194                op.field
1195            );
1196        }
1197    }
1198
1199    /// The full-content path opens the Payload leaf too — authenticated
1200    /// disclosure of the payload itself (the REQ-703 completion input),
1201    /// not a separate mechanism.
1202    #[test]
1203    fn opened_full_content_reveals_the_payload_leaf() {
1204        let m = sample_message(None);
1205        let mut fields = HEADER_FIELDS.to_vec();
1206        fields.push(FieldId::Payload);
1207        let env = build_opened(&m, &fields, &SignatureSuite::Ed25519, &ALICE).unwrap();
1208        assert_eq!(verify_opened(&env, &ALICE), Ok(()));
1209        let payload = env.opening(FieldId::Payload).expect("payload opened");
1210        assert!(format!("{}", payload.value).contains("the secret payload"));
1211    }
1212
1213    /// REQ-708: an unimplemented suite is a typed rejection on build.
1214    #[test]
1215    fn opened_unknown_suite_is_typed_rejection() {
1216        let m = sample_message(None);
1217        let pq = SignatureSuite::parse("pq-frodo");
1218        assert_eq!(
1219            build_opened(&m, &HEADER_FIELDS, &pq, &ALICE),
1220            Err(AttestError::UnknownSuite("pq-frodo".to_string()))
1221        );
1222    }
1223}