| |
| |
| |
| |
| |
| |
| |
| |
|
|
| use anyhow::{anyhow, Result}; |
| use heed::types::*; |
| use heed::{Database, Env, EnvOpenOptions}; |
| use serde::{Deserialize, Serialize}; |
| use std::path::Path; |
| use std::time::{SystemTime, UNIX_EPOCH}; |
|
|
| const MAX_DB_SIZE: usize = 256 * 1024 * 1024; |
|
|
| |
| #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] |
| pub enum TrustLevel { |
| |
| Untrusted = 0, |
| |
| Low = 1, |
| |
| Medium = 2, |
| |
| High = 3, |
| |
| Full = 4, |
| } |
|
|
| impl Default for TrustLevel { |
| fn default() -> Self { |
| TrustLevel::Low |
| } |
| } |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct Project { |
| |
| pub path: String, |
| |
| pub name: String, |
| |
| pub trust_level: TrustLevel, |
| |
| pub allowed_tools: Vec<String>, |
| |
| pub denied_tools: Vec<String>, |
| |
| pub protected_paths: Vec<String>, |
| |
| pub max_write_size: usize, |
| |
| pub max_writes_per_session: u32, |
| |
| pub session_writes: u32, |
| |
| pub total_reads: u64, |
| |
| pub total_writes: u64, |
| |
| pub total_complexity: u64, |
| |
| pub created_at: u64, |
| |
| pub last_accessed: u64, |
| |
| pub requires_activation: bool, |
| |
| pub is_active: bool, |
| |
| pub notes: String, |
| } |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct FileAccess { |
| |
| pub path: String, |
| |
| pub project: String, |
| |
| pub access_type: String, |
| |
| pub timestamp: u64, |
| |
| pub session_id: String, |
| |
| pub file_size: u64, |
| |
| pub allowed: bool, |
| |
| pub deny_reason: Option<String>, |
| } |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize, Default)] |
| pub struct ResourceUsage { |
| |
| pub bytes_read: u64, |
| |
| pub bytes_written: u64, |
| |
| pub files_created: u64, |
| |
| pub files_deleted: u64, |
| |
| pub bash_commands: u64, |
| |
| pub web_requests: u64, |
| } |
|
|
| |
| pub struct SpfTmpDb { |
| env: Env, |
| |
| projects: Database<Str, SerdeBincode<Project>>, |
| |
| access_log: Database<Str, SerdeBincode<FileAccess>>, |
| |
| resources: Database<Str, SerdeBincode<ResourceUsage>>, |
| |
| active: Database<Str, Str>, |
| } |
|
|
| impl SpfTmpDb { |
| |
| pub fn open(path: &Path) -> Result<Self> { |
| std::fs::create_dir_all(path)?; |
|
|
| let env = unsafe { |
| EnvOpenOptions::new() |
| .map_size(MAX_DB_SIZE) |
| .max_dbs(8) |
| .open(path)? |
| }; |
|
|
| let mut wtxn = env.write_txn()?; |
| let projects = env.create_database(&mut wtxn, Some("projects"))?; |
| let access_log = env.create_database(&mut wtxn, Some("access_log"))?; |
| let resources = env.create_database(&mut wtxn, Some("resources"))?; |
| let active = env.create_database(&mut wtxn, Some("active"))?; |
| wtxn.commit()?; |
|
|
| log::info!("TMP_DB LMDB opened at {:?}", path); |
| Ok(Self { env, projects, access_log, resources, active }) |
| } |
|
|
| |
| |
| |
|
|
| |
| pub fn register_project(&self, path: &str, name: &str, trust_level: TrustLevel) -> Result<Project> { |
| let canonical = std::fs::canonicalize(path) |
| .map(|p| p.to_string_lossy().to_string()) |
| .unwrap_or_else(|_| path.to_string()); |
|
|
| let now = SystemTime::now() |
| .duration_since(UNIX_EPOCH) |
| .unwrap_or_default() |
| .as_secs(); |
|
|
| let project = Project { |
| path: canonical.clone(), |
| name: name.to_string(), |
| trust_level, |
| allowed_tools: Vec::new(), |
| denied_tools: Vec::new(), |
| protected_paths: vec![".git".to_string(), ".env".to_string()], |
| max_write_size: 100_000, |
| max_writes_per_session: 100, |
| session_writes: 0, |
| total_reads: 0, |
| total_writes: 0, |
| total_complexity: 0, |
| created_at: now, |
| last_accessed: now, |
| requires_activation: trust_level < TrustLevel::High, |
| is_active: false, |
| notes: String::new(), |
| }; |
|
|
| let mut wtxn = self.env.write_txn()?; |
| self.projects.put(&mut wtxn, &canonical, &project)?; |
| self.resources.put(&mut wtxn, &canonical, &ResourceUsage::default())?; |
| wtxn.commit()?; |
|
|
| Ok(project) |
| } |
|
|
| |
| pub fn get_project(&self, path: &str) -> Result<Option<Project>> { |
| let canonical = std::fs::canonicalize(path) |
| .map(|p| p.to_string_lossy().to_string()) |
| .unwrap_or_else(|_| path.to_string()); |
|
|
| let rtxn = self.env.read_txn()?; |
| Ok(self.projects.get(&rtxn, &canonical)?) |
| } |
|
|
| |
| pub fn update_project(&self, project: &Project) -> Result<()> { |
| let mut wtxn = self.env.write_txn()?; |
| self.projects.put(&mut wtxn, &project.path, project)?; |
| wtxn.commit()?; |
| Ok(()) |
| } |
|
|
| |
| pub fn find_project_for_path(&self, file_path: &str) -> Result<Option<Project>> { |
| let canonical = std::fs::canonicalize(file_path) |
| .map(|p| p.to_string_lossy().to_string()) |
| .unwrap_or_else(|_| file_path.to_string()); |
|
|
| let rtxn = self.env.read_txn()?; |
| let iter = self.projects.iter(&rtxn)?; |
|
|
| |
| let mut best_match: Option<Project> = None; |
| let mut best_len = 0; |
|
|
| for result in iter { |
| let (project_path, project) = result?; |
| if canonical.starts_with(project_path) && project_path.len() > best_len { |
| best_match = Some(project); |
| best_len = project_path.len(); |
| } |
| } |
|
|
| Ok(best_match) |
| } |
|
|
| |
| pub fn list_projects(&self) -> Result<Vec<Project>> { |
| let rtxn = self.env.read_txn()?; |
| let iter = self.projects.iter(&rtxn)?; |
|
|
| let mut projects = Vec::new(); |
| for result in iter { |
| let (_, project) = result?; |
| projects.push(project); |
| } |
| Ok(projects) |
| } |
|
|
| |
| pub fn delete_project(&self, path: &str) -> Result<bool> { |
| let canonical = std::fs::canonicalize(path) |
| .map(|p| p.to_string_lossy().to_string()) |
| .unwrap_or_else(|_| path.to_string()); |
|
|
| let mut wtxn = self.env.write_txn()?; |
| let deleted = self.projects.delete(&mut wtxn, &canonical)?; |
| self.resources.delete(&mut wtxn, &canonical)?; |
| wtxn.commit()?; |
| Ok(deleted) |
| } |
|
|
| |
| |
| |
|
|
| |
| pub fn set_trust_level(&self, path: &str, level: TrustLevel) -> Result<()> { |
| let mut project = self.get_project(path)? |
| .ok_or_else(|| anyhow!("Project not found: {}", path))?; |
| project.trust_level = level; |
| project.requires_activation = level < TrustLevel::High; |
| self.update_project(&project) |
| } |
|
|
| |
| pub fn is_tool_allowed(&self, project_path: &str, tool: &str) -> Result<bool> { |
| let project = match self.get_project(project_path)? { |
| Some(s) => s, |
| None => return Ok(true), |
| }; |
|
|
| |
| if project.denied_tools.contains(&tool.to_string()) { |
| return Ok(false); |
| } |
|
|
| |
| if project.allowed_tools.contains(&tool.to_string()) { |
| return Ok(true); |
| } |
|
|
| |
| Ok(match project.trust_level { |
| TrustLevel::Untrusted => false, |
| TrustLevel::Low => matches!(tool, "Read" | "Glob" | "Grep"), |
| TrustLevel::Medium => !matches!(tool, "Bash"), |
| TrustLevel::High | TrustLevel::Full => true, |
| }) |
| } |
|
|
| |
| pub fn is_path_protected(&self, project_path: &str, file_path: &str) -> Result<bool> { |
| let project = match self.get_project(project_path)? { |
| Some(s) => s, |
| None => return Ok(false), |
| }; |
|
|
| |
| let relative = file_path.strip_prefix(&project.path) |
| .unwrap_or(file_path) |
| .trim_start_matches('/'); |
|
|
| for protected in &project.protected_paths { |
| if relative.starts_with(protected) || relative == *protected { |
| return Ok(true); |
| } |
| } |
| Ok(false) |
| } |
|
|
| |
| pub fn add_protected_path(&self, project_path: &str, protected: &str) -> Result<()> { |
| let mut project = self.get_project(project_path)? |
| .ok_or_else(|| anyhow!("Project not found: {}", project_path))?; |
|
|
| if !project.protected_paths.contains(&protected.to_string()) { |
| project.protected_paths.push(protected.to_string()); |
| self.update_project(&project)?; |
| } |
| Ok(()) |
| } |
|
|
| |
| |
| |
|
|
| |
| pub fn set_active(&self, path: &str) -> Result<()> { |
| let canonical = std::fs::canonicalize(path) |
| .map(|p| p.to_string_lossy().to_string()) |
| .unwrap_or_else(|_| path.to_string()); |
|
|
| |
| if let Some(current) = self.get_active()? { |
| let mut project = self.get_project(¤t)? |
| .ok_or_else(|| anyhow!("Active project not found"))?; |
| project.is_active = false; |
| self.update_project(&project)?; |
| } |
|
|
| |
| let mut project = self.get_project(&canonical)? |
| .ok_or_else(|| anyhow!("Project not found: {}", canonical))?; |
| project.is_active = true; |
| project.last_accessed = SystemTime::now() |
| .duration_since(UNIX_EPOCH) |
| .unwrap_or_default() |
| .as_secs(); |
| self.update_project(&project)?; |
|
|
| let mut wtxn = self.env.write_txn()?; |
| self.active.put(&mut wtxn, "active", &canonical)?; |
| wtxn.commit()?; |
| Ok(()) |
| } |
|
|
| |
| pub fn get_active(&self) -> Result<Option<String>> { |
| let rtxn = self.env.read_txn()?; |
| Ok(self.active.get(&rtxn, "active")?.map(|s| s.to_string())) |
| } |
|
|
| |
| pub fn clear_active(&self) -> Result<()> { |
| if let Some(current) = self.get_active()? { |
| if let Some(mut project) = self.get_project(¤t)? { |
| project.is_active = false; |
| self.update_project(&project)?; |
| } |
| } |
| let mut wtxn = self.env.write_txn()?; |
| self.active.delete(&mut wtxn, "active")?; |
| wtxn.commit()?; |
| Ok(()) |
| } |
|
|
| |
| |
| |
|
|
| |
| pub fn log_access( |
| &self, |
| file_path: &str, |
| project_path: &str, |
| access_type: &str, |
| session_id: &str, |
| file_size: u64, |
| allowed: bool, |
| deny_reason: Option<&str>, |
| ) -> Result<()> { |
| let now = SystemTime::now() |
| .duration_since(UNIX_EPOCH) |
| .unwrap_or_default() |
| .as_secs(); |
|
|
| let access = FileAccess { |
| path: file_path.to_string(), |
| project: project_path.to_string(), |
| access_type: access_type.to_string(), |
| timestamp: now, |
| session_id: session_id.to_string(), |
| file_size, |
| allowed, |
| deny_reason: deny_reason.map(|s| s.to_string()), |
| }; |
|
|
| let key = format!("{}:{}:{}", now, project_path, file_path); |
| let mut wtxn = self.env.write_txn()?; |
| self.access_log.put(&mut wtxn, &key, &access)?; |
| wtxn.commit()?; |
|
|
| |
| if let Some(mut project) = self.get_project(project_path)? { |
| if allowed { |
| match access_type { |
| "read" => project.total_reads += 1, |
| "write" | "edit" | "delete" => { |
| project.total_writes += 1; |
| project.session_writes += 1; |
| } |
| _ => {} |
| } |
| } |
| project.last_accessed = now; |
| self.update_project(&project)?; |
| } |
|
|
| |
| if allowed { |
| self.update_resources(project_path, access_type, file_size)?; |
| } |
|
|
| Ok(()) |
| } |
|
|
| |
| pub fn get_access_log(&self, project_path: &str, limit: usize) -> Result<Vec<FileAccess>> { |
| let rtxn = self.env.read_txn()?; |
| let iter = self.access_log.rev_iter(&rtxn)?; |
|
|
| let mut log = Vec::new(); |
| for result in iter { |
| let (_, access) = result?; |
| if access.project == project_path { |
| log.push(access); |
| if log.len() >= limit { |
| break; |
| } |
| } |
| } |
| Ok(log) |
| } |
|
|
| |
| pub fn prune_access_log(&self, max_age_secs: u64) -> Result<u64> { |
| let now = SystemTime::now() |
| .duration_since(UNIX_EPOCH) |
| .unwrap_or_default() |
| .as_secs(); |
| let cutoff = now.saturating_sub(max_age_secs); |
|
|
| let rtxn = self.env.read_txn()?; |
| let iter = self.access_log.iter(&rtxn)?; |
|
|
| let mut to_delete = Vec::new(); |
| for result in iter { |
| let (key, access) = result?; |
| if access.timestamp < cutoff { |
| to_delete.push(key.to_string()); |
| } |
| } |
| drop(rtxn); |
|
|
| let count = to_delete.len() as u64; |
| let mut wtxn = self.env.write_txn()?; |
| for key in to_delete { |
| self.access_log.delete(&mut wtxn, &key)?; |
| } |
| wtxn.commit()?; |
|
|
| Ok(count) |
| } |
|
|
| |
| |
| |
|
|
| fn update_resources(&self, project_path: &str, access_type: &str, size: u64) -> Result<()> { |
| let rtxn = self.env.read_txn()?; |
| let mut usage = self.resources.get(&rtxn, project_path)? |
| .unwrap_or_default(); |
| drop(rtxn); |
|
|
| match access_type { |
| "read" => usage.bytes_read += size, |
| "write" => { |
| usage.bytes_written += size; |
| usage.files_created += 1; |
| } |
| "edit" => usage.bytes_written += size, |
| "delete" => usage.files_deleted += 1, |
| "bash" => usage.bash_commands += 1, |
| "web" => usage.web_requests += 1, |
| _ => {} |
| } |
|
|
| let mut wtxn = self.env.write_txn()?; |
| self.resources.put(&mut wtxn, project_path, &usage)?; |
| wtxn.commit()?; |
| Ok(()) |
| } |
|
|
| |
| pub fn get_resources(&self, project_path: &str) -> Result<ResourceUsage> { |
| let rtxn = self.env.read_txn()?; |
| Ok(self.resources.get(&rtxn, project_path)?.unwrap_or_default()) |
| } |
|
|
| |
| pub fn reset_session_counters(&self) -> Result<()> { |
| let projects = self.list_projects()?; |
| for mut project in projects { |
| project.session_writes = 0; |
| self.update_project(&project)?; |
| } |
| Ok(()) |
| } |
|
|
| |
| |
| |
|
|
| |
| pub fn validate_operation( |
| &self, |
| file_path: &str, |
| operation: &str, |
| size: u64, |
| ) -> Result<(bool, Option<String>)> { |
| |
| let project = match self.find_project_for_path(file_path)? { |
| Some(s) => s, |
| None => return Ok((true, None)), |
| }; |
|
|
| |
| if project.requires_activation && !project.is_active { |
| return Ok((false, Some(format!( |
| "Project '{}' requires activation before file operations", |
| project.name |
| )))); |
| } |
|
|
| |
| if matches!(operation, "write" | "edit" | "delete") { |
| if project.trust_level == TrustLevel::Untrusted { |
| return Ok((false, Some("Untrusted project: write operations denied".to_string()))); |
| } |
|
|
| |
| if self.is_path_protected(&project.path, file_path)? { |
| return Ok((false, Some(format!( |
| "Path is protected in project '{}'", |
| project.name |
| )))); |
| } |
|
|
| |
| if size > project.max_write_size as u64 { |
| return Ok((false, Some(format!( |
| "File size {} exceeds project limit {}", |
| size, project.max_write_size |
| )))); |
| } |
|
|
| |
| if project.session_writes >= project.max_writes_per_session { |
| return Ok((false, Some(format!( |
| "Session write limit ({}) reached for project '{}'", |
| project.max_writes_per_session, project.name |
| )))); |
| } |
| } |
|
|
| Ok((true, None)) |
| } |
|
|
| |
| pub fn db_stats(&self) -> Result<(u64, u64, u64)> { |
| let rtxn = self.env.read_txn()?; |
| let projects_stat = self.projects.stat(&rtxn)?; |
| let access_stat = self.access_log.stat(&rtxn)?; |
| let resources_stat = self.resources.stat(&rtxn)?; |
| Ok((projects_stat.entries as u64, access_stat.entries as u64, resources_stat.entries as u64)) |
| } |
| } |
|
|