Cotton code
255 lines · 9.5 KB · RustRaw
//! One admission vocabulary for the mover, stored rows and the exchange.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum DeviceScope {    Full,    Runner,    Reader,}/// The only allowed (scope, takes_placements) pairs. The grant belongs only to/// a runner; full devices already receive their database and apply placements.pub const DEVICE_ADMISSIONS: &[(DeviceScope, &str, bool)] = &[    (DeviceScope::Full, "full", false),    (DeviceScope::Runner, "runner", false),    (DeviceScope::Runner, "runner", true),    (DeviceScope::Reader, "reader", false),];/// The same refusal reaches local writers, sync peers and HTTP callers.pub const READER_WRITE_REFUSAL: &str = "this device can only read; it cannot make changes";/// Read the newest approval, using the same ordering as device authentication./// Missing rows remain full for an existing unpaired file; unknown values fail closed.pub fn scope_of(db: &crate::Driver, device_id: &str) -> crate::Result<DeviceScope> {    let row = db.get(        "SELECT scope, takes_placements FROM cotton_devices WHERE device_id = ? \         ORDER BY (revoked_at IS NULL) DESC, approved_at DESC, id ASC LIMIT 1",        &[rusqlite::types::Value::Text(device_id.into())],    )?;    DeviceScope::from_pair(        row.as_ref().and_then(|r| r.text("scope")),        row.as_ref().and_then(|r| r.int("takes_placements")),    )    .map(|a| a.scope)    .map_err(crate::StoreError::refused)}pub fn require_write(db: &crate::Driver, device_id: &str) -> crate::Result<()> {    scope_of(db, device_id)?.require_write()}/// Every local mint checks the actual signer and any owner/member on whose/// behalf the server writes. A replica may additionally bind its persisted/// role before it receives its own device row in a partial snapshot.pub(crate) fn require_local_write(    db: &crate::Driver,    actor: &crate::actor::Actor,) -> crate::Result<()> {    db.batch_fact(&format!("local_write {}", actor.to_wire()), || read_local_write(db, actor))}fn read_local_write(db: &crate::Driver, actor: &crate::actor::Actor) -> crate::Result<()> {    if let Some(scope) = db.device_scope() {        scope.require_write()?;    }    if let Some(signer) = db.signer() {        require_write(db, &signer.device_key())?;    } else if let Some(row) = db.get("SELECT device_id FROM _meta LIMIT 1", &[])? {        if let Some(key) = row.text("device_id") {            require_write(db, key)?;        }    }    require_local_actor_write(db, actor)}/// An author's first fact carries its device key; later receipts resolve it/// from that fact. Even a direct call to the fold cannot let a reader write.pub(crate) fn receipt_refusal(    db: &crate::Driver,    receipt: &crate::canonical::Receipt,) -> crate::Result<Option<String>> {    let key = if receipt.table == "cotton_authors" {        receipt            .fields            .get("device_id")            .and_then(serde_json::Value::as_str)            .map(str::to_owned)    } else {        db.get(            "SELECT device_id FROM cotton_authors WHERE id = ?",            &[rusqlite::types::Value::Text(receipt.author.clone())],        )?        .and_then(|r| r.text("device_id").map(str::to_owned))    };    if let Some(key) = key {        if scope_of(db, &key)? == DeviceScope::Reader {            return Ok(Some(READER_WRITE_REFUSAL.into()));        }    }    // Also covers a rejected first author fact followed by the rest of its    // batch: its owner actor cannot turn that into a server-side write.    if let Ok(actor) = crate::actor::Actor::from_wire(&receipt.actor) {        match require_local_actor_write(db, &actor) {            Err(crate::StoreError::Refused(reason)) => return Ok(Some(reason)),            Err(error) => return Err(error),            Ok(()) => {}        }    }    Ok(None)}fn require_local_actor_write(db: &crate::Driver, actor: &crate::actor::Actor) -> crate::Result<()> {    match actor.principal() {        crate::actor::Actor::Owner(id) | crate::actor::Actor::Member(id) => {            if let Some(row) = db.get(                "SELECT device_id FROM cotton_devices WHERE id = ?",                &[rusqlite::types::Value::Text(id.as_str().into())],            )? {                if let Some(key) = row.text("device_id") {                    require_write(db, key)?;                }            }        }        _ => {}    }    Ok(())}#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct DeviceAdmission {    pub scope: DeviceScope,    pub takes_placements: bool,}impl DeviceScope {    pub fn require_write(self) -> crate::Result<()> {        if self == Self::Reader {            Err(crate::StoreError::refused(READER_WRITE_REFUSAL))        } else {            Ok(())        }    }    pub fn as_str(self) -> &'static str {        DEVICE_ADMISSIONS            .iter()            .find(|(scope, _, _)| *scope == self)            .expect("every scope has a spelling")            .1    }    /// Missing is the default full device. An explicit unknown word is refused.    pub fn parse(value: Option<&str>) -> Result<Self, &'static str> {        Self::from_pair(value, None).map(|admission| admission.scope)    }    pub fn from_pair(        value: Option<&str>,        takes_placements: Option<i64>,    ) -> Result<DeviceAdmission, &'static str> {        let value = value.unwrap_or("full");        let takes = match takes_placements.unwrap_or(0) {            0 => false,            1 => true,            _ => return Err("placement grant must be 0 or 1"),        };        DEVICE_ADMISSIONS            .iter()            .find(|(_, named, grant)| *named == value && *grant == takes)            .map(|(scope, _, takes_placements)| DeviceAdmission {                scope: *scope,                takes_placements: *takes_placements,            })            .ok_or("unknown device scope or placement grant")    }    pub fn written(value: &serde_json::Value) -> Result<Self, &'static str> {        Self::parse(Some(value.as_str().ok_or("device scope must be text")?))    }    pub fn written_pair(        value: &serde_json::Value,        takes: &serde_json::Value,    ) -> Result<DeviceAdmission, &'static str> {        Self::from_pair(            Some(value.as_str().ok_or("device scope must be text")?),            Some(takes.as_i64().ok_or("placement grant must be 0 or 1")?),        )    }}impl DeviceAdmission {    pub fn placement_runner(self) -> bool {        self.scope == DeviceScope::Runner && self.takes_placements    }    /// Scope is judged after the key's standing. The placement exchange then    /// checks the addressed rows before folding or answering anything.    pub fn admits(self, method: &str, path: &str) -> bool {        self.scope == DeviceScope::Full            || (self.placement_runner()                && method == "POST"                && path.split('?').next() == Some("/v1/sync/exchange"))    }}#[cfg(test)]mod tests {    use super::*;    /// RULE: One admission list governs every read and write; unknown scopes, invalid grants and (full, 1) are refused, because the placement grant belongs only to runners and must never widen access to the person's database.    #[test]    fn unknown_scope_or_grant_is_refused_on_write_and_read() {        for (scope, word, takes) in DEVICE_ADMISSIONS {            let read = DeviceScope::from_pair(Some(word), Some(i64::from(*takes))).unwrap();            assert_eq!((read.scope, read.takes_placements), (*scope, *takes));            assert_eq!(                DeviceScope::written_pair(                    &serde_json::json!(word),                    &serde_json::json!(i64::from(*takes))                )                .unwrap(),                read            );        }        for (word, grant) in [            ("full", 1),            ("reader", 1),            ("runner", 2),            ("runner", -1),            ("", 0),            ("future_scope", 0),            ("runner_placements", 0),        ] {            assert!(DeviceScope::from_pair(Some(word), Some(grant)).is_err());            assert!(                DeviceScope::written_pair(&serde_json::json!(word), &serde_json::json!(grant))                    .is_err()            );        }        for value in [            serde_json::Value::Null,            serde_json::json!(false),            serde_json::json!({}),            serde_json::json!([]),        ] {            assert!(DeviceScope::written(&value).is_err());            assert!(DeviceScope::written_pair(&serde_json::json!("runner"), &value).is_err());        }    }    /// RULE: A runner without the grant receives nothing; a runner with it reaches only the placement exchange; full devices retain their existing routes, because jobs must never grant a database copy.    #[test]    fn the_pair_controls_placement_exchange_admission() {        let full = DeviceScope::from_pair(Some("full"), Some(0)).unwrap();        let runner = DeviceScope::from_pair(Some("runner"), Some(0)).unwrap();        let placements = DeviceScope::from_pair(Some("runner"), Some(1)).unwrap();        assert!(placements.admits("POST", "/v1/sync/exchange?database=synthetic"));        for path in [            "/v1/sync/snapshot",            "/v1/sync/open",            "/v1/sync/exchange/all",            "/v1/media",            "/v1/me/databases",        ] {            assert!(full.admits("POST", path));            assert!(!placements.admits("POST", path));        }        assert!(!placements.admits("GET", "/v1/sync/exchange"));        for method in ["GET", "POST"] {            assert!(!runner.admits(method, "/v1/sync/exchange"));        }    }}