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