1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//! Async NSE Executor - Tokio-based async Lua VM wrapper
//!
//! Wraps ExecutorCore and adds tokio runtime ownership for async
//! NSE script execution contexts.
use mlua::{Lua, Result as LuaResult};
use std::path::PathBuf;
use tokio::runtime::Runtime;
use crate::executor_core::ExecutorCore;
use crate::limits::{NseCancellationToken, NseExecutionLimits, NseExecutionStats};
use crate::profile::{NseExecutionProfileKind, NseModulePolicy, NseNetworkPolicy, NseScriptPolicy};
use crate::SandboxMetrics;
/// Async NSE Executor with tokio runtime support.
///
/// Composes ExecutorCore for shared Lua VM state and adds optional
/// tokio runtime ownership for callers who need to spawn async tasks.
pub struct AsyncNseExecutor {
core: ExecutorCore,
runtime: Option<Runtime>,
owns_runtime: bool,
}
impl AsyncNseExecutor {
/// Create a new async executor with its own tokio runtime.
pub fn new() -> LuaResult<Self> {
let runtime = Runtime::new().map_err(|e| {
mlua::Error::RuntimeError(format!("Failed to create tokio runtime: {}", e))
})?;
Ok(Self {
core: ExecutorCore::new()?,
runtime: Some(runtime),
owns_runtime: true,
})
}
/// Create a new async executor with sandbox restrictions.
pub fn with_sandbox(sandbox: crate::SandboxConfig) -> LuaResult<Self> {
let runtime = Runtime::new().map_err(|e| {
mlua::Error::RuntimeError(format!("Failed to create tokio runtime: {}", e))
})?;
Ok(Self {
core: ExecutorCore::with_sandbox(sandbox)?,
runtime: Some(runtime),
owns_runtime: true,
})
}
/// Create async executor with a specific target.
pub fn with_target(target: &str) -> LuaResult<Self> {
let mut exec = Self::new()?;
exec.core.set_target(target).ok();
Ok(exec)
}
/// Create async executor using an externally-managed runtime.
/// The runtime will NOT be shut down when this executor is dropped.
pub fn with_runtime(runtime: Runtime) -> LuaResult<Self> {
Ok(Self {
core: ExecutorCore::new()?,
runtime: Some(runtime),
owns_runtime: false,
})
}
/// Create an async executor with explicit execution limits and cancellation token.
///
/// # Manual-only capability context
///
/// This constructor hardcodes `ManualPermissive` profile kind and
/// `AllowAllManual` network policy in the capability context. It is
/// intended for manual CLI/TUI surfaces where the operator is trusted
/// to scope behavior interactively. Marked `#[doc(hidden)]` to
/// discourage future automated callers from routing around the profile
/// engine.
///
/// Automated surfaces (MCP, agent, REST, daemon, CI) MUST use
/// [`AsyncNseExecutor::with_full_policy`] or
/// [`AsyncNseExecutor::with_profile`] so the capability engine enforces
/// the resolved profile's `profile_kind` and `network_policy`.
#[doc(hidden)]
pub fn with_policy(
sandbox: crate::SandboxConfig,
limits: NseExecutionLimits,
cancellation: NseCancellationToken,
script_policy: NseScriptPolicy,
module_policy: NseModulePolicy,
) -> LuaResult<Self> {
let runtime = Runtime::new().map_err(|e| {
mlua::Error::RuntimeError(format!("Failed to create tokio runtime: {}", e))
})?;
Ok(Self {
core: ExecutorCore::with_policy(
sandbox,
limits,
cancellation,
script_policy,
module_policy,
)?,
runtime: Some(runtime),
owns_runtime: true,
})
}
/// Create an async executor with explicit profile kind and network policy.
///
/// This is the canonical constructor for automated surfaces. It accepts
/// the full capability policy set (`profile_kind`, `network_policy`,
/// sandbox, limits, script/module policies) and threads them through to
/// the `NseCapabilityContext` so capability decisions match the resolved
/// profile.
///
/// Automated surfaces should prefer [`AsyncNseExecutor::with_profile`]
/// (which derives these fields from a `ResolvedNseExecutionProfile`).
pub fn with_full_policy(
sandbox: crate::SandboxConfig,
limits: NseExecutionLimits,
cancellation: NseCancellationToken,
script_policy: NseScriptPolicy,
module_policy: NseModulePolicy,
profile_kind: NseExecutionProfileKind,
network_policy: NseNetworkPolicy,
) -> LuaResult<Self> {
let runtime = Runtime::new().map_err(|e| {
mlua::Error::RuntimeError(format!("Failed to create tokio runtime: {}", e))
})?;
Ok(Self {
core: ExecutorCore::with_full_policy(
sandbox,
limits,
cancellation,
script_policy,
module_policy,
profile_kind,
network_policy,
)?,
runtime: Some(runtime),
owns_runtime: true,
})
}
/// Create an async executor from a resolved execution profile.
///
/// This is the preferred constructor when a profile is available.
/// It threads the profile's `kind` and `network_policy` into the
/// capability context so capability decisions match the resolved profile.
pub fn with_profile(profile: &crate::profile::ResolvedNseExecutionProfile) -> LuaResult<Self> {
let runtime = Runtime::new().map_err(|e| {
mlua::Error::RuntimeError(format!("Failed to create tokio runtime: {}", e))
})?;
Ok(Self {
core: ExecutorCore::with_profile(profile)?,
runtime: Some(runtime),
owns_runtime: true,
})
}
/// Create an async executor with explicit policy plus host services.
pub fn with_full_policy_and_services(
sandbox: crate::SandboxConfig,
limits: NseExecutionLimits,
cancellation: NseCancellationToken,
script_policy: NseScriptPolicy,
module_policy: NseModulePolicy,
profile_kind: NseExecutionProfileKind,
network_policy: NseNetworkPolicy,
host_services: crate::providers::NseHostServices,
) -> LuaResult<Self> {
let runtime = Runtime::new().map_err(|e| {
mlua::Error::RuntimeError(format!("Failed to create tokio runtime: {}", e))
})?;
Ok(Self {
core: ExecutorCore::with_full_policy_and_services(
sandbox,
limits,
cancellation,
script_policy,
module_policy,
profile_kind,
network_policy,
host_services,
)?,
runtime: Some(runtime),
owns_runtime: true,
})
}
/// Create an async executor from a resolved profile plus host services.
pub fn with_profile_and_services(
profile: &crate::profile::ResolvedNseExecutionProfile,
host_services: crate::providers::NseHostServices,
) -> LuaResult<Self> {
let runtime = Runtime::new().map_err(|e| {
mlua::Error::RuntimeError(format!("Failed to create tokio runtime: {}", e))
})?;
Ok(Self {
core: ExecutorCore::with_profile_and_services(profile, host_services)?,
runtime: Some(runtime),
owns_runtime: true,
})
}
/// Borrow the per-run host services.
pub fn host_services(&self) -> &crate::providers::NseHostServices {
self.core.host_services()
}
/// Create async executor with policy on an externally-managed runtime.
///
/// # Manual-only capability context
///
/// See [`AsyncNseExecutor::with_policy`] — this constructor shares the
/// same manual-permissive capability semantics. Automated surfaces must
/// use [`AsyncNseExecutor::with_profile`] or
/// [`AsyncNseExecutor::with_full_policy`].
pub fn with_policy_and_runtime(
sandbox: crate::SandboxConfig,
limits: NseExecutionLimits,
cancellation: NseCancellationToken,
script_policy: NseScriptPolicy,
module_policy: NseModulePolicy,
runtime: Runtime,
) -> LuaResult<Self> {
Ok(Self {
core: ExecutorCore::with_policy(
sandbox,
limits,
cancellation,
script_policy,
module_policy,
)?,
runtime: Some(runtime),
owns_runtime: false,
})
}
/// Set the target host.
pub fn set_target(&mut self, target: &str) {
self.core.set_target(target).ok();
}
/// Get the target host.
pub fn get_target(&self) -> &str {
self.core.target()
}
/// Add a scripts search path.
pub fn add_scripts_path(&self, path: PathBuf) {
self.core.add_scripts_path(path);
}
/// Run an NSE script synchronously.
pub fn run_script(&self, script: &str) -> LuaResult<String> {
self.core.run_script(script)
}
/// Run a script with the configured execution limits.
pub fn run_script_with_limits(&self, script: &str) -> LuaResult<String> {
self.core.run_script(script)
}
/// Get the execution stats from the last run.
pub fn execution_stats(&self) -> NseExecutionStats {
self.core.execution_stats()
}
/// Get a reference to the cancellation token.
pub fn cancellation_token(&self) -> &NseCancellationToken {
self.core.cancellation_token()
}
/// Get a reference to the execution limits.
pub fn limits(&self) -> &NseExecutionLimits {
self.core.limits()
}
/// Get access to the underlying Lua VM.
pub fn lua(&self) -> &Lua {
self.core.lua()
}
pub fn get_sandbox_metrics(&self) -> SandboxMetrics {
self.core.get_sandbox_metrics()
}
/// Get a reference to the executor's capability context.
pub fn capability_context(&self) -> &crate::capabilities::NseCapabilityContext {
self.core.capability_context()
}
/// Get all recorded capability events.
pub fn capability_events(&self) -> Vec<crate::capabilities::NseCapabilityEvent> {
self.core.capability_context().events()
}
/// Get access to the tokio runtime, if available.
pub fn runtime(&self) -> Option<&Runtime> {
self.runtime.as_ref()
}
}
impl Drop for AsyncNseExecutor {
fn drop(&mut self) {
if self.owns_runtime {
if let Some(runtime) = self.runtime.take() {
runtime.shutdown_timeout(std::time::Duration::from_secs(5));
}
}
}
}