pask-wire 0.2.0

SCITT-style COSE receipt library for Physical-Site Engagement Receipts: supplied-key production and verification for the wilder.pser/0.5, 0.6 and 0.7 profiles, not complete conformance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Wilder Management Inc. (d/b/a Wilder Robotics)
//! Local, bounded, self-contained JSON replay envelope for RECIPIENT-01.
//! This is not the PSER or content-proof wire format. Hex fields preserve the
//! original statement/fact/evidence bytes. The explicit key is outside the
//! document. The document's policy and context are unauthenticated local inputs.
//! No retrieval, discovery, service verification, or application decision occurs.

use crate::proposed_content::{
    ContentHeader, DisclosedFact, MAX_FACT_BYTES, MAX_FACTS, MAX_PROOF_HASHES,
};
use crate::proposed_evidence::{MAX_PRESENTED_EVIDENCE_BYTES, PresentedEvidence};
use crate::proposed_recipient::{
    ContentPresentation, ExpectedContext, LocalEvidenceObject, MAX_CONTEXT_BYTES,
    MAX_LOCAL_OBJECTS, MAX_STATEMENT_BYTES, RecipientPolicy, RecipientReport,
    inspect_proposed_recipient_ed25519,
};
use crate::{
    InspectionFinding, InspectionStatus, IssuerAffiliation, sha256_prefixed, verify_chain,
    verify_ed25519,
};
use alloc::{string::String, vec::Vec};
use ed25519_dalek::VerifyingKey;
use serde::{Deserialize, Deserializer, Serialize};

pub const DOCUMENT_SCHEMA: &str = "pask-local-recipient-replay/1";
pub const REPORT_SCHEMA: &str = "pask-local-recipient-replay-report/1";
pub const MAX_DOCUMENT_BYTES: usize = 8 * 1024 * 1024;
pub const MAX_DOCUMENT_DEPTH: usize = 32;
pub const MAX_ENTRIES: usize = 16;
pub const MAX_TOTAL_DECODED_BYTES: usize = 3 * 1024 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReplayMode {
    Single,
    Chain,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplayError {
    DocumentBytes,
    DocumentDepth,
    DocumentJson,
    Schema,
    EntryCount,
    ModeCardinality,
    FieldBound,
    InvalidHex,
    DecodedBudget,
    ObjectState,
    InvalidKey,
}
impl ReplayError {
    #[must_use]
    pub const fn code(self) -> &'static str {
        match self {
            Self::DocumentBytes => "document_byte_limit",
            Self::DocumentDepth => "document_depth_limit",
            Self::DocumentJson => "invalid_closed_replay_document",
            Self::Schema => "unsupported_replay_schema",
            Self::EntryCount => "entry_count_limit",
            Self::ModeCardinality => "single_mode_requires_one_entry",
            Self::FieldBound => "transport_field_limit",
            Self::InvalidHex => "invalid_lowercase_hex",
            Self::DecodedBudget => "aggregate_decoded_byte_limit",
            Self::ObjectState => "bytes_disagree_with_availability_state",
            Self::InvalidKey => "invalid_explicit_ed25519_key",
        }
    }
}

// deserialize_with (without default) requires the member even when its value
// may be null. Plain Option<T> would silently treat a missing member as None.
fn required_nullable<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    Option::<T>::deserialize(de)
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Document {
    schema: String,
    entries: Vec<Entry>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Entry {
    statement_hex: String,
    #[serde(deserialize_with = "required_nullable")]
    presentation: Option<Presentation>,
    objects: Vec<Object>,
    policy: Policy,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Presentation {
    construction: String,
    scope: String,
    vocabulary_digest: String,
    fact_count: u32,
    disclosures: Vec<Disclosure>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Disclosure {
    record_hex: String,
    salt_hex: String,
    index: u32,
    siblings_hex: Vec<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum Availability {
    Bytes,
    Unavailable,
    NotRequested,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Object {
    digest: String,
    state: Availability,
    #[serde(deserialize_with = "required_nullable")]
    bytes_hex: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Context {
    site_id: String,
    engagement_id: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Policy {
    #[serde(deserialize_with = "required_nullable")]
    expected_context: Option<Context>,
    require_presented_content: bool,
    require_all_committed_slots: bool,
    required_fact_names: Vec<String>,
    compare_unitless_scalars: bool,
}

struct OwnedDisclosure {
    record: Vec<u8>,
    salt: [u8; 32],
    index: u32,
    siblings: Vec<[u8; 32]>,
}
struct DecodedEntry {
    source: Entry,
    statement: Vec<u8>,
    disclosures: Vec<OwnedDisclosure>,
    objects: Vec<Option<Vec<u8>>>,
}

#[derive(Debug, Default, Serialize)]
pub struct ReplayMeasurements {
    pub document_bytes: usize,
    pub entry_count: usize,
    pub decoded_statement_bytes: usize,
    pub decoded_fact_bytes: usize,
    pub decoded_evidence_bytes: usize,
    pub decoded_salt_and_proof_bytes: usize,
    pub decoded_total_bytes: usize,
    pub note: &'static str,
}
#[derive(Debug, Serialize)]
pub struct ChainTransition {
    pub at_seq: u64,
    pub from: IssuerAffiliation,
    pub to: IssuerAffiliation,
}
#[derive(Debug, Serialize)]
pub struct ReplayChainReport {
    pub check: InspectionFinding,
    pub verified_payloads: usize,
    pub starts_at_genesis_required: bool,
    pub affiliation_changes: Vec<ChainTransition>,
    pub limitation: &'static str,
}
#[derive(Debug, Serialize)]
pub struct ReplayReport {
    pub schema: &'static str,
    pub mode: ReplayMode,
    pub input_document_digest: String,
    pub explicit_key_digest: String,
    pub key_origin: &'static str,
    pub policy_origin: &'static str,
    pub measurements: ReplayMeasurements,
    pub records: Vec<RecipientReport>,
    pub chain: ReplayChainReport,
    pub latest_or_complete_history: InspectionFinding,
    pub registration: InspectionFinding,
    pub application_acceptance: InspectionFinding,
    pub full_profile: InspectionFinding,
    pub note: &'static str,
}
fn finding(status: InspectionStatus, code: &'static str) -> InspectionFinding {
    InspectionFinding {
        status,
        code,
        detail: "Only the named local check; the supplied key and local policy are not authenticated origins.",
        evidence_refs: alloc::vec!["ordered_replay_entries"],
    }
}

fn raw_preflight(bytes: &[u8]) -> Result<(), ReplayError> {
    if bytes.len() > MAX_DOCUMENT_BYTES {
        return Err(ReplayError::DocumentBytes);
    }
    let (mut depth, mut in_string, mut escape) = (0usize, false, false);
    for &byte in bytes {
        if in_string {
            if escape {
                escape = false;
            } else if byte == b'\\' {
                escape = true;
            } else if byte == b'"' {
                in_string = false;
            }
        } else {
            match byte {
                b'"' => in_string = true,
                b'{' | b'[' => {
                    depth += 1;
                    if depth > MAX_DOCUMENT_DEPTH {
                        return Err(ReplayError::DocumentDepth);
                    }
                }
                b'}' | b']' => {
                    depth = depth.checked_sub(1).ok_or(ReplayError::DocumentJson)?;
                }
                _ => {}
            }
        }
    }
    // Complete syntax, duplicate/unknown fields and trailing input are checked
    // by the subsequent closed derived deserializer, not by this lexical scan.
    Ok(())
}
fn decode_hex(text: &str, maximum: usize, total: &mut usize) -> Result<Vec<u8>, ReplayError> {
    if text.len() > maximum.saturating_mul(2) || !text.len().is_multiple_of(2) {
        return Err(ReplayError::InvalidHex);
    }
    let length = text.len() / 2;
    let updated = total
        .checked_add(length)
        .ok_or(ReplayError::DecodedBudget)?;
    if updated > MAX_TOTAL_DECODED_BYTES {
        return Err(ReplayError::DecodedBudget);
    }
    fn nibble(byte: u8) -> Option<u8> {
        match byte {
            b'0'..=b'9' => Some(byte - b'0'),
            b'a'..=b'f' => Some(byte - b'a' + 10),
            _ => None,
        }
    }
    // Validate the complete string before allocating its decoded representation.
    if !text.bytes().all(|byte| nibble(byte).is_some()) {
        return Err(ReplayError::InvalidHex);
    }
    let (pairs, []) = text.as_bytes().as_chunks::<2>() else {
        return Err(ReplayError::InvalidHex);
    };
    let mut output = Vec::with_capacity(length);
    for pair in pairs {
        output.push(
            (nibble(pair[0]).ok_or(ReplayError::InvalidHex)? << 4)
                | nibble(pair[1]).ok_or(ReplayError::InvalidHex)?,
        );
    }
    *total = updated;
    Ok(output)
}
fn decode_hash(text: &str, total: &mut usize) -> Result<[u8; 32], ReplayError> {
    if text.len() != 64 {
        return Err(ReplayError::InvalidHex);
    }
    decode_hex(text, 32, total)?
        .try_into()
        .map_err(|_| ReplayError::InvalidHex)
}
/// Decode one explicit lowercase 64-hex-character public verification key.
/// It is not an authenticated identity or a secret/private key.
/// # Errors
/// Returns an error for any other representation or invalid key encoding.
pub fn replay_key_from_hex(text: &str) -> Result<VerifyingKey, ReplayError> {
    let mut used = 0;
    let bytes = decode_hash(text, &mut used).map_err(|_| ReplayError::InvalidKey)?;
    VerifyingKey::from_bytes(&bytes).map_err(|_| ReplayError::InvalidKey)
}
fn bounded_text(text: &str, maximum: usize) -> Result<(), ReplayError> {
    if text.len() > maximum {
        Err(ReplayError::FieldBound)
    } else {
        Ok(())
    }
}
fn decode_entry(source: Entry, m: &mut ReplayMeasurements) -> Result<DecodedEntry, ReplayError> {
    if source.objects.len() > MAX_LOCAL_OBJECTS
        || source.policy.required_fact_names.len() > MAX_FACTS
    {
        return Err(ReplayError::FieldBound);
    }
    for name in &source.policy.required_fact_names {
        bounded_text(name, 128)?;
    }
    if let Some(context) = &source.policy.expected_context {
        bounded_text(&context.site_id, MAX_CONTEXT_BYTES)?;
        bounded_text(&context.engagement_id, MAX_CONTEXT_BYTES)?;
    }
    let statement = decode_hex(
        &source.statement_hex,
        MAX_STATEMENT_BYTES,
        &mut m.decoded_total_bytes,
    )?;
    m.decoded_statement_bytes += statement.len();
    let mut disclosures = Vec::new();
    if let Some(p) = &source.presentation {
        bounded_text(&p.construction, 128)?;
        bounded_text(&p.scope, 128)?;
        bounded_text(&p.vocabulary_digest, 71)?;
        if p.disclosures.len() > MAX_FACTS || p.fact_count as usize > MAX_FACTS {
            return Err(ReplayError::FieldBound);
        }
        for fact in &p.disclosures {
            if fact.siblings_hex.len() > MAX_PROOF_HASHES {
                return Err(ReplayError::FieldBound);
            }
            let record = decode_hex(&fact.record_hex, MAX_FACT_BYTES, &mut m.decoded_total_bytes)?;
            m.decoded_fact_bytes += record.len();
            let salt = decode_hash(&fact.salt_hex, &mut m.decoded_total_bytes)?;
            let mut siblings = Vec::with_capacity(fact.siblings_hex.len());
            for hash in &fact.siblings_hex {
                siblings.push(decode_hash(hash, &mut m.decoded_total_bytes)?);
            }
            m.decoded_salt_and_proof_bytes += 32 * (1 + siblings.len());
            disclosures.push(OwnedDisclosure {
                record,
                salt,
                index: fact.index,
                siblings,
            });
        }
    }
    let mut objects = Vec::with_capacity(source.objects.len());
    for object in &source.objects {
        bounded_text(&object.digest, 71)?;
        let bytes = match (&object.state, &object.bytes_hex) {
            (Availability::Bytes, Some(text)) => {
                let data = decode_hex(
                    text,
                    MAX_PRESENTED_EVIDENCE_BYTES,
                    &mut m.decoded_total_bytes,
                )?;
                m.decoded_evidence_bytes += data.len();
                Some(data)
            }
            (Availability::Unavailable | Availability::NotRequested, None) => None,
            _ => return Err(ReplayError::ObjectState),
        };
        objects.push(bytes);
    }
    Ok(DecodedEntry {
        source,
        statement,
        disclosures,
        objects,
    })
}
fn inspect_entry(entry: &DecodedEntry, key: &VerifyingKey) -> RecipientReport {
    let records: Vec<_> = entry
        .disclosures
        .iter()
        .map(|f| DisclosedFact {
            record: &f.record,
            salt: f.salt,
            index: f.index,
            siblings: f.siblings.clone(),
        })
        .collect();
    let presentation = entry
        .source
        .presentation
        .as_ref()
        .map(|p| ContentPresentation {
            header: ContentHeader {
                construction: &p.construction,
                scope: &p.scope,
                vocabulary_digest: &p.vocabulary_digest,
            },
            fact_count: p.fact_count,
            disclosures: &records,
        });
    let objects: Vec<_> = entry
        .source
        .objects
        .iter()
        .zip(&entry.objects)
        .map(|(input, bytes)| {
            let availability = match &input.state {
                Availability::Bytes => PresentedEvidence::Bytes(bytes.as_deref().unwrap_or(&[])),
                Availability::Unavailable => PresentedEvidence::Unavailable,
                Availability::NotRequested => PresentedEvidence::NotRequested,
            };
            LocalEvidenceObject {
                digest: &input.digest,
                availability,
            }
        })
        .collect();
    let p = &entry.source.policy;
    let names: Vec<_> = p.required_fact_names.iter().map(String::as_str).collect();
    let policy = RecipientPolicy {
        expected_context: p.expected_context.as_ref().map(|c| ExpectedContext {
            site_id: &c.site_id,
            engagement_id: &c.engagement_id,
        }),
        require_presented_content: p.require_presented_content,
        require_all_committed_slots: p.require_all_committed_slots,
        required_fact_names: &names,
        compare_unitless_scalars: p.compare_unitless_scalars,
    };
    inspect_proposed_recipient_ed25519(&entry.statement, key, presentation, &objects, &policy)
}

/// Parse a bounded local replay envelope and evaluate its entries with the
/// unchanged RECIPIENT-01 path. Chain mode additionally invokes verify_chain
/// only on individually checked Payloads. No input is sorted or gap-filled.
/// # Errors
/// Returns a framing/resource error for malformed closed-schema JSON, bad hex,
/// or finite transport limits. Semantic verification failures are report fields,
/// not transport errors. Reports are not application acceptance decisions.
pub fn inspect_replay_document(
    bytes: &[u8],
    key: &VerifyingKey,
    mode: ReplayMode,
) -> Result<ReplayReport, ReplayError> {
    raw_preflight(bytes)?;
    let document: Document =
        serde_json::from_slice(bytes).map_err(|_| ReplayError::DocumentJson)?;
    if document.schema != DOCUMENT_SCHEMA {
        return Err(ReplayError::Schema);
    }
    if document.entries.is_empty() || document.entries.len() > MAX_ENTRIES {
        return Err(ReplayError::EntryCount);
    }
    if mode == ReplayMode::Single && document.entries.len() != 1 {
        return Err(ReplayError::ModeCardinality);
    }
    let mut measurements = ReplayMeasurements {
        document_bytes: bytes.len(),
        entry_count: document.entries.len(),
        note: "Input sizes only, not CPU, peak memory or an overall hashing-work bound; policy/header JSON is not decoded binary.",
        ..ReplayMeasurements::default()
    };
    // Parse/decode every entry before evaluating any. An invalid late envelope
    // cannot yield a successful partial batch. No external path is dereferenced.
    let mut entries = Vec::with_capacity(document.entries.len());
    for entry in document.entries {
        entries.push(decode_entry(entry, &mut measurements)?);
    }
    let reports: Vec<_> = entries
        .iter()
        .map(|entry| inspect_entry(entry, key))
        .collect();
    let mut chain = ReplayChainReport {
        check: finding(
            InspectionStatus::NotEvaluated,
            "single_mode_does_not_check_chain",
        ),
        verified_payloads: 0,
        starts_at_genesis_required: mode == ReplayMode::Chain,
        affiliation_changes: Vec::new(),
        limitation: "Checks presented sequence/hash links from genesis only; no discovery, identity continuity, same-site guarantee, latest-history or semantic completeness. Single-record findings stay scoped to their original calls.",
    };
    if mode == ReplayMode::Chain {
        if reports
            .iter()
            .any(|r| r.statement_check.status != InspectionStatus::Passed)
        {
            chain.check = finding(
                InspectionStatus::Unestablished,
                "all_statements_must_pass_before_chain_check",
            );
        } else {
            // Reuse the existing verifier to obtain its invariant-preserving
            // Payload type. This intentionally rechecks signatures; it does not
            // trust payload fields deserialized from an unsigned transport copy.
            let payloads: Result<Vec<_>, _> = entries
                .iter()
                .map(|entry| verify_ed25519(&entry.statement, key))
                .collect();
            match payloads {
                Err(_) => {
                    chain.check = finding(
                        InspectionStatus::Unestablished,
                        "payload_reverification_failed",
                    )
                }
                Ok(payloads) => {
                    chain.verified_payloads = payloads.len();
                    // Defensive ceiling before the inherited unchecked seq+1.
                    if payloads
                        .windows(2)
                        .any(|pair| pair[0].chain_seq().checked_add(1).is_none())
                    {
                        chain.check = finding(InspectionStatus::Failed, "chain_sequence_overflow");
                    } else {
                        match verify_chain(&payloads) {
                            Ok(result) => {
                                chain.check = finding(
                                    InspectionStatus::Passed,
                                    "presented_genesis_sequence_and_predecessor_hashes_checked",
                                );
                                chain.affiliation_changes = result
                                    .affiliation_changes()
                                    .iter()
                                    .map(|c| ChainTransition {
                                        at_seq: c.at_seq,
                                        from: c.from.clone(),
                                        to: c.to.clone(),
                                    })
                                    .collect();
                            }
                            Err(_) => {
                                chain.check = finding(
                                    InspectionStatus::Failed,
                                    "presented_chain_relation_failed",
                                )
                            }
                        }
                    }
                }
            }
        }
    }
    Ok(ReplayReport {
        schema: REPORT_SCHEMA,
        mode,
        input_document_digest: sha256_prefixed(bytes),
        explicit_key_digest: sha256_prefixed(key.as_bytes()),
        key_origin: "EXPLICIT_CALLER_KEY_UNAUTHENTICATED_ORIGIN",
        policy_origin: "LOCAL_DOCUMENT_NOT_AUTHENTICATED_POLICY",
        measurements,
        records: reports,
        chain,
        latest_or_complete_history: finding(
            InspectionStatus::Unestablished,
            "valid_prefix_does_not_exclude_withheld_suffix",
        ),
        registration: finding(
            InspectionStatus::NotEvaluated,
            "no_service_receipt_verification_in_this_runner",
        ),
        application_acceptance: finding(
            InspectionStatus::Unestablished,
            "reports_are_not_acceptance",
        ),
        full_profile: finding(
            InspectionStatus::Unestablished,
            "local_proposal_not_full_conformance",
        ),
        note: "One explicit Ed25519 key for all entries; no rotation lookup. Unchanged single-record reports and an additional batch chain finding, not a global pass/fail verdict.",
    })
}