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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! Permission profiles for sandbox security.
//!
//! Defines security profiles that control what sandboxed code can access.
use serde::{Deserialize, Serialize};
/// Security profile levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SecurityProfile {
/// Full access - network, all mounts, env passthrough
Permissive,
/// Balanced - network allowed, limited mounts, filtered env
#[default]
Moderate,
/// Maximum isolation - no network, no mounts, clean env
Restrictive,
/// Custom profile defined by explicit permissions
Custom,
}
impl SecurityProfile {
/// Get the default permissions for this profile
pub fn permissions(&self) -> Permissions {
match self {
SecurityProfile::Permissive => Permissions {
network: true,
mount_cwd: true,
mount_home: true,
pass_env: true,
allow_privileged: false,
read_only_root: false,
max_memory_mb: None,
max_cpu_percent: None,
seccomp: Some("default".to_string()),
},
SecurityProfile::Moderate => Permissions {
network: true,
mount_cwd: false,
mount_home: false,
pass_env: false,
allow_privileged: false,
read_only_root: false,
max_memory_mb: Some(512),
max_cpu_percent: Some(100),
seccomp: Some("moderate".to_string()),
},
SecurityProfile::Restrictive => Permissions {
network: false,
mount_cwd: false,
mount_home: false,
pass_env: false,
allow_privileged: false,
read_only_root: true,
max_memory_mb: Some(256),
max_cpu_percent: Some(50),
seccomp: Some("restrictive".to_string()),
},
SecurityProfile::Custom => Permissions::default(),
}
}
/// Parse from string
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Option<Self> {
match s.to_lowercase().as_str() {
"permissive" => Some(SecurityProfile::Permissive),
"moderate" => Some(SecurityProfile::Moderate),
"restrictive" => Some(SecurityProfile::Restrictive),
"custom" => Some(SecurityProfile::Custom),
_ => None,
}
}
}
/// Detailed permissions for sandbox execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Permissions {
/// Allow network access
pub network: bool,
/// Mount current working directory
pub mount_cwd: bool,
/// Mount home directory (read-only)
pub mount_home: bool,
/// Pass through host environment variables
pub pass_env: bool,
/// Allow privileged operations (dangerous)
pub allow_privileged: bool,
/// Make root filesystem read-only
pub read_only_root: bool,
/// Maximum memory in MB (None = unlimited)
pub max_memory_mb: Option<u64>,
/// Maximum CPU percentage (None = unlimited)
pub max_cpu_percent: Option<u32>,
/// Seccomp profile to use (None = Docker default, or "default", "moderate", "restrictive", "ai-agent")
pub seccomp: Option<String>,
}
impl Default for Permissions {
fn default() -> Self {
SecurityProfile::Moderate.permissions()
}
}
impl Permissions {
/// Create permission overrides from a Cedar policy decision.
///
/// When the enterprise policy engine evaluates an action, certain
/// Cedar conditions map to permission overrides. For example, a
/// forbid on the "Network" action translates to `network = false`.
///
/// This method applies Cedar-derived restrictions on top of the
/// existing base permissions. Cedar can only restrict, never grant
/// additional permissions beyond the base profile.
#[cfg(feature = "enterprise")]
#[allow(dead_code)]
pub fn from_cedar_decision(
base: &Permissions,
action: &crate::policy::Action,
decision: &crate::policy::PolicyDecision,
) -> Permissions {
let mut perms = base.clone();
// If Cedar denies the action, apply restrictive overrides
if !decision.is_permit() {
match action {
crate::policy::Action::Network => {
perms.network = false;
}
crate::policy::Action::Mount => {
perms.mount_cwd = false;
perms.mount_home = false;
}
crate::policy::Action::Create | crate::policy::Action::Run => {
// Deny the entire operation - caller should check decision first
}
crate::policy::Action::Exec => {
// Deny command execution - caller should check decision first
}
crate::policy::Action::Attach => {
// Deny attach - caller should check decision first
}
crate::policy::Action::PortMap => {
// Deny port mapping - caller should check decision first
}
crate::policy::Action::SSH => {
// Deny SSH access - caller should check decision first
}
crate::policy::Action::UseLlmProvider => {
// Deny LLM provider usage - caller should check decision first
}
}
}
perms
}
/// Resolve seccomp profile path from name or path
///
/// Built-in profiles: "default", "moderate", "restrictive", "ai-agent"
/// Custom profiles: provide absolute path to JSON file
pub fn resolve_seccomp_path(&self) -> Option<std::path::PathBuf> {
let profile = self.seccomp.as_ref()?;
// Check for built-in profiles
let builtin_names = ["default", "moderate", "restrictive", "ai-agent"];
if builtin_names.contains(&profile.as_str()) {
// Look for built-in profiles relative to executable or in known locations
let profile_name = format!("{}.json", profile);
// Try relative to current dir (development)
let dev_path = std::path::PathBuf::from("images/seccomp").join(&profile_name);
if dev_path.exists() {
return dev_path.canonicalize().ok();
}
// Try relative to executable (installed)
if let Ok(exe_path) = std::env::current_exe()
&& let Some(exe_dir) = exe_path.parent()
{
let installed_path = exe_dir.join("seccomp").join(&profile_name);
if installed_path.exists() {
return Some(installed_path);
}
}
// Try system location
let system_path =
std::path::PathBuf::from("/usr/share/agentkernel/seccomp").join(&profile_name);
if system_path.exists() {
return Some(system_path);
}
// Built-in profile not found - will fall back to Docker default
None
} else {
// Custom path provided
let path = std::path::PathBuf::from(profile);
if path.exists() { Some(path) } else { None }
}
}
/// Convert permissions to Docker run arguments
pub fn to_docker_args(&self) -> Vec<String> {
let mut args = Vec::new();
// Network
if !self.network {
args.push("--network=none".to_string());
}
// Memory limit
if let Some(mem) = self.max_memory_mb {
args.push(format!("--memory={}m", mem));
// Disable OOM killer overhead - container will be constrained but not killed
args.push("--oom-kill-disable".to_string());
}
// CPU limit
if let Some(cpu) = self.max_cpu_percent {
// Docker uses CPU period/quota, simplified here
args.push(format!("--cpus={:.2}", cpu as f64 / 100.0));
}
// Read-only root
if self.read_only_root {
args.push("--read-only".to_string());
// Add tmpfs for /tmp so programs can still write temp files
args.push("--tmpfs=/tmp:rw,noexec,nosuid,size=64m".to_string());
}
// Security options (always apply some baseline security)
if !self.allow_privileged {
args.push("--security-opt=no-new-privileges".to_string());
args.push("--cap-drop=ALL".to_string());
// Add back minimal caps needed for most programs
args.push("--cap-add=CHOWN".to_string());
args.push("--cap-add=SETUID".to_string());
args.push("--cap-add=SETGID".to_string());
}
// Seccomp profile
if let Some(seccomp_path) = self.resolve_seccomp_path() {
args.push(format!("--security-opt=seccomp={}", seccomp_path.display()));
}
args
}
/// Get environment variables to pass (or block)
pub fn get_env_args(&self) -> Vec<String> {
let mut args = Vec::new();
if self.pass_env {
// Pass through common useful env vars
for var in ["PATH", "HOME", "USER", "LANG", "LC_ALL", "TERM"] {
if let Ok(val) = std::env::var(var) {
args.push("-e".to_string());
args.push(format!("{}={}", var, val));
}
}
}
args
}
/// Get mount arguments
pub fn get_mount_args(&self, cwd: Option<&str>) -> Vec<String> {
let mut args = Vec::new();
if self.mount_cwd
&& let Some(dir) = cwd
{
args.push("-v".to_string());
args.push(format!("{}:/workspace:rw", dir));
args.push("-w".to_string());
args.push("/workspace".to_string());
}
if self.mount_home
&& let Ok(home) = std::env::var("HOME")
{
args.push("-v".to_string());
args.push(format!("{}:/home/user:ro", home));
}
args
}
/// Convert permissions to Kubernetes SecurityContext fields.
///
/// Returns a JSON value representing the K8s SecurityContext spec.
/// Used by the Kubernetes backend when building Pod specs.
#[cfg(feature = "kubernetes")]
#[allow(dead_code)]
pub fn to_k8s_security_context(&self) -> serde_json::Value {
use serde_json::json;
let mut ctx = json!({
"privileged": self.allow_privileged,
"allowPrivilegeEscalation": self.allow_privileged,
"readOnlyRootFilesystem": self.read_only_root,
"runAsNonRoot": !self.allow_privileged,
"runAsUser": 1000,
});
// Drop all capabilities unless privileged
if !self.allow_privileged {
ctx["capabilities"] = json!({
"drop": ["ALL"],
});
}
// Seccomp profile
if let Some(ref profile) = self.seccomp {
match profile.as_str() {
"default" | "moderate" | "restrictive" | "ai-agent" => {
ctx["seccompProfile"] = json!({
"type": "RuntimeDefault",
});
}
_ => {
// Custom profile path
ctx["seccompProfile"] = json!({
"type": "Localhost",
"localhostProfile": profile,
});
}
}
}
ctx
}
/// Convert permissions to Kubernetes ResourceRequirements.
///
/// Returns a JSON value representing K8s resource limits and requests.
#[cfg(feature = "kubernetes")]
#[allow(dead_code)]
pub fn to_k8s_resources(&self) -> serde_json::Value {
use serde_json::json;
let mut limits = serde_json::Map::new();
if let Some(mem) = self.max_memory_mb {
limits.insert("memory".to_string(), json!(format!("{}Mi", mem)));
}
if let Some(cpu) = self.max_cpu_percent {
// Convert percentage to millicores (100% = 1000m)
limits.insert("cpu".to_string(), json!(format!("{}m", cpu * 10)));
}
json!({
"limits": limits,
"requests": {},
})
}
/// Convert permissions to Nomad resource configuration.
///
/// Returns a JSON value matching Nomad's Resources stanza.
#[cfg(feature = "nomad")]
#[allow(dead_code)]
pub fn to_nomad_resources(&self) -> serde_json::Value {
use serde_json::json;
let memory_mb = self.max_memory_mb.unwrap_or(512);
let cpu_mhz = self.max_cpu_percent.map(|p| p * 10).unwrap_or(1000);
json!({
"CPU": cpu_mhz,
"MemoryMB": memory_mb,
})
}
}
/// Compatibility mode for agent-specific behavior
///
/// Different AI agents have different expectations for sandbox behavior.
/// This mode adjusts permissions and networking to match each agent's needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CompatibilityMode {
/// Default agentkernel behavior
#[default]
Native,
/// Claude Code compatible (proxy-style network, domain allowlist)
ClaudeCode,
/// OpenAI Codex compatible (Landlock-style, strict isolation)
Codex,
/// Gemini CLI compatible (Docker-style, project directory focus)
Gemini,
/// Amp compatible (Sourcegraph, multi-model, proxy-style network)
Amp,
/// Pi compatible (multi-provider, project directory focus)
Pi,
}
impl CompatibilityMode {
/// Parse from string
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Option<Self> {
match s.to_lowercase().as_str() {
"native" | "default" => Some(Self::Native),
"claude" | "claude-code" | "claudecode" => Some(Self::ClaudeCode),
"codex" | "openai-codex" => Some(Self::Codex),
"gemini" | "gemini-cli" => Some(Self::Gemini),
"amp" | "ampcode" => Some(Self::Amp),
"pi" | "pi-coding-agent" => Some(Self::Pi),
_ => None,
}
}
/// Get the agent profile for this compatibility mode
pub fn profile(&self) -> AgentProfile {
match self {
Self::Native => AgentProfile::native(),
Self::ClaudeCode => AgentProfile::claude_code(),
Self::Codex => AgentProfile::codex(),
Self::Gemini => AgentProfile::gemini(),
Self::Amp => AgentProfile::amp(),
Self::Pi => AgentProfile::pi(),
}
}
}
/// Network policy with domain allowlisting
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NetworkPolicy {
/// Enable network access
pub enabled: bool,
/// Always allowed domains (e.g., API endpoints)
pub always_allow: Vec<String>,
/// Allowed domains (e.g., package registries)
pub allow: Vec<String>,
/// Blocked domains (e.g., cloud metadata)
pub block: Vec<String>,
}
impl NetworkPolicy {
/// Create a policy that allows all network access
pub fn allow_all() -> Self {
Self {
enabled: true,
always_allow: Vec::new(),
allow: Vec::new(),
block: Vec::new(),
}
}
/// Create a policy that blocks all network access
#[allow(dead_code)]
pub fn deny_all() -> Self {
Self {
enabled: false,
always_allow: Vec::new(),
allow: Vec::new(),
block: Vec::new(),
}
}
/// Create a policy for Claude Code (Anthropic API + common registries)
pub fn claude_code() -> Self {
Self {
enabled: true,
always_allow: vec![
"api.anthropic.com".to_string(),
"cdn.anthropic.com".to_string(),
],
allow: vec![
"*.pypi.org".to_string(),
"*.npmjs.com".to_string(),
"*.github.com".to_string(),
"*.githubusercontent.com".to_string(),
"*.crates.io".to_string(),
],
block: vec![
"169.254.169.254".to_string(), // Cloud metadata
"metadata.google.internal".to_string(),
],
}
}
/// Create a policy for Codex (OpenAI API + strict isolation)
pub fn codex() -> Self {
Self {
enabled: true,
always_allow: vec!["api.openai.com".to_string(), "cdn.openai.com".to_string()],
allow: vec!["*.pypi.org".to_string(), "*.npmjs.com".to_string()],
block: vec![
"169.254.169.254".to_string(),
"metadata.google.internal".to_string(),
"*.internal".to_string(),
],
}
}
/// Create a policy for Gemini (Google API + Docker-style)
pub fn gemini() -> Self {
Self {
enabled: true,
always_allow: vec![
"generativelanguage.googleapis.com".to_string(),
"*.googleapis.com".to_string(),
],
allow: vec![
"*.pypi.org".to_string(),
"*.npmjs.com".to_string(),
"*.github.com".to_string(),
],
block: vec!["169.254.169.254".to_string()],
}
}
/// Create a policy for Amp (Anthropic API + Sourcegraph + common registries)
pub fn amp() -> Self {
Self {
enabled: true,
always_allow: vec![
"api.anthropic.com".to_string(),
"*.sourcegraph.com".to_string(),
],
allow: vec![
"*.pypi.org".to_string(),
"*.npmjs.com".to_string(),
"*.github.com".to_string(),
"*.githubusercontent.com".to_string(),
"*.crates.io".to_string(),
],
block: vec![
"169.254.169.254".to_string(),
"metadata.google.internal".to_string(),
],
}
}
/// Create a policy for Pi (multi-provider, common registries)
pub fn pi() -> Self {
Self {
enabled: true,
always_allow: Vec::new(), // Pi supports many providers, no single always-allow
allow: vec![
"api.anthropic.com".to_string(),
"api.openai.com".to_string(),
"generativelanguage.googleapis.com".to_string(),
"*.pypi.org".to_string(),
"*.npmjs.com".to_string(),
"*.github.com".to_string(),
"*.githubusercontent.com".to_string(),
],
block: vec![
"169.254.169.254".to_string(),
"metadata.google.internal".to_string(),
],
}
}
}
/// Agent-specific profile combining permissions and network policy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentProfile {
/// Compatibility mode name
pub mode: CompatibilityMode,
/// Base permissions
pub permissions: Permissions,
/// Network policy with domain control
pub network_policy: NetworkPolicy,
/// API key environment variable name (if any)
pub api_key_env: Option<String>,
/// Additional environment variables to set
pub env_vars: Vec<(String, String)>,
}
impl AgentProfile {
/// Native agentkernel profile
pub fn native() -> Self {
Self {
mode: CompatibilityMode::Native,
permissions: SecurityProfile::Moderate.permissions(),
network_policy: NetworkPolicy::allow_all(),
api_key_env: None,
env_vars: Vec::new(),
}
}
/// Claude Code profile
pub fn claude_code() -> Self {
let mut perms = SecurityProfile::Moderate.permissions();
perms.mount_cwd = true; // Claude needs project access
perms.pass_env = false; // Controlled env passthrough
perms.seccomp = Some("ai-agent".to_string()); // AI agent optimized profile
Self {
mode: CompatibilityMode::ClaudeCode,
permissions: perms,
network_policy: NetworkPolicy::claude_code(),
api_key_env: Some("ANTHROPIC_API_KEY".to_string()),
env_vars: vec![("CLAUDE_CODE_SANDBOX".to_string(), "agentkernel".to_string())],
}
}
/// Codex profile (strict isolation)
pub fn codex() -> Self {
let mut perms = SecurityProfile::Restrictive.permissions();
perms.network = true; // Codex needs API access
perms.mount_cwd = true; // Codex needs project access
perms.seccomp = Some("ai-agent".to_string()); // AI agent optimized profile
Self {
mode: CompatibilityMode::Codex,
permissions: perms,
network_policy: NetworkPolicy::codex(),
api_key_env: Some("OPENAI_API_KEY".to_string()),
env_vars: Vec::new(),
}
}
/// Gemini profile (Docker-style)
pub fn gemini() -> Self {
let mut perms = SecurityProfile::Moderate.permissions();
perms.mount_cwd = true; // Gemini focuses on project directory
perms.seccomp = Some("ai-agent".to_string()); // AI agent optimized profile
Self {
mode: CompatibilityMode::Gemini,
permissions: perms,
network_policy: NetworkPolicy::gemini(),
api_key_env: Some("GOOGLE_API_KEY".to_string()),
env_vars: Vec::new(),
}
}
/// Amp profile (multi-model, Sourcegraph-backed)
pub fn amp() -> Self {
let mut perms = SecurityProfile::Moderate.permissions();
perms.mount_cwd = true; // Amp needs project access
perms.pass_env = false;
perms.seccomp = Some("ai-agent".to_string());
Self {
mode: CompatibilityMode::Amp,
permissions: perms,
network_policy: NetworkPolicy::amp(),
api_key_env: Some("ANTHROPIC_API_KEY".to_string()),
env_vars: Vec::new(),
}
}
/// Pi profile (multi-provider, project directory focus)
pub fn pi() -> Self {
let mut perms = SecurityProfile::Moderate.permissions();
perms.mount_cwd = true; // Pi needs project access
perms.pass_env = false;
perms.seccomp = Some("ai-agent".to_string());
Self {
mode: CompatibilityMode::Pi,
permissions: perms,
network_policy: NetworkPolicy::pi(),
api_key_env: None, // Pi supports multiple providers
env_vars: Vec::new(),
}
}
/// Get Docker network arguments based on network policy
#[allow(dead_code)]
pub fn network_docker_args(&self) -> Vec<String> {
let mut args = Vec::new();
if !self.network_policy.enabled {
args.push("--network=none".to_string());
}
// Note: Domain-level filtering requires a proxy; Docker only supports on/off
// For full domain control, use the proxy architecture from plan/06-agent-in-sandbox.md
args
}
}
impl Default for AgentProfile {
fn default() -> Self {
Self::native()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_security_profiles() {
let permissive = SecurityProfile::Permissive.permissions();
assert!(permissive.network);
assert!(permissive.mount_cwd);
let moderate = SecurityProfile::Moderate.permissions();
assert!(moderate.network);
assert!(!moderate.mount_cwd);
let restrictive = SecurityProfile::Restrictive.permissions();
assert!(!restrictive.network);
assert!(!restrictive.mount_cwd);
assert!(restrictive.read_only_root);
}
#[test]
fn test_docker_args() {
let restrictive = SecurityProfile::Restrictive.permissions();
let args = restrictive.to_docker_args();
assert!(args.contains(&"--network=none".to_string()));
assert!(args.contains(&"--read-only".to_string()));
}
#[test]
fn test_compatibility_modes() {
assert_eq!(
CompatibilityMode::from_str("claude"),
Some(CompatibilityMode::ClaudeCode)
);
assert_eq!(
CompatibilityMode::from_str("codex"),
Some(CompatibilityMode::Codex)
);
assert_eq!(
CompatibilityMode::from_str("gemini"),
Some(CompatibilityMode::Gemini)
);
assert_eq!(
CompatibilityMode::from_str("native"),
Some(CompatibilityMode::Native)
);
assert_eq!(
CompatibilityMode::from_str("amp"),
Some(CompatibilityMode::Amp)
);
assert_eq!(
CompatibilityMode::from_str("pi"),
Some(CompatibilityMode::Pi)
);
assert_eq!(CompatibilityMode::from_str("unknown"), None);
}
#[test]
fn test_agent_profiles() {
let claude = AgentProfile::claude_code();
assert!(claude.permissions.mount_cwd);
assert!(claude.network_policy.enabled);
assert!(
claude
.network_policy
.always_allow
.contains(&"api.anthropic.com".to_string())
);
assert_eq!(claude.api_key_env, Some("ANTHROPIC_API_KEY".to_string()));
let codex = AgentProfile::codex();
assert!(codex.permissions.read_only_root); // Stricter than Claude
assert_eq!(codex.api_key_env, Some("OPENAI_API_KEY".to_string()));
let gemini = AgentProfile::gemini();
assert!(
gemini
.network_policy
.always_allow
.iter()
.any(|d| d.contains("googleapis.com"))
);
}
#[test]
fn test_network_policy() {
let allow_all = NetworkPolicy::allow_all();
assert!(allow_all.enabled);
assert!(allow_all.always_allow.is_empty());
let deny_all = NetworkPolicy::deny_all();
assert!(!deny_all.enabled);
let claude_net = NetworkPolicy::claude_code();
assert!(claude_net.block.contains(&"169.254.169.254".to_string()));
}
#[test]
fn test_seccomp_profiles_in_security_profiles() {
// Each security profile should have an appropriate seccomp profile
let permissive = SecurityProfile::Permissive.permissions();
assert_eq!(permissive.seccomp, Some("default".to_string()));
let moderate = SecurityProfile::Moderate.permissions();
assert_eq!(moderate.seccomp, Some("moderate".to_string()));
let restrictive = SecurityProfile::Restrictive.permissions();
assert_eq!(restrictive.seccomp, Some("restrictive".to_string()));
}
#[test]
fn test_seccomp_profiles_in_agent_profiles() {
// AI agent profiles should use the ai-agent seccomp profile
let claude = AgentProfile::claude_code();
assert_eq!(claude.permissions.seccomp, Some("ai-agent".to_string()));
let codex = AgentProfile::codex();
assert_eq!(codex.permissions.seccomp, Some("ai-agent".to_string()));
let gemini = AgentProfile::gemini();
assert_eq!(gemini.permissions.seccomp, Some("ai-agent".to_string()));
}
#[test]
fn test_seccomp_resolve_path_none() {
// No seccomp profile should return None
let mut perms = Permissions::default();
perms.seccomp = None;
assert!(perms.resolve_seccomp_path().is_none());
}
#[test]
fn test_seccomp_resolve_path_builtin() {
// Built-in profile should resolve if files exist in images/seccomp/
let perms = SecurityProfile::Moderate.permissions();
// This test will pass in development environment where images/seccomp/ exists
// In production, it may return None if profiles aren't installed
let path = perms.resolve_seccomp_path();
if let Some(p) = path {
assert!(p.to_string_lossy().contains("moderate.json"));
}
}
#[test]
fn test_seccomp_resolve_path_custom() {
// Custom path that doesn't exist should return None
let mut perms = Permissions::default();
perms.seccomp = Some("/nonexistent/custom/profile.json".to_string());
assert!(perms.resolve_seccomp_path().is_none());
}
#[test]
fn test_docker_args_include_seccomp() {
// When seccomp profile resolves, it should be included in docker args
let perms = SecurityProfile::Moderate.permissions();
let args = perms.to_docker_args();
// Check if seccomp is present (only if profile file exists)
let has_seccomp = args
.iter()
.any(|a| a.starts_with("--security-opt=seccomp="));
// This may be true or false depending on whether the profile files exist
// The important thing is the code doesn't panic
let _ = has_seccomp;
}
}