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, string::String, vec, vec::Vec};
8
9use serde::ser::{SerializeMap, Serializer};
10use serde::{Deserialize, Serialize};
11
12pub const PROTOCOL_VERSION: i32 = 1;
13
14/// The `expires_at` value that means "no expiry (until revoked)":
15/// 4070908799 = 2099-12-31 23:59:59 UTC. `DelegationCert.expires_at` is a
16/// required i64 with no null representation, so open-ended delegations carry
17/// this sentinel in the signed bytes. Conformant implementations MUST treat
18/// a cert with `expires_at == NO_EXPIRY_SENTINEL` as "no expiry (until
19/// revoked)" in display and policy evaluation — NOT as a literal 2099
20/// expiry. Verification is unchanged: the sentinel is a future timestamp, so
21/// the temporal check passes; revocation is the sole termination mechanism
22/// for such certs. See SPEC §5.7.
23pub const NO_EXPIRY_SENTINEL: i64 = 4070908799;
24pub const MAX_DELEGATION_CHAIN_DEPTH: usize = 3;
25pub const CHALLENGE_WINDOW_SECONDS: i64 = 300;
26
27pub const ED25519_PUBLIC_KEY_SIZE: usize = 32;
28pub const ED25519_SIGNATURE_SIZE: usize = 64;
29pub const MLDSA65_PUBLIC_KEY_SIZE: usize = 1952;
30pub const MLDSA65_SIGNATURE_SIZE: usize = 3309;
31
32/// Ed25519 + ML-DSA-65 public key pair.
33///
34/// Canonical JSON form (keys in lex order):
35/// `{"ed25519":"<base64-32-bytes>","ml_dsa_65":"<base64-1952-bytes>"}`
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct HybridPublicKey {
39    #[serde(with = "crate::canonical::base64_bytes")]
40    pub ed25519: Vec<u8>, // 32 bytes
41    #[serde(with = "crate::canonical::base64_bytes")]
42    pub ml_dsa_65: Vec<u8>, // 1952 bytes
43}
44
45/// Ed25519 + ML-DSA-65 signature pair over the same canonical bytes.
46///
47/// Both components MUST verify for the signature to be accepted.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct HybridSignature {
51    #[serde(with = "crate::canonical::base64_bytes")]
52    pub ed25519: Vec<u8>, // 64 bytes
53    #[serde(with = "crate::canonical::base64_bytes")]
54    pub ml_dsa_65: Vec<u8>, // 3309 bytes
55}
56
57/// Both component private keys. Never serialized to the wire.
58#[derive(Debug, Clone)]
59pub struct HybridPrivateKey {
60    pub ed25519: Vec<u8>,   // 32-byte seed
61    pub ml_dsa_65: Vec<u8>, // ML-DSA-65 secret key bytes
62}
63
64/// Optional external binding for higher-assurance identity.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct Anchor {
67    #[serde(rename = "type")]
68    pub anchor_type: String,
69    pub provider: String,
70    pub reference: String,
71    pub verified_at: i64,
72}
73
74/// Master identity for a human (or tenant admin).
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct HumanRoot {
77    pub id: String,
78    pub public_key: HybridPublicKey,
79    pub created_at: i64,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub anchors: Option<Vec<Anchor>>,
82}
83
84/// An AI agent's identity.
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct AgentIdentity {
87    pub id: String,
88    pub public_key: HybridPublicKey,
89    pub name: String,
90    pub agent_type: String,
91    pub created_at: i64,
92}
93
94/// Signed authorization from a principal to an agent.
95///
96/// `scope` answers *what* the agent may do. `constraints` answer *where /
97/// when / how much* — first-class bounds evaluated at verify time against a
98/// caller-supplied VerifierContext.
99#[derive(Debug, Clone, Serialize, Deserialize)]
100#[serde(deny_unknown_fields)]
101pub struct DelegationCert {
102    pub cert_id: String,
103    pub version: i32,
104    pub issuer_id: String,
105    pub issuer_pub_key: HybridPublicKey,
106    pub subject_id: String,
107    pub subject_pub_key: HybridPublicKey,
108    pub scope: Vec<String>,
109    /// Always present in canonical JSON (`[]` when empty) so canonical bytes
110    /// are deterministic across issuers.
111    #[serde(default)]
112    pub constraints: Vec<Constraint>,
113    #[serde(
114        serialize_with = "crate::canonical::wire_int::serialize",
115        deserialize_with = "crate::canonical::wire_int::deserialize"
116    )]
117    pub issued_at: i64,
118    #[serde(
119        serialize_with = "crate::canonical::wire_int::serialize",
120        deserialize_with = "crate::canonical::wire_int::deserialize"
121    )]
122    pub expires_at: i64,
123    pub signature: HybridSignature,
124}
125
126impl DelegationCert {
127    /// Reports whether the cert carries [`NO_EXPIRY_SENTINEL`], meaning "no
128    /// expiry (until revoked)". Callers rendering expiry to users or applying
129    /// lifetime policy caps MUST branch on this rather than treating the
130    /// sentinel as a real 2099 timestamp.
131    pub fn is_no_expiry(&self) -> bool {
132        self.expires_at == NO_EXPIRY_SENTINEL
133    }
134}
135
136/// First-class bound on when/where/how much an agent may exercise its scopes.
137///
138/// Wire format is a tagged JSON object. `type` discriminates the kind;
139/// remaining fields are kind-specific. Unknown `type` values MUST be
140/// rejected by conformant verifiers (fail-closed).
141///
142// Fields are declared in alphabetical JSON-key order so serde's default
143// struct serialization order produces canonical bytes that match the Go
144// reference and the other SDKs' lex-sorted output (SPEC §6.2). Do not
145// reorder — cross-SDK byte identicality depends on this.
146//
147// Serialization is custom (see impl Serialize below) to emit the
148// canonical per-kind shape rather than the default "skip if zero"
149// behavior. This closes the v1 zero-as-absence ambiguity: a geo_circle at
150// lat=0, lon=0 now emits lat:0, lon:0 explicitly instead of omitting them.
151#[derive(Debug, Clone, Default, Deserialize)]
152#[serde(deny_unknown_fields)]
153pub struct Constraint {
154    #[serde(
155        default,
156        serialize_with = "crate::canonical::wire_int::serialize",
157        deserialize_with = "crate::canonical::wire_int::deserialize"
158    )]
159    pub count: i64,
160    #[serde(default)]
161    pub currency: String,
162    #[serde(default)]
163    pub end: String,
164    #[serde(default)]
165    pub lat: f64,
166    #[serde(default)]
167    pub lon: f64,
168    #[serde(default)]
169    pub max_alt_m: f64,
170    #[serde(default)]
171    pub max_amount: f64,
172    #[serde(default)]
173    pub max_lat: f64,
174    #[serde(default)]
175    pub max_lon: f64,
176    #[serde(default)]
177    pub max_mps: f64,
178    #[serde(default)]
179    pub min_alt_m: f64,
180    #[serde(default)]
181    pub min_lat: f64,
182    #[serde(default)]
183    pub min_lon: f64,
184    #[serde(default)]
185    pub points: Vec<[f64; 2]>,
186    #[serde(default)]
187    pub radius_m: f64,
188    #[serde(default)]
189    pub start: String,
190    #[serde(default)]
191    pub tz: String,
192    #[serde(rename = "type")]
193    pub kind: String,
194    #[serde(
195        default,
196        serialize_with = "crate::canonical::wire_int::serialize",
197        deserialize_with = "crate::canonical::wire_int::deserialize"
198    )]
199    pub window_s: i64,
200}
201
202// Custom Serialize for Constraint — emits the canonical per-kind shape.
203// Mirrors Go's Constraint.MarshalJSON and TS canonicalConstraintDict.
204// Keys are emitted in alphabetical order, matching the other SDKs.
205impl Serialize for Constraint {
206    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
207        // Count fields up front so serde's map writer knows the length.
208        // Doing this the verbose way rather than with serialize_struct
209        // because the per-kind shape is dynamic, not a fixed struct.
210        let entries: Vec<(&'static str, FieldValue)> = match self.kind.as_str() {
211            "geo_circle" => vec![
212                ("lat", FieldValue::F64(self.lat)),
213                ("lon", FieldValue::F64(self.lon)),
214                ("radius_m", FieldValue::F64(self.radius_m)),
215                ("type", FieldValue::Str(self.kind.clone())),
216            ],
217            "geo_polygon" => vec![
218                ("points", FieldValue::Points(self.points.clone())),
219                ("type", FieldValue::Str(self.kind.clone())),
220            ],
221            "geo_bbox" => {
222                let mut v = vec![
223                    ("max_lat", FieldValue::F64(self.max_lat)),
224                    ("max_lon", FieldValue::F64(self.max_lon)),
225                    ("min_lat", FieldValue::F64(self.min_lat)),
226                    ("min_lon", FieldValue::F64(self.min_lon)),
227                ];
228                if self.min_alt_m != 0.0 || self.max_alt_m != 0.0 {
229                    // Insert altitude pair alphabetically: max_alt_m < max_lat.
230                    v.insert(0, ("max_alt_m", FieldValue::F64(self.max_alt_m)));
231                    // min_alt_m < min_lat → insert after max_lon (index 2).
232                    v.insert(3, ("min_alt_m", FieldValue::F64(self.min_alt_m)));
233                }
234                v.push(("type", FieldValue::Str(self.kind.clone())));
235                v
236            }
237            "time_window" => vec![
238                ("end", FieldValue::Str(self.end.clone())),
239                ("start", FieldValue::Str(self.start.clone())),
240                ("type", FieldValue::Str(self.kind.clone())),
241                ("tz", FieldValue::Str(self.tz.clone())),
242            ],
243            "max_speed_mps" => vec![
244                ("max_mps", FieldValue::F64(self.max_mps)),
245                ("type", FieldValue::Str(self.kind.clone())),
246            ],
247            "max_amount" => vec![
248                ("currency", FieldValue::Str(self.currency.clone())),
249                ("max_amount", FieldValue::F64(self.max_amount)),
250                ("type", FieldValue::Str(self.kind.clone())),
251            ],
252            "max_rate" => vec![
253                ("count", FieldValue::I64(self.count)),
254                ("type", FieldValue::Str(self.kind.clone())),
255                ("window_s", FieldValue::I64(self.window_s)),
256            ],
257            // Unknown kind: emit only the tag. Verifier returns constraint_unknown.
258            _ => vec![("type", FieldValue::Str(self.kind.clone()))],
259        };
260        let mut m = serializer.serialize_map(Some(entries.len()))?;
261        for (k, v) in entries {
262            match v {
263                FieldValue::F64(x) => m.serialize_entry(k, &x)?,
264                FieldValue::I64(x) => {
265                    // Encoder side of the wire integer domain (SPEC §6.2).
266                    if !crate::canonical::wire_int::in_domain(x) {
267                        return Err(serde::ser::Error::custom(
268                            "integer outside the safe-integer range [-(2^53-1), 2^53-1]",
269                        ));
270                    }
271                    m.serialize_entry(k, &x)?
272                }
273                FieldValue::Str(x) => m.serialize_entry(k, &x)?,
274                FieldValue::Points(x) => m.serialize_entry(k, &x)?,
275            }
276        }
277        m.end()
278    }
279}
280
281// Small sum type so the serialize impl can carry mixed-type values in one
282// vector. Kept private to this module.
283enum FieldValue {
284    F64(f64),
285    I64(i64),
286    Str(String),
287    Points(Vec<[f64; 2]>),
288}
289
290/// Callback answering "how many invocations of this cert in this window?"
291/// — (cert_id, window_s) -> count. Used by rate-limit constraints.
292pub type InvocationCounter<'a> = Box<dyn Fn(&str, i64) -> i64 + 'a>;
293
294/// Application-supplied inputs for evaluating first-class constraints.
295/// A cert bearing a constraint whose required context field is absent will
296/// be rejected with `constraint_unverifiable` (fail-closed).
297#[derive(Default)]
298pub struct VerifierContext<'a> {
299    pub current_lat: Option<f64>,
300    pub current_lon: Option<f64>,
301    pub current_alt_m: Option<f64>,
302    pub current_speed_mps: Option<f64>,
303    pub requested_amount: Option<f64>,
304    pub requested_currency: Option<String>,
305    /// (cert_id, window_s) -> invocation count
306    pub invocations_in_window: Option<InvocationCounter<'a>>,
307}
308
309/// Proof an agent presents to a verifier.
310///
311/// v1.1 optional stream binding: when `stream_id` and `stream_seq` are set,
312/// the bundle is "stream-bound" — it belongs to an ordered sequence of
313/// interactions sharing a stream_id. Both are signed into the challenge bytes
314/// (SPEC §6.4.2) so replay, reorder, or omission within the stream invalidate
315/// the signature.
316#[derive(Debug, Clone, Serialize, Deserialize)]
317#[serde(deny_unknown_fields)]
318pub struct ProofBundle {
319    pub agent_id: String,
320    pub agent_pub_key: HybridPublicKey,
321    pub delegations: Vec<DelegationCert>,
322    #[serde(with = "crate::canonical::base64_bytes")]
323    pub challenge: Vec<u8>,
324    #[serde(
325        serialize_with = "crate::canonical::wire_int::serialize",
326        deserialize_with = "crate::canonical::wire_int::deserialize"
327    )]
328    pub challenge_at: i64,
329    pub challenge_sig: HybridSignature,
330    #[serde(
331        default,
332        skip_serializing_if = "Vec::is_empty",
333        with = "crate::canonical::base64_bytes"
334    )]
335    pub session_context: Vec<u8>,
336    #[serde(
337        default,
338        skip_serializing_if = "Vec::is_empty",
339        with = "crate::canonical::base64_bytes"
340    )]
341    pub stream_id: Vec<u8>,
342    #[serde(
343        default,
344        skip_serializing_if = "is_zero_i64",
345        serialize_with = "crate::canonical::wire_int::serialize",
346        deserialize_with = "crate::canonical::wire_int::deserialize"
347    )]
348    pub stream_seq: i64,
349}
350
351fn is_zero_i64(v: &i64) -> bool {
352    *v == 0
353}
354
355/// Identity status values in a VerifyResult (SPEC §5.9). Granular failure
356/// statuses (scope_denied, constraint_denied, etc) let callers route on the
357/// enum directly — they do not have to parse error_reason text.
358#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
359#[serde(rename_all = "snake_case")]
360pub enum IdentityStatus {
361    VerifiedHuman,
362    AuthorizedAgent,
363    Expired,
364    Revoked,
365    ScopeDenied,
366    ConstraintDenied,
367    ConstraintUnverifiable,
368    ConstraintUnknown,
369    DelegationNotAuthorized,
370    /// A cert in the chain grants a scope that is not canonical, not a
371    /// wildcard, and not a `custom:` extension (SPEC §9). Fail-closed —
372    /// vocabulary outside the protocol is rejected as malformed rather than
373    /// silently intersected.
374    InvalidScope,
375    Invalid,
376    Unauthorized,
377}
378
379impl IdentityStatus {
380    pub fn as_str(&self) -> &'static str {
381        match self {
382            Self::VerifiedHuman => "verified_human",
383            Self::AuthorizedAgent => "authorized_agent",
384            Self::Expired => "expired",
385            Self::Revoked => "revoked",
386            Self::ScopeDenied => "scope_denied",
387            Self::ConstraintDenied => "constraint_denied",
388            Self::ConstraintUnverifiable => "constraint_unverifiable",
389            Self::ConstraintUnknown => "constraint_unknown",
390            Self::DelegationNotAuthorized => "delegation_not_authorized",
391            Self::InvalidScope => "invalid_scope",
392            Self::Invalid => "invalid",
393            Self::Unauthorized => "unauthorized",
394        }
395    }
396
397    /// Parse the snake_case wire form back into the enum. Returns None if
398    /// the input is not a known status; callers should fail-closed.
399    pub fn from_wire(s: &str) -> Option<Self> {
400        Some(match s {
401            "verified_human" => Self::VerifiedHuman,
402            "authorized_agent" => Self::AuthorizedAgent,
403            "expired" => Self::Expired,
404            "revoked" => Self::Revoked,
405            "scope_denied" => Self::ScopeDenied,
406            "constraint_denied" => Self::ConstraintDenied,
407            "constraint_unverifiable" => Self::ConstraintUnverifiable,
408            "constraint_unknown" => Self::ConstraintUnknown,
409            "delegation_not_authorized" => Self::DelegationNotAuthorized,
410            "invalid_scope" => Self::InvalidScope,
411            "invalid" => Self::Invalid,
412            "unauthorized" => Self::Unauthorized,
413            _ => return None,
414        })
415    }
416}
417
418/// Deterministic output of `verify_bundle`. Always check `valid` first.
419#[derive(Debug, Clone, Serialize, Deserialize)]
420pub struct VerifyResult {
421    pub valid: bool,
422    pub identity_status: IdentityStatus,
423    #[serde(skip_serializing_if = "String::is_empty", default)]
424    pub human_id: String,
425    #[serde(skip_serializing_if = "String::is_empty", default)]
426    pub agent_id: String,
427    #[serde(skip_serializing_if = "String::is_empty", default)]
428    pub agent_name: String,
429    #[serde(skip_serializing_if = "String::is_empty", default)]
430    pub agent_type: String,
431    #[serde(skip_serializing_if = "Vec::is_empty", default)]
432    pub granted_scope: Vec<String>,
433    #[serde(skip_serializing_if = "String::is_empty", default)]
434    pub error_reason: String,
435    /// Resolved external-identity binding for `human_id`, populated when
436    /// `VerifyOptions.anchor_resolver` is set on a successful verification.
437    /// Lets downstream `AuditProvider`s record an unforgeable chain from
438    /// verification event → identity attestation. (SPEC §17.8)
439    #[serde(skip_serializing_if = "Option::is_none", default)]
440    pub anchor: Option<Anchor>,
441}
442
443/// Signed list of revoked cert IDs, served by the issuer.
444#[derive(Debug, Clone, Serialize, Deserialize)]
445pub struct RevocationList {
446    pub issuer_id: String,
447    pub updated_at: i64,
448    pub revoked_certs: Vec<String>,
449    pub signature: HybridSignature,
450}
451
452/// v1.1 signed push notification of newly revoked cert IDs.
453#[derive(Debug, Clone, Serialize, Deserialize)]
454pub struct RevocationPush {
455    pub issuer_id: String,
456    pub seq_no: i64,
457    pub entries: Vec<String>,
458    pub pushed_at: i64,
459    pub signature: HybridSignature,
460}
461
462/// v1.1 element in a hash-chain append-only witness log.
463#[derive(Debug, Clone, Serialize, Deserialize)]
464pub struct WitnessEntry {
465    #[serde(with = "crate::canonical::base64_bytes")]
466    pub prev_hash: Vec<u8>,
467    #[serde(with = "crate::canonical::base64_bytes")]
468    pub entry_data: Vec<u8>,
469    pub timestamp: i64,
470    pub witness_id: String,
471    pub signature: HybridSignature,
472}
473
474/// v1.1 verifier-issued credential that caches a verified chain. MAC =
475/// HMAC-SHA256(session_secret, session_token_sign_bytes(token)). The session
476/// secret is private to the verifier and never leaves its trust boundary.
477#[derive(Debug, Clone, Serialize, Deserialize)]
478#[serde(deny_unknown_fields)]
479pub struct SessionToken {
480    pub version: i32,
481    pub session_id: String,
482    pub agent_id: String,
483    pub agent_pub_key: HybridPublicKey,
484    pub human_id: String,
485    pub granted_scope: Vec<String>,
486    #[serde(
487        serialize_with = "crate::canonical::wire_int::serialize",
488        deserialize_with = "crate::canonical::wire_int::deserialize"
489    )]
490    pub issued_at: i64,
491    #[serde(
492        serialize_with = "crate::canonical::wire_int::serialize",
493        deserialize_with = "crate::canonical::wire_int::deserialize"
494    )]
495    pub valid_until: i64,
496    #[serde(with = "crate::canonical::base64_bytes")]
497    pub chain_hash: Vec<u8>,
498    #[serde(with = "crate::canonical::base64_bytes")]
499    pub mac: Vec<u8>,
500}
501
502/// v1.1 canonical envelope for a multi-party, atomic transaction.
503#[derive(Debug, Clone, Serialize, Deserialize)]
504pub struct TransactionReceipt {
505    pub version: i32,
506    pub transaction_id: String,
507    pub created_at: i64,
508    pub terms_schema_uri: String,
509    #[serde(with = "crate::canonical::base64_bytes")]
510    pub terms_canonical_json: Vec<u8>,
511    pub parties: Vec<ReceiptParty>,
512    pub party_signatures: Vec<ReceiptPartySignature>,
513}
514
515/// One party to a TransactionReceipt.
516#[derive(Debug, Clone, Serialize, Deserialize)]
517pub struct ReceiptParty {
518    pub party_id: String,
519    pub role: String,
520    pub agent_id: String,
521    pub agent_pub_key: HybridPublicKey,
522    pub proof_bundle: ProofBundle,
523}
524
525/// Hybrid signature by a party over the canonical receipt signable.
526#[derive(Debug, Clone, Serialize, Deserialize)]
527pub struct ReceiptPartySignature {
528    pub party_id: String,
529    pub signature: HybridSignature,
530}
531
532/// Outcome of verify_transaction_receipt.
533pub struct TransactionReceiptResult {
534    pub valid: bool,
535    pub error_reason: String,
536    pub party_results: Vec<VerifyResult>,
537}
538
539/// Signed continuity statement from an old root key to a new root key.
540#[derive(Debug, Clone, Serialize, Deserialize)]
541pub struct KeyRotationStatement {
542    pub version: i32,
543    pub old_id: String,
544    pub old_pub_key: HybridPublicKey,
545    pub new_id: String,
546    pub new_pub_key: HybridPublicKey,
547    pub rotated_at: i64,
548    pub reason: String,
549    pub signature_old: HybridSignature,
550    pub signature_new: HybridSignature,
551}
552
553/// Verifier state tracked per stream_id for v1.1 stream-bound bundles.
554///
555/// `last_seen_seq` is the highest sequence number the verifier has already
556/// accepted for `stream_id`; zero means no turns accepted yet, so the first
557/// valid bundle must carry `stream_seq == 1`.
558#[derive(Debug, Clone, Default)]
559pub struct StreamContext {
560    pub stream_id: Vec<u8>,
561    pub last_seen_seq: i64,
562}
563
564/// Pluggable provider for revocation state (SPEC §17.1).
565///
566/// Implementations return `Ok(true)` for revoked, `Ok(false)` for live, and
567/// `Err(...)` to surface a lookup failure. A provider error is fail-closed:
568/// the bundle is rejected with `error_reason="revocation_error: ..."` —
569/// SDKs MUST NOT treat a lookup failure as "not revoked." On the verifier's
570/// hot path; implementations should be O(1) at call time.
571pub trait RevocationProvider {
572    fn is_revoked(&self, cert_id: &str) -> Result<bool, String>;
573}
574
575/// Pluggable evaluator for verifier-local policy (SPEC §17.2).
576///
577/// Evaluated AFTER all cryptographic, temporal, revocation, constraint, and
578/// scope-intersection checks pass. `Ok(true)` allows; `Ok(false)` denies with
579/// `scope_denied`; `Err(...)` fails closed with `policy_error`.
580pub trait PolicyProvider {
581    fn evaluate_policy(
582        &self,
583        bundle: &ProofBundle,
584        context: &VerifierContext,
585    ) -> Result<bool, String>;
586}
587
588/// Pluggable audit-receipt persistence (SPEC §17.3).
589///
590/// Invoked on every `verify_bundle` call (success AND failure). Errors are
591/// swallowed — auditing MUST NOT alter the verdict.
592pub trait AuditProvider {
593    fn log_verification(&self, result: &VerifyResult, bundle: &ProofBundle);
594}
595
596/// Pluggable evaluator for extension constraint types (SPEC §17.7).
597///
598/// Built-in types (geo_*, time_window, max_*) are evaluated by the SDK
599/// directly; an evaluator is consulted only for types the SDK does not
600/// natively understand. Returning `Ok(true)` allows; `Ok(false)` denies as
601/// `constraint_denied`; `Err("constraint_unverifiable: ...")` routes to
602/// `constraint_unverifiable`; other `Err(...)` denies with the wrapped
603/// reason.
604pub trait ConstraintEvaluator {
605    fn evaluate(
606        &self,
607        constraint: &Constraint,
608        cert_id: &str,
609        context: &VerifierContext,
610        now: i64,
611    ) -> Result<(), String>;
612}
613
614/// Resolves a verified `human_id` to its external-identity binding
615/// (SPEC §17.8). Errors are non-fatal: the verifier MUST NOT fail the bundle
616/// because the resolver errored — it silently leaves `VerifyResult.anchor`
617/// `None` and continues.
618pub trait AnchorResolver {
619    fn resolve_anchor(&self, human_id: &str) -> Result<Option<Anchor>, String>;
620}
621
622/// HMAC-bound cached policy decision (SPEC §17.6). The policy equivalent
623/// of `SessionToken`: issued once by a commercial policy backend, accepted
624/// locally by the verifier for the rest of `valid_until` without re-calling
625/// the backend.
626#[derive(Debug, Clone, Serialize, Deserialize)]
627pub struct PolicyVerdict {
628    pub version: i32,
629    pub verdict_id: String,
630    pub agent_id: String,
631    pub scope: String,
632    pub allow: bool,
633    #[serde(with = "crate::canonical::base64_bytes")]
634    pub context_hash: Vec<u8>, // 32 bytes
635    pub issued_at: i64,
636    pub valid_until: i64,
637    #[serde(with = "crate::canonical::base64_bytes")]
638    pub mac: Vec<u8>, // 32 bytes — HMAC-SHA256
639}
640
641/// Verifier-signed attestation that a specific ProofBundle was verified at
642/// a specific moment with a specific outcome (SPEC §17.5).
643///
644/// Receipts chain by `prev_hash` (SHA-256 of previous receipt's canonical
645/// signable bytes) so a missing or backdated entry is detectable. Genesis
646/// uses 32 zero bytes.
647#[derive(Debug, Clone, Serialize, Deserialize)]
648pub struct VerificationReceipt {
649    pub version: i32,
650    pub verifier_id: String,
651    pub verifier_pub: HybridPublicKey,
652    #[serde(with = "crate::canonical::base64_bytes")]
653    pub bundle_hash: Vec<u8>, // 32 bytes
654    pub decision: String,
655    #[serde(skip_serializing_if = "String::is_empty", default)]
656    pub human_id: String,
657    #[serde(skip_serializing_if = "String::is_empty", default)]
658    pub agent_id: String,
659    #[serde(skip_serializing_if = "Vec::is_empty", default)]
660    pub granted_scope: Vec<String>,
661    #[serde(skip_serializing_if = "String::is_empty", default)]
662    pub error_reason: String,
663    pub verified_at: i64,
664    #[serde(with = "crate::canonical::base64_bytes")]
665    pub prev_hash: Vec<u8>, // 32 bytes; zeros for genesis
666    pub signature: HybridSignature,
667}
668
669/// Options passed to `verify_bundle`.
670pub struct VerifyOptions<'a> {
671    /// Required scope; empty string skips scope checking.
672    pub required_scope: String,
673    /// Legacy v1 revocation closure.
674    ///
675    /// **Deprecated:** Use `revocation` (SPEC §17.1) instead. The closure
676    /// has no way to surface lookup failures; `revocation` returns
677    /// `Result<bool, String>` and fails closed on error. Slated for removal
678    /// in v1.0.0-beta.1. When both fields are set, `revocation` wins.
679    #[deprecated(since = "1.0.0-alpha.7", note = "use `revocation` (SPEC §17.1) instead")]
680    // Slated for removal in v1.0.0-beta.1 — not worth a public type alias.
681    #[allow(clippy::type_complexity)]
682    pub is_revoked: Option<Box<dyn Fn(&str) -> bool + 'a>>,
683    /// Pluggable revocation provider (SPEC §17.1). Takes precedence over
684    /// `is_revoked`. A provider error fails the bundle as `revocation_error`.
685    pub revocation: Option<Box<dyn RevocationProvider + 'a>>,
686    /// Force a fresh revocation check for high-stakes endpoints. The SDK
687    /// cannot fetch revocation state itself; callers must provide is_revoked
688    /// or a revocation provider when this is true.
689    pub force_revocation_check: bool,
690    /// Override current time (unix seconds); None = SystemTime::now().
691    pub now: Option<i64>,
692    /// Optional verifier-reconstructed 32-byte v1.1 session context.
693    pub session_context: Vec<u8>,
694    /// Optional verifier-tracked v1.1 stream context.
695    pub stream: Option<StreamContext>,
696    /// Application inputs for evaluating first-class constraints. Default is
697    /// empty; constraint-bearing certs fail closed if required context is
698    /// absent.
699    pub context: VerifierContext<'a>,
700    /// Advanced verifier-local policy evaluator (SPEC §17.2). Evaluated after
701    /// all cryptographic checks pass. Deny → `scope_denied`; provider error →
702    /// `policy_error`.
703    pub policy: Option<Box<dyn PolicyProvider + 'a>>,
704    /// Audit-receipt persistence hook (SPEC §17.3). Invoked on every Verify
705    /// (success AND failure). Provider errors are swallowed — auditing cannot
706    /// alter the verdict.
707    pub audit: Option<Box<dyn AuditProvider + 'a>>,
708    /// Per-Verify registry of extension constraint evaluators (SPEC §17.7).
709    /// Built-in types are evaluated by the SDK directly; the registry is
710    /// only consulted for unknown types.
711    pub constraint_evaluators:
712        Option<alloc::collections::BTreeMap<String, Box<dyn ConstraintEvaluator + 'a>>>,
713    /// Fast-path cached policy decision (SPEC §17.6). When present and
714    /// valid (MAC matches `policy_secret`, within window, agent/scope/
715    /// context_hash matches), the verifier skips the live `policy` hook.
716    /// Stale verdicts fall back to live policy.
717    pub policy_verdict: Option<PolicyVerdict>,
718    /// HMAC secret used to verify `policy_verdict.mac`.
719    pub policy_secret: Option<Vec<u8>>,
720    /// Anchor resolver (SPEC §17.8). When set on a Valid=true verification,
721    /// the verifier populates `VerifyResult.anchor`. Resolver errors are
722    /// non-fatal.
723    pub anchor_resolver: Option<Box<dyn AnchorResolver + 'a>>,
724    /// Single-use tracking for verifier-issued challenges (SPEC §10). When
725    /// set, the store is consulted (without consuming) before any signature
726    /// work, and the challenge is atomically consumed after the structural,
727    /// chain, and challenge-signature checks pass — before authorization
728    /// evaluation. A forged or malformed presentation never consumes a
729    /// challenge; a cryptographically valid presentation does, even if
730    /// authorization is subsequently denied. When a store is in use,
731    /// constraint evaluation is deferred until after consumption. The
732    /// store's session binding is checked against `session_context`.
733    pub challenge_store: Option<Box<dyn crate::challenge_store::ChallengeStore + 'a>>,
734}
735
736// Not derived: this manual impl exists to isolate the #[allow(deprecated)]
737// initialization of `is_revoked` to a single construction site. Deriving
738// would spread the deprecation suppression to the whole struct.
739#[allow(clippy::derivable_impls)]
740impl<'a> Default for VerifyOptions<'a> {
741    fn default() -> Self {
742        // The Default impl must initialize the deprecated field for backwards
743        // compatibility. Suppressing the warning is intentional and isolated
744        // to this single construction site.
745        #[allow(deprecated)]
746        Self {
747            required_scope: String::new(),
748            is_revoked: None,
749            revocation: None,
750            force_revocation_check: false,
751            now: None,
752            session_context: Vec::new(),
753            stream: None,
754            context: VerifierContext::default(),
755            policy: None,
756            audit: None,
757            constraint_evaluators: None,
758            policy_verdict: None,
759            policy_secret: None,
760            anchor_resolver: None,
761            challenge_store: None,
762        }
763    }
764}