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