Skip to main content

symbi_runtime/types/
security.rs

1//! Security-related types and data structures
2
3use serde::{Deserialize, Serialize};
4use std::time::{Duration, SystemTime};
5
6use super::{AgentId, PolicyId};
7
8/// Security tiers for sandboxing
9#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
10pub enum SecurityTier {
11    /// No isolation - native execution (⚠️ DEVELOPMENT ONLY)
12    None,
13    /// Docker-based isolation
14    #[default]
15    Tier1,
16    /// gVisor-based isolation
17    Tier2,
18    /// Firecracker-based isolation
19    Tier3,
20}
21
22impl std::fmt::Display for SecurityTier {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        match self {
25            SecurityTier::None => write!(f, "None (Native - No Isolation ⚠️)"),
26            SecurityTier::Tier1 => write!(f, "Tier1 (Docker)"),
27            SecurityTier::Tier2 => write!(f, "Tier2 (gVisor)"),
28            SecurityTier::Tier3 => write!(f, "Tier3 (Firecracker)"),
29        }
30    }
31}
32
33/// Risk assessment levels
34#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
35pub enum RiskLevel {
36    Low,
37    #[default]
38    Medium,
39    High,
40    Critical,
41}
42
43/// Security configuration for the runtime
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct SecurityConfig {
46    pub default_security_tier: SecurityTier,
47    pub encryption_enabled: bool,
48    pub signature_required: bool,
49    pub policy_enforcement_strict: bool,
50    pub sandbox_isolation_level: IsolationLevel,
51    pub audit_all_operations: bool,
52    pub e2b_api_key: Option<String>,
53    /// Allow native execution without isolation (⚠️ DEVELOPMENT ONLY)
54    pub allow_native_execution: bool,
55}
56
57impl Default for SecurityConfig {
58    fn default() -> Self {
59        Self {
60            default_security_tier: SecurityTier::Tier1,
61            encryption_enabled: true,
62            signature_required: true,
63            policy_enforcement_strict: true,
64            sandbox_isolation_level: IsolationLevel::High,
65            audit_all_operations: true,
66            e2b_api_key: None,
67            allow_native_execution: false,
68        }
69    }
70}
71
72/// Isolation levels for sandboxing
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
74pub enum IsolationLevel {
75    None,
76    Low,
77    Medium,
78    #[default]
79    High,
80    Maximum,
81}
82
83/// Policy context for enforcement decisions
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct PolicyContext {
86    pub agent_id: AgentId,
87    pub operation: String,
88    pub resource: Option<String>,
89    pub timestamp: SystemTime,
90    pub security_tier: SecurityTier,
91    pub risk_level: RiskLevel,
92}
93
94/// Policy decision result
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96pub enum PolicyDecision {
97    Allow,
98    Deny(String),
99    RequireApproval(String),
100}
101
102/// Policy enforcement result
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct PolicyResult {
105    pub decision: PolicyDecision,
106    pub policy_id: Option<PolicyId>,
107    pub reason: Option<String>,
108    pub timestamp: SystemTime,
109}
110
111impl PolicyResult {
112    pub fn allow() -> Self {
113        Self {
114            decision: PolicyDecision::Allow,
115            policy_id: None,
116            reason: None,
117            timestamp: SystemTime::now(),
118        }
119    }
120
121    pub fn deny(reason: String) -> Self {
122        Self {
123            decision: PolicyDecision::Deny(reason.clone()),
124            policy_id: None,
125            reason: Some(reason),
126            timestamp: SystemTime::now(),
127        }
128    }
129
130    pub fn require_approval(reason: String) -> Self {
131        Self {
132            decision: PolicyDecision::RequireApproval(reason.clone()),
133            policy_id: None,
134            reason: Some(reason),
135            timestamp: SystemTime::now(),
136        }
137    }
138}
139
140/// Types of security events
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142pub enum SecurityEventType {
143    PolicyViolation,
144    UnauthorizedAccess,
145    EncryptionFailure,
146    SignatureVerificationFailure,
147    SandboxBreach,
148    ResourceExhaustion,
149    SuspiciousActivity,
150    CronJobDeadLettered,
151    AgentPinVerificationFailed,
152}
153
154/// Policy violation details
155#[derive(Debug, Clone, Serialize, Deserialize)]
156pub struct PolicyViolation {
157    pub policy_id: PolicyId,
158    pub violation_type: String,
159    pub description: String,
160    pub severity: ViolationSeverity,
161    pub timestamp: SystemTime,
162}
163
164/// Severity levels for policy violations
165#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
166pub enum ViolationSeverity {
167    Info,
168    #[default]
169    Warning,
170    Error,
171    Critical,
172}
173
174/// Audit event types for the cryptographic audit trail
175#[derive(Debug, Clone, Serialize, Deserialize)]
176pub enum AuditEvent {
177    AgentCreated {
178        agent_id: AgentId,
179        config_hash: String,
180    },
181    AgentStarted {
182        agent_id: AgentId,
183        timestamp: SystemTime,
184    },
185    AgentTerminated {
186        agent_id: AgentId,
187        reason: super::agent::TerminationReason,
188    },
189    MessageSent {
190        from: AgentId,
191        to: Option<AgentId>,
192        message_id: super::MessageId,
193    },
194    PolicyViolation {
195        agent_id: AgentId,
196        violation: PolicyViolation,
197    },
198    ResourceAllocation {
199        agent_id: AgentId,
200        resources: super::resource::ResourceAllocation,
201    },
202    SecurityEvent {
203        event_type: SecurityEventType,
204        details: String,
205    },
206}
207
208/// Audit query for searching events
209#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct AuditQuery {
211    pub agent_id: Option<AgentId>,
212    pub event_types: Vec<String>,
213    pub start_time: Option<SystemTime>,
214    pub end_time: Option<SystemTime>,
215    pub limit: Option<usize>,
216}
217
218/// Audit configuration
219#[derive(Debug, Clone, Serialize, Deserialize)]
220pub struct AuditConfig {
221    pub enabled: bool,
222    pub sign_events: bool,
223    pub encrypt_events: bool,
224    pub retention_duration: Duration,
225    pub max_events_per_agent: usize,
226}
227
228impl Default for AuditConfig {
229    fn default() -> Self {
230        Self {
231            enabled: true,
232            sign_events: true,
233            encrypt_events: true,
234            retention_duration: Duration::from_secs(86400 * 365), // 1 year
235            max_events_per_agent: 10000,
236        }
237    }
238}
239
240/// Sandbox configuration for different security tiers
241#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct SandboxConfig {
243    pub security_tier: SecurityTier,
244    pub isolation_level: IsolationLevel,
245    pub network_isolation: bool,
246    pub filesystem_isolation: bool,
247    pub resource_limits: super::resource::ResourceLimits,
248    pub allowed_syscalls: Vec<String>,
249    pub environment_variables: std::collections::HashMap<String, String>,
250}
251
252impl Default for SandboxConfig {
253    fn default() -> Self {
254        Self {
255            security_tier: SecurityTier::Tier1,
256            isolation_level: IsolationLevel::High,
257            network_isolation: true,
258            filesystem_isolation: true,
259            resource_limits: super::resource::ResourceLimits::default(),
260            allowed_syscalls: vec![
261                "read".to_string(),
262                "write".to_string(),
263                "open".to_string(),
264                "close".to_string(),
265            ],
266            environment_variables: std::collections::HashMap::new(),
267        }
268    }
269}
270
271/// Sandbox status information
272#[derive(Debug, Clone, Serialize, Deserialize)]
273pub struct SandboxStatus {
274    pub id: String,
275    pub state: SandboxState,
276    pub security_tier: SecurityTier,
277    pub resource_usage: super::resource::ResourceUsage,
278    pub uptime: Duration,
279    pub last_activity: SystemTime,
280}
281
282/// Sandbox state
283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
284pub enum SandboxState {
285    #[default]
286    Creating,
287    Ready,
288    Running,
289    Suspended,
290    Terminating,
291    Terminated,
292    Failed,
293}
294
295/// Represents different types of capabilities that agents can request
296#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
297pub enum Capability {
298    /// File system operations
299    FileRead(String),
300    FileWrite(String),
301    FileDelete(String),
302
303    /// Network operations
304    NetworkRequest(String),
305    NetworkListen(u16),
306
307    /// System operations
308    Execute(String),
309    EnvironmentRead(String),
310    EnvironmentWrite(String),
311
312    /// Agent operations
313    AgentCreate,
314    AgentDelete,
315    AgentModify,
316
317    /// Data operations
318    DataRead(String),
319    DataWrite(String),
320    DataDelete(String),
321}