Cotton code
187 lines · 6.5 KB · RustRaw
//! What a placement row may say, judged the same way on every device.//!//! A placement (`cotton_secret_placements`) is *this secret belongs at this path//! on that Mac*. The phone writes one (Passwords › a secret › Put on a Mac), an//! approved migration list writes many, and the Mac the row names applies it//! (`cotton_client::vault::placements`). All three judge the request HERE, so a//! row the phone accepted is a row the Mac will write, and a path the Mac would//! refuse is refused under the field before it ever syncs.//!//! Pure: no filesystem, no clock, no database. Resolving `~/` against a real//! home is the applier's half and stays on the Mac.use serde_json::Value;/// How the bytes are laid out in the file.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Format {    /// The primary field's bytes and nothing else — **no trailing newline.**    /// A file read with `$(cat …)` into a header must not carry one.    Raw,    /// One `NAME=value` line inside a file that may hold others.    Env,}impl Format {    /// The spelling the row carries. `None` for anything else — the DDL's CHECK    /// makes that impossible on a row this machine wrote, and a row from a    /// future build is refused rather than guessed at.    pub fn parse(text: &str) -> Option<Format> {        match text {            "raw" => Some(Format::Raw),            "env" => Some(Format::Env),            _ => None,        }    }    pub fn as_str(self) -> &'static str {        match self {            Format::Raw => "raw",            Format::Env => "env",        }    }}/// Why a path is not one a Mac will write to.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PathRefusal {    /// It does not begin `~/`.    NotInHome,    /// A `..` segment — the one way a `~/` path can still leave the home.    ClimbsOut,    /// `~/` and nothing after it, or a segment that is empty or `.`.    NoName,}impl PathRefusal {    /// What a person reads on the placement. Plain words, and never the value.    pub fn sentence(self) -> &'static str {        match self {            PathRefusal::NotInHome => {                "this path is not in your home folder — a placement starts with ~/"            }            PathRefusal::ClimbsOut => "this path climbs out of your home folder with ..",            PathRefusal::NoName => "this path does not name a file",        }    }}/// The segments of a `~/…` path under the home, or why it is not one.////// This is the whole of "a placement cannot write outside your home folder";/// the applier joins these onto its home and every other rule assumes this ran.pub fn home_segments(path: &str) -> Result<Vec<&str>, PathRefusal> {    let Some(rest) = path.strip_prefix("~/") else {        return Err(PathRefusal::NotInHome);    };    if rest.is_empty() {        return Err(PathRefusal::NoName);    }    let mut segments = Vec::new();    for segment in rest.split('/') {        if segment == ".." {            return Err(PathRefusal::ClimbsOut);        }        if segment.is_empty() || segment == "." {            return Err(PathRefusal::NoName);        }        segments.push(segment);    }    Ok(segments)}/// Is this a name a shell would accept as an environment variable?pub fn is_env_name(name: &str) -> bool {    let mut characters = name.chars();    let Some(first) = characters.next() else {        return false;    };    if !(first.is_ascii_alphabetic() || first == '_') {        return false;    }    characters.all(|character| character.is_ascii_alphanumeric() || character == '_')}/// One placement as a caller asks for it, already judged.#[derive(Debug, Clone, PartialEq, Eq)]pub struct PlacementRequest {    pub secret_id: String,    /// The Mac's registry id — the one `devices.list` answers.    pub device_id: String,    pub path: String,    pub format: Format,    pub env_name: Option<String>,    pub mode: i64,}impl PlacementRequest {    /// Read `{secretId, deviceId, path, format?, envName?, mode?}` — the shape    /// the phone sends and a migration list carries — or say what is wrong in    /// a sentence a person can act on.    pub fn from_json(request: &Value) -> Result<PlacementRequest, String> {        let text = |key: &str| {            request                .get(key)                .and_then(Value::as_str)                .map(str::trim)                .filter(|value| !value.is_empty())                .map(str::to_string)                .ok_or_else(|| format!("`{key}` is required"))        };        let secret_id = text("secretId")?;        let device_id = text("deviceId")?;        let path = text("path")?;        let format = Format::parse(            request                .get("format")                .and_then(Value::as_str)                .unwrap_or("raw"),        )        .ok_or_else(|| "`format` is `raw` or `env`".to_string())?;        let env_name = request            .get("envName")            .and_then(Value::as_str)            .map(str::trim)            .filter(|name| !name.is_empty())            .map(str::to_string);        let mode = match request.get("mode") {            None | Some(Value::Null) => 0o600,            Some(value) => value                .as_i64()                .filter(|mode| (0..=0o777).contains(mode))                .ok_or_else(|| "`mode` is a Unix mode between 0 and 511".to_string())?,        };        home_segments(&path).map_err(|refusal| refusal.sentence().to_string())?;        match (format, &env_name) {            (Format::Env, None) => return Err("an env placement needs the NAME it writes".into()),            (Format::Env, Some(name)) if !is_env_name(name) => {                return Err(                    "an env name is letters, digits and underscores, and never starts with a digit"                        .into(),                )            }            (Format::Raw, Some(_)) => {                return Err("a raw placement is the whole file and has no name".into())            }            _ => {}        }        Ok(PlacementRequest {            secret_id,            device_id,            path,            format,            env_name,            mode,        })    }}#[cfg(test)]#[path = "placement_tests.rs"]mod tests;/// The same sentence on a device row and under a secret's "On your Macs"./// `name` is the secret's public label; `sentence` is the target Mac's outcome.pub fn problem_line(name: &str, sentence: &str) -> String {    format!("Can't put {name} on this Mac · {sentence}")}