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