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/// Callback answering "how many invocations of this cert in this window?"
263/// — (cert_id, window_s) -> count. Used by rate-limit constraints.
264pub type InvocationCounter<'a> = Box<dyn Fn(&str, i64) -> i64 + 'a>;
265
266/// Application-supplied inputs for evaluating first-class constraints.
267/// A cert bearing a constraint whose required context field is absent will
268/// be rejected with `constraint_unverifiable` (fail-closed).
269#[derive(Default)]
270pub struct VerifierContext<'a> {
271    pub current_lat: Option<f64>,
272    pub current_lon: Option<f64>,
273    pub current_alt_m: Option<f64>,
274    pub current_speed_mps: Option<f64>,
275    pub requested_amount: Option<f64>,
276    pub requested_currency: Option<String>,
277    /// (cert_id, window_s) -> invocation count
278    pub invocations_in_window: Option<InvocationCounter<'a>>,
279}
280
281/// Proof an agent presents to a verifier.
282///
283/// v1.1 optional stream binding: when `stream_id` and `stream_seq` are set,
284/// the bundle is "stream-bound" — it belongs to an ordered sequence of
285/// interactions sharing a stream_id. Both are signed into the challenge bytes
286/// (SPEC §6.4.2) so replay, reorder, or omission within the stream invalidate
287/// the signature.
288#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct ProofBundle {
290    pub agent_id: String,
291    pub agent_pub_key: HybridPublicKey,
292    pub delegations: Vec<DelegationCert>,
293    #[serde(with = "crate::canonical::base64_bytes")]
294    pub challenge: Vec<u8>,
295    pub challenge_at: i64,
296    pub challenge_sig: HybridSignature,
297    #[serde(
298        default,
299        skip_serializing_if = "Vec::is_empty",
300        with = "crate::canonical::base64_bytes"
301    )]
302    pub session_context: Vec<u8>,
303    #[serde(
304        default,
305        skip_serializing_if = "Vec::is_empty",
306        with = "crate::canonical::base64_bytes"
307    )]
308    pub stream_id: Vec<u8>,
309    #[serde(default, skip_serializing_if = "is_zero_i64")]
310    pub stream_seq: i64,
311}
312
313fn is_zero_i64(v: &i64) -> bool {
314    *v == 0
315}
316
317/// Identity status values in a VerifyResult (SPEC §5.9). Granular failure
318/// statuses (scope_denied, constraint_denied, etc) let callers route on the
319/// enum directly — they do not have to parse error_reason text.
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
321#[serde(rename_all = "snake_case")]
322pub enum IdentityStatus {
323    VerifiedHuman,
324    AuthorizedAgent,
325    Expired,
326    Revoked,
327    ScopeDenied,
328    ConstraintDenied,
329    ConstraintUnverifiable,
330    ConstraintUnknown,
331    DelegationNotAuthorized,
332    /// A cert in the chain grants a scope that is not canonical, not a
333    /// wildcard, and not a `custom:` extension (SPEC §9). Fail-closed —
334    /// vocabulary outside the protocol is rejected as malformed rather than
335    /// silently intersected.
336    InvalidScope,
337    Invalid,
338    Unauthorized,
339}
340
341impl IdentityStatus {
342    pub fn as_str(&self) -> &'static str {
343        match self {
344            Self::VerifiedHuman => "verified_human",
345            Self::AuthorizedAgent => "authorized_agent",
346            Self::Expired => "expired",
347            Self::Revoked => "revoked",
348            Self::ScopeDenied => "scope_denied",
349            Self::ConstraintDenied => "constraint_denied",
350            Self::ConstraintUnverifiable => "constraint_unverifiable",
351            Self::ConstraintUnknown => "constraint_unknown",
352            Self::DelegationNotAuthorized => "delegation_not_authorized",
353            Self::InvalidScope => "invalid_scope",
354            Self::Invalid => "invalid",
355            Self::Unauthorized => "unauthorized",
356        }
357    }
358
359    /// Parse the snake_case wire form back into the enum. Returns None if
360    /// the input is not a known status; callers should fail-closed.
361    pub fn from_wire(s: &str) -> Option<Self> {
362        Some(match s {
363            "verified_human" => Self::VerifiedHuman,
364            "authorized_agent" => Self::AuthorizedAgent,
365            "expired" => Self::Expired,
366            "revoked" => Self::Revoked,
367            "scope_denied" => Self::ScopeDenied,
368            "constraint_denied" => Self::ConstraintDenied,
369            "constraint_unverifiable" => Self::ConstraintUnverifiable,
370            "constraint_unknown" => Self::ConstraintUnknown,
371            "delegation_not_authorized" => Self::DelegationNotAuthorized,
372            "invalid_scope" => Self::InvalidScope,
373            "invalid" => Self::Invalid,
374            "unauthorized" => Self::Unauthorized,
375            _ => return None,
376        })
377    }
378}
379
380/// Deterministic output of `verify_bundle`. Always check `valid` first.
381#[derive(Debug, Clone, Serialize, Deserialize)]
382pub struct VerifyResult {
383    pub valid: bool,
384    pub identity_status: IdentityStatus,
385    #[serde(skip_serializing_if = "String::is_empty", default)]
386    pub human_id: String,
387    #[serde(skip_serializing_if = "String::is_empty", default)]
388    pub agent_id: String,
389    #[serde(skip_serializing_if = "String::is_empty", default)]
390    pub agent_name: String,
391    #[serde(skip_serializing_if = "String::is_empty", default)]
392    pub agent_type: String,
393    #[serde(skip_serializing_if = "Vec::is_empty", default)]
394    pub granted_scope: Vec<String>,
395    #[serde(skip_serializing_if = "String::is_empty", default)]
396    pub error_reason: String,
397    /// Resolved external-identity binding for `human_id`, populated when
398    /// `VerifyOptions.anchor_resolver` is set on a successful verification.
399    /// Lets downstream `AuditProvider`s record an unforgeable chain from
400    /// verification event → identity attestation. (SPEC §17.8)
401    #[serde(skip_serializing_if = "Option::is_none", default)]
402    pub anchor: Option<Anchor>,
403}
404
405/// Signed list of revoked cert IDs, served by the issuer.
406#[derive(Debug, Clone, Serialize, Deserialize)]
407pub struct RevocationList {
408    pub issuer_id: String,
409    pub updated_at: i64,
410    pub revoked_certs: Vec<String>,
411    pub signature: HybridSignature,
412}
413
414/// v1.1 signed push notification of newly revoked cert IDs.
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct RevocationPush {
417    pub issuer_id: String,
418    pub seq_no: i64,
419    pub entries: Vec<String>,
420    pub pushed_at: i64,
421    pub signature: HybridSignature,
422}
423
424/// v1.1 element in a hash-chain append-only witness log.
425#[derive(Debug, Clone, Serialize, Deserialize)]
426pub struct WitnessEntry {
427    #[serde(with = "crate::canonical::base64_bytes")]
428    pub prev_hash: Vec<u8>,
429    #[serde(with = "crate::canonical::base64_bytes")]
430    pub entry_data: Vec<u8>,
431    pub timestamp: i64,
432    pub witness_id: String,
433    pub signature: HybridSignature,
434}
435
436/// v1.1 verifier-issued credential that caches a verified chain. MAC =
437/// HMAC-SHA256(session_secret, session_token_sign_bytes(token)). The session
438/// secret is private to the verifier and never leaves its trust boundary.
439#[derive(Debug, Clone, Serialize, Deserialize)]
440pub struct SessionToken {
441    pub version: i32,
442    pub session_id: String,
443    pub agent_id: String,
444    pub agent_pub_key: HybridPublicKey,
445    pub human_id: String,
446    pub granted_scope: Vec<String>,
447    pub issued_at: i64,
448    pub valid_until: i64,
449    #[serde(with = "crate::canonical::base64_bytes")]
450    pub chain_hash: Vec<u8>,
451    #[serde(with = "crate::canonical::base64_bytes")]
452    pub mac: Vec<u8>,
453}
454
455/// v1.1 canonical envelope for a multi-party, atomic transaction.
456#[derive(Debug, Clone, Serialize, Deserialize)]
457pub struct TransactionReceipt {
458    pub version: i32,
459    pub transaction_id: String,
460    pub created_at: i64,
461    pub terms_schema_uri: String,
462    #[serde(with = "crate::canonical::base64_bytes")]
463    pub terms_canonical_json: Vec<u8>,
464    pub parties: Vec<ReceiptParty>,
465    pub party_signatures: Vec<ReceiptPartySignature>,
466}
467
468/// One party to a TransactionReceipt.
469#[derive(Debug, Clone, Serialize, Deserialize)]
470pub struct ReceiptParty {
471    pub party_id: String,
472    pub role: String,
473    pub agent_id: String,
474    pub agent_pub_key: HybridPublicKey,
475    pub proof_bundle: ProofBundle,
476}
477
478/// Hybrid signature by a party over the canonical receipt signable.
479#[derive(Debug, Clone, Serialize, Deserialize)]
480pub struct ReceiptPartySignature {
481    pub party_id: String,
482    pub signature: HybridSignature,
483}
484
485/// Outcome of verify_transaction_receipt.
486pub struct TransactionReceiptResult {
487    pub valid: bool,
488    pub error_reason: String,
489    pub party_results: Vec<VerifyResult>,
490}
491
492/// Signed continuity statement from an old root key to a new root key.
493#[derive(Debug, Clone, Serialize, Deserialize)]
494pub struct KeyRotationStatement {
495    pub version: i32,
496    pub old_id: String,
497    pub old_pub_key: HybridPublicKey,
498    pub new_id: String,
499    pub new_pub_key: HybridPublicKey,
500    pub rotated_at: i64,
501    pub reason: String,
502    pub signature_old: HybridSignature,
503    pub signature_new: HybridSignature,
504}
505
506/// Verifier state tracked per stream_id for v1.1 stream-bound bundles.
507///
508/// `last_seen_seq` is the highest sequence number the verifier has already
509/// accepted for `stream_id`; zero means no turns accepted yet, so the first
510/// valid bundle must carry `stream_seq == 1`.
511#[derive(Debug, Clone, Default)]
512pub struct StreamContext {
513    pub stream_id: Vec<u8>,
514    pub last_seen_seq: i64,
515}
516
517/// Pluggable provider for revocation state (SPEC §17.1).
518///
519/// Implementations return `Ok(true)` for revoked, `Ok(false)` for live, and
520/// `Err(...)` to surface a lookup failure. A provider error is fail-closed:
521/// the bundle is rejected with `error_reason="revocation_error: ..."` —
522/// SDKs MUST NOT treat a lookup failure as "not revoked." On the verifier's
523/// hot path; implementations should be O(1) at call time.
524pub trait RevocationProvider {
525    fn is_revoked(&self, cert_id: &str) -> Result<bool, String>;
526}
527
528/// Pluggable evaluator for verifier-local policy (SPEC §17.2).
529///
530/// Evaluated AFTER all cryptographic, temporal, revocation, constraint, and
531/// scope-intersection checks pass. `Ok(true)` allows; `Ok(false)` denies with
532/// `scope_denied`; `Err(...)` fails closed with `policy_error`.
533pub trait PolicyProvider {
534    fn evaluate_policy(
535        &self,
536        bundle: &ProofBundle,
537        context: &VerifierContext,
538    ) -> Result<bool, String>;
539}
540
541/// Pluggable audit-receipt persistence (SPEC §17.3).
542///
543/// Invoked on every `verify_bundle` call (success AND failure). Errors are
544/// swallowed — auditing MUST NOT alter the verdict.
545pub trait AuditProvider {
546    fn log_verification(&self, result: &VerifyResult, bundle: &ProofBundle);
547}
548
549/// Pluggable evaluator for extension constraint types (SPEC §17.7).
550///
551/// Built-in types (geo_*, time_window, max_*) are evaluated by the SDK
552/// directly; an evaluator is consulted only for types the SDK does not
553/// natively understand. Returning `Ok(true)` allows; `Ok(false)` denies as
554/// `constraint_denied`; `Err("constraint_unverifiable: ...")` routes to
555/// `constraint_unverifiable`; other `Err(...)` denies with the wrapped
556/// reason.
557pub trait ConstraintEvaluator {
558    fn evaluate(
559        &self,
560        constraint: &Constraint,
561        cert_id: &str,
562        context: &VerifierContext,
563        now: i64,
564    ) -> Result<(), String>;
565}
566
567/// Resolves a verified `human_id` to its external-identity binding
568/// (SPEC §17.8). Errors are non-fatal: the verifier MUST NOT fail the bundle
569/// because the resolver errored — it silently leaves `VerifyResult.anchor`
570/// `None` and continues.
571pub trait AnchorResolver {
572    fn resolve_anchor(&self, human_id: &str) -> Result<Option<Anchor>, String>;
573}
574
575/// HMAC-bound cached policy decision (SPEC §17.6). The policy equivalent
576/// of `SessionToken`: issued once by a commercial policy backend, accepted
577/// locally by the verifier for the rest of `valid_until` without re-calling
578/// the backend.
579#[derive(Debug, Clone, Serialize, Deserialize)]
580pub struct PolicyVerdict {
581    pub version: i32,
582    pub verdict_id: String,
583    pub agent_id: String,
584    pub scope: String,
585    pub allow: bool,
586    #[serde(with = "crate::canonical::base64_bytes")]
587    pub context_hash: Vec<u8>, // 32 bytes
588    pub issued_at: i64,
589    pub valid_until: i64,
590    #[serde(with = "crate::canonical::base64_bytes")]
591    pub mac: Vec<u8>, // 32 bytes — HMAC-SHA256
592}
593
594/// Verifier-signed attestation that a specific ProofBundle was verified at
595/// a specific moment with a specific outcome (SPEC §17.5).
596///
597/// Receipts chain by `prev_hash` (SHA-256 of previous receipt's canonical
598/// signable bytes) so a missing or backdated entry is detectable. Genesis
599/// uses 32 zero bytes.
600#[derive(Debug, Clone, Serialize, Deserialize)]
601pub struct VerificationReceipt {
602    pub version: i32,
603    pub verifier_id: String,
604    pub verifier_pub: HybridPublicKey,
605    #[serde(with = "crate::canonical::base64_bytes")]
606    pub bundle_hash: Vec<u8>, // 32 bytes
607    pub decision: String,
608    #[serde(skip_serializing_if = "String::is_empty", default)]
609    pub human_id: String,
610    #[serde(skip_serializing_if = "String::is_empty", default)]
611    pub agent_id: String,
612    #[serde(skip_serializing_if = "Vec::is_empty", default)]
613    pub granted_scope: Vec<String>,
614    #[serde(skip_serializing_if = "String::is_empty", default)]
615    pub error_reason: String,
616    pub verified_at: i64,
617    #[serde(with = "crate::canonical::base64_bytes")]
618    pub prev_hash: Vec<u8>, // 32 bytes; zeros for genesis
619    pub signature: HybridSignature,
620}
621
622/// Options passed to `verify_bundle`.
623pub struct VerifyOptions<'a> {
624    /// Required scope; empty string skips scope checking.
625    pub required_scope: String,
626    /// Legacy v1 revocation closure.
627    ///
628    /// **Deprecated:** Use `revocation` (SPEC §17.1) instead. The closure
629    /// has no way to surface lookup failures; `revocation` returns
630    /// `Result<bool, String>` and fails closed on error. Slated for removal
631    /// in v1.0.0-beta.1. When both fields are set, `revocation` wins.
632    #[deprecated(since = "1.0.0-alpha.7", note = "use `revocation` (SPEC §17.1) instead")]
633    // Slated for removal in v1.0.0-beta.1 — not worth a public type alias.
634    #[allow(clippy::type_complexity)]
635    pub is_revoked: Option<Box<dyn Fn(&str) -> bool + 'a>>,
636    /// Pluggable revocation provider (SPEC §17.1). Takes precedence over
637    /// `is_revoked`. A provider error fails the bundle as `revocation_error`.
638    pub revocation: Option<Box<dyn RevocationProvider + 'a>>,
639    /// Force a fresh revocation check for high-stakes endpoints. The SDK
640    /// cannot fetch revocation state itself; callers must provide is_revoked
641    /// or a revocation provider when this is true.
642    pub force_revocation_check: bool,
643    /// Override current time (unix seconds); None = SystemTime::now().
644    pub now: Option<i64>,
645    /// Optional verifier-reconstructed 32-byte v1.1 session context.
646    pub session_context: Vec<u8>,
647    /// Optional verifier-tracked v1.1 stream context.
648    pub stream: Option<StreamContext>,
649    /// Application inputs for evaluating first-class constraints. Default is
650    /// empty; constraint-bearing certs fail closed if required context is
651    /// absent.
652    pub context: VerifierContext<'a>,
653    /// Advanced verifier-local policy evaluator (SPEC §17.2). Evaluated after
654    /// all cryptographic checks pass. Deny → `scope_denied`; provider error →
655    /// `policy_error`.
656    pub policy: Option<Box<dyn PolicyProvider + 'a>>,
657    /// Audit-receipt persistence hook (SPEC §17.3). Invoked on every Verify
658    /// (success AND failure). Provider errors are swallowed — auditing cannot
659    /// alter the verdict.
660    pub audit: Option<Box<dyn AuditProvider + 'a>>,
661    /// Per-Verify registry of extension constraint evaluators (SPEC §17.7).
662    /// Built-in types are evaluated by the SDK directly; the registry is
663    /// only consulted for unknown types.
664    pub constraint_evaluators:
665        Option<alloc::collections::BTreeMap<String, Box<dyn ConstraintEvaluator + 'a>>>,
666    /// Fast-path cached policy decision (SPEC §17.6). When present and
667    /// valid (MAC matches `policy_secret`, within window, agent/scope/
668    /// context_hash matches), the verifier skips the live `policy` hook.
669    /// Stale verdicts fall back to live policy.
670    pub policy_verdict: Option<PolicyVerdict>,
671    /// HMAC secret used to verify `policy_verdict.mac`.
672    pub policy_secret: Option<Vec<u8>>,
673    /// Anchor resolver (SPEC §17.8). When set on a Valid=true verification,
674    /// the verifier populates `VerifyResult.anchor`. Resolver errors are
675    /// non-fatal.
676    pub anchor_resolver: Option<Box<dyn AnchorResolver + 'a>>,
677}
678
679// Not derived: this manual impl exists to isolate the #[allow(deprecated)]
680// initialization of `is_revoked` to a single construction site. Deriving
681// would spread the deprecation suppression to the whole struct.
682#[allow(clippy::derivable_impls)]
683impl<'a> Default for VerifyOptions<'a> {
684    fn default() -> Self {
685        // The Default impl must initialize the deprecated field for backwards
686        // compatibility. Suppressing the warning is intentional and isolated
687        // to this single construction site.
688        #[allow(deprecated)]
689        Self {
690            required_scope: String::new(),
691            is_revoked: None,
692            revocation: None,
693            force_revocation_check: false,
694            now: None,
695            session_context: Vec::new(),
696            stream: None,
697            context: VerifierContext::default(),
698            policy: None,
699            audit: None,
700            constraint_evaluators: None,
701            policy_verdict: None,
702            policy_secret: None,
703            anchor_resolver: None,
704        }
705    }
706}