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        /// Version of the live host speaking this handshake, so the guest can
154        /// compare it with the version baked into the image.
155        #[serde(default)]
156        host_version: String,
157    },
158    ClipboardData {
159        text: String,
160    },
161    HostExecStdout {
162        data: String,
163    },
164    HostExecStderr {
165        data: String,
166    },
167    /// One chunk of a streaming command's output, sent as the child
168    /// produces it. `data` is raw bytes (up to 16 KiB per chunk) so binary
169    /// output survives intact. Only sent when the guest negotiated
170    /// `host_exec_stream`; older guests keep receiving the buffered
171    /// `HostExecStdout`/`HostExecStderr` frames.
172    HostExecOutput {
173        stream: ExecStream,
174        data: Vec<u8>,
175    },
176    HostExecDone {
177        exit_code: i32,
178        /// Signal that killed the child, if any. `exit_code` already
179        /// follows the shell convention (`128 + signal`); this names the
180        /// cause. Old guests ignore the unknown field.
181        #[serde(default)]
182        signal: Option<i32>,
183    },
184    NotifyActionResult {
185        notification_id: u32,
186        action_key: String,
187    },
188    Ping,
189    Shutdown,
190    /// Sent by the host when all CLI sessions have ended; guest responds
191    /// with `IdleTimeout` or `Busy` after scanning `/proc`.
192    CheckIdle,
193    /// Sent by the host when a guest message is rejected (missing `Hello`
194    /// negotiation, or a capability that was not accepted).
195    Error {
196        reason: String,
197        /// Optional machine-readable code (e.g. `busy`) so clients can
198        /// distinguish rejection kinds without parsing `reason`.
199        #[serde(default)]
200        code: Option<String>,
201    },
202    /// Host → guest version/info query (doctor).
203    GetInfo,
204}
205
206/// Write a length-prefixed JSON frame.
207pub fn write_frame<W: Write>(w: &mut W, msg: &impl Serialize) -> io::Result<()> {
208    let json = serde_json::to_vec(msg)?;
209    if json.len() > MAX_FRAME_SIZE {
210        return Err(io::Error::new(
211            io::ErrorKind::InvalidInput,
212            format!(
213                "frame too large: {} bytes (max {MAX_FRAME_SIZE})",
214                json.len()
215            ),
216        ));
217    }
218    let len = u32::try_from(json.len())
219        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "frame payload exceeds 4 GiB"))?
220        .to_be_bytes();
221    w.write_all(&len)?;
222    w.write_all(&json)?;
223    w.flush()?;
224    Ok(())
225}
226
227/// Maximum frame size: 16 MiB.
228const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
229
230/// Largest clipboard payload either side will send or accept (8 MiB).
231/// Beyond this the host answers with an `Error` frame and the guest
232/// refuses locally with a clear message, instead of failing the frame.
233/// A fixed constant (not a config key): raising it needs the matching
234/// host/guest rollout, and the frame cap bounds it anyway.
235pub const MAX_CLIPBOARD_BYTES: usize = 8 * 1024 * 1024;
236
237/// Read a length-prefixed JSON frame.
238pub fn read_frame<R: Read>(r: &mut R) -> io::Result<Option<Vec<u8>>> {
239    let mut len_buf = [0u8; 4];
240    match r.read_exact(&mut len_buf) {
241        Ok(()) => {}
242        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
243        Err(e) => return Err(e),
244    }
245    let len = u32::from_be_bytes(len_buf) as usize;
246    if len > MAX_FRAME_SIZE {
247        return Err(io::Error::new(
248            io::ErrorKind::InvalidData,
249            format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
250        ));
251    }
252    let mut buf = vec![0u8; len];
253    r.read_exact(&mut buf)?;
254    Ok(Some(buf))
255}
256
257/// Incremental frame reader that survives read timeouts.
258///
259/// [`read_frame`] uses `read_exact`, which discards bytes it already read when
260/// a timeout fires mid-frame. The stream is then misaligned: the next read
261/// parses payload bytes as a length prefix. `FrameReader` keeps the partial
262/// frame, so a timeout returns `WouldBlock`/`TimedOut` with nothing lost and
263/// the caller can retry, or give up once [`FrameReader::stalled_for`] is long.
264#[derive(Debug, Default)]
265pub struct FrameReader {
266    prefix: [u8; 4],
267    prefix_filled: usize,
268    body: Vec<u8>,
269    body_filled: usize,
270    body_len: Option<usize>,
271    /// When the first byte of the frame in progress arrived.
272    started: Option<std::time::Instant>,
273}
274
275/// What a [`FrameReader::read`] call produced.
276#[derive(Debug, PartialEq, Eq)]
277pub enum FrameRead {
278    /// A complete frame payload.
279    Frame(Vec<u8>),
280    /// The peer closed the stream at a frame boundary.
281    Eof,
282}
283
284impl FrameReader {
285    pub fn new() -> Self {
286        Self::default()
287    }
288
289    /// True when part of a frame has been read and the rest is still due.
290    pub fn in_progress(&self) -> bool {
291        self.started.is_some()
292    }
293
294    /// Time since the first byte of the frame in progress, if one is in progress.
295    pub fn stalled_for(&self) -> Option<std::time::Duration> {
296        self.started.map(|t| t.elapsed())
297    }
298
299    /// Read until one frame is complete. A timeout returns `Err` and keeps the
300    /// partial frame, so a later call resumes exactly where this one stopped.
301    pub fn read<R: Read>(&mut self, r: &mut R) -> io::Result<FrameRead> {
302        while self.prefix_filled < 4 {
303            let n = r.read(&mut self.prefix[self.prefix_filled..])?;
304            if n == 0 {
305                return if self.prefix_filled == 0 {
306                    Ok(FrameRead::Eof)
307                } else {
308                    Err(io::Error::from(io::ErrorKind::UnexpectedEof))
309                };
310            }
311            self.started.get_or_insert_with(std::time::Instant::now);
312            self.prefix_filled += n;
313        }
314        let len = match self.body_len {
315            Some(len) => len,
316            None => {
317                let len = u32::from_be_bytes(self.prefix) as usize;
318                if len > MAX_FRAME_SIZE {
319                    return Err(io::Error::new(
320                        io::ErrorKind::InvalidData,
321                        format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
322                    ));
323                }
324                self.body = vec![0u8; len];
325                self.body_len = Some(len);
326                len
327            }
328        };
329        while self.body_filled < len {
330            let n = r.read(&mut self.body[self.body_filled..])?;
331            if n == 0 {
332                return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
333            }
334            self.body_filled += n;
335        }
336        let frame = std::mem::take(&mut self.body);
337        *self = Self::default();
338        Ok(FrameRead::Frame(frame))
339    }
340}
341
342/// Unix-only helpers shared by the host CLI and the guest daemon.
343#[cfg(unix)]
344pub mod sysutil;
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    #[test]
351    fn hello_serializes_with_type_tag() {
352        let msg = GuestMessage::Hello {
353            protocol_version: 1,
354            guest_version: "0.2.0".into(),
355            container: "myenv".into(),
356            capabilities: vec!["notify".into()],
357        };
358        let json = serde_json::to_string(&msg).unwrap();
359        assert!(json.contains("\"type\":\"hello\""));
360    }
361
362    #[test]
363    fn frame_length_prefix_matches_payload() {
364        let msg = GuestMessage::ClipboardGet;
365        let mut buf = Vec::new();
366        write_frame(&mut buf, &msg).unwrap();
367        let len = u32::from_be_bytes(buf[..4].try_into().unwrap()) as usize;
368        assert_eq!(len, buf[4..].len());
369    }
370
371    #[test]
372    fn interceptors_cover_known_binaries_and_capabilities() {
373        use std::collections::HashSet;
374        let binaries: HashSet<&str> = INTERCEPTORS.iter().map(|(bin, _)| *bin).collect();
375        assert_eq!(binaries.len(), INTERCEPTORS.len(), "duplicate binary");
376        for (_, cap) in INTERCEPTORS {
377            assert!(ALL_CAPABILITIES.contains(cap), "unknown capability {cap}");
378        }
379    }
380
381    #[test]
382    fn roundtrip_notify_message() {
383        let msg = GuestMessage::Notify {
384            summary: "hello".into(),
385            body: "world".into(),
386            urgency: "normal".into(),
387            actions: vec![],
388            app_name: String::new(),
389        };
390        let mut buf = Vec::new();
391        write_frame(&mut buf, &msg).unwrap();
392
393        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
394        let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
395        match decoded {
396            GuestMessage::Notify {
397                summary,
398                body,
399                urgency,
400                actions,
401                app_name: _,
402            } => {
403                assert_eq!(summary, "hello");
404                assert_eq!(body, "world");
405                assert_eq!(urgency, "normal");
406                assert!(actions.is_empty());
407            }
408            _ => panic!("wrong message type"),
409        }
410    }
411
412    #[test]
413    fn roundtrip_clipboard_set() {
414        let msg = GuestMessage::ClipboardSet {
415            text: "clipboard content".into(),
416        };
417        let mut buf = Vec::new();
418        write_frame(&mut buf, &msg).unwrap();
419
420        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
421        let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
422        match decoded {
423            GuestMessage::ClipboardSet { text } => {
424                assert_eq!(text, "clipboard content");
425            }
426            _ => panic!("wrong message type"),
427        }
428    }
429
430    #[test]
431    fn hello_ack_with_shims_round_trips() {
432        let msg = HostMessage::HelloAck {
433            accepted: vec!["host_exec".into()],
434            rejected: vec![],
435            idle_timeout_secs: 10,
436            host_exec_shims: vec!["git".into(), "code".into()],
437            host_version: "0.9.5".into(),
438        };
439        let mut buf = Vec::new();
440        write_frame(&mut buf, &msg).unwrap();
441        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
442        let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
443        match decoded {
444            HostMessage::HelloAck {
445                accepted,
446                host_exec_shims,
447                host_version,
448                ..
449            } => {
450                assert_eq!(accepted, vec!["host_exec"]);
451                assert_eq!(host_exec_shims, vec!["git", "code"]);
452                assert_eq!(host_version, "0.9.5");
453            }
454            _ => panic!("wrong message type"),
455        }
456    }
457
458    #[test]
459    fn hello_ack_backward_compat_missing_shims() {
460        let json = r#"{"type":"hello_ack","accepted":[],"rejected":[],"idle_timeout_secs":0}"#;
461        let msg: HostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
462        match msg {
463            HostMessage::HelloAck {
464                host_exec_shims,
465                host_version,
466                ..
467            } => {
468                assert!(host_exec_shims.is_empty());
469                assert!(host_version.is_empty());
470            }
471            _ => panic!("wrong message type"),
472        }
473    }
474
475    /// One scripted step of a fake socket: bytes, or a read timeout.
476    enum Step {
477        Bytes(Vec<u8>),
478        Timeout,
479    }
480
481    struct Scripted(std::collections::VecDeque<Step>);
482
483    impl Read for Scripted {
484        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
485            match self.0.pop_front() {
486                None => Ok(0),
487                Some(Step::Timeout) => Err(io::Error::from(io::ErrorKind::WouldBlock)),
488                Some(Step::Bytes(mut b)) => {
489                    let n = b.len().min(buf.len());
490                    buf[..n].copy_from_slice(&b[..n]);
491                    if n < b.len() {
492                        b.drain(..n);
493                        self.0.push_front(Step::Bytes(b));
494                    }
495                    Ok(n)
496                }
497            }
498        }
499    }
500
501    fn encoded(msg: &str) -> Vec<u8> {
502        let mut buf = Vec::new();
503        write_frame(&mut buf, &msg).unwrap();
504        buf
505    }
506
507    /// A timeout after the first two length bytes must not lose them: the
508    /// frame still comes out whole, with no misparse of the payload.
509    #[test]
510    fn frame_survives_a_timeout_in_the_length_prefix() {
511        let bytes = encoded("hello there");
512        let mut r = Scripted(
513            [
514                Step::Bytes(bytes[..2].to_vec()),
515                Step::Timeout,
516                Step::Bytes(bytes[2..].to_vec()),
517            ]
518            .into(),
519        );
520        let mut fr = FrameReader::new();
521        assert!(fr.read(&mut r).is_err());
522        assert!(fr.in_progress());
523        let got = fr.read(&mut r).unwrap();
524        assert_eq!(
525            got,
526            FrameRead::Frame(serde_json::to_vec("hello there").unwrap())
527        );
528        assert!(!fr.in_progress());
529    }
530
531    #[test]
532    fn frame_survives_a_timeout_in_the_payload() {
533        let bytes = encoded("a longer payload to split");
534        let cut = 4 + 7;
535        let mut r = Scripted(
536            [
537                Step::Bytes(bytes[..cut].to_vec()),
538                Step::Timeout,
539                Step::Bytes(bytes[cut..].to_vec()),
540            ]
541            .into(),
542        );
543        let mut fr = FrameReader::new();
544        assert!(fr.read(&mut r).is_err());
545        assert_eq!(
546            fr.read(&mut r).unwrap(),
547            FrameRead::Frame(serde_json::to_vec("a longer payload to split").unwrap())
548        );
549    }
550
551    #[test]
552    fn clean_eof_between_frames_is_eof_not_an_error() {
553        let mut r = Scripted(std::collections::VecDeque::new());
554        assert_eq!(FrameReader::new().read(&mut r).unwrap(), FrameRead::Eof);
555    }
556
557    #[test]
558    fn eof_inside_a_frame_is_an_error() {
559        let bytes = encoded("cut short");
560        let mut r = Scripted([Step::Bytes(bytes[..6].to_vec())].into());
561        let err = FrameReader::new().read(&mut r).unwrap_err();
562        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
563    }
564
565    #[test]
566    fn host_exec_output_chunk_round_trips_raw_bytes() {
567        // Invalid UTF-8 must survive the frame exactly: chunks carry bytes,
568        // not lossy strings.
569        let msg = HostMessage::HostExecOutput {
570            stream: ExecStream::Stdout,
571            data: vec![0xff, 0xfe, b'A'],
572        };
573        let mut buf = Vec::new();
574        write_frame(&mut buf, &msg).unwrap();
575        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
576        let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
577        match decoded {
578            HostMessage::HostExecOutput { stream, data } => {
579                assert_eq!(stream, ExecStream::Stdout);
580                assert_eq!(data, vec![0xff, 0xfe, b'A']);
581            }
582            _ => panic!("wrong message type"),
583        }
584    }
585
586    #[test]
587    fn host_exec_v2_optional_fields_are_serde_defaulted() {
588        // A minimal V2 frame (old guest shims that only know cmd/args,
589        // mostly future guests) must decode with every new field defaulted:
590        // the wire format is frozen without bumping PROTOCOL_VERSION.
591        let json = br#"{"type":"host_exec_v2","cmd":"cat","args":["-s"]}"#;
592        let msg: GuestMessage = serde_json::from_slice(json).unwrap();
593        match msg {
594            GuestMessage::HostExecV2 {
595                cmd,
596                args,
597                env,
598                cwd,
599                tty,
600            } => {
601                assert_eq!(cmd, "cat");
602                assert_eq!(args, vec!["-s"]);
603                assert!(env.is_empty());
604                assert!(cwd.is_none());
605                assert!(!tty);
606            }
607            other => panic!("expected HostExecV2, got {other:?}"),
608        }
609    }
610
611    #[test]
612    fn host_exec_v2_round_trips_the_full_field_set() {
613        let msg = GuestMessage::HostExecV2 {
614            cmd: "git".into(),
615            args: vec!["log".into()],
616            env: vec![("TERM".into(), "xterm-256color".into())],
617            cwd: Some("/home/user/project".into()),
618            tty: true,
619        };
620        let mut buf = Vec::new();
621        write_frame(&mut buf, &msg).unwrap();
622        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
623        let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
624        match decoded {
625            GuestMessage::HostExecV2 {
626                cmd,
627                args,
628                env,
629                cwd,
630                tty,
631            } => {
632                assert_eq!(cmd, "git");
633                assert_eq!(args, vec!["log"]);
634                assert_eq!(
635                    env,
636                    vec![("TERM".to_string(), "xterm-256color".to_string())]
637                );
638                assert_eq!(cwd.as_deref(), Some("/home/user/project"));
639                assert!(tty);
640            }
641            other => panic!("expected HostExecV2, got {other:?}"),
642        }
643    }
644
645    #[test]
646    fn host_exec_signal_round_trips() {
647        let msg = GuestMessage::HostExecSignal { sig: 2 };
648        let mut buf = Vec::new();
649        write_frame(&mut buf, &msg).unwrap();
650        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
651        let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
652        match decoded {
653            GuestMessage::HostExecSignal { sig } => assert_eq!(sig, 2),
654            other => panic!("expected HostExecSignal, got {other:?}"),
655        }
656    }
657
658    /// Wire compatibility in the other direction: a host built before
659    /// `host_exec_fds` can still parse a `Hello` that requests it — the
660    /// unknown capability lands in `capabilities` and negotiation rejects
661    /// it, which is how old hosts degrade the guest to plain `HostExec`.
662    #[test]
663    fn hello_with_an_unknown_capability_parses_on_the_old_schema() {
664        // Serde deserializes every declared field, so the enum's own test
665        // reads are the negotiate path, not these bindings.
666        #[allow(dead_code)]
667        #[derive(Deserialize)]
668        #[serde(tag = "type", rename_all = "snake_case")]
669        enum OldGuestMessage {
670            Hello {
671                protocol_version: u32,
672                guest_version: String,
673                container: String,
674                capabilities: Vec<String>,
675            },
676        }
677
678        let json = r#"{"type":"hello","protocol_version":1,"guest_version":"0.2.0",
679            "container":"dev","capabilities":["host_exec","host_exec_fds"]}"#;
680        let msg: OldGuestMessage = serde_json::from_slice(json.as_bytes()).unwrap();
681        let OldGuestMessage::Hello { capabilities, .. } = msg;
682        assert_eq!(capabilities, vec!["host_exec", "host_exec_fds"]);
683    }
684
685    #[test]
686    fn host_exec_done_carries_an_optional_signal() {
687        let msg = HostMessage::HostExecDone {
688            exit_code: 143,
689            signal: Some(15),
690        };
691        let mut buf = Vec::new();
692        write_frame(&mut buf, &msg).unwrap();
693        let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
694        let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
695        match decoded {
696            HostMessage::HostExecDone { exit_code, signal } => {
697                assert_eq!(exit_code, 143);
698                assert_eq!(signal, Some(15));
699            }
700            _ => panic!("wrong message type"),
701        }
702    }
703
704    /// Wire compatibility: a guest built before `signal` existed must
705    /// still parse the new `HostExecDone`. Serde ignores the unknown
706    /// field, so old guests keep working with no version bump.
707    #[test]
708    fn host_exec_done_with_signal_parses_under_the_old_schema() {
709        #[derive(Debug, Deserialize, PartialEq, Eq)]
710        #[serde(tag = "type", rename_all = "snake_case")]
711        enum OldHostMessage {
712            HostExecDone { exit_code: i32 },
713        }
714
715        let json = r#"{"type":"host_exec_done","exit_code":143,"signal":15}"#;
716        let msg: OldHostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
717        assert_eq!(msg, OldHostMessage::HostExecDone { exit_code: 143 });
718    }
719}