capsid-protocol 0.1.0-alpha.1

Versioned, size-bounded messages between the Capsid host and its guest agent.
Documentation
pub const MAX_BYTES: usize = 4096;

pub const MAX_COMPONENT_BYTES: usize = 255;

pub fn is_absolute(path: &[u8]) -> bool {
    path.starts_with(b"/") && path.len() <= MAX_BYTES && !path.contains(&0)
}

// One name within a directory: never empty, `.`, or `..`, and free of `/` and
// NUL bytes.
pub fn is_component(name: &[u8]) -> bool {
    !name.is_empty()
        && name.len() <= MAX_COMPONENT_BYTES
        && !name.contains(&0)
        && !name.contains(&b'/')
        && !matches!(name, b"." | b"..")
}

// A guest path the host may mount or publish onto: absolute, below the root,
// made of normal components without control characters, and outside every
// reserved tree.
pub fn is_guest_target(target: &str, reserved: &[&str]) -> bool {
    let Some(relative) = target.strip_prefix('/') else {
        return false;
    };
    is_absolute(target.as_bytes())
        && !relative.is_empty()
        && relative
            .split('/')
            .all(|component| is_component(component.as_bytes()))
        && !target.chars().any(char::is_control)
        && !reserved.iter().any(|reserved| overlap(reserved, target))
}

pub fn overlap(left: &str, right: &str) -> bool {
    left == right
        || left
            .strip_prefix(right)
            .is_some_and(|suffix| suffix.starts_with('/'))
        || right
            .strip_prefix(left)
            .is_some_and(|suffix| suffix.starts_with('/'))
}

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

    #[test]
    fn test_an_absolute_path_is_bounded_and_free_of_nul_bytes() {
        assert!(is_absolute(b"/srv/data"));
        assert!(!is_absolute(b"srv/data"));
        assert!(!is_absolute(b"/srv\0data"));
        assert!(is_absolute(&[b'/'; MAX_BYTES]));
        assert!(!is_absolute(&[b'/'; MAX_BYTES + 1]));
    }

    #[test]
    fn test_guest_targets_reject_reserved_trees_traversal_and_the_root() {
        let reserved = ["/proc", "/run/capsid"];
        for target in [
            "/",
            "relative",
            "/proc/x",
            "/run",
            "/run/capsid/x",
            "/a/../b",
            "/a/./b",
            "/a//b",
            "/a/\u{7}",
        ] {
            assert!(!is_guest_target(target, &reserved), "{target}");
        }
        assert!(is_guest_target("/run/other", &reserved));
        assert!(!is_guest_target(
            &format!("/{}", "a".repeat(MAX_COMPONENT_BYTES + 1)),
            &reserved
        ));
    }

    #[test]
    fn test_paths_overlap_only_at_component_boundaries() {
        assert!(overlap("/data", "/data"));
        assert!(overlap("/data", "/data/cache"));
        assert!(overlap("/data/cache", "/data"));
        assert!(!overlap("/data", "/database"));
        assert!(!overlap("/data/a", "/data/b"));
    }
}