Skip to main content

microsandbox_protocol/
message.rs

1//! Message envelope and type definitions for the agent protocol.
2
3use serde::{Deserialize, Serialize, de::DeserializeOwned};
4
5use crate::error::ProtocolResult;
6
7//--------------------------------------------------------------------------------------------------
8// Constants
9//--------------------------------------------------------------------------------------------------
10
11/// Current protocol version.
12pub const PROTOCOL_VERSION: u8 = 6;
13
14/// Frame flag: this is the last message for the given correlation ID.
15///
16/// Set on terminal message types such as `ExecExited`, `FsResponse`, and `TcpClosed`.
17pub const FLAG_TERMINAL: u8 = 0b0000_0001;
18
19/// Frame flag: this is the first message of a new session.
20///
21/// Set on session-initiating message types such as `ExecRequest`, `FsRequest`, and `TcpConnect`.
22pub const FLAG_SESSION_START: u8 = 0b0000_0010;
23
24/// Frame flag: this message requests sandbox shutdown.
25///
26/// Set on `Shutdown` messages. The sandbox-process relay uses this to trigger
27/// drain escalation (SIGTERM → SIGKILL) if the guest doesn't exit voluntarily.
28pub const FLAG_SHUTDOWN: u8 = 0b0000_0100;
29
30/// Size of the frame header fields that sit between the length prefix and the
31/// CBOR payload: `[id: u32 BE][flags: u8]` = 5 bytes.
32pub const FRAME_HEADER_SIZE: usize = 5;
33
34//--------------------------------------------------------------------------------------------------
35// Types
36//--------------------------------------------------------------------------------------------------
37
38/// The message envelope sent over the wire.
39///
40/// Each message contains a version, type, correlation ID, flags, and a CBOR payload.
41///
42/// Wire format: `[len: u32 BE][id: u32 BE][flags: u8][CBOR(v, t, p)]`
43///
44/// The `id` and `flags` fields live in the binary frame header (outside CBOR)
45/// so that relay intermediaries can route frames without CBOR parsing.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct Message {
48    /// Protocol generation, echoed into the frame.
49    ///
50    /// This is the single protocol version axis (see `VERSIONING.md`), the same
51    /// number negotiated once at the handshake — not a second, message-local
52    /// version. It is carried here so a frame is self-describing for debugging
53    /// and telemetry; behavior is gated on the negotiated generation, not on
54    /// reading this field per message.
55    pub v: u8,
56
57    /// Message type.
58    pub t: MessageType,
59
60    /// Correlation ID used to associate requests with responses and
61    /// to identify exec sessions.
62    ///
63    /// Serialized in the binary frame header, not in CBOR.
64    #[serde(skip)]
65    pub id: u32,
66
67    /// Frame flags computed from the message type.
68    ///
69    /// Serialized in the binary frame header, not in CBOR.
70    #[serde(skip)]
71    pub flags: u8,
72
73    /// The CBOR-encoded payload bytes.
74    #[serde(with = "serde_bytes")]
75    pub p: Vec<u8>,
76}
77
78/// Identifies the type of a protocol message.
79///
80/// The `#[strum(serialize = ...)]` attribute on each variant is the single
81/// source for its wire string: [`as_str`](Self::as_str) and
82/// [`from_wire_str`](Self::from_wire_str) are derived from it, and
83/// [`strum::IntoEnumIterator`] yields every variant for exhaustive iteration
84/// (the schema snapshot) without a hand-maintained list.
85#[derive(
86    Debug,
87    Clone,
88    Copy,
89    PartialEq,
90    Eq,
91    Hash,
92    strum::IntoStaticStr,
93    strum::EnumString,
94    strum::EnumIter,
95)]
96pub enum MessageType {
97    /// Guest agent is ready.
98    #[strum(serialize = "core.ready")]
99    Ready,
100
101    /// Guest reports init context before user mounts.
102    #[strum(serialize = "core.init.resolved")]
103    InitResolved,
104
105    /// Host acknowledges init-context setup.
106    #[strum(serialize = "core.init.ack")]
107    InitAck,
108
109    /// Host requests shutdown.
110    #[strum(serialize = "core.shutdown")]
111    Shutdown,
112
113    /// Host relay reports that one SDK client disconnected.
114    #[strum(serialize = "core.relay.client.disconnected")]
115    RelayClientDisconnected,
116
117    /// Host asks the guest to synchronize `CLOCK_REALTIME`.
118    #[strum(serialize = "core.clock.sync")]
119    ClockSync,
120
121    /// Host checks whether the guest agent is reachable.
122    #[strum(serialize = "core.ping")]
123    Ping,
124
125    /// Guest confirms that the guest agent is reachable.
126    #[strum(serialize = "core.pong")]
127    Pong,
128
129    /// Host explicitly records sandbox activity.
130    #[strum(serialize = "core.touch")]
131    Touch,
132
133    /// Guest confirms that sandbox activity was recorded.
134    #[strum(serialize = "core.touched")]
135    Touched,
136
137    /// Peer reports a recoverable protocol-level error.
138    #[strum(serialize = "core.error")]
139    CoreError,
140
141    /// Host requests command execution.
142    #[strum(serialize = "core.exec.request")]
143    ExecRequest,
144
145    /// Guest confirms command started.
146    #[strum(serialize = "core.exec.started")]
147    ExecStarted,
148
149    /// Host sends stdin data.
150    #[strum(serialize = "core.exec.stdin")]
151    ExecStdin,
152
153    /// Guest reports that a prior `ExecStdin` write to the child's
154    /// stdin failed (e.g. the child closed its read end). Non-terminal:
155    /// the session continues and may still produce stdout/stderr and
156    /// an exit code.
157    #[strum(serialize = "core.exec.stdin.error")]
158    ExecStdinError,
159
160    /// Guest sends stdout data.
161    #[strum(serialize = "core.exec.stdout")]
162    ExecStdout,
163
164    /// Guest sends stderr data.
165    #[strum(serialize = "core.exec.stderr")]
166    ExecStderr,
167
168    /// Guest reports command exit.
169    #[strum(serialize = "core.exec.exited")]
170    ExecExited,
171
172    /// Guest reports command failed to spawn (binary not found,
173    /// permission denied, etc.). Distinct from `ExecExited` —
174    /// `ExecFailed` means the user code never ran. Terminal.
175    #[strum(serialize = "core.exec.failed")]
176    ExecFailed,
177
178    /// Host requests PTY resize.
179    #[strum(serialize = "core.exec.resize")]
180    ExecResize,
181
182    /// Host sends signal to process.
183    #[strum(serialize = "core.exec.signal")]
184    ExecSignal,
185
186    /// Host requests a filesystem operation.
187    #[strum(serialize = "core.fs.request")]
188    FsRequest,
189
190    /// Guest sends a terminal filesystem response.
191    #[strum(serialize = "core.fs.response")]
192    FsResponse,
193
194    /// Streaming file data chunk (bidirectional).
195    #[strum(serialize = "core.fs.data")]
196    FsData,
197
198    /// Host requests a TCP connection from inside the guest.
199    #[strum(serialize = "core.tcp.connect")]
200    TcpConnect,
201
202    /// Guest confirms that a TCP connection was opened.
203    #[strum(serialize = "core.tcp.connected")]
204    TcpConnected,
205
206    /// TCP stream data chunk (bidirectional).
207    #[strum(serialize = "core.tcp.data")]
208    TcpData,
209
210    /// One TCP stream side has closed its write half.
211    #[strum(serialize = "core.tcp.eof")]
212    TcpEof,
213
214    /// Host requests a TCP session close.
215    #[strum(serialize = "core.tcp.close")]
216    TcpClose,
217
218    /// Guest reports that a TCP session is closed. Terminal.
219    #[strum(serialize = "core.tcp.closed")]
220    TcpClosed,
221
222    /// Guest reports that a TCP session failed. Terminal.
223    #[strum(serialize = "core.tcp.failed")]
224    TcpFailed,
225}
226
227//--------------------------------------------------------------------------------------------------
228// Methods
229//--------------------------------------------------------------------------------------------------
230
231impl Message {
232    /// Creates a new message with the current protocol version and raw payload bytes.
233    pub fn new(t: MessageType, id: u32, p: Vec<u8>) -> Self {
234        let flags = t.flags();
235        Self {
236            v: PROTOCOL_VERSION,
237            t,
238            id,
239            flags,
240            p,
241        }
242    }
243
244    /// Creates a new message by serializing the given payload to CBOR.
245    pub fn with_payload<T: Serialize>(
246        t: MessageType,
247        id: u32,
248        payload: &T,
249    ) -> ProtocolResult<Self> {
250        let mut p = Vec::new();
251        ciborium::into_writer(payload, &mut p)?;
252        let flags = t.flags();
253        Ok(Self {
254            v: PROTOCOL_VERSION,
255            t,
256            id,
257            flags,
258            p,
259        })
260    }
261
262    /// Deserializes the payload bytes into the given type.
263    pub fn payload<T: DeserializeOwned>(&self) -> ProtocolResult<T> {
264        Ok(ciborium::from_reader(&self.p[..])?)
265    }
266}
267
268impl MessageType {
269    /// Computes the frame flags byte for this message type.
270    pub fn flags(&self) -> u8 {
271        match self {
272            Self::Pong
273            | Self::Touched
274            | Self::CoreError
275            | Self::ExecExited
276            | Self::ExecFailed
277            | Self::FsResponse
278            | Self::TcpClosed
279            | Self::TcpFailed => FLAG_TERMINAL,
280            Self::ExecRequest | Self::FsRequest | Self::TcpConnect => FLAG_SESSION_START,
281            Self::Shutdown => FLAG_SHUTDOWN,
282            _ => 0,
283        }
284    }
285
286    /// The protocol generation that introduced this message type.
287    ///
288    /// A per-type label on the single protocol generation axis (see
289    /// `VERSIONING.md`), not a separate version counter. The send path gates on
290    /// it: a type whose generation exceeds the peer's negotiated generation is
291    /// rejected locally with a typed error instead of being sent to a peer that
292    /// cannot handle it, so only that one feature fails rather than the session.
293    ///
294    /// Core and exec types belong to the generation-1 baseline; they work on
295    /// every runtime we still talk to, including the pre-0.5 legacy one.
296    /// Filesystem streaming did not exist in the pre-0.5 legacy protocol
297    /// (generation 1), so the `Fs*` types require generation 2 or newer.
298    /// TCP forwarding was introduced in generation 4. `core.error` was
299    /// introduced in generation 5. Reachability checks and explicit idle
300    /// refreshes were introduced in generation 6.
301    ///
302    /// There is deliberately no wildcard arm: adding a new `MessageType` must
303    /// force a conscious choice of the generation that introduced it (and a
304    /// matching `PROTOCOL_VERSION` bump). Message types are append-only — never
305    /// lower or re-purpose an existing value.
306    pub fn min_protocol_version(&self) -> u8 {
307        match self {
308            Self::Ready
309            | Self::InitResolved
310            | Self::InitAck
311            | Self::Shutdown
312            | Self::RelayClientDisconnected
313            | Self::ClockSync
314            | Self::ExecRequest
315            | Self::ExecStarted
316            | Self::ExecStdin
317            | Self::ExecStdinError
318            | Self::ExecStdout
319            | Self::ExecStderr
320            | Self::ExecExited
321            | Self::ExecFailed
322            | Self::ExecResize
323            | Self::ExecSignal => 1,
324            Self::FsRequest | Self::FsResponse | Self::FsData => 2,
325            Self::CoreError => 5,
326            Self::Ping | Self::Pong | Self::Touch | Self::Touched => 6,
327            Self::TcpConnect
328            | Self::TcpConnected
329            | Self::TcpData
330            | Self::TcpEof
331            | Self::TcpClose
332            | Self::TcpClosed
333            | Self::TcpFailed => 4,
334        }
335    }
336
337    /// Whether a peer that speaks `peer_generation` is new enough to handle this
338    /// message type.
339    ///
340    /// The shared version-compatibility primitive for both directions. The host
341    /// gates its sends on it (`AgentClient::ensure_version_compat`); the guest
342    /// can gate a guest-initiated message the same way, reading the peer's
343    /// generation from the `v` field of the request that established the session.
344    /// See `VERSIONING.md`.
345    pub fn is_available_at(&self, peer_generation: u8) -> bool {
346        self.min_protocol_version() <= peer_generation
347    }
348
349    /// Returns the wire string representation.
350    ///
351    /// Backed by the per-variant `#[strum(serialize = ...)]` attribute, the
352    /// single source of truth for wire strings.
353    pub fn as_str(&self) -> &'static str {
354        (*self).into()
355    }
356
357    /// Parses a wire string into a message type, the inverse of
358    /// [`as_str`](Self::as_str). Returns `None` for an unknown string.
359    pub fn from_wire_str(s: &str) -> Option<Self> {
360        s.parse().ok()
361    }
362}
363
364//--------------------------------------------------------------------------------------------------
365// Trait Implementations
366//--------------------------------------------------------------------------------------------------
367
368impl Serialize for MessageType {
369    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
370    where
371        S: serde::Serializer,
372    {
373        serializer.serialize_str(self.as_str())
374    }
375}
376
377impl<'de> Deserialize<'de> for MessageType {
378    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
379    where
380        D: serde::Deserializer<'de>,
381    {
382        let s = String::deserialize(deserializer)?;
383        Self::from_wire_str(&s)
384            .ok_or_else(|| serde::de::Error::custom(format!("unknown message type: {s}")))
385    }
386}
387
388//--------------------------------------------------------------------------------------------------
389// Tests
390//--------------------------------------------------------------------------------------------------
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396    #[test]
397    fn test_message_type_roundtrip() {
398        let types = [
399            (MessageType::Ready, "core.ready"),
400            (MessageType::InitResolved, "core.init.resolved"),
401            (MessageType::InitAck, "core.init.ack"),
402            (MessageType::Shutdown, "core.shutdown"),
403            (
404                MessageType::RelayClientDisconnected,
405                "core.relay.client.disconnected",
406            ),
407            (MessageType::ClockSync, "core.clock.sync"),
408            (MessageType::Ping, "core.ping"),
409            (MessageType::Pong, "core.pong"),
410            (MessageType::Touch, "core.touch"),
411            (MessageType::Touched, "core.touched"),
412            (MessageType::CoreError, "core.error"),
413            (MessageType::ExecRequest, "core.exec.request"),
414            (MessageType::ExecStarted, "core.exec.started"),
415            (MessageType::ExecStdin, "core.exec.stdin"),
416            (MessageType::ExecStdinError, "core.exec.stdin.error"),
417            (MessageType::ExecStdout, "core.exec.stdout"),
418            (MessageType::ExecStderr, "core.exec.stderr"),
419            (MessageType::ExecExited, "core.exec.exited"),
420            (MessageType::ExecFailed, "core.exec.failed"),
421            (MessageType::ExecResize, "core.exec.resize"),
422            (MessageType::ExecSignal, "core.exec.signal"),
423            (MessageType::FsRequest, "core.fs.request"),
424            (MessageType::FsResponse, "core.fs.response"),
425            (MessageType::FsData, "core.fs.data"),
426            (MessageType::TcpConnect, "core.tcp.connect"),
427            (MessageType::TcpConnected, "core.tcp.connected"),
428            (MessageType::TcpData, "core.tcp.data"),
429            (MessageType::TcpEof, "core.tcp.eof"),
430            (MessageType::TcpClose, "core.tcp.close"),
431            (MessageType::TcpClosed, "core.tcp.closed"),
432            (MessageType::TcpFailed, "core.tcp.failed"),
433        ];
434
435        for (mt, expected_str) in &types {
436            assert_eq!(mt.as_str(), *expected_str);
437            assert_eq!(MessageType::from_wire_str(expected_str).unwrap(), *mt);
438        }
439    }
440
441    #[test]
442    fn test_message_type_serde_roundtrip() {
443        let types = [
444            MessageType::Ready,
445            MessageType::InitResolved,
446            MessageType::InitAck,
447            MessageType::Shutdown,
448            MessageType::RelayClientDisconnected,
449            MessageType::ClockSync,
450            MessageType::Ping,
451            MessageType::Pong,
452            MessageType::Touch,
453            MessageType::Touched,
454            MessageType::CoreError,
455            MessageType::ExecRequest,
456            MessageType::ExecStarted,
457            MessageType::ExecStdin,
458            MessageType::ExecStdinError,
459            MessageType::ExecStdout,
460            MessageType::ExecStderr,
461            MessageType::ExecExited,
462            MessageType::ExecFailed,
463            MessageType::ExecResize,
464            MessageType::ExecSignal,
465            MessageType::FsRequest,
466            MessageType::FsResponse,
467            MessageType::FsData,
468            MessageType::TcpConnect,
469            MessageType::TcpConnected,
470            MessageType::TcpData,
471            MessageType::TcpEof,
472            MessageType::TcpClose,
473            MessageType::TcpClosed,
474            MessageType::TcpFailed,
475        ];
476
477        for mt in &types {
478            let mut buf = Vec::new();
479            ciborium::into_writer(mt, &mut buf).unwrap();
480            let decoded: MessageType = ciborium::from_reader(&buf[..]).unwrap();
481            assert_eq!(&decoded, mt);
482        }
483    }
484
485    #[test]
486    fn test_unknown_message_type() {
487        assert!(MessageType::from_wire_str("core.unknown").is_none());
488    }
489
490    #[test]
491    fn test_message_with_payload_roundtrip() {
492        use crate::exec::ExecExited;
493
494        let msg =
495            Message::with_payload(MessageType::ExecExited, 7, &ExecExited { code: 42 }).unwrap();
496
497        assert_eq!(msg.t, MessageType::ExecExited);
498        assert_eq!(msg.id, 7);
499        assert_eq!(msg.flags, FLAG_TERMINAL);
500
501        let payload: ExecExited = msg.payload().unwrap();
502        assert_eq!(payload.code, 42);
503    }
504
505    #[test]
506    fn test_message_type_flags() {
507        assert_eq!(MessageType::ExecExited.flags(), FLAG_TERMINAL);
508        assert_eq!(MessageType::ExecFailed.flags(), FLAG_TERMINAL);
509        assert_eq!(MessageType::FsResponse.flags(), FLAG_TERMINAL);
510        assert_eq!(MessageType::TcpClosed.flags(), FLAG_TERMINAL);
511        assert_eq!(MessageType::TcpFailed.flags(), FLAG_TERMINAL);
512        assert_eq!(MessageType::Pong.flags(), FLAG_TERMINAL);
513        assert_eq!(MessageType::Touched.flags(), FLAG_TERMINAL);
514        assert_eq!(MessageType::ExecRequest.flags(), FLAG_SESSION_START);
515        assert_eq!(MessageType::FsRequest.flags(), FLAG_SESSION_START);
516        assert_eq!(MessageType::TcpConnect.flags(), FLAG_SESSION_START);
517        assert_eq!(MessageType::Ready.flags(), 0);
518        assert_eq!(MessageType::InitResolved.flags(), 0);
519        assert_eq!(MessageType::InitAck.flags(), 0);
520        assert_eq!(MessageType::Shutdown.flags(), FLAG_SHUTDOWN);
521        assert_eq!(MessageType::ClockSync.flags(), 0);
522        assert_eq!(MessageType::Ping.flags(), 0);
523        assert_eq!(MessageType::Touch.flags(), 0);
524        assert_eq!(MessageType::ExecStarted.flags(), 0);
525        assert_eq!(MessageType::ExecStdin.flags(), 0);
526        assert_eq!(MessageType::ExecStdout.flags(), 0);
527        assert_eq!(MessageType::ExecStderr.flags(), 0);
528        assert_eq!(MessageType::ExecResize.flags(), 0);
529        assert_eq!(MessageType::ExecSignal.flags(), 0);
530        assert_eq!(MessageType::FsData.flags(), 0);
531        assert_eq!(MessageType::TcpConnected.flags(), 0);
532        assert_eq!(MessageType::TcpData.flags(), 0);
533        assert_eq!(MessageType::TcpEof.flags(), 0);
534        assert_eq!(MessageType::TcpClose.flags(), 0);
535    }
536
537    #[test]
538    fn test_additive_fields_keep_old_and_new_compatible() {
539        // The core backward-compatibility guarantee from VERSIONING.md: a new,
540        // always-optional field is safe in both directions across a version skew.
541        use serde::{Deserialize, Serialize};
542
543        // A payload as it existed at an older generation.
544        #[derive(Serialize, Deserialize)]
545        struct Old {
546            a: u32,
547            b: u32,
548        }
549
550        // The same payload after a later generation added `c` (optional).
551        #[derive(Serialize, Deserialize, Debug, PartialEq)]
552        struct New {
553            a: u32,
554            b: u32,
555            #[serde(default)]
556            c: u32,
557        }
558
559        // New sender -> old receiver: the unknown `c` is ignored, not an error.
560        let mut new_bytes = Vec::new();
561        ciborium::into_writer(&New { a: 1, b: 2, c: 3 }, &mut new_bytes).unwrap();
562        let as_old: Old = ciborium::from_reader(&new_bytes[..]).unwrap();
563        assert_eq!((as_old.a, as_old.b), (1, 2));
564
565        // Old sender -> new receiver: the missing `c` falls back to its default.
566        let mut old_bytes = Vec::new();
567        ciborium::into_writer(&Old { a: 1, b: 2 }, &mut old_bytes).unwrap();
568        let as_new: New = ciborium::from_reader(&old_bytes[..]).unwrap();
569        assert_eq!(as_new, New { a: 1, b: 2, c: 0 });
570    }
571
572    #[test]
573    fn test_is_available_at() {
574        // Exec is in the generation-1 baseline: available to every peer.
575        assert!(MessageType::ExecRequest.is_available_at(1));
576        assert!(MessageType::ExecRequest.is_available_at(2));
577        assert!(MessageType::ExecRequest.is_available_at(PROTOCOL_VERSION));
578        // Filesystem requires generation 2: unavailable to a legacy (gen 1) peer.
579        assert!(!MessageType::FsRequest.is_available_at(1));
580        assert!(MessageType::FsRequest.is_available_at(2));
581        assert!(MessageType::FsRequest.is_available_at(PROTOCOL_VERSION));
582        // Ping/touch are generation-6 core capabilities.
583        assert!(!MessageType::Ping.is_available_at(5));
584        assert!(MessageType::Ping.is_available_at(6));
585        assert!(MessageType::Ping.is_available_at(PROTOCOL_VERSION));
586    }
587
588    #[test]
589    fn test_min_protocol_version_per_type() {
590        // Core and exec types are the generation-1 baseline: usable on every
591        // runtime we still talk to, including the pre-0.5 legacy one.
592        let baseline = [
593            MessageType::Ready,
594            MessageType::InitResolved,
595            MessageType::InitAck,
596            MessageType::Shutdown,
597            MessageType::RelayClientDisconnected,
598            MessageType::ClockSync,
599            MessageType::ExecRequest,
600            MessageType::ExecStarted,
601            MessageType::ExecStdin,
602            MessageType::ExecStdinError,
603            MessageType::ExecStdout,
604            MessageType::ExecStderr,
605            MessageType::ExecExited,
606            MessageType::ExecFailed,
607            MessageType::ExecResize,
608            MessageType::ExecSignal,
609        ];
610        for mt in &baseline {
611            assert_eq!(mt.min_protocol_version(), 1, "{mt:?} should be v1 baseline");
612        }
613
614        // Filesystem streaming did not exist in the pre-0.5 legacy protocol, so
615        // these require a post-legacy generation.
616        for mt in [
617            MessageType::FsRequest,
618            MessageType::FsResponse,
619            MessageType::FsData,
620        ] {
621            assert_eq!(mt.min_protocol_version(), 2, "{mt:?} should require gen 2");
622        }
623
624        for mt in [
625            MessageType::Ping,
626            MessageType::Pong,
627            MessageType::Touch,
628            MessageType::Touched,
629        ] {
630            assert_eq!(mt.min_protocol_version(), 6, "{mt:?} should require gen 6");
631        }
632
633        // Every current type must be sendable to a current peer.
634        assert!(MessageType::FsRequest.min_protocol_version() <= PROTOCOL_VERSION);
635    }
636
637    #[test]
638    fn test_message_new_computes_flags() {
639        let msg = Message::new(MessageType::ExecRequest, 1, Vec::new());
640        assert_eq!(msg.flags, FLAG_SESSION_START);
641
642        let msg = Message::new(MessageType::ExecStdout, 1, Vec::new());
643        assert_eq!(msg.flags, 0);
644    }
645}