chio-kernel 0.1.2

Chio runtime kernel: capability validation, guard evaluation, receipt signing
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use chio_core::capability::{
    runtime_attestation::RuntimeAttestationEvidence,
    scope::ChioScope,
    token::{CapabilityToken, CapabilityTokenBody},
};
use chio_core::crypto::{Keypair, PublicKey};
use uuid::Uuid;

use crate::KernelError;

const DEFAULT_CAPABILITY_ISSUANCE_CLOCK_SKEW_SECONDS: u64 = 30;

/// Validate that the local authority can issue the requested scope semantics.
pub fn ensure_capability_issuance_supported(_scope: &ChioScope) -> Result<(), KernelError> {
    Ok(())
}

/// Validate that an authority response is exactly the direct capability requested.
pub fn validate_issued_capability_response(
    capability: &CapabilityToken,
    requested_subject: &PublicKey,
    requested_scope: &ChioScope,
    requested_ttl_seconds: u64,
    current_issuer: &PublicKey,
) -> Result<(), KernelError> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|error| KernelError::CapabilityIssuanceFailed(error.to_string()))?
        .as_secs();
    validate_issued_capability_response_at(
        capability,
        requested_subject,
        requested_scope,
        requested_ttl_seconds,
        current_issuer,
        now,
        DEFAULT_CAPABILITY_ISSUANCE_CLOCK_SKEW_SECONDS,
    )
}

/// Deterministically validate an issuance response against the request and current authority.
pub fn validate_issued_capability_response_at(
    capability: &CapabilityToken,
    requested_subject: &PublicKey,
    requested_scope: &ChioScope,
    requested_ttl_seconds: u64,
    current_issuer: &PublicKey,
    now: u64,
    allowed_clock_skew_seconds: u64,
) -> Result<(), KernelError> {
    if &capability.issuer != current_issuer {
        return Err(KernelError::UntrustedIssuer);
    }
    if !matches!(capability.verify_signature(), Ok(true)) {
        return Err(KernelError::InvalidSignature);
    }
    if capability.aggregate_invocation_budget.is_some() {
        return Err(KernelError::CapabilityIssuanceDenied(
            "aggregate invocation capability issuance requires atomic composite admission enforcement"
                .to_string(),
        ));
    }
    ensure_capability_issuance_supported(&capability.scope)?;
    if &capability.subject != requested_subject {
        return Err(KernelError::CapabilityIssuanceFailed(
            "issued capability subject does not match the requested subject".to_string(),
        ));
    }
    if capability.scope.has_cumulative_approval() {
        chio_core::capability::cumulative_approval::verify_cumulative_approval_constraints(
            capability,
            std::slice::from_ref(current_issuer),
            None,
        )
        .map_err(|error| KernelError::CapabilityIssuanceFailed(error.to_string()))?;
    }
    let mut issued_scope = capability.scope.clone();
    for grant in &mut issued_scope.grants {
        for constraint in &mut grant.constraints {
            if let chio_core::capability::scope::Constraint::RequireCumulativeApprovalAbove {
                cumulative_approval_root_binding,
                ..
            } = constraint
            {
                *cumulative_approval_root_binding = None;
            }
        }
    }
    let issued_scope = chio_core::canonical_json_bytes(&issued_scope)
        .map_err(|error| KernelError::CapabilityIssuanceFailed(error.to_string()))?;
    let requested_scope = chio_core::canonical_json_bytes(requested_scope)
        .map_err(|error| KernelError::CapabilityIssuanceFailed(error.to_string()))?;
    if issued_scope != requested_scope {
        return Err(KernelError::CapabilityIssuanceFailed(
            "issued capability scope does not match the requested scope".to_string(),
        ));
    }
    if !capability.delegation_chain.is_empty() {
        return Err(KernelError::CapabilityIssuanceFailed(
            "issued capability must be direct".to_string(),
        ));
    }
    let latest_issued_at = now.saturating_add(allowed_clock_skew_seconds);
    if capability.issued_at > latest_issued_at {
        return Err(KernelError::CapabilityIssuanceFailed(format!(
            "issued capability timestamp {} is too far in the future relative to {now}",
            capability.issued_at
        )));
    }
    if capability.expires_at <= now {
        return Err(KernelError::CapabilityIssuanceFailed(format!(
            "issued capability is already expired at {} relative to {now}",
            capability.expires_at
        )));
    }
    let latest_expires_at = now
        .saturating_add(requested_ttl_seconds)
        .saturating_add(allowed_clock_skew_seconds);
    if capability.expires_at > latest_expires_at {
        return Err(KernelError::CapabilityIssuanceFailed(format!(
            "issued capability wall-clock expiry {} exceeds allowed maximum {latest_expires_at}",
            capability.expires_at
        )));
    }
    let lifetime = capability
        .expires_at
        .checked_sub(capability.issued_at)
        .ok_or_else(|| {
            KernelError::CapabilityIssuanceFailed(
                "issued capability lifetime is reversed".to_string(),
            )
        })?;
    if lifetime > requested_ttl_seconds {
        return Err(KernelError::CapabilityIssuanceFailed(format!(
            "issued capability lifetime {lifetime} exceeds requested TTL {requested_ttl_seconds}"
        )));
    }
    Ok(())
}

pub trait CapabilityAuthority: Send + Sync {
    fn authority_public_key(&self) -> PublicKey;

    fn trusted_public_keys(&self) -> Vec<PublicKey> {
        vec![self.authority_public_key()]
    }

    fn issue_capability(
        &self,
        subject: &PublicKey,
        scope: ChioScope,
        ttl_seconds: u64,
    ) -> Result<CapabilityToken, KernelError>;

    fn issue_capability_with_attestation(
        &self,
        subject: &PublicKey,
        scope: ChioScope,
        ttl_seconds: u64,
        _runtime_attestation: Option<RuntimeAttestationEvidence>,
    ) -> Result<CapabilityToken, KernelError> {
        self.issue_capability(subject, scope, ttl_seconds)
    }
}

pub struct LocalCapabilityAuthority {
    keypair: Keypair,
}

impl LocalCapabilityAuthority {
    pub fn new(keypair: Keypair) -> Self {
        Self { keypair }
    }
}

impl CapabilityAuthority for LocalCapabilityAuthority {
    fn authority_public_key(&self) -> PublicKey {
        self.keypair.public_key()
    }

    fn issue_capability(
        &self,
        subject: &PublicKey,
        scope: ChioScope,
        ttl_seconds: u64,
    ) -> Result<CapabilityToken, KernelError> {
        ensure_capability_issuance_supported(&scope)?;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|duration| duration.as_secs())
            .unwrap_or(0);
        let body = CapabilityTokenBody {
            id: format!("cap-{}", Uuid::now_v7()),
            issuer: self.keypair.public_key(),
            subject: subject.clone(),
            scope,
            issued_at: now,
            expires_at: now.saturating_add(ttl_seconds),
            delegation_chain: vec![],
            aggregate_invocation_budget: None,
        };

        if body.scope.has_cumulative_approval()
            && body.scope.grants.iter().any(|grant| {
                grant
                    .operations
                    .contains(&chio_core::capability::scope::Operation::Delegate)
            })
        {
            CapabilityToken::sign_cumulative_approval_family_root(body, &self.keypair)
        } else {
            CapabilityToken::sign(body, &self.keypair)
        }
        .map_err(|error| KernelError::CapabilityIssuanceFailed(error.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chio_core::capability::{
        aggregate_invocation::{AggregateInvocationBudget, AggregateInvocationScope},
        attenuation::{DelegationLink, DelegationLinkBody},
        scope::{Constraint, MonetaryAmount, Operation, ToolGrant},
    };

    fn tool_scope() -> ChioScope {
        ChioScope {
            grants: vec![ToolGrant {
                server_id: "server".to_string(),
                tool_name: "tool".to_string(),
                operations: vec![Operation::Invoke],
                constraints: Vec::new(),
                max_invocations: None,
                max_cost_per_invocation: None,
                max_total_cost: None,
                dpop_required: None,
            }],
            ..ChioScope::default()
        }
    }

    fn signed_response(
        issuer: &Keypair,
        subject: &PublicKey,
        scope: ChioScope,
        issued_at: u64,
        expires_at: u64,
        delegation_chain: Vec<DelegationLink>,
        aggregate_invocation_budget: Option<AggregateInvocationBudget>,
    ) -> Result<CapabilityToken, chio_core::error::Error> {
        CapabilityToken::sign(
            CapabilityTokenBody {
                id: "cap-issued-response".to_string(),
                issuer: issuer.public_key(),
                subject: subject.clone(),
                scope,
                issued_at,
                expires_at,
                delegation_chain,
                aggregate_invocation_budget,
            },
            issuer,
        )
    }

    #[test]
    fn issuance_response_accepts_exact_trusted_direct_capability(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let issuer = Keypair::generate();
        let subject = Keypair::generate().public_key();
        let scope = tool_scope();
        let capability = signed_response(&issuer, &subject, scope.clone(), 100, 160, vec![], None)?;

        validate_issued_capability_response_at(
            &capability,
            &subject,
            &scope,
            60,
            &issuer.public_key(),
            100,
            30,
        )?;
        Ok(())
    }

    #[test]
    fn issuance_response_rejects_historical_issuer() -> Result<(), Box<dyn std::error::Error>> {
        let historical_issuer = Keypair::generate();
        let current_issuer = Keypair::generate();
        let subject = Keypair::generate().public_key();
        let scope = tool_scope();
        let capability = signed_response(
            &historical_issuer,
            &subject,
            scope.clone(),
            100,
            160,
            vec![],
            None,
        )?;

        assert!(matches!(
            validate_issued_capability_response_at(
                &capability,
                &subject,
                &scope,
                60,
                &current_issuer.public_key(),
                100,
                30,
            ),
            Err(KernelError::UntrustedIssuer)
        ));
        Ok(())
    }

    #[test]
    fn issuance_response_rejects_far_future_issue_time() -> Result<(), Box<dyn std::error::Error>> {
        let issuer = Keypair::generate();
        let subject = Keypair::generate().public_key();
        let scope = tool_scope();
        let capability = signed_response(&issuer, &subject, scope.clone(), 131, 131, vec![], None)?;

        let error = validate_issued_capability_response_at(
            &capability,
            &subject,
            &scope,
            60,
            &issuer.public_key(),
            100,
            30,
        )
        .expect_err("future issuance must fail closed");
        assert!(error.to_string().contains("too far in the future"));
        Ok(())
    }

    #[test]
    fn issuance_response_rejects_overlong_wall_clock_expiry(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let issuer = Keypair::generate();
        let subject = Keypair::generate().public_key();
        let scope = tool_scope();
        let capability = signed_response(&issuer, &subject, scope.clone(), 130, 191, vec![], None)?;

        let error = validate_issued_capability_response_at(
            &capability,
            &subject,
            &scope,
            60,
            &issuer.public_key(),
            100,
            30,
        )
        .expect_err("wall-clock expiry beyond request allowance must fail closed");
        assert!(error.to_string().contains("wall-clock expiry"));
        Ok(())
    }

    #[test]
    fn issuance_response_rejects_already_expired_response() -> Result<(), Box<dyn std::error::Error>>
    {
        let issuer = Keypair::generate();
        let subject = Keypair::generate().public_key();
        let scope = tool_scope();
        let capability = signed_response(&issuer, &subject, scope.clone(), 40, 100, vec![], None)?;

        let error = match validate_issued_capability_response_at(
            &capability,
            &subject,
            &scope,
            60,
            &issuer.public_key(),
            100,
            30,
        ) {
            Ok(()) => panic!("expired issuance response must fail closed"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("already expired"));
        Ok(())
    }

    #[test]
    fn issuance_response_rejects_trusted_signed_subject_and_scope_substitutions(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let issuer = Keypair::generate();
        let requested_subject = Keypair::generate().public_key();
        let substituted_subject = Keypair::generate().public_key();
        let requested_scope = ChioScope::default();
        let subject_substitution = signed_response(
            &issuer,
            &substituted_subject,
            requested_scope.clone(),
            100,
            160,
            vec![],
            None,
        )?;
        let scope_substitution = signed_response(
            &issuer,
            &requested_subject,
            tool_scope(),
            100,
            160,
            vec![],
            None,
        )?;

        for capability in [&subject_substitution, &scope_substitution] {
            assert!(matches!(
                validate_issued_capability_response(
                    capability,
                    &requested_subject,
                    &requested_scope,
                    60,
                    &issuer.public_key(),
                ),
                Err(KernelError::CapabilityIssuanceFailed(_))
            ));
        }
        Ok(())
    }

    #[test]
    fn issuance_response_rejects_delegation_and_invalid_lifetimes(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let issuer = Keypair::generate();
        let subject = Keypair::generate().public_key();
        let scope = tool_scope();
        let link = DelegationLink::sign(
            DelegationLinkBody {
                capability_id: "cap-parent".to_string(),
                delegator: issuer.public_key(),
                delegatee: subject.clone(),
                attenuations: Vec::new(),
                timestamp: 100,
                scope_hash: None,
                aggregate_budget: None,
                cumulative_approval: None,
            },
            &issuer,
        )?;
        let delegated =
            signed_response(&issuer, &subject, scope.clone(), 100, 160, vec![link], None)?;
        let widened = signed_response(&issuer, &subject, scope.clone(), 100, 161, vec![], None)?;
        let reversed = signed_response(&issuer, &subject, scope.clone(), 101, 100, vec![], None)?;

        for capability in [&delegated, &widened, &reversed] {
            assert!(matches!(
                validate_issued_capability_response(
                    capability,
                    &subject,
                    &scope,
                    60,
                    &issuer.public_key(),
                ),
                Err(KernelError::CapabilityIssuanceFailed(_))
            ));
        }
        Ok(())
    }

    #[test]
    fn issuance_response_rejects_aggregate_and_accepts_cumulative_semantics(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let issuer = Keypair::generate();
        let subject = Keypair::generate().public_key();
        let aggregate_scope = tool_scope();
        let aggregate = signed_response(
            &issuer,
            &subject,
            aggregate_scope.clone(),
            100,
            160,
            vec![],
            Some(AggregateInvocationBudget {
                scope: AggregateInvocationScope::Capability,
                max_invocations: 2,
                root_binding: None,
            }),
        )?;
        assert!(matches!(
            validate_issued_capability_response(
                &aggregate,
                &subject,
                &aggregate_scope,
                60,
                &issuer.public_key(),
            ),
            Err(KernelError::CapabilityIssuanceDenied(_))
        ));

        let cumulative_scope = ChioScope {
            grants: vec![ToolGrant {
                server_id: "server".to_string(),
                tool_name: "tool".to_string(),
                operations: vec![Operation::Invoke, Operation::Delegate],
                constraints: vec![Constraint::RequireCumulativeApprovalAbove {
                    threshold: MonetaryAmount {
                        units: 100,
                        currency: "USD".to_string(),
                    },
                    approval_budget_id: "budget-1".to_string(),
                    approval_budget_epoch: 1,
                    cumulative_approval_root_binding: None,
                }],
                max_invocations: None,
                max_cost_per_invocation: None,
                max_total_cost: None,
                dpop_required: None,
            }],
            ..ChioScope::default()
        };
        let requested_cumulative_scope = cumulative_scope.clone();
        let cumulative = CapabilityToken::sign_cumulative_approval_family_root(
            CapabilityTokenBody {
                id: "cap-cumulative-response".to_string(),
                issuer: issuer.public_key(),
                subject: subject.clone(),
                scope: cumulative_scope,
                issued_at: 100,
                expires_at: 160,
                delegation_chain: vec![],
                aggregate_invocation_budget: None,
            },
            &issuer,
        )?;
        validate_issued_capability_response_at(
            &cumulative,
            &subject,
            &requested_cumulative_scope,
            60,
            &issuer.public_key(),
            100,
            0,
        )?;
        Ok(())
    }

    #[test]
    fn local_authority_issues_cumulative_approval_capabilities() {
        let authority = LocalCapabilityAuthority::new(Keypair::generate());
        let scope = ChioScope {
            grants: vec![ToolGrant {
                server_id: "server".to_string(),
                tool_name: "tool".to_string(),
                operations: vec![Operation::Invoke],
                constraints: vec![Constraint::RequireCumulativeApprovalAbove {
                    threshold: MonetaryAmount {
                        units: 100,
                        currency: "USD".to_string(),
                    },
                    approval_budget_id: "budget-1".to_string(),
                    approval_budget_epoch: 1,
                    cumulative_approval_root_binding: None,
                }],
                max_invocations: None,
                max_cost_per_invocation: None,
                max_total_cost: None,
                dpop_required: None,
            }],
            ..ChioScope::default()
        };

        let capability = authority
            .issue_capability(&Keypair::generate().public_key(), scope, 300)
            .expect("cumulative approval capability");
        assert!(capability.scope.has_cumulative_approval());
        assert!(capability.scope.grants[0]
            .constraints
            .iter()
            .any(|constraint| {
                matches!(
                    constraint,
                    Constraint::RequireCumulativeApprovalAbove {
                        cumulative_approval_root_binding: None,
                        ..
                    }
                )
            }));
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorityStatus {
    pub public_key: PublicKey,
    pub generation: u64,
    pub rotated_at: u64,
    pub trusted_public_keys: Vec<PublicKey>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorityTrustedKeySnapshot {
    pub public_key_hex: String,
    pub generation: u64,
    pub activated_at: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthoritySnapshot {
    pub public_key_hex: String,
    pub generation: u64,
    pub rotated_at: u64,
    pub trusted_keys: Vec<AuthorityTrustedKeySnapshot>,
}

#[derive(Debug, thiserror::Error)]
pub enum AuthorityStoreError {
    #[error("sqlite error: {0}")]
    Sqlite(#[from] rusqlite::Error),

    #[error("failed to prepare authority store directory: {0}")]
    Io(#[from] std::io::Error),

    #[error("invalid authority seed: {0}")]
    Core(#[from] chio_core::error::Error),

    #[error("authority fence rejected mutation: {0}")]
    Fence(String),

    #[error("{0}")]
    Schema(String),
}