revault_lockbox_api 0.0.48

reVault lockbox API to create and manage lockboxes
Documentation
//! Read-only Linux observations for test-only extraction experiments.
//! Device counters are host-global; they do not attribute I/O to this process.
use serde_json::{json, Value};
use std::fs;

pub(super) fn setting(name: &str) -> Option<String> {
    match std::env::var(name) {
        Ok(value) => Some(value),
        Err(std::env::VarError::NotPresent) => None,
        Err(error) => panic!("invalid {name}: {error}"),
    }
}
pub(super) fn parity(value: Option<&str>) -> Result<Option<u32>, &'static str> {
    match value {
        None => Ok(None),
        Some("0") => Ok(Some(0)),
        Some("1") => Ok(Some(1)),
        _ => Err("REVAULT_EXTRACT_TID_PARITY must be 0 or 1"),
    }
}
pub(super) fn devices(value: Option<&str>) -> Result<Vec<String>, &'static str> {
    let Some(value) = value else {
        return Ok(Vec::new());
    };
    let names: Vec<_> = value.split(',').collect();
    if names.is_empty()
        || names.len() > 4
        || names.iter().any(|name| {
            name.is_empty()
                || name.len() > 64
                || !name
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
        })
    {
        return Err(
            "REVAULT_EXTRACT_BLOCK_DEVICES requires 1..4 comma-separated block-device names",
        );
    }
    let mut result = Vec::new();
    for name in names {
        if result.iter().any(|other| other == name) {
            return Err("duplicate block device");
        }
        result.push(name.to_owned());
    }
    Ok(result)
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct ReaderIdentity {
    process: u32,
    tid: u32,
    namespace_tids: Vec<u32>,
    namespace: Option<String>,
}
impl ReaderIdentity {
    fn parse(process: u32, link: &str, status: &str, namespace: Option<String>) -> Option<Self> {
        let fields: Vec<_> = link.split('/').collect();
        if fields.len() != 3 || fields[0].parse::<u32>().ok()? != process || fields[1] != "task" {
            return None;
        }
        let tid = fields[2].parse::<u32>().ok()?;
        let line = status
            .lines()
            .find_map(|line| line.strip_prefix("NSpid:"))?;
        let namespace_tids: Vec<u32> = line
            .split_whitespace()
            .map(str::parse)
            .collect::<Result<_, _>>()
            .ok()?;
        if process == 0
            || tid == 0
            || namespace_tids.first().copied()? != tid
            || namespace_tids.contains(&0)
        {
            return None;
        }
        Some(Self {
            process,
            tid,
            namespace_tids,
            namespace,
        })
    }
    fn now() -> Option<Self> {
        Self::parse(
            std::process::id(),
            fs::read_link("/proc/thread-self").ok()?.to_str()?,
            &fs::read_to_string("/proc/thread-self/status").ok()?,
            fs::read_link("/proc/self/ns/pid")
                .ok()
                .map(|path| path.to_string_lossy().into_owned()),
        )
    }
    fn json(&self) -> Value {
        json!({"process_id":self.process,"reader_tid":self.tid,
        "reader_tid_parity":self.tid % 2,"namespace_tids":self.namespace_tids,"pid_namespace":self.namespace,
        "scope":"IDs visible in this procfs mount; not proof of host-kernel task ID or physical mirror"})
    }
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct BlockStat {
    reads: u64,
    writes: u64,
}
impl BlockStat {
    fn parse(text: &str) -> Option<Self> {
        let fields: Vec<u64> = text
            .split_whitespace()
            .map(str::parse)
            .collect::<Result<_, _>>()
            .ok()?;
        if fields.len() < 11 {
            return None;
        }
        Some(Self {
            reads: fields[2],
            writes: fields[6],
        })
    }
    fn now(name: &str) -> Option<Self> {
        Self::parse(&fs::read_to_string(format!("/sys/class/block/{name}/stat")).ok()?)
    }
    fn delta(&self, before: &Self) -> Option<Value> {
        Some(json!({"read_sectors":self.reads.checked_sub(before.reads)?,
            "write_sectors":self.writes.checked_sub(before.writes)?,"sector_bytes":512}))
    }
}
pub(super) struct Observation {
    pub(super) identity: Option<ReaderIdentity>,
    pub(super) desired: Option<u32>,
    names: Vec<String>,
    expected_namespace: Option<String>,
}
impl Observation {
    pub(super) fn environment() -> Self {
        Self {
            identity: ReaderIdentity::now(),
            desired: parity(setting("REVAULT_EXTRACT_TID_PARITY").as_deref()).unwrap(),
            names: devices(setting("REVAULT_EXTRACT_BLOCK_DEVICES").as_deref()).unwrap(),
            expected_namespace: setting("REVAULT_EXTRACT_PID_NAMESPACE"),
        }
    }
    #[cfg(test)]
    #[allow(dead_code)]
    pub(super) fn unconfigured() -> Self {
        Self {
            identity: ReaderIdentity::now(),
            desired: None,
            names: Vec::new(),
            expected_namespace: None,
        }
    }
    pub(super) fn admission_skip(&self) -> Option<Value> {
        let desired = self.desired?;
        let reason = match self.identity.as_ref() {
            None => "reader_identity_unavailable",
            Some(identity)
                if self
                    .expected_namespace
                    .as_ref()
                    .is_some_and(|expected| identity.namespace.as_ref() != Some(expected)) =>
            {
                "pid_namespace_mismatch"
            }
            Some(identity) if identity.namespace_tids.len() != 1 => "nested_pid_namespace",
            Some(identity) if identity.tid % 2 != desired => "reader_tid_parity_mismatch",
            Some(_) => return None,
        };
        Some(json!({"kind":"extraction_admission_skip","reason":reason,
            "requested_reader_tid_parity":desired,"reader_identity":self.identity_json(),
            "archive_opened":false,"output_created":false,"verified":false}))
    }
    pub(super) fn identity_json(&self) -> Value {
        self.identity
            .as_ref()
            .map(ReaderIdentity::json)
            .unwrap_or(Value::Null)
    }
    pub(super) fn snapshot(&self) -> Vec<Option<BlockStat>> {
        self.names.iter().map(|name| BlockStat::now(name)).collect()
    }
    pub(super) fn finish(&self, before: &[Option<BlockStat>]) -> Value {
        let after = self.snapshot();
        let entries: Vec<_> = self
            .names
            .iter()
            .zip(before)
            .zip(&after)
            .map(|((name, before), after)| {
                let delta = after
                    .as_ref()
                    .zip(before.as_ref())
                    .and_then(|(after, before)| after.delta(before));
                json!({"device":name,"delta":delta})
            })
            .collect();
        json!({"devices":entries,"scope":"global block-device counters around extraction, before output verification; includes unrelated host I/O; sector unit 512 bytes"})
    }
}
#[cfg(test)]
#[allow(dead_code)]
mod tests {
    // The harness=false benchmark includes this module without its test bodies.
    #[allow(unused_imports)]
    use super::*;
    #[test]
    fn identity_and_strict_parity_are_checked() {
        let identity =
            ReaderIdentity::parse(42, "42/task/45", "NSpid:\t45\n", Some("pid:[test]".into()))
                .unwrap();
        assert_eq!(identity.tid, 45);
        assert!(ReaderIdentity::parse(43, "42/task/45", "NSpid: 45", None).is_none());
        assert!(ReaderIdentity::parse(42, "42/task/45", "NSpid: 46", None).is_none());
        assert_eq!(parity(None), Ok(None));
        assert_eq!(parity(Some("0")), Ok(Some(0)));
        assert_eq!(parity(Some("1")), Ok(Some(1)));
        for value in ["", "2", "even", " 0"] {
            assert!(parity(Some(value)).is_err());
        }
        let mut observation = Observation {
            identity: Some(identity),
            desired: Some(0),
            names: Vec::new(),
            expected_namespace: None,
        };
        assert_eq!(
            observation.admission_skip().unwrap()["reason"],
            "reader_tid_parity_mismatch"
        );
        observation.desired = Some(1);
        assert!(observation.admission_skip().is_none());
        observation.expected_namespace = Some("pid:[other]".into());
        assert_eq!(
            observation.admission_skip().unwrap()["reason"],
            "pid_namespace_mismatch"
        );
        observation.identity = None;
        assert_eq!(
            observation.admission_skip().unwrap()["reason"],
            "reader_identity_unavailable"
        );
    }
    #[test]
    fn device_names_and_counter_deltas_are_bounded() {
        assert_eq!(devices(Some("nvme0n1,nvme1n1")).unwrap().len(), 2);
        for value in ["", "../stat", "a/b", "a,a", "a,b,c,d,e", "a, b"] {
            assert!(devices(Some(value)).is_err());
        }
        let before = BlockStat::parse("1 2 3 4 5 6 7 8 9 10 11").unwrap();
        let after = BlockStat {
            reads: 9,
            writes: 10,
        };
        assert_eq!(after.delta(&before).unwrap()["read_sectors"], 6);
        assert_eq!(after.delta(&before).unwrap()["write_sectors"], 3);
        assert!(before.delta(&after).is_none());
        assert!(BlockStat::parse("1 2 x 4 5 6 7 8 9 10 11").is_none());
        assert!(BlockStat::parse("1 2 3").is_none());
    }
}