Skip to main content

dvm_api/
sandbox_protocol.rs

1//! The sandbox server's frames (`frame.rs`), independent of the controller's
2//! API: requests on its stdin, answers on its stdout. A frame's bytes are a
3//! command's input or output, or a piece of a file.
4
5use std::collections::BTreeMap;
6
7use serde::{Deserialize, Serialize};
8
9#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
10#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
11#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
12#[serde(deny_unknown_fields)]
13pub struct SandboxRequest {
14    /// Run, read, and first-write ids increase across the session; input,
15    /// signals, and open-write pieces refer to earlier ids.
16    #[cfg_attr(feature = "typescript", ts(type = "number"))]
17    pub id: u64,
18    #[serde(flatten)]
19    pub action: SandboxRequestAction,
20}
21
22#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
24#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
25#[serde(rename_all = "snake_case")]
26pub enum SandboxRequestAction {
27    Run(SandboxRun),
28    Stdin(SandboxStdin),
29    Signal(i32),
30    Write(SandboxWrite),
31    Read(SandboxRead),
32}
33
34#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
36#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
37#[serde(deny_unknown_fields)]
38pub struct SandboxRun {
39    #[serde(flatten)]
40    pub program: SandboxProgram,
41    #[serde(default)]
42    #[cfg_attr(feature = "typescript", ts(optional = nullable))]
43    pub env: BTreeMap<String, String>,
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub cwd: Option<String>,
46    #[serde(default)]
47    #[cfg_attr(feature = "typescript", ts(optional = nullable))]
48    pub stdin: bool,
49    /// As `docker exec --user`: a name or uid, optionally `:group` or `:gid`.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub user: Option<String>,
52}
53
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
56#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
57#[serde(rename_all = "snake_case")]
58pub enum SandboxProgram {
59    Argv(Vec<String>),
60    Script(String),
61}
62
63#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
64#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
65#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
66#[serde(deny_unknown_fields)]
67pub struct SandboxStdin {
68    #[serde(default)]
69    #[cfg_attr(feature = "typescript", ts(optional = nullable))]
70    pub close: bool,
71}
72
73#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
74#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
75#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
76#[serde(deny_unknown_fields)]
77pub struct SandboxWrite {
78    pub path: String,
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub mode: Option<u32>,
81    #[serde(default)]
82    #[cfg_attr(feature = "typescript", ts(optional = nullable))]
83    pub last: bool,
84}
85
86#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
87#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
88#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
89#[serde(deny_unknown_fields)]
90pub struct SandboxRead {
91    pub path: String,
92}
93
94#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
95#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
96#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
97#[serde(deny_unknown_fields)]
98pub struct SandboxAnswer {
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    #[cfg_attr(feature = "typescript", ts(type = "number | null"))]
101    pub id: Option<u64>,
102    #[serde(flatten)]
103    pub answer: SandboxAnswerKind,
104}
105
106#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
107#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
108#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
109#[serde(rename_all = "snake_case")]
110pub enum SandboxAnswerKind {
111    Started(SandboxStarted),
112    /// The frame's bytes are the command's.
113    Stdout(bool),
114    Stderr(bool),
115    Exited(SandboxExited),
116    Written(bool),
117    /// The frame's bytes are the file's.
118    Data(bool),
119    End(bool),
120    Error(String),
121}
122
123#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
125#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
126#[serde(deny_unknown_fields)]
127pub struct SandboxStarted {
128    pub pid: i32,
129    pub argv: Vec<String>,
130}
131
132#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
133#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
134#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
135#[serde(deny_unknown_fields)]
136pub struct SandboxExited {
137    pub code: i32,
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    use crate::{decode_frame, encode_frame};
145
146    #[test]
147    fn requests_round_trip_and_ambiguous_ones_are_refused() {
148        for line in [
149            r#"{"id":0,"run":{"argv":["ls","-l"],"env":{"A":"1"},"cwd":"/repo","stdin":true}}"#,
150            r#"{"id":2,"run":{"script":"ls -l | wc -l"}}"#,
151            r#"{"id":0,"stdin":{"close":true}}"#,
152            r#"{"id":0,"signal":15}"#,
153            r#"{"id":3,"write":{"path":"/repo/a","mode":420}}"#,
154            r#"{"id":4,"read":{"path":"/repo/a"}}"#,
155            r#"{"id":3,"write":{"path":"/repo/a","last":true}}"#,
156        ] {
157            let request: SandboxRequest = serde_json::from_str(line).unwrap();
158            let encoded = serde_json::to_string(&request).unwrap();
159            assert_eq!(request, serde_json::from_str(&encoded).unwrap());
160        }
161        for line in [
162            r#"{"id":1,"signal":15,"read":{"path":"a"}}"#,
163            r#"{"id":1,"run":{"argv":["ls"],"script":"ls"}}"#,
164            r#"{"id":1,"run":{"argv":["ls"],"typo":true}}"#,
165            r#"{"id":1,"stdin":{"data":"aGk="}}"#,
166        ] {
167            assert!(
168                serde_json::from_str::<SandboxRequest>(line).is_err(),
169                "{line}"
170            );
171        }
172        let answer = SandboxAnswer {
173            id: None,
174            answer: SandboxAnswerKind::Error("bad line".into()),
175        };
176        assert_eq!(
177            serde_json::to_string(&answer).unwrap(),
178            r#"{"error":"bad line"}"#
179        );
180        for line in [
181            r#"{"id":1,"started":{"pid":7,"argv":["ls","-l"]}}"#,
182            r#"{"id":1,"stdout":true}"#,
183            r#"{"id":1,"stderr":true}"#,
184            r#"{"id":1,"exited":{"code":143}}"#,
185            r#"{"id":3,"written":true}"#,
186            r#"{"id":4,"data":true}"#,
187            r#"{"id":4,"end":true}"#,
188            r#"{"id":3,"error":"failed"}"#,
189            r#"{"error":"bad line"}"#,
190        ] {
191            let answer: SandboxAnswer = serde_json::from_str(line).unwrap();
192            assert_eq!(serde_json::to_string(&answer).unwrap(), line);
193        }
194    }
195
196    #[test]
197    fn a_requests_bytes_and_an_answers_follow_their_header_raw() {
198        let request = SandboxRequest {
199            id: 3,
200            action: SandboxRequestAction::Write(SandboxWrite {
201                path: "/repo/a".into(),
202                mode: None,
203                last: true,
204            }),
205        };
206        let frame = encode_frame(&request, b"\x00\n\xff");
207        assert_eq!(
208            frame,
209            b"{\"id\":3,\"write\":{\"path\":\"/repo/a\",\"last\":true},\"bytes\":3}\n\x00\n\xff"
210        );
211        let decoded = decode_frame::<SandboxRequest>(&frame).unwrap();
212        assert_eq!(
213            (decoded.header, decoded.payload),
214            (request, b"\x00\n\xff".to_vec())
215        );
216
217        let answer = SandboxAnswer {
218            id: Some(1),
219            answer: SandboxAnswerKind::Stdout(true),
220        };
221        let frame = encode_frame(&answer, b"hi\n");
222        assert_eq!(frame, b"{\"id\":1,\"stdout\":true,\"bytes\":3}\nhi\n");
223        assert_eq!(
224            decode_frame::<SandboxAnswer>(&frame).unwrap().header,
225            answer
226        );
227    }
228}