Cotton code
139 lines · 6.2 KB · RustRaw
//! The optional live read on a generic record page. Definitions name a read;//! only this core authorizes and binds it before an engine is invoked.use crate::definitions::{TableDefinition, LIVE_READ_METHODS};use super::Data;use serde::{Deserialize, Serialize};use serde_json::Value;/// Why a live read is refused, as a typed fact; said in the database's/// `refusal` lines (`records.live.*`). `Definition` and `Engine` carry the/// definition's and the engine's own refusals through.#[derive(Debug, Clone, PartialEq, Eq)]pub enum LiveRefusal {    NotReadOnly { method: String },    Needs { field: String },    Definition(String),    Engine(String),}impl LiveRefusal {    /// The refusal in `rows`' words, the kit's for a line they have none of.    #[must_use]    pub fn say(&self, rows: &[crate::rules::shell_lines::LineRow]) -> String {        let (line, fills): (&str, Vec<(&str, &str)>) = match self {            LiveRefusal::NotReadOnly { method } => ("not_read_only", vec![("method", method)]),            LiveRefusal::Needs { field } => ("needs", vec![("field", field)]),            LiveRefusal::Definition(said) | LiveRefusal::Engine(said) => return said.clone(),        };        crate::rules::shell_lines::resolve("refusal", &format!("records.live.{line}"), rows, &fills)            .unwrap_or_else(|| format!("refusal.records.live.{line}"))    }}impl std::fmt::Display for LiveRefusal {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(&self.say(&[]))    }}#[derive(Debug, Serialize, Deserialize)]pub struct LiveAnswer {    pub data: Data,    pub live: Vec<String>,}/// Called once at the top of a page, separately from its stored record read./// Recheck the allowlist here even when the definition was already validated:/// a synced or newer definition is data, not authority to execute a write.pub fn read(    definition: &TableDefinition,    id: &str,    stored: &Data,    engine: impl FnOnce(&str, &Data) -> Result<Data, String>,) -> Result<LiveAnswer, LiveRefusal> {    let Some(read) = &definition.live_read else {        return Ok(LiveAnswer { data: Data::new(), live: Vec::new() });    };    if !LIVE_READ_METHODS.contains(&read.method.as_str()) {        return Err(LiveRefusal::NotReadOnly { method: read.method.clone() });    }    definition.validate().map_err(|e| LiveRefusal::Definition(e.to_string()))?;    let mut args = Data::new();    for (argument, field) in read.bindings.iter() {        let value = if field == "$id" { Value::from(id) } else {            stored.get(field).cloned().ok_or_else(|| LiveRefusal::Needs { field: field.clone() })?        };        args.insert(argument.clone(), value);    }    let answer = engine(&read.method, &args).map_err(LiveRefusal::Engine)?;    let data = read.fields.iter().filter_map(|field| answer.get(field).cloned().map(|value| (field.clone(), value))).collect();    Ok(LiveAnswer { data, live: read.fields.clone() })}#[cfg(test)]mod tests {    use super::*;    /// A table with one live fact over the `devices` engine, the shape a    /// device page reads its live facts through.    fn device() -> crate::definitions::TableDefinition {        crate::definitions::TableDefinition::from_json(r#"{"id":"device","name":"Device","plural":"Devices","builtin":true,"engine":"devices",            "columns":[{"key":"name","type":"text","required":true},{"key":"notify","type":"bool"},                {"key":"changes_waiting","type":"number","readonly":true,"live":true}],            "title":"name","slip":{"title":"name"},"tile":{"face":"slip-list"},            "page":[{"heading":null,"columns":["name","notify","changes_waiting"]}],            "live_read":{"method":"device.facts","bindings":{"deviceId":"$id"},"fields":["changes_waiting"]}}"#).unwrap()    }    /// RULE: The live overlay owns readonly facts. Editable native settings    /// come from records.get, so definition edits cannot give an overlay a    /// second source of truth for a switch while its pick sheet is open.    #[test]    fn an_editable_setting_cannot_be_a_live_overlay_field() {        let mut definition = device();        definition.live_read.as_mut().unwrap().fields = vec!["notify".into()];        assert!(definition.validate().is_err());        let mut called = false;        assert!(read(&definition, "synthetic:phone", &Data::new(), |_, _| {            called = true;            Ok(Data::new())        }).is_err());        assert!(!called);    }    /// RULE: A live read cannot open a write from editable definition data; validation and call-time authorization both refuse it before the engine can mutate anything.    #[test]    fn a_write_method_never_reaches_the_engine() {        for method in ["device.setHost", "storage.setMacFiles", "records.update", "devices.revoke"] {            let mut definition = device();            definition.live_read.as_mut().unwrap().method = method.into();            assert!(definition.validate().is_err());            let mut state = serde_json::json!({"stayAwake":true});            let before = state.clone();            let result = read(&definition, "synthetic:mac", &Data::new(), |_, _| {                state["stayAwake"] = Value::Bool(false);                Ok(Data::new())            });            assert!(result.is_err());            assert_eq!(state, before, "opening a page cannot run {method}");        }    }    /// RULE: One top-level live read binds the record id in core and returns only its declared fields, so page internals cannot fan out or disclose unrelated engine facts.    #[test]    fn one_read_binds_the_id_and_limits_the_answer() {        let definition = device();        let mut calls = 0;        let answer = read(&definition, "synthetic:mac", &Data::new(), |method, args| {            calls += 1;            assert_eq!(method, "device.facts");            assert_eq!(args["deviceId"], "synthetic:mac");            Ok(Data::from_iter([("changes_waiting".into(), Value::from(3)), ("unrelated".into(), Value::from("private"))]))        }).unwrap();        assert_eq!(calls, 1);        assert_eq!(answer.data["changes_waiting"], 3);        assert!(!answer.data.contains_key("unrelated"));        assert!(answer.live.contains(&"changes_waiting".to_string()));    }}