Skip to main content

pask_wire/
payload.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 Wilder Management Inc. (d/b/a Wilder Robotics) <rob@wilder-robotics.com>
3// pask-wire is licensed Apache-2.0. No commercial agreement is required to use,
4// modify or redistribute it; see LICENSING.md in the workspace root.
5
6use alloc::{
7    borrow::ToOwned,
8    string::{String, ToString},
9    vec::Vec,
10};
11use serde::{Deserialize, Serialize};
12use time::{OffsetDateTime, format_description::well_known::Rfc3339};
13
14use crate::{Error, Result, sha256_prefixed, validate_sha256};
15
16/// Supported PSER profile version.
17pub const SPEC_VERSION: &str = "wilder.pser/0.5";
18
19/// Profile version carrying the timestamp containment requirement.
20pub const SPEC_VERSION_06: &str = "wilder.pser/0.6";
21/// Proposed local 0.7 candidate, not a published profile.
22pub const SPEC_VERSION_07: &str = "wilder.pser/0.7";
23
24/// Returns true when the given spec string is a supported profile version.
25#[must_use]
26pub fn is_supported_spec(spec: &str) -> bool {
27    spec == SPEC_VERSION || spec == SPEC_VERSION_06 || spec == SPEC_VERSION_07
28}
29
30/// Wire strings for the three named `adapter.ackProvenance` values.
31///
32/// The value space is a closed set enumerated in the profile document rather
33/// than an IANA registry, so these strings are the whole of it. A conforming
34/// producer MUST emit one of them.
35const BINDING_MODE_DIRECT_WITNESS: &str = "DIRECT_WITNESS";
36const BINDING_MODE_DELEGATED_WITNESS: &str = "DELEGATED_WITNESS";
37
38const ACK_PROVENANCE_THIRD_PARTY: &str = "THIRD_PARTY";
39const ACK_PROVENANCE_ISSUER_ASSERTED: &str = "ISSUER_ASSERTED";
40const ACK_PROVENANCE_NONE: &str = "NONE";
41
42/// Wire strings for the three named `issuerAffiliation` values.
43///
44/// Closed set, enumerated in the profile document rather than an IANA registry.
45/// A conforming producer MUST emit one of them.
46const ISSUER_AFFILIATION_AFFILIATED: &str = "AFFILIATED";
47const ISSUER_AFFILIATION_INDEPENDENT: &str = "INDEPENDENT";
48const ISSUER_AFFILIATION_NOT_DISCLOSED: &str = "NOT_DISCLOSED";
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(deny_unknown_fields)]
52struct Site {
53    id: String,
54    class: SiteClass,
55    envelope: SiteEnvelope,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "lowercase")]
60enum SiteClass {
61    Residential,
62    Industrial,
63    Healthcare,
64    Infra,
65    Other,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(deny_unknown_fields)]
70struct SiteEnvelope {
71    id: String,
72    digest: String,
73    #[serde(deserialize_with = "deserialize_required_option")]
74    geobounds: Option<String>,
75    temporal: Temporal,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(deny_unknown_fields)]
80struct Temporal {
81    #[serde(deserialize_with = "deserialize_required_option")]
82    starts: Option<String>,
83    #[serde(deserialize_with = "deserialize_required_option")]
84    ends: Option<String>,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(deny_unknown_fields)]
89struct Actor {
90    id: String,
91    class: ActorClass,
92    operator: String,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
97enum ActorClass {
98    Autonomous,
99    SemiAutonomous,
100    Human,
101    Crew,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(deny_unknown_fields, rename_all = "camelCase")]
106struct Engagement {
107    id: String,
108    window: Window,
109    r#type: String,
110    outcome_class: OutcomeClass,
111    envelope_conformance: EnvelopeConformance,
112    evidence_digest: String,
113    #[serde(
114        default,
115        skip_serializing_if = "Option::is_none",
116        deserialize_with = "present_content_digest"
117    )]
118    content_digest: Option<serde_json::Value>,
119}
120
121fn present_content_digest<'de, D: serde::Deserializer<'de>>(
122    deserializer: D,
123) -> core::result::Result<Option<serde_json::Value>, D::Error> {
124    serde_json::Value::deserialize(deserializer).map(Some)
125}
126
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(deny_unknown_fields)]
129struct Window {
130    start: String,
131    end: String,
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
136enum OutcomeClass {
137    Completed,
138    Aborted,
139    Refused,
140    Errored,
141    ObservedOnly,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
146enum EnvelopeConformance {
147    Within,
148    ExceededTemporal,
149    ExceededGeo,
150    ExceededActor,
151    Unknown,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(deny_unknown_fields, rename_all = "camelCase")]
156struct Attestation {
157    binding_mode: BindingMode,
158    tee_class: String,
159    measured_boot: MeasuredBoot,
160    platform_evidence: PlatformEvidence,
161    sealed_evidence: SealedEvidence,
162    witness_key: String,
163    validity: Validity,
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167#[serde(deny_unknown_fields, rename_all = "camelCase")]
168struct MeasuredBoot {
169    chain: String,
170    components: Vec<MeasuredBootComponent>,
171}
172
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174#[serde(deny_unknown_fields, rename_all = "camelCase")]
175struct MeasuredBootComponent {
176    name: String,
177    digest: String,
178}
179
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(deny_unknown_fields, rename_all = "camelCase")]
182struct PlatformEvidence {
183    encoding: String,
184    digest: String,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188#[serde(deny_unknown_fields, rename_all = "camelCase")]
189struct Validity {
190    not_before: String,
191    not_after: String,
192}
193
194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(deny_unknown_fields, rename_all = "camelCase")]
196struct SealedEvidence {
197    digest: String,
198    size_bytes: u64,
199    encoding: String,
200}
201
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(deny_unknown_fields, rename_all = "camelCase")]
204struct Adapter {
205    system: String,
206    endpoint: String,
207    posted_at: String,
208    ack_digest: String,
209    ack_provenance: AckProvenance,
210    mode: AdapterMode,
211}
212
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214enum AdapterMode {
215    #[serde(rename = "WRITE_ONLY")]
216    WriteOnly,
217}
218
219/// How the acknowledgement recorded in `adapter.ackDigest` was obtained.
220///
221/// # Why this member exists
222///
223/// Under a write-only adapter posture there is no read path, so `ackDigest`
224/// alone cannot tell a reader whether an independent operations layer
225/// acknowledged the write-in or the Issuer authored a minimal acknowledgement
226/// object itself when nothing structured came back. The digest proves a digest
227/// was computed over something. It does not prove who produced the thing. This
228/// member makes the distinction a property of the record instead of a property
229/// of the Issuer's unpublished manifest.
230///
231/// Classification belongs to the profile. What a deployment then *does* about
232/// an Issuer-asserted acknowledgement -- refuse, warn, or record and carry on
233/// -- is a matter of that deployment's risk appetite and is deliberately not
234/// specified here.
235///
236/// # Why an unrecognised value is preserved rather than rejected
237///
238/// [`Self::Unrecognized`] carries the exact string that was on the wire. Two
239/// rules sit next to each other and they are separate requirements:
240///
241/// 1. The three named values remain distinguishable from each other.
242/// 2. An unrecognised value is surfaced as unrecognised. It is not read as
243///    [`Self::ThirdParty`] and it is not normalised to [`Self::NoAcknowledgement`].
244///
245/// The second rule is the one that is easy to get wrong, because the obvious
246/// instinct is to fail closed on anything unrecognised. **That instinct is
247/// correct for an enumeration feeding a pre-action gate and wrong here, and the
248/// difference is the cost function underneath it.** At a gate, refusing costs
249/// availability and the action simply does not happen. This member is a
250/// descriptive property of a record that gets read afterwards, often by
251/// somebody reconstructing an event months later. Refusing there means refusing
252/// the record, and refusing the record destroys the reconstruction the record
253/// exists to serve. Once the engagement has already happened, refusal is not
254/// the conservative choice.
255///
256/// Normalising to [`Self::NoAcknowledgement`] is the same collapse pointing the
257/// other way: it manufactures a positive claim that the operations layer
258/// returned nothing, which is a substantive statement about what happened at the
259/// site and may be false.
260///
261/// So the profile is **closed on the producing side and tolerant on the
262/// consuming side.** A conforming producer MUST emit one of the three named
263/// values; a verifier MUST NOT refuse a receipt solely because this member
264/// carries something else, and MUST surface it as unrecognised.
265///
266/// # Serialization
267///
268/// `Serialize` and `Deserialize` are written by hand rather than derived.
269/// `#[serde(other)]` would discard the unrecognised string, which fails rule 2:
270/// the value has to stay available to the reader, not merely be distinguishable
271/// as "not one of ours". Round-tripping is byte-exact, which matters because the
272/// payload is signed over its JCS serialization -- a variant that re-serialised
273/// to anything other than the original bytes would invalidate the signature.
274#[derive(Debug, Clone, PartialEq, Eq)]
275pub enum AckProvenance {
276    /// An independent operations layer produced the acknowledgement. Wire value
277    /// `THIRD_PARTY`.
278    ///
279    /// Under a write-only posture this remains the Issuer's claim about a third
280    /// party rather than an independently verified fact. The profile does not
281    /// name this state `CONFIRMED` for exactly that reason.
282    ThirdParty,
283    /// The Issuer authored the acknowledgement object itself. Wire value
284    /// `ISSUER_ASSERTED`.
285    IssuerAsserted,
286    /// No acknowledgement was obtained. Wire value `NONE`.
287    ///
288    /// Named `NoAcknowledgement` in Rust rather than `None`, which would shadow
289    /// [`Option::None`] at every use site and produce compiler messages that
290    /// read as if the option type were involved. The wire string is pinned by
291    /// hand and is unaffected.
292    NoAcknowledgement,
293    /// A value outside the closed set, preserved exactly as it appeared.
294    ///
295    /// A receipt carrying this is not conforming. It still parses, still
296    /// validates, and still presents this member to the reader, for the reasons
297    /// in the type-level documentation.
298    Unrecognized(String),
299}
300
301/// The attestation-binding mode a receipt was produced under.
302///
303/// # Why this is in the payload
304///
305/// `-02` required a Verifier to obtain this from a document the Issuer
306/// published separately, and simultaneously declined to specify that document.
307/// Two problems followed. The obligation could not be discharged, because there
308/// was nothing to fetch. And even had there been, a per-receipt fact would have
309/// been resolved from a document that describes an Issuer rather than a
310/// receipt, so the introduction's non-extractability property stopped being
311/// checkable from the presented bytes.
312///
313/// The mode was fixed at the instant the receipt was signed and was known to
314/// the signer. Carrying it costs one string.
315///
316/// # Why an unrecognised value is rejected here and preserved in [`AckProvenance`]
317///
318/// The two members answer different questions and the difference is not
319/// stylistic. `adapter.ackProvenance` qualifies a record of something that
320/// already happened, so refusing to parse it destroys the reconstruction the
321/// receipt exists for, and the honest move is to surface the unknown.
322///
323/// `attestation.bindingMode` selects which security property a reader is
324/// entitled to rely on. There is no safe reading of an unrecognised value: it
325/// cannot be treated as direct-witness without asserting a property nobody
326/// claimed, and treating it as delegated-witness invents a delegation
327/// credential to go looking for. So the profile closes the set and this rejects.
328#[derive(Debug, Clone, PartialEq, Eq)]
329pub enum BindingMode {
330    /// The signing key is the TEE signing key. Wire value `DIRECT_WITNESS`.
331    DirectWitness,
332    /// The signing key is the Issuer's own, authorised by a TEE-issued
333    /// delegation credential. Wire value `DELEGATED_WITNESS`.
334    ///
335    /// A reader of such a receipt obtains a weaker property than the
336    /// non-extractability one, and the delegation credential is resolved out of
337    /// band. Nothing in this repository resolves it; see `KNOWN-LIMITATIONS.md`.
338    DelegatedWitness,
339    /// A value outside the closed set, preserved exactly as it appeared.
340    ///
341    /// Retained rather than dropped so a reader can report what was actually
342    /// present. A payload carrying this fails validation.
343    Unrecognized(String),
344}
345
346impl BindingMode {
347    /// Returns the wire string for this value.
348    #[must_use]
349    pub fn as_wire_str(&self) -> &str {
350        match self {
351            Self::DirectWitness => BINDING_MODE_DIRECT_WITNESS,
352            Self::DelegatedWitness => BINDING_MODE_DELEGATED_WITNESS,
353            Self::Unrecognized(raw) => raw,
354        }
355    }
356
357    /// Returns `true` when the value is outside the closed set the profile names.
358    #[must_use]
359    pub const fn is_unrecognized(&self) -> bool {
360        matches!(self, Self::Unrecognized(_))
361    }
362}
363
364impl Serialize for BindingMode {
365    fn serialize<S: serde::Serializer>(
366        &self,
367        serializer: S,
368    ) -> core::result::Result<S::Ok, S::Error> {
369        serializer.serialize_str(self.as_wire_str())
370    }
371}
372
373impl<'de> Deserialize<'de> for BindingMode {
374    fn deserialize<D: serde::Deserializer<'de>>(
375        deserializer: D,
376    ) -> core::result::Result<Self, D::Error> {
377        let raw = String::deserialize(deserializer)?;
378        Ok(match raw.as_str() {
379            BINDING_MODE_DIRECT_WITNESS => Self::DirectWitness,
380            BINDING_MODE_DELEGATED_WITNESS => Self::DelegatedWitness,
381            // Parsed, not accepted. Deserialization keeps the raw string so the
382            // value can be reported; `validate` is what refuses it. Rejecting
383            // here instead would surface as a parse error and lose the value.
384            _ => Self::Unrecognized(raw),
385        })
386    }
387}
388
389impl AckProvenance {
390    /// Returns the wire string for this value.
391    #[must_use]
392    pub fn as_wire_str(&self) -> &str {
393        match self {
394            Self::ThirdParty => ACK_PROVENANCE_THIRD_PARTY,
395            Self::IssuerAsserted => ACK_PROVENANCE_ISSUER_ASSERTED,
396            Self::NoAcknowledgement => ACK_PROVENANCE_NONE,
397            Self::Unrecognized(raw) => raw,
398        }
399    }
400
401    /// Returns `true` when the value is outside the closed set the profile names.
402    ///
403    /// A verifier that surfaces the acknowledgement-provenance state to a reader
404    /// uses this rather than comparing against the named variants, so that an
405    /// unrecognised value cannot be silently folded into one of them.
406    #[must_use]
407    pub const fn is_unrecognized(&self) -> bool {
408        matches!(self, Self::Unrecognized(_))
409    }
410}
411
412impl Serialize for AckProvenance {
413    fn serialize<S: serde::Serializer>(
414        &self,
415        serializer: S,
416    ) -> core::result::Result<S::Ok, S::Error> {
417        serializer.serialize_str(self.as_wire_str())
418    }
419}
420
421impl<'de> Deserialize<'de> for AckProvenance {
422    fn deserialize<D: serde::Deserializer<'de>>(
423        deserializer: D,
424    ) -> core::result::Result<Self, D::Error> {
425        let raw = String::deserialize(deserializer)?;
426        Ok(match raw.as_str() {
427            ACK_PROVENANCE_THIRD_PARTY => Self::ThirdParty,
428            ACK_PROVENANCE_ISSUER_ASSERTED => Self::IssuerAsserted,
429            ACK_PROVENANCE_NONE => Self::NoAcknowledgement,
430            // Deliberately not an error. See the type-level documentation: this
431            // is a record read after the fact, and refusing it destroys the
432            // reconstruction it exists for. The raw string is retained so the
433            // value stays distinguishable from both THIRD_PARTY and NONE.
434            _ => Self::Unrecognized(raw),
435        })
436    }
437}
438
439/// Whether the Site Owner and the Issuer are affiliated parties.
440///
441/// # Why this member exists
442///
443/// Nothing else in a receipt tells a reader whether the party that controls the
444/// site and the party that issued the receipt are related. A reader who cannot
445/// see the relationship has no way to check it, and the natural reading of
446/// silence is that the two are unrelated. That reading is a claim, and it is a
447/// claim nobody made.
448///
449/// The failure is the same shape as an unrecognised [`AckProvenance`] read as
450/// [`AckProvenance::ThirdParty`], one level up: an unknown resolved in the
451/// receipt's favour rather than surfaced as unknown. So the fix is the same.
452/// Name the unknown, and make naming it the default rather than the exception.
453///
454/// This does not overlap the profile's prohibition on collapsing two of the
455/// three trust roles into one principal. That rule addresses one principal
456/// wearing two hats. This member addresses the ordinary and far more common
457/// case of three distinct principals, two of which are related.
458///
459/// # What the profile does and does not do with it
460///
461/// The Issuer signs the receipt, so this member is the Issuer's statement about
462/// the Issuer's own standing. **The profile records that statement. It does not
463/// verify it, and no verification of it is possible from the receipt bytes.**
464///
465/// That is a weaker guarantee than it first appears to be and it is still worth
466/// having. A false value here is a false statement inside a signed, timestamped,
467/// registered record, attributable to the key that signed it and discoverable by
468/// anyone auditing the log. Silence is unfalsifiable and costs a dishonest
469/// Issuer nothing at all. The whole profile rests on that trade.
470///
471/// # Why REQUIRED rather than optional
472///
473/// Identical reasoning to [`AckProvenance`]: an absent member would itself have
474/// to be assigned a meaning, and every available meaning is wrong. Read as
475/// independent, it manufactures the claim this member exists to prevent. Read as
476/// affiliated, it defames an Issuer that simply predates the member. Read as
477/// unknown, it duplicates [`Self::NotDisclosed`] while being indistinguishable
478/// from a producer that forgot.
479///
480/// [`Self::NotDisclosed`] is the honest default value. A producer that has not
481/// established the relationship, or that declines to state it, emits it
482/// explicitly.
483///
484/// # Why an unrecognised value is preserved rather than rejected
485///
486/// See [`AckProvenance`]. The cost function is the same one: this is a
487/// descriptive property of a record read after the fact, refusing the record
488/// destroys the reconstruction it exists to serve, and normalising to
489/// [`Self::NotDisclosed`] manufactures a positive claim that nobody disclosed
490/// anything when in fact somebody may have disclosed something this build does
491/// not recognise.
492///
493/// # A standing fact carried per receipt
494///
495/// Affiliation between two principals is a standing relationship, not a fact
496/// about one engagement. Carrying it per receipt means a chain can disagree with
497/// itself. A verifier that observes the value change within a single chain
498/// surfaces the change rather than taking the later value as current, in the same
499/// way an ordering that cannot be established is surfaced as undetermined rather
500/// than guessed. This crate exposes [`Payload::issuer_affiliation`] so a chain
501/// verifier can make that comparison; the comparison itself is a chain-level
502/// concern and is not performed here.
503#[derive(Debug, Clone, PartialEq, Eq)]
504pub enum IssuerAffiliation {
505    /// The Site Owner and the Issuer are affiliated parties, and the Issuer
506    /// discloses it. Wire value `AFFILIATED`.
507    ///
508    /// The profile does not prohibit this arrangement. It requires that the
509    /// weaker standing of a receipt issued under it be visible rather than
510    /// implied, which is the same treatment already given to an Issuer that
511    /// registers with a Transparency Service it operates itself.
512    Affiliated,
513    /// The Issuer asserts that it and the Site Owner are unaffiliated. Wire
514    /// value `INDEPENDENT`.
515    ///
516    /// An assertion by the Issuer about the Issuer. Not independently verified,
517    /// and not verifiable from the receipt bytes.
518    Independent,
519    /// The relationship is not disclosed. Wire value `NOT_DISCLOSED`.
520    ///
521    /// The default, and an honest one. It states that nobody made a claim, which
522    /// is different from a claim of independence and must not be read as one.
523    NotDisclosed,
524    /// A value outside the closed set, preserved exactly as it appeared.
525    ///
526    /// A receipt carrying this is not conforming. It still parses, still
527    /// validates, and still presents this member to the reader.
528    Unrecognized(String),
529}
530
531impl IssuerAffiliation {
532    /// Returns the wire string for this value.
533    #[must_use]
534    pub fn as_wire_str(&self) -> &str {
535        match self {
536            Self::Affiliated => ISSUER_AFFILIATION_AFFILIATED,
537            Self::Independent => ISSUER_AFFILIATION_INDEPENDENT,
538            Self::NotDisclosed => ISSUER_AFFILIATION_NOT_DISCLOSED,
539            Self::Unrecognized(raw) => raw,
540        }
541    }
542
543    /// Returns `true` when the value is outside the closed set the profile names.
544    ///
545    /// A verifier that surfaces the affiliation state to a reader uses this
546    /// rather than comparing against the named variants, so that an unrecognised
547    /// value cannot be silently folded into one of them.
548    #[must_use]
549    pub const fn is_unrecognized(&self) -> bool {
550        matches!(self, Self::Unrecognized(_))
551    }
552
553    /// Returns `true` when the receipt carries no disclosure of the relationship.
554    ///
555    /// Deliberately distinct from [`Self::is_unrecognized`]. A reader that
556    /// collapses "nobody disclosed" and "disclosed something I do not recognise"
557    /// into one state loses the difference between an Issuer that declined to
558    /// speak and an Issuer that spoke in a vocabulary this build predates.
559    #[must_use]
560    pub const fn is_not_disclosed(&self) -> bool {
561        matches!(self, Self::NotDisclosed)
562    }
563}
564
565impl Serialize for IssuerAffiliation {
566    fn serialize<S: serde::Serializer>(
567        &self,
568        serializer: S,
569    ) -> core::result::Result<S::Ok, S::Error> {
570        serializer.serialize_str(self.as_wire_str())
571    }
572}
573
574impl<'de> Deserialize<'de> for IssuerAffiliation {
575    fn deserialize<D: serde::Deserializer<'de>>(
576        deserializer: D,
577    ) -> core::result::Result<Self, D::Error> {
578        let raw = String::deserialize(deserializer)?;
579        Ok(match raw.as_str() {
580            ISSUER_AFFILIATION_AFFILIATED => Self::Affiliated,
581            ISSUER_AFFILIATION_INDEPENDENT => Self::Independent,
582            ISSUER_AFFILIATION_NOT_DISCLOSED => Self::NotDisclosed,
583            // Deliberately not an error, for the reasons in the type-level
584            // documentation. The raw string is retained so the value stays
585            // distinguishable from both INDEPENDENT and NOT_DISCLOSED.
586            _ => Self::Unrecognized(raw),
587        })
588    }
589}
590
591#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
592#[serde(deny_unknown_fields, rename_all = "camelCase")]
593struct Chain {
594    seq: u64,
595    #[serde(deserialize_with = "deserialize_required_option")]
596    prev_hash: Option<String>,
597    hash: String,
598}
599
600/// Reads only `spec` and rejects a version this build does not implement.
601///
602/// This runs **before** the full deserialization, and the ordering is the whole
603/// point of it. Deserializing first and checking the version afterwards produces
604/// an honest answer only while every revision happens to carry the same members.
605/// The moment a revision requires a member an earlier one did not carry -- which
606/// is exactly what `wilder.pser/0.5` does with `adapter.ackProvenance` -- a
607/// receipt from the earlier revision fails on the missing member and the caller
608/// is told a member is absent when the real and far more useful answer is that
609/// the receipt is from a revision this build does not implement. One diagnosis
610/// sends an operator looking for a malformed producer; the other tells them to
611/// upgrade the verifier.
612///
613/// Measured on `wilder.pser/0.3` before this check existed: a receipt whose
614/// version *and* member shape both differed reported
615/// `unknown field ...`, while a receipt differing in version alone reported
616/// `unsupported spec version` correctly. Only the first case was wrong, and only
617/// the first case is the one a real version skew produces.
618///
619/// The permissive intermediate parse is deliberate: this stage must tolerate a
620/// document it cannot fully model, or it could not report the version at all.
621fn check_spec_version(bytes: &[u8]) -> Result<()> {
622    #[derive(Deserialize)]
623    struct SpecOnly {
624        spec: String,
625    }
626
627    // A document too malformed to yield a `spec` string is not a version
628    // problem. Say nothing and let the full parse produce the real diagnosis.
629    if let Ok(probe) = serde_json::from_slice::<SpecOnly>(bytes)
630        && !is_supported_spec(&probe.spec)
631    {
632        return Err(Error::Validation("unsupported spec version"));
633    }
634    Ok(())
635}
636
637fn deserialize_required_option<'de, D, T>(
638    deserializer: D,
639) -> core::result::Result<Option<T>, D::Error>
640where
641    D: serde::Deserializer<'de>,
642    T: Deserialize<'de>,
643{
644    Option::<T>::deserialize(deserializer)
645}
646
647/// Strongly typed `wilder.pser/0.5` payload.
648#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
649#[serde(deny_unknown_fields, rename_all = "camelCase")]
650pub struct Payload {
651    spec: String,
652    id: String,
653    ts: String,
654    issuer_affiliation: IssuerAffiliation,
655    site: Site,
656    actor: Actor,
657    engagement: Engagement,
658    attestation: Attestation,
659    adapter: Adapter,
660    chain: Chain,
661}
662
663impl Payload {
664    /// Parses JSON and validates every profile rule, including `chain.hash`.
665    ///
666    /// # Errors
667    ///
668    /// Returns an error when JSON parsing or any profile validation rule fails.
669    pub fn from_json(bytes: &[u8]) -> Result<Self> {
670        check_spec_version(bytes)?;
671        let payload: Self =
672            serde_json::from_slice(bytes).map_err(|error| Error::Json(error.to_string()))?;
673        payload.validate()?;
674        Ok(payload)
675    }
676
677    /// Parses producer input, replaces the supplied `chain.hash`, and validates the result.
678    ///
679    /// # Errors
680    ///
681    /// Returns an error when JSON parsing, hashing, or any profile validation rule fails.
682    pub fn from_json_for_production(bytes: &[u8]) -> Result<Self> {
683        check_spec_version(bytes)?;
684        let mut payload: Self =
685            serde_json::from_slice(bytes).map_err(|error| Error::Json(error.to_string()))?;
686        payload.update_chain_hash()?;
687        payload.validate()?;
688        Ok(payload)
689    }
690
691    /// Returns the RFC 8785 JCS serialization of the complete payload.
692    ///
693    /// # Errors
694    ///
695    /// Returns an error if the payload cannot be serialized.
696    pub fn to_jcs(&self) -> Result<Vec<u8>> {
697        let value = serde_json::to_value(self).map_err(|error| Error::Json(error.to_string()))?;
698        canonicalize_value(&value)
699    }
700
701    /// Returns the profile version string.
702    #[must_use]
703    pub fn spec(&self) -> &str {
704        &self.spec
705    }
706
707    /// Returns the stable site identifier used as the CWT subject.
708    #[must_use]
709    pub fn site_id(&self) -> &str {
710        &self.site.id
711    }
712
713    /// Returns the witness key identifier used as the CWT issuer by the CLI.
714    #[must_use]
715    pub const fn attestation_binding_mode(&self) -> &BindingMode {
716        &self.attestation.binding_mode
717    }
718
719    /// Key identifier of the TEE signing key.
720    pub fn witness_key(&self) -> &str {
721        &self.attestation.witness_key
722    }
723
724    /// Returns the stored chain digest.
725    #[must_use]
726    pub fn chain_hash(&self) -> &str {
727        &self.chain.hash
728    }
729
730    /// Returns the receipt's position in its chain.
731    #[must_use]
732    pub fn chain_seq(&self) -> u64 {
733        self.chain.seq
734    }
735
736    /// Returns the preceding receipt's `chain.hash`, or `None` at sequence zero.
737    #[must_use]
738    pub fn chain_prev_hash(&self) -> Option<&str> {
739        self.chain.prev_hash.as_deref()
740    }
741
742    /// Returns whether the Site Owner and the Issuer are affiliated parties.
743    ///
744    /// A value outside the closed set is returned as
745    /// [`IssuerAffiliation::Unrecognized`] carrying the original string, never
746    /// folded into one of the named values. [`IssuerAffiliation::NotDisclosed`]
747    /// means nobody made a claim and MUST NOT be read as a claim of
748    /// independence. See [`IssuerAffiliation`] for why.
749    #[must_use]
750    pub const fn issuer_affiliation(&self) -> &IssuerAffiliation {
751        &self.issuer_affiliation
752    }
753
754    /// Returns how the acknowledgement in `adapter.ackDigest` was obtained.
755    ///
756    /// A value outside the closed set is returned as
757    /// [`AckProvenance::Unrecognized`] carrying the original string, never
758    /// folded into one of the named values. See [`AckProvenance`] for why.
759    #[must_use]
760    pub const fn adapter_ack_provenance(&self) -> &AckProvenance {
761        &self.adapter.ack_provenance
762    }
763
764    /// Returns the stable actor identifier.
765    #[must_use]
766    pub fn actor_id(&self) -> &str {
767        &self.actor.id
768    }
769
770    /// Returns the operator string associated with the actor.
771    #[must_use]
772    pub fn actor_operator(&self) -> &str {
773        &self.actor.operator
774    }
775
776    /// Returns the stable engagement identifier.
777    #[must_use]
778    pub fn engagement_id(&self) -> &str {
779        &self.engagement.id
780    }
781
782    /// Returns the engagement type string (RFC 3986 URI or short identifier per §6 of the draft).
783    #[must_use]
784    pub fn engagement_type(&self) -> &str {
785        &self.engagement.r#type
786    }
787
788    /// Returns the RFC 3339 UTC start of the engagement window.
789    #[must_use]
790    pub fn engagement_window_start(&self) -> &str {
791        &self.engagement.window.start
792    }
793
794    /// Returns the RFC 3339 UTC end of the engagement window.
795    #[must_use]
796    pub fn engagement_window_end(&self) -> &str {
797        &self.engagement.window.end
798    }
799
800    /// Returns the SHA-256 digest of the raw evidence bundle referenced by this engagement.
801    #[must_use]
802    pub fn engagement_evidence_digest(&self) -> &str {
803        &self.engagement.evidence_digest
804    }
805
806    /// None for legacy profiles, Some(Null) for no block at seal in 0.7.
807    pub fn engagement_content_digest(&self) -> Option<&serde_json::Value> {
808        self.engagement.content_digest.as_ref()
809    }
810
811    /// Returns the TEE class identifier.
812    #[must_use]
813    pub fn attestation_tee_class(&self) -> &str {
814        &self.attestation.tee_class
815    }
816
817    /// Returns the SHA-256 digest of the sealed evidence blob.
818    #[must_use]
819    pub fn sealed_evidence_digest(&self) -> &str {
820        &self.attestation.sealed_evidence.digest
821    }
822
823    /// Returns the size in bytes of the sealed evidence blob.
824    #[must_use]
825    pub fn sealed_evidence_size_bytes(&self) -> u64 {
826        self.attestation.sealed_evidence.size_bytes
827    }
828
829    /// Returns the sealed evidence encoding identifier.
830    #[must_use]
831    pub fn sealed_evidence_encoding(&self) -> &str {
832        &self.attestation.sealed_evidence.encoding
833    }
834
835    /// Returns the operations-layer system identifier.
836    ///
837    /// This value selects which write-in adapter is responsible for pushing this receipt.
838    /// Values are defined by the PSER profile registry (see §6 of the draft). Example
839    /// values: `"buildium"`, `"propertymeld"`.
840    #[must_use]
841    pub fn adapter_system(&self) -> &str {
842        &self.adapter.system
843    }
844
845    /// Returns the opaque per-system endpoint identifier.
846    ///
847    /// The value is interpreted by the target adapter, not by `pask-wire`. For the
848    /// `buildium` adapter it is the Buildium rental property ID; for other adapters,
849    /// consult the adapter documentation.
850    #[must_use]
851    pub fn adapter_endpoint(&self) -> &str {
852        &self.adapter.endpoint
853    }
854
855    /// Returns the RFC 3339 UTC timestamp at which the write-in was posted.
856    #[must_use]
857    pub fn adapter_posted_at(&self) -> &str {
858        &self.adapter.posted_at
859    }
860
861    /// Returns the SHA-256 digest of the operations-layer acknowledgement.
862    #[must_use]
863    pub fn adapter_ack_digest(&self) -> &str {
864        &self.adapter.ack_digest
865    }
866
867    /// Returns whether the receipt is marked WRITE_ONLY.
868    ///
869    /// Every `wilder.pser/0.3` receipt that parses successfully MUST be WRITE_ONLY;
870    /// this accessor exists so downstream adapters can enforce the property as
871    /// defense-in-depth without pattern-matching the internal enum.
872    #[must_use]
873    pub fn adapter_is_write_only(&self) -> bool {
874        matches!(self.adapter.mode, AdapterMode::WriteOnly)
875    }
876
877    pub(crate) fn parse_canonical(bytes: &[u8]) -> Result<Self> {
878        let payload = Self::from_json(bytes)?;
879        if payload.to_jcs()?.as_slice() != bytes {
880            return Err(Error::NonCanonicalPayload);
881        }
882        Ok(payload)
883    }
884
885    fn update_chain_hash(&mut self) -> Result<()> {
886        self.chain.hash = self.expected_chain_hash()?;
887        Ok(())
888    }
889
890    fn expected_chain_hash(&self) -> Result<String> {
891        let mut value =
892            serde_json::to_value(self).map_err(|error| Error::Json(error.to_string()))?;
893        let chain = value
894            .get_mut("chain")
895            .and_then(serde_json::Value::as_object_mut)
896            .ok_or(Error::Validation("chain must be an object"))?;
897        chain.remove("hash");
898        let canonical = canonicalize_value(&value)?;
899        Ok(sha256_prefixed(&canonical))
900    }
901
902    fn validate(&self) -> Result<()> {
903        if !is_supported_spec(&self.spec) {
904            return Err(Error::Validation("unsupported spec version"));
905        }
906        // The profile closes this set. See `BindingMode` for why an unknown is
907        // refused here while an unknown `adapter.ackProvenance` is surfaced.
908        if self.attestation.binding_mode.is_unrecognized() {
909            return Err(Error::Validation("unrecognized attestation binding mode"));
910        }
911        for value in [
912            &self.id,
913            &self.site.id,
914            &self.site.envelope.id,
915            &self.actor.id,
916            &self.actor.operator,
917            &self.engagement.id,
918            &self.engagement.r#type,
919            &self.attestation.tee_class,
920            &self.attestation.platform_evidence.encoding,
921            &self.attestation.sealed_evidence.encoding,
922            &self.attestation.witness_key,
923            &self.adapter.system,
924            &self.adapter.endpoint,
925        ] {
926            if value.is_empty() {
927                return Err(Error::Validation("required string must not be empty"));
928            }
929        }
930        validate_utc(&self.ts)?;
931        validate_optional_window(
932            self.site.envelope.temporal.starts.as_deref(),
933            self.site.envelope.temporal.ends.as_deref(),
934        )?;
935        let start = validate_utc(&self.engagement.window.start)?;
936        let end = validate_utc(&self.engagement.window.end)?;
937        if end < start {
938            return Err(Error::Validation(
939                "engagement window end precedes its start",
940            ));
941        }
942        validate_utc(&self.adapter.posted_at)?;
943        validate_sha256(&self.site.envelope.digest)?;
944        validate_sha256(&self.engagement.evidence_digest)?;
945        if self.spec == SPEC_VERSION_07 {
946            match self.engagement.content_digest.as_ref() {
947                Some(serde_json::Value::Null) => {}
948                Some(serde_json::Value::String(digest)) => validate_sha256(digest)?,
949                _ => {
950                    return Err(Error::Validation(
951                        "0.7 requires explicit null or SHA-256 contentDigest",
952                    ));
953                }
954            }
955        } else if self.engagement.content_digest.is_some() {
956            return Err(Error::Validation(
957                "contentDigest is not permitted in legacy profiles",
958            ));
959        }
960        validate_sha256(&self.attestation.measured_boot.chain)?;
961        validate_sha256(&self.attestation.platform_evidence.digest)?;
962        validate_sha256(&self.attestation.sealed_evidence.digest)?;
963        for component in &self.attestation.measured_boot.components {
964            if component.name.is_empty() {
965                return Err(Error::Validation(
966                    "measured-boot component name must not be empty",
967                ));
968            }
969            validate_sha256(&component.digest)?;
970        }
971        let validity_start = validate_utc(&self.attestation.validity.not_before)?;
972        let validity_end = validate_utc(&self.attestation.validity.not_after)?;
973        // Q3, ruled 2026-08-09: `pask-wire` and `pask-attest` MUST enforce the
974        // identical rule. `pask-attest` rejects a zero-length window
975        // (`validity.rs`, `not_after <= not_before`); this crate previously
976        // accepted one, so a payload could pass one crate and fail the other.
977        // That is the Axis-B defect class this revision exists to close, so it
978        // is not left standing inside the revision that closes it.
979        //
980        // The single rule, stated once: notAfter MUST be strictly later than
981        // notBefore. A zero-length window asserts validity for an instant of
982        // zero duration and has no legitimate producer.
983        //
984        // Out of scope in `-01`: containment of `ts` within the window is NOT
985        // required in this revision. The interval is carried and its internal
986        // consistency is checked; nothing validates an event timestamp against
987        // it. Stated plainly so no policy author writes a rule this
988        // implementation does not enforce.
989        if validity_end <= validity_start {
990            return Err(Error::Validation(
991                "attestation validity notAfter must be strictly later than notBefore",
992            ));
993        }
994        // Issue #30: Under wilder.pser/0.6 and proposed 0.7, check that
995        // the receipt-issuance timestamp `ts` falls within the attestation
996        // validity interval [notBefore, notAfter] using inclusive endpoints.
997        // This check does not apply to wilder.pser/0.5, whose profile does not
998        // require timestamp containment. A separately identified local policy
999        // may perform an additional check without changing the historical
1000        // profile contract.
1001        if self.spec == SPEC_VERSION_06 || self.spec == SPEC_VERSION_07 {
1002            let ts = validate_utc(&self.ts)?;
1003            if ts < validity_start || ts > validity_end {
1004                return Err(Error::Validation(
1005                    "receipt-issuance timestamp is outside the attestation validity interval",
1006                ));
1007            }
1008        }
1009        validate_sha256(&self.adapter.ack_digest)?;
1010        match (self.chain.seq, self.chain.prev_hash.as_deref()) {
1011            (0, None) => {}
1012            (0, Some(_)) => {
1013                return Err(Error::Validation("sequence zero must have null prevHash"));
1014            }
1015            (_, Some(previous)) => validate_sha256(previous)?,
1016            (_, None) => {
1017                return Err(Error::Validation("nonzero sequence must include prevHash"));
1018            }
1019        }
1020        validate_sha256(&self.chain.hash)?;
1021        if self.chain.hash != self.expected_chain_hash()? {
1022            return Err(Error::Validation("chain.hash does not match payload"));
1023        }
1024        Ok(())
1025    }
1026}
1027
1028/// Canonicalizes one JSON value according to RFC 8785.
1029///
1030/// # Errors
1031///
1032/// Returns an error for malformed JSON or values outside the finite I-JSON number domain.
1033pub fn canonicalize_json(bytes: &[u8]) -> Result<Vec<u8>> {
1034    let value: serde_json::Value =
1035        serde_json::from_slice(bytes).map_err(|error| Error::Json(error.to_string()))?;
1036    canonicalize_value(&value)
1037}
1038
1039fn canonicalize_value(value: &serde_json::Value) -> Result<Vec<u8>> {
1040    let mut output = Vec::new();
1041    write_canonical(value, &mut output)?;
1042    Ok(output)
1043}
1044
1045fn write_canonical(value: &serde_json::Value, output: &mut Vec<u8>) -> Result<()> {
1046    match value {
1047        serde_json::Value::Null => output.extend_from_slice(b"null"),
1048        serde_json::Value::Bool(true) => output.extend_from_slice(b"true"),
1049        serde_json::Value::Bool(false) => output.extend_from_slice(b"false"),
1050        serde_json::Value::Number(number) => {
1051            let text = if let Some(integer) = number.as_i64() {
1052                integer.to_string()
1053            } else if let Some(integer) = number.as_u64() {
1054                integer.to_string()
1055            } else {
1056                let number = number
1057                    .as_f64()
1058                    .ok_or(Error::Jcs("number is not representable as f64".to_owned()))?;
1059                if !number.is_finite() {
1060                    return Err(Error::Jcs("JCS numbers must be finite".to_owned()));
1061                }
1062                ryu_js::Buffer::new().format_finite(number).to_owned()
1063            };
1064            output.extend_from_slice(text.as_bytes());
1065        }
1066        serde_json::Value::String(string) => {
1067            let escaped =
1068                serde_json::to_string(string).map_err(|error| Error::Jcs(error.to_string()))?;
1069            output.extend_from_slice(escaped.as_bytes());
1070        }
1071        serde_json::Value::Array(values) => {
1072            output.push(b'[');
1073            for (index, item) in values.iter().enumerate() {
1074                if index != 0 {
1075                    output.push(b',');
1076                }
1077                write_canonical(item, output)?;
1078            }
1079            output.push(b']');
1080        }
1081        serde_json::Value::Object(object) => {
1082            let mut entries: Vec<_> = object.iter().collect();
1083            entries.sort_by(|(left, _), (right, _)| left.encode_utf16().cmp(right.encode_utf16()));
1084            output.push(b'{');
1085            for (index, (key, item)) in entries.into_iter().enumerate() {
1086                if index != 0 {
1087                    output.push(b',');
1088                }
1089                let escaped =
1090                    serde_json::to_string(key).map_err(|error| Error::Jcs(error.to_string()))?;
1091                output.extend_from_slice(escaped.as_bytes());
1092                output.push(b':');
1093                write_canonical(item, output)?;
1094            }
1095            output.push(b'}');
1096        }
1097    }
1098    Ok(())
1099}
1100
1101fn validate_utc(value: &str) -> Result<OffsetDateTime> {
1102    if !value.ends_with('Z') {
1103        return Err(Error::Validation("timestamp must use UTC Z notation"));
1104    }
1105    OffsetDateTime::parse(value, &Rfc3339)
1106        .map_err(|_| Error::Validation("timestamp must be valid RFC 3339"))
1107}
1108
1109fn validate_optional_window(starts: Option<&str>, ends: Option<&str>) -> Result<()> {
1110    let starts = starts.map(validate_utc).transpose()?;
1111    let ends = ends.map(validate_utc).transpose()?;
1112    if let (Some(start), Some(end)) = (starts, ends)
1113        && end < start
1114    {
1115        return Err(Error::Validation("temporal end precedes its start"));
1116    }
1117    Ok(())
1118}