1use std::collections::HashMap;
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10use base64::Engine;
11use bytes::Bytes;
12use camel_api::{Body, CamelError, Exchange};
13use camel_component_api::RuntimeObservability;
14use tokio::sync::Semaphore;
15use tower::Service;
16
17use crate::audit::{ExecAuditEvent, emit};
18use crate::config::{ExecGlobalConfig, ExecProfile};
19use crate::error::ExecError;
20use crate::headers::*;
21use crate::policy;
22use crate::process::{self, RawResult};
23
24pub struct ExecProducer {
25 pub(crate) profile: Arc<ExecProfile>,
26 pub(crate) global: Arc<ExecGlobalConfig>,
27 pub(crate) route_id: String,
28 pub(crate) host_env: HashMap<String, String>,
29 pub(crate) semaphore: Arc<Semaphore>,
30 pub(crate) rt: Option<Arc<dyn RuntimeObservability>>,
31}
32
33impl Clone for ExecProducer {
34 fn clone(&self) -> Self {
35 Self {
36 profile: Arc::clone(&self.profile),
37 global: Arc::clone(&self.global),
38 route_id: self.route_id.clone(),
39 host_env: self.host_env.clone(),
40 semaphore: Arc::clone(&self.semaphore),
41 rt: self.rt.clone(),
42 }
43 }
44}
45
46impl Service<Exchange> for ExecProducer {
47 type Response = Exchange;
48 type Error = CamelError;
49 type Future = std::pin::Pin<
50 Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
51 >;
52
53 fn poll_ready(
54 &mut self,
55 _cx: &mut std::task::Context<'_>,
56 ) -> std::task::Poll<Result<(), Self::Error>> {
57 std::task::Poll::Ready(Ok(()))
58 }
59
60 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
61 let this = self.clone();
62 Box::pin(async move { this.run(&mut exchange).await.map(|_| exchange) })
63 }
64}
65
66impl ExecProducer {
67 pub fn new(
69 profile: Arc<ExecProfile>,
70 global: Arc<ExecGlobalConfig>,
71 route_id: String,
72 host_env: HashMap<String, String>,
73 semaphore: Arc<Semaphore>,
74 rt: Option<Arc<dyn RuntimeObservability>>,
75 ) -> Self {
76 Self {
77 profile,
78 global,
79 route_id,
80 host_env,
81 semaphore,
82 rt,
83 }
84 }
85
86 async fn run(&self, ex: &mut Exchange) -> Result<(), CamelError> {
87 let start = Instant::now();
88 let args = self.resolve_args(ex)?;
90 if let Err(e) = policy::eval_args(&args, &self.profile.args, &self.profile.deny_flags) {
92 self.metric_denied("arg_policy");
93 return Err(pack(&self.route_id, e));
94 }
95 let exe = self
97 .profile
98 .canonical_executable
99 .clone()
100 .unwrap_or_default();
101 let exe_str = exe.to_string_lossy().to_string();
102 if !self.profile.allow_shell && policy::is_known_shell(&exe_str) {
103 self.metric_denied("shell");
104 return Err(pack(
105 &self.route_id,
106 ExecError::ShellRejected {
107 executable: exe_str.clone(),
108 },
109 ));
110 }
111 let env = policy::build_env(&self.profile.env, &self.global.deny_env, &self.host_env);
113 let cwd = match &self.global.canonical_workspace_root {
115 Some(root) => crate::config::confine(root, &self.profile.working_dir).map_err(|e| {
116 self.metric_denied("workdir");
117 pack(&self.route_id, ExecError::InvalidWorkDir { path: e })
118 })?,
119 None => {
120 return Err(pack(
121 &self.route_id,
122 ExecError::InvalidWorkDir {
123 path: "workspace root not pinned at startup".into(),
124 },
125 ));
126 }
127 };
128 let stdin =
130 extract_stdin(ex, self.profile.stdin_max_bytes).map_err(|e| pack(&self.route_id, e))?;
131 let _permit = self.semaphore.acquire().await.map_err(|_| {
133 CamelError::ProcessorErrorWithSource(
134 "exec semaphore closed".into(),
135 Arc::new(ExecError::Spawn(std::io::Error::other("semaphore"))),
136 )
137 })?;
138 let raw = self
140 .spawn_and_collect(&exe, &args, &env, &cwd, stdin)
141 .await
142 .map_err(|e| pack(&self.route_id, e))?;
143 let exit_code = raw.exit_code;
145 let accepted = exit_code
146 .map(|c| self.profile.accepted_exit_codes.contains(&c))
147 .unwrap_or(false);
148 let body_out = ExecResult {
149 exit_code,
150 stdout: b64(&raw.stdout),
151 stderr: b64(&raw.stderr),
152 stdout_truncated: raw.stdout_truncated,
153 stderr_truncated: raw.stderr_truncated,
154 timed_out: raw.timed_out,
155 profile: self.profile.name.clone(),
156 duration_ms: start.elapsed().as_millis() as u64,
157 };
158 ex.input.body = Body::Json(serde_json::to_value(&body_out).map_err(|e| {
159 pack(
160 &self.route_id,
161 ExecError::InvalidArgs(format!("serialize result: {e}")),
162 )
163 })?);
164 let h = &mut ex.input.headers;
165 h.insert(
166 CAMEL_EXEC_PROFILE.to_string(),
167 serde_json::Value::String(self.profile.name.clone()),
168 );
169 if let Some(c) = exit_code {
171 h.insert(CAMEL_EXEC_EXIT_CODE.to_string(), serde_json::Value::from(c));
172 h.insert(
173 CAMEL_EXEC_EXIT_ACCEPTED.to_string(),
174 serde_json::Value::from(accepted),
175 );
176 } else {
177 h.insert(
178 CAMEL_EXEC_EXIT_ACCEPTED.to_string(),
179 serde_json::Value::from(false),
180 );
181 }
182 h.insert(
183 CAMEL_EXEC_TIMED_OUT.to_string(),
184 serde_json::Value::from(raw.timed_out),
185 );
186 h.insert(
187 CAMEL_EXEC_STDOUT_TRUNCATED.to_string(),
188 serde_json::Value::from(raw.stdout_truncated),
189 );
190 h.insert(
191 CAMEL_EXEC_STDERR_TRUNCATED.to_string(),
192 serde_json::Value::from(raw.stderr_truncated),
193 );
194 h.insert(
195 CAMEL_EXEC_STDERR.to_string(),
196 serde_json::Value::String(String::from_utf8_lossy(&raw.stderr).into_owned()),
197 );
198 self.metric_outcome(
200 exit_code,
201 raw.timed_out,
202 raw.stdout_truncated,
203 start.elapsed(),
204 );
205 emit(&ExecAuditEvent {
206 route_id: &self.route_id,
207 profile: &self.profile.name,
208 canonical_executable: &exe_str,
209 args: &args,
210 env_keys: env.keys().map(|k| k.as_str()).collect::<Vec<_>>(),
211 cwd: &cwd.to_string_lossy(),
212 exit_code,
213 timed_out: raw.timed_out,
214 stdout_truncated: raw.stdout_truncated,
215 stderr_truncated: raw.stderr_truncated,
216 duration: start.elapsed(),
217 });
218 Ok(())
219 }
220
221 async fn spawn_and_collect(
222 &self,
223 exe: &std::path::Path,
224 args: &[String],
225 env: &HashMap<String, String>,
226 cwd: &std::path::Path,
227 stdin: Bytes,
228 ) -> Result<RawResult, ExecError> {
229 let mut child = process::spawn(exe, args, env, cwd)?;
232 let stdin_handle = child.stdin.take();
233 let out = child.stdout.take();
234 let err = child.stderr.take();
235 let out_task = tokio::spawn(drain_join(out, self.profile.stdout_max_bytes));
237 let err_task = tokio::spawn(drain_join(err, self.profile.stderr_max_bytes));
238 let stdin_task = tokio::spawn(async move {
239 if let Some(mut sin) = stdin_handle {
240 use tokio::io::AsyncWriteExt;
241 let _ = sin.write_all(&stdin).await;
242 let _ = sin.shutdown().await;
243 }
244 });
245
246 let timeout = Duration::from_secs(self.profile.timeout_secs);
247 let (exit_code, timed_out) = tokio::select! {
251 biased;
252 status = child.wait() => match status {
253 Ok(s) => (s.code(), false),
254 Err(e) => return Err(ExecError::Spawn(e)),
255 },
256 _ = tokio::time::sleep(timeout) => {
257 process::kill_tree(&child);
258 let _ = child.wait().await; (None, true)
260 }
261 };
262 let _ = tokio::time::timeout(Duration::from_secs(2), stdin_task).await; let (stdout, stdout_tr) = out_task.await.unwrap_or((Bytes::new(), false));
266 let (stderr, stderr_tr) = err_task.await.unwrap_or((Bytes::new(), false));
267 Ok(RawResult {
268 stdout,
269 stderr,
270 stdout_truncated: stdout_tr,
271 stderr_truncated: stderr_tr,
272 exit_code,
273 timed_out,
274 })
275 }
276
277 fn resolve_args(&self, ex: &Exchange) -> Result<Vec<String>, CamelError> {
278 if let Some(v) = ex.input.headers.get(CAMEL_EXEC_ARGS) {
279 serde_json::from_value::<Vec<String>>(v.clone())
280 .map_err(|e| pack(&self.route_id, ExecError::InvalidArgs(e.to_string())))
281 } else {
282 Ok(Vec::new())
283 }
284 }
285
286 fn metric_denied(&self, reason: &'static str) {
287 if let Some(rt) = &self.rt {
288 rt.metrics().record_counter(
289 "exec_policy_denials_total",
290 1.0,
291 &[("reason", reason), ("route", &self.route_id)],
292 );
293 }
294 }
295
296 fn metric_outcome(
297 &self,
298 exit_code: Option<i32>,
299 timed_out: bool,
300 stdout_truncated: bool,
301 dur: Duration,
302 ) {
303 let Some(rt) = &self.rt else { return };
304 rt.metrics().record_histogram(
305 "exec_duration_secs",
306 dur.as_secs_f64(),
307 &[("route", &self.route_id)],
308 );
309 if let Some(c) = exit_code {
310 let code_str = c.to_string();
311 rt.metrics().record_counter(
312 "exec_exit_code",
313 1.0,
314 &[("code", &code_str), ("route", &self.route_id)],
315 );
316 }
317 if timed_out {
318 rt.metrics()
319 .record_counter("exec_timeouts_total", 1.0, &[("route", &self.route_id)]);
320 }
321 if stdout_truncated {
322 rt.metrics().record_counter(
323 "exec_stdout_truncated_total",
324 1.0,
325 &[("route", &self.route_id)],
326 );
327 }
328 }
329}
330
331async fn drain_join<R: tokio::io::AsyncRead + Unpin + Send + 'static>(
333 r: Option<R>,
334 cap: usize,
335) -> (Bytes, bool) {
336 match r {
337 Some(reader) => process::drain_with_cap(reader, cap).await,
338 None => (Bytes::new(), false),
339 }
340}
341
342#[derive(Debug, serde::Serialize, serde::Deserialize)]
346#[non_exhaustive]
347pub struct ExecResult {
348 pub exit_code: Option<i32>,
349 pub stdout: String, pub stderr: String, pub stdout_truncated: bool,
352 pub stderr_truncated: bool,
353 pub timed_out: bool,
354 pub profile: String,
355 pub duration_ms: u64,
356}
357
358fn b64(b: &[u8]) -> String {
359 base64::engine::general_purpose::STANDARD.encode(b)
360}
361
362fn extract_stdin(ex: &Exchange, cap: usize) -> Result<Bytes, ExecError> {
363 let b = match &ex.input.body {
364 Body::Text(s) => Bytes::copy_from_slice(s.as_bytes()),
365 Body::Bytes(b) => Bytes::copy_from_slice(b),
366 Body::Json(v) => Bytes::from(serde_json::to_vec(v).unwrap_or_default()),
367 _ => Bytes::new(),
368 };
369 if b.len() > cap {
370 return Err(ExecError::StdinTooLarge {
371 size: b.len(),
372 max: cap,
373 });
374 }
375 Ok(b)
376}
377
378fn pack(route_id: &str, e: ExecError) -> CamelError {
379 CamelError::ProcessorErrorWithSource(format!("exec producer ({route_id}): {e}"), Arc::new(e))
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385 use crate::config::{ArgPolicy, ExecGlobalConfig, ExecProfile};
386 use camel_api::{Body, Exchange};
387 use std::collections::HashMap;
388 use std::path::PathBuf;
389 use std::sync::Arc;
390 use tokio::sync::Semaphore;
391
392 fn which(name: &str) -> PathBuf {
395 let path = std::env::var_os("PATH").expect("PATH must be set");
396 for dir in std::env::split_paths(&path) {
397 let cand = dir.join(name);
398 if cand.is_file() {
399 return cand; }
401 }
402 panic!("{name} not found on PATH");
403 }
404
405 fn make_global() -> Arc<ExecGlobalConfig> {
406 let root = std::env::temp_dir().canonicalize().unwrap();
407 Arc::new(ExecGlobalConfig {
408 canonical_workspace_root: Some(root),
409 ..ExecGlobalConfig::default()
410 })
411 }
412
413 fn make_profile(
414 exe: &str,
415 args_policy: ArgPolicy,
416 accepted: Vec<i32>,
417 timeout: u64,
418 ) -> ExecProfile {
419 let mut env = crate::config::EnvPolicy::default();
421 if let Ok(path) = std::env::var("PATH") {
422 env.set.insert("PATH".into(), path);
423 }
424
425 ExecProfile {
426 name: "test".into(),
427 executable: exe.into(),
428 args: args_policy,
429 deny_flags: Default::default(),
430 allow_shell: true, env,
432 working_dir: ".".into(),
433 timeout_secs: timeout,
434 accepted_exit_codes: accepted,
435 concurrency: 1,
436 stdin_max_bytes: 1 << 20,
437 stdout_max_bytes: 10 << 20,
438 stderr_max_bytes: 1 << 20,
439 sandbox: Default::default(),
440 output_mode: Default::default(),
441 canonical_executable: Some(which(exe)),
442 }
443 }
444
445 fn make_producer(profile: ExecProfile) -> ExecProducer {
446 ExecProducer {
447 profile: Arc::new(profile),
448 global: make_global(),
449 route_id: "test".into(),
450 host_env: HashMap::new(),
451 semaphore: Arc::new(Semaphore::new(1)),
452 rt: None,
453 }
454 }
455
456 fn set_args(ex: &mut Exchange, args: Vec<&str>) {
458 let v: Vec<String> = args.into_iter().map(String::from).collect();
459 ex.input.headers.insert(
460 crate::headers::CAMEL_EXEC_ARGS.to_string(),
461 serde_json::to_value(v).unwrap(),
462 );
463 }
464
465 fn result_from_body(ex: &Exchange) -> ExecResult {
467 let v = match &ex.input.body {
468 Body::Json(v) => v.clone(),
469 other => panic!("expected Body::Json, got {other:?}"),
470 };
471 serde_json::from_value(v).expect("deserialize ExecResult")
472 }
473
474 #[tokio::test]
475 async fn echo_happy_path() {
476 let profile = make_profile("echo", ArgPolicy::Any, vec![0], 30);
477 let producer = make_producer(profile);
478 let mut ex = Exchange::default();
479 set_args(&mut ex, vec!["hello"]);
480
481 producer.run(&mut ex).await.expect("echo must succeed");
482
483 let result = result_from_body(&ex);
484 assert_eq!(result.exit_code, Some(0));
485 assert!(!result.timed_out);
486 let stdout_bytes = base64::engine::general_purpose::STANDARD
488 .decode(&result.stdout)
489 .unwrap();
490 assert_eq!(stdout_bytes, b"hello\n");
491 assert_eq!(
493 ex.input
494 .headers
495 .get(crate::headers::CAMEL_EXEC_EXIT_ACCEPTED),
496 Some(&serde_json::Value::Bool(true))
497 );
498 assert_eq!(
499 ex.input.headers.get(crate::headers::CAMEL_EXEC_TIMED_OUT),
500 Some(&serde_json::Value::Bool(false))
501 );
502 }
503
504 #[tokio::test]
505 async fn timeout_is_non_error_outcome() {
506 let profile = make_profile("sleep", ArgPolicy::Any, vec![0], 1);
507 let producer = make_producer(profile);
508 let mut ex = Exchange::default();
509 set_args(&mut ex, vec!["30"]);
510
511 let res = producer.run(&mut ex).await;
513 assert!(
514 res.is_ok(),
515 "timeout must be non-error outcome, got {res:?}"
516 );
517
518 let result = result_from_body(&ex);
519 assert_eq!(result.exit_code, None, "killed process has no exit code");
520 assert!(result.timed_out, "must be marked as timed out");
521 assert_eq!(
523 ex.input
524 .headers
525 .get(crate::headers::CAMEL_EXEC_EXIT_ACCEPTED),
526 Some(&serde_json::Value::Bool(false))
527 );
528 assert_eq!(
529 ex.input.headers.get(crate::headers::CAMEL_EXEC_TIMED_OUT),
530 Some(&serde_json::Value::Bool(true))
531 );
532 }
533
534 #[tokio::test]
535 async fn non_zero_exit_is_non_error_outcome() {
536 let profile = make_profile("sh", ArgPolicy::Any, vec![0], 30);
538 let producer = make_producer(profile);
539 let mut ex = Exchange::default();
540 set_args(&mut ex, vec!["-c", "exit 2"]);
541
542 let res = producer.run(&mut ex).await;
543 assert!(res.is_ok(), "non-zero exit must be non-error outcome");
544
545 let result = result_from_body(&ex);
546 assert_eq!(result.exit_code, Some(2));
547 assert!(!result.timed_out);
548 assert_eq!(
549 ex.input
550 .headers
551 .get(crate::headers::CAMEL_EXEC_EXIT_ACCEPTED),
552 Some(&serde_json::Value::Bool(false)),
553 "exit 2 not in accepted_exit_codes=[0]"
554 );
555
556 let profile2 = make_profile("sh", ArgPolicy::Any, vec![2], 30);
558 let producer2 = make_producer(profile2);
559 let mut ex2 = Exchange::default();
560 set_args(&mut ex2, vec!["-c", "exit 2"]);
561
562 producer2.run(&mut ex2).await.expect("must succeed");
563 assert_eq!(
564 ex2.input
565 .headers
566 .get(crate::headers::CAMEL_EXEC_EXIT_ACCEPTED),
567 Some(&serde_json::Value::Bool(true)),
568 "exit 2 in accepted_exit_codes=[2]"
569 );
570 }
571}