Skip to main content

echo_authority_core/
lib.rs

1//! echo-authority-core — a reference implementation of the Echo Authority Protocol, Draft 0.1.
2//!
3//! This crate is a SECOND, INDEPENDENT implementation of the deterministic Border Control
4//! verifier and the attenuation-only delegation rule. It exists to prove the protocol is a
5//! shared language, not one company's server: given the same Authority Object, the same
6//! Invocation, and the same verifier state, this Rust code MUST return the identical verdict
7//! as the TypeScript reference at /protocol.
8//!
9//! The verifier is deliberately boring. No model, no heuristics, no network. Every decision
10//! falls out of the object's own declared bounds.
11
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::collections::BTreeMap;
15
16// ---------------------------------------------------------------------------
17// Reason codes — the complete, ordered vocabulary of why Border Control decides.
18// ---------------------------------------------------------------------------
19
20#[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    /// On ALLOW, an opaque commitment over the exercised terms. Proof, never data.
55    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// ---------------------------------------------------------------------------
65// The Authority Object and Invocation.
66// ---------------------------------------------------------------------------
67
68#[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    /// Unix seconds. Action is invalid before this instant.
82    pub not_before: i64,
83    /// Unix seconds. Action is invalid at/after this instant.
84    pub expires: i64,
85    pub max_uses: u64,
86    /// If true, an interactive human confirmation MUST accompany the invocation.
87    /// Required on the wire: a grant that omits or misspells it is malformed, not "false".
88    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    /// e.g. "revocation-list". A revoked id in verifier state ends the grant.
104    pub method: String,
105    pub id: String,
106    /// The gateway must have checked revocation within this many seconds.
107    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    /// Base64 Ed25519 public key of the issuer (for signature verification).
122    pub issuer_pub: String,
123    /// Base64 signature over the canonical form.
124    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    /// True only when a human interactively confirmed this specific invocation.
142    #[serde(default)]
143    pub human_confirmed: bool,
144    /// Base64 Ed25519 public key of the subject.
145    pub subject_pub: String,
146    pub sig: String,
147}
148
149/// Mutable verifier state — what the gateway knows at decision time.
150#[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    /// authority_id -> uses already consumed.
159    pub uses: BTreeMap<String, u64>,
160    /// authority_id -> value already spent.
161    pub spent_total: BTreeMap<String, f64>,
162    /// A payment above this value cannot be authorized while offline.
163    pub offline_limit: f64,
164}
165
166// ---------------------------------------------------------------------------
167// Never-grantable capabilities. No signature, no delegation, no human can grant these.
168// ---------------------------------------------------------------------------
169
170pub const FORBIDDEN_CAPS: &[&str] = &[
171    "export-root-key",
172    "export-recovery-secret",
173    "disable-audit",
174    "grant-beyond-owner",
175    "rewrite-history",
176];
177
178// ---------------------------------------------------------------------------
179// Canonical serialization + signature helpers.
180//
181// The canonical string is deterministic and field-ordered. Two implementations that
182// agree on this string will verify each other's signatures. It commits every field
183// that defines the grant's power.
184// ---------------------------------------------------------------------------
185
186pub 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    // Strict: rejects small-order keys and non-canonical signatures.
244    vk.verify_strict(msg.as_bytes(), &sig).is_ok()
245}
246
247/// Opaque commitment written on ALLOW. Commits the exercised terms; carries no data.
248fn 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
260// ---------------------------------------------------------------------------
261// Resource subset test — used by both Border Control and attenuation.
262//
263// A resource `child` is within `parent` when parent is an exact match, or parent is a
264// glob prefix (`vault/*`) that covers child, or parent is a path prefix of child.
265// ---------------------------------------------------------------------------
266
267/// A concrete resource (the thing an invocation targets) is literal and has exactly one
268/// spelling: no wildcard, and no empty, `.` or `..` path segment. A leading, trailing or
269/// doubled slash, or a relative segment, names something an embedder may later normalise
270/// into a different resource from the one compared here.
271pub 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
293// ---------------------------------------------------------------------------
294// Border Control — the deterministic verifier. This is the load-bearing wall.
295//
296// The check order is fixed and each gate returns the exact reason it failed. A conformant
297// implementation in any language must produce the identical (decision, reason) pair.
298// ---------------------------------------------------------------------------
299
300pub fn border_check(
301    authority: &AuthorityObject,
302    invocation: &Invocation,
303    state: &VerifierState,
304) -> BorderResult {
305    // 1. Both signatures must verify. Intelligence cannot forge authorship.
306    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    // 2. The invocation must come from the subject the authority names.
314    if invocation.subject != authority.subject {
315        return BorderResult::deny(Reason::SubjectMismatch);
316    }
317
318    // 3. The requested capability must match the granted one.
319    if invocation.capability != authority.capability {
320        return BorderResult::deny(Reason::CapabilityMismatch);
321    }
322
323    // 4. The target resource must be concrete and within the granted resource.
324    //    The reason vocabulary of Draft 0.1 is unchanged: an unparseable target is a mismatch.
325    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    // 5. Value must respect currency and both caps (per-action and running total).
333    //    Amounts and caps must be finite and non-negative: a negative or NaN amount would
334    //    otherwise skip every value gate and could reduce the embedder's running total.
335    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        // Draft 0.1 has no dedicated reason code; a value outside the representable
341        // range of the grant is refused as exceeding its limit.
342        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    // 6. Time window.
361    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    // 7. Uses budget.
369    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    // 8. Audience binding — a grant for one gateway cannot be replayed at another.
375    if invocation.audience != state.audience {
376        return BorderResult::deny(Reason::AudienceMismatch);
377    }
378
379    // 9. Replay protection — a nonce is single-use.
380    if state.used_nonces.contains(&invocation.nonce) {
381        return BorderResult::deny(Reason::NonceReplay);
382    }
383
384    // 10. Revocation + freshness. Offline changes the risk, never the rule.
385    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    // 11. Never-grantable capabilities. Structural refusal — no grant can carry these.
398    if FORBIDDEN_CAPS.contains(&authority.capability.as_str()) {
399        return BorderResult::deny(Reason::ForbiddenCapability);
400    }
401
402    // 12. Human confirmation, when the grant demands it.
403    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// ---------------------------------------------------------------------------
411// Attenuation — a child grant may only narrow its parent. It can never widen.
412// ---------------------------------------------------------------------------
413
414#[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
469// ---------------------------------------------------------------------------
470// A tiny, dependency-free base64 decoder (standard alphabet, no padding required).
471// ---------------------------------------------------------------------------
472
473fn 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
500// ---------------------------------------------------------------------------
501// Shared JSON entry point.
502//
503// Both the `echo-border-control` CLI and the WebAssembly build call this ONE function, so
504// the CLI, the browser, and any embedder run byte-for-byte the same verifier. Input is a
505// request document; output is a canonical verdict document. Parsing never panics — a
506// malformed request is itself a DENY.
507// ---------------------------------------------------------------------------
508
509/// The stable, human-readable name of a reason code (matches the TypeScript reference).
510pub 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
564/// The outcome of evaluating a request: the canonical verdict JSON plus whether it allowed.
565pub struct JsonVerdict {
566    pub json: String,
567    pub allow: bool,
568}
569
570/// Evaluate a `{ authority, invocation, state }` request document and return the canonical
571/// verdict `{ "decision", "reason", "receipt" }`. Deterministic; never panics.
572pub 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}