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)]
37pub struct HybridPublicKey {
38 #[serde(with = "crate::canonical::base64_bytes")]
39 pub ed25519: Vec<u8>, #[serde(with = "crate::canonical::base64_bytes")]
41 pub ml_dsa_65: Vec<u8>, }
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct HybridSignature {
49 #[serde(with = "crate::canonical::base64_bytes")]
50 pub ed25519: Vec<u8>, #[serde(with = "crate::canonical::base64_bytes")]
52 pub ml_dsa_65: Vec<u8>, }
54
55#[derive(Debug, Clone)]
57pub struct HybridPrivateKey {
58 pub ed25519: Vec<u8>, pub ml_dsa_65: Vec<u8>, }
61
62#[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#[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#[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#[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 #[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 pub fn is_no_expiry(&self) -> bool {
121 self.expires_at == NO_EXPIRY_SENTINEL
122 }
123}
124
125#[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
182impl Serialize for Constraint {
186 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
187 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 v.insert(0, ("max_alt_m", FieldValue::F64(self.max_alt_m)));
211 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 _ => 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
253enum FieldValue {
256 F64(f64),
257 I64(i64),
258 Str(String),
259 Points(Vec<[f64; 2]>),
260}
261
262pub type InvocationCounter<'a> = Box<dyn Fn(&str, i64) -> i64 + 'a>;
265
266#[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 pub invocations_in_window: Option<InvocationCounter<'a>>,
279}
280
281#[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#[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 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 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#[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 #[serde(skip_serializing_if = "Option::is_none", default)]
402 pub anchor: Option<Anchor>,
403}
404
405#[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#[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#[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#[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#[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
480pub struct ReceiptPartySignature {
481 pub party_id: String,
482 pub signature: HybridSignature,
483}
484
485pub struct TransactionReceiptResult {
487 pub valid: bool,
488 pub error_reason: String,
489 pub party_results: Vec<VerifyResult>,
490}
491
492#[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#[derive(Debug, Clone, Default)]
512pub struct StreamContext {
513 pub stream_id: Vec<u8>,
514 pub last_seen_seq: i64,
515}
516
517pub trait RevocationProvider {
525 fn is_revoked(&self, cert_id: &str) -> Result<bool, String>;
526}
527
528pub trait PolicyProvider {
534 fn evaluate_policy(
535 &self,
536 bundle: &ProofBundle,
537 context: &VerifierContext,
538 ) -> Result<bool, String>;
539}
540
541pub trait AuditProvider {
546 fn log_verification(&self, result: &VerifyResult, bundle: &ProofBundle);
547}
548
549pub 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
567pub trait AnchorResolver {
572 fn resolve_anchor(&self, human_id: &str) -> Result<Option<Anchor>, String>;
573}
574
575#[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>, pub issued_at: i64,
589 pub valid_until: i64,
590 #[serde(with = "crate::canonical::base64_bytes")]
591 pub mac: Vec<u8>, }
593
594#[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>, 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>, pub signature: HybridSignature,
620}
621
622pub struct VerifyOptions<'a> {
624 pub required_scope: String,
626 #[deprecated(since = "1.0.0-alpha.7", note = "use `revocation` (SPEC §17.1) instead")]
633 #[allow(clippy::type_complexity)]
635 pub is_revoked: Option<Box<dyn Fn(&str) -> bool + 'a>>,
636 pub revocation: Option<Box<dyn RevocationProvider + 'a>>,
639 pub force_revocation_check: bool,
643 pub now: Option<i64>,
645 pub session_context: Vec<u8>,
647 pub stream: Option<StreamContext>,
649 pub context: VerifierContext<'a>,
653 pub policy: Option<Box<dyn PolicyProvider + 'a>>,
657 pub audit: Option<Box<dyn AuditProvider + 'a>>,
661 pub constraint_evaluators:
665 Option<alloc::collections::BTreeMap<String, Box<dyn ConstraintEvaluator + 'a>>>,
666 pub policy_verdict: Option<PolicyVerdict>,
671 pub policy_secret: Option<Vec<u8>>,
673 pub anchor_resolver: Option<Box<dyn AnchorResolver + 'a>>,
677}
678
679#[allow(clippy::derivable_impls)]
683impl<'a> Default for VerifyOptions<'a> {
684 fn default() -> Self {
685 #[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}