1#[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
14pub 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#[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>, #[serde(with = "crate::canonical::base64_bytes")]
42 pub ml_dsa_65: Vec<u8>, }
44
45#[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>, #[serde(with = "crate::canonical::base64_bytes")]
54 pub ml_dsa_65: Vec<u8>, }
56
57#[derive(Debug, Clone)]
59pub struct HybridPrivateKey {
60 pub ed25519: Vec<u8>, pub ml_dsa_65: Vec<u8>, }
63
64#[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#[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#[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#[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 #[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 pub fn is_no_expiry(&self) -> bool {
132 self.expires_at == NO_EXPIRY_SENTINEL
133 }
134}
135
136#[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
202impl Serialize for Constraint {
206 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
207 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 v.insert(0, ("max_alt_m", FieldValue::F64(self.max_alt_m)));
231 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 _ => 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 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
281enum FieldValue {
284 F64(f64),
285 I64(i64),
286 Str(String),
287 Points(Vec<[f64; 2]>),
288}
289
290pub type InvocationCounter<'a> = Box<dyn Fn(&str, i64) -> i64 + 'a>;
293
294#[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 pub invocations_in_window: Option<InvocationCounter<'a>>,
307}
308
309#[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#[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 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 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#[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 #[serde(skip_serializing_if = "Option::is_none", default)]
440 pub anchor: Option<Anchor>,
441}
442
443#[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#[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#[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#[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#[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
527pub struct ReceiptPartySignature {
528 pub party_id: String,
529 pub signature: HybridSignature,
530}
531
532pub struct TransactionReceiptResult {
534 pub valid: bool,
535 pub error_reason: String,
536 pub party_results: Vec<VerifyResult>,
537}
538
539#[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#[derive(Debug, Clone, Default)]
559pub struct StreamContext {
560 pub stream_id: Vec<u8>,
561 pub last_seen_seq: i64,
562}
563
564pub trait RevocationProvider {
572 fn is_revoked(&self, cert_id: &str) -> Result<bool, String>;
573}
574
575pub trait PolicyProvider {
581 fn evaluate_policy(
582 &self,
583 bundle: &ProofBundle,
584 context: &VerifierContext,
585 ) -> Result<bool, String>;
586}
587
588pub trait AuditProvider {
593 fn log_verification(&self, result: &VerifyResult, bundle: &ProofBundle);
594}
595
596pub 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
614pub trait AnchorResolver {
619 fn resolve_anchor(&self, human_id: &str) -> Result<Option<Anchor>, String>;
620}
621
622#[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>, pub issued_at: i64,
636 pub valid_until: i64,
637 #[serde(with = "crate::canonical::base64_bytes")]
638 pub mac: Vec<u8>, }
640
641#[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>, 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>, pub signature: HybridSignature,
667}
668
669pub struct VerifyOptions<'a> {
671 pub required_scope: String,
673 #[deprecated(since = "1.0.0-alpha.7", note = "use `revocation` (SPEC §17.1) instead")]
680 #[allow(clippy::type_complexity)]
682 pub is_revoked: Option<Box<dyn Fn(&str) -> bool + 'a>>,
683 pub revocation: Option<Box<dyn RevocationProvider + 'a>>,
686 pub force_revocation_check: bool,
690 pub now: Option<i64>,
692 pub session_context: Vec<u8>,
694 pub stream: Option<StreamContext>,
696 pub context: VerifierContext<'a>,
700 pub policy: Option<Box<dyn PolicyProvider + 'a>>,
704 pub audit: Option<Box<dyn AuditProvider + 'a>>,
708 pub constraint_evaluators:
712 Option<alloc::collections::BTreeMap<String, Box<dyn ConstraintEvaluator + 'a>>>,
713 pub policy_verdict: Option<PolicyVerdict>,
718 pub policy_secret: Option<Vec<u8>>,
720 pub anchor_resolver: Option<Box<dyn AnchorResolver + 'a>>,
724 pub challenge_store: Option<Box<dyn crate::challenge_store::ChallengeStore + 'a>>,
734}
735
736#[allow(clippy::derivable_impls)]
740impl<'a> Default for VerifyOptions<'a> {
741 fn default() -> Self {
742 #[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}