use std::path::{Path, PathBuf};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use crate::{AttemptId, Error, Result};
pub const KERNEL_ARGUMENT: &str = "capsid.boot";
pub const CONTAINER_CHANNEL: &str = "/.capsid/channel";
pub const CONTAINER_DATA: &str = "/.capsid/data";
pub const CONTAINER_PROXY: &str = "127.0.0.1:3128";
pub const BOOT_FILE: &str = "boot.json";
const MAX_CONFIG_BYTES: usize = 4096;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Platform {
Vm,
Container,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Purpose {
Application,
Files,
}
crate::named_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Network {
Isolated = "isolated",
Egress = "egress",
Private = "private",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BootConfig {
pub attempt: AttemptId,
pub platform: Platform,
pub purpose: Purpose,
pub fresh_template: bool,
pub network: Network,
pub tcp_ports: Vec<u16>,
}
impl BootConfig {
pub fn kernel_argument(&self) -> Result<String> {
let json = serde_json::to_vec(self)?;
Ok(format!(
"{KERNEL_ARGUMENT}={}",
URL_SAFE_NO_PAD.encode(json)
))
}
pub fn from_kernel_command_line(cmdline: &str) -> Result<Self> {
let prefix = format!("{KERNEL_ARGUMENT}=");
let encoded = cmdline
.split_whitespace()
.find_map(|argument| argument.strip_prefix(&prefix))
.ok_or(Error::Invalid("missing boot configuration"))?;
if encoded.len() > MAX_CONFIG_BYTES.div_ceil(3) * 4 {
return Err(Error::Invalid("boot configuration is too large"));
}
Self::decode(&URL_SAFE_NO_PAD.decode(encoded)?)
}
pub fn decode(bytes: &[u8]) -> Result<Self> {
if bytes.len() > MAX_CONFIG_BYTES {
return Err(Error::Invalid("boot configuration is too large"));
}
let config: Self = serde_json::from_slice(bytes)?;
config.validate()?;
Ok(config)
}
pub fn validate(&self) -> Result<()> {
if self.tcp_ports.contains(&0) {
return Err(Error::Invalid("invalid boot TCP port"));
}
Ok(())
}
}
pub fn guest_socket(channel: &Path, port: u32) -> PathBuf {
channel.join(format!("g{port}"))
}
pub fn host_socket(channel: &Path, port: u32) -> PathBuf {
channel.join(format!("h{port}"))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::Result;
fn config() -> BootConfig {
BootConfig {
attempt: AttemptId::from_uuid(uuid::Uuid::from_u128(
0x0b6f_3c1e_2a4d_4b8e_9f10_1234_5678_90ab,
)),
platform: Platform::Vm,
purpose: Purpose::Application,
fresh_template: false,
network: Network::Egress,
tcp_ports: vec![80, 8080],
}
}
#[test]
fn test_a_kernel_argument_round_trips_among_other_arguments() -> Result {
let argument = config().kernel_argument()?;
assert!(!argument.contains(char::is_whitespace));
let cmdline = format!("console=ttyS0 {argument} init=/init");
assert_eq!(BootConfig::from_kernel_command_line(&cmdline)?, config());
Ok(())
}
#[test]
fn test_malformed_or_hostile_configurations_are_refused() -> Result {
assert!(BootConfig::from_kernel_command_line("console=ttyS0").is_err());
assert!(BootConfig::from_kernel_command_line("capsid.boot=a").is_err());
assert!(BootConfig::from_kernel_command_line("capsid.boot=!!").is_err());
let oversized = format!("capsid.boot={}", "a".repeat(8192));
assert!(BootConfig::from_kernel_command_line(&oversized).is_err());
let mut escape = serde_json::to_value(config())?;
escape["attempt"] = "../escape".into();
assert!(BootConfig::decode(&serde_json::to_vec(&escape)?).is_err());
let mut invalid = config();
invalid.tcp_ports.push(0);
assert!(BootConfig::decode(&serde_json::to_vec(&invalid)?).is_err());
assert!(BootConfig::decode(br#"{"attempt":"a","unknown":true}"#).is_err());
Ok(())
}
}