Skip to main content

capsid_protocol/
boot.rs

1use std::path::{Path, PathBuf};
2
3use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
4use serde::{Deserialize, Serialize};
5
6use crate::{AttemptId, Error, Result};
7
8pub const KERNEL_ARGUMENT: &str = "capsid.boot";
9
10pub const CONTAINER_CHANNEL: &str = "/.capsid/channel";
11
12pub const CONTAINER_DATA: &str = "/.capsid/data";
13
14pub const CONTAINER_PROXY: &str = "127.0.0.1:3128";
15
16pub const BOOT_FILE: &str = "boot.json";
17
18const MAX_CONFIG_BYTES: usize = 4096;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum Platform {
23    Vm,
24
25    Container,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum Purpose {
31    Application,
32
33    Files,
34}
35
36crate::named_enum! {
37    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
38    pub enum Network {
39        Isolated = "isolated",
40        Egress = "egress",
41        Private = "private",
42    }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(deny_unknown_fields)]
47pub struct BootConfig {
48    pub attempt: AttemptId,
49
50    pub platform: Platform,
51
52    pub purpose: Purpose,
53
54    pub fresh_template: bool,
55
56    pub network: Network,
57
58    pub tcp_ports: Vec<u16>,
59}
60
61impl BootConfig {
62    pub fn kernel_argument(&self) -> Result<String> {
63        let json = serde_json::to_vec(self)?;
64        Ok(format!(
65            "{KERNEL_ARGUMENT}={}",
66            URL_SAFE_NO_PAD.encode(json)
67        ))
68    }
69
70    pub fn from_kernel_command_line(cmdline: &str) -> Result<Self> {
71        let prefix = format!("{KERNEL_ARGUMENT}=");
72        let encoded = cmdline
73            .split_whitespace()
74            .find_map(|argument| argument.strip_prefix(&prefix))
75            .ok_or(Error::Invalid("missing boot configuration"))?;
76        if encoded.len() > MAX_CONFIG_BYTES.div_ceil(3) * 4 {
77            return Err(Error::Invalid("boot configuration is too large"));
78        }
79        Self::decode(&URL_SAFE_NO_PAD.decode(encoded)?)
80    }
81
82    pub fn decode(bytes: &[u8]) -> Result<Self> {
83        if bytes.len() > MAX_CONFIG_BYTES {
84            return Err(Error::Invalid("boot configuration is too large"));
85        }
86
87        let config: Self = serde_json::from_slice(bytes)?;
88        config.validate()?;
89        Ok(config)
90    }
91
92    pub fn validate(&self) -> Result<()> {
93        if self.tcp_ports.contains(&0) {
94            return Err(Error::Invalid("invalid boot TCP port"));
95        }
96        Ok(())
97    }
98}
99
100pub fn guest_socket(channel: &Path, port: u32) -> PathBuf {
101    channel.join(format!("g{port}"))
102}
103
104pub fn host_socket(channel: &Path, port: u32) -> PathBuf {
105    channel.join(format!("h{port}"))
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use crate::testing::Result;
112
113    fn config() -> BootConfig {
114        BootConfig {
115            attempt: AttemptId::from_uuid(uuid::Uuid::from_u128(
116                0x0b6f_3c1e_2a4d_4b8e_9f10_1234_5678_90ab,
117            )),
118            platform: Platform::Vm,
119            purpose: Purpose::Application,
120            fresh_template: false,
121            network: Network::Egress,
122            tcp_ports: vec![80, 8080],
123        }
124    }
125
126    #[test]
127    fn test_a_kernel_argument_round_trips_among_other_arguments() -> Result {
128        let argument = config().kernel_argument()?;
129        assert!(!argument.contains(char::is_whitespace));
130        let cmdline = format!("console=ttyS0 {argument} init=/init");
131        assert_eq!(BootConfig::from_kernel_command_line(&cmdline)?, config());
132        Ok(())
133    }
134
135    #[test]
136    fn test_malformed_or_hostile_configurations_are_refused() -> Result {
137        assert!(BootConfig::from_kernel_command_line("console=ttyS0").is_err());
138        assert!(BootConfig::from_kernel_command_line("capsid.boot=a").is_err());
139        assert!(BootConfig::from_kernel_command_line("capsid.boot=!!").is_err());
140        let oversized = format!("capsid.boot={}", "a".repeat(8192));
141        assert!(BootConfig::from_kernel_command_line(&oversized).is_err());
142        let mut escape = serde_json::to_value(config())?;
143        escape["attempt"] = "../escape".into();
144        assert!(BootConfig::decode(&serde_json::to_vec(&escape)?).is_err());
145        let mut invalid = config();
146        invalid.tcp_ports.push(0);
147        assert!(BootConfig::decode(&serde_json::to_vec(&invalid)?).is_err());
148        assert!(BootConfig::decode(br#"{"attempt":"a","unknown":true}"#).is_err());
149        Ok(())
150    }
151}