Skip to main content

capsid_protocol/
process.rs

1use std::{collections::BTreeMap, num::NonZeroU16, str::FromStr};
2
3use serde::{Deserialize, Serialize};
4
5use crate::{Error, Result, path::is_absolute};
6
7pub const MAX_ARGS: usize = 128;
8
9pub const MAX_ARG_BYTES: usize = 4096;
10
11pub const MAX_ENVIRONMENT: usize = 128;
12
13pub const MAX_ENVIRONMENT_NAME_BYTES: usize = 128;
14
15pub const MAX_ENVIRONMENT_VALUE_BYTES: usize = 4096;
16
17pub const MAX_USER_BYTES: usize = 256;
18
19const MAX_HTTP_PATH_BYTES: usize = 2048;
20
21pub fn validate_process_input(
22    argv: &[String],
23    environment: &BTreeMap<String, String>,
24) -> Result<()> {
25    if argv.len() > MAX_ARGS
26        || argv
27            .iter()
28            .any(|value| value.len() > MAX_ARG_BYTES || value.contains('\0'))
29        || environment.len() > MAX_ENVIRONMENT
30        || environment.iter().any(|(key, value)| {
31            key.is_empty()
32                || key.len() > MAX_ENVIRONMENT_NAME_BYTES
33                || key.contains(['=', '\0'])
34                || value.len() > MAX_ENVIRONMENT_VALUE_BYTES
35                || value.contains('\0')
36        })
37    {
38        return Err(Error::Invalid(
39            "invalid application arguments or environment",
40        ));
41    }
42    Ok(())
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(try_from = "u8", into = "u8")]
47pub struct StopSignal(u8);
48
49impl StopSignal {
50    pub fn number(self) -> i32 {
51        i32::from(self.0)
52    }
53}
54
55impl Default for StopSignal {
56    fn default() -> Self {
57        Self(15)
58    }
59}
60
61impl TryFrom<u8> for StopSignal {
62    type Error = Error;
63
64    fn try_from(value: u8) -> Result<Self> {
65        if (1..=31).contains(&value) {
66            Ok(Self(value))
67        } else {
68            Err(Error::Invalid(
69                "unsupported stop signal; use a Linux signal from 1 to 31",
70            ))
71        }
72    }
73}
74
75impl From<StopSignal> for u8 {
76    fn from(value: StopSignal) -> Self {
77        value.0
78    }
79}
80
81impl FromStr for StopSignal {
82    type Err = Error;
83
84    fn from_str(value: &str) -> Result<Self> {
85        let name = value.strip_prefix("SIG").unwrap_or(value);
86        let signal = match name {
87            "HUP" => 1,
88            "INT" => 2,
89            "QUIT" => 3,
90            "ILL" => 4,
91            "TRAP" => 5,
92            "ABRT" | "IOT" => 6,
93            "BUS" => 7,
94            "FPE" => 8,
95            "KILL" => 9,
96            "USR1" => 10,
97            "SEGV" => 11,
98            "USR2" => 12,
99            "PIPE" => 13,
100            "ALRM" => 14,
101            "TERM" => 15,
102            "STKFLT" => 16,
103            "CHLD" | "CLD" => 17,
104            "CONT" => 18,
105            "STOP" => 19,
106            "TSTP" => 20,
107            "TTIN" => 21,
108            "TTOU" => 22,
109            "URG" => 23,
110            "XCPU" => 24,
111            "XFSZ" => 25,
112            "VTALRM" => 26,
113            "PROF" => 27,
114            "WINCH" => 28,
115            "IO" | "POLL" => 29,
116            "PWR" => 30,
117            "SYS" => 31,
118            _ => value
119                .parse::<u8>()
120                .map_err(|_| Error::Invalid("unsupported stop signal name or number"))?,
121        };
122        Self::try_from(signal)
123    }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
128pub enum ReadinessProbe {
129    File { path: String },
130
131    Http(HttpProbe),
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(deny_unknown_fields)]
136pub struct HttpProbe {
137    pub port: NonZeroU16,
138
139    pub path: String,
140
141    #[serde(default = "default_interval")]
142    pub interval_ms: u64,
143
144    #[serde(default = "default_timeout")]
145    pub timeout_ms: u64,
146
147    #[serde(default = "default_success")]
148    pub success_threshold: u16,
149
150    #[serde(default = "default_failure")]
151    pub failure_threshold: u16,
152}
153
154fn default_interval() -> u64 {
155    1_000
156}
157
158fn default_timeout() -> u64 {
159    500
160}
161
162fn default_success() -> u16 {
163    1
164}
165
166fn default_failure() -> u16 {
167    3
168}
169
170impl ReadinessProbe {
171    pub fn http(input: &str) -> Result<Self> {
172        let (port, path) = input
173            .split_once(':')
174            .ok_or(Error::Invalid("HTTP readiness expects PORT:/path"))?;
175        let probe = Self::Http(HttpProbe {
176            port: port
177                .parse()
178                .map_err(|_| Error::Invalid("HTTP readiness port must be 1..65535"))?,
179            path: path.into(),
180            interval_ms: default_interval(),
181            timeout_ms: default_timeout(),
182            success_threshold: default_success(),
183            failure_threshold: default_failure(),
184        });
185        probe.validate()?;
186        Ok(probe)
187    }
188
189    pub fn validate(&self) -> Result<()> {
190        match self {
191            Self::File { path } => validate_path(path),
192            Self::Http(probe) => probe.validate(),
193        }
194    }
195}
196
197impl HttpProbe {
198    pub fn validate(&self) -> Result<()> {
199        let path = &self.path;
200        if !path.starts_with('/')
201            || path.starts_with("//")
202            || path.len() > MAX_HTTP_PATH_BYTES
203            || path
204                .bytes()
205                .any(|byte| !byte.is_ascii_graphic() || byte == b'#')
206        {
207            return Err(Error::Invalid(
208                "HTTP readiness requires an ASCII origin-form path of at most 2048 bytes, without spaces, fragments, or control characters",
209            ));
210        }
211
212        if !(100..=60_000).contains(&self.interval_ms)
213            || !(50..=5_000).contains(&self.timeout_ms)
214            || self.timeout_ms > self.interval_ms
215            || !(1..=10).contains(&self.success_threshold)
216            || !(1..=10).contains(&self.failure_threshold)
217        {
218            return Err(Error::Invalid(
219                "readiness requires interval 100..60000 ms, timeout 50..5000 ms no greater than interval, and thresholds 1..10",
220            ));
221        }
222        Ok(())
223    }
224}
225
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(deny_unknown_fields)]
228pub struct ProcessSettings {
229    pub working_directory: String,
230
231    pub user: String,
232
233    pub stop_signal: StopSignal,
234
235    pub readiness: Option<ReadinessProbe>,
236}
237
238impl Default for ProcessSettings {
239    fn default() -> Self {
240        Self {
241            working_directory: "/".to_owned(),
242            user: "0".to_owned(),
243            stop_signal: StopSignal::default(),
244            readiness: None,
245        }
246    }
247}
248
249impl ProcessSettings {
250    pub fn validate(&self) -> Result<()> {
251        validate_path(&self.working_directory)?;
252        validate_user(&self.user)?;
253        if let Some(probe) = &self.readiness {
254            probe.validate()?;
255        }
256        Ok(())
257    }
258}
259
260#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
261#[serde(default, deny_unknown_fields)]
262pub struct ExecOverrides {
263    pub user: Option<String>,
264
265    pub working_directory: Option<String>,
266
267    pub environment: BTreeMap<String, String>,
268}
269
270impl ExecOverrides {
271    pub fn validate(&self) -> Result<()> {
272        if let Some(user) = &self.user {
273            validate_user(user)?;
274        }
275
276        if let Some(path) = &self.working_directory {
277            validate_path(path)?;
278        }
279        Ok(())
280    }
281}
282
283fn validate_path(path: &str) -> Result<()> {
284    if !is_absolute(path.as_bytes()) {
285        return Err(Error::Invalid(
286            "process paths must be absolute guest paths of at most 4096 bytes",
287        ));
288    }
289    Ok(())
290}
291
292fn validate_user(user: &str) -> Result<()> {
293    let parts = user.split(':').collect::<Vec<_>>();
294    if user.len() > MAX_USER_BYTES
295        || parts.len() > 2
296        || parts.iter().any(|part| {
297            part.is_empty()
298                || part.contains(['\0', '/', '\n', '\r'])
299                || part.bytes().any(|byte| byte.is_ascii_whitespace())
300                || (part.bytes().all(|byte| byte.is_ascii_digit())
301                    && part.parse::<u32>().map_or(true, |id| id == u32::MAX))
302        })
303    {
304        return Err(Error::Invalid(
305            "user must be USER[:GROUP] with valid names or numeric IDs below 4294967295",
306        ));
307    }
308    Ok(())
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314    use crate::testing::Result;
315
316    #[test]
317    fn test_readiness_accepts_only_bounded_loopback_http_paths_and_timing() -> Result {
318        assert!(ReadinessProbe::http("8080:/health?check=ready").is_ok());
319        for input in [
320            "0:/health",
321            "65536:/",
322            "example.com:/",
323            "80:http://other/",
324            "80://other/",
325            "80:/a\r\nInjected:x",
326            "80:/a b",
327            "80:/#fragment",
328        ] {
329            assert!(ReadinessProbe::http(input).is_err(), "{input:?}");
330        }
331        for input in [
332            serde_json::json!({"kind":"http", "port":80,"path":"/", "interval_ms":99}),
333            serde_json::json!({"kind":"http", "port":80,"path":"/", "timeout_ms":1001}),
334            serde_json::json!({"kind":"http", "port":80,"path":"/", "failure_threshold":0}),
335        ] {
336            assert!(
337                serde_json::from_value::<ReadinessProbe>(input)?
338                    .validate()
339                    .is_err()
340            );
341        }
342        assert!(
343            serde_json::from_value::<ReadinessProbe>(
344                serde_json::json!({"kind":"http", "port":80,"path":"/","host":"169.254.169.254"})
345            )
346            .is_err()
347        );
348        Ok(())
349    }
350
351    #[test]
352    fn test_validates_stop_signals_at_text_and_wire_boundaries() -> Result {
353        assert_eq!("SIGUSR1".parse::<StopSignal>()?.number(), 10);
354        assert_eq!("TERM".parse::<StopSignal>()?, "15".parse()?);
355        for value in ["0", "32", "64", "-1", "SIGBOGUS"] {
356            assert!(value.parse::<StopSignal>().is_err());
357        }
358        assert!(serde_json::from_str::<StopSignal>("255").is_err());
359        Ok(())
360    }
361
362    #[test]
363    fn test_rejects_invalid_user_ids_and_relative_working_directories() {
364        for user in [
365            "",
366            ":0",
367            "a:",
368            "a:b:c",
369            "4294967295",
370            "a:4294967295",
371            "a\nb",
372        ] {
373            assert!(
374                ProcessSettings {
375                    user: user.to_owned(),
376                    ..Default::default()
377                }
378                .validate()
379                .is_err()
380            );
381        }
382        assert!(
383            ProcessSettings {
384                working_directory: "relative".to_owned(),
385                ..Default::default()
386            }
387            .validate()
388            .is_err()
389        );
390    }
391}