Skip to main content

ratify_protocol/
types.rs

1//! Ratify Protocol v1 types.
2//!
3//! Every public key and every signature is a hybrid pair: one Ed25519
4//! component and one ML-DSA-65 (FIPS 204) component. Both must verify.
5
6#[cfg(not(feature = "std"))]
7use alloc::{boxed::Box, format, string::String, string::ToString, vec, vec::Vec};
8
9use alloc::collections::BTreeMap;
10use serde::de::{Error as DeError, MapAccess, SeqAccess, Visitor};
11use serde::ser::{SerializeMap, SerializeSeq, Serializer};
12use serde::{Deserialize, Deserializer, Serialize};
13use core::fmt;
14
15pub const PROTOCOL_VERSION: i32 = 1;
16
17/// The `expires_at` value that means "no expiry (until revoked)":
18/// 4070908799 = 2099-12-31 23:59:59 UTC. `DelegationCert.expires_at` is a
19/// required i64 with no null representation, so open-ended delegations carry
20/// this sentinel in the signed bytes. Conformant implementations MUST treat
21/// a cert with `expires_at == NO_EXPIRY_SENTINEL` as "no expiry (until
22/// revoked)" in display and policy evaluation — NOT as a literal 2099
23/// expiry. Verification is unchanged: the sentinel is a future timestamp, so
24/// the temporal check passes; revocation is the sole termination mechanism
25/// for such certs. See SPEC §5.7.
26pub const NO_EXPIRY_SENTINEL: i64 = 4070908799;
27/// Maximum number of certs in a delegation chain. A wire-determinism and
28/// denial-of-service bound, not cryptography (SPEC §5.1); raised from 3 to 8
29/// in v1.0.0-alpha.16 for multi-hop agent topologies.
30pub const MAX_DELEGATION_CHAIN_DEPTH: usize = 8;
31pub const CHALLENGE_WINDOW_SECONDS: i64 = 300;
32
33// Input bounds (SPEC §5.1). The depth ceiling alone does not bound parsing or
34// intersection work; these limits do. Violations route to the existing
35// `invalid` status with a descriptive error_reason — no new status.
36
37/// Bounds the encoded size of a ProofBundle. Wire decoders enforce it BEFORE
38/// parsing; an oversized payload is rejected without ever being parsed.
39pub const MAX_PROOF_BUNDLE_BYTES: usize = 131072; // 128 KiB
40/// Bounds `len(DelegationCert.scope)`.
41pub const MAX_SCOPES_PER_CERT: usize = 128;
42/// Bounds `len(DelegationCert.constraints)`.
43pub const MAX_CONSTRAINTS_PER_CERT: usize = 32;
44/// Bounds the UTF-8 byte length of a single scope.
45pub const MAX_SCOPE_LENGTH_BYTES: usize = 256;
46/// Bounds `resource_path`'s `resource_id` (SPEC §5.1).
47pub const MAX_IDENTIFIER_LENGTH_BYTES: usize = 512;
48/// Bounds `AgentIdentity.name` (UTF-8 bytes), enforced at construction.
49pub const MAX_AGENT_NAME_LENGTH_BYTES: usize = 256;
50/// Bounds JSON container nesting in wire documents, enforced during parse.
51pub const MAX_JSON_NESTING_DEPTH: usize = 16;
52
53pub const ED25519_PUBLIC_KEY_SIZE: usize = 32;
54pub const ED25519_SIGNATURE_SIZE: usize = 64;
55pub const MLDSA65_PUBLIC_KEY_SIZE: usize = 1952;
56pub const MLDSA65_SIGNATURE_SIZE: usize = 3309;
57
58/// Ed25519 + ML-DSA-65 public key pair.
59///
60/// Canonical JSON form (keys in lex order):
61/// `{"ed25519":"<base64-32-bytes>","ml_dsa_65":"<base64-1952-bytes>"}`
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct HybridPublicKey {
65    #[serde(with = "crate::canonical::base64_bytes")]
66    pub ed25519: Vec<u8>, // 32 bytes
67    #[serde(with = "crate::canonical::base64_bytes")]
68    pub ml_dsa_65: Vec<u8>, // 1952 bytes
69}
70
71/// Ed25519 + ML-DSA-65 signature pair over the same canonical bytes.
72///
73/// Both components MUST verify for the signature to be accepted.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub struct HybridSignature {
77    #[serde(with = "crate::canonical::base64_bytes")]
78    pub ed25519: Vec<u8>, // 64 bytes
79    #[serde(with = "crate::canonical::base64_bytes")]
80    pub ml_dsa_65: Vec<u8>, // 3309 bytes
81}
82
83/// Both component private keys. Never serialized to the wire.
84///
85/// The components are private: read them only to persist the key, through
86/// [`HybridPrivateKey::ed25519`] and [`HybridPrivateKey::ml_dsa_65`]. Both
87/// buffers are wiped when the value is dropped, and `Debug` prints only the
88/// Ed25519 public half.
89#[derive(Clone)]
90pub struct HybridPrivateKey {
91    ed25519: Vec<u8>,   // 32-byte seed (or 64-byte seed || public)
92    ml_dsa_65: Vec<u8>, // ML-DSA-65 secret key bytes
93}
94
95impl HybridPrivateKey {
96    /// Assemble a private key from stored components: the 32-byte Ed25519
97    /// seed (or the 64-byte seed-and-public form) and the ML-DSA-65 secret
98    /// key bytes. The components are validated when the key is used.
99    pub fn from_components(ed25519: Vec<u8>, ml_dsa_65: Vec<u8>) -> Self {
100        HybridPrivateKey { ed25519, ml_dsa_65 }
101    }
102
103    /// The Ed25519 private component. Secret: handle it as key material.
104    pub fn ed25519(&self) -> &[u8] {
105        &self.ed25519
106    }
107
108    /// The ML-DSA-65 secret key bytes. Secret: handle them as key material.
109    pub fn ml_dsa_65(&self) -> &[u8] {
110        &self.ml_dsa_65
111    }
112}
113
114impl Drop for HybridPrivateKey {
115    fn drop(&mut self) {
116        use zeroize::Zeroize;
117        self.ed25519.zeroize();
118        self.ml_dsa_65.zeroize();
119    }
120}
121
122impl fmt::Debug for HybridPrivateKey {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        let public = self
125            .ed25519
126            .get(..32)
127            .and_then(|s| <[u8; 32]>::try_from(s).ok())
128            .map(zeroize::Zeroizing::new)
129            .map(|seed| {
130                hex::encode(ed25519_dalek::SigningKey::from_bytes(&seed).verifying_key().to_bytes())
131            });
132        f.debug_struct("HybridPrivateKey")
133            .field("ed25519_public", &public)
134            .finish_non_exhaustive()
135    }
136}
137
138/// Optional external binding for higher-assurance identity.
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct Anchor {
141    #[serde(rename = "type")]
142    pub anchor_type: String,
143    pub provider: String,
144    pub reference: String,
145    pub verified_at: i64,
146}
147
148/// Master identity for a human (or tenant admin).
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct HumanRoot {
151    pub id: String,
152    pub public_key: HybridPublicKey,
153    pub created_at: i64,
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub anchors: Option<Vec<Anchor>>,
156}
157
158/// An AI agent's identity.
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct AgentIdentity {
161    pub id: String,
162    pub public_key: HybridPublicKey,
163    pub name: String,
164    pub agent_type: String,
165    pub created_at: i64,
166}
167
168/// Signed authorization from a principal to an agent.
169///
170/// `scope` answers *what* the agent may do. `constraints` answer *where /
171/// when / how much* — first-class bounds evaluated at verify time against a
172/// caller-supplied VerifierContext.
173#[derive(Debug, Clone, Serialize, Deserialize)]
174#[serde(deny_unknown_fields)]
175pub struct DelegationCert {
176    pub cert_id: String,
177    pub version: i32,
178    pub issuer_id: String,
179    pub issuer_pub_key: HybridPublicKey,
180    pub subject_id: String,
181    pub subject_pub_key: HybridPublicKey,
182    pub scope: Vec<String>,
183    /// Always present in canonical JSON (`[]` when empty) so canonical bytes
184    /// are deterministic across issuers.
185    #[serde(default)]
186    pub constraints: Vec<Constraint>,
187    #[serde(
188        serialize_with = "crate::canonical::wire_int::serialize",
189        deserialize_with = "crate::canonical::wire_int::deserialize"
190    )]
191    pub issued_at: i64,
192    #[serde(
193        serialize_with = "crate::canonical::wire_int::serialize",
194        deserialize_with = "crate::canonical::wire_int::deserialize"
195    )]
196    pub expires_at: i64,
197    pub signature: HybridSignature,
198}
199
200impl DelegationCert {
201    /// Reports whether the cert carries [`NO_EXPIRY_SENTINEL`], meaning "no
202    /// expiry (until revoked)". Callers rendering expiry to users or applying
203    /// lifetime policy caps MUST branch on this rather than treating the
204    /// sentinel as a real 2099 timestamp.
205    pub fn is_no_expiry(&self) -> bool {
206        self.expires_at == NO_EXPIRY_SENTINEL
207    }
208}
209
210/// Extension-constraint parameter value under the restricted value model
211/// (SPEC §5.7.1): null, booleans, strings, safe integers (|n| ≤ 2^53−1), and
212/// arrays/objects of these. Floats and non-integer numbers are prohibited;
213/// integers beyond the safe range travel as decimal strings. Object keys are
214/// held in a `BTreeMap` so canonical serialization emits them in byte-lex
215/// order (RFC 8785) with no extra sort.
216#[derive(Debug, Clone, PartialEq)]
217pub enum ParamsValue {
218    Null,
219    Bool(bool),
220    Int(i64),
221    Str(String),
222    Array(Vec<ParamsValue>),
223    Object(BTreeMap<String, ParamsValue>),
224}
225
226impl Serialize for ParamsValue {
227    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
228        match self {
229            ParamsValue::Null => serializer.serialize_unit(),
230            ParamsValue::Bool(b) => serializer.serialize_bool(*b),
231            ParamsValue::Int(n) => {
232                if !crate::canonical::wire_int::in_domain(*n) {
233                    return Err(serde::ser::Error::custom(
234                        "params integer exceeds the safe-integer range; carry it as a decimal string",
235                    ));
236                }
237                serializer.serialize_i64(*n)
238            }
239            ParamsValue::Str(s) => serializer.serialize_str(s),
240            ParamsValue::Array(items) => {
241                let mut seq = serializer.serialize_seq(Some(items.len()))?;
242                for item in items {
243                    seq.serialize_element(item)?;
244                }
245                seq.end()
246            }
247            ParamsValue::Object(map) => {
248                // BTreeMap iterates in sorted key order → canonical.
249                let mut m = serializer.serialize_map(Some(map.len()))?;
250                for (k, v) in map {
251                    m.serialize_entry(k, v)?;
252                }
253                m.end()
254            }
255        }
256    }
257}
258
259struct ParamsValueVisitor;
260
261impl<'de> Visitor<'de> for ParamsValueVisitor {
262    type Value = ParamsValue;
263
264    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
265        f.write_str("a restricted params value (null, bool, string, safe integer, array, or object)")
266    }
267
268    fn visit_bool<E: DeError>(self, v: bool) -> Result<Self::Value, E> {
269        Ok(ParamsValue::Bool(v))
270    }
271    fn visit_i64<E: DeError>(self, v: i64) -> Result<Self::Value, E> {
272        Ok(ParamsValue::Int(v))
273    }
274    fn visit_u64<E: DeError>(self, v: u64) -> Result<Self::Value, E> {
275        if v > i64::MAX as u64 {
276            return Err(E::custom(
277                "params integer exceeds the safe-integer range; carry it as a decimal string",
278            ));
279        }
280        Ok(ParamsValue::Int(v as i64))
281    }
282    fn visit_f64<E: DeError>(self, v: f64) -> Result<Self::Value, E> {
283        // JSON numbers reach here as f64. Integral values within the safe
284        // range are wire integers; anything else is outside the value model.
285        if !v.is_finite() || v.fract() != 0.0 {
286            return Err(E::custom(
287                "params values must be safe integers, not floats (carry non-integers as strings)",
288            ));
289        }
290        let max = crate::canonical::wire_int::MAX_SAFE_INTEGER as f64;
291        if v.abs() > max {
292            return Err(E::custom(
293                "params integer exceeds the safe-integer range; carry it as a decimal string",
294            ));
295        }
296        Ok(ParamsValue::Int(v as i64))
297    }
298    fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {
299        Ok(ParamsValue::Str(v.to_string()))
300    }
301    fn visit_string<E: DeError>(self, v: String) -> Result<Self::Value, E> {
302        Ok(ParamsValue::Str(v))
303    }
304    fn visit_none<E: DeError>(self) -> Result<Self::Value, E> {
305        Ok(ParamsValue::Null)
306    }
307    fn visit_unit<E: DeError>(self) -> Result<Self::Value, E> {
308        Ok(ParamsValue::Null)
309    }
310    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
311        let mut out = Vec::new();
312        while let Some(item) = seq.next_element()? {
313            out.push(item);
314        }
315        Ok(ParamsValue::Array(out))
316    }
317    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
318        let mut out: BTreeMap<String, ParamsValue> = BTreeMap::new();
319        while let Some((k, v)) = map.next_entry::<String, ParamsValue>()? {
320            if out.insert(k, v).is_some() {
321                // Duplicate object keys are prohibited (SPEC §5.7.1).
322                return Err(A::Error::custom("params contains a duplicate object key"));
323            }
324        }
325        Ok(ParamsValue::Object(out))
326    }
327}
328
329impl<'de> Deserialize<'de> for ParamsValue {
330    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
331        deserializer.deserialize_any(ParamsValueVisitor)
332    }
333}
334
335/// Reports whether `t` is one of the canonical v1 constraint kinds
336/// (SPEC §5.7.2). `params` is permitted only on non-canonical types.
337pub fn is_canonical_constraint_type(t: &str) -> bool {
338    matches!(
339        t,
340        "geo_circle"
341            | "geo_polygon"
342            | "geo_bbox"
343            | "time_window"
344            | "max_speed_mps"
345            | "max_amount"
346            | "max_rate"
347            | "resource_path"
348    )
349}
350
351// Deserialize helper for `path_prefix`: presence is load-bearing (SPEC
352// §5.7.3). Serde only invokes a `deserialize_with` when the key is PRESENT,
353// so an ABSENT field falls through to `#[serde(default)]` = None (whole
354// resource). A present `null`, present `""`, or non-string value reaches
355// this function and is REJECTED — a malformed path restriction must never
356// silently widen into whole-resource authority.
357fn de_path_prefix<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
358where
359    D: Deserializer<'de>,
360{
361    // `String::deserialize` rejects `null` and non-strings by type.
362    let s = String::deserialize(deserializer)?;
363    if s.is_empty() {
364        return Err(D::Error::custom(
365            "constraint path_prefix must not be empty or null; omit the field to authorize the entire resource",
366        ));
367    }
368    Ok(Some(s))
369}
370
371/// First-class bound on when/where/how much an agent may exercise its scopes.
372///
373/// Wire format is a tagged JSON object. `type` discriminates the kind;
374/// remaining fields are kind-specific. Unknown `type` values MUST be
375/// rejected by conformant verifiers (fail-closed).
376///
377// Fields are declared in alphabetical JSON-key order so serde's default
378// struct serialization order produces canonical bytes that match the Go
379// reference and the other SDKs' lex-sorted output (SPEC §6.2). Do not
380// reorder — cross-SDK byte identicality depends on this.
381//
382// Serialization is custom (see impl Serialize below) to emit the
383// canonical per-kind shape rather than the default "skip if zero"
384// behavior. This closes the v1 zero-as-absence ambiguity: a geo_circle at
385// lat=0, lon=0 now emits lat:0, lon:0 explicitly instead of omitting them.
386// Constraint deserializes THROUGH `ConstraintWire` (serde `try_from`) so
387// cross-field wire invariants are enforced at the deserialize boundary — for
388// direct `Constraint` decoding and for cert/bundle decoding alike, matching
389// Go's `Constraint.UnmarshalJSON`. A `resource_id` on a `resource_path` that
390// is absent, empty, null, or non-string is rejected here; strict wire
391// acceptance does not differ by SDK. (`null`/non-string already fail as type
392// errors against the `String` field; the `try_from` also closes absent and
393// empty.)
394#[derive(Debug, Clone, Default, Deserialize)]
395#[serde(deny_unknown_fields)]
396struct ConstraintWire {
397    #[serde(default, deserialize_with = "crate::canonical::wire_int::deserialize")]
398    count: i64,
399    #[serde(default)]
400    currency: String,
401    #[serde(default)]
402    end: String,
403    #[serde(default)]
404    lat: f64,
405    #[serde(default)]
406    lon: f64,
407    #[serde(default)]
408    max_alt_m: f64,
409    #[serde(default)]
410    max_amount: f64,
411    #[serde(default)]
412    max_lat: f64,
413    #[serde(default)]
414    max_lon: f64,
415    #[serde(default)]
416    max_mps: f64,
417    #[serde(default)]
418    min_alt_m: f64,
419    #[serde(default)]
420    min_lat: f64,
421    #[serde(default)]
422    min_lon: f64,
423    #[serde(default)]
424    params: Option<BTreeMap<String, ParamsValue>>,
425    #[serde(default, deserialize_with = "de_path_prefix")]
426    path_prefix: Option<String>,
427    #[serde(default)]
428    points: Vec<[f64; 2]>,
429    #[serde(default)]
430    radius_m: f64,
431    #[serde(default)]
432    resource_id: String,
433    #[serde(default)]
434    start: String,
435    #[serde(default)]
436    tz: String,
437    #[serde(rename = "type")]
438    kind: String,
439    #[serde(default, deserialize_with = "crate::canonical::wire_int::deserialize")]
440    window_s: i64,
441}
442
443impl TryFrom<ConstraintWire> for Constraint {
444    type Error = String;
445    fn try_from(w: ConstraintWire) -> Result<Self, Self::Error> {
446        if w.kind == "resource_path" && w.resource_id.is_empty() {
447            return Err(
448                "resource_path constraint requires a non-empty resource_id".into(),
449            );
450        }
451        Ok(Constraint {
452            count: w.count,
453            currency: w.currency,
454            end: w.end,
455            lat: w.lat,
456            lon: w.lon,
457            max_alt_m: w.max_alt_m,
458            max_amount: w.max_amount,
459            max_lat: w.max_lat,
460            max_lon: w.max_lon,
461            max_mps: w.max_mps,
462            min_alt_m: w.min_alt_m,
463            min_lat: w.min_lat,
464            min_lon: w.min_lon,
465            params: w.params,
466            path_prefix: w.path_prefix,
467            points: w.points,
468            radius_m: w.radius_m,
469            resource_id: w.resource_id,
470            start: w.start,
471            tz: w.tz,
472            kind: w.kind,
473            window_s: w.window_s,
474        })
475    }
476}
477
478#[derive(Debug, Clone, Default, Deserialize)]
479#[serde(try_from = "ConstraintWire")]
480pub struct Constraint {
481    pub count: i64,
482    pub currency: String,
483    pub end: String,
484    pub lat: f64,
485    pub lon: f64,
486    pub max_alt_m: f64,
487    pub max_amount: f64,
488    pub max_lat: f64,
489    pub max_lon: f64,
490    pub max_mps: f64,
491    pub min_alt_m: f64,
492    pub min_lat: f64,
493    pub min_lon: f64,
494    /// Extension-constraint parameters (SPEC §5.7.1). Permitted ONLY on
495    /// non-canonical types under the restricted value model. Canonical types
496    /// carrying params are rejected at encode/issue/decode.
497    pub params: Option<BTreeMap<String, ParamsValue>>,
498    /// Optionally narrows a `resource_path` constraint to a path at or below
499    /// it under segment-boundary matching (SPEC §5.7.3). Absence (`None`) —
500    /// never the empty string — is the sole encoding of "entire resource".
501    pub path_prefix: Option<String>,
502    pub points: Vec<[f64; 2]>,
503    pub radius_m: f64,
504    /// Names the resource a `resource_path` constraint binds to. Opaque
505    /// UTF-8; compared byte-for-byte, never dereferenced or normalized.
506    pub resource_id: String,
507    pub start: String,
508    pub tz: String,
509    pub kind: String,
510    pub window_s: i64,
511}
512
513// Custom Serialize for Constraint — emits the canonical per-kind shape.
514// Mirrors Go's Constraint.MarshalJSON and TS canonicalConstraintDict.
515// Keys are emitted in alphabetical order, matching the other SDKs.
516impl Serialize for Constraint {
517    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
518        // params is permitted only on non-canonical types (SPEC §5.7.1).
519        if self.params.is_some() && is_canonical_constraint_type(&self.kind) {
520            return Err(serde::ser::Error::custom(format!(
521                "canonical constraint type \"{}\" must not carry params",
522                self.kind
523            )));
524        }
525        // Count fields up front so serde's map writer knows the length.
526        // Doing this the verbose way rather than with serialize_struct
527        // because the per-kind shape is dynamic, not a fixed struct.
528        let entries: Vec<(&'static str, FieldValue)> = match self.kind.as_str() {
529            "geo_circle" => vec![
530                ("lat", FieldValue::F64(self.lat)),
531                ("lon", FieldValue::F64(self.lon)),
532                ("radius_m", FieldValue::F64(self.radius_m)),
533                ("type", FieldValue::Str(self.kind.clone())),
534            ],
535            "geo_polygon" => vec![
536                ("points", FieldValue::Points(self.points.clone())),
537                ("type", FieldValue::Str(self.kind.clone())),
538            ],
539            "geo_bbox" => {
540                let mut v = vec![
541                    ("max_lat", FieldValue::F64(self.max_lat)),
542                    ("max_lon", FieldValue::F64(self.max_lon)),
543                    ("min_lat", FieldValue::F64(self.min_lat)),
544                    ("min_lon", FieldValue::F64(self.min_lon)),
545                ];
546                if self.min_alt_m != 0.0 || self.max_alt_m != 0.0 {
547                    // Insert altitude pair alphabetically: max_alt_m < max_lat.
548                    v.insert(0, ("max_alt_m", FieldValue::F64(self.max_alt_m)));
549                    // min_alt_m < min_lat → insert after max_lon (index 2).
550                    v.insert(3, ("min_alt_m", FieldValue::F64(self.min_alt_m)));
551                }
552                v.push(("type", FieldValue::Str(self.kind.clone())));
553                v
554            }
555            "time_window" => vec![
556                ("end", FieldValue::Str(self.end.clone())),
557                ("start", FieldValue::Str(self.start.clone())),
558                ("type", FieldValue::Str(self.kind.clone())),
559                ("tz", FieldValue::Str(self.tz.clone())),
560            ],
561            "max_speed_mps" => vec![
562                ("max_mps", FieldValue::F64(self.max_mps)),
563                ("type", FieldValue::Str(self.kind.clone())),
564            ],
565            "max_amount" => vec![
566                ("currency", FieldValue::Str(self.currency.clone())),
567                ("max_amount", FieldValue::F64(self.max_amount)),
568                ("type", FieldValue::Str(self.kind.clone())),
569            ],
570            "max_rate" => vec![
571                ("count", FieldValue::I64(self.count)),
572                ("type", FieldValue::Str(self.kind.clone())),
573                ("window_s", FieldValue::I64(self.window_s)),
574            ],
575            "resource_path" => {
576                // keys: path_prefix (only when present), resource_id, type.
577                // Absence — not "" — is the sole encoding of whole-resource
578                // authorization (SPEC §5.7.3).
579                if self.resource_id.is_empty() {
580                    return Err(serde::ser::Error::custom(
581                        "resource_path constraint requires a non-empty resource_id",
582                    ));
583                }
584                let mut v = Vec::new();
585                if let Some(prefix) = &self.path_prefix {
586                    v.push(("path_prefix", FieldValue::Str(prefix.clone())));
587                }
588                v.push(("resource_id", FieldValue::Str(self.resource_id.clone())));
589                v.push(("type", FieldValue::Str(self.kind.clone())));
590                v
591            }
592            // Extension kind — emit params (when present) plus the tag
593            // (SPEC §5.7.1). "params" sorts before "type". Verifier without a
594            // registered evaluator returns constraint_unknown on this shape.
595            _ => {
596                let mut v = Vec::new();
597                if let Some(params) = &self.params {
598                    v.push(("params", FieldValue::Params(params.clone())));
599                }
600                v.push(("type", FieldValue::Str(self.kind.clone())));
601                v
602            }
603        };
604        let mut m = serializer.serialize_map(Some(entries.len()))?;
605        for (k, v) in entries {
606            match v {
607                FieldValue::F64(x) => m.serialize_entry(k, &x)?,
608                FieldValue::I64(x) => {
609                    // Encoder side of the wire integer domain (SPEC §6.2).
610                    if !crate::canonical::wire_int::in_domain(x) {
611                        return Err(serde::ser::Error::custom(
612                            "integer outside the safe-integer range [-(2^53-1), 2^53-1]",
613                        ));
614                    }
615                    m.serialize_entry(k, &x)?
616                }
617                FieldValue::Str(x) => m.serialize_entry(k, &x)?,
618                FieldValue::Points(x) => m.serialize_entry(k, &x)?,
619                FieldValue::Params(x) => m.serialize_entry(k, &x)?,
620            }
621        }
622        m.end()
623    }
624}
625
626// Small sum type so the serialize impl can carry mixed-type values in one
627// vector. Kept private to this module.
628enum FieldValue {
629    F64(f64),
630    I64(i64),
631    Str(String),
632    Points(Vec<[f64; 2]>),
633    Params(BTreeMap<String, ParamsValue>),
634}
635
636/// Callback answering "how many invocations of this cert in this window?"
637/// — (cert_id, window_s) -> count. Used by rate-limit constraints.
638/// A negative return means the count is unavailable; `max_rate` then fails
639/// closed with `constraint_unverifiable`.
640pub type InvocationCounter<'a> = Box<dyn Fn(&str, i64) -> i64 + 'a>;
641
642/// Application-supplied inputs for evaluating first-class constraints.
643/// A cert bearing a constraint whose required context field is absent will
644/// be rejected with `constraint_unverifiable` (fail-closed).
645#[derive(Default)]
646pub struct VerifierContext<'a> {
647    pub current_lat: Option<f64>,
648    pub current_lon: Option<f64>,
649    pub current_alt_m: Option<f64>,
650    pub current_speed_mps: Option<f64>,
651    pub requested_amount: Option<f64>,
652    pub requested_currency: Option<String>,
653    /// (cert_id, window_s) -> invocation count
654    pub invocations_in_window: Option<InvocationCounter<'a>>,
655    /// The resource the operation targets (SPEC §5.16). Required by
656    /// `resource_path`; `None` (or empty) → `constraint_unverifiable`.
657    /// Compared byte-exactly against the constraint's `resource_id`.
658    pub requested_resource_id: Option<String>,
659    /// The path the operation targets, following the logical path model of
660    /// §5.7.3. Callers MUST apply every decoding/normalization step (URL
661    /// decode, Unicode NFC, case folding, separator conversion) BEFORE
662    /// populating this; the verifier never transforms it.
663    pub requested_path: Option<String>,
664}
665
666/// Proof an agent presents to a verifier.
667///
668/// v1.1 optional stream binding: when `stream_id` and `stream_seq` are set,
669/// the bundle is "stream-bound" — it belongs to an ordered sequence of
670/// interactions sharing a stream_id. Both are signed into the challenge bytes
671/// (SPEC §6.4.2) so replay, reorder, or omission within the stream invalidate
672/// the signature.
673#[derive(Debug, Clone, Serialize, Deserialize)]
674#[serde(deny_unknown_fields)]
675pub struct ProofBundle {
676    pub agent_id: String,
677    pub agent_pub_key: HybridPublicKey,
678    pub delegations: Vec<DelegationCert>,
679    #[serde(with = "crate::canonical::base64_bytes")]
680    pub challenge: Vec<u8>,
681    #[serde(
682        serialize_with = "crate::canonical::wire_int::serialize",
683        deserialize_with = "crate::canonical::wire_int::deserialize"
684    )]
685    pub challenge_at: i64,
686    pub challenge_sig: HybridSignature,
687    #[serde(
688        default,
689        skip_serializing_if = "Vec::is_empty",
690        with = "crate::canonical::base64_bytes"
691    )]
692    pub session_context: Vec<u8>,
693    #[serde(
694        default,
695        skip_serializing_if = "Vec::is_empty",
696        with = "crate::canonical::base64_bytes"
697    )]
698    pub stream_id: Vec<u8>,
699    #[serde(
700        default,
701        skip_serializing_if = "is_zero_i64",
702        serialize_with = "crate::canonical::wire_int::serialize",
703        deserialize_with = "crate::canonical::wire_int::deserialize"
704    )]
705    pub stream_seq: i64,
706}
707
708fn is_zero_i64(v: &i64) -> bool {
709    *v == 0
710}
711
712/// Identity status values in a VerifyResult (SPEC §5.9). Granular failure
713/// statuses (scope_denied, constraint_denied, etc) let callers route on the
714/// enum directly — they do not have to parse error_reason text.
715#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
716#[serde(rename_all = "snake_case")]
717pub enum IdentityStatus {
718    VerifiedHuman,
719    AuthorizedAgent,
720    Expired,
721    Revoked,
722    ScopeDenied,
723    ConstraintDenied,
724    ConstraintUnverifiable,
725    ConstraintUnknown,
726    DelegationNotAuthorized,
727    /// A cert in the chain grants a scope that is not canonical, not a
728    /// wildcard, and not a `custom:` extension (SPEC §9). Fail-closed —
729    /// vocabulary outside the protocol is rejected as malformed rather than
730    /// silently intersected.
731    InvalidScope,
732    Invalid,
733    Unauthorized,
734}
735
736impl IdentityStatus {
737    pub fn as_str(&self) -> &'static str {
738        match self {
739            Self::VerifiedHuman => "verified_human",
740            Self::AuthorizedAgent => "authorized_agent",
741            Self::Expired => "expired",
742            Self::Revoked => "revoked",
743            Self::ScopeDenied => "scope_denied",
744            Self::ConstraintDenied => "constraint_denied",
745            Self::ConstraintUnverifiable => "constraint_unverifiable",
746            Self::ConstraintUnknown => "constraint_unknown",
747            Self::DelegationNotAuthorized => "delegation_not_authorized",
748            Self::InvalidScope => "invalid_scope",
749            Self::Invalid => "invalid",
750            Self::Unauthorized => "unauthorized",
751        }
752    }
753
754    /// Parse the snake_case wire form back into the enum. Returns None if
755    /// the input is not a known status; callers should fail-closed.
756    pub fn from_wire(s: &str) -> Option<Self> {
757        Some(match s {
758            "verified_human" => Self::VerifiedHuman,
759            "authorized_agent" => Self::AuthorizedAgent,
760            "expired" => Self::Expired,
761            "revoked" => Self::Revoked,
762            "scope_denied" => Self::ScopeDenied,
763            "constraint_denied" => Self::ConstraintDenied,
764            "constraint_unverifiable" => Self::ConstraintUnverifiable,
765            "constraint_unknown" => Self::ConstraintUnknown,
766            "delegation_not_authorized" => Self::DelegationNotAuthorized,
767            "invalid_scope" => Self::InvalidScope,
768            "invalid" => Self::Invalid,
769            "unauthorized" => Self::Unauthorized,
770            _ => return None,
771        })
772    }
773}
774
775/// Deterministic output of `verify_bundle`. Always check `valid` first.
776#[derive(Debug, Clone, Serialize, Deserialize)]
777pub struct VerifyResult {
778    pub valid: bool,
779    pub identity_status: IdentityStatus,
780    #[serde(skip_serializing_if = "String::is_empty", default)]
781    pub human_id: String,
782    #[serde(skip_serializing_if = "String::is_empty", default)]
783    pub agent_id: String,
784    #[serde(skip_serializing_if = "String::is_empty", default)]
785    pub agent_name: String,
786    #[serde(skip_serializing_if = "String::is_empty", default)]
787    pub agent_type: String,
788    #[serde(skip_serializing_if = "Vec::is_empty", default)]
789    pub granted_scope: Vec<String>,
790    #[serde(skip_serializing_if = "String::is_empty", default)]
791    pub error_reason: String,
792    /// Resolved external-identity binding for `human_id`, populated when
793    /// `VerifyOptions.anchor_resolver` is set on a successful verification.
794    /// Lets downstream `AuditProvider`s record an unforgeable chain from
795    /// verification event → identity attestation. (SPEC §17.8)
796    #[serde(skip_serializing_if = "Option::is_none", default)]
797    pub anchor: Option<Anchor>,
798}
799
800/// Signed list of revoked cert IDs, served by the issuer.
801#[derive(Debug, Clone, Serialize, Deserialize)]
802pub struct RevocationList {
803    pub issuer_id: String,
804    pub updated_at: i64,
805    pub revoked_certs: Vec<String>,
806    pub signature: HybridSignature,
807}
808
809/// v1.1 signed push notification of newly revoked cert IDs.
810#[derive(Debug, Clone, Serialize, Deserialize)]
811pub struct RevocationPush {
812    pub issuer_id: String,
813    pub seq_no: i64,
814    pub entries: Vec<String>,
815    pub pushed_at: i64,
816    pub signature: HybridSignature,
817}
818
819/// v1.1 element in a hash-chain append-only witness log.
820#[derive(Debug, Clone, Serialize, Deserialize)]
821pub struct WitnessEntry {
822    #[serde(with = "crate::canonical::base64_bytes")]
823    pub prev_hash: Vec<u8>,
824    #[serde(with = "crate::canonical::base64_bytes")]
825    pub entry_data: Vec<u8>,
826    pub timestamp: i64,
827    pub witness_id: String,
828    pub signature: HybridSignature,
829}
830
831/// v1.1 verifier-issued credential that caches a verified chain. MAC =
832/// HMAC-SHA256(session_secret, session_token_sign_bytes(token)). The session
833/// secret is private to the verifier and never leaves its trust boundary.
834#[derive(Debug, Clone, Serialize, Deserialize)]
835#[serde(deny_unknown_fields)]
836pub struct SessionToken {
837    pub version: i32,
838    pub session_id: String,
839    pub agent_id: String,
840    pub agent_pub_key: HybridPublicKey,
841    pub human_id: String,
842    pub granted_scope: Vec<String>,
843    #[serde(
844        serialize_with = "crate::canonical::wire_int::serialize",
845        deserialize_with = "crate::canonical::wire_int::deserialize"
846    )]
847    pub issued_at: i64,
848    #[serde(
849        serialize_with = "crate::canonical::wire_int::serialize",
850        deserialize_with = "crate::canonical::wire_int::deserialize"
851    )]
852    pub valid_until: i64,
853    #[serde(with = "crate::canonical::base64_bytes")]
854    pub chain_hash: Vec<u8>,
855    #[serde(with = "crate::canonical::base64_bytes")]
856    pub mac: Vec<u8>,
857}
858
859/// v1.1 canonical envelope for a multi-party, atomic transaction.
860#[derive(Debug, Clone, Serialize, Deserialize)]
861pub struct TransactionReceipt {
862    pub version: i32,
863    pub transaction_id: String,
864    pub created_at: i64,
865    pub terms_schema_uri: String,
866    #[serde(with = "crate::canonical::base64_bytes")]
867    pub terms_canonical_json: Vec<u8>,
868    pub parties: Vec<ReceiptParty>,
869    pub party_signatures: Vec<ReceiptPartySignature>,
870}
871
872/// One party to a TransactionReceipt.
873#[derive(Debug, Clone, Serialize, Deserialize)]
874pub struct ReceiptParty {
875    pub party_id: String,
876    pub role: String,
877    pub agent_id: String,
878    pub agent_pub_key: HybridPublicKey,
879    pub proof_bundle: ProofBundle,
880}
881
882/// Hybrid signature by a party over the canonical receipt signable.
883#[derive(Debug, Clone, Serialize, Deserialize)]
884pub struct ReceiptPartySignature {
885    pub party_id: String,
886    pub signature: HybridSignature,
887}
888
889/// Outcome of verify_transaction_receipt.
890pub struct TransactionReceiptResult {
891    pub valid: bool,
892    pub error_reason: String,
893    pub party_results: Vec<VerifyResult>,
894}
895
896/// Signed continuity statement from an old root key to a new root key.
897#[derive(Debug, Clone, Serialize, Deserialize)]
898pub struct KeyRotationStatement {
899    pub version: i32,
900    pub old_id: String,
901    pub old_pub_key: HybridPublicKey,
902    pub new_id: String,
903    pub new_pub_key: HybridPublicKey,
904    pub rotated_at: i64,
905    pub reason: String,
906    pub signature_old: HybridSignature,
907    pub signature_new: HybridSignature,
908}
909
910/// Verifier state tracked per stream_id for v1.1 stream-bound bundles.
911///
912/// `last_seen_seq` is the highest sequence number the verifier has already
913/// accepted for `stream_id`; zero means no turns accepted yet, so the first
914/// valid bundle must carry `stream_seq == 1`.
915#[derive(Debug, Clone, Default)]
916pub struct StreamContext {
917    pub stream_id: Vec<u8>,
918    pub last_seen_seq: i64,
919}
920
921/// Pluggable provider for revocation state (SPEC §17.1).
922///
923/// Implementations return `Ok(true)` for revoked, `Ok(false)` for live, and
924/// `Err(...)` to surface a lookup failure. A provider error is fail-closed:
925/// the bundle is rejected with `error_reason="revocation_error: ..."` —
926/// SDKs MUST NOT treat a lookup failure as "not revoked." On the verifier's
927/// hot path; implementations should be O(1) at call time.
928pub trait RevocationProvider {
929    fn is_revoked(&self, cert_id: &str) -> Result<bool, String>;
930}
931
932/// Pluggable evaluator for verifier-local policy (SPEC §17.2).
933///
934/// Evaluated AFTER all cryptographic, temporal, revocation, constraint, and
935/// scope-intersection checks pass. `Ok(true)` allows; `Ok(false)` denies with
936/// `scope_denied`; `Err(...)` fails closed with `policy_error`.
937pub trait PolicyProvider {
938    fn evaluate_policy(
939        &self,
940        bundle: &ProofBundle,
941        context: &VerifierContext,
942    ) -> Result<bool, String>;
943}
944
945/// Pluggable audit-receipt persistence (SPEC §17.3).
946///
947/// Invoked on every `verify_bundle` call (success AND failure). Errors are
948/// swallowed — auditing MUST NOT alter the verdict.
949pub trait AuditProvider {
950    fn log_verification(&self, result: &VerifyResult, bundle: &ProofBundle);
951}
952
953/// Pluggable evaluator for extension constraint types (SPEC §17.7).
954///
955/// Built-in types (geo_*, time_window, max_*) are evaluated by the SDK
956/// directly; an evaluator is consulted only for types the SDK does not
957/// natively understand. Returning `Ok(true)` allows; `Ok(false)` denies as
958/// `constraint_denied`; `Err("constraint_unverifiable: ...")` routes to
959/// `constraint_unverifiable`; other `Err(...)` denies with the wrapped
960/// reason.
961pub trait ConstraintEvaluator {
962    fn evaluate(
963        &self,
964        constraint: &Constraint,
965        cert_id: &str,
966        context: &VerifierContext,
967        now: i64,
968    ) -> Result<(), String>;
969}
970
971/// Resolves a verified `human_id` to its external-identity binding
972/// (SPEC §17.8). Errors are non-fatal: the verifier MUST NOT fail the bundle
973/// because the resolver errored — it silently leaves `VerifyResult.anchor`
974/// `None` and continues.
975pub trait AnchorResolver {
976    fn resolve_anchor(&self, human_id: &str) -> Result<Option<Anchor>, String>;
977}
978
979/// HMAC-bound cached policy decision (SPEC §17.6). The policy equivalent
980/// of `SessionToken`: issued once by a commercial policy backend, accepted
981/// locally by the verifier for the rest of `valid_until` without re-calling
982/// the backend.
983#[derive(Debug, Clone, Serialize, Deserialize)]
984pub struct PolicyVerdict {
985    pub version: i32,
986    pub verdict_id: String,
987    pub agent_id: String,
988    pub scope: String,
989    pub allow: bool,
990    #[serde(with = "crate::canonical::base64_bytes")]
991    pub context_hash: Vec<u8>, // 32 bytes
992    pub issued_at: i64,
993    pub valid_until: i64,
994    #[serde(with = "crate::canonical::base64_bytes")]
995    pub mac: Vec<u8>, // 32 bytes — HMAC-SHA256
996}
997
998/// Verifier-signed attestation that a specific ProofBundle was verified at
999/// a specific moment with a specific outcome (SPEC §17.5).
1000///
1001/// Receipts chain by `prev_hash` (SHA-256 of previous receipt's canonical
1002/// signable bytes) so a missing or backdated entry is detectable. Genesis
1003/// uses 32 zero bytes.
1004#[derive(Debug, Clone, Serialize, Deserialize)]
1005pub struct VerificationReceipt {
1006    pub version: i32,
1007    pub verifier_id: String,
1008    pub verifier_pub: HybridPublicKey,
1009    #[serde(with = "crate::canonical::base64_bytes")]
1010    pub bundle_hash: Vec<u8>, // 32 bytes
1011    pub decision: String,
1012    #[serde(skip_serializing_if = "String::is_empty", default)]
1013    pub human_id: String,
1014    #[serde(skip_serializing_if = "String::is_empty", default)]
1015    pub agent_id: String,
1016    #[serde(skip_serializing_if = "Vec::is_empty", default)]
1017    pub granted_scope: Vec<String>,
1018    #[serde(skip_serializing_if = "String::is_empty", default)]
1019    pub error_reason: String,
1020    pub verified_at: i64,
1021    #[serde(with = "crate::canonical::base64_bytes")]
1022    pub prev_hash: Vec<u8>, // 32 bytes; zeros for genesis
1023    pub signature: HybridSignature,
1024}
1025
1026/// Options passed to `verify_bundle`.
1027pub struct VerifyOptions<'a> {
1028    /// Required scope; empty string skips scope checking.
1029    pub required_scope: String,
1030    /// Legacy v1 revocation closure.
1031    ///
1032    /// **Deprecated:** Use `revocation` (SPEC §17.1) instead. The closure
1033    /// has no way to surface lookup failures; `revocation` returns
1034    /// `Result<bool, String>` and fails closed on error. Slated for removal
1035    /// in v1.0.0-beta.1. When both fields are set, `revocation` wins.
1036    #[deprecated(since = "1.0.0-alpha.7", note = "use `revocation` (SPEC §17.1) instead")]
1037    // Slated for removal in v1.0.0-beta.1 — not worth a public type alias.
1038    #[allow(clippy::type_complexity)]
1039    pub is_revoked: Option<Box<dyn Fn(&str) -> bool + 'a>>,
1040    /// Pluggable revocation provider (SPEC §17.1). Takes precedence over
1041    /// `is_revoked`. A provider error fails the bundle as `revocation_error`.
1042    pub revocation: Option<Box<dyn RevocationProvider + 'a>>,
1043    /// Force a fresh revocation check for high-stakes endpoints. The SDK
1044    /// cannot fetch revocation state itself; callers must provide is_revoked
1045    /// or a revocation provider when this is true.
1046    pub force_revocation_check: bool,
1047    /// Override current time (unix seconds); None = SystemTime::now().
1048    pub now: Option<i64>,
1049    /// Optional verifier-reconstructed 32-byte v1.1 session context.
1050    pub session_context: Vec<u8>,
1051    /// Optional verifier-tracked v1.1 stream context.
1052    pub stream: Option<StreamContext>,
1053    /// Application inputs for evaluating first-class constraints. Default is
1054    /// empty; constraint-bearing certs fail closed if required context is
1055    /// absent.
1056    pub context: VerifierContext<'a>,
1057    /// Advanced verifier-local policy evaluator (SPEC §17.2). Evaluated after
1058    /// all cryptographic checks pass. Deny → `scope_denied`; provider error →
1059    /// `policy_error`.
1060    pub policy: Option<Box<dyn PolicyProvider + 'a>>,
1061    /// Audit-receipt persistence hook (SPEC §17.3). Invoked on every Verify
1062    /// (success AND failure). Provider errors are swallowed — auditing cannot
1063    /// alter the verdict.
1064    pub audit: Option<Box<dyn AuditProvider + 'a>>,
1065    /// Per-Verify registry of extension constraint evaluators (SPEC §17.7).
1066    /// Built-in types are evaluated by the SDK directly; the registry is
1067    /// only consulted for unknown types.
1068    pub constraint_evaluators:
1069        Option<alloc::collections::BTreeMap<String, Box<dyn ConstraintEvaluator + 'a>>>,
1070    /// Fast-path cached policy decision (SPEC §17.6). When present and
1071    /// valid (MAC matches `policy_secret`, within window, agent/scope/
1072    /// context_hash matches), the verifier skips the live `policy` hook.
1073    /// Stale verdicts fall back to live policy.
1074    pub policy_verdict: Option<PolicyVerdict>,
1075    /// HMAC secret used to verify `policy_verdict.mac`.
1076    pub policy_secret: Option<Vec<u8>>,
1077    /// Anchor resolver (SPEC §17.8). When set on a Valid=true verification,
1078    /// the verifier populates `VerifyResult.anchor`. Resolver errors are
1079    /// non-fatal.
1080    pub anchor_resolver: Option<Box<dyn AnchorResolver + 'a>>,
1081    /// Single-use tracking for verifier-issued challenges (SPEC §10). When
1082    /// set, the store is consulted (without consuming) before any signature
1083    /// work, and the challenge is atomically consumed after the structural,
1084    /// chain, and challenge-signature checks pass — before authorization
1085    /// evaluation. A forged or malformed presentation never consumes a
1086    /// challenge; a cryptographically valid presentation does, even if
1087    /// authorization is subsequently denied. When a store is in use,
1088    /// constraint evaluation is deferred until after consumption. The
1089    /// store's session binding is checked against `session_context`.
1090    pub challenge_store: Option<Box<dyn crate::challenge_store::ChallengeStore + 'a>>,
1091}
1092
1093// Not derived: this manual impl exists to isolate the #[allow(deprecated)]
1094// initialization of `is_revoked` to a single construction site. Deriving
1095// would spread the deprecation suppression to the whole struct.
1096#[allow(clippy::derivable_impls)]
1097impl<'a> Default for VerifyOptions<'a> {
1098    fn default() -> Self {
1099        // The Default impl must initialize the deprecated field for backwards
1100        // compatibility. Suppressing the warning is intentional and isolated
1101        // to this single construction site.
1102        #[allow(deprecated)]
1103        Self {
1104            required_scope: String::new(),
1105            is_revoked: None,
1106            revocation: None,
1107            force_revocation_check: false,
1108            now: None,
1109            session_context: Vec::new(),
1110            stream: None,
1111            context: VerifierContext::default(),
1112            policy: None,
1113            audit: None,
1114            constraint_evaluators: None,
1115            policy_verdict: None,
1116            policy_secret: None,
1117            anchor_resolver: None,
1118            challenge_store: None,
1119        }
1120    }
1121}