Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

feat: implement sandboxed tools and async permission broker

Oleksandr Ivanchenko5c3ff5e5ee2f
diff --git a/src/broker/mod.rs b/src/broker/mod.rs
new file mode 100644
index 00000000..c48cca96
--- /dev/null
+++ b/src/broker/mod.rs
@@ -0,0 +1,57 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::collections::HashMap;
+use std::sync::Arc;
+use tokio::sync::{oneshot, Mutex};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub enum ApprovalDecision {
+ AllowOnce,
+ AlwaysAllowSession,
+ Deny,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ApprovalRequest {
+ pub id: String,
+ pub kwant_id: String,
+ pub tool_name: String,
+ pub details: Value,
+}
+
+#[derive(Clone, Debug, Default)]
+pub struct PermissionBroker {
+ pending: Arc<Mutex<HashMap<String, oneshot::Sender<ApprovalDecision>>>>,
+}
+
+impl PermissionBroker {
+ pub fn new() -> Self {
+ Self {
+ pending: Arc::new(Mutex::new(HashMap::new())),
+ }
+ }
+
+ /// Registers a pending approval ticket and returns a receiver waiting for user choice.
+ pub async fn request_approval(&self, request: ApprovalRequest) -> oneshot::Receiver<ApprovalDecision> {
+ let (tx, rx) = oneshot::channel();
+ let mut map = self.pending.lock().await;
+ map.insert(request.id, tx);
+ rx
+ }
+
+ /// Checks if a ticket is currently pending user resolution.
+ pub async fn is_pending(&self, ticket_id: &str) -> bool {
+ let map = self.pending.lock().await;
+ map.contains_key(ticket_id)
+ }
+
+ /// Resolves an approval ticket by sending the user's decision to the waiting oneshot channel.
+ pub async fn resolve(&self, ticket_id: &str, decision: ApprovalDecision) -> bool {
+ let mut map = self.pending.lock().await;
+ if let Some(sender) = map.remove(ticket_id) {
+ sender.send(decision).is_ok()
+ } else {
+ false
+ }
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index ad385add..70f6452c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,9 +1,13 @@
+pub mod broker;
pub mod config;
pub mod db;
pub mod drivers;
pub mod router;
+pub mod tools;
+pub use broker::{ApprovalDecision, ApprovalRequest, PermissionBroker};
pub use config::{Config, ConfigError};
pub use db::{Database, DbError};
pub use drivers::{create_driver_for_kwant, ApiDriver, CliDriver, Driver, DriverError, RuntimeEvent, TurnInput, TurnOutput};
pub use router::{LayaRouter, RouteDecision, RouterError};
+pub use tools::{ToolError, ToolRunner};
diff --git a/src/tools/file_ops.rs b/src/tools/file_ops.rs
new file mode 100644
index 00000000..dc0bd873
--- /dev/null
+++ b/src/tools/file_ops.rs
@@ -0,0 +1,110 @@
+use super::ToolError;
+use serde_json::{json, Value};
+use std::fs;
+use std::path::{Path, PathBuf};
+
+pub fn resolve_safe_path(workspace: &Path, rel_path: &str) -> Result<PathBuf, ToolError> {
+ // Prevent empty paths or absolute root escapes
+ let normalized = PathBuf::from(rel_path);
+ if normalized.is_absolute() {
+ return Err(ToolError::Security(
+ "Absolute paths outside workspace are forbidden".into(),
+ ));
+ }
+
+ // Resolve relative to workspace
+ let target = workspace.join(normalized);
+
+ // If target exists, canonicalize and verify workspace prefix
+ if target.exists() {
+ let canon_target = fs::canonicalize(&target)?;
+ let canon_ws = fs::canonicalize(workspace)?;
+ if !canon_target.starts_with(&canon_ws) {
+ return Err(ToolError::Security(
+ "Path traversal outside workspace root is blocked".into(),
+ ));
+ }
+ Ok(canon_target)
+ } else {
+ // For new files, check canonical parent
+ let parent = target.parent().unwrap_or(workspace);
+ if parent.exists() {
+ let canon_parent = fs::canonicalize(parent)?;
+ let canon_ws = fs::canonicalize(workspace)?;
+ if !canon_parent.starts_with(&canon_ws) {
+ return Err(ToolError::Security(
+ "Path traversal outside workspace root is blocked".into(),
+ ));
+ }
+ } else {
+ // Check lexical components for ".."
+ for comp in target.components() {
+ if let std::path::Component::ParentDir = comp {
+ return Err(ToolError::Security(
+ "Path traversal outside workspace root is blocked".into(),
+ ));
+ }
+ }
+ }
+ Ok(target)
+ }
+}
+
+pub fn write_file(workspace: &Path, args: &Value) -> Result<Value, ToolError> {
+ let path_str = args["path"]
+ .as_str()
+ .ok_or_else(|| ToolError::InvalidArgs("Missing 'path' argument".into()))?;
+ let content = args["content"]
+ .as_str()
+ .ok_or_else(|| ToolError::InvalidArgs("Missing 'content' argument".into()))?;
+
+ let safe_path = resolve_safe_path(workspace, path_str)?;
+ if let Some(parent) = safe_path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+
+ fs::write(&safe_path, content)?;
+
+ Ok(json!({
+ "status": "success",
+ "path": path_str,
+ "bytes_written": content.len()
+ }))
+}
+
+pub fn read_file(workspace: &Path, args: &Value) -> Result<Value, ToolError> {
+ let path_str = args["path"]
+ .as_str()
+ .ok_or_else(|| ToolError::InvalidArgs("Missing 'path' argument".into()))?;
+
+ let safe_path = resolve_safe_path(workspace, path_str)?;
+ let content = fs::read_to_string(&safe_path)?;
+
+ Ok(json!({
+ "status": "success",
+ "path": path_str,
+ "content": content
+ }))
+}
+
+pub fn list_dir(workspace: &Path, args: &Value) -> Result<Value, ToolError> {
+ let path_str = args["path"].as_str().unwrap_or(".");
+ let safe_path = resolve_safe_path(workspace, path_str)?;
+
+ let mut entries = vec![];
+ for entry in fs::read_dir(safe_path)? {
+ let entry = entry?;
+ let file_type = entry.file_type()?;
+ entries.push(json!({
+ "name": entry.file_name().to_string_lossy(),
+ "is_dir": file_type.is_dir(),
+ "bytes": entry.metadata()?.len()
+ }));
+ }
+
+ Ok(json!({
+ "status": "success",
+ "path": path_str,
+ "entries": entries
+ }))
+}
diff --git a/src/tools/mod.rs b/src/tools/mod.rs
new file mode 100644
index 00000000..89d848a5
--- /dev/null
+++ b/src/tools/mod.rs
@@ -0,0 +1,48 @@
+pub mod file_ops;
+pub mod shell;
+pub mod web;
+
+use serde_json::Value;
+use std::path::PathBuf;
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum ToolError {
+ #[error("I/O error during tool execution: {0}")]
+ Io(#[from] std::io::Error),
+
+ #[error("Security violation: {0}")]
+ Security(String),
+
+ #[error("Invalid tool arguments: {0}")]
+ InvalidArgs(String),
+
+ #[error("Tool execution failed: {0}")]
+ Execution(String),
+
+ #[error("Unknown tool '{0}'")]
+ UnknownTool(String),
+}
+
+#[derive(Clone, Debug)]
+pub struct ToolRunner {
+ pub workspace_dir: PathBuf,
+}
+
+impl ToolRunner {
+ pub fn new(workspace_dir: PathBuf) -> Self {
+ let _ = std::fs::create_dir_all(&workspace_dir);
+ Self { workspace_dir }
+ }
+
+ pub async fn execute(&self, tool_name: &str, args: &Value) -> Result<Value, ToolError> {
+ match tool_name {
+ "write_file" => file_ops::write_file(&self.workspace_dir, args),
+ "read_file" => file_ops::read_file(&self.workspace_dir, args),
+ "list_dir" => file_ops::list_dir(&self.workspace_dir, args),
+ "execute_shell" => shell::execute_shell(&self.workspace_dir, args).await,
+ "web_fetch" => web::web_fetch(args).await,
+ other => Err(ToolError::UnknownTool(other.to_string())),
+ }
+ }
+}
diff --git a/src/tools/shell.rs b/src/tools/shell.rs
new file mode 100644
index 00000000..4a9de2da
--- /dev/null
+++ b/src/tools/shell.rs
@@ -0,0 +1,35 @@
+use super::ToolError;
+use serde_json::{json, Value};
+use std::path::Path;
+use std::time::Duration;
+use tokio::process::Command;
+use tokio::time::timeout;
+
+pub async fn execute_shell(workspace: &Path, args: &Value) -> Result<Value, ToolError> {
+ let command_str = args["command"]
+ .as_str()
+ .ok_or_else(|| ToolError::InvalidArgs("Missing 'command' argument".into()))?;
+
+ let timeout_secs = args["timeout_secs"].as_u64().unwrap_or(30);
+
+ let mut cmd = Command::new("bash");
+ cmd.arg("-c").arg(command_str);
+ cmd.current_dir(workspace);
+
+ let output = timeout(Duration::from_secs(timeout_secs), cmd.output())
+ .await
+ .map_err(|_| ToolError::Execution("Command execution timed out".into()))?
+ .map_err(|e| ToolError::Execution(format!("Failed to execute shell: {}", e)))?;
+
+ let stdout = String::from_utf8_lossy(&output.stdout).to_string();
+ let stderr = String::from_utf8_lossy(&output.stderr).to_string();
+ let exit_code = output.status.code().unwrap_or(-1);
+
+ Ok(json!({
+ "command": command_str,
+ "stdout": stdout,
+ "stderr": stderr,
+ "exit_code": exit_code,
+ "success": output.status.success()
+ }))
+}
diff --git a/src/tools/web.rs b/src/tools/web.rs
new file mode 100644
index 00000000..dbb83b42
--- /dev/null
+++ b/src/tools/web.rs
@@ -0,0 +1,64 @@
+use super::ToolError;
+use reqwest::Client;
+use serde_json::{json, Value};
+use std::time::Duration;
+
+pub async fn web_fetch(args: &Value) -> Result<Value, ToolError> {
+ let url = args["url"]
+ .as_str()
+ .ok_or_else(|| ToolError::InvalidArgs("Missing 'url' argument".into()))?;
+
+ let client = Client::builder()
+ .timeout(Duration::from_secs(10))
+ .build()
+ .map_err(|e| ToolError::Execution(e.to_string()))?;
+
+ let resp = client
+ .get(url)
+ .header("User-Agent", "KwantsBot/1.0 (8-bit-Agent-Platform)")
+ .send()
+ .await
+ .map_err(|e| ToolError::Execution(format!("Web request failed: {}", e)))?;
+
+ let status = resp.status().as_u16();
+ let body = resp
+ .text()
+ .await
+ .map_err(|e| ToolError::Execution(format!("Failed reading web response: {}", e)))?;
+
+ // Basic HTML tag stripping and whitespace normalization
+ let stripped = strip_html_tags(&body);
+ let truncated = if stripped.len() > 8000 {
+ format!("{}... [content truncated]", &stripped[..8000])
+ } else {
+ stripped
+ };
+
+ Ok(json!({
+ "url": url,
+ "status": status,
+ "content": truncated
+ }))
+}
+
+fn strip_html_tags(html: &str) -> String {
+ let mut in_tag = false;
+ let mut output = String::with_capacity(html.len());
+
+ for ch in html.chars() {
+ if ch == '<' {
+ in_tag = true;
+ } else if ch == '>' {
+ in_tag = false;
+ output.push(' ');
+ } else if !in_tag {
+ output.push(ch);
+ }
+ }
+
+ // Collapse multiple whitespaces
+ output
+ .split_whitespace()
+ .collect::<Vec<&str>>()
+ .join(" ")
+}
diff --git a/tests/broker_test.rs b/tests/broker_test.rs
new file mode 100644
index 00000000..8c1a7d94
--- /dev/null
+++ b/tests/broker_test.rs
@@ -0,0 +1,28 @@
+use kwnt::broker::{ApprovalDecision, ApprovalRequest, PermissionBroker};
+use serde_json::json;
+
+#[tokio::test]
+async fn test_permission_broker_allow_and_deny() {
+ let broker = PermissionBroker::new();
+
+ let req = ApprovalRequest {
+ id: "ticket-1".into(),
+ kwant_id: "k-1".into(),
+ tool_name: "execute_shell".into(),
+ details: json!({"command": "rm -rf /"}),
+ };
+
+ let rx = broker.request_approval(req).await;
+ assert!(broker.is_pending("ticket-1").await);
+
+ // Resolve in background
+ let broker_clone = broker.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
+ broker_clone.resolve("ticket-1", ApprovalDecision::AllowOnce).await;
+ });
+
+ let decision = rx.await.unwrap();
+ assert_eq!(decision, ApprovalDecision::AllowOnce);
+ assert!(!broker.is_pending("ticket-1").await);
+}
diff --git a/tests/tools_test.rs b/tests/tools_test.rs
new file mode 100644
index 00000000..7acd5bd4
--- /dev/null
+++ b/tests/tools_test.rs
@@ -0,0 +1,56 @@
+use kwnt::tools::ToolRunner;
+use serde_json::json;
+use tempfile::tempdir;
+
+#[tokio::test]
+async fn test_path_traversal_is_blocked() {
+ let tmp = tempdir().unwrap();
+ let runner = ToolRunner::new(tmp.path().to_path_buf());
+
+ let bad_args = json!({
+ "path": "../../etc/shadow",
+ "content": "hacked"
+ });
+
+ let res = runner.execute("write_file", &bad_args).await;
+ assert!(res.is_err());
+ let err_str = res.unwrap_err().to_string();
+ assert!(err_str.contains("Path traversal") || err_str.contains("outside"));
+}
+
+#[tokio::test]
+async fn test_safe_file_lifecycle() {
+ let tmp = tempdir().unwrap();
+ let runner = ToolRunner::new(tmp.path().to_path_buf());
+
+ let write_args = json!({
+ "path": "hero_stats.txt",
+ "content": "HP: 100\nMP: 50\nLVL: 5"
+ });
+ let write_res = runner.execute("write_file", &write_args).await.unwrap();
+ assert_eq!(write_res["status"], "success");
+
+ let read_args = json!({
+ "path": "hero_stats.txt"
+ });
+ let read_res = runner.execute("read_file", &read_args).await.unwrap();
+ assert_eq!(read_res["content"], "HP: 100\nMP: 50\nLVL: 5");
+
+ let list_args = json!({ "path": "." });
+ let list_res = runner.execute("list_dir", &list_args).await.unwrap();
+ let entries = list_res["entries"].as_array().unwrap();
+ assert!(entries.iter().any(|e| e["name"] == "hero_stats.txt"));
+}
+
+#[tokio::test]
+async fn test_shell_execution() {
+ let tmp = tempdir().unwrap();
+ let runner = ToolRunner::new(tmp.path().to_path_buf());
+
+ let shell_args = json!({
+ "command": "echo 'LEVEL UP'"
+ });
+ let res = runner.execute("execute_shell", &shell_args).await.unwrap();
+ assert!(res["stdout"].as_str().unwrap().contains("LEVEL UP"));
+ assert_eq!(res["exit_code"], 0);
+}