mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ExecutionRequest, ScriptResponse};
use crate::mxc_common::mxc_error::MxcError;
use crate::mxc_common::validator::{
    validate_common, validate_network_policy_support, NetworkPolicySupport,
};

/// Executor-owned cooperative cancellation. It owns no native handles and installs no handlers.
#[doc(hidden)]
#[derive(Debug, Clone, Default)]
pub struct RunCancellation(std::sync::Arc<std::sync::atomic::AtomicU8>);

impl RunCancellation {
    const REQUESTED: u8 = 1;
    const OBSERVED: u8 = 2;
    const COMPLETE: u8 = 4;

    /// Returns false once the execution owner has finished cleanup.
    pub fn request(&self) -> bool {
        self.0
            .fetch_or(Self::REQUESTED, std::sync::atomic::Ordering::AcqRel)
            & Self::COMPLETE
            == 0
    }

    pub fn was_cancelled(&self) -> bool {
        self.0.load(std::sync::atomic::Ordering::Acquire) & Self::OBSERVED != 0
    }

    pub fn begin(&self) {
        // Preserve a request that arrived before a new run, but reset a reused runner.
        let _ = self.0.fetch_update(
            std::sync::atomic::Ordering::AcqRel,
            std::sync::atomic::Ordering::Acquire,
            |state| (state & Self::COMPLETE != 0).then_some(0),
        );
    }

    pub fn complete(&self) {
        self.0
            .fetch_or(Self::COMPLETE, std::sync::atomic::Ordering::AcqRel);
    }

    pub fn check(&self) -> Result<(), MxcError> {
        if self.0.load(std::sync::atomic::Ordering::Acquire) & Self::REQUESTED != 0 {
            self.0
                .fetch_or(Self::OBSERVED, std::sync::atomic::Ordering::AcqRel);
            Err(MxcError::backend_error("execution cancelled"))
        } else {
            Ok(())
        }
    }
}

/// Trait for executing scripts within a containment backend.
///
/// Each backend (AppContainer, Windows Sandbox, etc.) implements this trait
/// to provide a uniform interface for `wxc-exec`.
///
/// Implementors provide [`execute`](ScriptRunner::execute) and optionally
/// [`validate_runner`](ScriptRunner::validate_runner). The provided
/// [`run`](ScriptRunner::run) method handles validation, dry-run mode,
/// and delegates to [`execute`](ScriptRunner::execute).
pub trait ScriptRunner {
    /// A cancellation signal only when this runner can cooperatively tear down its run.
    fn cancellation(&self) -> Option<RunCancellation> {
        None
    }

    /// Validate shared network support and runner-specific constraints.
    fn validate_runner(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> {
        validate_network_policy_support(request, NetworkPolicySupport::default())?;
        Ok(())
    }

    /// Execute the script inside this backend's containment and return the response.
    /// Implement this instead of `run` — validation and dry-run are handled by the trait.
    fn execute(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse;

    /// Entry point called by the binary. Runs shared validation, runner-specific
    /// validation, checks for dry-run mode, then delegates to
    /// [`execute`](ScriptRunner::execute).
    fn run(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
        if let Err(response) = validate_common(request) {
            return response;
        }

        if let Err(response) = self.validate_runner(request) {
            return response;
        }

        if request.dry_run {
            return ScriptResponse {
                exit_code: 0,
                ..Default::default()
            };
        }

        self.execute(request, logger)
    }
}

/// Convert a timeout value to milliseconds, treating 0 as infinite (INFINITE = `u32::MAX`).
pub fn get_timeout_milliseconds(timeout: u32) -> u32 {
    if timeout == 0 {
        u32::MAX
    } else {
        timeout
    }
}

/// The one-line dry-run verdict, including the rejection reason when there is
/// one.
fn dry_run_summary(response: &ScriptResponse) -> String {
    if response.exit_code == 0 {
        return "Dry run completed. Result: validation passed".to_string();
    }
    if response.error_message.is_empty() {
        return "Dry run completed. Result: validation failed".to_string();
    }
    format!(
        "Dry run completed. Result: validation failed: {}",
        response.error_message
    )
}

pub fn emit_dry_run_result(response: &ScriptResponse, logger: &mut Logger) {
    use std::fmt::Write;
    let _ = writeln!(logger, "{}", dry_run_summary(response));
    print!("{}", logger.get_buffer());
    emit_backend_error_envelope(response);
}

/// Print a dry-run result message to the logger, flush, and exit the process.
/// A failed dry run also emits its typed error envelope on stderr.
pub fn handle_dry_run_exit(response: &ScriptResponse, logger: &mut Logger) -> ! {
    emit_dry_run_result(response, logger);
    std::process::exit(response.exit_code);
}

/// Emit a structured JSON error envelope on stderr when a completed run carries
/// an infrastructure error message.
///
/// Shared by `wxc-exec` and `lxc-exec` so that MXC never exits non-zero on an
/// infrastructure failure without first printing a machine-readable diagnostic
/// (see issue #564). This deliberately keys off a **non-empty**
/// `error_message`: a sandboxed process that merely exits non-zero on its own
/// (a faithfully propagated guest exit code, no MXC error) leaves
/// `error_message` empty and is intentionally not annotated here.
///
/// In non-debug mode the diagnostic `Logger` is buffered and never flushed, so
/// this envelope is the only place the error surfaces to the caller.
///
/// The `code` comes from the response's
/// [`FailurePhase`](crate::mxc_common::models::FailurePhase), so a refused policy is
/// reported as `policy_validation` and a host that cannot provide the backend
/// as `backend_unavailable`, rather than both being flattened into the generic
/// `backend_error` every other failure uses. The envelope starts on a fresh line
/// because the workload's stderr may not end in a newline.
pub fn emit_backend_error_envelope(response: &ScriptResponse) {
    if let Some(line) = backend_error_envelope_line(response) {
        eprintln!("\n{line}");
    }
}

/// The stderr line [`emit_backend_error_envelope`] writes, if any.
fn backend_error_envelope_line(response: &ScriptResponse) -> Option<String> {
    if response.exit_code == 0 || response.error_message.is_empty() {
        return None;
    }

    if let Some(error) = response.structured_error() {
        return Some(console_error_envelope(error.clone()));
    }
    let mut envelope = serde_json::json!({
        "error": {
            "code": response.failure_phase.error_code().as_str(),
            "message": response.error_message,
        }
    });
    if !response.extended_error.is_empty() {
        envelope["error"]["extended_error"] =
            serde_json::Value::String(response.extended_error.clone());
    }
    serde_json::to_string(&envelope).ok()
}

fn console_error_envelope(mut error: crate::mxc_common::mxc_error::ErrorEnvelope) -> String {
    error.details = None;
    serde_json::to_string(&serde_json::json!({ "error": error })).unwrap_or_else(|_| {
        MxcError::backend_error("failed to serialise error envelope").to_envelope_string()
    })
}

/// The stderr lines a run's warnings are emitted as, one JSON object each.
///
/// Kept separate from [`emit_warning_envelopes`] so the exact bytes a caller
/// has to parse are testable without capturing the process's stderr.
fn warning_envelope_lines(warnings: &[String]) -> Vec<String> {
    warnings
        .iter()
        .filter(|warning| !warning.trim().is_empty())
        .filter_map(|warning| {
            serde_json::to_string(&serde_json::json!({ "warning": { "message": warning } })).ok()
        })
        .collect()
}

/// Emit each warning as its own structured JSON line on stderr.
///
/// Warnings are reported on success as well as on failure, so this is separate
/// from [`emit_backend_error_envelope`] rather than folded into it. One object
/// per line keeps the stream parseable a line at a time, matching the error
/// envelope. The batch starts on a fresh line because the workload's stderr may
/// not end in a newline.
pub fn emit_warning_envelopes(warnings: &[String]) {
    let lines = warning_envelope_lines(warnings);
    if !lines.is_empty() {
        eprintln!("\n{}", lines.join("\n"));
    }
}

/// Emit a typed JSON error envelope on stderr for a failure raised before any
/// [`ScriptResponse`] exists, then exit with the status its code implies.
///
/// Shared by every executor entry point. Without it such a failure prints a
/// bare line and exits 1, which a caller cannot tell from a typed policy
/// rejection.
pub fn emit_mxc_error_exit(error: &MxcError) -> ! {
    eprintln!("{}", console_error_envelope(error.to_envelope()));
    std::process::exit(error.code.exit_code());
}

#[cfg(test)]
mod tests {
    use super::get_timeout_milliseconds;

    #[test]
    fn timeout_zero_returns_u32_max() {
        let result = get_timeout_milliseconds(0);
        assert_eq!(result, u32::MAX);
    }

    #[test]
    fn timeout_non_zero_returns_same_value() {
        let value = 1500u32;
        let result = get_timeout_milliseconds(value);
        assert_eq!(result, value);
    }

    #[test]
    fn error_envelope_is_noop_without_error() {
        use crate::mxc_common::models::ScriptResponse;
        // exit 0 => no-op; non-zero but empty message (clean sandbox exit) => no-op.
        assert!(super::backend_error_envelope_line(&ScriptResponse {
            exit_code: 0,
            error_message: "ignored on success".to_string(),
            ..Default::default()
        })
        .is_none());
        assert!(super::backend_error_envelope_line(&ScriptResponse {
            exit_code: 1,
            error_message: String::new(),
            ..Default::default()
        })
        .is_none());
    }

    #[test]
    fn error_envelope_carries_the_code_for_each_failure_kind() {
        use crate::mxc_common::models::ScriptResponse;
        let cases = [
            (ScriptResponse::rejected("refused"), "policy_validation"),
            (
                ScriptResponse::unavailable("missing"),
                "backend_unavailable",
            ),
            (ScriptResponse::error("broke"), "backend_error"),
        ];
        for (response, code) in cases {
            let line = super::backend_error_envelope_line(&response).expect(code);
            let parsed: serde_json::Value = serde_json::from_str(&line).unwrap();
            assert_eq!(parsed["error"]["code"], code, "{line}");
            assert_eq!(parsed["error"]["message"], response.error_message);
        }
    }

    #[test]
    fn error_envelope_includes_extended_error_when_present() {
        use crate::mxc_common::models::ScriptResponse;
        let line = super::backend_error_envelope_line(&ScriptResponse {
            extended_error: "WIN32_ERROR(1920)".to_string(),
            ..ScriptResponse::unavailable("backend unavailable")
        })
        .unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&line).unwrap();
        assert_eq!(parsed["error"]["extended_error"], "WIN32_ERROR(1920)");
    }

    #[test]
    fn policy_errors_keep_details_for_explicit_serialization_not_console_output() {
        use crate::mxc_common::models::ScriptResponse;
        use crate::mxc_common::mxc_error::{ApiFailure, MxcError};
        let error = MxcError::policy_validation("Creation refused.")
            .with_api_failure(
                ApiFailure::new("CreateProcessSecurityEnvironment").with_native_code("0x800704EC"),
            )
            .with_remediation("Prepare a restricted request.")
            .with_details(serde_json::json!({
                "policyFailures": {"resource": "CLI_POLICY_RESOURCE_MARKER"}
            }));
        let response = ScriptResponse::rejected("Creation refused.").with_error(error.clone());
        for line in [
            super::backend_error_envelope_line(&response).unwrap(),
            super::console_error_envelope(error.to_envelope()),
        ] {
            assert!(!line.contains("CLI_POLICY_RESOURCE_MARKER"), "{line}");
            let value: serde_json::Value = serde_json::from_str(&line).unwrap();
            assert!(value["error"].get("details").is_none());
            assert_eq!(value["error"]["code"], "policy_validation");
            assert_eq!(
                value["error"]["operation"],
                "CreateProcessSecurityEnvironment"
            );
            assert_eq!(value["error"]["nativeCode"], "0x800704EC");
            assert_eq!(
                value["error"]["remediation"],
                "Prepare a restricted request."
            );
        }
        assert!(error
            .to_envelope_string()
            .contains("CLI_POLICY_RESOURCE_MARKER"));
        assert!(response
            .into_mxc_error()
            .to_envelope_string()
            .contains("CLI_POLICY_RESOURCE_MARKER"));
    }

    #[test]
    fn policy_resources_do_not_reach_process_stderr() {
        use crate::mxc_common::models::ScriptResponse;
        use crate::mxc_common::mxc_error::MxcError;
        const MODE: &str = "MXC_TEST_CONSOLE_POLICY_ERROR";
        const TEST: &str =
            "core_modules::mxc_common::script_runner::tests::policy_resources_do_not_reach_process_stderr";
        if let Ok(mode) = std::env::var(MODE) {
            let error = MxcError::policy_validation("Creation refused.").with_details(
                serde_json::json!({"policyFailures": {"resource": "CLI_POLICY_RESOURCE_MARKER"}}),
            );
            if mode == "early" {
                super::emit_mxc_error_exit(&error);
            }
            super::emit_backend_error_envelope(
                &ScriptResponse::rejected("Creation refused.").with_error(error),
            );
            return;
        }
        for mode in ["backend", "early"] {
            let mut command = std::process::Command::new(std::env::current_exe().unwrap());
            command
                .args(["--exact", TEST, "--nocapture"])
                .env(MODE, mode);
            #[cfg(target_os = "windows")]
            {
                use std::os::windows::process::CommandExt;
                command.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
            }
            let output = command.output().unwrap();
            assert_eq!(
                output.status.code(),
                Some(if mode == "early" { 1 } else { 0 })
            );
            for bytes in [&output.stdout, &output.stderr] {
                assert!(!String::from_utf8_lossy(bytes).contains("CLI_POLICY_RESOURCE_MARKER"));
            }
            let text = String::from_utf8(output.stderr).unwrap();
            let line = text.lines().find(|line| line.starts_with('{')).unwrap();
            let value: serde_json::Value = serde_json::from_str(line).unwrap();
            assert_eq!(value["error"]["code"], "policy_validation");
            assert_eq!(value["error"]["message"], "Creation refused.");
        }
    }

    #[test]
    fn warning_lines_are_one_parseable_object_each() {
        let lines = super::warning_envelope_lines(&[
            "dacl augmentation fell back".to_string(),
            "quoted \"name\" and \\ backslash".to_string(),
        ]);

        assert_eq!(
            lines[0],
            r#"{"warning":{"message":"dacl augmentation fell back"}}"#
        );
        // A warning is free-form text, so it has to survive JSON escaping.
        let parsed: serde_json::Value = serde_json::from_str(&lines[1]).unwrap();
        assert_eq!(
            parsed["warning"]["message"],
            "quoted \"name\" and \\ backslash"
        );
    }

    #[test]
    fn blank_warnings_do_not_reach_the_stream() {
        assert!(super::warning_envelope_lines(&[String::new(), "   ".to_string()]).is_empty());
    }

    #[test]
    fn dry_run_summary_reports_why_validation_failed() {
        use crate::mxc_common::models::ScriptResponse;
        let summary = super::dry_run_summary(&ScriptResponse::rejected(
            "network.egress allow/deny rules are not supported by the selected backend",
        ));
        assert_eq!(
            summary,
            "Dry run completed. Result: validation failed: \
             network.egress allow/deny rules are not supported by the selected backend"
        );
    }

    #[test]
    fn dry_run_summary_keeps_the_bare_verdicts() {
        use crate::mxc_common::models::ScriptResponse;
        assert_eq!(
            super::dry_run_summary(&ScriptResponse {
                exit_code: 0,
                ..Default::default()
            }),
            "Dry run completed. Result: validation passed"
        );
        // A refusal that carried no message must not grow a dangling colon.
        assert_eq!(
            super::dry_run_summary(&ScriptResponse {
                exit_code: 1,
                error_message: String::new(),
                ..Default::default()
            }),
            "Dry run completed. Result: validation failed"
        );
    }
}