#[allow(unused_imports)]
use crate::prelude::*;
#[cfg(feature = "ureq")]
use crate::audit::AuditEvent;
#[cfg(feature = "std")]
use crate::audit::AuditLog;
#[cfg(feature = "std")]
use crate::audit::DEFAULT_MAX_AUDIT_BYTES;
use crate::error::{OmegaError, Result};
use crate::types::Action;
use hashbrown::HashSet;
#[cfg(all(feature = "std", feature = "async"))]
use std::future::Future;
#[cfg(feature = "std")]
use std::io::Write;
#[cfg(feature = "std")]
use std::path::{Path, PathBuf};
#[cfg(all(feature = "std", feature = "async"))]
use std::sync::{Arc, Mutex};
#[cfg(feature = "ureq")]
use std::time::Duration;
#[cfg(all(feature = "std", feature = "async"))]
use tokio::io::AsyncWriteExt;
pub trait Executor {
fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>>;
}
#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
pub trait AsyncExecutor {
fn execute_async(
&mut self,
actions: &[Action],
) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send;
}
#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
pub struct AsyncExecutorAdapter<E> {
inner: Arc<Mutex<Option<E>>>,
}
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
impl<E> AsyncExecutorAdapter<E> {
pub fn new(executor: E) -> Self {
Self {
inner: Arc::new(Mutex::new(Some(executor))),
}
}
pub fn try_into_inner(self) -> Option<E> {
Arc::try_unwrap(self.inner)
.ok()
.and_then(|mutex| mutex.into_inner().ok())
.and_then(Option::from)
}
pub fn into_inner(self) -> E {
self.try_into_inner()
.expect("AsyncExecutorAdapter is still in use")
}
}
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
impl<E: Executor + Send + 'static> AsyncExecutor for AsyncExecutorAdapter<E> {
fn execute_async(
&mut self,
actions: &[Action],
) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send {
let inner = Arc::clone(&self.inner);
let actions = actions.to_vec();
async move {
tokio::task::spawn_blocking(move || {
let mut guard = inner.lock().map_err(|_| {
OmegaError::ExecutionBlocked("executor adapter lock poisoned".into())
})?;
let mut executor = guard.take().ok_or_else(|| {
OmegaError::ExecutionBlocked(
"AsyncExecutorAdapter executor is unavailable after a failed invocation"
.into(),
)
})?;
let result = executor.execute(&actions);
*guard = Some(executor);
result
})
.await
.map_err(|e| OmegaError::Other(anyhow::anyhow!(e)))?
}
}
}
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
impl<E: Executor + Send + 'static> From<E> for AsyncExecutorAdapter<E> {
fn from(executor: E) -> Self {
Self::new(executor)
}
}
pub struct SandboxedExecutor {
allowed: HashSet<String>,
}
impl SandboxedExecutor {
pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
Self {
allowed: allowed.into_iter().collect(),
}
}
}
impl Executor for SandboxedExecutor {
fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
let mut results = Vec::new();
for act in actions {
if !act.constraints_checked {
return Err(OmegaError::ExecutionBlocked(format!(
"{} (constraints not checked)",
act.name
)));
}
if !self.allowed.contains(&act.name) {
return Err(OmegaError::ExecutionBlocked(act.name.clone()));
}
results.push(serde_json::json!({
"status": "ok",
"action": act.name,
"params": act.params
}));
}
Ok(results)
}
}
#[cfg(feature = "std")]
pub struct LoggingExecutor {
allowed: HashSet<String>,
log_path: Option<PathBuf>,
echo_stdout: bool,
}
#[cfg(feature = "std")]
impl LoggingExecutor {
pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
Self {
allowed: allowed.into_iter().collect(),
log_path: None,
echo_stdout: true,
}
}
pub fn with_log_file(mut self, path: impl AsRef<Path>) -> Self {
self.log_path = Some(path.as_ref().to_path_buf());
self
}
pub fn echo_stdout(mut self, enabled: bool) -> Self {
self.echo_stdout = enabled;
self
}
}
#[cfg(feature = "std")]
impl Executor for LoggingExecutor {
fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
let mut results = Vec::new();
for act in actions {
if !act.constraints_checked {
return Err(OmegaError::ExecutionBlocked(format!(
"{} (constraints not checked)",
act.name
)));
}
if !self.allowed.contains(&act.name) {
return Err(OmegaError::ExecutionBlocked(act.name.clone()));
}
let entry = serde_json::json!({
"status": "logged",
"action": act.name,
"params": act.params,
"ts": crate::now_utc_string()
});
if self.echo_stdout {
println!("[LoggingExecutor] {}", entry);
}
if let Some(path) = &self.log_path {
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map_err(|e| OmegaError::ExecutionBlocked(format!("log open: {e}")))?;
writeln!(file, "{entry}")
.map_err(|e| OmegaError::ExecutionBlocked(format!("log write: {e}")))?;
}
results.push(entry);
}
Ok(results)
}
}
#[cfg(feature = "ureq")]
const HTTP_GET_BODY_LIMIT: usize = 2048;
#[cfg(feature = "ureq")]
fn safe_http_get(url: &str) -> Result<serde_json::Value> {
let input_url = url.trim();
let parsed = crate::l0::observer::parse_http_url(input_url)?;
let (status, bytes, truncated) = crate::l0::observer::fetch_http_sync_preview(
parsed,
Duration::from_secs(10),
Duration::from_secs(5),
HTTP_GET_BODY_LIMIT,
)?;
let preview = String::from_utf8_lossy(&bytes).into_owned();
Ok(serde_json::json!({
"status": "ok",
"action": "http_get",
"http_status": status,
"url": input_url,
"body_preview": preview,
"truncated": truncated,
"effect": "network_get",
}))
}
#[cfg(feature = "std")]
pub struct ToolGateExecutor {
#[cfg_attr(not(feature = "ureq"), allow(dead_code))]
allowed: HashSet<String>,
#[cfg_attr(not(feature = "ureq"), allow(dead_code))]
denied: HashSet<String>,
audit: Option<AuditLog>,
audit_max_bytes: u64,
echo: bool,
fail_closed: bool,
enable_http_get: bool,
}
#[cfg(feature = "std")]
impl ToolGateExecutor {
pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
Self {
allowed: allowed.into_iter().collect(),
denied: HashSet::new(),
audit: None,
audit_max_bytes: DEFAULT_MAX_AUDIT_BYTES,
echo: true,
fail_closed: true,
enable_http_get: false,
}
}
pub fn deny(mut self, names: impl IntoIterator<Item = String>) -> Self {
self.denied.extend(names);
self
}
pub fn with_audit(mut self, log: AuditLog) -> Self {
self.audit = Some(log);
self
}
pub fn audit_max_bytes(mut self, max_bytes: u64) -> Self {
self.audit_max_bytes = max_bytes;
self
}
pub fn echo(mut self, on: bool) -> Self {
self.echo = on;
self
}
pub fn fail_closed(mut self, on: bool) -> Self {
self.fail_closed = on;
self
}
pub fn enable_http_get(mut self, on: bool) -> Self {
self.enable_http_get = on;
self
}
#[cfg_attr(not(feature = "ureq"), allow(dead_code))]
fn is_denied(&self, name: &str) -> bool {
self.denied.contains(name) || !self.allowed.contains(name)
}
}
#[cfg(feature = "ureq")]
impl Executor for ToolGateExecutor {
fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
let mut results = Vec::new();
for act in actions {
if !act.constraints_checked {
return Err(OmegaError::ExecutionBlocked(format!(
"{} (constraints not checked)",
act.name
)));
}
if self.is_denied(&act.name) {
let reason = if self.denied.contains(&act.name) {
"deny_list"
} else {
"not_on_allow_list"
};
if let Some(log) = &self.audit {
log.append_with_max_bytes(
AuditEvent::ToolDenied {
tool: act.name.clone(),
reason: reason.into(),
},
self.audit_max_bytes,
)?;
}
if self.echo {
println!("[tool-gate] DENY {} ({reason})", act.name);
}
if self.fail_closed {
return Err(OmegaError::ExecutionBlocked(format!(
"tool denied: {} ({reason})",
act.name
)));
}
results.push(serde_json::json!({
"status": "denied",
"action": act.name,
"reason": reason,
}));
continue;
}
if let Some(log) = &self.audit {
log.append_with_max_bytes(
AuditEvent::ToolAllowed {
tool: act.name.clone(),
},
self.audit_max_bytes,
)?;
}
if self.echo {
println!("[tool-gate] ALLOW {}", act.name);
}
if self.enable_http_get && act.name == "http_get" {
let url = act.params.get("url").and_then(|v| v.as_str()).unwrap_or("");
if url.is_empty() {
return Err(OmegaError::ExecutionBlocked(
"http_get requires params.url".into(),
));
}
if self.echo {
println!("[tool-gate] GET {url}");
}
results.push(safe_http_get(url)?);
continue;
}
results.push(serde_json::json!({
"status": "ok",
"action": act.name,
"params": act.params,
"effect": "simulated",
}));
}
Ok(results)
}
}
#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
pub struct AsyncLoggingExecutor {
allowed: HashSet<String>,
log_path: Option<PathBuf>,
echo_stdout: bool,
}
#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
impl AsyncLoggingExecutor {
pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
Self {
allowed: allowed.into_iter().collect(),
log_path: None,
echo_stdout: true,
}
}
pub fn with_log_file(mut self, path: impl AsRef<Path>) -> Self {
self.log_path = Some(path.as_ref().to_path_buf());
self
}
pub fn echo_stdout(mut self, enabled: bool) -> Self {
self.echo_stdout = enabled;
self
}
}
#[cfg(all(feature = "std", feature = "async"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
impl AsyncExecutor for AsyncLoggingExecutor {
fn execute_async(
&mut self,
actions: &[Action],
) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send {
let allowed = self.allowed.clone();
let log_path = self.log_path.clone();
let echo_stdout = self.echo_stdout;
let actions = actions.to_vec();
async move {
let mut results = Vec::new();
for act in actions {
if !act.constraints_checked {
return Err(OmegaError::ExecutionBlocked(format!(
"{} (constraints not checked)",
act.name
)));
}
if !allowed.contains(&act.name) {
return Err(OmegaError::ExecutionBlocked(act.name.clone()));
}
let entry = serde_json::json!({
"status": "logged",
"action": act.name,
"params": act.params,
"ts": crate::now_utc_string()
});
if echo_stdout {
println!("[AsyncLoggingExecutor] {}", entry);
}
if let Some(path) = &log_path {
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.await
.map_err(|e| OmegaError::ExecutionBlocked(format!("log open: {e}")))?;
let line = format!("{}\n", entry);
file.write_all(line.as_bytes())
.await
.map_err(|e| OmegaError::ExecutionBlocked(format!("log write: {e}")))?;
}
results.push(entry);
}
Ok(results)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::Action;
use alloc::collections::BTreeMap;
fn action(name: &str, checked: bool) -> Action {
Action {
name: name.into(),
params: BTreeMap::new(),
constraints_checked: checked,
}
}
#[test]
fn allows_whitelisted_checked_action() {
let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
let res = ex.execute(&[action("observe", true)]);
assert!(res.is_ok());
assert_eq!(res.unwrap().len(), 1);
}
#[test]
fn blocks_unchecked_action() {
let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
let res = ex.execute(&[action("observe", false)]);
assert!(res.is_err());
}
#[test]
fn blocks_non_whitelisted_action() {
let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
let res = ex.execute(&[action("delete_everything", true)]);
assert!(res.is_err());
}
#[cfg(feature = "async")]
struct CountingExecutor {
calls: usize,
}
#[cfg(feature = "async")]
impl Executor for CountingExecutor {
fn execute(&mut self, _actions: &[Action]) -> Result<Vec<serde_json::Value>> {
self.calls += 1;
Ok(vec![serde_json::json!({"call": self.calls})])
}
}
#[cfg(feature = "async")]
#[tokio::test]
async fn async_executor_adapter_supports_consecutive_calls() {
let mut adapter = AsyncExecutorAdapter::new(CountingExecutor { calls: 0 });
let actions = [action("observe", true)];
let first = adapter.execute_async(&actions).await.unwrap();
let second = adapter.execute_async(&actions).await.unwrap();
assert_eq!(first[0]["call"], 1);
assert_eq!(second[0]["call"], 2);
assert_eq!(adapter.into_inner().calls, 2);
}
#[test]
fn logging_executor_records_action() {
let mut ex = LoggingExecutor::new(vec!["observe".into()]).echo_stdout(false);
let res = ex.execute(&[action("observe", true)]).unwrap();
assert_eq!(res[0]["status"], "logged");
assert_eq!(res[0]["action"], "observe");
}
#[test]
#[cfg(all(feature = "std", feature = "async"))]
fn async_adapter_can_execute_repeatedly() {
let runtime = tokio::runtime::Runtime::new().unwrap();
runtime.block_on(async {
let mut executor =
AsyncExecutorAdapter::new(SandboxedExecutor::new(vec!["observe".into()]));
for _ in 0..2 {
let results = executor
.execute_async(&[action("observe", true)])
.await
.unwrap();
assert_eq!(results.len(), 1);
}
let _ = executor.into_inner();
});
}
#[test]
#[cfg(all(feature = "std", feature = "async"))]
fn async_logging_propagates_open_failure() {
let blocker =
std::env::temp_dir().join(format!("omega-async-log-blocker-{}", crate::new_uuid()));
std::fs::write(&blocker, b"not a directory").unwrap();
let mut executor = AsyncLoggingExecutor::new(vec!["observe".into()])
.with_log_file(blocker.join("actions.jsonl"))
.echo_stdout(false);
let runtime = tokio::runtime::Runtime::new().unwrap();
let error = runtime
.block_on(executor.execute_async(&[action("observe", true)]))
.unwrap_err();
assert!(error.to_string().contains("log open"), "{error}");
let _ = std::fs::remove_file(blocker);
}
#[test]
#[cfg(feature = "ureq")]
fn tool_gate_denies_dangerous_tool() {
use crate::audit::AuditLog;
use std::env::temp_dir;
let dir = temp_dir().join(format!(
"omega-gate-{}-{}",
std::process::id(),
crate::new_uuid()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("state.json");
let audit = AuditLog::beside_state(&path);
let mut gate = ToolGateExecutor::new(["search_docs".into(), "http_get".into()])
.deny(["delete_database".into(), "shell_exec".into()])
.with_audit(audit)
.echo(false)
.fail_closed(true);
assert!(gate.execute(&[action("search_docs", true)]).is_ok());
assert!(gate.execute(&[action("delete_database", true)]).is_err());
let rows = AuditLog::beside_state(&path).read_all().unwrap();
assert!(rows.len() >= 2);
let _ = std::fs::remove_file(AuditLog::beside_state(&path).path);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[cfg(feature = "ureq")]
fn tool_gate_propagates_audit_size_limit_errors_for_allowed_and_denied_tools() {
use crate::audit::AuditLog;
use std::env::temp_dir;
let dir = temp_dir().join(format!(
"omega-gate-limit-{}-{}",
std::process::id(),
crate::new_uuid()
));
std::fs::create_dir_all(&dir).unwrap();
let state_path = dir.join("state.json");
let audit = AuditLog::beside_state(&state_path);
let mut gate = ToolGateExecutor::new(["safe_tool".into()])
.deny(["blocked_tool".into()])
.with_audit(audit)
.audit_max_bytes(0)
.echo(false)
.fail_closed(false);
let allowed_error = gate.execute(&[action("safe_tool", true)]).unwrap_err();
assert!(
allowed_error
.to_string()
.contains("audit log size limit exceeded"),
"{allowed_error}"
);
let denied_error = gate.execute(&[action("blocked_tool", true)]).unwrap_err();
assert!(
denied_error
.to_string()
.contains("audit log size limit exceeded"),
"{denied_error}"
);
assert!(!dir.join("audit.jsonl").exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[cfg(feature = "ureq")]
fn http_get_bounds_large_response_preview() {
use std::io::Write;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut request = [0_u8; 1024];
let _ = std::io::Read::read(&mut stream, &mut request);
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8192\r\nConnection: close\r\n\r\n")
.unwrap();
stream.write_all(&[b'x'; 8192]).unwrap();
});
let url = crate::l0::observer::parse_http_url(&format!("http://{address}/large")).unwrap();
let (status, body, truncated) = crate::l0::observer::fetch_http_sync_preview_with_resolver(
url,
Duration::from_secs(2),
Duration::from_millis(300),
HTTP_GET_BODY_LIMIT,
move |_, _| Ok(vec![address]),
)
.unwrap();
server.join().unwrap();
assert_eq!(status, 200);
assert_eq!(body.len(), HTTP_GET_BODY_LIMIT);
assert!(truncated);
}
#[test]
#[cfg(feature = "ureq")]
fn http_get_rejects_private_and_metadata_ip_literals() {
for url in [
"http://127.0.0.1/",
"http://10.0.0.1/",
"http://169.254.169.254/latest/meta-data/",
"http://[::1]/",
] {
assert!(safe_http_get(url).is_err(), "accepted unsafe target {url}");
}
}
#[test]
#[cfg(feature = "ureq")]
fn http_get_rejects_credentialed_urls() {
assert!(safe_http_get("http://user:password@example.com/").is_err());
}
#[test]
#[cfg(feature = "ureq")]
fn http_get_rejects_non_http_scheme() {
let mut gate = ToolGateExecutor::new(["http_get".into()])
.enable_http_get(true)
.echo(false);
let mut params = BTreeMap::new();
params.insert("url".into(), serde_json::json!("file:///etc/passwd"));
let act = Action {
name: "http_get".into(),
params,
constraints_checked: true,
};
assert!(gate.execute(&[act]).is_err());
}
}