Cotton code
595 lines · 23.6 KB · RustRaw
//! The secrets tools — `create_secret`, `update_secret`, `list_secrets`,//! `delete_secret` (the vault, schema v6 of the Rust ladder;//! Cotton note "The vault — the honest sentence").//!//! THERE IS NO `get_secret`, AND THERE WILL NOT BE ONE. Four tools name a//! secret, store one, change one and bin one; nothing here reads one back, and//! no fifth tool is going to. `list_secrets` answers names, sites, usernames//! and the last FOUR characters — enough to tell two logins apart on a screen,//! useless to anybody who has it. The reveal is the person's own device,//! against its own replica, with its own key; the only readers of a value in//! this whole tree are named in `vault.md` and not one of them is reachable//! from a tool call. That is the document-password rule one table over//! ([assistants-never-see-a-document-s-password-they-get-the-unlocked]).//!//! THE VAULT IS A CAPABILITY, and its absence is a REFUSAL rather than a//! half-write. `ToolServices::vault` holds it; it is `Some` on a server that//! opened this workspace's master key at boot, and `None` on a phone, on a//! `cotton-server` started with no vault key, and on a Mac whose own key this//! workspace has never been wrapped for. A build without one refuses//! `vault_unavailable` BY NAME — the contract every other rail already keeps —//! rather than writing a row whose `value_enc` is the plaintext somebody//! pasted. `list_secrets` and `delete_secret` need no vault and work//! everywhere: naming what you hold and binning it are not secrets.//!//! ONE ROW PER (service, name), STILL — but only where there IS a service. The//! partial UNIQUE index says so: a BYOK key for `anthropic` and a filed//! document's password are addressable by name and must not collide, while a//! login has no service at all and a person has two called "Gmail".use cotton_core::vault::payload::{SecretKind, SecretPayload};use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::common::{    insert_row, iso_timestamp, maybe_row, optional_string, require_string, require_uuid,    rows, text, update_row,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};use crate::rails::{SealedSecret, VaultRail};pub fn handlers() -> HandlerGroup {    &[        ("create_secret", create_secret),        ("list_secrets", list_secrets),        ("delete_secret", delete_secret),        ("update_secret", update_secret),    ]}/// The table's own caps, which are CHECKs — refusing here with a sentence is/// what turns a constraint error into something a model can act on.////// RE-EXPORTED: the vault declares them once (`cotton_core::vault::columns`),/// because the import parsers and the import writer hold rows to the same/// numbers.pub use cotton_core::vault::columns::{NAME_MAX, SERVICE_MAX, SITE_MAX, USERNAME_MAX};/// The service a filed document's password is stored under. One string, here,/// because the sweep writes it and the PDF pipeline reads it.pub const DOCUMENT_SERVICE: &str = "document";/// How many characters of a value a person is shown, and the function that/// takes them.////// RE-EXPORTED, not re-implemented: the vault owns the rule now/// (`cotton_core::vault::payload`), because the apps seal their own payloads/// and compute their own hints, and two answers to "what does a list show/// instead of the secret" is one answer too many.pub use cotton_core::vault::payload::{hint_of, HINT_CHARS};/// What a build with no vault answers, by name.////// ONE sentence, in one place: every tool here that would have to seal or open/// says exactly this, so a model meets one closed door rather than four/// differently-worded ones.pub fn vault_unavailable() -> ToolFailure {    ToolFailure::new(        "vault_unavailable: this Cotton build cannot open the owner's passwords — the vault key \         lives on their own Mac. Nothing was written. Do not retry.",    )}/// `service` as the column admits it: lowercase, and only letters, digits and/// `. _ -`, starting with a letter or a digit. Spelled here as a refusal/// because the CHECK's own message says nothing a model could correct itself/// from.////// `pub` for ONE caller outside this file: the phone's `secrets.set`/// (`cotton-ffi`'s `phone::secrets`), which validates HERE first so the person/// sees the refusal under what they typed rather than after a round trip. A/// second copy of the vocabulary would be a second opinion about what the/// column admits.pub fn validate_service(service: &str) -> Result<String, ToolFailure> {    if service.len() > SERVICE_MAX {        return Err(ToolFailure::new(format!(            "service must be at most {SERVICE_MAX} characters"        )));    }    let ok = !service.is_empty()        && service            .chars()            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))        && service            .chars()            .next()            .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());    if !ok {        return Err(ToolFailure::new(            "service must be lowercase letters, digits, dots, hyphens or underscores, starting \             with a letter or a digit — 'anthropic', 'openai', 'my-bank'",        ));    }    Ok(service.to_string())}fn capped(value: &str, max: usize, what: &str) -> Result<String, ToolFailure> {    if value.chars().count() > max {        return Err(ToolFailure::new(format!(            "{what} must be at most {max} characters"        )));    }    Ok(value.to_string())}/// The kind a call named, or the refusal that names every one there is.fn kind_of(args: &Map<String, Value>, fallback: Option<SecretKind>) -> Result<SecretKind, ToolFailure> {    let Some(raw) = optional_string(args, "kind") else {        return fallback.ok_or_else(|| ToolFailure::new(kinds_sentence()));    };    SecretKind::parse(&raw).ok_or_else(|| ToolFailure::new(kinds_sentence()))}fn kinds_sentence() -> String {    format!(        "kind must be one of {}",        SecretKind::ALL            .iter()            .map(|kind| kind.as_str())            .collect::<Vec<_>>()            .join(", ")    )}/// Build the typed payload from what a call carried.////// TWO WAYS IN, and they are not two schemes: `value` is the kind's PRIMARY/// field on its own — which is the whole of an api key, a note or a password —/// and `fields` is the typed object for a card, an identity or a login with a/// one-time secret beside it. A call naming both is refused rather than having/// one of them silently win.pub fn payload_of(    kind: SecretKind,    args: &Map<String, Value>,) -> Result<SecretPayload, ToolFailure> {    let has_fields = matches!(args.get("fields"), Some(Value::Object(_)));    // The VALUE is read without `require_string`'s trim-and-drop-if-blank: a    // credential's own leading space would be part of it, and a blank one is a    // refusal rather than a silently absent field.    let value = args.get("value").and_then(Value::as_str);    if has_fields && value.is_some() {        return Err(ToolFailure::new(            "pass value OR fields, not both — value is the one primary field, fields is the whole \             typed payload",        ));    }    if let Some(Value::Object(fields)) = args.get("fields") {        let mut object = fields.clone();        // The tag is the kind the call already named; a `kind` inside `fields`        // that disagreed would be a second opinion about what this row is.        object.insert("kind".to_string(), Value::from(kind.as_str()));        return serde_json::from_value(Value::Object(object)).map_err(|error| {            ToolFailure::new(format!(                "fields is not a {} payload: {error}. The fields of a {} are {}.",                kind,                kind,                kind.spec()                    .fields                    .iter()                    .map(|field| field.name)                    .collect::<Vec<_>>()                    .join(", ")            ))        });    }    let Some(value) = value else {        return Err(ToolFailure::new(format!(            "value is required — the {} of a {kind}",            kind.primary_field()        )));    };    if value.is_empty() {        return Err(ToolFailure::new(            "value is empty — pass the credential itself, or delete_secret to bin one",        ));    }    let mut object = Map::new();    object.insert("kind".to_string(), Value::from(kind.as_str()));    object.insert(kind.primary_field().to_string(), Value::from(value));    serde_json::from_value(Value::Object(object))        .map_err(|error| ToolFailure::new(format!("the value could not be sealed: {error}")))}/// Seal one payload for one row, or refuse by name.////// The plaintext JSON is WIPED on the way out whatever happens — it is a/// password on a stack, and the one thing that must not be left behind for/// whatever allocates next.pub fn seal_payload(    vault: &dyn VaultRail,    secret_id: &str,    payload: &SecretPayload,) -> Result<(SealedSecret, String), ToolFailure> {    let hint = payload.hint();    let json = serde_json::to_vec(payload)        .map_err(|error| ToolFailure::new(format!("the payload could not be written: {error}")))?;    let sealed = vault.seal(secret_id, &json);    cotton_core::vault::seal::wipe(json);    let sealed = sealed.ok_or_else(|| {        ToolFailure::new(            "the secret could not be sealed. Nothing was written. Do not retry.",        )    })?;    Ok((sealed, hint))}/// Store one secret, sealed.////// Idempotent on (service, name) where a service is named: a second call with a/// new value REPLACES the first, which is what a person re-pasting a rotated/// key means. A row with no service is always a NEW row — a person has two/// logins called "Gmail", and collapsing them would lose one.pub fn create_secret(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let Some(name) = require_string(args, "name") else {        return Err(ToolFailure::new("name is required"));    };    let name = capped(&name, NAME_MAX, "name")?;    // The v5 shape had no kind and every row was an api key; a call that names    // none still means that, because `create_secret` with a name, a service and    // one opaque value IS an api key.    let kind = kind_of(args, Some(SecretKind::ApiKey))?;    let service = match optional_string(args, "service") {        Some(service) => Some(validate_service(&service)?),        // A key with no service cannot be found by `api_key_for`, which is the        // reason this tool exists — so an api key still insists on one.        None if kind == SecretKind::ApiKey => {            return Err(ToolFailure::new(                "service is required for an api key — it is how the key is found again \                 ('anthropic', 'openai')",            ))        }        None => None,    };    let site = match optional_string(args, "site") {        Some(site) => Some(capped(&site, SITE_MAX, "site")?),        None => None,    };    let username = match optional_string(args, "username") {        Some(username) => Some(capped(&username, USERNAME_MAX, "username")?),        None => None,    };    let expires_at = expires_at_of(args)?;    let payload = payload_of(kind, args)?;    // THE VAULT, OR NOTHING. A build with no vault refuses BY NAME rather than    // writing the plaintext into a column called `value_enc`.    let Some(vault) = ctx.services.vault.clone() else {        return Err(vault_unavailable());    };    let existing = match service.as_ref() {        Some(service) => maybe_row(            ctx,            &Query::on("cotton_secrets")                .columns(&["id"])                .eq("service", service.clone())                .eq("name", name.clone()),        )?,        None => None,    };    // The id is decided BEFORE the seal: it is the seal's associated data, so a    // payload sealed for one row can never be opened as another's.    let id = existing        .as_ref()        .and_then(|row| text(row, "id"))        .unwrap_or_else(|| ctx.new_uuid());    let (sealed, hint) = seal_payload(vault.as_ref(), &id, &payload)?;    let mut patch = Map::new();    patch.insert("value_enc".to_string(), Value::from(sealed.value_enc));    patch.insert(        "vmk_version".to_string(),        Value::from(i64::from(sealed.vmk_version)),    );    patch.insert("hint".to_string(), Value::from(hint.clone()));    patch.insert("kind".to_string(), Value::from(kind.as_str()));    if let Some(site) = site.clone() {        patch.insert("site".to_string(), Value::from(site));    }    if let Some(username) = username.clone() {        patch.insert("username".to_string(), Value::from(username));    }    if let Some(expires_at) = expires_at.clone() {        patch.insert("expires_at".to_string(), Value::from(expires_at));    }    // Re-pasting a key that was binned brings it back: the person plainly means    // to have it.    patch.insert("trashed_at".to_string(), Value::Null);    if existing.is_some() {        update_row(ctx, "cotton_secrets", &id, patch)?;    } else {        patch.insert("name".to_string(), Value::from(name.clone()));        if let Some(service) = service.clone() {            patch.insert("service".to_string(), Value::from(service));        }        insert_row(ctx, "cotton_secrets", &id, patch)?;    }    ctx.commit()?;    Ok(answer(&id, kind, &name, site, username, service, &hint))}/// Change what a secret is called, where it belongs — and, when a payload is/// passed, what it holds.////// NEVER ANSWERS A VALUE, including the one it was just handed.pub fn update_secret(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = require_uuid(args, "id")?;    let Some(row) = maybe_row(        ctx,        &Query::on("cotton_secrets")            .columns(&["id", "kind", "name", "site", "username", "service"])            .eq("id", id.clone()),    )?    else {        return Err(ToolFailure::new(format!("no secret with id {id}")));    };    let stored_kind = text(&row, "kind")        .and_then(|kind| SecretKind::parse(&kind))        .unwrap_or(SecretKind::ApiKey);    let mut patch = Map::new();    let mut name = text(&row, "name").unwrap_or_default();    if let Some(asked) = optional_string(args, "name") {        name = capped(&asked, NAME_MAX, "name")?;        patch.insert("name".to_string(), Value::from(name.clone()));    }    let mut site = text(&row, "site");    if let Some(asked) = optional_string(args, "site") {        site = Some(capped(&asked, SITE_MAX, "site")?);        patch.insert("site".to_string(), Value::from(site.clone().unwrap()));    }    let mut username = text(&row, "username");    if let Some(asked) = optional_string(args, "username") {        username = Some(capped(&asked, USERNAME_MAX, "username")?);        patch.insert(            "username".to_string(),            Value::from(username.clone().unwrap()),        );    }    let mut service = text(&row, "service");    if let Some(asked) = optional_string(args, "service") {        service = Some(validate_service(&asked)?);        patch.insert("service".to_string(), Value::from(service.clone().unwrap()));    }    if let Some(expires_at) = expires_at_of(args)? {        patch.insert("expires_at".to_string(), Value::from(expires_at));    }    // THE PAYLOAD, when one is passed. The KIND does not move: a login that    // became a card would leave its site and username describing nothing, and a    // person who means that means a new secret.    let mut hint = None;    if args.contains_key("fields") || args.contains_key("value") {        let Some(vault) = ctx.services.vault.clone() else {            return Err(vault_unavailable());        };        let payload = payload_of(stored_kind, args)?;        let (sealed, fresh) = seal_payload(vault.as_ref(), &id, &payload)?;        patch.insert("value_enc".to_string(), Value::from(sealed.value_enc));        patch.insert(            "vmk_version".to_string(),            Value::from(i64::from(sealed.vmk_version)),        );        patch.insert("hint".to_string(), Value::from(fresh.clone()));        hint = Some(fresh);    }    if patch.is_empty() {        return Err(ToolFailure::new(            "nothing to change — pass a name, site, username, service, expiresAt, or a new payload",        ));    }    update_row(ctx, "cotton_secrets", &id, patch)?;    ctx.commit()?;    let hint = match hint {        Some(hint) => hint,        // The hint of a payload this call did not touch is the row's own, and        // it is read back rather than recomputed: opening a value to answer        // with four characters of it is a read this tool has no reason to make.        None => maybe_row(            ctx,            &Query::on("cotton_secrets")                .columns(&["hint"])                .eq("id", id.clone()),        )?        .as_ref()        .and_then(|row| text(row, "hint"))        .unwrap_or_default(),    };    Ok(answer(&id, stored_kind, &name, site, username, service, &hint))}fn expires_at_of(args: &Map<String, Value>) -> Result<Option<String>, ToolFailure> {    let Some(raw) = optional_string(args, "expiresAt") else {        return Ok(None);    };    iso_timestamp(&raw)        .map(Some)        .ok_or_else(|| ToolFailure::new("expiresAt must be a date or a timestamp"))}/// What both writers answer: what the row IS, and the hint — never the value,/// including on the way back out of the tool that was just handed one.fn answer(    id: &str,    kind: SecretKind,    name: &str,    site: Option<String>,    username: Option<String>,    service: Option<String>,    hint: &str,) -> Value {    let mut out = Map::new();    out.insert("id".to_string(), Value::from(id));    out.insert("kind".to_string(), Value::from(kind.as_str()));    out.insert("name".to_string(), Value::from(name));    if let Some(site) = site {        out.insert("site".to_string(), Value::from(site));    }    if let Some(username) = username {        out.insert("username".to_string(), Value::from(username));    }    if let Some(service) = service {        out.insert("service".to_string(), Value::from(service));    }    out.insert("hint".to_string(), Value::from(hint));    Value::Object(out)}/// The columns a list answers with.////// `value_enc` IS NOT IN THIS LIST and must never join it. The column is read/// by the named Rust readers in Cotton note "The vault — the honest sentence" and by nothing else,/// and a tool that selected it would be one `json!` away from answering with/// somebody's password.const LIST_COLUMNS: &[&str] = &[    "id",    "kind",    "name",    "site",    "username",    "service",    "hint",    "last_used_at",    "expires_at",    "created_at",    "updated_at",];/// What is stored, and nothing of what it says.pub fn list_secrets(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let mut query = Query::on("cotton_secrets")        .columns(LIST_COLUMNS)        // The bin is a separate surface (`list_bin`): a binned password in this        // list would read as one the person still has.        .filter(Filter::IsNull("trashed_at".to_string()))        .order_by("updated_at", Order::Desc);    if let Some(raw) = optional_string(args, "kind") {        let kind = SecretKind::parse(&raw).ok_or_else(|| ToolFailure::new(kinds_sentence()))?;        query = query.eq("kind", kind.as_str().to_string());    }    if let Some(service) = optional_string(args, "service") {        query = query.eq("service", service);    }    let asked = optional_string(args, "q").map(|q| q.to_lowercase());    let found = rows(ctx, &query)?;    let secrets: Vec<Value> = found        .into_iter()        .filter(|row| match asked.as_deref() {            None => true,            // Over the PLAIN columns only, which is the same set `fts_secrets`            // indexes — matched here rather than through the index because a            // list of a person's own passwords is tens of rows, and a second            // answer to "does this row match" is a second thing to keep true.            Some(needle) => ["name", "site", "username", "service"].iter().any(|column| {                text(row, column)                    .map(|value| value.to_lowercase().contains(needle))                    .unwrap_or(false)            }),        })        .map(|row| {            let mut out = Map::new();            for column in LIST_COLUMNS {                if let Some(value) = text(&row, column) {                    out.insert(camel(column), Value::from(value));                }            }            // Whether a value has actually arrived — a named key with none yet            // is a real state, and "not set" is what the person needs to read.            out.insert("isSet".to_string(), Value::Bool(out.contains_key("hint")));            Value::Object(out)        })        .collect();    let mut out = Map::new();    out.insert("secrets".to_string(), Value::Array(secrets));    Ok(Value::Object(out))}/// `last_used_at` → `lastUsedAt`. The columns are snake and the surface is/// camel, everywhere.fn camel(column: &str) -> String {    let mut out = String::with_capacity(column.len());    let mut upper = false;    for c in column.chars() {        if c == '_' {            upper = true;            continue;        }        out.push(if upper { c.to_ascii_uppercase() } else { c });        upper = false;    }    out}/// Move one to the bin.////// A CHANGE FROM THE v5 SHAPE, and a deliberate one: erasing on the spot made/// being wrong unrecoverable, and a person deleting the wrong login loses/// something they cannot re-derive. `restore_from_bin` brings it back and/// `empty_bin` is what erases — the kind-generic bin, with `secret` in/// `BinKind` like every other binnable primitive.pub fn delete_secret(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = require_uuid(args, "id")?;    // Read-then-write: the read takes `id`, `kind` and `name` only — never the    // value, not even to confirm what is about to go.    let Some(row) = maybe_row(        ctx,        &Query::on("cotton_secrets")            .columns(&["id", "kind", "name", "service", "trashed_at"])            .eq("id", id.clone()),    )?    else {        return Err(ToolFailure::new(format!("no secret with id {id}")));    };    set_trashed(ctx, &id, true)?;    ctx.commit()?;    let mut out = Map::new();    out.insert("binned".to_string(), Value::Bool(true));    out.insert("id".to_string(), Value::from(id));    if let Some(name) = text(&row, "name") {        out.insert("name".to_string(), Value::from(name));    }    if let Some(kind) = text(&row, "kind") {        out.insert("kind".to_string(), Value::from(kind));    }    if let Some(service) = text(&row, "service") {        out.insert("service".to_string(), Value::from(service));    }    Ok(Value::Object(out))}/// A secret into the bin (`trashed`) or back out of it: its `trashed_at` and/// nothing else, never its sealed value. The one write behind/// `delete_secret`, the generic delete and its Undo, and the phone's/// `vault.trash` / `vault.restore`, so every door bins a password the same way.pub fn set_trashed(ctx: &mut Ctx<'_>, id: &str, trashed: bool) -> Result<(), ToolFailure> {    let kind = cotton_core::constants::BinKind::Secret;    if trashed {        super::bin::put_away(ctx, kind, id)    } else {        let args = serde_json::json!({"kind":kind.as_str(), "id":id});        super::bin::restore_from_bin(ctx, args.as_object().unwrap()).map(|_| ())    }}#[cfg(test)]#[path = "secrets_tests.rs"]pub(crate) mod secrets_tests;