capsid-protocol 0.1.0-alpha.1

Versioned, size-bounded messages between the Capsid host and its guest agent.
Documentation
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{
    AttemptId, Error, InstanceId, Result, WorkspaceAttachmentId, WorkspaceGrantId, WorkspaceId,
};

pub const MAX_MOUNTS: usize = 64;

pub const MAX_WORKSPACES: usize = 512;

pub const MAX_SESSIONS: usize = 128;

pub const MAX_NEW_GRANTS: usize = 4096;

pub const MAX_GRANTS: usize = 2 * MAX_NEW_GRANTS;

pub const GUEST_ROOT: &str = "/workspaces";

pub const MIN_STORAGE_UID: u32 = 1_000_000;

pub const MAX_STORAGE_UID: u32 = i32::MAX as u32;

pub fn is_storage_uid(uid: u32) -> bool {
    (MIN_STORAGE_UID..=MAX_STORAGE_UID).contains(&uid)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RequiredMount {
    pub attachment: WorkspaceAttachmentId,

    pub target: String,

    pub access: Access,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Mount {
    pub attachment: WorkspaceAttachmentId,

    pub grant: WorkspaceGrantId,

    pub generation: u64,

    pub target: String,

    pub access: Access,

    pub user: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ClientRequest {
    pub version: u32,

    pub attachment: WorkspaceAttachmentId,

    pub grant: WorkspaceGrantId,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MountState {
    Mounting,

    Mounted,

    Busy,

    Detaching,

    Failed,

    Detached,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MountStatus {
    pub binding: Mount,

    pub state: MountState,

    pub message: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GrantSpec {
    pub workspace: WorkspaceId,

    pub attachment: WorkspaceAttachmentId,

    pub id: WorkspaceGrantId,

    pub generation: u64,

    pub instance: InstanceId,

    pub attempt: AttemptId,

    pub storage_attempt: AttemptId,

    pub access: Access,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum StorageAction {
    Hello,

    Create {
        workspace: WorkspaceId,

        uid: u32,

        quota: Quota,
    },

    Inspect {
        workspace: WorkspaceId,
    },

    Delete {
        workspace: WorkspaceId,

        uid: u32,

        quota: Quota,
    },

    Grant {
        grant: GrantSpec,
    },

    Revoke {
        grant: GrantSpec,
    },

    GrantStatus {
        grant: WorkspaceGrantId,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StorageRequest {
    pub version: u32,

    pub storage_attempt: AttemptId,

    pub action: StorageAction,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StorageState {
    Creating,

    Ready,

    Deleting,

    Removed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StorageGrantState {
    Active,

    Revoking,

    Revoked,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GrantStatus {
    pub spec: GrantSpec,

    pub state: StorageGrantState,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum StorageResult {
    Hello {
        boot: Uuid,

        capacity_bytes: u64,
    },

    Workspace {
        workspace: WorkspaceId,

        uid: u32,

        quota: Quota,

        state: StorageState,

        bytes: u64,

        inodes: u64,
    },

    Grant {
        grant: GrantStatus,
    },

    Error {
        message: String,
    },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StorageResponse {
    pub version: u32,

    pub storage_attempt: AttemptId,

    pub result: StorageResult,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DataRequest {
    pub version: u32,

    pub storage_attempt: AttemptId,

    pub grant: WorkspaceGrantId,

    pub attempt: AttemptId,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum DataResponse {
    Connected { grant: WorkspaceGrantId },

    Error { message: String },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Access {
    ReadOnly,

    ReadWrite,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Quota {
    pub bytes: u64,

    pub inodes: u64,
}

impl Quota {
    pub fn validate(&self) -> Result<()> {
        if !(64 * 1024..=256 * 1024 * 1024).contains(&self.bytes)
            || !self.bytes.is_multiple_of(4096)
            || !(16..=65536).contains(&self.inodes)
        {
            return Err(Error::Invalid(
                "workspace quota requires 64 KiB to 256 MiB in whole 4 KiB blocks and 16 to 65536 inodes",
            ));
        }
        Ok(())
    }
}

pub fn validate_target(target: &str) -> Result<()> {
    let valid = target_path(target).is_some_and(|tail| {
        !tail.is_empty()
            && tail.split('/').count() <= 8
            && tail.split('/').all(|part| {
                !part.is_empty()
                    && part != "."
                    && part != ".."
                    && part != ".capsid"
                    && part.len() <= 128
                    && part
                        .bytes()
                        .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
            })
    });
    if !valid || target.len() > 1024 {
        return Err(Error::Invalid(
            "workspace target must be a normal path below /workspaces with at most eight components",
        ));
    }
    Ok(())
}

pub fn target_path(target: &str) -> Option<&str> {
    target
        .strip_prefix(GUEST_ROOT)
        .and_then(|tail| tail.strip_prefix('/'))
}

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

    #[test]
    fn test_targets_stay_below_the_reserved_directory() {
        for target in [
            "/workspaces/a",
            "/workspaces/a/results",
            "/workspaces/result-1",
        ] {
            assert!(validate_target(target).is_ok(), "{target}");
        }
        for target in [
            "/workspaces",
            "/workspaces/",
            "/workspaces//a",
            "/workspaces/a/../b",
            "/workspaces/./a",
            "/workspaces/.capsid/a",
            "/dev/a",
            "/workspaces/a\n",
        ] {
            assert!(validate_target(target).is_err(), "{target:?}");
        }
        assert!(crate::path::overlap(
            "/workspaces/a",
            "/workspaces/a/result"
        ));
        assert!(!crate::path::overlap("/workspaces/a", "/workspaces/ab"));
    }
}