From 69578e4170f948da70d16fdf0c929d306495f526 Mon Sep 17 00:00:00 2001 From: Hakula Chen Date: Tue, 1 Dec 2026 19:37:19 +0800 Subject: [PATCH] feat(ox-core): add project root trust store for hooks and commands --- crates/ox-core/src/lib.rs | 1 + crates/ox-core/src/trust.rs | 475 ++++++++++++++++++++++++++++++++++++ docs/README.md | 1 + docs/reference/trust.md | 33 +++ 4 files changed, 510 insertions(+) create mode 100644 crates/ox-core/src/trust.rs create mode 100644 docs/reference/trust.md diff --git a/crates/ox-core/src/lib.rs b/crates/ox-core/src/lib.rs index 7364d8a43..a01649156 100644 --- a/crates/ox-core/src/lib.rs +++ b/crates/ox-core/src/lib.rs @@ -12,3 +12,4 @@ pub mod prompt; pub mod session; pub mod skills; pub mod tools; +pub mod trust; diff --git a/crates/ox-core/src/trust.rs b/crates/ox-core/src/trust.rs new file mode 100644 index 000000000..88f689001 --- /dev/null +++ b/crates/ox-core/src/trust.rs @@ -0,0 +1,475 @@ +//! Persistent trust store for project root directories. +//! +//! Project-local hooks, plugins, and commands can execute arbitrary code when an agent opens a +//! repository. [`TrustStore`] records user-approved project roots in a TOML file under +//! `$XDG_STATE_HOME/ox/trusted.toml` (falling back to `~/.local/state/ox/trusted.toml`) and +//! provides gating helpers so untrusted repositories cannot run project-local extensions. + +use std::collections::BTreeSet; +use std::fs; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +/// Monotonic counter used to generate unique temporary filenames for atomic writes. +static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0); + +/// Errors produced while resolving, loading, querying, or saving the trust store. +#[derive(Debug, Error)] +pub enum TrustError { + /// Failed to resolve the default state directory because neither `XDG_STATE_HOME` nor `HOME` + /// is set. + #[error("cannot determine trust file path: neither XDG_STATE_HOME nor HOME is set")] + MissingStateDir, + /// Filesystem operation failed for `path`. + #[error("filesystem error for {path}: {source}")] + Io { + /// Path involved in the failed operation. + path: PathBuf, + /// Underlying I/O error. + source: std::io::Error, + }, + /// Failed to parse the trust store TOML file. + #[error("failed to parse trust store: {0}")] + TomlDeserialize(#[from] toml::de::Error), + /// Failed to serialize the trust store to TOML. + #[error("failed to serialize trust store: {0}")] + TomlSerialize(#[from] toml::ser::Error), +} + +/// Decision returned by [`TrustStore::gate_project`] when checking whether project-local +/// hooks, plugins, or commands may load or execute. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrustDecision { + /// The project root is trusted and project-local extensions may run. + Allowed, + /// The project root is not trusted, so project-local extensions must be skipped. + Untrusted, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +struct TrustedFile { + #[serde(default)] + trusted_roots: BTreeSet, +} + +/// Returns the default path to the trust store file. +/// +/// Uses `$XDG_STATE_HOME/ox/trusted.toml` when `XDG_STATE_HOME` is set and non-empty, otherwise +/// falls back to `$HOME/.local/state/ox/trusted.toml`. +pub fn default_trust_file_path() -> Result { + let xdg_state_home = std::env::var("XDG_STATE_HOME").ok(); + let home = std::env::var("HOME").ok(); + resolve_trust_file_path(xdg_state_home.as_deref(), home.as_deref()) +} + +fn resolve_trust_file_path( + xdg_state_home: Option<&str>, + home: Option<&str>, +) -> Result { + if let Some(dir) = xdg_state_home.filter(|dir| !dir.is_empty()) { + return Ok(PathBuf::from(dir).join("ox").join("trusted.toml")); + } + + if let Some(dir) = home.filter(|dir| !dir.is_empty()) { + return Ok(PathBuf::from(dir) + .join(".local") + .join("state") + .join("ox") + .join("trusted.toml")); + } + + Err(TrustError::MissingStateDir) +} + +/// Persistent store of canonicalized trusted project root directories. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TrustStore { + path: PathBuf, + roots: BTreeSet, +} + +impl TrustStore { + /// Loads the trust store from [`default_trust_file_path`]. + pub fn load_default() -> Result { + let path = default_trust_file_path()?; + Self::load(path) + } + + /// Loads the trust store from `path`. + /// + /// Returns an empty store if `path` does not yet exist. + pub fn load(path: impl Into) -> Result { + let path = path.into(); + match fs::read_to_string(&path) { + Ok(content) => { + let parsed: TrustedFile = toml::from_str(&content)?; + Ok(Self { + path, + roots: parsed.trusted_roots, + }) + } + + Err(source) if source.kind() == ErrorKind::NotFound => Ok(Self { + path, + roots: BTreeSet::new(), + }), + + Err(source) => Err(TrustError::Io { path, source }), + } + } + + /// Returns the backing TOML file path for this store. + pub fn path(&self) -> &Path { + &self.path + } + + /// Returns `true` if the canonicalized `root` is present in the trust store. + pub fn is_trusted(&self, root: impl AsRef) -> Result { + let canonical = canonicalize_path(root.as_ref())?; + Ok(self.roots.contains(&canonical)) + } + + /// Canonicalizes `root` and adds it to the trust store. + /// + /// Returns `true` if the root was newly added, or `false` if it was already trusted. + pub fn trust(&mut self, root: impl AsRef) -> Result { + let canonical = canonicalize_path(root.as_ref())?; + Ok(self.roots.insert(canonical)) + } + + /// Removes `root` from the trust store. + /// + /// Canonicalizes `root` when it exists on disk. If the directory has already been deleted, + /// falls back to matching the provided path verbatim so stale entries can still be revoked. + /// Returns `true` if an entry was removed. + pub fn revoke(&mut self, root: impl AsRef) -> Result { + let path = root.as_ref(); + let target = match fs::canonicalize(path) { + Ok(canonical) => canonical, + Err(source) if source.kind() == ErrorKind::NotFound => path.to_path_buf(), + + Err(source) => { + return Err(TrustError::Io { + path: path.to_path_buf(), + source, + }); + } + }; + Ok(self.roots.remove(&target)) + } + + /// Returns all trusted project roots in deterministic sorted order. + pub fn list(&self) -> Vec<&Path> { + self.roots.iter().map(PathBuf::as_path).collect() + } + + /// Persists the trust store to disk using an atomic temporary-file write and rename. + pub fn save(&self) -> Result<(), TrustError> { + if let Some(parent) = self + .path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + fs::create_dir_all(parent).map_err(|source| TrustError::Io { + path: parent.to_path_buf(), + source, + })?; + } + + let payload = TrustedFile { + trusted_roots: self.roots.clone(), + }; + let encoded = toml::to_string_pretty(&payload)?; + let temp_path = temp_path_for(&self.path); + + fs::write(&temp_path, encoded).map_err(|source| TrustError::Io { + path: temp_path.clone(), + source, + })?; + + if let Err(source) = fs::rename(&temp_path, &self.path) { + let _: std::io::Result<()> = fs::remove_file(&temp_path); + return Err(TrustError::Io { + path: self.path.clone(), + source, + }); + } + + Ok(()) + } + + /// Checks whether project-local hooks, plugins, or commands may run for `root`. + pub fn gate_project(&self, root: impl AsRef) -> Result { + if self.is_trusted(root)? { + Ok(TrustDecision::Allowed) + } else { + Ok(TrustDecision::Untrusted) + } + } + + /// Runs `action` only when `root` is trusted. + /// + /// Returns `Ok(Some(value))` when `root` is trusted and `Ok(None)` without invoking `action` + /// when `root` is untrusted. + pub fn guard_project( + &self, + root: impl AsRef, + action: F, + ) -> Result, TrustError> + where + F: FnOnce() -> T, + { + match self.gate_project(root)? { + TrustDecision::Allowed => Ok(Some(action())), + TrustDecision::Untrusted => Ok(None), + } + } +} + +fn canonicalize_path(path: &Path) -> Result { + fs::canonicalize(path).map_err(|source| TrustError::Io { + path: path.to_path_buf(), + source, + }) +} + +fn temp_path_for(target: &Path) -> PathBuf { + let seq = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed); + let pid = std::process::id(); + let file_name = target + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("trusted.toml"); + let temp_name = format!(".{file_name}.tmp.{pid}.{seq}"); + match target.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent.join(temp_name), + _ => PathBuf::from(temp_name), + } +} + +#[cfg(test)] +mod tests { + use std::fs; + #[cfg(unix)] + use std::os::unix::fs::symlink; + use std::path::{Path, PathBuf}; + + use indoc::indoc; + use tempfile::TempDir; + + use super::{TrustDecision, TrustError, TrustStore, resolve_trust_file_path, temp_path_for}; + + #[test] + fn resolve_trust_file_path_prefers_xdg_state_home() { + let path = resolve_trust_file_path(Some("/tmp/state"), Some("/home/alice")).unwrap(); + assert_eq!(path, PathBuf::from("/tmp/state/ox/trusted.toml")); + } + + #[test] + fn resolve_trust_file_path_falls_back_to_home() { + let path = resolve_trust_file_path(Some(""), Some("/home/alice")).unwrap(); + assert_eq!( + path, + PathBuf::from("/home/alice/.local/state/ox/trusted.toml") + ); + } + + #[test] + fn resolve_trust_file_path_errors_when_no_base_dir_is_set() { + let err = resolve_trust_file_path(None, None).unwrap_err(); + assert!(matches!(err, TrustError::MissingStateDir)); + } + + #[test] + fn load_returns_empty_store_when_file_is_missing() { + let dir = TempDir::new().unwrap(); + let store_path = dir.path().join("ox").join("trusted.toml"); + + let store = TrustStore::load(&store_path).unwrap(); + assert_eq!(store.path(), store_path.as_path()); + assert_eq!(store.list(), Vec::<&Path>::new()); + } + + #[test] + fn load_parses_existing_toml_file() { + let dir = TempDir::new().unwrap(); + let store_path = dir.path().join("trusted.toml"); + fs::write( + &store_path, + indoc! {r#" + trusted_roots = [ + "/workspace/beta", + "/workspace/alpha", + ] + "#}, + ) + .unwrap(); + + let store = TrustStore::load(&store_path).unwrap(); + assert_eq!( + store.list(), + vec![Path::new("/workspace/alpha"), Path::new("/workspace/beta")] + ); + } + + #[test] + fn load_rejects_malformed_toml() { + let dir = TempDir::new().unwrap(); + let store_path = dir.path().join("trusted.toml"); + fs::write(&store_path, "trusted_roots = [unclosed").unwrap(); + + let err = TrustStore::load(&store_path).unwrap_err(); + assert!(matches!(err, TrustError::TomlDeserialize(_))); + } + + #[test] + fn load_errors_when_path_is_a_directory() { + let dir = TempDir::new().unwrap(); + let err = TrustStore::load(dir.path()).unwrap_err(); + assert!(matches!(err, TrustError::Io { .. })); + } + + #[test] + fn trust_is_trusted_and_revoke_canonicalize_paths() { + let dir = TempDir::new().unwrap(); + let project = dir.path().join("project"); + fs::create_dir_all(&project).unwrap(); + let canonical = fs::canonicalize(&project).unwrap(); + + let mut store = TrustStore::load(dir.path().join("trusted.toml")).unwrap(); + assert!(!store.is_trusted(&project).unwrap()); + + assert!(store.trust(&project).unwrap()); + assert!(!store.trust(&project).unwrap()); + assert!(store.is_trusted(&project).unwrap()); + assert_eq!(store.list(), vec![canonical.as_path()]); + + #[cfg(unix)] + { + let link = dir.path().join("project-link"); + symlink(&project, &link).unwrap(); + assert!(store.is_trusted(&link).unwrap()); + assert!(store.revoke(&link).unwrap()); + } + #[cfg(not(unix))] + { + assert!(store.revoke(&project).unwrap()); + } + + assert!(!store.is_trusted(&project).unwrap()); + assert!(!store.revoke(&project).unwrap()); + } + + #[test] + fn is_trusted_and_trust_error_on_nonexistent_path() { + let dir = TempDir::new().unwrap(); + let missing = dir.path().join("does-not-exist"); + let mut store = TrustStore::load(dir.path().join("trusted.toml")).unwrap(); + + assert!(matches!( + store.is_trusted(&missing).unwrap_err(), + TrustError::Io { .. } + )); + assert!(matches!( + store.trust(&missing).unwrap_err(), + TrustError::Io { .. } + )); + } + + #[test] + fn revoke_removes_already_deleted_directory() { + let dir = TempDir::new().unwrap(); + let project = dir.path().join("ephemeral"); + fs::create_dir_all(&project).unwrap(); + let canonical = fs::canonicalize(&project).unwrap(); + + let mut store = TrustStore::load(dir.path().join("trusted.toml")).unwrap(); + store.trust(&project).unwrap(); + fs::remove_dir(&project).unwrap(); + + assert!(store.revoke(&canonical).unwrap()); + assert_eq!(store.list(), Vec::<&Path>::new()); + } + + #[test] + fn save_creates_parent_directories_and_round_trips() { + let dir = TempDir::new().unwrap(); + let project_a = dir.path().join("repo-a"); + let project_b = dir.path().join("repo-b"); + fs::create_dir_all(&project_a).unwrap(); + fs::create_dir_all(&project_b).unwrap(); + + let store_path = dir.path().join("nested").join("ox").join("trusted.toml"); + let mut store = TrustStore::load(&store_path).unwrap(); + store.trust(&project_b).unwrap(); + store.trust(&project_a).unwrap(); + store.save().unwrap(); + + let reloaded = TrustStore::load(&store_path).unwrap(); + assert_eq!(reloaded, store); + } + + #[test] + fn save_errors_when_target_path_is_a_directory() { + let dir = TempDir::new().unwrap(); + let target_dir = dir.path().join("occupied"); + fs::create_dir_all(&target_dir).unwrap(); + + let store = TrustStore { + path: target_dir, + roots: std::collections::BTreeSet::new(), + }; + let err = store.save().unwrap_err(); + assert!(matches!(err, TrustError::Io { .. })); + } + + #[test] + fn gate_and_guard_project_block_untrusted_and_allow_trusted_roots() { + let dir = TempDir::new().unwrap(); + let project = dir.path().join("repo"); + fs::create_dir_all(&project).unwrap(); + + let mut store = TrustStore::load(dir.path().join("trusted.toml")).unwrap(); + assert_eq!( + store.gate_project(&project).unwrap(), + TrustDecision::Untrusted + ); + + let mut ran = false; + let blocked = store + .guard_project(&project, || { + ran = true; + 42 + }) + .unwrap(); + assert_eq!(blocked, None); + assert!(!ran); + + store.trust(&project).unwrap(); + assert_eq!( + store.gate_project(&project).unwrap(), + TrustDecision::Allowed + ); + + let allowed = store + .guard_project(&project, || { + ran = true; + 42 + }) + .unwrap(); + assert_eq!(allowed, Some(42)); + assert!(ran); + } + + #[test] + fn temp_path_for_handles_filename_without_parent() { + let temp = temp_path_for(Path::new("trusted.toml")); + assert_eq!(temp.parent(), Some(Path::new(""))); + let name = temp.file_name().unwrap().to_str().unwrap(); + assert!(name.starts_with(".trusted.toml.tmp.")); + } +} diff --git a/docs/README.md b/docs/README.md index df9433b2b..e1cb32331 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,6 +26,7 @@ Documentation for `oxide-code` (`ox`) is organized into three user-facing bucket | [Statusline](reference/statusline.md) | Built-in statusline segments and external ANSI command protocol | | [System Prompt](reference/system-prompt.md) | Named system prompt sections and declarative Markdown overrides | | [Themes](reference/themes.md) | Built-in palettes and custom TOML theme file schema | +| [Trust](reference/trust.md) | Project root trust store (`trusted.toml`) and extension gating | ## Architecture diff --git a/docs/reference/trust.md b/docs/reference/trust.md new file mode 100644 index 000000000..692899f6d --- /dev/null +++ b/docs/reference/trust.md @@ -0,0 +1,33 @@ +# Project Trust + +Project-local hooks, plugins, and commands can execute arbitrary code when `ox` opens a repository. The project trust store records user-approved project roots so untrusted repositories cannot run project-local extensions automatically. + +## Storage Location + +`TrustStore::load_default` reads and writes a TOML file at: + +1. `$XDG_STATE_HOME/ox/trusted.toml` when `XDG_STATE_HOME` is set and non-empty. +2. `~/.local/state/ox/trusted.toml` otherwise. + +Callers and tests can override the path with `TrustStore::load(path)`. + +## File Format + +`trusted.toml` stores a sorted, deduplicated list of canonicalized project root paths under `trusted_roots`: + +```toml +trusted_roots = [ + "/Users/alice/GitHub/oxide-code", + "/Users/alice/work/service-api", +] +``` + +| Field | Type | Default | Description | +| --------------- | --------------- | ------- | -------------------------------------------------- | +| `trusted_roots` | array of string | `[]` | Canonicalized absolute paths of trusted workspaces | + +## Behavior + +- **Canonicalization**: `TrustStore::is_trusted`, `trust`, and `revoke` resolve symlinks and relative segments with `std::fs::canonicalize`. Revoking a directory that has already been deleted falls back to matching the provided path verbatim so stale entries can still be removed. +- **Atomic writes**: `TrustStore::save` creates missing parent directories, writes the serialized TOML to a sibling temporary file, and atomically renames it into place. +- **Extension gating**: `TrustStore::gate_project` returns `TrustDecision::Allowed` or `TrustDecision::Untrusted`, and `TrustStore::guard_project` runs a closure only when the project root is trusted.