Cotton code
445 lines · 15.5 KB · RustRaw
//! Putting a secret on a machine as a file (spec §7.2).//!//! A placement is a row saying *this secret belongs at this path on that//! machine*. The APPLIER is the half that runs on the machine the row names://! it opens the value with this Mac's own vault key, renders the bytes the file//! should hold, and writes them — atomically, at the mode the row asks for, and//! only when what is on disk is not already right.//!//! ## Four rules, each one a way this could go wrong//!//! **A path is `~/…` and nothing else.** Not an absolute path, not a `..`//! segment, not a bare name. A placement is a row that SYNCS — it arrives on//! this machine from somewhere else — so the path in it is untrusted input with//! a credential attached, and a row that could name `/etc/…` or climb out of//! the home directory is a way to write a password wherever the row's author//! liked. [`resolve`] is the one judge and it refuses rather than repairs.//!//! **The disk decides, not the row.** `applied_hash` records what was last//! written, but the SKIP is decided by hashing what the file actually holds://! a placement whose file somebody deleted comes back on the next pass, which//! is the whole point of having asked for it. A row's stamp can only ever be//! stale; the file cannot.//!//! **Write beside, chmod, then rename.** A half-written credential file that//! something reads at that moment is a build picking up half a token. The temp//! file is in the SAME directory so the rename is atomic (a cross-filesystem//! rename is a copy), and the mode is set BEFORE the rename so the file is//! never briefly world-readable under its real name.//!//! **A failure is a state this machine holds, never a retry.** The row is//! simply not stamped — see [`Outcome`] — and nothing here loops. A path that//! is refused is refused on every pass and stays refused until a person changes//! the row.//!//! ## The value never appears anywhere but the file//!//! No outcome, no refusal sentence and no error in this module carries the//! secret. `Failed` names the path and what the operating system said; it never//! names what was being written.use std::collections::BTreeSet;use std::fs;use std::io::Write;use std::path::{Path, PathBuf};use sha2::{Digest, Sha256};use cotton_core::vault::placement::{home_segments, is_env_name};pub use cotton_core::vault::placement::{Format, PathRefusal};/// One `cotton_secret_placements` row, as the applier reads it.////// `applied_hash` is carried so a pass can tell "already right AND already/// stamped" from "already right but never stamped" — the second still needs the/// row written back, or the page says *waiting* for ever about a file that is/// sitting there correct.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Placement {    pub id: String,    pub secret_id: String,    pub path: String,    pub mode: u32,    pub format: Format,    pub env_name: Option<String>,    pub applied_hash: Option<String>,}/// Why a value cannot be laid out the way the row asks.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum RenderRefusal {    /// `env` with no `NAME`. The DDL forbids it; a row from elsewhere might not.    NoEnvName,    /// A `NAME` that is not a shell environment name.    BadEnvName,    /// The value carries a newline and the format is one LINE. Writing it would    /// forge a second assignment in the file out of somebody's password.    ValueHasNewline,}impl RenderRefusal {    pub fn sentence(self) -> &'static str {        match self {            RenderRefusal::NoEnvName => "this placement is an env line with no name",            RenderRefusal::BadEnvName => {                "an env name is letters, digits and underscores, and never starts with a digit"            }            RenderRefusal::ValueHasNewline => {                "this value runs over more than one line, so it cannot be an env line"            }        }    }}/// What one placement did on this pass.////// The target Mac reports a failure sentence in `apply_problem` and clears/// the success stamps. Only the sentence syncs: values, hashes and file contents/// are never part of a problem. Applying clears that sentence again.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Outcome {    /// Written. The row wants `applied_at` and this `hash`.    Applied { id: String, hash: String },    /// The file already held exactly this, and the row already says so.    Unchanged { id: String },    /// The row asks for something this machine will not do. No retry helps.    Refused { id: String, sentence: String },    /// This machine tried and could not — a permission, a full disk, a value it    /// could not open. The next pass tries again.    Failed { id: String, sentence: String },}impl Outcome {    pub fn id(&self) -> &str {        match self {            Outcome::Applied { id, .. }            | Outcome::Unchanged { id }            | Outcome::Refused { id, .. }            | Outcome::Failed { id, .. } => id,        }    }    /// The sentence a person reads, or nothing when there is nothing wrong.    pub fn problem(&self) -> Option<&str> {        match self {            Outcome::Refused { sentence, .. } | Outcome::Failed { sentence, .. } => Some(sentence),            Outcome::Applied { .. } | Outcome::Unchanged { .. } => None,        }    }    /// The hash to stamp on the row, when this pass wrote one.    pub fn hash(&self) -> Option<&str> {        match self {            Outcome::Applied { hash, .. } => Some(hash),            _ => None,        }    }}/// Everything one pass did, in the order the rows were read.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Pass {    pub outcomes: Vec<Outcome>,}impl Pass {    /// How many files this pass actually wrote.    pub fn written(&self) -> usize {        self.outcomes            .iter()            .filter(|outcome| matches!(outcome, Outcome::Applied { .. }))            .count()    }    /// The placements that have something to say, by id.    pub fn problems(&self) -> Vec<(&str, &str)> {        self.outcomes            .iter()            .filter_map(|outcome| outcome.problem().map(|sentence| (outcome.id(), sentence)))            .collect()    }}/// Expand `~/…` against this machine's home, or say why not.////// PURE and exhaustively tested: this is the whole of "a placement cannot write/// outside your home folder", and every other rule in this module assumes it/// already ran.pub fn resolve(path: &str, home: &Path) -> Result<PathBuf, PathRefusal> {    let mut out = home.to_path_buf();    out.extend(home_segments(path)?);    Ok(out)}/// What the file should hold, given what it holds now.////// `existing` is the file's current contents, or `None` when there is no file./// For [`Format::Raw`] it is ignored — a raw placement OWNS its file. For/// [`Format::Env`] it is the whole point: the `NAME=` line is replaced where it/// stands and every other line is kept, byte for byte, including a comment/// above it and whatever a person put at the bottom.pub fn render(    format: Format,    env_name: Option<&str>,    value: &str,    existing: Option<&str>,) -> Result<Vec<u8>, RenderRefusal> {    match format {        Format::Raw => Ok(value.as_bytes().to_vec()),        Format::Env => {            let Some(name) = env_name else {                return Err(RenderRefusal::NoEnvName);            };            if !is_env_name(name) {                return Err(RenderRefusal::BadEnvName);            }            if value.contains('\n') || value.contains('\r') {                return Err(RenderRefusal::ValueHasNewline);            }            Ok(env_file(name, value, existing.unwrap_or_default()).into_bytes())        }    }}/// The env file, with one line replaced in place or appended.////// The trailing newline is normalised: a file this writes always ends in one,/// because a file that does not is a file whose next appended line joins the/// last.fn env_file(name: &str, value: &str, existing: &str) -> String {    let assignment = format!("{name}={value}");    let prefix = format!("{name}=");    let mut out = String::with_capacity(existing.len() + assignment.len() + 1);    let mut replaced = false;    for line in existing.split_inclusive('\n') {        let bare = line.strip_suffix('\n').unwrap_or(line);        let bare = bare.strip_suffix('\r').unwrap_or(bare);        // `export NAME=` counts: a person writing one is naming the same        // variable, and leaving it beside our line would be two answers in one        // file with the shell taking the second.        let names_it = bare            .trim_start()            .strip_prefix("export ")            .unwrap_or(bare.trim_start());        if names_it.starts_with(&prefix) && !replaced {            out.push_str(&assignment);            out.push('\n');            replaced = true;            continue;        }        if names_it.starts_with(&prefix) {            // A second line naming the same variable is dropped rather than            // left to win over the one just written.            continue;        }        out.push_str(bare);        out.push('\n');    }    if !replaced {        out.push_str(&assignment);        out.push('\n');    }    out}/// The sha256 of some bytes, lowercase hex — the spelling `applied_hash` holds.pub fn sha256_hex(bytes: &[u8]) -> String {    let mut hasher = Sha256::new();    hasher.update(bytes);    hex::encode(hasher.finalize())}/// Apply ONE placement, given the secret's primary field in the clear.////// The value is borrowed and never copied anywhere but into the bytes that go/// to disk.pub fn apply_one(placement: &Placement, value: &str, home: &Path) -> Outcome {    let target = match resolve(&placement.path, home) {        Ok(target) => target,        Err(refusal) => {            return Outcome::Refused {                id: placement.id.clone(),                sentence: refusal.sentence().to_string(),            }        }    };    // The existing contents matter only to `env`; reading a raw placement's    // file as UTF-8 would refuse a binary file we are about to overwrite whole.    let existing = match placement.format {        Format::Raw => None,        Format::Env => fs::read_to_string(&target).ok(),    };    let wanted = match render(        placement.format,        placement.env_name.as_deref(),        value,        existing.as_deref(),    ) {        Ok(bytes) => bytes,        Err(refusal) => {            return Outcome::Refused {                id: placement.id.clone(),                sentence: refusal.sentence().to_string(),            }        }    };    let hash = sha256_hex(&wanted);    // THE DISK DECIDES. A row stamped with this hash whose file is gone is a    // placement that has to be written again, and the row cannot tell us that.    let on_disk = fs::read(&target).ok();    if on_disk.as_deref() == Some(wanted.as_slice())        && placement.applied_hash.as_deref() == Some(hash.as_str())        && mode_of(&target) == Some(placement.mode)    {        return Outcome::Unchanged {            id: placement.id.clone(),        };    }    match write_atomically(&target, &wanted, placement.mode) {        Ok(()) => Outcome::Applied {            id: placement.id.clone(),            hash,        },        Err(sentence) => Outcome::Failed {            id: placement.id.clone(),            sentence,        },    }}/// Every placement addressed to this machine, in one pass.////// `open` is handed a secret id and answers its primary field, or `None` when/// the vault could not open it. The closure rather than a value is what keeps/// the master key out of this module entirely: nothing here can hold, log or/// answer with one.pub fn apply_all(    placements: &[Placement],    home: &Path,    open: &mut dyn FnMut(&str) -> Option<String>,) -> Pass {    let mut outcomes = Vec::with_capacity(placements.len());    for placement in placements {        match open(&placement.secret_id) {            Some(value) => outcomes.push(apply_one(placement, &value, home)),            None => outcomes.push(Outcome::Failed {                id: placement.id.clone(),                sentence: "this Mac could not open the value for this placement".to_string(),            }),        }    }    Pass { outcomes }}/// The file's permission bits, or nothing when it is not there.fn mode_of(path: &Path) -> Option<u32> {    #[cfg(unix)]    {        use std::os::unix::fs::PermissionsExt;        Some(fs::metadata(path).ok()?.permissions().mode() & 0o777)    }    #[cfg(not(unix))]    {        let _ = path;        None    }}/// Write beside, chmod, rename over. Never in that order rearranged.fn write_atomically(target: &Path, bytes: &[u8], mode: u32) -> Result<(), String> {    let Some(parent) = target.parent() else {        return Err("this path has no folder to write into".to_string());    };    make_parents(parent)?;    // The temp name is this pass's, in the SAME directory: a rename across    // filesystems is a copy, and a copy is the torn write this avoids.    let temporary = parent.join(format!(        ".{}.cotton-placement",        target            .file_name()            .and_then(|name| name.to_str())            .unwrap_or("placement")    ));    let write = || -> std::io::Result<()> {        let mut file = fs::File::create(&temporary)?;        set_mode(&file, mode)?;        file.write_all(bytes)?;        file.sync_all()?;        Ok(())    };    if let Err(error) = write() {        let _ = fs::remove_file(&temporary);        return Err(format!("this Mac could not write the file: {error}"));    }    if let Err(error) = fs::rename(&temporary, target) {        let _ = fs::remove_file(&temporary);        return Err(format!("this Mac could not put the file in place: {error}"));    }    Ok(())}/// Every missing parent, at 0700 — a credential's folder is nobody else's.////// An EXISTING folder is left exactly as it is: a placement in `~/.config` does/// not get to decide what `~/.config` is readable by.fn make_parents(parent: &Path) -> Result<(), String> {    let mut missing: Vec<&Path> = Vec::new();    let mut walk = Some(parent);    while let Some(directory) = walk {        if directory.exists() {            break;        }        missing.push(directory);        walk = directory.parent();    }    // Deepest last: created outermost first, and the set keeps a repeated path    // from being made twice on a strange tree.    let mut made: BTreeSet<PathBuf> = BTreeSet::new();    for directory in missing.into_iter().rev() {        if !made.insert(directory.to_path_buf()) {            continue;        }        fs::create_dir(directory)            .map_err(|error| format!("this Mac could not make the folder: {error}"))?;        set_directory_mode(directory)?;    }    Ok(())}fn set_mode(file: &fs::File, mode: u32) -> std::io::Result<()> {    #[cfg(unix)]    {        use std::os::unix::fs::PermissionsExt;        file.set_permissions(fs::Permissions::from_mode(mode))    }    #[cfg(not(unix))]    {        let _ = (file, mode);        Ok(())    }}fn set_directory_mode(directory: &Path) -> Result<(), String> {    #[cfg(unix)]    {        use std::os::unix::fs::PermissionsExt;        fs::set_permissions(directory, fs::Permissions::from_mode(0o700))            .map_err(|error| format!("this Mac could not set the folder's mode: {error}"))    }    #[cfg(not(unix))]    {        let _ = directory;        Ok(())    }}#[cfg(test)]#[path = "placements_tests.rs"]mod tests;