Skip to main content

podbox_protocol/
lib.rs

1use std::io::{self, Read, Write};
2
3use serde::{Deserialize, Serialize};
4
5/// Increment on breaking wire-format changes. Backwards-compatible
6/// additions (new optional message types) do NOT increment this.
7pub const PROTOCOL_VERSION: u32 = 1;
8
9/// Guest protocol capability identifiers.
10///
11/// Single source of truth — always use these constants in match arms,
12/// construction, and capability negotiation rather than inline strings.
13pub const CAP_NOTIFY: &str = "notify";
14pub const CAP_XDG_OPEN: &str = "xdg_open";
15pub const CAP_CLIPBOARD: &str = "clipboard";
16pub const CAP_HOST_EXEC: &str = "host_exec";
17/// Streaming host-exec output (`HostExecOutput` byte chunks instead of one
18/// buffered `HostExecStdout`/`HostExecStderr` frame). Requested alongside
19/// `host_exec`; old hosts leave it in the rejected list and the guest falls
20/// back to buffered frames.
21pub const CAP_HOST_EXEC_STREAM: &str = "host_exec_stream";
22/// Host-exec with the child's stdio supplied by the guest: a
23/// `HostExecV2` frame with three descriptors attached via `SCM_RIGHTS`,
24/// plus `HostExecSignal` relay while the child runs. Old hosts leave it
25/// in the rejected list and the guest falls back to plain `HostExec`.
26pub const CAP_HOST_EXEC_FDS: &str = "host_exec_fds";
27
28/// All known capabilities in negotiation order.
29pub const ALL_CAPABILITIES: &[&str] = &[
30    CAP_NOTIFY,
31    CAP_XDG_OPEN,
32    CAP_CLIPBOARD,
33    CAP_HOST_EXEC,
34    CAP_HOST_EXEC_STREAM,
35    CAP_HOST_EXEC_FDS,
36];
37
38/// Interceptor binaries and the capability each needs: `(binary, capability)`.
39///
40/// Single source of truth for shim installation and the core-interceptor
41/// guard in the guest daemon. (`podmgr-*` names are legacy aliases handled
42/// separately at the use sites.)
43pub const INTERCEPTORS: &[(&str, &str)] = &[
44    ("notify-send", CAP_NOTIFY),
45    ("xdg-open", CAP_XDG_OPEN),
46    ("podbox-clipboard", CAP_CLIPBOARD),
47    ("host-exec", CAP_HOST_EXEC),
48];
49
50/// Messages sent from guest to host.
51#[derive(Debug, Serialize, Deserialize)]
52#[serde(tag = "type", rename_all = "snake_case")]
53pub enum GuestMessage {
54    Hello {
55        protocol_version: u32,
56        guest_version: String,
57        container: String,
58        capabilities: Vec<String>,
59    },
60    Notify {
61        summary: String,
62        body: String,
63        urgency: String,
64        #[serde(default)]
65        actions: Vec<NotifyAction>,
66        #[serde(default)]
67        app_name: String,
68    },
69    XdgOpen {
70        uri: String,
71    },
72    ClipboardSet {
73        text: String,
74    },
75    ClipboardGet,
76    HostExec {
77        cmd: String,
78        args: Vec<String>,
79    },
80    /// Host-exec with the child's stdio taken from descriptors the guest
81    /// attaches to this frame (capability `host_exec_fds`).
82    ///
83    /// Exactly three descriptors ride via `SCM_RIGHTS` on the same message,
84    /// in stdin, stdout, stderr order. The host uses them directly as the
85    /// child's stdio, so binary data and large outputs never pass through
86    /// the protocol. A guest whose request is refused by this capability
87    /// keeps using [`GuestMessage::HostExec`] instead.
88    ///
89    /// The optional fields are serde-defaulted so the wire format here is
90    /// frozen now, while the host phases in behaviour behind them:
91    /// `cmd`/`args`/`env` are consumed, `cwd` is carried but not yet
92    /// processed, and `tty` must be false (the host refuses `true` with a
93    /// typed error until the TTY path exists).
94    HostExecV2 {
95        cmd: String,
96        args: Vec<String>,
97        /// Key/value pairs the guest asks the host to export to the child.
98        /// The host applies only allowlisted keys (TERM, LANG, COLORTERM).
99        #[serde(default)]
100        env: Vec<(String, String)>,
101        #[serde(default)]
102        cwd: Option<String>,
103        #[serde(default)]
104        tty: bool,
105    },
106    /// Relay a signal (SIGINT, SIGTERM, SIGHUP or SIGWINCH) from the guest
107    /// shim to a running host-exec child. Only sent on a `host_exec_fds`
108    /// session: the host forwards it to the child's process group. The
109    /// child's death is reported through the regular `HostExecDone` frame.
110    HostExecSignal {
111        sig: i32,
112    },
113    /// Sent by the host CLI to register a new terminal session.
114    /// The `pidfd` follows via `SCM_RIGHTS` on the same connection.
115    RegisterSession,
116    /// Sent by the guest daemon when user processes are still running.
117    Busy,
118    /// Sent by the guest daemon when no user processes remain.
119    IdleTimeout,
120    /// Guest reply to host `GetInfo`.
121    Info {
122        guest_version: String,
123        protocol_version: u32,
124    },
125}
126
127#[derive(Debug, Serialize, Deserialize, Clone)]
128pub struct NotifyAction {
129    pub key: String,
130    pub label: String,
131}
132
133/// Which pipe of a streaming host-exec child a chunk came from.
134#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
135#[serde(rename_all = "snake_case")]
136pub enum ExecStream {
137    Stdout,
138    Stderr,
139}
140
141/// Messages sent from host to guest.
142#[derive(Debug, Serialize, Deserialize)]
143#[serde(tag = "type", rename_all = "snake_case")]
144pub enum HostMessage {
145    HelloAck {
146        accepted: Vec<String>,
147        rejected: Vec<String>,
148        #[serde(default)]
149        idle_timeout_secs: u64,
150        /// List of command names for which the guest daemon should create PATH shims.
151        #[serde(default)]
152        host_exec_shims: Vec<String>,
153    },
154    ClipboardData {
155        text: String,
156    },
157    HostExecStdout {
158        data: String,
159    },
160    HostExecStderr {
161        data: String,
162    },
163    /// One chunk of a streaming command's output, sent as the child
164    /// produces it. `data` is raw bytes (up to 16 KiB per chunk) so binary
165    /// output survives intact. Only sent when the guest negotiated
166    /// `host_exec_stream`; older guests keep receiving the buffered
167    /// `HostExecStdout`/`HostExecStderr` frames.
168    HostExecOutput {
169        stream: ExecStream,
170        data: Vec<u8>,
171    },
172    HostExecDone {
173        exit_code: i32,
174        /// Signal that killed the child, if any. `exit_code` already
175        /// follows the shell convention (`128 + signal`); this names the
176        /// cause. Old guests ignore the unknown field.
177        #[serde(default)]
178        signal: Option<i32>,
179    },
180    NotifyActionResult {
181        notification_id: u32,
182        action_key: String,
183    },
184    Ping,
185    Shutdown,
186    /// Sent by the host when all CLI sessions have ended; guest responds
187    /// with `IdleTimeout` or `Busy` after scanning `/proc`.
188    CheckIdle,
189    /// Sent by the host when a guest message is rejected (missing `Hello`
190    /// negotiation, or a capability that was not accepted).
191    Error {
192        reason: String,
193        /// Optional machine-readable code (e.g. `busy`) so clients can
194        /// distinguish rejection kinds without parsing `reason`.
195        #[serde(default)]
196        code: Option<String>,
197    },
198    /// Host → guest version/info query (doctor).
199    GetInfo,
200}
201
202/// Write a length-prefixed JSON frame.
203pub fn write_frame<W: Write>(w: &mut W, msg: &impl Serialize) -> io::Result<()> {
204    let json = serde_json::to_vec(msg)?;
205    let len = u32::try_from(json.len())
206        .expect("frame payload exceeds 4 GiB")
207        .to_be_bytes();
208    w.write_all(&len)?;
209    w.write_all(&json)?;
210    w.flush()?;
211    Ok(())
212}
213
214/// Maximum frame size: 16 MiB.
215const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
216
217/// Largest clipboard payload either side will send or accept (8 MiB).
218/// Beyond this the host answers with an `Error` frame and the guest
219/// refuses locally with a clear message, instead of failing the frame.
220/// A fixed constant (not a config key): raising it needs the matching
221/// host/guest rollout, and the frame cap bounds it anyway.
222pub const MAX_CLIPBOARD_BYTES: usize = 8 * 1024 * 1024;
223
224/// Read a length-prefixed JSON frame.
225pub fn read_frame<R: Read>(r: &mut R) -> io::Result<Option<Vec<u8>>> {
226    let mut len_buf = [0u8; 4];
227    match r.read_exact(&mut len_buf) {
228        Ok(()) => {}
229        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
230        Err(e) => return Err(e),
231    }
232    let len = u32::from_be_bytes(len_buf) as usize;
233    if len > MAX_FRAME_SIZE {
234        return Err(io::Error::new(
235            io::ErrorKind::InvalidData,
236            format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
237        ));
238    }
239    let mut buf = vec![0u8; len];
240    r.read_exact(&mut buf)?;
241    Ok(Some(buf))
242}
243
244/// Incremental frame reader that survives read timeouts.
245///
246/// [`read_frame`] uses `read_exact`, which discards bytes it already read when
247/// a timeout fires mid-frame. The stream is then misaligned: the next read
248/// parses payload bytes as a length prefix. `FrameReader` keeps the partial
249/// frame, so a timeout returns `WouldBlock`/`TimedOut` with nothing lost and
250/// the caller can retry, or give up once [`FrameReader::stalled_for`] is long.
251#[derive(Debug, Default)]
252pub struct FrameReader {
253    prefix: [u8; 4],
254    prefix_filled: usize,
255    body: Vec<u8>,
256    body_filled: usize,
257    body_len: Option<usize>,
258    /// When the first byte of the frame in progress arrived.
259    started: Option<std::time::Instant>,
260}
261
262/// What a [`FrameReader::read`] call produced.
263#[derive(Debug, PartialEq, Eq)]
264pub enum FrameRead {
265    /// A complete frame payload.
266    Frame(Vec<u8>),
267    /// The peer closed the stream at a frame boundary.
268    Eof,
269}
270
271impl FrameReader {
272    pub fn new() -> Self {
273        Self::default()
274    }
275
276    /// True when part of a frame has been read and the rest is still due.
277    pub fn in_progress(&self) -> bool {
278        self.started.is_some()
279    }
280
281    /// Time since the first byte of the frame in progress, if one is in progress.
282    pub fn stalled_for(&self) -> Option<std::time::Duration> {
283        self.started.map(|t| t.elapsed())
284    }
285
286    /// Read until one frame is complete. A timeout returns `Err` and keeps the
287    /// partial frame, so a later call resumes exactly where this one stopped.
288    pub fn read<R: Read>(&mut self, r: &mut R) -> io::Result<FrameRead> {
289        while self.prefix_filled < 4 {
290            let n = r.read(&mut self.prefix[self.prefix_filled..])?;
291            if n == 0 {
292                return if self.prefix_filled == 0 {
293                    Ok(FrameRead::Eof)
294                } else {
295                    Err(io::Error::from(io::ErrorKind::UnexpectedEof))
296                };
297            }
298            self.started.get_or_insert_with(std::time::Instant::now);
299            self.prefix_filled += n;
300        }
301        let len = match self.body_len {
302            Some(len) => len,
303            None => {
304                let len = u32::from_be_bytes(self.prefix) as usize;
305                if len > MAX_FRAME_SIZE {
306                    return Err(io::Error::new(
307                        io::ErrorKind::InvalidData,
308                        format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
309                    ));
310                }
311                self.body = vec![0u8; len];
312                self.body_len = Some(len);
313                len
314            }
315        };
316        while self.body_filled < len {
317            let n = r.read(&mut self.body[self.body_filled..])?;
318            if n == 0 {
319                return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
320            }
321            self.body_filled += n;
322        }
323        let frame = std::mem::take(&mut self.body);
324        *self = Self::default();
325        Ok(FrameRead::Frame(frame))
326    }
327}
328
329/// Unix-only helpers shared by the host CLI and the guest daemon.
330#[cfg(unix)]
331pub mod sysutil;
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    #[test]
338    fn hello_serializes_with_type_tag() {
339        let msg = GuestMessage::Hello {
340            protocol_version: 1,
341            guest_version: "0.2.0".into(),
342            container: "myenv".into(),
343            capabilities: vec!["notify".into()],
344        };
345        let json = serde_json::to_string(&msg).unwrap();
346        assert!(json.contains("\"type\":\"hello\""));
347    }
348
349    #[test]
350    fn frame_length_prefix_matches_payload() {
351        let msg = GuestMessage::ClipboardGet;
352        let mut buf = Vec::new();
353        write_frame(&mut buf, &msg).unwrap();
354        let len = u32::from_be_bytes(buf[..4].try_into().unwrap()) as usize;
355        assert_eq!(len, buf[4..].len());
356    }
357
358    #[test]
359    fn interceptors_cover_known_binaries_and_capabilities() {
360        use std::collections::HashSet;
361        let binaries: HashSet<&str> = INTERCEPTORS.iter().map(|(bin, _)| *bin).collect();
362        assert_eq!(binaries.len(), INTERCEPTORS.len(), "duplicate binary");
363        for (_, cap) in INTERCEPTORS {
364            assert!(ALL_CAPABILITIES.contains(cap), "unknown capability {cap}");
365        }
366    }
367
368    #[test]
369    fn roundtrip_notify_message() {
370        let msg = GuestMessage::Notify {
371            summary: "hello".into(),
372            body: "world".into(),
373            urgency: "normal".into(),
374            actions: vec![],
375            app_name: String::new(),
376        };
377        let mut buf = Vec::new();
378        write_frame(&mut buf, &msg).unwrap();
379
380        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
381        let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
382        match decoded {
383            GuestMessage::Notify {
384                summary,
385                body,
386                urgency,
387                actions,
388                app_name: _,
389            } => {
390                assert_eq!(summary, "hello");
391                assert_eq!(body, "world");
392                assert_eq!(urgency, "normal");
393                assert!(actions.is_empty());
394            }
395            _ => panic!("wrong message type"),
396        }
397    }
398
399    #[test]
400    fn roundtrip_clipboard_set() {
401        let msg = GuestMessage::ClipboardSet {
402            text: "clipboard content".into(),
403        };
404        let mut buf = Vec::new();
405        write_frame(&mut buf, &msg).unwrap();
406
407        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
408        let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
409        match decoded {
410            GuestMessage::ClipboardSet { text } => {
411                assert_eq!(text, "clipboard content");
412            }
413            _ => panic!("wrong message type"),
414        }
415    }
416
417    #[test]
418    fn hello_ack_with_shims_round_trips() {
419        let msg = HostMessage::HelloAck {
420            accepted: vec!["host_exec".into()],
421            rejected: vec![],
422            idle_timeout_secs: 10,
423            host_exec_shims: vec!["git".into(), "code".into()],
424        };
425        let mut buf = Vec::new();
426        write_frame(&mut buf, &msg).unwrap();
427        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
428        let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
429        match decoded {
430            HostMessage::HelloAck {
431                accepted,
432                host_exec_shims,
433                ..
434            } => {
435                assert_eq!(accepted, vec!["host_exec"]);
436                assert_eq!(host_exec_shims, vec!["git", "code"]);
437            }
438            _ => panic!("wrong message type"),
439        }
440    }
441
442    #[test]
443    fn hello_ack_backward_compat_missing_shims() {
444        let json = r#"{"type":"hello_ack","accepted":[],"rejected":[],"idle_timeout_secs":0}"#;
445        let msg: HostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
446        match msg {
447            HostMessage::HelloAck {
448                host_exec_shims, ..
449            } => assert!(host_exec_shims.is_empty()),
450            _ => panic!("wrong message type"),
451        }
452    }
453
454    /// One scripted step of a fake socket: bytes, or a read timeout.
455    enum Step {
456        Bytes(Vec<u8>),
457        Timeout,
458    }
459
460    struct Scripted(std::collections::VecDeque<Step>);
461
462    impl Read for Scripted {
463        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
464            match self.0.pop_front() {
465                None => Ok(0),
466                Some(Step::Timeout) => Err(io::Error::from(io::ErrorKind::WouldBlock)),
467                Some(Step::Bytes(mut b)) => {
468                    let n = b.len().min(buf.len());
469                    buf[..n].copy_from_slice(&b[..n]);
470                    if n < b.len() {
471                        b.drain(..n);
472                        self.0.push_front(Step::Bytes(b));
473                    }
474                    Ok(n)
475                }
476            }
477        }
478    }
479
480    fn encoded(msg: &str) -> Vec<u8> {
481        let mut buf = Vec::new();
482        write_frame(&mut buf, &msg).unwrap();
483        buf
484    }
485
486    /// A timeout after the first two length bytes must not lose them: the
487    /// frame still comes out whole, with no misparse of the payload.
488    #[test]
489    fn frame_survives_a_timeout_in_the_length_prefix() {
490        let bytes = encoded("hello there");
491        let mut r = Scripted(
492            [
493                Step::Bytes(bytes[..2].to_vec()),
494                Step::Timeout,
495                Step::Bytes(bytes[2..].to_vec()),
496            ]
497            .into(),
498        );
499        let mut fr = FrameReader::new();
500        assert!(fr.read(&mut r).is_err());
501        assert!(fr.in_progress());
502        let got = fr.read(&mut r).unwrap();
503        assert_eq!(
504            got,
505            FrameRead::Frame(serde_json::to_vec("hello there").unwrap())
506        );
507        assert!(!fr.in_progress());
508    }
509
510    #[test]
511    fn frame_survives_a_timeout_in_the_payload() {
512        let bytes = encoded("a longer payload to split");
513        let cut = 4 + 7;
514        let mut r = Scripted(
515            [
516                Step::Bytes(bytes[..cut].to_vec()),
517                Step::Timeout,
518                Step::Bytes(bytes[cut..].to_vec()),
519            ]
520            .into(),
521        );
522        let mut fr = FrameReader::new();
523        assert!(fr.read(&mut r).is_err());
524        assert_eq!(
525            fr.read(&mut r).unwrap(),
526            FrameRead::Frame(serde_json::to_vec("a longer payload to split").unwrap())
527        );
528    }
529
530    #[test]
531    fn clean_eof_between_frames_is_eof_not_an_error() {
532        let mut r = Scripted(std::collections::VecDeque::new());
533        assert_eq!(FrameReader::new().read(&mut r).unwrap(), FrameRead::Eof);
534    }
535
536    #[test]
537    fn eof_inside_a_frame_is_an_error() {
538        let bytes = encoded("cut short");
539        let mut r = Scripted([Step::Bytes(bytes[..6].to_vec())].into());
540        let err = FrameReader::new().read(&mut r).unwrap_err();
541        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
542    }
543
544    #[test]
545    fn host_exec_output_chunk_round_trips_raw_bytes() {
546        // Invalid UTF-8 must survive the frame exactly: chunks carry bytes,
547        // not lossy strings.
548        let msg = HostMessage::HostExecOutput {
549            stream: ExecStream::Stdout,
550            data: vec![0xff, 0xfe, b'A'],
551        };
552        let mut buf = Vec::new();
553        write_frame(&mut buf, &msg).unwrap();
554        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
555        let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
556        match decoded {
557            HostMessage::HostExecOutput { stream, data } => {
558                assert_eq!(stream, ExecStream::Stdout);
559                assert_eq!(data, vec![0xff, 0xfe, b'A']);
560            }
561            _ => panic!("wrong message type"),
562        }
563    }
564
565    #[test]
566    fn host_exec_v2_optional_fields_are_serde_defaulted() {
567        // A minimal V2 frame (old guest shims that only know cmd/args,
568        // mostly future guests) must decode with every new field defaulted:
569        // the wire format is frozen without bumping PROTOCOL_VERSION.
570        let json = br#"{"type":"host_exec_v2","cmd":"cat","args":["-s"]}"#;
571        let msg: GuestMessage = serde_json::from_slice(json).unwrap();
572        match msg {
573            GuestMessage::HostExecV2 {
574                cmd,
575                args,
576                env,
577                cwd,
578                tty,
579            } => {
580                assert_eq!(cmd, "cat");
581                assert_eq!(args, vec!["-s"]);
582                assert!(env.is_empty());
583                assert!(cwd.is_none());
584                assert!(!tty);
585            }
586            other => panic!("expected HostExecV2, got {other:?}"),
587        }
588    }
589
590    #[test]
591    fn host_exec_v2_round_trips_the_full_field_set() {
592        let msg = GuestMessage::HostExecV2 {
593            cmd: "git".into(),
594            args: vec!["log".into()],
595            env: vec![("TERM".into(), "xterm-256color".into())],
596            cwd: Some("/home/user/project".into()),
597            tty: true,
598        };
599        let mut buf = Vec::new();
600        write_frame(&mut buf, &msg).unwrap();
601        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
602        let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
603        match decoded {
604            GuestMessage::HostExecV2 {
605                cmd,
606                args,
607                env,
608                cwd,
609                tty,
610            } => {
611                assert_eq!(cmd, "git");
612                assert_eq!(args, vec!["log"]);
613                assert_eq!(
614                    env,
615                    vec![("TERM".to_string(), "xterm-256color".to_string())]
616                );
617                assert_eq!(cwd.as_deref(), Some("/home/user/project"));
618                assert!(tty);
619            }
620            other => panic!("expected HostExecV2, got {other:?}"),
621        }
622    }
623
624    #[test]
625    fn host_exec_signal_round_trips() {
626        let msg = GuestMessage::HostExecSignal { sig: 2 };
627        let mut buf = Vec::new();
628        write_frame(&mut buf, &msg).unwrap();
629        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
630        let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
631        match decoded {
632            GuestMessage::HostExecSignal { sig } => assert_eq!(sig, 2),
633            other => panic!("expected HostExecSignal, got {other:?}"),
634        }
635    }
636
637    /// Wire compatibility in the other direction: a host built before
638    /// `host_exec_fds` can still parse a `Hello` that requests it — the
639    /// unknown capability lands in `capabilities` and negotiation rejects
640    /// it, which is how old hosts degrade the guest to plain `HostExec`.
641    #[test]
642    fn hello_with_an_unknown_capability_parses_on_the_old_schema() {
643        // Serde deserializes every declared field, so the enum's own test
644        // reads are the negotiate path, not these bindings.
645        #[allow(dead_code)]
646        #[derive(Deserialize)]
647        #[serde(tag = "type", rename_all = "snake_case")]
648        enum OldGuestMessage {
649            Hello {
650                protocol_version: u32,
651                guest_version: String,
652                container: String,
653                capabilities: Vec<String>,
654            },
655        }
656
657        let json = r#"{"type":"hello","protocol_version":1,"guest_version":"0.2.0",
658            "container":"dev","capabilities":["host_exec","host_exec_fds"]}"#;
659        let msg: OldGuestMessage = serde_json::from_slice(json.as_bytes()).unwrap();
660        let OldGuestMessage::Hello { capabilities, .. } = msg;
661        assert_eq!(capabilities, vec!["host_exec", "host_exec_fds"]);
662    }
663
664    #[test]
665    fn host_exec_done_carries_an_optional_signal() {
666        let msg = HostMessage::HostExecDone {
667            exit_code: 143,
668            signal: Some(15),
669        };
670        let mut buf = Vec::new();
671        write_frame(&mut buf, &msg).unwrap();
672        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
673        let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
674        match decoded {
675            HostMessage::HostExecDone { exit_code, signal } => {
676                assert_eq!(exit_code, 143);
677                assert_eq!(signal, Some(15));
678            }
679            _ => panic!("wrong message type"),
680        }
681    }
682
683    /// Wire compatibility: a guest built before `signal` existed must
684    /// still parse the new `HostExecDone`. Serde ignores the unknown
685    /// field, so old guests keep working with no version bump.
686    #[test]
687    fn host_exec_done_with_signal_parses_under_the_old_schema() {
688        #[derive(Debug, Deserialize, PartialEq, Eq)]
689        #[serde(tag = "type", rename_all = "snake_case")]
690        enum OldHostMessage {
691            HostExecDone { exit_code: i32 },
692        }
693
694        let json = r#"{"type":"host_exec_done","exit_code":143,"signal":15}"#;
695        let msg: OldHostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
696        assert_eq!(msg, OldHostMessage::HostExecDone { exit_code: 143 });
697    }
698}