capsid-protocol 0.1.0-alpha.1

Versioned, size-bounded messages between the Capsid host and its guest agent.
Documentation
use std::{collections::BTreeMap, num::NonZeroU16, str::FromStr};

use serde::{Deserialize, Serialize};

use crate::{Error, Result, path::is_absolute};

pub const MAX_ARGS: usize = 128;

pub const MAX_ARG_BYTES: usize = 4096;

pub const MAX_ENVIRONMENT: usize = 128;

pub const MAX_ENVIRONMENT_NAME_BYTES: usize = 128;

pub const MAX_ENVIRONMENT_VALUE_BYTES: usize = 4096;

pub const MAX_USER_BYTES: usize = 256;

const MAX_HTTP_PATH_BYTES: usize = 2048;

pub fn validate_process_input(
    argv: &[String],
    environment: &BTreeMap<String, String>,
) -> Result<()> {
    if argv.len() > MAX_ARGS
        || argv
            .iter()
            .any(|value| value.len() > MAX_ARG_BYTES || value.contains('\0'))
        || environment.len() > MAX_ENVIRONMENT
        || environment.iter().any(|(key, value)| {
            key.is_empty()
                || key.len() > MAX_ENVIRONMENT_NAME_BYTES
                || key.contains(['=', '\0'])
                || value.len() > MAX_ENVIRONMENT_VALUE_BYTES
                || value.contains('\0')
        })
    {
        return Err(Error::Invalid(
            "invalid application arguments or environment",
        ));
    }
    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "u8", into = "u8")]
pub struct StopSignal(u8);

impl StopSignal {
    pub fn number(self) -> i32 {
        i32::from(self.0)
    }
}

impl Default for StopSignal {
    fn default() -> Self {
        Self(15)
    }
}

impl TryFrom<u8> for StopSignal {
    type Error = Error;

    fn try_from(value: u8) -> Result<Self> {
        if (1..=31).contains(&value) {
            Ok(Self(value))
        } else {
            Err(Error::Invalid(
                "unsupported stop signal; use a Linux signal from 1 to 31",
            ))
        }
    }
}

impl From<StopSignal> for u8 {
    fn from(value: StopSignal) -> Self {
        value.0
    }
}

impl FromStr for StopSignal {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        let name = value.strip_prefix("SIG").unwrap_or(value);
        let signal = match name {
            "HUP" => 1,
            "INT" => 2,
            "QUIT" => 3,
            "ILL" => 4,
            "TRAP" => 5,
            "ABRT" | "IOT" => 6,
            "BUS" => 7,
            "FPE" => 8,
            "KILL" => 9,
            "USR1" => 10,
            "SEGV" => 11,
            "USR2" => 12,
            "PIPE" => 13,
            "ALRM" => 14,
            "TERM" => 15,
            "STKFLT" => 16,
            "CHLD" | "CLD" => 17,
            "CONT" => 18,
            "STOP" => 19,
            "TSTP" => 20,
            "TTIN" => 21,
            "TTOU" => 22,
            "URG" => 23,
            "XCPU" => 24,
            "XFSZ" => 25,
            "VTALRM" => 26,
            "PROF" => 27,
            "WINCH" => 28,
            "IO" | "POLL" => 29,
            "PWR" => 30,
            "SYS" => 31,
            _ => value
                .parse::<u8>()
                .map_err(|_| Error::Invalid("unsupported stop signal name or number"))?,
        };
        Self::try_from(signal)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ReadinessProbe {
    File { path: String },

    Http(HttpProbe),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HttpProbe {
    pub port: NonZeroU16,

    pub path: String,

    #[serde(default = "default_interval")]
    pub interval_ms: u64,

    #[serde(default = "default_timeout")]
    pub timeout_ms: u64,

    #[serde(default = "default_success")]
    pub success_threshold: u16,

    #[serde(default = "default_failure")]
    pub failure_threshold: u16,
}

fn default_interval() -> u64 {
    1_000
}

fn default_timeout() -> u64 {
    500
}

fn default_success() -> u16 {
    1
}

fn default_failure() -> u16 {
    3
}

impl ReadinessProbe {
    pub fn http(input: &str) -> Result<Self> {
        let (port, path) = input
            .split_once(':')
            .ok_or(Error::Invalid("HTTP readiness expects PORT:/path"))?;
        let probe = Self::Http(HttpProbe {
            port: port
                .parse()
                .map_err(|_| Error::Invalid("HTTP readiness port must be 1..65535"))?,
            path: path.into(),
            interval_ms: default_interval(),
            timeout_ms: default_timeout(),
            success_threshold: default_success(),
            failure_threshold: default_failure(),
        });
        probe.validate()?;
        Ok(probe)
    }

    pub fn validate(&self) -> Result<()> {
        match self {
            Self::File { path } => validate_path(path),
            Self::Http(probe) => probe.validate(),
        }
    }
}

impl HttpProbe {
    pub fn validate(&self) -> Result<()> {
        let path = &self.path;
        if !path.starts_with('/')
            || path.starts_with("//")
            || path.len() > MAX_HTTP_PATH_BYTES
            || path
                .bytes()
                .any(|byte| !byte.is_ascii_graphic() || byte == b'#')
        {
            return Err(Error::Invalid(
                "HTTP readiness requires an ASCII origin-form path of at most 2048 bytes, without spaces, fragments, or control characters",
            ));
        }

        if !(100..=60_000).contains(&self.interval_ms)
            || !(50..=5_000).contains(&self.timeout_ms)
            || self.timeout_ms > self.interval_ms
            || !(1..=10).contains(&self.success_threshold)
            || !(1..=10).contains(&self.failure_threshold)
        {
            return Err(Error::Invalid(
                "readiness requires interval 100..60000 ms, timeout 50..5000 ms no greater than interval, and thresholds 1..10",
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProcessSettings {
    pub working_directory: String,

    pub user: String,

    pub stop_signal: StopSignal,

    pub readiness: Option<ReadinessProbe>,
}

impl Default for ProcessSettings {
    fn default() -> Self {
        Self {
            working_directory: "/".to_owned(),
            user: "0".to_owned(),
            stop_signal: StopSignal::default(),
            readiness: None,
        }
    }
}

impl ProcessSettings {
    pub fn validate(&self) -> Result<()> {
        validate_path(&self.working_directory)?;
        validate_user(&self.user)?;
        if let Some(probe) = &self.readiness {
            probe.validate()?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ExecOverrides {
    pub user: Option<String>,

    pub working_directory: Option<String>,

    pub environment: BTreeMap<String, String>,
}

impl ExecOverrides {
    pub fn validate(&self) -> Result<()> {
        if let Some(user) = &self.user {
            validate_user(user)?;
        }

        if let Some(path) = &self.working_directory {
            validate_path(path)?;
        }
        Ok(())
    }
}

fn validate_path(path: &str) -> Result<()> {
    if !is_absolute(path.as_bytes()) {
        return Err(Error::Invalid(
            "process paths must be absolute guest paths of at most 4096 bytes",
        ));
    }
    Ok(())
}

fn validate_user(user: &str) -> Result<()> {
    let parts = user.split(':').collect::<Vec<_>>();
    if user.len() > MAX_USER_BYTES
        || parts.len() > 2
        || parts.iter().any(|part| {
            part.is_empty()
                || part.contains(['\0', '/', '\n', '\r'])
                || part.bytes().any(|byte| byte.is_ascii_whitespace())
                || (part.bytes().all(|byte| byte.is_ascii_digit())
                    && part.parse::<u32>().map_or(true, |id| id == u32::MAX))
        })
    {
        return Err(Error::Invalid(
            "user must be USER[:GROUP] with valid names or numeric IDs below 4294967295",
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::Result;

    #[test]
    fn test_readiness_accepts_only_bounded_loopback_http_paths_and_timing() -> Result {
        assert!(ReadinessProbe::http("8080:/health?check=ready").is_ok());
        for input in [
            "0:/health",
            "65536:/",
            "example.com:/",
            "80:http://other/",
            "80://other/",
            "80:/a\r\nInjected:x",
            "80:/a b",
            "80:/#fragment",
        ] {
            assert!(ReadinessProbe::http(input).is_err(), "{input:?}");
        }
        for input in [
            serde_json::json!({"kind":"http", "port":80,"path":"/", "interval_ms":99}),
            serde_json::json!({"kind":"http", "port":80,"path":"/", "timeout_ms":1001}),
            serde_json::json!({"kind":"http", "port":80,"path":"/", "failure_threshold":0}),
        ] {
            assert!(
                serde_json::from_value::<ReadinessProbe>(input)?
                    .validate()
                    .is_err()
            );
        }
        assert!(
            serde_json::from_value::<ReadinessProbe>(
                serde_json::json!({"kind":"http", "port":80,"path":"/","host":"169.254.169.254"})
            )
            .is_err()
        );
        Ok(())
    }

    #[test]
    fn test_validates_stop_signals_at_text_and_wire_boundaries() -> Result {
        assert_eq!("SIGUSR1".parse::<StopSignal>()?.number(), 10);
        assert_eq!("TERM".parse::<StopSignal>()?, "15".parse()?);
        for value in ["0", "32", "64", "-1", "SIGBOGUS"] {
            assert!(value.parse::<StopSignal>().is_err());
        }
        assert!(serde_json::from_str::<StopSignal>("255").is_err());
        Ok(())
    }

    #[test]
    fn test_rejects_invalid_user_ids_and_relative_working_directories() {
        for user in [
            "",
            ":0",
            "a:",
            "a:b:c",
            "4294967295",
            "a:4294967295",
            "a\nb",
        ] {
            assert!(
                ProcessSettings {
                    user: user.to_owned(),
                    ..Default::default()
                }
                .validate()
                .is_err()
            );
        }
        assert!(
            ProcessSettings {
                working_directory: "relative".to_owned(),
                ..Default::default()
            }
            .validate()
            .is_err()
        );
    }
}