Cotton code
146 lines · 6.3 KB · RustRaw
//! The DEVELOPER TOOL — `dev_reveal_secret`, which exists only while this//! server's `COTTON_DEV_TOOLS` switch is on.//!//! The owner's decision of 27 September 2026//! ([until-the-app-goes-public-a-developer-mcp-dev-tools-behind-a-ser]): until//! the app is public, the gates that need a person standing at a screen cost//! more than they buy, so an assistant may read a password back. It is inside//! the ordinary Cotton MCP, on the same connector and in the same tool list,//! because a second server would be a second set of refusals to keep true.//!//! **THE SWITCH IS ONE FIELD AND THE HANDLER READS IT FIRST.**//! `ToolServices::dev_tools` is `Some` on a server with the line set and `None`//! everywhere else, and [`rail`] is the handler's first line. That is not//! belt-and-braces over [`crate::mcp::dispatch::call_tool`]'s own check: the//! owner's app dispatches through `handler_for` and never through `call_tool`,//! so a check that lived only at the door would leave the app's door open.//!//! **EVERY CALL IS AUDITED, AND NO AUDIT LINE CARRIES A VALUE.** The handler//! adds one line naming the OUTCOME (`dev_reveal_secret:opened`, with the//! secret's id and name), because "which password was opened" is the question//! the owner will actually ask of the trail. The line never carries the secret,//! and `the_trail_names_the_secret_and_never_carries_its_value` holds that.//!//! **WHAT IS NOT HERE.** Revoking a device: it is monotone and it decides who//! may open the database at all, so being wrong once is permanent — the grid's//! written refusal stands, switch or no switch.use std::sync::Arc;use serde_json::{json, Map, Value};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::common::{maybe_row, require_uuid, text};use crate::mcp::protocol::{dev_tools_off, ToolFailure};use crate::mcp::read_db::Query;use crate::rails::DevToolsRail;pub fn handlers() -> HandlerGroup {    &[        ("dev_reveal_secret", dev_reveal_secret),    ]}/// The switch, read as the capability it is.////// ONE function, called first by the handler, so there is exactly one/// place a developer tool can decide it is allowed to run — and one sentence it/// answers with when it is not.fn rail(ctx: &Ctx<'_>, tool: &str) -> Result<Arc<dyn DevToolsRail>, ToolFailure> {    ctx.services        .dev_tools        .clone()        .ok_or_else(|| dev_tools_off(tool))}// ── reading one stored password back ────────────────────────────────────────pub fn dev_reveal_secret(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let _rail = rail(ctx, "dev_reveal_secret")?;    let id = require_uuid(args, "secretId")?;    let Some(vault) = ctx.services.vault.clone() else {        return Err(crate::mcp::handlers::secrets::vault_unavailable());    };    let Some(row) = maybe_row(        ctx,        &Query::on("cotton_secrets")            .columns(&[                "id",                "kind",                "name",                "service",                "site",                "username",                "value_enc",                "vmk_version",                "trashed_at",            ])            .eq("id", id.clone()),    )?    else {        return Err(ToolFailure::new(format!("no secret with id {id}")));    };    let name = text(&row, "name").unwrap_or_default();    // A BINNED SECRET IS STILL READABLE, and deliberately: the bin is a    // recoverable state rather than an erasure, and the one time somebody needs    // a password back is after they binned the wrong row.    let binned = text(&row, "trashed_at").is_some();    let sealed = text(&row, "value_enc").filter(|sealed| !sealed.is_empty());    let Some(sealed) = sealed else {        return Err(ToolFailure::new(format!(            "{name} is a named secret with nothing stored in it yet — list_secrets says isSet \             false for it"        )));    };    let vmk_version = u32::try_from(crate::mcp::handlers::common::int(&row, "vmk_version"))        .map_err(|_| ToolFailure::new(format!("{name} names a key version this build cannot read")))?;    // THE VAULT IS ASKED FIRST AND EXPLAINS AFTERWARDS. A pre-check for the old    // scheme would be a second judgment about what can be opened, and the one    // that matters is the vault's own — so the `is_legacy` reading is used to    // choose the SENTENCE for a refusal the vault has already made, never to    // refuse on its own.    let Some(opened) = vault.open(&id, vmk_version, &sealed) else {        if cotton_core::vault::seal::is_legacy(&sealed) {            return Err(ToolFailure::new(format!(                "{name} was sealed under the old scheme and the re-seal sweep has not reached it \                 — nothing here can open it. Do not retry."            )));        }        return Err(ToolFailure::new(format!(            "the vault would not open {name} — a wrong key version, a body that does not verify, \             or a vault that cannot open this database. Nothing was changed. Do not retry."        )));    };    // The payload is parsed from the opened bytes and the bytes are WIPED    // whatever happens, which is the rule every other reader in this tree keeps    // (the placement applier, the document-password pipeline, the phone's own    // reveal).    let payload: Result<cotton_core::vault::SecretPayload, _> = serde_json::from_slice(&opened);    let as_json = payload        .as_ref()        .ok()        .and_then(|payload| serde_json::to_value(payload).ok());    cotton_core::vault::seal::wipe(opened);    let Some(as_json) = as_json else {        return Err(ToolFailure::new(format!(            "{name} opened but what is inside it is not a payload this build understands"        )));    };    // WHICH SECRET, NEVER WHAT IT SAID. The call's own audit row already    // carries `secretId=…`; this line is the one a person reads, and the two    // things it names are the id and the name.    ctx.audit("dev_reveal_secret", &format!("opened {name} ({id})"));    Ok(json!({        "id": id,        "kind": text(&row, "kind"),        "name": name,        "service": text(&row, "service"),        "site": text(&row, "site"),        "username": text(&row, "username"),        "binned": binned,        "payload": as_json,    }))}