1#[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
17pub const NO_EXPIRY_SENTINEL: i64 = 4070908799;
27pub const MAX_DELEGATION_CHAIN_DEPTH: usize = 8;
31pub const CHALLENGE_WINDOW_SECONDS: i64 = 300;
32
33pub const MAX_PROOF_BUNDLE_BYTES: usize = 131072; pub const MAX_SCOPES_PER_CERT: usize = 128;
42pub const MAX_CONSTRAINTS_PER_CERT: usize = 32;
44pub const MAX_SCOPE_LENGTH_BYTES: usize = 256;
46pub const MAX_IDENTIFIER_LENGTH_BYTES: usize = 512;
48pub const MAX_AGENT_NAME_LENGTH_BYTES: usize = 256;
50pub 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#[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>, #[serde(with = "crate::canonical::base64_bytes")]
68 pub ml_dsa_65: Vec<u8>, }
70
71#[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>, #[serde(with = "crate::canonical::base64_bytes")]
80 pub ml_dsa_65: Vec<u8>, }
82
83#[derive(Clone)]
90pub struct HybridPrivateKey {
91 ed25519: Vec<u8>, ml_dsa_65: Vec<u8>, }
94
95impl HybridPrivateKey {
96 pub fn from_components(ed25519: Vec<u8>, ml_dsa_65: Vec<u8>) -> Self {
100 HybridPrivateKey { ed25519, ml_dsa_65 }
101 }
102
103 pub fn ed25519(&self) -> &[u8] {
105 &self.ed25519
106 }
107
108 pub fn ml_dsa_65(&self) -> &[u8] {
110 &self.ml_dsa_65
111 }
112}
113
114impl Drop for HybridPrivateKey {
115 fn drop(&mut self) {
116 use zeroize::Zeroize;
117 self.ed25519.zeroize();
118 self.ml_dsa_65.zeroize();
119 }
120}
121
122impl fmt::Debug for HybridPrivateKey {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 let public = self
125 .ed25519
126 .get(..32)
127 .and_then(|s| <[u8; 32]>::try_from(s).ok())
128 .map(zeroize::Zeroizing::new)
129 .map(|seed| {
130 hex::encode(ed25519_dalek::SigningKey::from_bytes(&seed).verifying_key().to_bytes())
131 });
132 f.debug_struct("HybridPrivateKey")
133 .field("ed25519_public", &public)
134 .finish_non_exhaustive()
135 }
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct Anchor {
141 #[serde(rename = "type")]
142 pub anchor_type: String,
143 pub provider: String,
144 pub reference: String,
145 pub verified_at: i64,
146}
147
148#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct HumanRoot {
151 pub id: String,
152 pub public_key: HybridPublicKey,
153 pub created_at: i64,
154 #[serde(skip_serializing_if = "Option::is_none")]
155 pub anchors: Option<Vec<Anchor>>,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct AgentIdentity {
161 pub id: String,
162 pub public_key: HybridPublicKey,
163 pub name: String,
164 pub agent_type: String,
165 pub created_at: i64,
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
174#[serde(deny_unknown_fields)]
175pub struct DelegationCert {
176 pub cert_id: String,
177 pub version: i32,
178 pub issuer_id: String,
179 pub issuer_pub_key: HybridPublicKey,
180 pub subject_id: String,
181 pub subject_pub_key: HybridPublicKey,
182 pub scope: Vec<String>,
183 #[serde(default)]
186 pub constraints: Vec<Constraint>,
187 #[serde(
188 serialize_with = "crate::canonical::wire_int::serialize",
189 deserialize_with = "crate::canonical::wire_int::deserialize"
190 )]
191 pub issued_at: i64,
192 #[serde(
193 serialize_with = "crate::canonical::wire_int::serialize",
194 deserialize_with = "crate::canonical::wire_int::deserialize"
195 )]
196 pub expires_at: i64,
197 pub signature: HybridSignature,
198}
199
200impl DelegationCert {
201 pub fn is_no_expiry(&self) -> bool {
206 self.expires_at == NO_EXPIRY_SENTINEL
207 }
208}
209
210#[derive(Debug, Clone, PartialEq)]
217pub enum ParamsValue {
218 Null,
219 Bool(bool),
220 Int(i64),
221 Str(String),
222 Array(Vec<ParamsValue>),
223 Object(BTreeMap<String, ParamsValue>),
224}
225
226impl Serialize for ParamsValue {
227 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
228 match self {
229 ParamsValue::Null => serializer.serialize_unit(),
230 ParamsValue::Bool(b) => serializer.serialize_bool(*b),
231 ParamsValue::Int(n) => {
232 if !crate::canonical::wire_int::in_domain(*n) {
233 return Err(serde::ser::Error::custom(
234 "params integer exceeds the safe-integer range; carry it as a decimal string",
235 ));
236 }
237 serializer.serialize_i64(*n)
238 }
239 ParamsValue::Str(s) => serializer.serialize_str(s),
240 ParamsValue::Array(items) => {
241 let mut seq = serializer.serialize_seq(Some(items.len()))?;
242 for item in items {
243 seq.serialize_element(item)?;
244 }
245 seq.end()
246 }
247 ParamsValue::Object(map) => {
248 let mut m = serializer.serialize_map(Some(map.len()))?;
250 for (k, v) in map {
251 m.serialize_entry(k, v)?;
252 }
253 m.end()
254 }
255 }
256 }
257}
258
259struct ParamsValueVisitor;
260
261impl<'de> Visitor<'de> for ParamsValueVisitor {
262 type Value = ParamsValue;
263
264 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
265 f.write_str("a restricted params value (null, bool, string, safe integer, array, or object)")
266 }
267
268 fn visit_bool<E: DeError>(self, v: bool) -> Result<Self::Value, E> {
269 Ok(ParamsValue::Bool(v))
270 }
271 fn visit_i64<E: DeError>(self, v: i64) -> Result<Self::Value, E> {
272 Ok(ParamsValue::Int(v))
273 }
274 fn visit_u64<E: DeError>(self, v: u64) -> Result<Self::Value, E> {
275 if v > i64::MAX as u64 {
276 return Err(E::custom(
277 "params integer exceeds the safe-integer range; carry it as a decimal string",
278 ));
279 }
280 Ok(ParamsValue::Int(v as i64))
281 }
282 fn visit_f64<E: DeError>(self, v: f64) -> Result<Self::Value, E> {
283 if !v.is_finite() || v.fract() != 0.0 {
286 return Err(E::custom(
287 "params values must be safe integers, not floats (carry non-integers as strings)",
288 ));
289 }
290 let max = crate::canonical::wire_int::MAX_SAFE_INTEGER as f64;
291 if v.abs() > max {
292 return Err(E::custom(
293 "params integer exceeds the safe-integer range; carry it as a decimal string",
294 ));
295 }
296 Ok(ParamsValue::Int(v as i64))
297 }
298 fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {
299 Ok(ParamsValue::Str(v.to_string()))
300 }
301 fn visit_string<E: DeError>(self, v: String) -> Result<Self::Value, E> {
302 Ok(ParamsValue::Str(v))
303 }
304 fn visit_none<E: DeError>(self) -> Result<Self::Value, E> {
305 Ok(ParamsValue::Null)
306 }
307 fn visit_unit<E: DeError>(self) -> Result<Self::Value, E> {
308 Ok(ParamsValue::Null)
309 }
310 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
311 let mut out = Vec::new();
312 while let Some(item) = seq.next_element()? {
313 out.push(item);
314 }
315 Ok(ParamsValue::Array(out))
316 }
317 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
318 let mut out: BTreeMap<String, ParamsValue> = BTreeMap::new();
319 while let Some((k, v)) = map.next_entry::<String, ParamsValue>()? {
320 if out.insert(k, v).is_some() {
321 return Err(A::Error::custom("params contains a duplicate object key"));
323 }
324 }
325 Ok(ParamsValue::Object(out))
326 }
327}
328
329impl<'de> Deserialize<'de> for ParamsValue {
330 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
331 deserializer.deserialize_any(ParamsValueVisitor)
332 }
333}
334
335pub fn is_canonical_constraint_type(t: &str) -> bool {
338 matches!(
339 t,
340 "geo_circle"
341 | "geo_polygon"
342 | "geo_bbox"
343 | "time_window"
344 | "max_speed_mps"
345 | "max_amount"
346 | "max_rate"
347 | "resource_path"
348 )
349}
350
351fn de_path_prefix<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
358where
359 D: Deserializer<'de>,
360{
361 let s = String::deserialize(deserializer)?;
363 if s.is_empty() {
364 return Err(D::Error::custom(
365 "constraint path_prefix must not be empty or null; omit the field to authorize the entire resource",
366 ));
367 }
368 Ok(Some(s))
369}
370
371#[derive(Debug, Clone, Default, Deserialize)]
395#[serde(deny_unknown_fields)]
396struct ConstraintWire {
397 #[serde(default, deserialize_with = "crate::canonical::wire_int::deserialize")]
398 count: i64,
399 #[serde(default)]
400 currency: String,
401 #[serde(default)]
402 end: String,
403 #[serde(default)]
404 lat: f64,
405 #[serde(default)]
406 lon: f64,
407 #[serde(default)]
408 max_alt_m: f64,
409 #[serde(default)]
410 max_amount: f64,
411 #[serde(default)]
412 max_lat: f64,
413 #[serde(default)]
414 max_lon: f64,
415 #[serde(default)]
416 max_mps: f64,
417 #[serde(default)]
418 min_alt_m: f64,
419 #[serde(default)]
420 min_lat: f64,
421 #[serde(default)]
422 min_lon: f64,
423 #[serde(default)]
424 params: Option<BTreeMap<String, ParamsValue>>,
425 #[serde(default, deserialize_with = "de_path_prefix")]
426 path_prefix: Option<String>,
427 #[serde(default)]
428 points: Vec<[f64; 2]>,
429 #[serde(default)]
430 radius_m: f64,
431 #[serde(default)]
432 resource_id: String,
433 #[serde(default)]
434 start: String,
435 #[serde(default)]
436 tz: String,
437 #[serde(rename = "type")]
438 kind: String,
439 #[serde(default, deserialize_with = "crate::canonical::wire_int::deserialize")]
440 window_s: i64,
441}
442
443impl TryFrom<ConstraintWire> for Constraint {
444 type Error = String;
445 fn try_from(w: ConstraintWire) -> Result<Self, Self::Error> {
446 if w.kind == "resource_path" && w.resource_id.is_empty() {
447 return Err(
448 "resource_path constraint requires a non-empty resource_id".into(),
449 );
450 }
451 Ok(Constraint {
452 count: w.count,
453 currency: w.currency,
454 end: w.end,
455 lat: w.lat,
456 lon: w.lon,
457 max_alt_m: w.max_alt_m,
458 max_amount: w.max_amount,
459 max_lat: w.max_lat,
460 max_lon: w.max_lon,
461 max_mps: w.max_mps,
462 min_alt_m: w.min_alt_m,
463 min_lat: w.min_lat,
464 min_lon: w.min_lon,
465 params: w.params,
466 path_prefix: w.path_prefix,
467 points: w.points,
468 radius_m: w.radius_m,
469 resource_id: w.resource_id,
470 start: w.start,
471 tz: w.tz,
472 kind: w.kind,
473 window_s: w.window_s,
474 })
475 }
476}
477
478#[derive(Debug, Clone, Default, Deserialize)]
479#[serde(try_from = "ConstraintWire")]
480pub struct Constraint {
481 pub count: i64,
482 pub currency: String,
483 pub end: String,
484 pub lat: f64,
485 pub lon: f64,
486 pub max_alt_m: f64,
487 pub max_amount: f64,
488 pub max_lat: f64,
489 pub max_lon: f64,
490 pub max_mps: f64,
491 pub min_alt_m: f64,
492 pub min_lat: f64,
493 pub min_lon: f64,
494 pub params: Option<BTreeMap<String, ParamsValue>>,
498 pub path_prefix: Option<String>,
502 pub points: Vec<[f64; 2]>,
503 pub radius_m: f64,
504 pub resource_id: String,
507 pub start: String,
508 pub tz: String,
509 pub kind: String,
510 pub window_s: i64,
511}
512
513impl Serialize for Constraint {
517 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
518 if self.params.is_some() && is_canonical_constraint_type(&self.kind) {
520 return Err(serde::ser::Error::custom(format!(
521 "canonical constraint type \"{}\" must not carry params",
522 self.kind
523 )));
524 }
525 let entries: Vec<(&'static str, FieldValue)> = match self.kind.as_str() {
529 "geo_circle" => vec![
530 ("lat", FieldValue::F64(self.lat)),
531 ("lon", FieldValue::F64(self.lon)),
532 ("radius_m", FieldValue::F64(self.radius_m)),
533 ("type", FieldValue::Str(self.kind.clone())),
534 ],
535 "geo_polygon" => vec![
536 ("points", FieldValue::Points(self.points.clone())),
537 ("type", FieldValue::Str(self.kind.clone())),
538 ],
539 "geo_bbox" => {
540 let mut v = vec![
541 ("max_lat", FieldValue::F64(self.max_lat)),
542 ("max_lon", FieldValue::F64(self.max_lon)),
543 ("min_lat", FieldValue::F64(self.min_lat)),
544 ("min_lon", FieldValue::F64(self.min_lon)),
545 ];
546 if self.min_alt_m != 0.0 || self.max_alt_m != 0.0 {
547 v.insert(0, ("max_alt_m", FieldValue::F64(self.max_alt_m)));
549 v.insert(3, ("min_alt_m", FieldValue::F64(self.min_alt_m)));
551 }
552 v.push(("type", FieldValue::Str(self.kind.clone())));
553 v
554 }
555 "time_window" => vec![
556 ("end", FieldValue::Str(self.end.clone())),
557 ("start", FieldValue::Str(self.start.clone())),
558 ("type", FieldValue::Str(self.kind.clone())),
559 ("tz", FieldValue::Str(self.tz.clone())),
560 ],
561 "max_speed_mps" => vec![
562 ("max_mps", FieldValue::F64(self.max_mps)),
563 ("type", FieldValue::Str(self.kind.clone())),
564 ],
565 "max_amount" => vec![
566 ("currency", FieldValue::Str(self.currency.clone())),
567 ("max_amount", FieldValue::F64(self.max_amount)),
568 ("type", FieldValue::Str(self.kind.clone())),
569 ],
570 "max_rate" => vec![
571 ("count", FieldValue::I64(self.count)),
572 ("type", FieldValue::Str(self.kind.clone())),
573 ("window_s", FieldValue::I64(self.window_s)),
574 ],
575 "resource_path" => {
576 if self.resource_id.is_empty() {
580 return Err(serde::ser::Error::custom(
581 "resource_path constraint requires a non-empty resource_id",
582 ));
583 }
584 let mut v = Vec::new();
585 if let Some(prefix) = &self.path_prefix {
586 v.push(("path_prefix", FieldValue::Str(prefix.clone())));
587 }
588 v.push(("resource_id", FieldValue::Str(self.resource_id.clone())));
589 v.push(("type", FieldValue::Str(self.kind.clone())));
590 v
591 }
592 _ => {
596 let mut v = Vec::new();
597 if let Some(params) = &self.params {
598 v.push(("params", FieldValue::Params(params.clone())));
599 }
600 v.push(("type", FieldValue::Str(self.kind.clone())));
601 v
602 }
603 };
604 let mut m = serializer.serialize_map(Some(entries.len()))?;
605 for (k, v) in entries {
606 match v {
607 FieldValue::F64(x) => m.serialize_entry(k, &x)?,
608 FieldValue::I64(x) => {
609 if !crate::canonical::wire_int::in_domain(x) {
611 return Err(serde::ser::Error::custom(
612 "integer outside the safe-integer range [-(2^53-1), 2^53-1]",
613 ));
614 }
615 m.serialize_entry(k, &x)?
616 }
617 FieldValue::Str(x) => m.serialize_entry(k, &x)?,
618 FieldValue::Points(x) => m.serialize_entry(k, &x)?,
619 FieldValue::Params(x) => m.serialize_entry(k, &x)?,
620 }
621 }
622 m.end()
623 }
624}
625
626enum FieldValue {
629 F64(f64),
630 I64(i64),
631 Str(String),
632 Points(Vec<[f64; 2]>),
633 Params(BTreeMap<String, ParamsValue>),
634}
635
636pub type InvocationCounter<'a> = Box<dyn Fn(&str, i64) -> i64 + 'a>;
641
642#[derive(Default)]
646pub struct VerifierContext<'a> {
647 pub current_lat: Option<f64>,
648 pub current_lon: Option<f64>,
649 pub current_alt_m: Option<f64>,
650 pub current_speed_mps: Option<f64>,
651 pub requested_amount: Option<f64>,
652 pub requested_currency: Option<String>,
653 pub invocations_in_window: Option<InvocationCounter<'a>>,
655 pub requested_resource_id: Option<String>,
659 pub requested_path: Option<String>,
664}
665
666#[derive(Debug, Clone, Serialize, Deserialize)]
674#[serde(deny_unknown_fields)]
675pub struct ProofBundle {
676 pub agent_id: String,
677 pub agent_pub_key: HybridPublicKey,
678 pub delegations: Vec<DelegationCert>,
679 #[serde(with = "crate::canonical::base64_bytes")]
680 pub challenge: Vec<u8>,
681 #[serde(
682 serialize_with = "crate::canonical::wire_int::serialize",
683 deserialize_with = "crate::canonical::wire_int::deserialize"
684 )]
685 pub challenge_at: i64,
686 pub challenge_sig: HybridSignature,
687 #[serde(
688 default,
689 skip_serializing_if = "Vec::is_empty",
690 with = "crate::canonical::base64_bytes"
691 )]
692 pub session_context: Vec<u8>,
693 #[serde(
694 default,
695 skip_serializing_if = "Vec::is_empty",
696 with = "crate::canonical::base64_bytes"
697 )]
698 pub stream_id: Vec<u8>,
699 #[serde(
700 default,
701 skip_serializing_if = "is_zero_i64",
702 serialize_with = "crate::canonical::wire_int::serialize",
703 deserialize_with = "crate::canonical::wire_int::deserialize"
704 )]
705 pub stream_seq: i64,
706}
707
708fn is_zero_i64(v: &i64) -> bool {
709 *v == 0
710}
711
712#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
716#[serde(rename_all = "snake_case")]
717pub enum IdentityStatus {
718 VerifiedHuman,
719 AuthorizedAgent,
720 Expired,
721 Revoked,
722 ScopeDenied,
723 ConstraintDenied,
724 ConstraintUnverifiable,
725 ConstraintUnknown,
726 DelegationNotAuthorized,
727 InvalidScope,
732 Invalid,
733 Unauthorized,
734}
735
736impl IdentityStatus {
737 pub fn as_str(&self) -> &'static str {
738 match self {
739 Self::VerifiedHuman => "verified_human",
740 Self::AuthorizedAgent => "authorized_agent",
741 Self::Expired => "expired",
742 Self::Revoked => "revoked",
743 Self::ScopeDenied => "scope_denied",
744 Self::ConstraintDenied => "constraint_denied",
745 Self::ConstraintUnverifiable => "constraint_unverifiable",
746 Self::ConstraintUnknown => "constraint_unknown",
747 Self::DelegationNotAuthorized => "delegation_not_authorized",
748 Self::InvalidScope => "invalid_scope",
749 Self::Invalid => "invalid",
750 Self::Unauthorized => "unauthorized",
751 }
752 }
753
754 pub fn from_wire(s: &str) -> Option<Self> {
757 Some(match s {
758 "verified_human" => Self::VerifiedHuman,
759 "authorized_agent" => Self::AuthorizedAgent,
760 "expired" => Self::Expired,
761 "revoked" => Self::Revoked,
762 "scope_denied" => Self::ScopeDenied,
763 "constraint_denied" => Self::ConstraintDenied,
764 "constraint_unverifiable" => Self::ConstraintUnverifiable,
765 "constraint_unknown" => Self::ConstraintUnknown,
766 "delegation_not_authorized" => Self::DelegationNotAuthorized,
767 "invalid_scope" => Self::InvalidScope,
768 "invalid" => Self::Invalid,
769 "unauthorized" => Self::Unauthorized,
770 _ => return None,
771 })
772 }
773}
774
775#[derive(Debug, Clone, Serialize, Deserialize)]
777pub struct VerifyResult {
778 pub valid: bool,
779 pub identity_status: IdentityStatus,
780 #[serde(skip_serializing_if = "String::is_empty", default)]
781 pub human_id: String,
782 #[serde(skip_serializing_if = "String::is_empty", default)]
783 pub agent_id: String,
784 #[serde(skip_serializing_if = "String::is_empty", default)]
785 pub agent_name: String,
786 #[serde(skip_serializing_if = "String::is_empty", default)]
787 pub agent_type: String,
788 #[serde(skip_serializing_if = "Vec::is_empty", default)]
789 pub granted_scope: Vec<String>,
790 #[serde(skip_serializing_if = "String::is_empty", default)]
791 pub error_reason: String,
792 #[serde(skip_serializing_if = "Option::is_none", default)]
797 pub anchor: Option<Anchor>,
798}
799
800#[derive(Debug, Clone, Serialize, Deserialize)]
802pub struct RevocationList {
803 pub issuer_id: String,
804 pub updated_at: i64,
805 pub revoked_certs: Vec<String>,
806 pub signature: HybridSignature,
807}
808
809#[derive(Debug, Clone, Serialize, Deserialize)]
811pub struct RevocationPush {
812 pub issuer_id: String,
813 pub seq_no: i64,
814 pub entries: Vec<String>,
815 pub pushed_at: i64,
816 pub signature: HybridSignature,
817}
818
819#[derive(Debug, Clone, Serialize, Deserialize)]
821pub struct WitnessEntry {
822 #[serde(with = "crate::canonical::base64_bytes")]
823 pub prev_hash: Vec<u8>,
824 #[serde(with = "crate::canonical::base64_bytes")]
825 pub entry_data: Vec<u8>,
826 pub timestamp: i64,
827 pub witness_id: String,
828 pub signature: HybridSignature,
829}
830
831#[derive(Debug, Clone, Serialize, Deserialize)]
835#[serde(deny_unknown_fields)]
836pub struct SessionToken {
837 pub version: i32,
838 pub session_id: String,
839 pub agent_id: String,
840 pub agent_pub_key: HybridPublicKey,
841 pub human_id: String,
842 pub granted_scope: Vec<String>,
843 #[serde(
844 serialize_with = "crate::canonical::wire_int::serialize",
845 deserialize_with = "crate::canonical::wire_int::deserialize"
846 )]
847 pub issued_at: i64,
848 #[serde(
849 serialize_with = "crate::canonical::wire_int::serialize",
850 deserialize_with = "crate::canonical::wire_int::deserialize"
851 )]
852 pub valid_until: i64,
853 #[serde(with = "crate::canonical::base64_bytes")]
854 pub chain_hash: Vec<u8>,
855 #[serde(with = "crate::canonical::base64_bytes")]
856 pub mac: Vec<u8>,
857}
858
859#[derive(Debug, Clone, Serialize, Deserialize)]
861pub struct TransactionReceipt {
862 pub version: i32,
863 pub transaction_id: String,
864 pub created_at: i64,
865 pub terms_schema_uri: String,
866 #[serde(with = "crate::canonical::base64_bytes")]
867 pub terms_canonical_json: Vec<u8>,
868 pub parties: Vec<ReceiptParty>,
869 pub party_signatures: Vec<ReceiptPartySignature>,
870}
871
872#[derive(Debug, Clone, Serialize, Deserialize)]
874pub struct ReceiptParty {
875 pub party_id: String,
876 pub role: String,
877 pub agent_id: String,
878 pub agent_pub_key: HybridPublicKey,
879 pub proof_bundle: ProofBundle,
880}
881
882#[derive(Debug, Clone, Serialize, Deserialize)]
884pub struct ReceiptPartySignature {
885 pub party_id: String,
886 pub signature: HybridSignature,
887}
888
889pub struct TransactionReceiptResult {
891 pub valid: bool,
892 pub error_reason: String,
893 pub party_results: Vec<VerifyResult>,
894}
895
896#[derive(Debug, Clone, Serialize, Deserialize)]
898pub struct KeyRotationStatement {
899 pub version: i32,
900 pub old_id: String,
901 pub old_pub_key: HybridPublicKey,
902 pub new_id: String,
903 pub new_pub_key: HybridPublicKey,
904 pub rotated_at: i64,
905 pub reason: String,
906 pub signature_old: HybridSignature,
907 pub signature_new: HybridSignature,
908}
909
910#[derive(Debug, Clone, Default)]
916pub struct StreamContext {
917 pub stream_id: Vec<u8>,
918 pub last_seen_seq: i64,
919}
920
921pub trait RevocationProvider {
929 fn is_revoked(&self, cert_id: &str) -> Result<bool, String>;
930}
931
932pub trait PolicyProvider {
938 fn evaluate_policy(
939 &self,
940 bundle: &ProofBundle,
941 context: &VerifierContext,
942 ) -> Result<bool, String>;
943}
944
945pub trait AuditProvider {
950 fn log_verification(&self, result: &VerifyResult, bundle: &ProofBundle);
951}
952
953pub trait ConstraintEvaluator {
962 fn evaluate(
963 &self,
964 constraint: &Constraint,
965 cert_id: &str,
966 context: &VerifierContext,
967 now: i64,
968 ) -> Result<(), String>;
969}
970
971pub trait AnchorResolver {
976 fn resolve_anchor(&self, human_id: &str) -> Result<Option<Anchor>, String>;
977}
978
979#[derive(Debug, Clone, Serialize, Deserialize)]
984pub struct PolicyVerdict {
985 pub version: i32,
986 pub verdict_id: String,
987 pub agent_id: String,
988 pub scope: String,
989 pub allow: bool,
990 #[serde(with = "crate::canonical::base64_bytes")]
991 pub context_hash: Vec<u8>, pub issued_at: i64,
993 pub valid_until: i64,
994 #[serde(with = "crate::canonical::base64_bytes")]
995 pub mac: Vec<u8>, }
997
998#[derive(Debug, Clone, Serialize, Deserialize)]
1005pub struct VerificationReceipt {
1006 pub version: i32,
1007 pub verifier_id: String,
1008 pub verifier_pub: HybridPublicKey,
1009 #[serde(with = "crate::canonical::base64_bytes")]
1010 pub bundle_hash: Vec<u8>, pub decision: String,
1012 #[serde(skip_serializing_if = "String::is_empty", default)]
1013 pub human_id: String,
1014 #[serde(skip_serializing_if = "String::is_empty", default)]
1015 pub agent_id: String,
1016 #[serde(skip_serializing_if = "Vec::is_empty", default)]
1017 pub granted_scope: Vec<String>,
1018 #[serde(skip_serializing_if = "String::is_empty", default)]
1019 pub error_reason: String,
1020 pub verified_at: i64,
1021 #[serde(with = "crate::canonical::base64_bytes")]
1022 pub prev_hash: Vec<u8>, pub signature: HybridSignature,
1024}
1025
1026pub struct VerifyOptions<'a> {
1028 pub required_scope: String,
1030 #[deprecated(since = "1.0.0-alpha.7", note = "use `revocation` (SPEC §17.1) instead")]
1037 #[allow(clippy::type_complexity)]
1039 pub is_revoked: Option<Box<dyn Fn(&str) -> bool + 'a>>,
1040 pub revocation: Option<Box<dyn RevocationProvider + 'a>>,
1043 pub force_revocation_check: bool,
1047 pub now: Option<i64>,
1049 pub session_context: Vec<u8>,
1051 pub stream: Option<StreamContext>,
1053 pub context: VerifierContext<'a>,
1057 pub policy: Option<Box<dyn PolicyProvider + 'a>>,
1061 pub audit: Option<Box<dyn AuditProvider + 'a>>,
1065 pub constraint_evaluators:
1069 Option<alloc::collections::BTreeMap<String, Box<dyn ConstraintEvaluator + 'a>>>,
1070 pub policy_verdict: Option<PolicyVerdict>,
1075 pub policy_secret: Option<Vec<u8>>,
1077 pub anchor_resolver: Option<Box<dyn AnchorResolver + 'a>>,
1081 pub challenge_store: Option<Box<dyn crate::challenge_store::ChallengeStore + 'a>>,
1091}
1092
1093#[allow(clippy::derivable_impls)]
1097impl<'a> Default for VerifyOptions<'a> {
1098 fn default() -> Self {
1099 #[allow(deprecated)]
1103 Self {
1104 required_scope: String::new(),
1105 is_revoked: None,
1106 revocation: None,
1107 force_revocation_check: false,
1108 now: None,
1109 session_context: Vec::new(),
1110 stream: None,
1111 context: VerifierContext::default(),
1112 policy: None,
1113 audit: None,
1114 constraint_evaluators: None,
1115 policy_verdict: None,
1116 policy_secret: None,
1117 anchor_resolver: None,
1118 challenge_store: None,
1119 }
1120 }
1121}