1#[allow(unused_imports)]
2use crate::prelude::*;
3
4#[cfg(feature = "ureq")]
5use crate::audit::AuditEvent;
6#[cfg(feature = "std")]
7use crate::audit::AuditLog;
8#[cfg(feature = "std")]
9use crate::audit::DEFAULT_MAX_AUDIT_BYTES;
10use crate::error::{OmegaError, Result};
11use crate::types::Action;
12use hashbrown::HashSet;
13#[cfg(all(feature = "std", feature = "async"))]
14use std::future::Future;
15#[cfg(feature = "std")]
16use std::io::Write;
17#[cfg(feature = "std")]
18use std::path::{Path, PathBuf};
19#[cfg(all(feature = "std", feature = "async"))]
20use std::sync::{Arc, Mutex};
21#[cfg(feature = "ureq")]
22use std::time::Duration;
23
24#[cfg(all(feature = "std", feature = "async"))]
25use tokio::io::AsyncWriteExt;
26
27pub trait Executor {
33 fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>>;
35}
36
37#[cfg(all(feature = "std", feature = "async"))]
42#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
43pub trait AsyncExecutor {
44 fn execute_async(
46 &mut self,
47 actions: &[Action],
48 ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send;
49}
50
51#[cfg(all(feature = "std", feature = "async"))]
57#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
58pub struct AsyncExecutorAdapter<E> {
59 inner: Arc<Mutex<Option<E>>>,
60}
61
62#[cfg(feature = "async")]
63#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
64impl<E> AsyncExecutorAdapter<E> {
65 pub fn new(executor: E) -> Self {
67 Self {
68 inner: Arc::new(Mutex::new(Some(executor))),
69 }
70 }
71
72 pub fn try_into_inner(self) -> Option<E> {
76 Arc::try_unwrap(self.inner)
77 .ok()
78 .and_then(|mutex| mutex.into_inner().ok())
79 .and_then(Option::from)
80 }
81
82 pub fn into_inner(self) -> E {
89 self.try_into_inner()
90 .expect("AsyncExecutorAdapter is still in use")
91 }
92}
93
94#[cfg(feature = "async")]
95#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
96impl<E: Executor + Send + 'static> AsyncExecutor for AsyncExecutorAdapter<E> {
97 fn execute_async(
98 &mut self,
99 actions: &[Action],
100 ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send {
101 let inner = Arc::clone(&self.inner);
102 let actions = actions.to_vec();
103 async move {
104 tokio::task::spawn_blocking(move || {
105 let mut guard = inner.lock().map_err(|_| {
106 OmegaError::ExecutionBlocked("executor adapter lock poisoned".into())
107 })?;
108 let mut executor = guard.take().ok_or_else(|| {
109 OmegaError::ExecutionBlocked(
110 "AsyncExecutorAdapter executor is unavailable after a failed invocation"
111 .into(),
112 )
113 })?;
114 let result = executor.execute(&actions);
115 *guard = Some(executor);
116 result
117 })
118 .await
119 .map_err(|e| OmegaError::Other(anyhow::anyhow!(e)))?
120 }
121 }
122}
123
124#[cfg(feature = "async")]
127#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
128impl<E: Executor + Send + 'static> From<E> for AsyncExecutorAdapter<E> {
129 fn from(executor: E) -> Self {
130 Self::new(executor)
131 }
132}
133
134pub struct SandboxedExecutor {
136 allowed: HashSet<String>,
137}
138
139impl SandboxedExecutor {
140 pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
142 Self {
143 allowed: allowed.into_iter().collect(),
144 }
145 }
146}
147
148impl Executor for SandboxedExecutor {
149 fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
150 let mut results = Vec::new();
151 for act in actions {
152 if !act.constraints_checked {
153 return Err(OmegaError::ExecutionBlocked(format!(
154 "{} (constraints not checked)",
155 act.name
156 )));
157 }
158 if !self.allowed.contains(&act.name) {
159 return Err(OmegaError::ExecutionBlocked(act.name.clone()));
160 }
161 results.push(serde_json::json!({
162 "status": "ok",
163 "action": act.name,
164 "params": act.params
165 }));
166 }
167 Ok(results)
168 }
169}
170
171#[cfg(feature = "std")]
173pub struct LoggingExecutor {
174 allowed: HashSet<String>,
175 log_path: Option<PathBuf>,
176 echo_stdout: bool,
177}
178
179#[cfg(feature = "std")]
180impl LoggingExecutor {
181 pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
183 Self {
184 allowed: allowed.into_iter().collect(),
185 log_path: None,
186 echo_stdout: true,
187 }
188 }
189
190 pub fn with_log_file(mut self, path: impl AsRef<Path>) -> Self {
192 self.log_path = Some(path.as_ref().to_path_buf());
193 self
194 }
195
196 pub fn echo_stdout(mut self, enabled: bool) -> Self {
198 self.echo_stdout = enabled;
199 self
200 }
201}
202
203#[cfg(feature = "std")]
204impl Executor for LoggingExecutor {
205 fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
206 let mut results = Vec::new();
207 for act in actions {
208 if !act.constraints_checked {
209 return Err(OmegaError::ExecutionBlocked(format!(
210 "{} (constraints not checked)",
211 act.name
212 )));
213 }
214 if !self.allowed.contains(&act.name) {
215 return Err(OmegaError::ExecutionBlocked(act.name.clone()));
216 }
217
218 let entry = serde_json::json!({
219 "status": "logged",
220 "action": act.name,
221 "params": act.params,
222 "ts": crate::now_utc_string()
223 });
224
225 if self.echo_stdout {
226 println!("[LoggingExecutor] {}", entry);
227 }
228 if let Some(path) = &self.log_path {
229 let mut file = std::fs::OpenOptions::new()
230 .create(true)
231 .append(true)
232 .open(path)
233 .map_err(|e| OmegaError::ExecutionBlocked(format!("log open: {e}")))?;
234 writeln!(file, "{entry}")
235 .map_err(|e| OmegaError::ExecutionBlocked(format!("log write: {e}")))?;
236 }
237
238 results.push(entry);
239 }
240 Ok(results)
241 }
242}
243
244#[cfg(feature = "ureq")]
246const HTTP_GET_BODY_LIMIT: usize = 2048;
247
248#[cfg(feature = "ureq")]
251fn safe_http_get(url: &str) -> Result<serde_json::Value> {
252 let input_url = url.trim();
253 let parsed = crate::l0::observer::parse_http_url(input_url)?;
254 let (status, bytes, truncated) = crate::l0::observer::fetch_http_sync_preview(
255 parsed,
256 Duration::from_secs(10),
257 Duration::from_secs(5),
258 HTTP_GET_BODY_LIMIT,
259 )?;
260 let preview = String::from_utf8_lossy(&bytes).into_owned();
261 Ok(serde_json::json!({
262 "status": "ok",
263 "action": "http_get",
264 "http_status": status,
265 "url": input_url,
266 "body_preview": preview,
267 "truncated": truncated,
268 "effect": "network_get",
269 }))
270}
271
272#[cfg(feature = "std")]
277pub struct ToolGateExecutor {
278 #[cfg_attr(not(feature = "ureq"), allow(dead_code))]
279 allowed: HashSet<String>,
280 #[cfg_attr(not(feature = "ureq"), allow(dead_code))]
281 denied: HashSet<String>,
282 audit: Option<AuditLog>,
283 audit_max_bytes: u64,
284 echo: bool,
285 fail_closed: bool,
286 enable_http_get: bool,
288}
289
290#[cfg(feature = "std")]
291impl ToolGateExecutor {
292 pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
294 Self {
295 allowed: allowed.into_iter().collect(),
296 denied: HashSet::new(),
297 audit: None,
298 audit_max_bytes: DEFAULT_MAX_AUDIT_BYTES,
299 echo: true,
300 fail_closed: true,
301 enable_http_get: false,
302 }
303 }
304
305 pub fn deny(mut self, names: impl IntoIterator<Item = String>) -> Self {
307 self.denied.extend(names);
308 self
309 }
310
311 pub fn with_audit(mut self, log: AuditLog) -> Self {
313 self.audit = Some(log);
314 self
315 }
316
317 pub fn audit_max_bytes(mut self, max_bytes: u64) -> Self {
319 self.audit_max_bytes = max_bytes;
320 self
321 }
322
323 pub fn echo(mut self, on: bool) -> Self {
325 self.echo = on;
326 self
327 }
328
329 pub fn fail_closed(mut self, on: bool) -> Self {
331 self.fail_closed = on;
332 self
333 }
334
335 pub fn enable_http_get(mut self, on: bool) -> Self {
337 self.enable_http_get = on;
338 self
339 }
340
341 #[cfg_attr(not(feature = "ureq"), allow(dead_code))]
342 fn is_denied(&self, name: &str) -> bool {
343 self.denied.contains(name) || !self.allowed.contains(name)
344 }
345}
346
347#[cfg(feature = "ureq")]
348impl Executor for ToolGateExecutor {
349 fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
350 let mut results = Vec::new();
351 for act in actions {
352 if !act.constraints_checked {
353 return Err(OmegaError::ExecutionBlocked(format!(
354 "{} (constraints not checked)",
355 act.name
356 )));
357 }
358
359 if self.is_denied(&act.name) {
360 let reason = if self.denied.contains(&act.name) {
361 "deny_list"
362 } else {
363 "not_on_allow_list"
364 };
365 if let Some(log) = &self.audit {
366 log.append_with_max_bytes(
367 AuditEvent::ToolDenied {
368 tool: act.name.clone(),
369 reason: reason.into(),
370 },
371 self.audit_max_bytes,
372 )?;
373 }
374 if self.echo {
375 println!("[tool-gate] DENY {} ({reason})", act.name);
376 }
377 if self.fail_closed {
378 return Err(OmegaError::ExecutionBlocked(format!(
379 "tool denied: {} ({reason})",
380 act.name
381 )));
382 }
383 results.push(serde_json::json!({
384 "status": "denied",
385 "action": act.name,
386 "reason": reason,
387 }));
388 continue;
389 }
390
391 if let Some(log) = &self.audit {
392 log.append_with_max_bytes(
393 AuditEvent::ToolAllowed {
394 tool: act.name.clone(),
395 },
396 self.audit_max_bytes,
397 )?;
398 }
399 if self.echo {
400 println!("[tool-gate] ALLOW {}", act.name);
401 }
402
403 if self.enable_http_get && act.name == "http_get" {
405 let url = act.params.get("url").and_then(|v| v.as_str()).unwrap_or("");
406 if url.is_empty() {
407 return Err(OmegaError::ExecutionBlocked(
408 "http_get requires params.url".into(),
409 ));
410 }
411 if self.echo {
412 println!("[tool-gate] GET {url}");
413 }
414 results.push(safe_http_get(url)?);
415 continue;
416 }
417
418 results.push(serde_json::json!({
419 "status": "ok",
420 "action": act.name,
421 "params": act.params,
422 "effect": "simulated",
423 }));
424 }
425 Ok(results)
426 }
427}
428
429#[cfg(all(feature = "std", feature = "async"))]
431#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
432pub struct AsyncLoggingExecutor {
433 allowed: HashSet<String>,
434 log_path: Option<PathBuf>,
435 echo_stdout: bool,
436}
437
438#[cfg(all(feature = "std", feature = "async"))]
439#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
440impl AsyncLoggingExecutor {
441 pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
443 Self {
444 allowed: allowed.into_iter().collect(),
445 log_path: None,
446 echo_stdout: true,
447 }
448 }
449
450 pub fn with_log_file(mut self, path: impl AsRef<Path>) -> Self {
452 self.log_path = Some(path.as_ref().to_path_buf());
453 self
454 }
455
456 pub fn echo_stdout(mut self, enabled: bool) -> Self {
458 self.echo_stdout = enabled;
459 self
460 }
461}
462
463#[cfg(all(feature = "std", feature = "async"))]
464#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
465impl AsyncExecutor for AsyncLoggingExecutor {
466 fn execute_async(
467 &mut self,
468 actions: &[Action],
469 ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send {
470 let allowed = self.allowed.clone();
471 let log_path = self.log_path.clone();
472 let echo_stdout = self.echo_stdout;
473 let actions = actions.to_vec();
474 async move {
475 let mut results = Vec::new();
476 for act in actions {
477 if !act.constraints_checked {
478 return Err(OmegaError::ExecutionBlocked(format!(
479 "{} (constraints not checked)",
480 act.name
481 )));
482 }
483 if !allowed.contains(&act.name) {
484 return Err(OmegaError::ExecutionBlocked(act.name.clone()));
485 }
486
487 let entry = serde_json::json!({
488 "status": "logged",
489 "action": act.name,
490 "params": act.params,
491 "ts": crate::now_utc_string()
492 });
493
494 if echo_stdout {
495 println!("[AsyncLoggingExecutor] {}", entry);
496 }
497
498 if let Some(path) = &log_path {
499 let mut file = tokio::fs::OpenOptions::new()
500 .create(true)
501 .append(true)
502 .open(path)
503 .await
504 .map_err(|e| OmegaError::ExecutionBlocked(format!("log open: {e}")))?;
505 let line = format!("{}\n", entry);
506 file.write_all(line.as_bytes())
507 .await
508 .map_err(|e| OmegaError::ExecutionBlocked(format!("log write: {e}")))?;
509 }
510
511 results.push(entry);
512 }
513 Ok(results)
514 }
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521 use crate::types::Action;
522 use alloc::collections::BTreeMap;
523
524 fn action(name: &str, checked: bool) -> Action {
525 Action {
526 name: name.into(),
527 params: BTreeMap::new(),
528 constraints_checked: checked,
529 }
530 }
531
532 #[test]
533 fn allows_whitelisted_checked_action() {
534 let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
535 let res = ex.execute(&[action("observe", true)]);
536 assert!(res.is_ok());
537 assert_eq!(res.unwrap().len(), 1);
538 }
539
540 #[test]
541 fn blocks_unchecked_action() {
542 let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
543 let res = ex.execute(&[action("observe", false)]);
544 assert!(res.is_err());
545 }
546
547 #[test]
548 fn blocks_non_whitelisted_action() {
549 let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
550 let res = ex.execute(&[action("delete_everything", true)]);
551 assert!(res.is_err());
552 }
553
554 #[cfg(feature = "async")]
555 struct CountingExecutor {
556 calls: usize,
557 }
558
559 #[cfg(feature = "async")]
560 impl Executor for CountingExecutor {
561 fn execute(&mut self, _actions: &[Action]) -> Result<Vec<serde_json::Value>> {
562 self.calls += 1;
563 Ok(vec![serde_json::json!({"call": self.calls})])
564 }
565 }
566
567 #[cfg(feature = "async")]
568 #[tokio::test]
569 async fn async_executor_adapter_supports_consecutive_calls() {
570 let mut adapter = AsyncExecutorAdapter::new(CountingExecutor { calls: 0 });
571 let actions = [action("observe", true)];
572
573 let first = adapter.execute_async(&actions).await.unwrap();
574 let second = adapter.execute_async(&actions).await.unwrap();
575
576 assert_eq!(first[0]["call"], 1);
577 assert_eq!(second[0]["call"], 2);
578 assert_eq!(adapter.into_inner().calls, 2);
579 }
580
581 #[test]
582 fn logging_executor_records_action() {
583 let mut ex = LoggingExecutor::new(vec!["observe".into()]).echo_stdout(false);
584 let res = ex.execute(&[action("observe", true)]).unwrap();
585 assert_eq!(res[0]["status"], "logged");
586 assert_eq!(res[0]["action"], "observe");
587 }
588
589 #[test]
590 #[cfg(all(feature = "std", feature = "async"))]
591 fn async_adapter_can_execute_repeatedly() {
592 let runtime = tokio::runtime::Runtime::new().unwrap();
593 runtime.block_on(async {
594 let mut executor =
595 AsyncExecutorAdapter::new(SandboxedExecutor::new(vec!["observe".into()]));
596 for _ in 0..2 {
597 let results = executor
598 .execute_async(&[action("observe", true)])
599 .await
600 .unwrap();
601 assert_eq!(results.len(), 1);
602 }
603 let _ = executor.into_inner();
604 });
605 }
606
607 #[test]
608 #[cfg(all(feature = "std", feature = "async"))]
609 fn async_logging_propagates_open_failure() {
610 let blocker =
611 std::env::temp_dir().join(format!("omega-async-log-blocker-{}", crate::new_uuid()));
612 std::fs::write(&blocker, b"not a directory").unwrap();
613 let mut executor = AsyncLoggingExecutor::new(vec!["observe".into()])
614 .with_log_file(blocker.join("actions.jsonl"))
615 .echo_stdout(false);
616 let runtime = tokio::runtime::Runtime::new().unwrap();
617 let error = runtime
618 .block_on(executor.execute_async(&[action("observe", true)]))
619 .unwrap_err();
620 assert!(error.to_string().contains("log open"), "{error}");
621 let _ = std::fs::remove_file(blocker);
622 }
623
624 #[test]
625 #[cfg(feature = "ureq")]
626 fn tool_gate_denies_dangerous_tool() {
627 use crate::audit::AuditLog;
628 use std::env::temp_dir;
629 let dir = temp_dir().join(format!(
630 "omega-gate-{}-{}",
631 std::process::id(),
632 crate::new_uuid()
633 ));
634 std::fs::create_dir_all(&dir).unwrap();
635 let path = dir.join("state.json");
636 let audit = AuditLog::beside_state(&path);
637 let mut gate = ToolGateExecutor::new(["search_docs".into(), "http_get".into()])
638 .deny(["delete_database".into(), "shell_exec".into()])
639 .with_audit(audit)
640 .echo(false)
641 .fail_closed(true);
642 assert!(gate.execute(&[action("search_docs", true)]).is_ok());
643 assert!(gate.execute(&[action("delete_database", true)]).is_err());
644 let rows = AuditLog::beside_state(&path).read_all().unwrap();
645 assert!(rows.len() >= 2);
646 let _ = std::fs::remove_file(AuditLog::beside_state(&path).path);
647 let _ = std::fs::remove_dir_all(&dir);
648 }
649
650 #[test]
651 #[cfg(feature = "ureq")]
652 fn tool_gate_propagates_audit_size_limit_errors_for_allowed_and_denied_tools() {
653 use crate::audit::AuditLog;
654 use std::env::temp_dir;
655
656 let dir = temp_dir().join(format!(
657 "omega-gate-limit-{}-{}",
658 std::process::id(),
659 crate::new_uuid()
660 ));
661 std::fs::create_dir_all(&dir).unwrap();
662 let state_path = dir.join("state.json");
663 let audit = AuditLog::beside_state(&state_path);
664 let mut gate = ToolGateExecutor::new(["safe_tool".into()])
665 .deny(["blocked_tool".into()])
666 .with_audit(audit)
667 .audit_max_bytes(0)
668 .echo(false)
669 .fail_closed(false);
670
671 let allowed_error = gate.execute(&[action("safe_tool", true)]).unwrap_err();
672 assert!(
673 allowed_error
674 .to_string()
675 .contains("audit log size limit exceeded"),
676 "{allowed_error}"
677 );
678 let denied_error = gate.execute(&[action("blocked_tool", true)]).unwrap_err();
679 assert!(
680 denied_error
681 .to_string()
682 .contains("audit log size limit exceeded"),
683 "{denied_error}"
684 );
685 assert!(!dir.join("audit.jsonl").exists());
686 let _ = std::fs::remove_dir_all(&dir);
687 }
688
689 #[test]
690 #[cfg(feature = "ureq")]
691 fn http_get_bounds_large_response_preview() {
692 use std::io::Write;
693 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
694 let address = listener.local_addr().unwrap();
695 let server = std::thread::spawn(move || {
696 let (mut stream, _) = listener.accept().unwrap();
697 let mut request = [0_u8; 1024];
698 let _ = std::io::Read::read(&mut stream, &mut request);
699 stream
700 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8192\r\nConnection: close\r\n\r\n")
701 .unwrap();
702 stream.write_all(&[b'x'; 8192]).unwrap();
703 });
704
705 let url = crate::l0::observer::parse_http_url(&format!("http://{address}/large")).unwrap();
706 let (status, body, truncated) = crate::l0::observer::fetch_http_sync_preview_with_resolver(
707 url,
708 Duration::from_secs(2),
709 Duration::from_millis(300),
710 HTTP_GET_BODY_LIMIT,
711 move |_, _| Ok(vec![address]),
712 )
713 .unwrap();
714 server.join().unwrap();
715 assert_eq!(status, 200);
716 assert_eq!(body.len(), HTTP_GET_BODY_LIMIT);
717 assert!(truncated);
718 }
719
720 #[test]
721 #[cfg(feature = "ureq")]
722 fn http_get_rejects_private_and_metadata_ip_literals() {
723 for url in [
724 "http://127.0.0.1/",
725 "http://10.0.0.1/",
726 "http://169.254.169.254/latest/meta-data/",
727 "http://[::1]/",
728 ] {
729 assert!(safe_http_get(url).is_err(), "accepted unsafe target {url}");
730 }
731 }
732
733 #[test]
734 #[cfg(feature = "ureq")]
735 fn http_get_rejects_credentialed_urls() {
736 assert!(safe_http_get("http://user:password@example.com/").is_err());
737 }
738
739 #[test]
740 #[cfg(feature = "ureq")]
741 fn http_get_rejects_non_http_scheme() {
742 let mut gate = ToolGateExecutor::new(["http_get".into()])
743 .enable_http_get(true)
744 .echo(false);
745 let mut params = BTreeMap::new();
746 params.insert("url".into(), serde_json::json!("file:///etc/passwd"));
747 let act = Action {
748 name: "http_get".into(),
749 params,
750 constraints_checked: true,
751 };
752 assert!(gate.execute(&[act]).is_err());
753 }
754}