Cotton code
399 lines · 15.3 KB · RustRaw
//! Who asked for a write — inside the AUTHOR (the device) that made it.//!//! An author is a device: `device:<ulid>`, the stream a stamp belongs to. An//! actor is the authenticated thing on that device that asked for the write://! the owner at the screen, an MCP token, a code credential, a job, a session,//! an automation acting for one of them. The two are kept apart because//! revocation ends an actor, never a device's past writes, and because a//! reader that branched on author strings (`server:<job>`) could never tell a//! job from a token.//!//! **AN ACTOR IS NEVER BUILT FROM A BARE STRING.** Every constructor takes a//! typed id, and every typed id is built either from a row this file holds//! ([`TokenId::in_file`] and its siblings, which refuse an id the file does//! not know) or from a name written in code (a `&'static str`). The one//! parser, [`Actor::from_wire`], is `pub(crate)`: it exists for the two places//! that read an actor back — `wire` (a peer's bytes) and `stored` (a row of//! this file) — and for nothing else. The guard//! `tests/actor_cannot_be_built_from_a_string.rs` holds this over the source.use std::fmt;use rusqlite::types::Value as SqlValue;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::outbox::IdSource;macro_rules! row_id {    ($(#[$doc:meta])* $name:ident, $table:literal $(, $other_table:literal)?) => {        $(#[$doc])*        #[derive(Debug, Clone, PartialEq, Eq, Hash)]        pub struct $name(String);        impl $name {            /// The id of a row this file holds — refused when `` $table `` has            /// no row with that id, because an actor the file cannot name is            /// not an authenticated context.            pub fn in_file(db: &Driver, id: &str) -> Result<Self> {                if id.is_empty() {                    return Err(StoreError::refused(concat!(                        "an empty id names no row of ",                        $table                    )));                }                let held = db.get(                    concat!("SELECT id FROM ", $table, " WHERE id = ?1"                        $(, " UNION ALL SELECT id FROM ", $other_table, " WHERE id = ?1")?),                    &[SqlValue::Text(id.to_string())],                )?;                if held.is_none() {                    return Err(StoreError::refused(format!(                        concat!("this file holds no ", $table, $(" or ", $other_table,)? " row {} — an actor is built from a row the file knows"),                        id                    )));                }                Ok(Self(id.to_string()))            }            /// Read back from a wire or stored form that was checked when it            /// was written. Crate-only: nothing outside the store parses one.            pub(crate) fn from_wire(id: &str) -> std::result::Result<Self, String> {                if id.is_empty() {                    return Err(concat!("an empty ", $table, " id").to_string());                }                Ok(Self(id.to_string()))            }            pub fn as_str(&self) -> &str {                &self.0            }        }    };}row_id!(    /// An MCP token's row in `cotton_mcp_tokens`.    TokenId,    "cotton_mcp_tokens");impl TokenId {    /// A token resolved ONCE in its home file and carried into this one    /// (design 3.8): no other file ever holds a row for it, so the actor it    /// writes under here names the home file beside the token —    /// `token:<home file id>:<token id>`. Refused when `home` IS this file    /// (then the row is looked up, [`TokenId::in_file`]) or either part is    /// empty.    pub fn carried(db: &Driver, home: &str, id: &str) -> Result<Self> {        carried_id(db, "token", home, id).map(Self)    }}/// `<home file id>:<id>` for a row that lives in ANOTHER file of the owner's/// and was resolved there once — the one rule [`TokenId::carried`] and/// [`CredentialId::carried`] share. Refused when either part is empty, and when/// `home` is THIS file, because then the row is here and is looked up instead.fn carried_id(db: &Driver, what: &str, home: &str, id: &str) -> Result<String> {    if home.is_empty() || id.is_empty() {        return Err(StoreError::refused(format!(            "a carried {what} names its home file and its id; one of them is empty"        )));    }    let here = db        .get("SELECT id FROM cotton_workspaces LIMIT 1", &[])?        .and_then(|row| row.text("id").map(str::to_string));    if here.as_deref() == Some(home) {        return Err(StoreError::refused(format!(            "{what} {id} names {home} as its home, and that is this file — its row is looked up here, not carried"        )));    }    Ok(format!("{home}:{id}"))}row_id!(    /// A code credential's grant: a standing row in `cotton_code_credentials`,    /// or its job in `cotton_repo_jobs` for a per-job token. Admission has    /// already checked the grant's liveness; both actors name a held row.    CredentialId,    "cotton_code_credentials",    "cotton_repo_jobs");impl CredentialId {    /// A credential resolved ONCE in its home file and carried into this one —    /// a `ctg_` minted in the personal database writing to a repository that    /// lives in a project's: no other file holds a row for it, so the actor it    /// writes under here names the home file beside the credential —    /// `credential:<home file id>:<credential id>`, as a carried token does    /// ([`TokenId::carried`]). Refused when `home` IS this file (then the row is    /// looked up, [`CredentialId::in_file`]) or either part is empty.    pub fn carried(db: &Driver, home: &str, id: &str) -> Result<Self> {        carried_id(db, "credential", home, id).map(Self)    }}row_id!(    /// A device's approval row in `cotton_devices` — the owner at that device.    DeviceId,    "cotton_devices");row_id!(    /// An OAuth grant's row in `cotton_oauth_grants`.    GrantId,    "cotton_oauth_grants");row_id!(    /// A session's row in `cotton_sessions`.    SessionId,    "cotton_sessions");row_id!(    /// A tool definition's row in `cotton_tool_definitions`; an automation is    /// data inside a tool package, and the definition is the row the file    /// holds for it.    AutomationId,    "cotton_tool_definitions");/// A job's name, written in code: `job:<name>` and `device-job:<name>`.#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub struct JobName(&'static str);impl JobName {    /// A name from the source: one word, so it reads back from the wire.    pub fn named(name: &'static str) -> Result<Self> {        if name.is_empty() || name.contains([':', ' ']) {            return Err(StoreError::refused(format!(                "`{name}` is not a job name — one word, no colon, no space"            )));        }        Ok(JobName(name))    }    pub(crate) fn from_wire(name: &str) -> std::result::Result<Self, String> {        if name.is_empty() || name.contains([':', ' ']) {            return Err(format!("`{name}` is not a job name"));        }        // A name read back is one the source wrote once; leaking it is the        // price of a `'static` name, paid once per distinct job per process.        Ok(JobName(Box::leak(name.to_string().into_boxed_str())))    }    pub fn as_str(&self) -> &str {        self.0    }}/// A carry run's id — minted fresh for the run, never typed in.#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub struct RunId(String);impl RunId {    /// A new run, from the caller's id source (this crate mints no ids of    /// its own, spec R7).    pub fn minted(ids: &mut dyn IdSource, now_ms: i64) -> Result<Self> {        Ok(RunId(ids.next_op_id(now_ms)?))    }    pub(crate) fn from_wire(id: &str) -> std::result::Result<Self, String> {        if id.is_empty() {            return Err("an empty run id".to_string());        }        Ok(RunId(id.to_string()))    }    pub fn as_str(&self) -> &str {        &self.0    }}/// The authenticated context a write was asked from.#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub enum Actor {    /// `token:<id>` — an MCP token the serving Mac admitted; in a file other    /// than the token's home, `token:<home file id>:<id>` (the token resolved    /// in its home file and carried, [`TokenId::carried`]).    Token(TokenId),    /// `credential:<id>` — a code credential the serving Mac admitted.    Credential(CredentialId),    /// `owner:<device id>` — the owner at that device's screen.    Owner(DeviceId),    /// `job:<name>` — a job of the serving Mac.    Job(JobName),    /// `import:<run id>` — the carry's offline import.    Import(RunId),    /// `admin:<token id>` — an owner-device token acting through the admin    /// routes.    Admin(TokenId),    /// `oauth:<grant id>` — a connector acting under an OAuth grant.    OAuth(GrantId),    /// `automation:<id> for <actor>` — an automation running for the actor    /// whose write set it off.    Automation {        id: AutomationId,        on_behalf_of: Box<Actor>,    },    /// `device-job:<name>` — a job any device runs for itself.    DeviceJob(JobName),    /// `session:<id>` — a session (an agent) the file hosts.    Session(SessionId),    /// `takeover` — slice 12's one act on a restored file.    Takeover,    /// `member:<device id>` — a member of this database at one of their    /// devices: a person the owner or an admin admitted, not the owner.    Member(DeviceId),}impl Actor {    pub fn token(id: TokenId) -> Actor {        Actor::Token(id)    }    pub fn credential(id: CredentialId) -> Actor {        Actor::Credential(id)    }    pub fn owner(device: DeviceId) -> Actor {        Actor::Owner(device)    }    pub fn job(name: JobName) -> Actor {        Actor::Job(name)    }    pub fn import(run: RunId) -> Actor {        Actor::Import(run)    }    pub fn admin(token: TokenId) -> Actor {        Actor::Admin(token)    }    pub fn oauth(grant: GrantId) -> Actor {        Actor::OAuth(grant)    }    pub fn automation(id: AutomationId, on_behalf_of: Actor) -> Actor {        Actor::Automation {            id,            on_behalf_of: Box::new(on_behalf_of),        }    }    pub fn device_job(name: JobName) -> Actor {        Actor::DeviceJob(name)    }    pub fn session(id: SessionId) -> Actor {        Actor::Session(id)    }    pub fn takeover() -> Actor {        Actor::Takeover    }    /// A member at `device`. Refused unless that device's row names a person    /// key: a row with none is a device of the database's owner, and the    /// owner is never written down as a member.    pub fn member(db: &Driver, device: DeviceId) -> Result<Actor> {        let person = db            .get(                "SELECT person_key FROM cotton_devices WHERE id = ?",                &[SqlValue::Text(device.as_str().to_string())],            )?            .and_then(|row| row.text("person_key").map(str::to_string))            .filter(|key| !key.is_empty());        if person.is_none() {            return Err(StoreError::refused(format!(                "device row {} names no person key — a member actor is built only from a member's device row",                device.as_str()            )));        }        Ok(Actor::Member(device))    }    /// Whether this is the owner at one of their devices — the one question a    /// handler asks of the actor (a comment by the person versus by an agent).    pub fn is_owner(&self) -> bool {        matches!(self, Actor::Owner(_))    }    /// The word before the colon on the wire — what a screen or a log keys on.    pub fn kind(&self) -> &'static str {        match self {            Actor::Token(_) => "token",            Actor::Credential(_) => "credential",            Actor::Owner(_) => "owner",            Actor::Job(_) => "job",            Actor::Import(_) => "import",            Actor::Admin(_) => "admin",            Actor::OAuth(_) => "oauth",            Actor::Automation { .. } => "automation",            Actor::DeviceJob(_) => "device-job",            Actor::Session(_) => "session",            Actor::Takeover => "takeover",            Actor::Member(_) => "member",        }    }    /// The actor an automation ultimately acts for; itself otherwise.    pub fn principal(&self) -> &Actor {        match self {            Actor::Automation { on_behalf_of, .. } => on_behalf_of.principal(),            other => other,        }    }    /// The wire and stored form, exactly as [`fmt::Display`] writes it.    pub fn to_wire(&self) -> String {        self.to_string()    }    /// Read an actor back. Crate-only: the two readers are `wire` and    /// `stored`; everything else builds one from an authenticated context.    pub(crate) fn from_wire(text: &str) -> std::result::Result<Actor, String> {        if text == "takeover" {            return Ok(Actor::Takeover);        }        let Some((kind, rest)) = text.split_once(':') else {            return Err(format!("`{text}` is not an actor: no kind before a colon"));        };        Ok(match kind {            "token" => Actor::Token(TokenId::from_wire(rest)?),            "credential" => Actor::Credential(CredentialId::from_wire(rest)?),            "owner" => Actor::Owner(DeviceId::from_wire(rest)?),            "job" => Actor::Job(JobName::from_wire(rest)?),            "import" => Actor::Import(RunId::from_wire(rest)?),            "admin" => Actor::Admin(TokenId::from_wire(rest)?),            "oauth" => Actor::OAuth(GrantId::from_wire(rest)?),            "device-job" => Actor::DeviceJob(JobName::from_wire(rest)?),            "session" => Actor::Session(SessionId::from_wire(rest)?),            "member" => Actor::Member(DeviceId::from_wire(rest)?),            "automation" => {                let Some((id, principal)) = rest.split_once(" for ") else {                    return Err(format!(                        "`{text}` is not an automation actor: `automation:<id> for <actor>`"                    ));                };                Actor::Automation {                    id: AutomationId::from_wire(id)?,                    on_behalf_of: Box::new(Actor::from_wire(principal)?),                }            }            other => return Err(format!("`{other}` is not a kind of actor this build knows")),        })    }}impl fmt::Display for Actor {    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {        match self {            Actor::Token(id) => write!(f, "token:{}", id.as_str()),            Actor::Credential(id) => write!(f, "credential:{}", id.as_str()),            Actor::Owner(id) => write!(f, "owner:{}", id.as_str()),            Actor::Job(name) => write!(f, "job:{}", name.as_str()),            Actor::Import(run) => write!(f, "import:{}", run.as_str()),            Actor::Admin(id) => write!(f, "admin:{}", id.as_str()),            Actor::OAuth(id) => write!(f, "oauth:{}", id.as_str()),            Actor::Automation { id, on_behalf_of } => {                write!(f, "automation:{} for {on_behalf_of}", id.as_str())            }            Actor::DeviceJob(name) => write!(f, "device-job:{}", name.as_str()),            Actor::Session(id) => write!(f, "session:{}", id.as_str()),            Actor::Takeover => f.write_str("takeover"),            Actor::Member(id) => write!(f, "member:{}", id.as_str()),        }    }}#[cfg(test)]#[path = "actor_tests.rs"]mod tests;