mxc-sdk 1.0.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Control protocol shared between the sandbox daemon and guest agent.
//!
//! All messages are length-prefixed: a 4-byte little-endian `u32` frame length
//! followed by that many bytes of JSON (serde_json).  This keeps the framing
//! trivial while still allowing structured payloads.

use serde::ser::Error as _;
use serde::{Deserialize, Serialize};

const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024; // 16 MB

// ---------------------------------------------------------------------------
// Message types
// ---------------------------------------------------------------------------

/// Envelope sent on the **control** channel.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type")]
pub enum ControlMessage {
    /// Agent → Host: the sandbox is ready to accept EXEC commands.
    Ready,

    /// Host → Agent: execute a script.
    Exec(ExecRequest),

    /// Agent → Host: script finished.
    Exit(ExitNotification),

    /// Agent → Host: new data streams are ready to be connected.
    ///
    /// Sent after the agent has re-opened its TCP listener for the next
    /// set of stdin/stdout/stderr connections following an [`Exit`].
    StreamsReady,

    /// Either direction: keepalive probe.
    Ping,

    /// Either direction: keepalive reply.
    Pong,
}

/// Payload for [`ControlMessage::Exec`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ExecRequest {
    /// Unique identifier correlating the stdin/stdout/stderr connections.
    pub exec_id: String,
    /// Command line to execute (e.g. `python -c "print('hi')"`).
    pub script_code: String,
    /// Working directory inside the sandbox (empty = agent default).
    pub working_directory: String,
    /// Timeout in milliseconds (0 = no timeout).
    pub timeout_ms: u32,
}

/// Payload for [`ControlMessage::Exit`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ExitNotification {
    /// Correlates with the original [`ExecRequest::exec_id`].
    pub exec_id: String,
    /// Process exit code (negative values indicate error/timeout).
    pub exit_code: i32,
    /// Optional error message (e.g. if the process could not be spawned).
    pub error_message: String,
}

// ---------------------------------------------------------------------------
// Framing helpers
// ---------------------------------------------------------------------------

/// Serialize a [`ControlMessage`] into a length-prefixed frame.
///
/// Layout: `[len: u32 LE][json: len bytes]`
pub fn encode_message(msg: &ControlMessage) -> Result<Vec<u8>, serde_json::Error> {
    let json = serde_json::to_vec(msg)?;
    if json.len() > u32::MAX as usize {
        return Err(serde_json::Error::custom(
            "message too large for protocol framing",
        ));
    }
    let len = json.len() as u32;
    let mut frame = Vec::with_capacity(4 + json.len());
    frame.extend_from_slice(&len.to_le_bytes());
    frame.extend_from_slice(&json);
    Ok(frame)
}

/// Result of attempting to decode a frame from a byte buffer.
#[derive(Debug, PartialEq, Eq)]
pub enum DecodeResult {
    /// A complete message was decoded; `consumed` bytes should be drained
    /// from the front of the buffer.
    Message {
        message: ControlMessage,
        consumed: usize,
    },
    /// The buffer does not yet contain a full frame.
    Incomplete,
}

/// Try to decode one [`ControlMessage`] from the front of `buf`.
///
/// Returns [`DecodeResult::Incomplete`] if fewer than `4 + len` bytes are
/// available.  On success the caller should drain `consumed` bytes from
/// the buffer before calling again.
pub fn decode_message(buf: &[u8]) -> Result<DecodeResult, serde_json::Error> {
    if buf.len() < 4 {
        return Ok(DecodeResult::Incomplete);
    }
    let len = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
    if len > MAX_FRAME_SIZE {
        return Err(serde_json::Error::custom("frame too large"));
    }
    let total = 4 + len;
    if buf.len() < total {
        return Ok(DecodeResult::Incomplete);
    }
    let message: ControlMessage = serde_json::from_slice(&buf[4..total])?;
    Ok(DecodeResult::Message {
        message,
        consumed: total,
    })
}

// ---------------------------------------------------------------------------
// Connection preamble (control-channel handshake)
// ---------------------------------------------------------------------------

/// Magic bytes the guest agent writes first on the control channel.
///
/// Lets the host fail fast (rather than hanging or misframing) if it connects
/// to something that is not a matching guest agent.
pub const PROTOCOL_MAGIC: [u8; 4] = *b"WSBP";

/// Compatibility version for the host/guest control-channel wire protocol.
///
/// The host injects the guest binary, so in normal operation both sides are
/// always the same build; the version guards against a stale guest left over
/// from an incompatible image and makes mismatches diagnosable. Bump this only
/// for incompatible changes to framing, preamble semantics, or required control
/// messages. A mismatch rejects the connection before any framed messages run.
pub const PROTOCOL_VERSION: u32 = 1;

/// Length in bytes of the fixed control-channel preamble (4 magic + 4 version).
pub const PREAMBLE_LEN: usize = 8;

/// Reason an 8-byte control preamble was rejected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PreambleError {
    /// The first four bytes did not match [`PROTOCOL_MAGIC`].
    BadMagic([u8; 4]),
    /// The magic matched but the peer's version differed from [`PROTOCOL_VERSION`].
    VersionMismatch { expected: u32, actual: u32 },
}

impl std::fmt::Display for PreambleError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PreambleError::BadMagic(got) => write!(
                f,
                "bad protocol magic: expected {:?}, got {:?}",
                PROTOCOL_MAGIC, got
            ),
            PreambleError::VersionMismatch { expected, actual } => write!(
                f,
                "protocol version mismatch: expected {}, got {}",
                expected, actual
            ),
        }
    }
}

impl std::error::Error for PreambleError {}

/// Encode the fixed control-channel preamble the guest sends before `Ready`.
pub fn encode_preamble() -> [u8; PREAMBLE_LEN] {
    let mut bytes = [0u8; PREAMBLE_LEN];
    bytes[..4].copy_from_slice(&PROTOCOL_MAGIC);
    bytes[4..].copy_from_slice(&PROTOCOL_VERSION.to_le_bytes());
    bytes
}

/// Validate an 8-byte preamble, returning the peer's protocol version.
pub fn validate_preamble(bytes: &[u8; PREAMBLE_LEN]) -> Result<u32, PreambleError> {
    let mut magic = [0u8; 4];
    magic.copy_from_slice(&bytes[..4]);
    if magic != PROTOCOL_MAGIC {
        return Err(PreambleError::BadMagic(magic));
    }
    let actual = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
    if actual != PROTOCOL_VERSION {
        return Err(PreambleError::VersionMismatch {
            expected: PROTOCOL_VERSION,
            actual,
        });
    }
    Ok(actual)
}

// ---------------------------------------------------------------------------
// Daemon IPC result (line-based protocol between wxc-exec and daemon)
// ---------------------------------------------------------------------------

/// Placeholder for empty base64 fields in the RESULT protocol line.
/// Avoids ambiguous whitespace splitting when stdout or stderr is empty.
const EMPTY_BASE64_PLACEHOLDER: &str = "-";

/// Result sent from the daemon to wxc-exec over the IPC channel.
///
/// Wire format: `RESULT <exit-code> <stdout-b64> <stderr-b64> [error-message]\n`
/// Empty stdout/stderr fields are represented as `"-"`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DaemonResult {
    pub exit_code: i32,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
    pub error_message: String,
}

impl DaemonResult {
    /// Format as a protocol line for sending over IPC.
    pub fn to_line(&self) -> String {
        let stdout_b64 = if self.stdout.is_empty() {
            EMPTY_BASE64_PLACEHOLDER.to_string()
        } else {
            crate::mxc_common::string_util::base64_encode(&self.stdout)
        };
        let stderr_b64 = if self.stderr.is_empty() {
            EMPTY_BASE64_PLACEHOLDER.to_string()
        } else {
            crate::mxc_common::string_util::base64_encode(&self.stderr)
        };
        format!(
            "RESULT {} {} {} {}\n",
            self.exit_code, stdout_b64, stderr_b64, self.error_message
        )
    }

    /// Parse a protocol line received from the daemon.
    ///
    /// Expects format: `RESULT <exit-code> <stdout-b64> <stderr-b64> [error-message]`
    /// (without the trailing newline — caller should trim first).
    pub fn parse(line: &str) -> Result<Self, String> {
        let rest = line
            .strip_prefix("RESULT ")
            .ok_or_else(|| format!("expected RESULT prefix, got: {}", line))?;

        let parts: Vec<&str> = rest.splitn(4, ' ').collect();
        if parts.len() < 3 {
            return Err(format!(
                "malformed RESULT: expected at least 3 fields, got {}",
                parts.len()
            ));
        }

        let exit_code = parts[0].parse::<i32>().unwrap_or(-1);
        let stdout = decode_base64_field(parts[1]);
        let stderr = decode_base64_field(parts[2]);
        let error_message = if parts.len() == 4 {
            parts[3].to_string()
        } else {
            String::new()
        };

        Ok(Self {
            exit_code,
            stdout,
            stderr,
            error_message,
        })
    }
}

/// Decode a base64 field, returning empty Vec for the placeholder.
fn decode_base64_field(field: &str) -> Vec<u8> {
    if field == EMPTY_BASE64_PLACEHOLDER {
        return Vec::new();
    }
    crate::mxc_common::string_util::base64_decode(field).unwrap_or_default()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn roundtrip_ready() {
        let msg = ControlMessage::Ready;
        let frame = encode_message(&msg).unwrap();
        let result = decode_message(&frame).unwrap();
        assert_eq!(
            result,
            DecodeResult::Message {
                message: msg,
                consumed: frame.len(),
            }
        );
    }

    #[test]
    fn preamble_roundtrip() {
        let bytes = encode_preamble();
        assert_eq!(bytes.len(), PREAMBLE_LEN);
        assert_eq!(&bytes[..4], &PROTOCOL_MAGIC);
        assert_eq!(validate_preamble(&bytes).unwrap(), PROTOCOL_VERSION);
    }

    #[test]
    fn preamble_rejects_bad_magic() {
        let mut bytes = encode_preamble();
        bytes[0] ^= 0xFF;
        match validate_preamble(&bytes) {
            Err(PreambleError::BadMagic(_)) => {}
            other => panic!("expected BadMagic, got {:?}", other),
        }
    }

    #[test]
    fn preamble_rejects_version_mismatch() {
        let mut bytes = encode_preamble();
        let bad = PROTOCOL_VERSION.wrapping_add(1);
        bytes[4..].copy_from_slice(&bad.to_le_bytes());
        match validate_preamble(&bytes) {
            Err(PreambleError::VersionMismatch { expected, actual }) => {
                assert_eq!(expected, PROTOCOL_VERSION);
                assert_eq!(actual, bad);
            }
            other => panic!("expected VersionMismatch, got {:?}", other),
        }
    }

    #[test]
    fn roundtrip_exec() {
        let msg = ControlMessage::Exec(ExecRequest {
            exec_id: "abc-123".to_string(),
            script_code: "python -c \"print('hello')\"".to_string(),
            working_directory: "C:\\temp".to_string(),
            timeout_ms: 30000,
        });
        let frame = encode_message(&msg).unwrap();
        let result = decode_message(&frame).unwrap();
        assert_eq!(
            result,
            DecodeResult::Message {
                message: msg,
                consumed: frame.len(),
            }
        );
    }

    #[test]
    fn roundtrip_exit() {
        let msg = ControlMessage::Exit(ExitNotification {
            exec_id: "abc-123".to_string(),
            exit_code: 42,
            error_message: String::new(),
        });
        let frame = encode_message(&msg).unwrap();
        let result = decode_message(&frame).unwrap();
        assert_eq!(
            result,
            DecodeResult::Message {
                message: msg,
                consumed: frame.len(),
            }
        );
    }

    #[test]
    fn roundtrip_exit_with_error() {
        let msg = ControlMessage::Exit(ExitNotification {
            exec_id: "err-1".to_string(),
            exit_code: -1,
            error_message: "spawn failed: file not found".to_string(),
        });
        let frame = encode_message(&msg).unwrap();
        let result = decode_message(&frame).unwrap();
        assert_eq!(
            result,
            DecodeResult::Message {
                message: msg,
                consumed: frame.len(),
            }
        );
    }

    #[test]
    fn roundtrip_streams_ready() {
        let msg = ControlMessage::StreamsReady;
        let frame = encode_message(&msg).unwrap();
        let result = decode_message(&frame).unwrap();
        assert_eq!(
            result,
            DecodeResult::Message {
                message: msg,
                consumed: frame.len(),
            }
        );
    }

    #[test]
    fn roundtrip_ping_pong() {
        for msg in [ControlMessage::Ping, ControlMessage::Pong] {
            let frame = encode_message(&msg).unwrap();
            let result = decode_message(&frame).unwrap();
            assert_eq!(
                result,
                DecodeResult::Message {
                    message: msg,
                    consumed: frame.len(),
                }
            );
        }
    }

    #[test]
    fn decode_incomplete_header() {
        assert_eq!(decode_message(&[0u8; 3]).unwrap(), DecodeResult::Incomplete);
    }

    #[test]
    fn decode_incomplete_body() {
        // Header says 100 bytes, but we only have 10.
        let mut buf = Vec::new();
        buf.extend_from_slice(&100u32.to_le_bytes());
        buf.extend_from_slice(&[0u8; 10]);
        assert_eq!(decode_message(&buf).unwrap(), DecodeResult::Incomplete);
    }

    #[test]
    fn decode_empty_buffer() {
        assert_eq!(decode_message(&[]).unwrap(), DecodeResult::Incomplete);
    }

    #[test]
    fn multiple_messages_in_buffer() {
        let msg1 = ControlMessage::Ping;
        let msg2 = ControlMessage::Pong;
        let frame1 = encode_message(&msg1).unwrap();
        let frame2 = encode_message(&msg2).unwrap();

        let mut buf = Vec::new();
        buf.extend_from_slice(&frame1);
        buf.extend_from_slice(&frame2);

        // Decode first message.
        let result1 = decode_message(&buf).unwrap();
        let consumed1 = match &result1 {
            DecodeResult::Message { consumed, .. } => *consumed,
            _ => panic!("expected message"),
        };
        assert_eq!(
            result1,
            DecodeResult::Message {
                message: msg1,
                consumed: consumed1,
            }
        );

        // Decode second message from remaining buffer.
        let result2 = decode_message(&buf[consumed1..]).unwrap();
        assert_eq!(
            result2,
            DecodeResult::Message {
                message: msg2,
                consumed: buf.len() - consumed1,
            }
        );
    }

    #[test]
    fn frame_length_is_correct() {
        let msg = ControlMessage::Exec(ExecRequest {
            exec_id: "x".to_string(),
            script_code: "echo hi".to_string(),
            working_directory: String::new(),
            timeout_ms: 0,
        });
        let frame = encode_message(&msg).unwrap();

        // First 4 bytes = LE u32 length of the JSON payload.
        let declared_len = u32::from_le_bytes([frame[0], frame[1], frame[2], frame[3]]) as usize;
        assert_eq!(declared_len, frame.len() - 4);
    }

    #[test]
    fn daemon_result_roundtrip_with_output() {
        let result = DaemonResult {
            exit_code: 0,
            stdout: b"hello world".to_vec(),
            stderr: b"some warning".to_vec(),
            error_message: String::new(),
        };
        let line = result.to_line();
        let parsed = DaemonResult::parse(line.trim()).unwrap();
        assert_eq!(parsed, result);
    }

    #[test]
    fn daemon_result_roundtrip_empty_output() {
        let result = DaemonResult {
            exit_code: 42,
            stdout: Vec::new(),
            stderr: Vec::new(),
            error_message: "something failed".to_string(),
        };
        let line = result.to_line();
        let parsed = DaemonResult::parse(line.trim()).unwrap();
        assert_eq!(parsed, result);
    }

    #[test]
    fn daemon_result_parse_rejects_malformed() {
        assert!(DaemonResult::parse("RESULT 0").is_err());
        assert!(DaemonResult::parse("ERROR something").is_err());
        assert!(DaemonResult::parse("garbage").is_err());
    }
}