1mod capabilities;
2mod framing;
3mod messages;
4
5pub use capabilities::{
6 ALL_CAPABILITIES, CAP_CLIPBOARD, CAP_HOST_EXEC, CAP_HOST_EXEC_FDS, CAP_HOST_EXEC_STREAM,
7 CAP_NOTIFY, CAP_XDG_OPEN, INTERCEPTORS, TERMINAL_ENV_KEYS, is_host_exec_env,
8};
9pub use framing::{FrameRead, FrameReader, read_frame, write_frame};
10pub use messages::{ExecStream, GuestMessage, HostMessage, NotifyAction};
11
12pub const PROTOCOL_VERSION: u32 = 1;
15
16pub const MAX_CLIPBOARD_BYTES: usize = 8 * 1024 * 1024;
22
23#[cfg(unix)]
25pub mod sysutil;
26
27#[cfg(test)]
28mod tests {
29 use super::*;
30 use serde::Deserialize;
31 use std::io::{self, Read};
32
33 #[test]
34 fn hello_serializes_with_type_tag() {
35 let msg = GuestMessage::Hello {
36 protocol_version: 1,
37 guest_version: "0.2.0".into(),
38 container: "myenv".into(),
39 capabilities: vec!["notify".into()],
40 };
41 let json = serde_json::to_string(&msg).unwrap();
42 assert!(json.contains("\"type\":\"hello\""));
43 }
44
45 #[test]
46 fn frame_length_prefix_matches_payload() {
47 let msg = GuestMessage::ClipboardGet;
48 let mut buf = Vec::new();
49 write_frame(&mut buf, &msg).unwrap();
50 let len = u32::from_be_bytes(buf[..4].try_into().unwrap()) as usize;
51 assert_eq!(len, buf[4..].len());
52 }
53
54 #[test]
55 fn interceptors_cover_known_binaries_and_capabilities() {
56 use std::collections::HashSet;
57 let binaries: HashSet<&str> = INTERCEPTORS.iter().map(|(bin, _)| *bin).collect();
58 assert_eq!(binaries.len(), INTERCEPTORS.len(), "duplicate binary");
59 for (_, cap) in INTERCEPTORS {
60 assert!(ALL_CAPABILITIES.contains(cap), "unknown capability {cap}");
61 }
62 }
63
64 #[test]
65 fn roundtrip_notify_message() {
66 let msg = GuestMessage::Notify {
67 summary: "hello".into(),
68 body: "world".into(),
69 urgency: "normal".into(),
70 actions: vec![],
71 app_name: String::new(),
72 };
73 let mut buf = Vec::new();
74 write_frame(&mut buf, &msg).unwrap();
75
76 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
77 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
78 match decoded {
79 GuestMessage::Notify {
80 summary,
81 body,
82 urgency,
83 actions,
84 app_name: _,
85 } => {
86 assert_eq!(summary, "hello");
87 assert_eq!(body, "world");
88 assert_eq!(urgency, "normal");
89 assert!(actions.is_empty());
90 }
91 _ => panic!("wrong message type"),
92 }
93 }
94
95 #[test]
96 fn roundtrip_clipboard_set() {
97 let msg = GuestMessage::ClipboardSet {
98 text: "clipboard content".into(),
99 };
100 let mut buf = Vec::new();
101 write_frame(&mut buf, &msg).unwrap();
102
103 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
104 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
105 match decoded {
106 GuestMessage::ClipboardSet { text } => {
107 assert_eq!(text, "clipboard content");
108 }
109 _ => panic!("wrong message type"),
110 }
111 }
112
113 #[test]
114 fn hello_ack_with_shims_round_trips() {
115 let msg = HostMessage::HelloAck {
116 accepted: vec!["host_exec".into()],
117 rejected: vec![],
118 idle_timeout_secs: 10,
119 host_exec_shims: vec!["git".into(), "code".into()],
120 host_version: "0.9.5".into(),
121 };
122 let mut buf = Vec::new();
123 write_frame(&mut buf, &msg).unwrap();
124 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
125 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
126 match decoded {
127 HostMessage::HelloAck {
128 accepted,
129 host_exec_shims,
130 host_version,
131 ..
132 } => {
133 assert_eq!(accepted, vec!["host_exec"]);
134 assert_eq!(host_exec_shims, vec!["git", "code"]);
135 assert_eq!(host_version, "0.9.5");
136 }
137 _ => panic!("wrong message type"),
138 }
139 }
140
141 #[test]
142 fn hello_ack_backward_compat_missing_shims() {
143 let json = r#"{"type":"hello_ack","accepted":[],"rejected":[],"idle_timeout_secs":0}"#;
144 let msg: HostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
145 match msg {
146 HostMessage::HelloAck {
147 host_exec_shims,
148 host_version,
149 ..
150 } => {
151 assert!(host_exec_shims.is_empty());
152 assert!(host_version.is_empty());
153 }
154 _ => panic!("wrong message type"),
155 }
156 }
157
158 enum Step {
160 Bytes(Vec<u8>),
161 Timeout,
162 }
163
164 struct Scripted(std::collections::VecDeque<Step>);
165
166 impl Read for Scripted {
167 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
168 match self.0.pop_front() {
169 None => Ok(0),
170 Some(Step::Timeout) => Err(io::Error::from(io::ErrorKind::WouldBlock)),
171 Some(Step::Bytes(mut b)) => {
172 let n = b.len().min(buf.len());
173 buf[..n].copy_from_slice(&b[..n]);
174 if n < b.len() {
175 b.drain(..n);
176 self.0.push_front(Step::Bytes(b));
177 }
178 Ok(n)
179 }
180 }
181 }
182 }
183
184 fn encoded(msg: &str) -> Vec<u8> {
185 let mut buf = Vec::new();
186 write_frame(&mut buf, &msg).unwrap();
187 buf
188 }
189
190 #[test]
193 fn frame_survives_a_timeout_in_the_length_prefix() {
194 let bytes = encoded("hello there");
195 let mut r = Scripted(
196 [
197 Step::Bytes(bytes[..2].to_vec()),
198 Step::Timeout,
199 Step::Bytes(bytes[2..].to_vec()),
200 ]
201 .into(),
202 );
203 let mut fr = FrameReader::new();
204 assert!(fr.read(&mut r).is_err());
205 assert!(fr.in_progress());
206 let got = fr.read(&mut r).unwrap();
207 assert_eq!(
208 got,
209 FrameRead::Frame(serde_json::to_vec("hello there").unwrap())
210 );
211 assert!(!fr.in_progress());
212 }
213
214 #[test]
215 fn frame_survives_a_timeout_in_the_payload() {
216 let bytes = encoded("a longer payload to split");
217 let cut = 4 + 7;
218 let mut r = Scripted(
219 [
220 Step::Bytes(bytes[..cut].to_vec()),
221 Step::Timeout,
222 Step::Bytes(bytes[cut..].to_vec()),
223 ]
224 .into(),
225 );
226 let mut fr = FrameReader::new();
227 assert!(fr.read(&mut r).is_err());
228 assert_eq!(
229 fr.read(&mut r).unwrap(),
230 FrameRead::Frame(serde_json::to_vec("a longer payload to split").unwrap())
231 );
232 }
233
234 #[test]
235 fn clean_eof_between_frames_is_eof_not_an_error() {
236 let mut r = Scripted(std::collections::VecDeque::new());
237 assert_eq!(FrameReader::new().read(&mut r).unwrap(), FrameRead::Eof);
238 }
239
240 #[test]
241 fn eof_inside_a_frame_is_an_error() {
242 let bytes = encoded("cut short");
243 let mut r = Scripted([Step::Bytes(bytes[..6].to_vec())].into());
244 let err = FrameReader::new().read(&mut r).unwrap_err();
245 assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
246 }
247
248 #[test]
249 fn host_exec_output_chunk_round_trips_raw_bytes() {
250 let msg = HostMessage::HostExecOutput {
253 stream: ExecStream::Stdout,
254 data: vec![0xff, 0xfe, b'A'],
255 };
256 let mut buf = Vec::new();
257 write_frame(&mut buf, &msg).unwrap();
258 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
259 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
260 match decoded {
261 HostMessage::HostExecOutput { stream, data } => {
262 assert_eq!(stream, ExecStream::Stdout);
263 assert_eq!(data, vec![0xff, 0xfe, b'A']);
264 }
265 _ => panic!("wrong message type"),
266 }
267 }
268
269 #[test]
270 fn host_exec_v2_optional_fields_are_serde_defaulted() {
271 let json = br#"{"type":"host_exec_v2","cmd":"cat","args":["-s"]}"#;
275 let msg: GuestMessage = serde_json::from_slice(json).unwrap();
276 match msg {
277 GuestMessage::HostExecV2 {
278 cmd,
279 args,
280 env,
281 cwd,
282 tty,
283 } => {
284 assert_eq!(cmd, "cat");
285 assert_eq!(args, vec!["-s"]);
286 assert!(env.is_empty());
287 assert!(cwd.is_none());
288 assert!(!tty);
289 }
290 other => panic!("expected HostExecV2, got {other:?}"),
291 }
292 }
293
294 #[test]
295 fn host_exec_v2_round_trips_the_full_field_set() {
296 let msg = GuestMessage::HostExecV2 {
297 cmd: "git".into(),
298 args: vec!["log".into()],
299 env: vec![("TERM".into(), "xterm-256color".into())],
300 cwd: Some("/home/user/project".into()),
301 tty: true,
302 };
303 let mut buf = Vec::new();
304 write_frame(&mut buf, &msg).unwrap();
305 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
306 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
307 match decoded {
308 GuestMessage::HostExecV2 {
309 cmd,
310 args,
311 env,
312 cwd,
313 tty,
314 } => {
315 assert_eq!(cmd, "git");
316 assert_eq!(args, vec!["log"]);
317 assert_eq!(
318 env,
319 vec![("TERM".to_string(), "xterm-256color".to_string())]
320 );
321 assert_eq!(cwd.as_deref(), Some("/home/user/project"));
322 assert!(tty);
323 }
324 other => panic!("expected HostExecV2, got {other:?}"),
325 }
326 }
327
328 #[test]
329 fn terminal_env_allowlist_carries_identity_but_not_host_sockets() {
330 for key in [
331 "TERM",
332 "COLORTERM",
333 "TERM_PROGRAM",
334 "TERM_PROGRAM_VERSION",
335 "VTE_VERSION",
336 "KITTY_WINDOW_ID",
337 "LC_TERMINAL",
338 ] {
339 assert!(TERMINAL_ENV_KEYS.contains(&key), "{key} must be forwarded");
340 assert!(is_host_exec_env(key), "{key} must reach host-exec");
341 }
342 assert!(is_host_exec_env("LANG"));
343 for key in [
344 "PATH",
345 "LD_PRELOAD",
346 "KITTY_LISTEN_ON",
347 "WEZTERM_UNIX_SOCKET",
348 "TMUX",
349 "STY",
350 ] {
351 assert!(!is_host_exec_env(key), "{key} must stay inside");
352 assert!(
353 !TERMINAL_ENV_KEYS.contains(&key),
354 "{key} is not terminal identity"
355 );
356 }
357 }
358
359 #[test]
360 fn host_exec_signal_round_trips() {
361 let msg = GuestMessage::HostExecSignal { sig: 2 };
362 let mut buf = Vec::new();
363 write_frame(&mut buf, &msg).unwrap();
364 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
365 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
366 match decoded {
367 GuestMessage::HostExecSignal { sig } => assert_eq!(sig, 2),
368 other => panic!("expected HostExecSignal, got {other:?}"),
369 }
370 }
371
372 #[test]
377 fn hello_with_an_unknown_capability_parses_on_the_old_schema() {
378 #[allow(dead_code)]
381 #[derive(Deserialize)]
382 #[serde(tag = "type", rename_all = "snake_case")]
383 enum OldGuestMessage {
384 Hello {
385 protocol_version: u32,
386 guest_version: String,
387 container: String,
388 capabilities: Vec<String>,
389 },
390 }
391
392 let json = r#"{"type":"hello","protocol_version":1,"guest_version":"0.2.0",
393 "container":"dev","capabilities":["host_exec","host_exec_fds"]}"#;
394 let msg: OldGuestMessage = serde_json::from_slice(json.as_bytes()).unwrap();
395 let OldGuestMessage::Hello { capabilities, .. } = msg;
396 assert_eq!(capabilities, vec!["host_exec", "host_exec_fds"]);
397 }
398
399 #[test]
400 fn host_exec_done_carries_an_optional_signal() {
401 let msg = HostMessage::HostExecDone {
402 exit_code: 143,
403 signal: Some(15),
404 };
405 let mut buf = Vec::new();
406 write_frame(&mut buf, &msg).unwrap();
407 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
408 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
409 match decoded {
410 HostMessage::HostExecDone { exit_code, signal } => {
411 assert_eq!(exit_code, 143);
412 assert_eq!(signal, Some(15));
413 }
414 _ => panic!("wrong message type"),
415 }
416 }
417
418 #[test]
422 fn host_exec_done_with_signal_parses_under_the_old_schema() {
423 #[derive(Debug, Deserialize, PartialEq, Eq)]
424 #[serde(tag = "type", rename_all = "snake_case")]
425 enum OldHostMessage {
426 HostExecDone { exit_code: i32 },
427 }
428
429 let json = r#"{"type":"host_exec_done","exit_code":143,"signal":15}"#;
430 let msg: OldHostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
431 assert_eq!(msg, OldHostMessage::HostExecDone { exit_code: 143 });
432 }
433}