Skip to main content

ratify_protocol/
wire.rs

1//! Wire decoders and the `VerificationReceipt` codec pair (SPEC §17.5, §5.1).
2//!
3//! Decoders are strict: unknown fields are rejected (serde `deny_unknown_fields`
4//! on the wire types), the wire-integer domain and canonical base64 are
5//! enforced by the field (de)serializers, and the input bounds of SPEC §5.1 are
6//! enforced here — [`decode_proof_bundle`] rejects an oversized payload BEFORE
7//! parsing, and JSON container nesting beyond [`MAX_JSON_NESTING_DEPTH`] is
8//! rejected up front. Violations are structural failures — callers surface them
9//! as the existing `invalid` status.
10//!
11//! JSON parsing (and therefore the `decode_*` functions) requires `serde_json`
12//! and is only available with the `std` feature. [`encode_verification_receipt`]
13//! and [`check_json_nesting_depth`] are `no_std`-compatible.
14
15#[cfg(not(feature = "std"))]
16use alloc::{format, string::String, string::ToString, vec::Vec};
17
18use crate::types::{
19    is_canonical_constraint_type, DelegationCert, IdentityStatus, VerificationReceipt,
20    MAX_CONSTRAINTS_PER_CERT, MAX_IDENTIFIER_LENGTH_BYTES, MAX_JSON_NESTING_DEPTH,
21    MAX_SCOPES_PER_CERT, MAX_SCOPE_LENGTH_BYTES,
22};
23
24use crate::canonical::{encode_bytes_b64, encode_hybrid_pub_key, encode_hybrid_sig, encode_i64, encode_str, encode_str_array};
25use crate::resource_path::validate_constraint_params;
26
27/// Reject JSON whose container nesting exceeds [`MAX_JSON_NESTING_DEPTH`],
28/// scanning the raw bytes with string-literal awareness so brackets inside
29/// strings do not count. Mirrors the depth rule of Go's `CheckWireJSON`.
30pub fn check_json_nesting_depth(data: &[u8]) -> Result<(), String> {
31    let mut depth: usize = 0;
32    let mut in_string = false;
33    let mut escaped = false;
34    for &b in data {
35        if in_string {
36            if escaped {
37                escaped = false;
38            } else if b == b'\\' {
39                escaped = true;
40            } else if b == b'"' {
41                in_string = false;
42            }
43            continue;
44        }
45        match b {
46            b'"' => in_string = true,
47            b'{' | b'[' => {
48                if depth >= MAX_JSON_NESTING_DEPTH {
49                    return Err(format!(
50                        "wire: JSON nesting exceeds MAX_JSON_NESTING_DEPTH ({})",
51                        MAX_JSON_NESTING_DEPTH
52                    ));
53                }
54                depth += 1;
55            }
56            b'}' | b']' => {
57                depth = depth.saturating_sub(1);
58            }
59            _ => {}
60        }
61    }
62    Ok(())
63}
64
65/// Enforce the per-cert count and length limits of SPEC §5.1 during decode.
66/// Does NOT enforce issuance hygiene (`validate_resource_constraints`) —
67/// decoders accept what issuance rejects; verification fails unsatisfiable
68/// sets closed.
69pub fn check_cert_bounds(cert: &DelegationCert) -> Result<(), String> {
70    if cert.scope.len() > MAX_SCOPES_PER_CERT {
71        return Err(format!(
72            "wire: {} scopes exceeds MAX_SCOPES_PER_CERT ({})",
73            cert.scope.len(),
74            MAX_SCOPES_PER_CERT
75        ));
76    }
77    if cert.constraints.len() > MAX_CONSTRAINTS_PER_CERT {
78        return Err(format!(
79            "wire: {} constraints exceeds MAX_CONSTRAINTS_PER_CERT ({})",
80            cert.constraints.len(),
81            MAX_CONSTRAINTS_PER_CERT
82        ));
83    }
84    for s in &cert.scope {
85        if s.len() > MAX_SCOPE_LENGTH_BYTES {
86            return Err(format!(
87                "wire: scope of {} bytes exceeds MAX_SCOPE_LENGTH_BYTES ({})",
88                s.len(),
89                MAX_SCOPE_LENGTH_BYTES
90            ));
91        }
92    }
93    for c in &cert.constraints {
94        if c.resource_id.len() > MAX_IDENTIFIER_LENGTH_BYTES {
95            return Err(format!(
96                "wire: resource_id of {} bytes exceeds MAX_IDENTIFIER_LENGTH_BYTES ({})",
97                c.resource_id.len(),
98                MAX_IDENTIFIER_LENGTH_BYTES
99            ));
100        }
101        if c.params.is_some() {
102            if is_canonical_constraint_type(&c.kind) {
103                return Err(format!(
104                    "wire: canonical constraint type \"{}\" must not carry params",
105                    c.kind
106                ));
107            }
108            validate_constraint_params(c).map_err(|e| format!("wire: constraint params: {}", e))?;
109        }
110    }
111    Ok(())
112}
113
114/// Enforce the structural invariants of a wire [`VerificationReceipt`]
115/// (SPEC §17.5) — shared by the encoder and decoder so the codec pair never
116/// emits a document its counterpart rejects.
117pub fn check_receipt_structure(r: &VerificationReceipt) -> Result<(), String> {
118    if r.version != crate::types::PROTOCOL_VERSION {
119        return Err(format!(
120            "wire: receipt version {} is not PROTOCOL_VERSION ({})",
121            r.version,
122            crate::types::PROTOCOL_VERSION
123        ));
124    }
125    if r.verifier_id.is_empty() {
126        return Err("wire: receipt verifier_id must be non-empty".to_string());
127    }
128    if IdentityStatus::from_wire(&r.decision).is_none() {
129        return Err(format!(
130            "wire: receipt decision \"{}\" is not a known identity_status",
131            r.decision
132        ));
133    }
134    if r.bundle_hash.len() != 32 {
135        return Err(format!(
136            "wire: bundle_hash must be 32 bytes, got {}",
137            r.bundle_hash.len()
138        ));
139    }
140    if r.prev_hash.len() != 32 {
141        return Err(format!(
142            "wire: prev_hash must be 32 bytes, got {}",
143            r.prev_hash.len()
144        ));
145    }
146    if r.verifier_pub.ed25519.len() != 32 {
147        return Err(format!(
148            "wire: verifier_pub.ed25519 must be 32 bytes, got {}",
149            r.verifier_pub.ed25519.len()
150        ));
151    }
152    if r.verifier_pub.ml_dsa_65.len() != 1952 {
153        return Err(format!(
154            "wire: verifier_pub.ml_dsa_65 must be 1952 bytes, got {}",
155            r.verifier_pub.ml_dsa_65.len()
156        ));
157    }
158    if r.signature.ed25519.len() != 64 {
159        return Err(format!(
160            "wire: signature.ed25519 must be 64 bytes, got {}",
161            r.signature.ed25519.len()
162        ));
163    }
164    if r.signature.ml_dsa_65.len() != 3309 {
165        return Err(format!(
166            "wire: signature.ml_dsa_65 must be 3309 bytes, got {}",
167            r.signature.ml_dsa_65.len()
168        ));
169    }
170    Ok(())
171}
172
173/// Marshal a [`VerificationReceipt`] into its canonical wire JSON (SPEC §17.5):
174/// lex-sorted keys, byte fields as base64-standard strings, optional fields
175/// omitted when empty. A structurally invalid receipt is an error, never
176/// emitted: the codec pair never produces a document its own decoder rejects.
177pub fn encode_verification_receipt(r: &VerificationReceipt) -> Result<Vec<u8>, String> {
178    check_receipt_structure(r)?;
179    // Keys in lex order: agent_id, bundle_hash, decision, error_reason,
180    // granted_scope, human_id, prev_hash, signature, verified_at,
181    // verifier_id, verifier_pub, version.
182    let mut out = String::new();
183    out.push('{');
184    let mut sep = "";
185    if !r.agent_id.is_empty() {
186        out.push_str(sep); sep = ",";
187        out.push_str("\"agent_id\":"); encode_str(&r.agent_id, &mut out);
188    }
189    out.push_str(sep); sep = ",";
190    out.push_str("\"bundle_hash\":"); encode_bytes_b64(&r.bundle_hash, &mut out);
191    out.push_str(sep);
192    out.push_str("\"decision\":"); encode_str(&r.decision, &mut out);
193    if !r.error_reason.is_empty() {
194        out.push_str(sep);
195        out.push_str("\"error_reason\":"); encode_str(&r.error_reason, &mut out);
196    }
197    if !r.granted_scope.is_empty() {
198        out.push_str(sep);
199        out.push_str("\"granted_scope\":"); encode_str_array(&r.granted_scope, &mut out);
200    }
201    if !r.human_id.is_empty() {
202        out.push_str(sep);
203        out.push_str("\"human_id\":"); encode_str(&r.human_id, &mut out);
204    }
205    out.push_str(sep);
206    out.push_str("\"prev_hash\":"); encode_bytes_b64(&r.prev_hash, &mut out);
207    out.push_str(sep);
208    out.push_str("\"signature\":"); encode_hybrid_sig(&r.signature, &mut out);
209    out.push_str(sep);
210    out.push_str("\"verified_at\":"); encode_i64(r.verified_at, &mut out);
211    out.push_str(sep);
212    out.push_str("\"verifier_id\":"); encode_str(&r.verifier_id, &mut out);
213    out.push_str(sep);
214    out.push_str("\"verifier_pub\":"); encode_hybrid_pub_key(&r.verifier_pub, &mut out);
215    out.push_str(sep);
216    out.push_str("\"version\":"); out.push_str(&r.version.to_string());
217    out.push('}');
218    Ok(out.into_bytes())
219}
220
221// ------------------------------------------------------------------
222// JSON decoders (require serde_json → std only).
223// ------------------------------------------------------------------
224
225/// Parse canonical wire JSON into a [`DelegationCert`] under strict wire
226/// acceptance and the SPEC §5.1 input bounds.
227#[cfg(feature = "std")]
228pub fn decode_delegation_cert(data: &[u8]) -> Result<DelegationCert, String> {
229    check_json_nesting_depth(data)?;
230    let cert: DelegationCert =
231        serde_json::from_slice(data).map_err(|e| format!("wire: {}", e))?;
232    check_cert_bounds(&cert)?;
233    Ok(cert)
234}
235
236/// Parse canonical wire JSON into a [`crate::types::ProofBundle`] under strict
237/// wire acceptance and the SPEC §5.1 input bounds. The
238/// [`MAX_PROOF_BUNDLE_BYTES`] check runs BEFORE any parsing: an oversized
239/// payload is rejected without being parsed at all.
240#[cfg(feature = "std")]
241pub fn decode_proof_bundle(data: &[u8]) -> Result<crate::types::ProofBundle, String> {
242    if data.len() > crate::types::MAX_PROOF_BUNDLE_BYTES {
243        return Err(format!(
244            "wire: proof bundle of {} bytes exceeds MAX_PROOF_BUNDLE_BYTES ({})",
245            data.len(),
246            crate::types::MAX_PROOF_BUNDLE_BYTES
247        ));
248    }
249    check_json_nesting_depth(data)?;
250    let bundle: crate::types::ProofBundle =
251        serde_json::from_slice(data).map_err(|e| format!("wire: {}", e))?;
252    // Chain depth is NOT enforced here: it is a verify-time semantic ceiling
253    // (chain_too_deep), not a wire-structural bound. The byte limit above
254    // already caps pre-parse work, and an over-deep chain must reach verify
255    // to produce its documented identity_status. This keeps every SDK's
256    // public decoder identical: decode succeeds, verify rejects.
257    for cert in &bundle.delegations {
258        check_cert_bounds(cert)?;
259    }
260    Ok(bundle)
261}
262
263// Strict wire mirror of VerificationReceipt: rejects unknown fields at decode
264// so constraint-level strictness holds regardless of the public type's serde
265// configuration.
266#[cfg(feature = "std")]
267#[derive(serde::Deserialize)]
268#[serde(deny_unknown_fields)]
269struct VerificationReceiptWire {
270    version: i32,
271    verifier_id: String,
272    verifier_pub: crate::types::HybridPublicKey,
273    #[serde(with = "crate::canonical::base64_bytes")]
274    bundle_hash: Vec<u8>,
275    decision: String,
276    #[serde(default)]
277    human_id: String,
278    #[serde(default)]
279    agent_id: String,
280    #[serde(default)]
281    granted_scope: Vec<String>,
282    #[serde(default)]
283    error_reason: String,
284    verified_at: i64,
285    #[serde(with = "crate::canonical::base64_bytes")]
286    prev_hash: Vec<u8>,
287    signature: crate::types::HybridSignature,
288}
289
290/// Parse canonical wire JSON into a [`VerificationReceipt`] under strict wire
291/// acceptance and the same structural invariants the encoder enforces (hash
292/// and key-component lengths, known decision, protocol version). Signature
293/// verification is the caller's job via `verify_verification_receipt`.
294#[cfg(feature = "std")]
295pub fn decode_verification_receipt(data: &[u8]) -> Result<VerificationReceipt, String> {
296    check_json_nesting_depth(data)?;
297    let w: VerificationReceiptWire =
298        serde_json::from_slice(data).map_err(|e| format!("wire: {}", e))?;
299    let r = VerificationReceipt {
300        version: w.version,
301        verifier_id: w.verifier_id,
302        verifier_pub: w.verifier_pub,
303        bundle_hash: w.bundle_hash,
304        decision: w.decision,
305        human_id: w.human_id,
306        agent_id: w.agent_id,
307        granted_scope: w.granted_scope,
308        error_reason: w.error_reason,
309        verified_at: w.verified_at,
310        prev_hash: w.prev_hash,
311        signature: w.signature,
312    };
313    check_receipt_structure(&r)?;
314    Ok(r)
315}