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)]
69pub struct Scope {
70 pub currency: Option<String>,
71 #[serde(default)]
72 pub max_per_action: f64,
73 #[serde(default)]
74 pub max_total: f64,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct Constraints {
79 pub not_before: i64,
81 pub expires: i64,
83 pub max_uses: u64,
84 #[serde(default)]
86 pub require_human_confirmation: bool,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct Delegation {
91 #[serde(default)]
92 pub allowed: bool,
93 #[serde(default)]
94 pub max_depth: u32,
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Revocation {
99 pub method: String,
101 pub id: String,
102 pub freshness_required_sec: i64,
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct AuthorityObject {
108 pub issuer: String,
109 pub subject: String,
110 pub capability: String,
111 pub resource: String,
112 pub scope: Scope,
113 pub constraints: Constraints,
114 pub delegation: Delegation,
115 pub revocation: Revocation,
116 pub issuer_pub: String,
118 pub sig: String,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct Invocation {
124 pub authority_id: String,
125 pub invocation_id: String,
126 pub subject: String,
127 pub capability: String,
128 pub resource: String,
129 #[serde(default)]
130 pub amount: f64,
131 pub currency: Option<String>,
132 pub audience: String,
133 pub nonce: String,
134 pub created: i64,
135 #[serde(default)]
137 pub human_confirmed: bool,
138 pub subject_pub: String,
140 pub sig: String,
141}
142
143#[derive(Debug, Clone, Default)]
145pub struct VerifierState {
146 pub now: i64,
147 pub audience: String,
148 pub online: bool,
149 pub revocation_age_sec: i64,
150 pub revoked_ids: std::collections::BTreeSet<String>,
151 pub used_nonces: std::collections::BTreeSet<String>,
152 pub uses: BTreeMap<String, u64>,
154 pub spent_total: BTreeMap<String, f64>,
156 pub offline_limit: f64,
158}
159
160pub const FORBIDDEN_CAPS: &[&str] = &[
165 "export-root-key",
166 "export-recovery-secret",
167 "disable-audit",
168 "grant-beyond-owner",
169 "rewrite-history",
170];
171
172pub fn canonical_authority(a: &AuthorityObject) -> String {
181 format!(
182 "ECHO-AUTHORITY\nv0.1\n{}\n{}\n{}\n{}\n{}|{}|{}\n{}|{}|{}|{}\n{}|{}\n{}|{}|{}",
183 a.issuer,
184 a.subject,
185 a.capability,
186 a.resource,
187 a.scope.currency.clone().unwrap_or_default(),
188 a.scope.max_per_action,
189 a.scope.max_total,
190 a.constraints.not_before,
191 a.constraints.expires,
192 a.constraints.max_uses,
193 a.constraints.require_human_confirmation,
194 a.delegation.allowed,
195 a.delegation.max_depth,
196 a.revocation.method,
197 a.revocation.id,
198 a.revocation.freshness_required_sec,
199 )
200}
201
202pub fn canonical_invocation(i: &Invocation) -> String {
203 format!(
204 "ECHO-INVOCATION\nv0.1\n{}\n{}\n{}\n{}\n{}\n{}|{}\n{}\n{}\n{}",
205 i.authority_id,
206 i.invocation_id,
207 i.subject,
208 i.capability,
209 i.resource,
210 i.amount,
211 i.currency.clone().unwrap_or_default(),
212 i.audience,
213 i.nonce,
214 i.created,
215 )
216}
217
218fn verify_sig(msg: &str, pub_b64: &str, sig_b64: &str) -> bool {
219 use ed25519_dalek::{Signature, Verifier, VerifyingKey};
220 let pub_bytes = match base64_decode(pub_b64) {
221 Some(b) if b.len() == 32 => b,
222 _ => return false,
223 };
224 let sig_bytes = match base64_decode(sig_b64) {
225 Some(b) if b.len() == 64 => b,
226 _ => return false,
227 };
228 let mut pk = [0u8; 32];
229 pk.copy_from_slice(&pub_bytes);
230 let vk = match VerifyingKey::from_bytes(&pk) {
231 Ok(k) => k,
232 Err(_) => return false,
233 };
234 let mut sg = [0u8; 64];
235 sg.copy_from_slice(&sig_bytes);
236 let sig = Signature::from_bytes(&sg);
237 vk.verify(msg.as_bytes(), &sig).is_ok()
238}
239
240fn receipt_head(a: &AuthorityObject, i: &Invocation) -> String {
242 let mut h = Sha256::new();
243 h.update(
244 format!(
245 "ECHO-RECEIPT\n{}\n{}\n{}\n{}\n{}\n{}",
246 a.issuer, i.subject, i.capability, i.resource, i.amount, i.invocation_id
247 )
248 .as_bytes(),
249 );
250 hex::encode(h.finalize())
251}
252
253pub fn resource_within(child: &str, parent: &str) -> bool {
261 if child == parent {
262 return true;
263 }
264 if let Some(prefix) = parent.strip_suffix('*') {
265 return child.starts_with(prefix);
266 }
267 if let Some(prefix) = parent.strip_suffix('/') {
268 return child.starts_with(prefix);
269 }
270 child.starts_with(&format!("{parent}/"))
271}
272
273pub fn border_check(
281 authority: &AuthorityObject,
282 invocation: &Invocation,
283 state: &VerifierState,
284) -> BorderResult {
285 if !verify_sig(&canonical_authority(authority), &authority.issuer_pub, &authority.sig) {
287 return BorderResult::deny(Reason::BadAuthoritySignature);
288 }
289 if !verify_sig(&canonical_invocation(invocation), &invocation.subject_pub, &invocation.sig) {
290 return BorderResult::deny(Reason::BadInvocationSignature);
291 }
292
293 if invocation.subject != authority.subject {
295 return BorderResult::deny(Reason::SubjectMismatch);
296 }
297
298 if invocation.capability != authority.capability {
300 return BorderResult::deny(Reason::CapabilityMismatch);
301 }
302
303 if !resource_within(&invocation.resource, &authority.resource) {
305 return BorderResult::deny(Reason::ResourceMismatch);
306 }
307
308 if invocation.amount > 0.0 {
310 if authority.scope.currency != invocation.currency {
311 return BorderResult::deny(Reason::CurrencyMismatch);
312 }
313 if invocation.amount > authority.scope.max_per_action {
314 return BorderResult::deny(Reason::ValueLimitExceeded);
315 }
316 let already = *state.spent_total.get(&invocation.authority_id).unwrap_or(&0.0);
317 if already + invocation.amount > authority.scope.max_total {
318 return BorderResult::deny(Reason::TotalLimitExceeded);
319 }
320 }
321
322 if state.now < authority.constraints.not_before {
324 return BorderResult::deny(Reason::NotYetValid);
325 }
326 if state.now >= authority.constraints.expires {
327 return BorderResult::deny(Reason::Expired);
328 }
329
330 let used = *state.uses.get(&invocation.authority_id).unwrap_or(&0);
332 if used >= authority.constraints.max_uses {
333 return BorderResult::deny(Reason::MaxUsesExceeded);
334 }
335
336 if invocation.audience != state.audience {
338 return BorderResult::deny(Reason::AudienceMismatch);
339 }
340
341 if state.used_nonces.contains(&invocation.nonce) {
343 return BorderResult::deny(Reason::NonceReplay);
344 }
345
346 if state.revoked_ids.contains(&authority.revocation.id) {
348 return BorderResult::deny(Reason::Revoked);
349 }
350 if !state.online {
351 if state.revocation_age_sec > authority.revocation.freshness_required_sec {
352 return BorderResult::deny(Reason::RevocationStale);
353 }
354 if invocation.amount > state.offline_limit {
355 return BorderResult::deny(Reason::OfflineValueExceeded);
356 }
357 }
358
359 if FORBIDDEN_CAPS.contains(&authority.capability.as_str()) {
361 return BorderResult::deny(Reason::ForbiddenCapability);
362 }
363
364 if authority.constraints.require_human_confirmation && !invocation.human_confirmed {
366 return BorderResult::deny(Reason::HumanConfirmationRequired);
367 }
368
369 BorderResult { decision: Decision::Allow, reason: Reason::Ok, receipt: Some(receipt_head(authority, invocation)) }
370}
371
372#[derive(Debug, Clone)]
377pub struct AttenuationResult {
378 pub ok: bool,
379 pub violations: Vec<String>,
380}
381
382pub fn check_attenuation(child: &AuthorityObject, parent: &AuthorityObject) -> AttenuationResult {
383 let mut v = Vec::new();
384
385 if !parent.delegation.allowed {
386 v.push("parent does not permit delegation".into());
387 }
388 if parent.delegation.max_depth == 0 {
389 v.push("parent delegation depth is exhausted".into());
390 }
391 if child.capability != parent.capability {
392 v.push("capability must equal the parent capability".into());
393 }
394 if !resource_within(&child.resource, &parent.resource) {
395 v.push("resource is not within the parent resource".into());
396 }
397 if child.scope.max_per_action > parent.scope.max_per_action {
398 v.push("scope.max_per_action exceeds parent".into());
399 }
400 if child.scope.max_total > parent.scope.max_total {
401 v.push("scope.max_total exceeds parent".into());
402 }
403 if child.scope.currency != parent.scope.currency {
404 v.push("scope.currency differs from parent".into());
405 }
406 if child.constraints.expires > parent.constraints.expires {
407 v.push("child expiry is later than parent".into());
408 }
409 if child.constraints.max_uses > parent.constraints.max_uses {
410 v.push("child max_uses exceeds parent".into());
411 }
412 if child.delegation.max_depth >= parent.delegation.max_depth {
413 v.push("child delegation depth is not strictly less than parent".into());
414 }
415
416 AttenuationResult { ok: v.is_empty(), violations: v }
417}
418
419fn base64_decode(s: &str) -> Option<Vec<u8>> {
424 const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
425 let mut lookup = [255u8; 256];
426 for (i, &c) in ALPHABET.iter().enumerate() {
427 lookup[c as usize] = i as u8;
428 }
429 let mut out = Vec::new();
430 let mut buf = 0u32;
431 let mut bits = 0u32;
432 for &c in s.as_bytes() {
433 if c == b'=' || c == b'\n' || c == b'\r' {
434 continue;
435 }
436 let val = lookup[c as usize];
437 if val == 255 {
438 return None;
439 }
440 buf = (buf << 6) | val as u32;
441 bits += 6;
442 if bits >= 8 {
443 bits -= 8;
444 out.push((buf >> bits) as u8);
445 }
446 }
447 Some(out)
448}
449
450pub fn reason_str(r: Reason) -> &'static str {
461 match r {
462 Reason::Ok => "OK",
463 Reason::BadAuthoritySignature => "BAD_AUTHORITY_SIGNATURE",
464 Reason::BadInvocationSignature => "BAD_INVOCATION_SIGNATURE",
465 Reason::SubjectMismatch => "SUBJECT_MISMATCH",
466 Reason::CapabilityMismatch => "CAPABILITY_MISMATCH",
467 Reason::ResourceMismatch => "RESOURCE_MISMATCH",
468 Reason::ValueLimitExceeded => "VALUE_LIMIT_EXCEEDED",
469 Reason::TotalLimitExceeded => "TOTAL_LIMIT_EXCEEDED",
470 Reason::CurrencyMismatch => "CURRENCY_MISMATCH",
471 Reason::Expired => "EXPIRED",
472 Reason::NotYetValid => "NOT_YET_VALID",
473 Reason::MaxUsesExceeded => "MAX_USES_EXCEEDED",
474 Reason::AudienceMismatch => "AUDIENCE_MISMATCH",
475 Reason::NonceReplay => "NONCE_REPLAY",
476 Reason::Revoked => "REVOKED",
477 Reason::RevocationStale => "REVOCATION_STALE",
478 Reason::OfflineValueExceeded => "OFFLINE_VALUE_EXCEEDED",
479 Reason::ForbiddenCapability => "FORBIDDEN_CAPABILITY",
480 Reason::HumanConfirmationRequired => "HUMAN_CONFIRMATION_REQUIRED",
481 Reason::DelegationNotSubset => "DELEGATION_NOT_SUBSET",
482 }
483}
484
485#[derive(serde::Deserialize)]
486struct StateWire {
487 now: i64,
488 audience: String,
489 #[serde(default)]
490 online: bool,
491 #[serde(default)]
492 revocation_age_sec: i64,
493 #[serde(default)]
494 revoked_ids: Vec<String>,
495 #[serde(default)]
496 used_nonces: Vec<String>,
497 #[serde(default)]
498 uses: BTreeMap<String, u64>,
499 #[serde(default)]
500 spent_total: BTreeMap<String, f64>,
501 #[serde(default)]
502 offline_limit: f64,
503}
504
505#[derive(serde::Deserialize)]
506struct RequestWire {
507 authority: AuthorityObject,
508 invocation: Invocation,
509 state: StateWire,
510}
511
512pub struct JsonVerdict {
514 pub json: String,
515 pub allow: bool,
516}
517
518pub fn evaluate_json(input: &str) -> JsonVerdict {
521 let req: RequestWire = match serde_json::from_str(input) {
522 Ok(r) => r,
523 Err(_) => {
524 return JsonVerdict {
525 json: "{\"decision\":\"DENY\",\"reason\":\"MALFORMED_REQUEST\",\"receipt\":null}"
526 .to_string(),
527 allow: false,
528 };
529 }
530 };
531
532 let state = VerifierState {
533 now: req.state.now,
534 audience: req.state.audience,
535 online: req.state.online,
536 revocation_age_sec: req.state.revocation_age_sec,
537 revoked_ids: req.state.revoked_ids.into_iter().collect(),
538 used_nonces: req.state.used_nonces.into_iter().collect(),
539 uses: req.state.uses,
540 spent_total: req.state.spent_total,
541 offline_limit: req.state.offline_limit,
542 };
543
544 let result = border_check(&req.authority, &req.invocation, &state);
545 let allow = result.decision == Decision::Allow;
546 let decision = if allow { "ALLOW" } else { "DENY" };
547 let receipt = match &result.receipt {
548 Some(h) => format!("\"{h}\""),
549 None => "null".to_string(),
550 };
551 let json = format!(
552 "{{\"decision\":\"{}\",\"reason\":\"{}\",\"receipt\":{}}}",
553 decision,
554 reason_str(result.reason),
555 receipt
556 );
557 JsonVerdict { json, allow }
558}