use super::{RuntimeResult, RuntimeError, RuntimeConfig};
use std::time::{Duration, Instant};
pub struct SecuritySandbox {
limits: ResourceLimits,
usage: ResourceUsage,
policies: SecurityPolicies,
monitor: ExecutionMonitor,
}
#[derive(Debug, Clone)]
pub struct ResourceLimits {
pub max_memory_bytes: usize,
pub max_execution_time: Duration,
pub max_cpu_percent: f64,
pub max_function_calls: u32,
pub max_recursion_depth: u32,
pub max_file_descriptors: u32,
pub max_network_connections: u32,
}
#[derive(Debug, Clone, Default)]
pub struct ResourceUsage {
pub memory_bytes: usize,
pub peak_memory_bytes: usize,
pub execution_start: Option<Instant>,
pub total_execution_time: Duration,
pub function_calls: u32,
pub recursion_depth: u32,
pub open_file_descriptors: u32,
pub network_connections: u32,
}
#[derive(Debug, Clone)]
pub struct SecurityPolicies {
pub allow_file_access: bool,
pub allow_network_access: bool,
pub allow_system_calls: bool,
pub allowed_paths: Vec<String>,
pub allowed_hosts: Vec<String>,
pub allowed_syscalls: Vec<String>,
pub allow_debugging: bool,
}
#[derive(Debug, Clone, Default)]
pub struct ExecutionMonitor {
pub violations_count: u32,
pub violation_types: Vec<ViolationType>,
pub warnings_count: u32,
pub last_health_check: Option<Instant>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ViolationType {
UnauthorizedFileAccess(String),
UnauthorizedNetworkAccess(String),
ForbiddenSystemCall(String),
ResourceLimitExceeded(ResourceType),
SuspiciousPattern(String),
CodeInjection,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ResourceType {
Memory,
ExecutionTime,
CpuUsage,
FunctionCalls,
RecursionDepth,
FileDescriptors,
NetworkConnections,
}
pub struct SandboxContext {
pub execution_id: String,
pub function_name: String,
pub runtime_type: RuntimeType,
pub start_time: Instant,
pub query_context: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum RuntimeType {
Lua,
Wasm,
Native,
}
impl SecuritySandbox {
pub fn new(config: RuntimeConfig) -> Self {
let limits = ResourceLimits {
max_memory_bytes: config.max_memory_bytes,
max_execution_time: Duration::from_millis(config.max_execution_time_ms),
max_cpu_percent: 80.0,
max_function_calls: 10_000,
max_recursion_depth: config.max_stack_depth as u32,
max_file_descriptors: 0,
max_network_connections: 0,
};
let policies = SecurityPolicies {
allow_file_access: false,
allow_network_access: false,
allow_system_calls: false,
allowed_paths: Vec::new(),
allowed_hosts: Vec::new(),
allowed_syscalls: Vec::new(),
allow_debugging: false,
};
Self {
limits,
usage: ResourceUsage::default(),
policies,
monitor: ExecutionMonitor::default(),
}
}
pub fn begin_execution(&mut self, context: SandboxContext) -> RuntimeResult<SandboxGuard<'_>> {
self.usage.execution_start = Some(Instant::now());
self.usage.function_calls = 0;
self.usage.recursion_depth = 0;
Ok(SandboxGuard {
sandbox: self,
context,
})
}
pub fn check_resource_limits(&mut self) -> RuntimeResult<()> {
if self.usage.memory_bytes > self.limits.max_memory_bytes {
self.record_violation(ViolationType::ResourceLimitExceeded(ResourceType::Memory));
return Err(RuntimeError::ResourceLimitExceeded(
format!("Memory limit exceeded: {} > {}",
self.usage.memory_bytes, self.limits.max_memory_bytes)
));
}
if let Some(start_time) = self.usage.execution_start {
let elapsed = start_time.elapsed();
if elapsed > self.limits.max_execution_time {
self.record_violation(ViolationType::ResourceLimitExceeded(ResourceType::ExecutionTime));
return Err(RuntimeError::ResourceLimitExceeded(
format!("Execution time limit exceeded: {:?} > {:?}",
elapsed, self.limits.max_execution_time)
));
}
}
Ok(())
}
fn record_violation(&mut self, violation: ViolationType) {
self.monitor.violations_count += 1;
self.monitor.violation_types.push(violation);
}
pub fn update_memory_usage(&mut self, new_usage: usize) {
self.usage.memory_bytes = new_usage;
if new_usage > self.usage.peak_memory_bytes {
self.usage.peak_memory_bytes = new_usage;
}
}
pub fn get_usage_stats(&self) -> &ResourceUsage {
&self.usage
}
pub fn get_violation_summary(&self) -> ViolationSummary {
ViolationSummary {
total_violations: self.monitor.violations_count,
violation_types: self.monitor.violation_types.clone(),
warnings_issued: self.monitor.warnings_count,
}
}
}
pub struct SandboxGuard<'a> {
sandbox: &'a mut SecuritySandbox,
context: SandboxContext,
}
impl<'a> SandboxGuard<'a> {
pub fn context(&self) -> &SandboxContext {
&self.context
}
pub fn check_limits(&mut self) -> RuntimeResult<()> {
self.sandbox.check_resource_limits()
}
}
impl<'a> Drop for SandboxGuard<'a> {
fn drop(&mut self) {
if let Some(start_time) = self.sandbox.usage.execution_start {
self.sandbox.usage.total_execution_time += start_time.elapsed();
self.sandbox.usage.execution_start = None;
}
}
}
#[derive(Debug, Clone)]
pub struct ViolationSummary {
pub total_violations: u32,
pub violation_types: Vec<ViolationType>,
pub warnings_issued: u32,
}