aegis-delegate 0.2.0

AEGIS delegation and authority model — delegation trees, session keys, scope constraints
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
// AEGIS Delegate — Scope Constraints
//
// Reference: AEGIS Specification v1.0.0 §9.4, §9.6
//
// Implements the no-amplification rule (§9.6 rule 1) and intersection
// narrowing (§9.6 rule 2) for delegation scope hierarchies.

use openagent_aegis_core::{DelegationError, DelegationScope, SpendingLimits, TemporalConstraints};

/// Checks if `child` scope is a subset of `parent` scope (no-amplification rule §9.6).
///
/// A child scope is a subset when:
/// - Every action in child is present in parent (or parent has no actions, meaning wildcard)
/// - Every resource in child is present in parent (or parent has no restrictions)
/// - Every chain in child is present in parent (or parent has no restrictions)
/// - Child limits are at least as restrictive as parent limits
pub fn is_scope_subset(child: &DelegationScope, parent: &DelegationScope) -> bool {
    // Actions: if parent is non-empty, child must be a subset
    if !parent.actions.is_empty() && !child.actions.iter().all(|a| parent.actions.contains(a)) {
        return false;
    }

    // Resources: if parent is non-empty, child must be a subset
    if !parent.resources.is_empty() && !child.resources.iter().all(|r| parent.resources.contains(r))
    {
        return false;
    }

    // Chains: if parent is non-empty, child must be a subset
    if !parent.chains.is_empty() && !child.chains.iter().all(|c| parent.chains.contains(c)) {
        return false;
    }

    // Limits: child must be more restrictive or equal
    if let Some(ref parent_limits) = parent.limits {
        match child.limits {
            None => {
                // No limits on child but parent has limits => child is less restrictive
                return false;
            }
            Some(ref child_limits) => {
                if !is_limits_subset(child_limits, parent_limits) {
                    return false;
                }
            }
        }
    }
    // If parent has no limits, child may have any limits (more restrictive is fine)

    true
}

/// Checks whether `child_limits` is at least as restrictive as `parent_limits`.
fn is_limits_subset(child: &SpendingLimits, parent: &SpendingLimits) -> bool {
    // max_amount: child must be <= parent
    if let Some(ref parent_max) = parent.max_amount {
        match child.max_amount {
            None => return false, // no limit < parent limit
            Some(ref child_max) => {
                if !is_amount_leq(child_max, parent_max) {
                    return false;
                }
            }
        }
    }

    // daily_volume: child must be <= parent
    if let Some(ref parent_daily) = parent.daily_volume {
        match child.daily_volume {
            None => return false,
            Some(ref child_daily) => {
                if !is_amount_leq(child_daily, parent_daily) {
                    return false;
                }
            }
        }
    }

    // asset_allowlist: child must be subset of parent (if parent restricts)
    if !parent.asset_allowlist.is_empty()
        && !child
            .asset_allowlist
            .iter()
            .all(|a| parent.asset_allowlist.contains(a))
    {
        return false;
    }

    // recipient_allowlist: child must be subset
    if !parent.recipient_allowlist.is_empty()
        && !child
            .recipient_allowlist
            .iter()
            .all(|r| parent.recipient_allowlist.contains(r))
    {
        return false;
    }

    // approval_threshold: child must be <= parent (lower threshold = more restrictive)
    if let Some(ref parent_thresh) = parent.approval_threshold {
        match child.approval_threshold {
            None => return false,
            Some(ref child_thresh) => {
                if !is_amount_leq(child_thresh, parent_thresh) {
                    return false;
                }
            }
        }
    }

    true
}

/// Compare two decimal amount strings. Returns true if `a <= b`.
///
/// Both values are parsed as f64 for comparison. If parsing fails,
/// falls back to lexicographic comparison.
fn is_amount_leq(a: &str, b: &str) -> bool {
    match (a.parse::<f64>(), b.parse::<f64>()) {
        (Ok(av), Ok(bv)) => av <= bv,
        _ => a <= b,
    }
}

/// Computes the intersection of two scopes (intersection narrowing rule §9.6).
///
/// For each dimension:
/// - If either side is empty (wildcard), use the other side's restriction
/// - Otherwise, take the set intersection
/// - For limits, take the most restrictive value
pub fn intersect_scopes(a: &DelegationScope, b: &DelegationScope) -> DelegationScope {
    let actions = intersect_lists(&a.actions, &b.actions);
    let resources = intersect_lists(&a.resources, &b.resources);
    let chains = intersect_lists(&a.chains, &b.chains);
    let limits = intersect_limits(&a.limits, &b.limits);
    let temporal = intersect_temporal(&a.temporal, &b.temporal);

    DelegationScope {
        actions,
        resources,
        chains,
        limits,
        temporal,
    }
}

/// Intersects two string lists. If either is empty (wildcard), returns the other.
fn intersect_lists(a: &[String], b: &[String]) -> Vec<String> {
    if a.is_empty() {
        return b.to_vec();
    }
    if b.is_empty() {
        return a.to_vec();
    }
    a.iter().filter(|x| b.contains(x)).cloned().collect()
}

/// Intersects two optional spending limits, keeping the most restrictive values.
fn intersect_limits(
    a: &Option<SpendingLimits>,
    b: &Option<SpendingLimits>,
) -> Option<SpendingLimits> {
    match (a, b) {
        (None, None) => None,
        (Some(limits), None) | (None, Some(limits)) => Some(limits.clone()),
        (Some(a_lim), Some(b_lim)) => Some(SpendingLimits {
            max_amount: min_amount_opt(&a_lim.max_amount, &b_lim.max_amount),
            daily_volume: min_amount_opt(&a_lim.daily_volume, &b_lim.daily_volume),
            asset_allowlist: intersect_lists(&a_lim.asset_allowlist, &b_lim.asset_allowlist),
            recipient_allowlist: intersect_lists(
                &a_lim.recipient_allowlist,
                &b_lim.recipient_allowlist,
            ),
            approval_threshold: min_amount_opt(
                &a_lim.approval_threshold,
                &b_lim.approval_threshold,
            ),
        }),
    }
}

/// Intersects two optional temporal constraints, keeping the most restrictive.
fn intersect_temporal(
    a: &Option<TemporalConstraints>,
    b: &Option<TemporalConstraints>,
) -> Option<TemporalConstraints> {
    match (a, b) {
        (None, None) => None,
        (Some(t), None) | (None, Some(t)) => Some(t.clone()),
        (Some(a_t), Some(b_t)) => {
            // valid_from: take the later one (more restrictive start)
            let valid_from = match (&a_t.valid_from, &b_t.valid_from) {
                (None, None) => None,
                (Some(t), None) | (None, Some(t)) => Some(*t),
                (Some(at), Some(bt)) => Some((*at).max(*bt)),
            };

            // valid_until: take the earlier one (more restrictive end)
            let valid_until = match (&a_t.valid_until, &b_t.valid_until) {
                (None, None) => None,
                (Some(t), None) | (None, Some(t)) => Some(*t),
                (Some(at), Some(bt)) => Some((*at).min(*bt)),
            };

            // active_hours: prefer more restrictive; if both present, take a's
            // (true intersection of hour windows requires timezone math beyond scope)
            let active_hours = a_t
                .active_hours
                .clone()
                .or_else(|| b_t.active_hours.clone());

            // cooldown: keep the longer cooldown (more restrictive)
            let cooldown = match (&a_t.cooldown, &b_t.cooldown) {
                (None, None) => None,
                (Some(c), None) | (None, Some(c)) => Some(c.clone()),
                (Some(ac), Some(bc)) => {
                    // ISO 8601 duration comparison is non-trivial;
                    // for safety, keep the lexicographically larger one
                    if ac >= bc {
                        Some(ac.clone())
                    } else {
                        Some(bc.clone())
                    }
                }
            };

            Some(TemporalConstraints {
                valid_from,
                valid_until,
                active_hours,
                cooldown,
            })
        }
    }
}

/// Returns the minimum of two optional amount strings, or the one that is present.
fn min_amount_opt(a: &Option<String>, b: &Option<String>) -> Option<String> {
    match (a, b) {
        (None, None) => None,
        (Some(v), None) | (None, Some(v)) => Some(v.clone()),
        (Some(av), Some(bv)) => {
            if is_amount_leq(av, bv) {
                Some(av.clone())
            } else {
                Some(bv.clone())
            }
        }
    }
}

/// Validates that a delegation scope is well-formed.
///
/// A scope is well-formed if:
/// - Actions, resources, and chains contain no empty strings
/// - If limits are present, numeric fields parse as valid numbers
pub fn validate_scope(scope: &DelegationScope) -> Result<(), DelegationError> {
    // Check for empty strings in lists
    for action in &scope.actions {
        if action.is_empty() {
            return Err(DelegationError::ScopeAmplification {
                reason: "action must not be empty".to_string(),
            });
        }
    }
    for resource in &scope.resources {
        if resource.is_empty() {
            return Err(DelegationError::ScopeAmplification {
                reason: "resource must not be empty".to_string(),
            });
        }
    }
    for chain in &scope.chains {
        if chain.is_empty() {
            return Err(DelegationError::ScopeAmplification {
                reason: "chain must not be empty".to_string(),
            });
        }
    }

    // Validate limits if present
    if let Some(ref limits) = scope.limits {
        validate_amount_field(&limits.max_amount, "max_amount")?;
        validate_amount_field(&limits.daily_volume, "daily_volume")?;
        validate_amount_field(&limits.approval_threshold, "approval_threshold")?;
    }

    // Validate temporal constraints if present
    if let Some(ref temporal) = scope.temporal {
        if let (Some(from), Some(until)) = (&temporal.valid_from, &temporal.valid_until) {
            if from >= until {
                return Err(DelegationError::ScopeAmplification {
                    reason: "valid_from must be before valid_until".to_string(),
                });
            }
        }
        if let Some(ref hours) = temporal.active_hours {
            if hours.start_hour > 23 || hours.end_hour > 23 {
                return Err(DelegationError::ScopeAmplification {
                    reason: "active hours must be 0-23".to_string(),
                });
            }
        }
    }

    Ok(())
}

/// Validates that an optional amount string is parseable as a number.
fn validate_amount_field(field: &Option<String>, name: &str) -> Result<(), DelegationError> {
    if let Some(ref val) = field {
        if val.parse::<f64>().is_err() {
            return Err(DelegationError::ScopeAmplification {
                reason: format!("{name} is not a valid number: {val}"),
            });
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use openagent_aegis_core::SpendingLimits;

    fn full_scope() -> DelegationScope {
        DelegationScope {
            actions: vec![
                "transfer".to_string(),
                "approve".to_string(),
                "stake".to_string(),
            ],
            resources: vec!["0xabc".to_string(), "0xdef".to_string()],
            chains: vec!["ethereum".to_string(), "polygon".to_string()],
            limits: Some(SpendingLimits {
                max_amount: Some("1000".to_string()),
                daily_volume: Some("5000".to_string()),
                asset_allowlist: vec!["ETH".to_string(), "USDC".to_string()],
                recipient_allowlist: vec!["0x111".to_string()],
                approval_threshold: Some("500".to_string()),
            }),
            temporal: None,
        }
    }

    fn narrow_scope() -> DelegationScope {
        DelegationScope {
            actions: vec!["transfer".to_string()],
            resources: vec!["0xabc".to_string()],
            chains: vec!["ethereum".to_string()],
            limits: Some(SpendingLimits {
                max_amount: Some("100".to_string()),
                daily_volume: Some("500".to_string()),
                asset_allowlist: vec!["ETH".to_string()],
                recipient_allowlist: vec!["0x111".to_string()],
                approval_threshold: Some("50".to_string()),
            }),
            temporal: None,
        }
    }

    #[test]
    fn narrow_is_subset_of_full() {
        assert!(is_scope_subset(&narrow_scope(), &full_scope()));
    }

    #[test]
    fn full_is_not_subset_of_narrow() {
        assert!(!is_scope_subset(&full_scope(), &narrow_scope()));
    }

    #[test]
    fn scope_is_subset_of_itself() {
        let s = full_scope();
        assert!(is_scope_subset(&s, &s));
    }

    #[test]
    fn empty_parent_accepts_anything() {
        let parent = DelegationScope {
            actions: vec![],
            resources: vec![],
            chains: vec![],
            limits: None,
            temporal: None,
        };
        assert!(is_scope_subset(&full_scope(), &parent));
    }

    #[test]
    fn amplification_in_actions_rejected() {
        let child = DelegationScope {
            actions: vec!["transfer".to_string(), "destroy".to_string()],
            resources: vec![],
            chains: vec![],
            limits: None,
            temporal: None,
        };
        let parent = DelegationScope {
            actions: vec!["transfer".to_string()],
            resources: vec![],
            chains: vec![],
            limits: None,
            temporal: None,
        };
        assert!(!is_scope_subset(&child, &parent));
    }

    #[test]
    fn amplification_in_limits_rejected() {
        let child = DelegationScope {
            actions: vec!["transfer".to_string()],
            resources: vec![],
            chains: vec![],
            limits: Some(SpendingLimits {
                max_amount: Some("2000".to_string()), // exceeds parent's 1000
                daily_volume: None,
                asset_allowlist: vec![],
                recipient_allowlist: vec![],
                approval_threshold: None,
            }),
            temporal: None,
        };
        let parent = DelegationScope {
            actions: vec!["transfer".to_string()],
            resources: vec![],
            chains: vec![],
            limits: Some(SpendingLimits {
                max_amount: Some("1000".to_string()),
                daily_volume: None,
                asset_allowlist: vec![],
                recipient_allowlist: vec![],
                approval_threshold: None,
            }),
            temporal: None,
        };
        assert!(!is_scope_subset(&child, &parent));
    }

    #[test]
    fn intersection_narrows_correctly() {
        let result = intersect_scopes(&full_scope(), &narrow_scope());

        // Actions: intersection of [transfer,approve,stake] and [transfer]
        assert_eq!(result.actions, vec!["transfer".to_string()]);
        // Resources: intersection of [0xabc,0xdef] and [0xabc]
        assert_eq!(result.resources, vec!["0xabc".to_string()]);
        // Chains: intersection of [ethereum,polygon] and [ethereum]
        assert_eq!(result.chains, vec!["ethereum".to_string()]);
        // Limits: more restrictive
        let limits = result.limits.as_ref();
        assert!(limits.is_some());
        if let Some(l) = limits {
            assert_eq!(l.max_amount.as_deref(), Some("100"));
            assert_eq!(l.daily_volume.as_deref(), Some("500"));
            assert_eq!(l.approval_threshold.as_deref(), Some("50"));
        }
    }

    #[test]
    fn intersection_with_empty_is_identity() {
        let empty = DelegationScope {
            actions: vec![],
            resources: vec![],
            chains: vec![],
            limits: None,
            temporal: None,
        };
        let result = intersect_scopes(&full_scope(), &empty);
        assert_eq!(result.actions, full_scope().actions);
        assert_eq!(result.resources, full_scope().resources);
    }

    #[test]
    fn validate_scope_rejects_empty_action() {
        let scope = DelegationScope {
            actions: vec!["".to_string()],
            resources: vec![],
            chains: vec![],
            limits: None,
            temporal: None,
        };
        assert!(validate_scope(&scope).is_err());
    }

    #[test]
    fn validate_scope_rejects_invalid_amount() {
        let scope = DelegationScope {
            actions: vec!["transfer".to_string()],
            resources: vec![],
            chains: vec![],
            limits: Some(SpendingLimits {
                max_amount: Some("not-a-number".to_string()),
                daily_volume: None,
                asset_allowlist: vec![],
                recipient_allowlist: vec![],
                approval_threshold: None,
            }),
            temporal: None,
        };
        assert!(validate_scope(&scope).is_err());
    }

    #[test]
    fn validate_scope_accepts_valid() {
        assert!(validate_scope(&full_scope()).is_ok());
    }
}