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
262#[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 pub invocations_in_window: Option<Box<dyn Fn(&str, i64) -> i64 + 'a>>,
275}
276
277#[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#[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 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 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#[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 #[serde(skip_serializing_if = "Option::is_none", default)]
398 pub anchor: Option<Anchor>,
399}
400
401#[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#[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#[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#[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#[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
476pub struct ReceiptPartySignature {
477 pub party_id: String,
478 pub signature: HybridSignature,
479}
480
481pub struct TransactionReceiptResult {
483 pub valid: bool,
484 pub error_reason: String,
485 pub party_results: Vec<VerifyResult>,
486}
487
488#[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#[derive(Debug, Clone, Default)]
508pub struct StreamContext {
509 pub stream_id: Vec<u8>,
510 pub last_seen_seq: i64,
511}
512
513pub trait RevocationProvider {
521 fn is_revoked(&self, cert_id: &str) -> Result<bool, String>;
522}
523
524pub trait PolicyProvider {
530 fn evaluate_policy(
531 &self,
532 bundle: &ProofBundle,
533 context: &VerifierContext,
534 ) -> Result<bool, String>;
535}
536
537pub trait AuditProvider {
542 fn log_verification(&self, result: &VerifyResult, bundle: &ProofBundle);
543}
544
545pub 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
563pub trait AnchorResolver {
568 fn resolve_anchor(&self, human_id: &str) -> Result<Option<Anchor>, String>;
569}
570
571#[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>, pub issued_at: i64,
585 pub valid_until: i64,
586 #[serde(with = "crate::canonical::base64_bytes")]
587 pub mac: Vec<u8>, }
589
590#[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>, 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>, pub signature: HybridSignature,
616}
617
618pub struct VerifyOptions<'a> {
620 pub required_scope: String,
622 #[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 pub revocation: Option<Box<dyn RevocationProvider + 'a>>,
633 pub force_revocation_check: bool,
637 pub now: Option<i64>,
639 pub session_context: Vec<u8>,
641 pub stream: Option<StreamContext>,
643 pub context: VerifierContext<'a>,
647 pub policy: Option<Box<dyn PolicyProvider + 'a>>,
651 pub audit: Option<Box<dyn AuditProvider + 'a>>,
655 pub constraint_evaluators:
659 Option<alloc::collections::BTreeMap<String, Box<dyn ConstraintEvaluator + 'a>>>,
660 pub policy_verdict: Option<PolicyVerdict>,
665 pub policy_secret: Option<Vec<u8>>,
667 pub anchor_resolver: Option<Box<dyn AnchorResolver + 'a>>,
671}
672
673impl<'a> Default for VerifyOptions<'a> {
674 fn default() -> Self {
675 #[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}