symbi-runtime 3.0.0

Agent Runtime System for the Symbi platform
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
//! Security-related types and data structures

use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::time::{Duration, SystemTime};

use super::{AgentId, PolicyId};

/// Security tiers for sandboxing.
///
/// `Tier1` → `Tier3` form a monotonically increasing host-isolation ladder
/// (Docker → gVisor → Firecracker). `Hosted` is **not** a peer on that
/// ladder — it represents execution on third-party infrastructure (e.g.
/// E2B) where the operator does not run their own sandbox host. It carries
/// no on-host isolation guarantees but is not outright `None`, so it sits
/// between `None` and `Tier1` on that ladder. `Landlock` is a separate native
/// Linux boundary: it is stronger than `None`, but deliberately incomparable
/// with hosted execution and the container/VM ladder.
///
/// Use [`SecurityTier::satisfies`] for minimum-requirement decisions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum SecurityTier {
    /// No isolation — native execution (⚠️ DEVELOPMENT ONLY)
    None,
    /// Hosted cloud execution (e.g. E2B) — code runs on third-party
    /// infrastructure. No on-host isolation guarantees; trust assumption
    /// is "you trust the hosting provider."
    Hosted,
    /// Native Linux Landlock, seccomp and namespace isolation
    Landlock,
    /// Docker-based isolation
    #[default]
    Tier1,
    /// gVisor-based isolation
    Tier2,
    /// Firecracker-based isolation
    Tier3,
}

impl PartialOrd for SecurityTier {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        use SecurityTier::*;
        if self == other {
            return Some(Ordering::Equal);
        }
        match (self, other) {
            (None, _) => Some(Ordering::Less),
            (_, None) => Some(Ordering::Greater),
            (Landlock, _) | (_, Landlock) => Option::None,
            _ => {
                let rank = |tier: &SecurityTier| match tier {
                    Hosted => 1,
                    Tier1 => 2,
                    Tier2 => 3,
                    Tier3 => 4,
                    None | Landlock => unreachable!(),
                };
                rank(self).partial_cmp(&rank(other))
            }
        }
    }
}

impl std::fmt::Display for SecurityTier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SecurityTier::None => write!(f, "None (Native - No Isolation ⚠️)"),
            SecurityTier::Hosted => write!(f, "Hosted (third-party cloud sandbox)"),
            SecurityTier::Landlock => write!(f, "Landlock (native Linux isolation)"),
            SecurityTier::Tier1 => write!(f, "Tier1 (Docker)"),
            SecurityTier::Tier2 => write!(f, "Tier2 (gVisor)"),
            SecurityTier::Tier3 => write!(f, "Tier3 (Firecracker)"),
        }
    }
}

impl SecurityTier {
    /// Map a DSL `sandbox_tier` value to the runtime's `SecurityTier`.
    ///
    /// `dsl::SandboxTier::E2B` maps to `Hosted` — it is not a host-
    /// isolation tier. The runner factory still picks the actual E2B
    /// backend; this mapping only affects how the agent's security
    /// requirements are categorised in policy decisions.
    pub fn from_dsl_sandbox(tier: &dsl::SandboxTier) -> Self {
        match tier {
            dsl::SandboxTier::Docker => SecurityTier::Tier1,
            dsl::SandboxTier::Landlock => SecurityTier::Landlock,
            dsl::SandboxTier::GVisor => SecurityTier::Tier2,
            dsl::SandboxTier::Firecracker => SecurityTier::Tier3,
            dsl::SandboxTier::E2B => SecurityTier::Hosted,
        }
    }

    /// Whether this selected boundary satisfies an explicit minimum.
    ///
    /// Every non-`None` backend satisfies `None`. Landlock satisfies only
    /// `Landlock` (and `None`); it never silently substitutes for a container,
    /// VM or hosted-execution requirement.
    pub fn satisfies(&self, required: &Self) -> bool {
        matches!(
            self.partial_cmp(required),
            Some(Ordering::Equal | Ordering::Greater)
        )
    }
}

/// Risk assessment levels
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
pub enum RiskLevel {
    Low,
    #[default]
    Medium,
    High,
    Critical,
}

/// Security configuration for the runtime
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    pub default_security_tier: SecurityTier,
    pub encryption_enabled: bool,
    pub signature_required: bool,
    pub policy_enforcement_strict: bool,
    pub sandbox_isolation_level: IsolationLevel,
    pub audit_all_operations: bool,
    pub e2b_api_key: Option<String>,
    /// Allow native execution without isolation (⚠️ DEVELOPMENT ONLY)
    pub allow_native_execution: bool,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            default_security_tier: SecurityTier::Tier1,
            encryption_enabled: true,
            signature_required: true,
            policy_enforcement_strict: true,
            sandbox_isolation_level: IsolationLevel::High,
            audit_all_operations: true,
            e2b_api_key: None,
            allow_native_execution: false,
        }
    }
}

/// Isolation levels for sandboxing
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum IsolationLevel {
    None,
    Low,
    Medium,
    #[default]
    High,
    Maximum,
}

/// Policy context for enforcement decisions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyContext {
    pub agent_id: AgentId,
    pub operation: String,
    pub resource: Option<String>,
    pub timestamp: SystemTime,
    pub security_tier: SecurityTier,
    pub risk_level: RiskLevel,
}

/// Policy decision result
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PolicyDecision {
    Allow,
    Deny(String),
    RequireApproval(String),
}

/// Policy enforcement result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyResult {
    pub decision: PolicyDecision,
    pub policy_id: Option<PolicyId>,
    pub reason: Option<String>,
    pub timestamp: SystemTime,
}

impl PolicyResult {
    pub fn allow() -> Self {
        Self {
            decision: PolicyDecision::Allow,
            policy_id: None,
            reason: None,
            timestamp: SystemTime::now(),
        }
    }

    pub fn deny(reason: String) -> Self {
        Self {
            decision: PolicyDecision::Deny(reason.clone()),
            policy_id: None,
            reason: Some(reason),
            timestamp: SystemTime::now(),
        }
    }

    pub fn require_approval(reason: String) -> Self {
        Self {
            decision: PolicyDecision::RequireApproval(reason.clone()),
            policy_id: None,
            reason: Some(reason),
            timestamp: SystemTime::now(),
        }
    }
}

/// Types of security events
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SecurityEventType {
    PolicyViolation,
    UnauthorizedAccess,
    EncryptionFailure,
    SignatureVerificationFailure,
    SandboxBreach,
    ResourceExhaustion,
    SuspiciousActivity,
    CronJobDeadLettered,
    AgentPinVerificationFailed,
}

/// Policy violation details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyViolation {
    pub policy_id: PolicyId,
    pub violation_type: String,
    pub description: String,
    pub severity: ViolationSeverity,
    pub timestamp: SystemTime,
}

/// Severity levels for policy violations
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
pub enum ViolationSeverity {
    Info,
    #[default]
    Warning,
    Error,
    Critical,
}

/// Audit event types for the cryptographic audit trail
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AuditEvent {
    AgentCreated {
        agent_id: AgentId,
        config_hash: String,
    },
    AgentStarted {
        agent_id: AgentId,
        timestamp: SystemTime,
    },
    AgentTerminated {
        agent_id: AgentId,
        reason: super::agent::TerminationReason,
    },
    MessageSent {
        from: AgentId,
        to: Option<AgentId>,
        message_id: super::MessageId,
    },
    PolicyViolation {
        agent_id: AgentId,
        violation: PolicyViolation,
    },
    ResourceAllocation {
        agent_id: AgentId,
        resources: super::resource::ResourceAllocation,
    },
    SecurityEvent {
        event_type: SecurityEventType,
        details: String,
    },
}

/// Audit query for searching events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditQuery {
    pub agent_id: Option<AgentId>,
    pub event_types: Vec<String>,
    pub start_time: Option<SystemTime>,
    pub end_time: Option<SystemTime>,
    pub limit: Option<usize>,
}

/// Audit configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditConfig {
    pub enabled: bool,
    pub sign_events: bool,
    pub encrypt_events: bool,
    pub retention_duration: Duration,
    pub max_events_per_agent: usize,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            sign_events: true,
            encrypt_events: true,
            retention_duration: Duration::from_secs(86400 * 365), // 1 year
            max_events_per_agent: 10000,
        }
    }
}

/// Sandbox configuration for different security tiers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxConfig {
    pub security_tier: SecurityTier,
    pub isolation_level: IsolationLevel,
    pub network_isolation: bool,
    pub filesystem_isolation: bool,
    pub resource_limits: super::resource::ResourceLimits,
    pub allowed_syscalls: Vec<String>,
    pub environment_variables: std::collections::HashMap<String, String>,
}

impl Default for SandboxConfig {
    fn default() -> Self {
        Self {
            security_tier: SecurityTier::Tier1,
            isolation_level: IsolationLevel::High,
            network_isolation: true,
            filesystem_isolation: true,
            resource_limits: super::resource::ResourceLimits::default(),
            allowed_syscalls: vec![
                "read".to_string(),
                "write".to_string(),
                "open".to_string(),
                "close".to_string(),
            ],
            environment_variables: std::collections::HashMap::new(),
        }
    }
}

/// Sandbox status information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxStatus {
    pub id: String,
    pub state: SandboxState,
    pub security_tier: SecurityTier,
    pub resource_usage: super::resource::ResourceUsage,
    pub uptime: Duration,
    pub last_activity: SystemTime,
}

/// Sandbox state
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum SandboxState {
    #[default]
    Creating,
    Ready,
    Running,
    Suspended,
    Terminating,
    Terminated,
    Failed,
}

/// Represents different types of capabilities that agents can request
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Capability {
    /// File system operations
    FileRead(String),
    FileWrite(String),
    FileDelete(String),

    /// Network operations
    NetworkRequest(String),
    NetworkListen(u16),

    /// System operations
    Execute(String),
    EnvironmentRead(String),
    EnvironmentWrite(String),

    /// Agent operations
    AgentCreate,
    AgentDelete,
    AgentModify,

    /// Data operations
    DataRead(String),
    DataWrite(String),
    DataDelete(String),
}

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

    #[test]
    fn dsl_sandbox_maps_to_runtime_tier() {
        assert_eq!(
            SecurityTier::from_dsl_sandbox(&dsl::SandboxTier::Landlock),
            SecurityTier::Landlock
        );
        assert_eq!(
            SecurityTier::from_dsl_sandbox(&dsl::SandboxTier::Docker),
            SecurityTier::Tier1
        );
        assert_eq!(
            SecurityTier::from_dsl_sandbox(&dsl::SandboxTier::GVisor),
            SecurityTier::Tier2
        );
        assert_eq!(
            SecurityTier::from_dsl_sandbox(&dsl::SandboxTier::Firecracker),
            SecurityTier::Tier3
        );
        // E2B is hosted (third-party cloud), not a host-isolation tier.
        assert_eq!(
            SecurityTier::from_dsl_sandbox(&dsl::SandboxTier::E2B),
            SecurityTier::Hosted
        );
    }

    #[test]
    fn hosted_orders_below_tier1() {
        // Policies that require host isolation use `tier >= Tier1`. Hosted
        // must sort below Tier1 so those checks reject it.
        assert!(SecurityTier::Hosted < SecurityTier::Tier1);
        assert!(SecurityTier::Hosted < SecurityTier::Tier2);
        assert!(SecurityTier::Hosted < SecurityTier::Tier3);
        assert!(SecurityTier::None < SecurityTier::Hosted);
    }

    #[test]
    fn landlock_is_an_explicit_partial_order_branch() {
        assert!(SecurityTier::Landlock > SecurityTier::None);
        assert_eq!(
            SecurityTier::Landlock.partial_cmp(&SecurityTier::Hosted),
            None
        );
        assert_eq!(
            SecurityTier::Landlock.partial_cmp(&SecurityTier::Tier1),
            None
        );
        assert!(SecurityTier::Landlock.satisfies(&SecurityTier::Landlock));
        assert!(SecurityTier::Landlock.satisfies(&SecurityTier::None));
        assert!(!SecurityTier::Landlock.satisfies(&SecurityTier::Tier1));
        assert!(!SecurityTier::Tier3.satisfies(&SecurityTier::Landlock));
        assert!(SecurityTier::Tier3.satisfies(&SecurityTier::Tier1));
    }
}