exochain-sdk 0.2.0-beta

EXOCHAIN SDK — ergonomic Rust API for the constitutional governance fabric
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Authority delegation and chain verification.
//!
//! An **authority chain** is an ordered list of delegation links where the
//! `grantee` of each link is the `grantor` of the next. The chain terminates
//! at a specific actor (the "terminal"). [`AuthorityChainBuilder`] accumulates
//! links and validates the resulting topology on
//! [`AuthorityChainBuilder::build`]. Structurally:
//!
//! ```text
//! root --[perms]--> middle --[perms]--> leaf
//! ```
//!
//! ## Why use this module
//!
//! - You need to prove that a terminal actor was delegated authority through
//!   a well-formed chain rooted at a specific principal.
//! - You want the SDK to reject broken topologies (gaps, wrong terminal,
//!   empty chain) before you ever submit them to the kernel.
//! - You want the validated chain as a serializable artifact that survives
//!   network hops and storage.
//!
//! ## Quick start
//!
//! ```
//! use exochain_sdk::authority::AuthorityChainBuilder;
//! use exo_core::Did;
//!
//! let root = Did::new("did:exo:root").expect("valid");
//! let mid = Did::new("did:exo:mid").expect("valid");
//! let leaf = Did::new("did:exo:leaf").expect("valid");
//!
//! let chain = AuthorityChainBuilder::new()
//!     .add_link(root, mid.clone(), vec!["delegate".into()])
//!     .add_link(mid, leaf.clone(), vec!["read".into()])
//!     .build(&leaf)?;
//!
//! assert_eq!(chain.depth, 2);
//! assert_eq!(chain.terminal, leaf);
//! # Ok::<(), exochain_sdk::error::ExoError>(())
//! ```

use exo_core::Did;
use serde::{Deserialize, Deserializer, Serialize, de};

use crate::error::{ExoError, ExoResult};

/// Maximum delegation links accepted in an SDK authority chain.
///
/// This bound prevents untrusted chain material from driving unbounded memory
/// growth while remaining far above the constitutional delegation depths used
/// by the runtime.
pub const MAX_CHAIN_DEPTH: usize = 64;

/// Builder for a validated authority chain.
///
/// Links are appended one at a time with [`AuthorityChainBuilder::add_link`]
/// and the full chain is validated by [`AuthorityChainBuilder::build`]. The
/// builder is `Default` and `Clone`, so a partially-built chain can be forked.
///
/// # Examples
///
/// ```
/// use exochain_sdk::authority::AuthorityChainBuilder;
/// use exo_core::Did;
///
/// let root = Did::new("did:exo:root").expect("valid");
/// let leaf = Did::new("did:exo:leaf").expect("valid");
/// let chain = AuthorityChainBuilder::new()
///     .add_link(root, leaf.clone(), vec!["all".into()])
///     .build(&leaf)?;
/// assert_eq!(chain.depth, 1);
/// # Ok::<(), exochain_sdk::error::ExoError>(())
/// ```
#[derive(Debug, Clone, Default)]
pub struct AuthorityChainBuilder {
    links: Vec<ChainLink>,
    overflowed: bool,
}

impl AuthorityChainBuilder {
    /// Construct an empty builder.
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::authority::AuthorityChainBuilder;
    /// let builder = AuthorityChainBuilder::new();
    /// # let _ = builder;
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            links: Vec::new(),
            overflowed: false,
        }
    }

    /// Append a new delegation link.
    ///
    /// Each link records that `grantor` has delegated `permissions` to
    /// `grantee`. Permission strings are opaque to the SDK; downstream
    /// consumers are free to interpret them.
    ///
    /// # Examples
    ///
    /// ```
    /// # use exochain_sdk::authority::AuthorityChainBuilder;
    /// # use exo_core::Did;
    /// let a = Did::new("did:exo:a").expect("valid");
    /// let b = Did::new("did:exo:b").expect("valid");
    /// let builder = AuthorityChainBuilder::new()
    ///     .add_link(a, b, vec!["read".into(), "write".into()]);
    /// # let _ = builder;
    /// ```
    #[must_use]
    pub fn add_link(mut self, grantor: Did, grantee: Did, permissions: Vec<String>) -> Self {
        if self.links.len() >= MAX_CHAIN_DEPTH {
            self.overflowed = true;
            return self;
        }
        self.links.push(ChainLink {
            grantor,
            grantee,
            permissions,
        });
        self
    }

    /// Validate the chain topology and produce a [`ValidatedChain`].
    ///
    /// Validation rules:
    /// - The chain must contain at least one link.
    /// - For each consecutive pair of links,
    ///   `links[i].grantee == links[i+1].grantor`.
    /// - The final link's `grantee` must equal `terminal_actor`.
    ///
    /// # Errors
    ///
    /// Returns [`ExoError::Authority`] if any rule is violated: empty chain,
    /// a broken delegation between consecutive links, or a mismatch between
    /// the terminal link's grantee and `terminal_actor`.
    ///
    /// # Examples
    ///
    /// A valid three-link chain:
    ///
    /// ```
    /// use exochain_sdk::authority::AuthorityChainBuilder;
    /// use exo_core::Did;
    ///
    /// let root = Did::new("did:exo:root").expect("valid");
    /// let mid = Did::new("did:exo:mid").expect("valid");
    /// let leaf = Did::new("did:exo:leaf").expect("valid");
    /// let chain = AuthorityChainBuilder::new()
    ///     .add_link(root, mid.clone(), vec!["delegate".into()])
    ///     .add_link(mid, leaf.clone(), vec!["read".into()])
    ///     .build(&leaf)?;
    /// assert_eq!(chain.depth, 2);
    /// # Ok::<(), exochain_sdk::error::ExoError>(())
    /// ```
    ///
    /// A broken chain (middle grantee does not match next grantor):
    ///
    /// ```
    /// use exochain_sdk::authority::AuthorityChainBuilder;
    /// use exochain_sdk::error::ExoError;
    /// use exo_core::Did;
    ///
    /// let root = Did::new("did:exo:root").expect("valid");
    /// let mid = Did::new("did:exo:mid").expect("valid");
    /// let other = Did::new("did:exo:other").expect("valid");
    /// let leaf = Did::new("did:exo:leaf").expect("valid");
    /// let err = AuthorityChainBuilder::new()
    ///     .add_link(root, mid, vec!["read".into()])
    ///     .add_link(other, leaf.clone(), vec!["read".into()])
    ///     .build(&leaf)
    ///     .unwrap_err();
    /// assert!(matches!(err, ExoError::Authority(_)));
    /// ```
    pub fn build(self, terminal_actor: &Did) -> ExoResult<ValidatedChain> {
        if self.overflowed {
            return Err(ExoError::Authority(format!(
                "authority chain depth exceeds maximum of {MAX_CHAIN_DEPTH}"
            )));
        }
        let depth = self.links.len();
        validate_chain_parts(depth, &self.links, terminal_actor).map_err(ExoError::Authority)?;
        Ok(ValidatedChain {
            depth,
            links: self.links,
            terminal: terminal_actor.clone(),
        })
    }
}

struct BoundedChainLinks(Vec<ChainLink>);

impl<'de> Deserialize<'de> for BoundedChainLinks {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_seq(BoundedChainLinksVisitor)
    }
}

struct BoundedChainLinksVisitor;

impl<'de> de::Visitor<'de> for BoundedChainLinksVisitor {
    type Value = BoundedChainLinks;

    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "an authority chain containing at most {MAX_CHAIN_DEPTH} links"
        )
    }

    fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
    where
        A: de::SeqAccess<'de>,
    {
        if seq.size_hint().is_some_and(|hint| hint > MAX_CHAIN_DEPTH) {
            return Err(de::Error::custom(format!(
                "authority chain depth exceeds maximum of {MAX_CHAIN_DEPTH}"
            )));
        }

        let mut links = Vec::new();
        while let Some(link) = seq.next_element()? {
            if links.len() >= MAX_CHAIN_DEPTH {
                return Err(de::Error::custom(format!(
                    "authority chain depth exceeds maximum of {MAX_CHAIN_DEPTH}"
                )));
            }
            links.push(link);
        }

        Ok(BoundedChainLinks(links))
    }
}

/// A single delegation link in an authority chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChainLink {
    /// The delegating authority.
    pub grantor: Did,
    /// The recipient of the delegation.
    pub grantee: Did,
    /// Permissions delegated at this link.
    pub permissions: Vec<String>,
}

/// A validated authority chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ValidatedChain {
    /// Number of links in the chain.
    pub depth: usize,
    /// The chain of delegation links, root-first.
    pub links: Vec<ChainLink>,
    /// The terminal actor the chain delegates authority to.
    pub terminal: Did,
}

impl<'de> Deserialize<'de> for ValidatedChain {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct WireValidatedChain {
            depth: usize,
            links: BoundedChainLinks,
            terminal: Did,
        }

        let wire = WireValidatedChain::deserialize(deserializer)?;
        let links = wire.links.0;
        validate_chain_parts(wire.depth, &links, &wire.terminal).map_err(de::Error::custom)?;
        Ok(Self {
            depth: wire.depth,
            links,
            terminal: wire.terminal,
        })
    }
}

fn validate_chain_parts(depth: usize, links: &[ChainLink], terminal: &Did) -> Result<(), String> {
    if depth > MAX_CHAIN_DEPTH || links.len() > MAX_CHAIN_DEPTH {
        return Err(format!(
            "authority chain depth exceeds maximum of {MAX_CHAIN_DEPTH}"
        ));
    }
    if links.is_empty() {
        return Err("authority chain is empty".into());
    }
    if depth != links.len() {
        return Err(format!(
            "authority chain depth {depth} does not match link count {}",
            links.len()
        ));
    }

    for window in links.windows(2) {
        let a = &window[0];
        let b = &window[1];
        if a.grantee != b.grantor {
            return Err(format!("broken delegation: {} != {}", a.grantee, b.grantor));
        }
    }

    let Some(last) = links.last() else {
        return Err("authority chain is empty".into());
    };
    if &last.grantee != terminal {
        return Err(format!(
            "terminal mismatch: chain ends at {} but terminal_actor is {}",
            last.grantee, terminal
        ));
    }

    Ok(())
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    fn did(s: &str) -> Did {
        Did::new(s).expect("valid DID")
    }

    #[test]
    fn valid_chain_passes() {
        let root = did("did:exo:root");
        let mid = did("did:exo:mid");
        let leaf = did("did:exo:leaf");
        let chain = AuthorityChainBuilder::new()
            .add_link(root.clone(), mid.clone(), vec!["read".into()])
            .add_link(mid.clone(), leaf.clone(), vec!["read".into()])
            .build(&leaf)
            .expect("valid");
        assert_eq!(chain.depth, 2);
        assert_eq!(chain.terminal, leaf);
        assert_eq!(chain.links[0].grantor, root);
        assert_eq!(chain.links[1].grantee, leaf);
    }

    #[test]
    fn single_link_chain_passes() {
        let root = did("did:exo:root");
        let leaf = did("did:exo:leaf");
        let chain = AuthorityChainBuilder::new()
            .add_link(root, leaf.clone(), vec!["all".into()])
            .build(&leaf)
            .expect("valid");
        assert_eq!(chain.depth, 1);
    }

    #[test]
    fn empty_chain_fails() {
        let leaf = did("did:exo:leaf");
        let err = AuthorityChainBuilder::new().build(&leaf).unwrap_err();
        assert!(matches!(err, ExoError::Authority(_)));
    }

    #[test]
    fn broken_chain_fails() {
        let root = did("did:exo:root");
        let mid = did("did:exo:mid");
        let other = did("did:exo:other");
        let leaf = did("did:exo:leaf");
        let err = AuthorityChainBuilder::new()
            .add_link(root, mid, vec!["read".into()])
            .add_link(other, leaf.clone(), vec!["read".into()])
            .build(&leaf)
            .unwrap_err();
        assert!(matches!(err, ExoError::Authority(_)));
    }

    #[test]
    fn wrong_terminal_fails() {
        let root = did("did:exo:root");
        let mid = did("did:exo:mid");
        let leaf = did("did:exo:leaf");
        let claimed = did("did:exo:claimed");
        let err = AuthorityChainBuilder::new()
            .add_link(root, mid.clone(), vec!["read".into()])
            .add_link(mid, leaf, vec!["read".into()])
            .build(&claimed)
            .unwrap_err();
        assert!(matches!(err, ExoError::Authority(_)));
    }

    #[test]
    fn validated_chain_serde_roundtrip() {
        let root = did("did:exo:root");
        let leaf = did("did:exo:leaf");
        let chain = AuthorityChainBuilder::new()
            .add_link(root, leaf.clone(), vec!["read".into(), "write".into()])
            .build(&leaf)
            .expect("ok");
        let json = serde_json::to_string(&chain).expect("serialize");
        let decoded: ValidatedChain = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(chain, decoded);
    }

    #[test]
    fn validated_chain_deserialization_rejects_broken_topology() {
        let json = serde_json::json!({
            "depth": 2,
            "links": [
                {
                    "grantor": "did:exo:root",
                    "grantee": "did:exo:mid",
                    "permissions": ["read"]
                },
                {
                    "grantor": "did:exo:other",
                    "grantee": "did:exo:leaf",
                    "permissions": ["read"]
                }
            ],
            "terminal": "did:exo:leaf"
        });

        let result = serde_json::from_value::<ValidatedChain>(json);

        assert!(
            result.is_err(),
            "deserialization must enforce authority-chain continuity"
        );
    }

    #[test]
    fn validated_chain_deserialization_rejects_depth_mismatch() {
        let root = did("did:exo:root");
        let leaf = did("did:exo:leaf");
        let chain = AuthorityChainBuilder::new()
            .add_link(root, leaf.clone(), vec!["read".into()])
            .build(&leaf)
            .expect("valid");
        let mut json = serde_json::to_value(&chain).expect("serialize");
        json["depth"] = serde_json::json!(usize::MAX);

        let result = serde_json::from_value::<ValidatedChain>(json);

        assert!(
            result.is_err(),
            "deserialization must reject forged depth metadata"
        );
    }

    #[test]
    fn builder_rejects_chain_beyond_maximum_depth() {
        let mut builder = AuthorityChainBuilder::new();
        for i in 0..65 {
            builder = builder.add_link(
                did(&format!("did:exo:node-{i}")),
                did(&format!("did:exo:node-{}", i + 1)),
                vec!["read".into()],
            );
        }

        let err = builder
            .build(&did("did:exo:node-65"))
            .expect_err("authority chains deeper than 64 links must be rejected");

        assert!(matches!(err, ExoError::Authority(_)));
    }

    #[test]
    fn builder_accepts_chain_at_maximum_depth() {
        let mut builder = AuthorityChainBuilder::new();
        for i in 0..MAX_CHAIN_DEPTH {
            builder = builder.add_link(
                did(&format!("did:exo:max-node-{i}")),
                did(&format!("did:exo:max-node-{}", i + 1)),
                vec!["read".into()],
            );
        }

        let chain = builder
            .build(&did(&format!("did:exo:max-node-{MAX_CHAIN_DEPTH}")))
            .expect("authority chains at the maximum depth must remain valid");

        assert_eq!(chain.depth, MAX_CHAIN_DEPTH);
    }

    #[test]
    fn builder_does_not_retain_links_beyond_maximum_depth() {
        let mut builder = AuthorityChainBuilder::new();
        for i in 0..(MAX_CHAIN_DEPTH + 10) {
            builder = builder.add_link(
                did(&format!("did:exo:capped-node-{i}")),
                did(&format!("did:exo:capped-node-{}", i + 1)),
                vec!["read".into()],
            );
        }

        assert_eq!(builder.links.len(), MAX_CHAIN_DEPTH);
        assert!(
            builder.overflowed,
            "builder must remember that an over-depth chain was attempted"
        );
    }

    #[test]
    fn validated_chain_deserialization_rejects_chain_beyond_maximum_depth() {
        let links: Vec<_> = (0..65)
            .map(|i| {
                serde_json::json!({
                    "grantor": format!("did:exo:node-{i}"),
                    "grantee": format!("did:exo:node-{}", i + 1),
                    "permissions": ["read"]
                })
            })
            .collect();
        let json = serde_json::json!({
            "depth": 65,
            "links": links,
            "terminal": "did:exo:node-65"
        });

        assert!(
            serde_json::from_value::<ValidatedChain>(json).is_err(),
            "deserialization must reject authority chains deeper than 64 links"
        );
    }

    #[test]
    fn validated_chain_deserialization_accepts_chain_at_maximum_depth() {
        let links: Vec<_> = (0..MAX_CHAIN_DEPTH)
            .map(|i| {
                serde_json::json!({
                    "grantor": format!("did:exo:serde-max-node-{i}"),
                    "grantee": format!("did:exo:serde-max-node-{}", i + 1),
                    "permissions": ["read"]
                })
            })
            .collect();
        let json = serde_json::json!({
            "depth": MAX_CHAIN_DEPTH,
            "links": links,
            "terminal": format!("did:exo:serde-max-node-{MAX_CHAIN_DEPTH}")
        });

        let chain =
            serde_json::from_value::<ValidatedChain>(json).expect("max-depth chain is valid");

        assert_eq!(chain.depth, MAX_CHAIN_DEPTH);
        assert_eq!(chain.links.len(), MAX_CHAIN_DEPTH);
    }

    #[test]
    fn default_builder_is_empty() {
        let b = AuthorityChainBuilder::default();
        assert!(b.links.is_empty());
    }
}