1use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::collections::BTreeMap;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21pub enum Reason {
22 Ok,
23 BadAuthoritySignature,
24 BadInvocationSignature,
25 SubjectMismatch,
26 CapabilityMismatch,
27 ResourceMismatch,
28 ValueLimitExceeded,
29 TotalLimitExceeded,
30 CurrencyMismatch,
31 Expired,
32 NotYetValid,
33 MaxUsesExceeded,
34 AudienceMismatch,
35 NonceReplay,
36 Revoked,
37 RevocationStale,
38 OfflineValueExceeded,
39 ForbiddenCapability,
40 HumanConfirmationRequired,
41 DelegationNotSubset,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum Decision {
46 Allow,
47 Deny,
48}
49
50#[derive(Debug, Clone)]
51pub struct BorderResult {
52 pub decision: Decision,
53 pub reason: Reason,
54 pub receipt: Option<String>,
56}
57
58impl BorderResult {
59 fn deny(reason: Reason) -> Self {
60 BorderResult { decision: Decision::Deny, reason, receipt: None }
61 }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
69#[serde(deny_unknown_fields)]
70pub struct Scope {
71 pub currency: Option<String>,
72 #[serde(default)]
73 pub max_per_action: f64,
74 #[serde(default)]
75 pub max_total: f64,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize)]
79#[serde(deny_unknown_fields)]
80pub struct Constraints {
81 pub not_before: i64,
83 pub expires: i64,
85 pub max_uses: u64,
86 pub require_human_confirmation: bool,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
92#[serde(deny_unknown_fields)]
93pub struct Delegation {
94 #[serde(default)]
95 pub allowed: bool,
96 #[serde(default)]
97 pub max_depth: u32,
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct Revocation {
103 pub method: String,
105 pub id: String,
106 pub freshness_required_sec: i64,
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
111#[serde(deny_unknown_fields)]
112pub struct AuthorityObject {
113 pub issuer: String,
114 pub subject: String,
115 pub capability: String,
116 pub resource: String,
117 pub scope: Scope,
118 pub constraints: Constraints,
119 pub delegation: Delegation,
120 pub revocation: Revocation,
121 pub issuer_pub: String,
123 pub sig: String,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
128#[serde(deny_unknown_fields)]
129pub struct Invocation {
130 pub authority_id: String,
131 pub invocation_id: String,
132 pub subject: String,
133 pub capability: String,
134 pub resource: String,
135 #[serde(default)]
136 pub amount: f64,
137 pub currency: Option<String>,
138 pub audience: String,
139 pub nonce: String,
140 pub created: i64,
141 #[serde(default)]
143 pub human_confirmed: bool,
144 pub subject_pub: String,
146 pub sig: String,
147}
148
149#[derive(Debug, Clone, Default)]
151pub struct VerifierState {
152 pub now: i64,
153 pub audience: String,
154 pub online: bool,
155 pub revocation_age_sec: i64,
156 pub revoked_ids: std::collections::BTreeSet<String>,
157 pub used_nonces: std::collections::BTreeSet<String>,
158 pub uses: BTreeMap<String, u64>,
160 pub spent_total: BTreeMap<String, f64>,
162 pub offline_limit: f64,
164}
165
166pub const FORBIDDEN_CAPS: &[&str] = &[
171 "export-root-key",
172 "export-recovery-secret",
173 "disable-audit",
174 "grant-beyond-owner",
175 "rewrite-history",
176];
177
178pub fn canonical_authority(a: &AuthorityObject) -> String {
187 format!(
188 "ECHO-AUTHORITY\nv0.1\n{}\n{}\n{}\n{}\n{}|{}|{}\n{}|{}|{}|{}\n{}|{}\n{}|{}|{}",
189 a.issuer,
190 a.subject,
191 a.capability,
192 a.resource,
193 a.scope.currency.clone().unwrap_or_default(),
194 a.scope.max_per_action,
195 a.scope.max_total,
196 a.constraints.not_before,
197 a.constraints.expires,
198 a.constraints.max_uses,
199 a.constraints.require_human_confirmation,
200 a.delegation.allowed,
201 a.delegation.max_depth,
202 a.revocation.method,
203 a.revocation.id,
204 a.revocation.freshness_required_sec,
205 )
206}
207
208pub fn canonical_invocation(i: &Invocation) -> String {
209 format!(
210 "ECHO-INVOCATION\nv0.1\n{}\n{}\n{}\n{}\n{}\n{}|{}\n{}\n{}\n{}",
211 i.authority_id,
212 i.invocation_id,
213 i.subject,
214 i.capability,
215 i.resource,
216 i.amount,
217 i.currency.clone().unwrap_or_default(),
218 i.audience,
219 i.nonce,
220 i.created,
221 )
222}
223
224fn verify_sig(msg: &str, pub_b64: &str, sig_b64: &str) -> bool {
225 use ed25519_dalek::{Signature, VerifyingKey};
226 let pub_bytes = match base64_decode(pub_b64) {
227 Some(b) if b.len() == 32 => b,
228 _ => return false,
229 };
230 let sig_bytes = match base64_decode(sig_b64) {
231 Some(b) if b.len() == 64 => b,
232 _ => return false,
233 };
234 let mut pk = [0u8; 32];
235 pk.copy_from_slice(&pub_bytes);
236 let vk = match VerifyingKey::from_bytes(&pk) {
237 Ok(k) => k,
238 Err(_) => return false,
239 };
240 let mut sg = [0u8; 64];
241 sg.copy_from_slice(&sig_bytes);
242 let sig = Signature::from_bytes(&sg);
243 vk.verify_strict(msg.as_bytes(), &sig).is_ok()
245}
246
247fn receipt_head(a: &AuthorityObject, i: &Invocation) -> String {
249 let mut h = Sha256::new();
250 h.update(
251 format!(
252 "ECHO-RECEIPT\n{}\n{}\n{}\n{}\n{}\n{}",
253 a.issuer, i.subject, i.capability, i.resource, i.amount, i.invocation_id
254 )
255 .as_bytes(),
256 );
257 hex::encode(h.finalize())
258}
259
260pub fn resource_is_concrete(resource: &str) -> bool {
272 !resource.is_empty()
273 && !resource.contains('*')
274 && !resource.split('/').any(|seg| seg.is_empty() || seg == "." || seg == "..")
275}
276
277pub fn resource_within(child: &str, parent: &str) -> bool {
278 if child.split('/').any(|seg| seg == "." || seg == "..") {
279 return false;
280 }
281 if child == parent {
282 return true;
283 }
284 if let Some(prefix) = parent.strip_suffix('*') {
285 return child.starts_with(prefix);
286 }
287 if let Some(prefix) = parent.strip_suffix('/') {
288 return child.starts_with(prefix);
289 }
290 child.starts_with(&format!("{parent}/"))
291}
292
293pub fn border_check(
301 authority: &AuthorityObject,
302 invocation: &Invocation,
303 state: &VerifierState,
304) -> BorderResult {
305 if !verify_sig(&canonical_authority(authority), &authority.issuer_pub, &authority.sig) {
307 return BorderResult::deny(Reason::BadAuthoritySignature);
308 }
309 if !verify_sig(&canonical_invocation(invocation), &invocation.subject_pub, &invocation.sig) {
310 return BorderResult::deny(Reason::BadInvocationSignature);
311 }
312
313 if invocation.subject != authority.subject {
315 return BorderResult::deny(Reason::SubjectMismatch);
316 }
317
318 if invocation.capability != authority.capability {
320 return BorderResult::deny(Reason::CapabilityMismatch);
321 }
322
323 if !resource_is_concrete(&invocation.resource) {
326 return BorderResult::deny(Reason::ResourceMismatch);
327 }
328 if !resource_within(&invocation.resource, &authority.resource) {
329 return BorderResult::deny(Reason::ResourceMismatch);
330 }
331
332 let finite_non_negative = |v: f64| v.is_finite() && v >= 0.0;
336 if !finite_non_negative(invocation.amount)
337 || !finite_non_negative(authority.scope.max_per_action)
338 || !finite_non_negative(authority.scope.max_total)
339 {
340 return BorderResult::deny(Reason::ValueLimitExceeded);
343 }
344 if invocation.amount > 0.0 {
345 if authority.scope.currency != invocation.currency {
346 return BorderResult::deny(Reason::CurrencyMismatch);
347 }
348 if invocation.amount > authority.scope.max_per_action {
349 return BorderResult::deny(Reason::ValueLimitExceeded);
350 }
351 let already = *state.spent_total.get(&invocation.authority_id).unwrap_or(&0.0);
352 if !finite_non_negative(already) {
353 return BorderResult::deny(Reason::TotalLimitExceeded);
354 }
355 if already + invocation.amount > authority.scope.max_total {
356 return BorderResult::deny(Reason::TotalLimitExceeded);
357 }
358 }
359
360 if state.now < authority.constraints.not_before {
362 return BorderResult::deny(Reason::NotYetValid);
363 }
364 if state.now >= authority.constraints.expires {
365 return BorderResult::deny(Reason::Expired);
366 }
367
368 let used = *state.uses.get(&invocation.authority_id).unwrap_or(&0);
370 if used >= authority.constraints.max_uses {
371 return BorderResult::deny(Reason::MaxUsesExceeded);
372 }
373
374 if invocation.audience != state.audience {
376 return BorderResult::deny(Reason::AudienceMismatch);
377 }
378
379 if state.used_nonces.contains(&invocation.nonce) {
381 return BorderResult::deny(Reason::NonceReplay);
382 }
383
384 if state.revoked_ids.contains(&authority.revocation.id) {
386 return BorderResult::deny(Reason::Revoked);
387 }
388 if !state.online {
389 if state.revocation_age_sec > authority.revocation.freshness_required_sec {
390 return BorderResult::deny(Reason::RevocationStale);
391 }
392 if invocation.amount > state.offline_limit {
393 return BorderResult::deny(Reason::OfflineValueExceeded);
394 }
395 }
396
397 if FORBIDDEN_CAPS.contains(&authority.capability.as_str()) {
399 return BorderResult::deny(Reason::ForbiddenCapability);
400 }
401
402 if authority.constraints.require_human_confirmation && !invocation.human_confirmed {
404 return BorderResult::deny(Reason::HumanConfirmationRequired);
405 }
406
407 BorderResult { decision: Decision::Allow, reason: Reason::Ok, receipt: Some(receipt_head(authority, invocation)) }
408}
409
410#[derive(Debug, Clone)]
415pub struct AttenuationResult {
416 pub ok: bool,
417 pub violations: Vec<String>,
418}
419
420pub fn check_attenuation(child: &AuthorityObject, parent: &AuthorityObject) -> AttenuationResult {
421 let mut v = Vec::new();
422
423 if !parent.delegation.allowed {
424 v.push("parent does not permit delegation".into());
425 }
426 if parent.delegation.max_depth == 0 {
427 v.push("parent delegation depth is exhausted".into());
428 }
429 if child.capability != parent.capability {
430 v.push("capability must equal the parent capability".into());
431 }
432 if !resource_within(&child.resource, &parent.resource) {
433 v.push("resource is not within the parent resource".into());
434 }
435 if child.scope.max_per_action > parent.scope.max_per_action {
436 v.push("scope.max_per_action exceeds parent".into());
437 }
438 if child.scope.max_total > parent.scope.max_total {
439 v.push("scope.max_total exceeds parent".into());
440 }
441 if child.scope.currency != parent.scope.currency {
442 v.push("scope.currency differs from parent".into());
443 }
444 if child.constraints.not_before < parent.constraints.not_before {
445 v.push("child not_before is earlier than parent".into());
446 }
447 if parent.constraints.require_human_confirmation && !child.constraints.require_human_confirmation {
448 v.push("child drops the parent's human-confirmation requirement".into());
449 }
450 if child.revocation.freshness_required_sec > parent.revocation.freshness_required_sec {
451 v.push("child loosens revocation freshness".into());
452 }
453 if child.delegation.allowed && !parent.delegation.allowed {
454 v.push("child permits delegation the parent does not".into());
455 }
456 if child.constraints.expires > parent.constraints.expires {
457 v.push("child expiry is later than parent".into());
458 }
459 if child.constraints.max_uses > parent.constraints.max_uses {
460 v.push("child max_uses exceeds parent".into());
461 }
462 if child.delegation.max_depth >= parent.delegation.max_depth {
463 v.push("child delegation depth is not strictly less than parent".into());
464 }
465
466 AttenuationResult { ok: v.is_empty(), violations: v }
467}
468
469fn base64_decode(s: &str) -> Option<Vec<u8>> {
474 const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
475 let mut lookup = [255u8; 256];
476 for (i, &c) in ALPHABET.iter().enumerate() {
477 lookup[c as usize] = i as u8;
478 }
479 let mut out = Vec::new();
480 let mut buf = 0u32;
481 let mut bits = 0u32;
482 for &c in s.as_bytes() {
483 if c == b'=' || c == b'\n' || c == b'\r' {
484 continue;
485 }
486 let val = lookup[c as usize];
487 if val == 255 {
488 return None;
489 }
490 buf = (buf << 6) | val as u32;
491 bits += 6;
492 if bits >= 8 {
493 bits -= 8;
494 out.push((buf >> bits) as u8);
495 }
496 }
497 Some(out)
498}
499
500pub fn reason_str(r: Reason) -> &'static str {
511 match r {
512 Reason::Ok => "OK",
513 Reason::BadAuthoritySignature => "BAD_AUTHORITY_SIGNATURE",
514 Reason::BadInvocationSignature => "BAD_INVOCATION_SIGNATURE",
515 Reason::SubjectMismatch => "SUBJECT_MISMATCH",
516 Reason::CapabilityMismatch => "CAPABILITY_MISMATCH",
517 Reason::ResourceMismatch => "RESOURCE_MISMATCH",
518 Reason::ValueLimitExceeded => "VALUE_LIMIT_EXCEEDED",
519 Reason::TotalLimitExceeded => "TOTAL_LIMIT_EXCEEDED",
520 Reason::CurrencyMismatch => "CURRENCY_MISMATCH",
521 Reason::Expired => "EXPIRED",
522 Reason::NotYetValid => "NOT_YET_VALID",
523 Reason::MaxUsesExceeded => "MAX_USES_EXCEEDED",
524 Reason::AudienceMismatch => "AUDIENCE_MISMATCH",
525 Reason::NonceReplay => "NONCE_REPLAY",
526 Reason::Revoked => "REVOKED",
527 Reason::RevocationStale => "REVOCATION_STALE",
528 Reason::OfflineValueExceeded => "OFFLINE_VALUE_EXCEEDED",
529 Reason::ForbiddenCapability => "FORBIDDEN_CAPABILITY",
530 Reason::HumanConfirmationRequired => "HUMAN_CONFIRMATION_REQUIRED",
531 Reason::DelegationNotSubset => "DELEGATION_NOT_SUBSET",
532 }
533}
534
535#[derive(serde::Deserialize)]
536#[serde(deny_unknown_fields)]
537struct StateWire {
538 now: i64,
539 audience: String,
540 #[serde(default)]
541 online: bool,
542 #[serde(default)]
543 revocation_age_sec: i64,
544 #[serde(default)]
545 revoked_ids: Vec<String>,
546 #[serde(default)]
547 used_nonces: Vec<String>,
548 #[serde(default)]
549 uses: BTreeMap<String, u64>,
550 #[serde(default)]
551 spent_total: BTreeMap<String, f64>,
552 #[serde(default)]
553 offline_limit: f64,
554}
555
556#[derive(serde::Deserialize)]
557#[serde(deny_unknown_fields)]
558struct RequestWire {
559 authority: AuthorityObject,
560 invocation: Invocation,
561 state: StateWire,
562}
563
564pub struct JsonVerdict {
566 pub json: String,
567 pub allow: bool,
568}
569
570pub fn evaluate_json(input: &str) -> JsonVerdict {
573 let req: RequestWire = match serde_json::from_str(input) {
574 Ok(r) => r,
575 Err(_) => {
576 return JsonVerdict {
577 json: "{\"decision\":\"DENY\",\"reason\":\"MALFORMED_REQUEST\",\"receipt\":null}"
578 .to_string(),
579 allow: false,
580 };
581 }
582 };
583
584 let state = VerifierState {
585 now: req.state.now,
586 audience: req.state.audience,
587 online: req.state.online,
588 revocation_age_sec: req.state.revocation_age_sec,
589 revoked_ids: req.state.revoked_ids.into_iter().collect(),
590 used_nonces: req.state.used_nonces.into_iter().collect(),
591 uses: req.state.uses,
592 spent_total: req.state.spent_total,
593 offline_limit: req.state.offline_limit,
594 };
595
596 let result = border_check(&req.authority, &req.invocation, &state);
597 let allow = result.decision == Decision::Allow;
598 let decision = if allow { "ALLOW" } else { "DENY" };
599 let receipt = match &result.receipt {
600 Some(h) => format!("\"{h}\""),
601 None => "null".to_string(),
602 };
603 let json = format!(
604 "{{\"decision\":\"{}\",\"reason\":\"{}\",\"receipt\":{}}}",
605 decision,
606 reason_str(result.reason),
607 receipt
608 );
609 JsonVerdict { json, allow }
610}