agentkernel 0.18.1

Run AI coding agents in secure, isolated microVMs
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! Cedar policy evaluation engine for enterprise authorization.
//!
//! Defines the Cedar schema for the AgentKernel namespace and provides
//! policy evaluation for sandbox operations (Create, Run, Exec, Attach,
//! Mount, Network).

#![cfg(feature = "enterprise")]

use anyhow::{Context as _, Result};
use cedar_policy::{
    Authorizer, Context, Decision, Entities, Entity, EntityTypeName, EntityUid, PolicySet, Request,
    RestrictedExpression, Schema,
};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::str::FromStr;

/// Cedar schema definition for the AgentKernel namespace.
///
/// Defines entity types (User, Sandbox) and actions
/// (Run, Exec, Create, Attach, Mount, Network).
pub const CEDAR_SCHEMA: &str = r#"
namespace AgentKernel {
    entity User = {
        email: String,
        org_id: String,
        roles: Set<String>,
        mfa_verified: Bool,
    };

    entity Sandbox = {
        name: String,
        agent_type: String,
        runtime: String,
    };

    action Run appliesTo {
        principal: [User],
        resource: [Sandbox],
    };

    action Exec appliesTo {
        principal: [User],
        resource: [Sandbox],
    };

    action Create appliesTo {
        principal: [User],
        resource: [Sandbox],
    };

    action Attach appliesTo {
        principal: [User],
        resource: [Sandbox],
    };

    action Mount appliesTo {
        principal: [User],
        resource: [Sandbox],
    };

    action Network appliesTo {
        principal: [User],
        resource: [Sandbox],
    };

    action PortMap appliesTo {
        principal: [User],
        resource: [Sandbox],
    };

    action SSH appliesTo {
        principal: [User],
        resource: [Sandbox],
    };

    action UseLlmProvider appliesTo {
        principal: [User],
        resource: [Sandbox],
    };
}
"#;

/// Actions supported by the AgentKernel policy schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Action {
    Run,
    Exec,
    Create,
    Attach,
    Mount,
    Network,
    PortMap,
    SSH,
    UseLlmProvider,
}

impl Action {
    /// Get the Cedar entity UID string for this action.
    pub fn cedar_uid(&self) -> String {
        match self {
            Action::Run => r#"AgentKernel::Action::"Run""#.to_string(),
            Action::Exec => r#"AgentKernel::Action::"Exec""#.to_string(),
            Action::Create => r#"AgentKernel::Action::"Create""#.to_string(),
            Action::Attach => r#"AgentKernel::Action::"Attach""#.to_string(),
            Action::Mount => r#"AgentKernel::Action::"Mount""#.to_string(),
            Action::Network => r#"AgentKernel::Action::"Network""#.to_string(),
            Action::PortMap => r#"AgentKernel::Action::"PortMap""#.to_string(),
            Action::SSH => r#"AgentKernel::Action::"SSH""#.to_string(),
            Action::UseLlmProvider => r#"AgentKernel::Action::"UseLlmProvider""#.to_string(),
        }
    }
}

impl std::fmt::Display for Action {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Action::Run => write!(f, "Run"),
            Action::Exec => write!(f, "Exec"),
            Action::Create => write!(f, "Create"),
            Action::Attach => write!(f, "Attach"),
            Action::Mount => write!(f, "Mount"),
            Action::Network => write!(f, "Network"),
            Action::PortMap => write!(f, "PortMap"),
            Action::SSH => write!(f, "SSH"),
            Action::UseLlmProvider => write!(f, "UseLlmProvider"),
        }
    }
}

/// Principal identity for policy evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Principal {
    /// User identifier (e.g., email)
    pub id: String,
    /// Email address
    pub email: String,
    /// Organization identifier
    pub org_id: String,
    /// Assigned roles
    pub roles: Vec<String>,
    /// Whether MFA has been verified
    pub mfa_verified: bool,
}

/// Resource (sandbox) for policy evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Resource {
    /// Sandbox name
    pub name: String,
    /// Agent type (claude, gemini, codex, opencode)
    pub agent_type: String,
    /// Runtime (python, node, rust, etc.)
    pub runtime: String,
}

/// Result of a policy evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyDecision {
    /// Whether the action is permitted
    pub decision: PolicyEffect,
    /// Reason for the decision
    pub reason: String,
    /// IDs of policies that contributed to this decision
    pub matched_policies: Vec<String>,
    /// Evaluation duration in microseconds
    pub evaluation_time_us: u64,
}

/// The effect of a policy decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PolicyEffect {
    /// Action is allowed
    Permit,
    /// Action is denied
    Deny,
}

impl PolicyDecision {
    /// Create a permit decision.
    pub fn permit(reason: impl Into<String>, matched: Vec<String>, time_us: u64) -> Self {
        Self {
            decision: PolicyEffect::Permit,
            reason: reason.into(),
            matched_policies: matched,
            evaluation_time_us: time_us,
        }
    }

    /// Create a deny decision.
    pub fn deny(reason: impl Into<String>, matched: Vec<String>, time_us: u64) -> Self {
        Self {
            decision: PolicyEffect::Deny,
            reason: reason.into(),
            matched_policies: matched,
            evaluation_time_us: time_us,
        }
    }

    /// Check if the decision permits the action.
    pub fn is_permit(&self) -> bool {
        self.decision == PolicyEffect::Permit
    }
}

/// Cedar policy evaluation engine.
///
/// Loads Cedar policies and schema, then evaluates authorization requests
/// against them.
pub struct CedarEngine {
    /// Parsed Cedar policies
    policy_set: PolicySet,
    /// Parsed Cedar schema
    schema: Schema,
    /// The authorizer instance
    authorizer: Authorizer,
}

impl CedarEngine {
    /// Create a new CedarEngine with the given policies and the built-in schema.
    pub fn new(policies_src: &str) -> Result<Self> {
        let (schema, _warnings) =
            Schema::from_cedarschema_str(CEDAR_SCHEMA).context("Failed to parse Cedar schema")?;

        let policy_set: PolicySet = policies_src
            .parse()
            .map_err(|e| anyhow::anyhow!("Failed to parse Cedar policies: {}", e))?;

        Ok(Self {
            policy_set,
            schema,
            authorizer: Authorizer::new(),
        })
    }

    /// Create a CedarEngine with a custom schema.
    pub fn with_schema(policies_src: &str, schema_src: &str) -> Result<Self> {
        let (schema, _warnings) =
            Schema::from_cedarschema_str(schema_src).context("Failed to parse Cedar schema")?;

        let policy_set: PolicySet = policies_src
            .parse()
            .map_err(|e| anyhow::anyhow!("Failed to parse Cedar policies: {}", e))?;

        Ok(Self {
            policy_set,
            schema,
            authorizer: Authorizer::new(),
        })
    }

    /// Replace the policy set with new policies.
    pub fn update_policies(&mut self, policies_src: &str) -> Result<()> {
        let policy_set: PolicySet = policies_src
            .parse()
            .map_err(|e| anyhow::anyhow!("Failed to parse Cedar policies: {}", e))?;
        self.policy_set = policy_set;
        Ok(())
    }

    /// Evaluate an authorization request.
    ///
    /// Returns a PolicyDecision indicating whether the principal is allowed
    /// to perform the action on the resource.
    pub fn evaluate(
        &self,
        principal: &Principal,
        action: Action,
        resource: &Resource,
        extra_context: Option<HashMap<String, String>>,
    ) -> PolicyDecision {
        let start = std::time::Instant::now();

        // Build Cedar entities
        let entities = match self.build_entities(principal, resource) {
            Ok(e) => e,
            Err(e) => {
                let elapsed = start.elapsed().as_micros() as u64;
                return PolicyDecision::deny(
                    format!("Failed to build entities: {}", e),
                    vec![],
                    elapsed,
                );
            }
        };

        // Build request
        let request = match self.build_request(principal, action, resource, extra_context) {
            Ok(r) => r,
            Err(e) => {
                let elapsed = start.elapsed().as_micros() as u64;
                return PolicyDecision::deny(
                    format!("Failed to build request: {}", e),
                    vec![],
                    elapsed,
                );
            }
        };

        // Evaluate
        let response = self
            .authorizer
            .is_authorized(&request, &self.policy_set, &entities);
        let elapsed = start.elapsed().as_micros() as u64;

        let matched: Vec<String> = response
            .diagnostics()
            .reason()
            .map(|id| id.to_string())
            .collect();

        match response.decision() {
            Decision::Allow => {
                PolicyDecision::permit("Policy evaluation: permit", matched, elapsed)
            }
            Decision::Deny => {
                let errors: Vec<String> = response
                    .diagnostics()
                    .errors()
                    .map(|e| e.to_string())
                    .collect();

                let reason = if errors.is_empty() {
                    "Policy evaluation: deny (no matching permit or explicit forbid)".to_string()
                } else {
                    format!("Policy evaluation: deny (errors: {})", errors.join("; "))
                };

                PolicyDecision::deny(reason, matched, elapsed)
            }
        }
    }

    /// Get a reference to the schema (for validation).
    pub fn schema(&self) -> &Schema {
        &self.schema
    }

    /// Build Cedar entities from principal and resource.
    fn build_entities(&self, principal: &Principal, resource: &Resource) -> Result<Entities> {
        let mut entities_vec = Vec::new();

        // Build User entity
        let user_type = EntityTypeName::from_str("AgentKernel::User")
            .map_err(|e| anyhow::anyhow!("Invalid entity type: {}", e))?;
        let user_uid = EntityUid::from_type_name_and_id(
            user_type,
            principal
                .id
                .clone()
                .parse()
                .map_err(|e| anyhow::anyhow!("Invalid entity id: {}", e))?,
        );

        let roles_iter = principal
            .roles
            .iter()
            .map(|r| RestrictedExpression::new_string(r.clone()));

        let user_attrs: HashMap<String, RestrictedExpression> = [
            (
                "email".to_string(),
                RestrictedExpression::new_string(principal.email.clone()),
            ),
            (
                "org_id".to_string(),
                RestrictedExpression::new_string(principal.org_id.clone()),
            ),
            (
                "roles".to_string(),
                RestrictedExpression::new_set(roles_iter),
            ),
            (
                "mfa_verified".to_string(),
                RestrictedExpression::new_bool(principal.mfa_verified),
            ),
        ]
        .into_iter()
        .collect();

        let user_entity = Entity::new(user_uid.clone(), user_attrs, HashSet::new())
            .map_err(|e| anyhow::anyhow!("Failed to create User entity: {}", e))?;
        entities_vec.push(user_entity);

        // Build Sandbox entity
        let sandbox_type = EntityTypeName::from_str("AgentKernel::Sandbox")
            .map_err(|e| anyhow::anyhow!("Invalid entity type: {}", e))?;
        let sandbox_uid = EntityUid::from_type_name_and_id(
            sandbox_type,
            resource
                .name
                .clone()
                .parse()
                .map_err(|e| anyhow::anyhow!("Invalid entity id: {}", e))?,
        );

        let sandbox_attrs: HashMap<String, RestrictedExpression> = [
            (
                "name".to_string(),
                RestrictedExpression::new_string(resource.name.clone()),
            ),
            (
                "agent_type".to_string(),
                RestrictedExpression::new_string(resource.agent_type.clone()),
            ),
            (
                "runtime".to_string(),
                RestrictedExpression::new_string(resource.runtime.clone()),
            ),
        ]
        .into_iter()
        .collect();

        let sandbox_entity = Entity::new(sandbox_uid, sandbox_attrs, HashSet::new())
            .map_err(|e| anyhow::anyhow!("Failed to create Sandbox entity: {}", e))?;
        entities_vec.push(sandbox_entity);

        Entities::from_entities(entities_vec, Some(&self.schema))
            .context("Failed to build entity set")
    }

    /// Build a Cedar Request from principal, action, resource, and optional context.
    fn build_request(
        &self,
        principal: &Principal,
        action: Action,
        resource: &Resource,
        extra_context: Option<HashMap<String, String>>,
    ) -> Result<Request> {
        let principal_uid: EntityUid = format!(r#"AgentKernel::User::"{}""#, principal.id)
            .parse()
            .map_err(|e| anyhow::anyhow!("Invalid principal UID: {}", e))?;

        let action_uid: EntityUid = action
            .cedar_uid()
            .parse()
            .map_err(|e| anyhow::anyhow!("Invalid action UID: {}", e))?;

        let resource_uid: EntityUid = format!(r#"AgentKernel::Sandbox::"{}""#, resource.name)
            .parse()
            .map_err(|e| anyhow::anyhow!("Invalid resource UID: {}", e))?;

        let context = if let Some(ctx_map) = extra_context {
            Context::from_pairs(
                ctx_map
                    .into_iter()
                    .map(|(k, v)| (k, RestrictedExpression::new_string(v))),
            )
            .context("Failed to build context")?
        } else {
            Context::empty()
        };

        Request::new(
            principal_uid,
            action_uid,
            resource_uid,
            context,
            Some(&self.schema),
        )
        .map_err(|e| anyhow::anyhow!("Failed to create request: {}", e))
    }
}

/// Validate Cedar policy syntax without building a full engine.
///
/// Useful for lightweight validation (e.g., in a K8s CRD reconciler)
/// where you want to check if the Cedar text parses before aggregating.
pub fn validate_cedar_syntax(src: &str) -> Result<()> {
    let _: PolicySet = src
        .parse()
        .map_err(|e| anyhow::anyhow!("Invalid Cedar syntax: {}", e))?;
    Ok(())
}

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

    fn test_principal() -> Principal {
        Principal {
            id: "alice".to_string(),
            email: "alice@acme.com".to_string(),
            org_id: "acme-corp".to_string(),
            roles: vec!["developer".to_string()],
            mfa_verified: true,
        }
    }

    fn test_resource() -> Resource {
        Resource {
            name: "my-sandbox".to_string(),
            agent_type: "claude".to_string(),
            runtime: "python".to_string(),
        }
    }

    #[test]
    fn test_permit_policy() {
        let policies = r#"
permit(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"Run",
    resource is AgentKernel::Sandbox
);
        "#;

        let engine = CedarEngine::new(policies).unwrap();
        let decision = engine.evaluate(&test_principal(), Action::Run, &test_resource(), None);

        assert!(decision.is_permit());
        assert_eq!(decision.decision, PolicyEffect::Permit);
    }

    #[test]
    fn test_deny_no_matching_policy() {
        // No policies match Exec action
        let policies = r#"
permit(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"Run",
    resource is AgentKernel::Sandbox
);
        "#;

        let engine = CedarEngine::new(policies).unwrap();
        let decision = engine.evaluate(&test_principal(), Action::Exec, &test_resource(), None);

        assert!(!decision.is_permit());
        assert_eq!(decision.decision, PolicyEffect::Deny);
    }

    #[test]
    fn test_explicit_forbid() {
        let policies = r#"
permit(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"Network",
    resource is AgentKernel::Sandbox
);
forbid(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"Network",
    resource is AgentKernel::Sandbox
) when {
    !principal.mfa_verified
};
        "#;

        // MFA verified user should be permitted (forbid doesn't match)
        let engine = CedarEngine::new(policies).unwrap();
        let decision = engine.evaluate(&test_principal(), Action::Network, &test_resource(), None);
        assert!(decision.is_permit());

        // Non-MFA user should be denied
        let mut no_mfa = test_principal();
        no_mfa.mfa_verified = false;
        let decision = engine.evaluate(&no_mfa, Action::Network, &test_resource(), None);
        assert!(!decision.is_permit());
    }

    #[test]
    fn test_role_based_policy() {
        let policies = r#"
permit(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"Create",
    resource is AgentKernel::Sandbox
) when {
    principal.roles.contains("developer")
};
        "#;

        let engine = CedarEngine::new(policies).unwrap();

        // Developer should be permitted
        let decision = engine.evaluate(&test_principal(), Action::Create, &test_resource(), None);
        assert!(decision.is_permit());

        // Non-developer should be denied
        let mut viewer = test_principal();
        viewer.roles = vec!["viewer".to_string()];
        let decision = engine.evaluate(&viewer, Action::Create, &test_resource(), None);
        assert!(!decision.is_permit());
    }

    #[test]
    fn test_update_policies() {
        let initial = r#"
permit(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"Run",
    resource is AgentKernel::Sandbox
);
        "#;

        let mut engine = CedarEngine::new(initial).unwrap();

        // Initially permits Run
        let decision = engine.evaluate(&test_principal(), Action::Run, &test_resource(), None);
        assert!(decision.is_permit());

        // Update to only permit Create
        let updated = r#"
permit(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"Create",
    resource is AgentKernel::Sandbox
);
        "#;
        engine.update_policies(updated).unwrap();

        // Run should now be denied
        let decision = engine.evaluate(&test_principal(), Action::Run, &test_resource(), None);
        assert!(!decision.is_permit());

        // Create should be permitted
        let decision = engine.evaluate(&test_principal(), Action::Create, &test_resource(), None);
        assert!(decision.is_permit());
    }

    #[test]
    fn test_action_display() {
        assert_eq!(Action::Run.to_string(), "Run");
        assert_eq!(Action::Exec.to_string(), "Exec");
        assert_eq!(Action::Create.to_string(), "Create");
        assert_eq!(Action::Attach.to_string(), "Attach");
        assert_eq!(Action::Mount.to_string(), "Mount");
        assert_eq!(Action::Network.to_string(), "Network");
        assert_eq!(Action::PortMap.to_string(), "PortMap");
    }

    #[test]
    fn test_policy_decision_helpers() {
        let permit = PolicyDecision::permit("ok", vec!["policy0".to_string()], 100);
        assert!(permit.is_permit());
        assert_eq!(permit.matched_policies, vec!["policy0"]);
        assert_eq!(permit.evaluation_time_us, 100);

        let deny = PolicyDecision::deny("nope", vec![], 50);
        assert!(!deny.is_permit());
    }

    #[test]
    fn test_empty_policies() {
        // Empty policy set should deny everything (default deny)
        let engine = CedarEngine::new("").unwrap();
        let decision = engine.evaluate(&test_principal(), Action::Run, &test_resource(), None);
        assert!(!decision.is_permit());
    }

    #[test]
    fn test_ssh_action_evaluation() {
        // Permit SSH for users with "developer" role
        let policies = r#"
permit(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"SSH",
    resource is AgentKernel::Sandbox
) when {
    principal.roles.contains("developer")
};
        "#;

        let engine = CedarEngine::new(policies).unwrap();

        // Developer should be permitted SSH
        let decision = engine.evaluate(&test_principal(), Action::SSH, &test_resource(), None);
        assert!(decision.is_permit());

        // Non-developer should be denied SSH
        let mut viewer = test_principal();
        viewer.roles = vec!["viewer".to_string()];
        let decision = engine.evaluate(&viewer, Action::SSH, &test_resource(), None);
        assert!(!decision.is_permit());
    }

    #[test]
    fn test_forbid_ssh_action() {
        // Permit all actions, but explicitly forbid SSH
        let policies = r#"
permit(
    principal is AgentKernel::User,
    action,
    resource is AgentKernel::Sandbox
);
forbid(
    principal is AgentKernel::User,
    action == AgentKernel::Action::"SSH",
    resource is AgentKernel::Sandbox
);
        "#;

        let engine = CedarEngine::new(policies).unwrap();

        // SSH should be denied despite the broad permit
        let decision = engine.evaluate(&test_principal(), Action::SSH, &test_resource(), None);
        assert!(!decision.is_permit());

        // Other actions should still be permitted
        let decision = engine.evaluate(&test_principal(), Action::Run, &test_resource(), None);
        assert!(decision.is_permit());
    }

    #[test]
    fn test_ssh_action_display() {
        assert_eq!(Action::SSH.to_string(), "SSH");
        assert_eq!(Action::SSH.cedar_uid(), r#"AgentKernel::Action::"SSH""#);
    }
}