Skip to main content

adk_code/
embedded_js.rs

1//! Embedded JavaScript executor — secondary script backend.
2//!
3//! [`EmbeddedJsExecutor`] uses `boa_engine` to run JavaScript snippets
4//! in-process. It is useful for lightweight transforms, deterministic
5//! state shaping, and compatibility with existing Studio JS flows.
6//!
7//! This is **not** the primary code-execution path. The flagship backend
8//! is [`crate::RustSandboxExecutor`] for authored Rust code.
9//!
10//! # Security Model
11//!
12//! - In-process execution on a dedicated thread (no container isolation)
13//! - No filesystem access
14//! - No network access
15//! - No child process creation
16//! - Deadline enforced on the result: `execute` returns
17//!   [`ExecutionStatus::Timeout`] once the policy timeout passes
18//! - Runtime limits stop runaway scripts: loop iterations per call frame,
19//!   call depth, and VM stack size
20//! - No heap limit — `boa_engine` 0.20 has none
21//! - JSON input injected as `input` variable
22//! - Return value converted back to JSON
23//!
24//! # Example
25//!
26//! ```rust,ignore
27//! use adk_code::{EmbeddedJsExecutor, CodeExecutor, ExecutionRequest,
28//!     ExecutionLanguage, ExecutionPayload, SandboxPolicy};
29//!
30//! let executor = EmbeddedJsExecutor::new();
31//! let request = ExecutionRequest {
32//!     language: ExecutionLanguage::JavaScript,
33//!     payload: ExecutionPayload::Source {
34//!         code: "return input.x + 1;".to_string(),
35//!     },
36//!     argv: vec![],
37//!     stdin: None,
38//!     input: Some(serde_json::json!({ "x": 41 })),
39//!     sandbox: SandboxPolicy::strict_js(),
40//!     identity: None,
41//! };
42//! ```
43
44use async_trait::async_trait;
45use boa_engine::{Context, JsNativeError, JsValue, Source};
46use std::time::Instant;
47use tracing::warn;
48
49use crate::{
50    BackendCapabilities, CodeExecutor, ExecutionError, ExecutionIsolation, ExecutionLanguage,
51    ExecutionPayload, ExecutionRequest, ExecutionResult, ExecutionStatus,
52};
53
54/// Loop iterations allowed per call frame before Boa throws an uncatchable
55/// `RuntimeLimit` error. Boa has no preemption, so this is what stops a
56/// `while (true) {}` after the caller's deadline has passed.
57const LOOP_ITERATION_LIMIT: u64 = 10_000_000;
58
59/// Maximum JavaScript call depth.
60const RECURSION_LIMIT: usize = 512;
61
62/// Maximum number of values on the Boa VM stack.
63const STACK_SIZE_LIMIT: usize = 10 * 1024;
64
65/// Native stack for the interpreter thread. JavaScript calls made through
66/// native builtins (`Array.prototype.map` callbacks, getters) recurse on the
67/// Rust stack; 8 MiB leaves headroom for unoptimised `boa_engine` builds, whose
68/// frames are larger, to reach `RECURSION_LIMIT` before overflowing.
69const INTERPRETER_STACK_BYTES: usize = 8 * 1024 * 1024;
70
71/// Secondary embedded JavaScript executor using `boa_engine`.
72///
73/// Runs JavaScript snippets in-process for lightweight transforms.
74/// Does not provide container-level isolation — the security boundary
75/// is the `boa_engine` interpreter sandbox.
76///
77/// # Isolation Model — Enforcement by Omission
78///
79/// `boa_engine` is a pure ECMAScript interpreter with **no** built-in APIs for
80/// network access, filesystem operations, or environment variable reads. Unlike
81/// Node.js or Deno, Boa does not expose `fetch`, `fs`, `process.env`, or any
82/// host-level I/O. This means network, filesystem, and environment policies are
83/// enforced by omission — the engine simply cannot perform those operations.
84///
85/// [`capabilities()`](Self::capabilities) reports `enforce_network_policy`,
86/// `enforce_filesystem_policy`, and `enforce_environment_policy` as `true`
87/// because the isolation guarantee holds unconditionally.
88///
89/// # Timeouts and Runtime Limits
90///
91/// Each evaluation runs on its own thread. [`execute`](CodeExecutor::execute)
92/// waits for it until [`SandboxPolicy::timeout`](crate::SandboxPolicy::timeout)
93/// and then returns [`ExecutionStatus::Timeout`].
94///
95/// Boa cannot be interrupted from another thread, so a timed-out evaluation keeps
96/// running in the background, consuming a core, until it finishes or reaches a
97/// runtime limit. The loop limit counts per call frame, so a loop that repeatedly
98/// calls a looping function can run far longer than one frame's limit.
99///
100/// | Limit | Value | Error |
101/// |---|---|---|
102/// | Loop iterations per call frame | 10,000,000 | `RuntimeLimit` |
103/// | Call depth | 512 | `RuntimeLimit` |
104/// | VM stack values | 10,240 | `RuntimeLimit` |
105///
106/// `RuntimeLimit` errors cannot be caught by `try`/`catch`. A limit reached
107/// before the deadline yields [`ExecutionStatus::Failed`] with the limit named in
108/// `stderr`. Work inside a single native builtin — a pathological regular
109/// expression, for example — is not counted by any limit, and there is no heap
110/// limit.
111///
112/// # Product Posture
113///
114/// This backend is secondary scripting support. Use [`crate::RustSandboxExecutor`]
115/// for the primary authored-code path.
116#[derive(Debug, Default)]
117pub struct EmbeddedJsExecutor;
118
119impl EmbeddedJsExecutor {
120    /// Create a new embedded JS executor.
121    pub fn new() -> Self {
122        Self
123    }
124}
125
126#[async_trait]
127impl CodeExecutor for EmbeddedJsExecutor {
128    fn name(&self) -> &str {
129        "EmbeddedJsExecutor"
130    }
131
132    /// Returns the capabilities of this backend.
133    ///
134    /// Network, filesystem, and environment policies are reported as enforced
135    /// because `boa_engine` has no APIs for those operations (enforcement by
136    /// omission). The timeout is enforced on the result: `execute` returns at the
137    /// deadline, and runtime limits stop the abandoned interpreter. See the
138    /// [struct-level docs](Self) for details.
139    fn capabilities(&self) -> BackendCapabilities {
140        BackendCapabilities {
141            isolation: ExecutionIsolation::InProcess,
142            // boa_engine has no network, filesystem, or environment APIs —
143            // enforcement is by omission: the engine simply cannot perform
144            // these operations, so the policies are inherently satisfied.
145            enforce_network_policy: true,
146            enforce_filesystem_policy: true,
147            enforce_environment_policy: true,
148            enforce_timeout: true,
149            supports_structured_output: true,
150            supports_process_execution: false,
151            supports_persistent_workspace: false,
152            supports_interactive_sessions: false,
153        }
154    }
155
156    fn supports_language(&self, lang: &ExecutionLanguage) -> bool {
157        matches!(lang, ExecutionLanguage::JavaScript)
158    }
159
160    async fn execute(&self, request: ExecutionRequest) -> Result<ExecutionResult, ExecutionError> {
161        crate::validate_request(&self.capabilities(), &[ExecutionLanguage::JavaScript], &request)?;
162
163        let code = match &request.payload {
164            ExecutionPayload::Source { code } => code.clone(),
165            ExecutionPayload::GuestModule { .. } => {
166                return Err(ExecutionError::InvalidRequest(
167                    "EmbeddedJsExecutor does not support guest modules".to_string(),
168                ));
169            }
170        };
171
172        if code.trim().is_empty() {
173            return Err(ExecutionError::InvalidRequest("empty JavaScript source".to_string()));
174        }
175
176        let timeout = request.sandbox.timeout;
177        let input = request.input.clone();
178        let start = Instant::now();
179
180        // A dedicated thread rather than `spawn_blocking`: a runaway script must
181        // not occupy a blocking-pool thread or hold up runtime shutdown.
182        let (sender, receiver) = tokio::sync::oneshot::channel();
183        std::thread::Builder::new()
184            .name("adk-embedded-js".to_string())
185            .stack_size(INTERPRETER_STACK_BYTES)
186            .spawn(move || {
187                // The receiver is gone once the caller has timed out; the result is discarded.
188                let _ = sender.send(evaluate(&code, input.as_ref()));
189            })
190            .map_err(|e| {
191                ExecutionError::InternalError(format!("failed to spawn JavaScript thread: {e}"))
192            })?;
193
194        match tokio::time::timeout(timeout, receiver).await {
195            Ok(Ok(result)) => Ok(result),
196            Ok(Err(_)) => Err(ExecutionError::InternalError("JS thread panicked".to_string())),
197            Err(_) => {
198                warn!(
199                    timeout_ms = timeout.as_millis() as u64,
200                    "javascript execution timed out; the interpreter stops at its next runtime limit"
201                );
202                Ok(ExecutionResult {
203                    status: ExecutionStatus::Timeout,
204                    stdout: String::new(),
205                    stderr: format!("execution exceeded timeout of {}ms", timeout.as_millis()),
206                    output: None,
207                    exit_code: None,
208                    stdout_truncated: false,
209                    stderr_truncated: false,
210                    duration_ms: start.elapsed().as_millis() as u64,
211                    metadata: None,
212                })
213            }
214        }
215    }
216}
217
218/// Evaluates `code` in a fresh, limited Boa context with `input` bound as a global.
219fn evaluate(code: &str, input: Option<&serde_json::Value>) -> ExecutionResult {
220    let start = Instant::now();
221    let mut context = Context::default();
222    let limits = context.runtime_limits_mut();
223    limits.set_loop_iteration_limit(LOOP_ITERATION_LIMIT);
224    limits.set_recursion_limit(RECURSION_LIMIT);
225    limits.set_stack_size_limit(STACK_SIZE_LIMIT);
226
227    let failed = |stderr: String, start: Instant| ExecutionResult {
228        status: ExecutionStatus::Failed,
229        stdout: String::new(),
230        stderr,
231        output: None,
232        exit_code: None,
233        stdout_truncated: false,
234        stderr_truncated: false,
235        duration_ms: start.elapsed().as_millis() as u64,
236        metadata: None,
237    };
238
239    // Inject input as a global variable.
240    let input_str = input
241        .map(|v| serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()))
242        .unwrap_or_else(|| "null".to_string());
243
244    let setup = format!("var input = {input_str};");
245    if let Err(e) = context.eval(Source::from_bytes(&setup)) {
246        return failed(format!("Failed to inject input: {e:?}"), start);
247    }
248
249    // Wrap user code in an IIFE so `return` works.
250    let wrapped = format!("(function() {{ {code} }})()");
251    match context.eval(Source::from_bytes(&wrapped)) {
252        Ok(val) => {
253            let output = js_value_to_json(&val, &mut context);
254            ExecutionResult {
255                status: ExecutionStatus::Success,
256                stdout: String::new(),
257                stderr: String::new(),
258                output: Some(output),
259                exit_code: None,
260                stdout_truncated: false,
261                stderr_truncated: false,
262                duration_ms: start.elapsed().as_millis() as u64,
263                metadata: None,
264            }
265        }
266        Err(e) if e.as_native().is_some_and(JsNativeError::is_runtime_limit) => {
267            failed(format!("JavaScript runtime limit exceeded: {e}"), start)
268        }
269        Err(e) => failed(format!("JavaScript error: {e:?}"), start),
270    }
271}
272
273/// Convert a `boa_engine` JS value to a `serde_json::Value`.
274fn js_value_to_json(val: &JsValue, context: &mut Context) -> serde_json::Value {
275    match val {
276        JsValue::Null | JsValue::Undefined => serde_json::Value::Null,
277        JsValue::Boolean(b) => serde_json::Value::Bool(*b),
278        JsValue::Integer(n) => serde_json::json!(*n),
279        JsValue::Rational(n) => {
280            if n.is_finite() {
281                serde_json::json!(*n)
282            } else {
283                serde_json::Value::Null
284            }
285        }
286        JsValue::String(s) => serde_json::Value::String(s.to_std_string_escaped()),
287        JsValue::BigInt(n) => serde_json::Value::String(n.to_string()),
288        JsValue::Symbol(_) => serde_json::Value::Null,
289        JsValue::Object(_) => {
290            // Use JSON.stringify to serialize complex objects.
291            let stringify_code = format!(
292                "JSON.stringify({})",
293                // Re-evaluate the value by wrapping in a closure isn't practical,
294                // so we use a global temp variable approach.
295                "__adk_tmp__"
296            );
297            // Set the value as a global temp
298            let global = context.global_object();
299            let key = boa_engine::JsString::from("__adk_tmp__");
300            let _ = global.set(key.clone(), val.clone(), false, context);
301            let result = context.eval(Source::from_bytes(stringify_code.as_bytes()));
302            // Clean up
303            let _ = global.delete_property_or_throw(key, context);
304
305            if let Ok(json_val) = result
306                && let Some(s) = json_val.as_string()
307            {
308                let std_str: String = s.to_std_string_escaped();
309                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&std_str) {
310                    return parsed;
311                }
312            }
313            serde_json::Value::String("[object]".to_string())
314        }
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use crate::SandboxPolicy;
322    use std::time::Duration;
323
324    fn js_request(code: &str, timeout: Duration) -> ExecutionRequest {
325        ExecutionRequest {
326            language: ExecutionLanguage::JavaScript,
327            payload: ExecutionPayload::Source { code: code.to_string() },
328            argv: vec![],
329            stdin: None,
330            input: Some(serde_json::json!({ "x": 41 })),
331            sandbox: SandboxPolicy { timeout, ..SandboxPolicy::strict_js() },
332            identity: None,
333        }
334    }
335
336    #[tokio::test]
337    async fn returns_json_output() {
338        let result = EmbeddedJsExecutor::new()
339            .execute(js_request("return { y: input.x + 1 };", Duration::from_secs(5)))
340            .await
341            .unwrap();
342        assert_eq!(result.status, ExecutionStatus::Success);
343        assert_eq!(result.output, Some(serde_json::json!({ "y": 42 })));
344    }
345
346    /// An infinite loop returns within the deadline instead of blocking the caller.
347    #[tokio::test]
348    async fn infinite_loop_returns_at_the_deadline() {
349        let timeout = Duration::from_millis(500);
350        let started = Instant::now();
351        let result = EmbeddedJsExecutor::new()
352            .execute(js_request("while (true) {}", timeout))
353            .await
354            .unwrap();
355
356        assert!(
357            started.elapsed() < timeout + Duration::from_secs(2),
358            "took {:?}",
359            started.elapsed()
360        );
361        let stopped_by_limit = result.status == ExecutionStatus::Failed
362            && result.stderr.contains("runtime limit exceeded");
363        assert!(
364            result.status == ExecutionStatus::Timeout || stopped_by_limit,
365            "unexpected result: {result:?}"
366        );
367    }
368
369    /// The loop limit stops the interpreter itself, so an abandoned evaluation
370    /// does not spin forever. `try`/`catch` cannot swallow it.
371    #[test]
372    fn loop_limit_stops_the_interpreter_and_cannot_be_caught() {
373        let result = evaluate("try { while (true) {} } catch (e) { return 'caught'; }", None);
374        assert_eq!(result.status, ExecutionStatus::Failed, "{result:?}");
375        assert!(result.stderr.contains("runtime limit exceeded"), "{}", result.stderr);
376        assert!(result.stderr.contains("loop iteration"), "{}", result.stderr);
377    }
378
379    /// Loop limits are per call frame, so repeated calls into a looping function
380    /// outlast any single limit; the deadline still returns control to the caller.
381    #[tokio::test]
382    async fn work_spread_across_frames_returns_timeout_at_the_deadline() {
383        let timeout = Duration::from_millis(300);
384        let code =
385            "function spin() { for (let i = 0; i < 1000000; i++) {} } while (true) { spin(); }";
386        let started = Instant::now();
387        let result = EmbeddedJsExecutor::new().execute(js_request(code, timeout)).await.unwrap();
388
389        assert_eq!(result.status, ExecutionStatus::Timeout, "{result:?}");
390        assert!(
391            started.elapsed() < timeout + Duration::from_secs(2),
392            "took {:?}",
393            started.elapsed()
394        );
395    }
396
397    #[test]
398    fn unbounded_recursion_hits_the_recursion_limit() {
399        let result = evaluate("function f() { return f(); } return f();", None);
400        assert_eq!(result.status, ExecutionStatus::Failed, "{result:?}");
401        assert!(result.stderr.contains("runtime limit exceeded"), "{}", result.stderr);
402    }
403
404    /// Recursion through a native builtin uses the Rust stack; the interpreter
405    /// thread must hit the call-depth limit before it overflows.
406    #[tokio::test]
407    async fn recursion_through_native_builtins_hits_the_limit_not_the_native_stack() {
408        let code = "function f(n) { return [n].map(x => f(x + 1)); } return f(0);";
409        let result = EmbeddedJsExecutor::new()
410            .execute(js_request(code, Duration::from_secs(30)))
411            .await
412            .unwrap();
413        assert_eq!(result.status, ExecutionStatus::Failed, "{result:?}");
414        assert!(result.stderr.contains("runtime limit exceeded"), "{}", result.stderr);
415    }
416}