Cotton code
231 lines · 8.7 KB · RustRaw
//! The DEVELOPER TOOL — the switch, and `dev_reveal_secret` behind it.//!//! Two properties, and the first is the whole feature://!//! 1. **THE SWITCH IS THE DOOR.** The tool refuses by name on a server that//!    was not told to have it, whatever the caller's scopes and whichever door//!    the call came through — and the refusal names `COTTON_DEV_TOOLS`,//!    because the fix is a line in a file on a Mac and no amount of retrying//!    is it.//! 2. **THE TRAIL NAMES THE ACT AND NEVER THE VALUE.** `dev_reveal_secret`//!    answers a password and writes an audit line carrying the secret's id and//!    name; nothing it writes carries what was inside.//!//! Every row is synthetic and every value invented//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use rusqlite::types::Value as SqlValue;use serde_json::json;use support::fakes::{FakeServices, FakeVault};use support::harness::Harness;use support::mcp::{call_tool, call_tool_raw, mint_token};const NOW: &str = "2026-09-08T10:00:00.000Z";/// Device keys — CREDENTIAL ids, invented.const STUDY_MAC: &str = "a-synthetic-study-mac-key";fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// A harness whose server was NOT told to have the developer tools — every/// ordinary server, and the state property 1 is asserted against.fn switched_off() -> (Harness, String) {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    (h, secret)}/// A harness whose server has `COTTON_DEV_TOOLS` on.fn switched_on() -> (Harness, String) {    let mut bag = FakeServices::new();    bag.with_dev_tools();    let mut h = Harness::with_services(bag);    let secret = mint_token(&mut h, &["read", "write"], "Claude");    (h, secret)}/// A device the owner admitted. Written straight into the file: approving one is/// what `dev_approve_device` is for and a fixture must not depend on it.fn admit(h: &Harness, device_id: &str, name: &str, rank: Option<i64>) {    h.db.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, app_version, \         host_version, sessions_cap, serving_rank, approved_at, approved_by_device, created_at, \         updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",        &[            text(&format!("device-row-{device_id}")),            text(&h.workspace_id),            text(device_id),            text(name),            text("mac"),            text("0.16.0"),            text("0.3.1"),            SqlValue::Integer(3),            rank.map_or(SqlValue::Null, SqlValue::Integer),            text(NOW),            text("self"),            text(NOW),            text(NOW),        ],    )    .expect("the device row");}// ── 1. the switch is the door ───────────────────────────────────────────────/// RULE: Every developer tool refuses by name on a server whose developer switch is off, and the refusal names the switch.#[test]fn every_developer_tool_refuses_by_name_when_the_switch_is_off() {    let (h, secret) = switched_off();    admit(&h, STUDY_MAC, "Study Mac", None);    for (tool, args) in [(        "dev_reveal_secret",        json!({ "secretId": "00000000-0000-4000-8000-000000000000" }),    )] {        let answer = call_tool_raw(&h, &secret, tool, args);        assert!(answer.is_error, "{tool} ran on a server with the switch off");        assert!(            answer.text.starts_with("dev_tools_off:"),            "{tool} refused with {:?} rather than the one sentence",            answer.text        );        assert!(            answer.text.contains("COTTON_DEV_TOOLS"),            "{tool}'s refusal does not name the switch: {:?}",            answer.text        );        assert!(            answer.text.contains("Do not retry"),            "{tool}'s refusal does not say a retry is pointless: {:?}",            answer.text        );    }}// ── 2. reading one stored password back ─────────────────────────────────────fn store_a_secret(h: &Harness, secret: &str, name: &str, value: &str) -> String {    let created = call_tool(        h,        secret,        "create_secret",        json!({ "name": name, "service": "anthropic", "value": value }),    );    created["id"].as_str().expect("the new secret's id").to_string()}#[test]fn opens_a_stored_secret_and_answers_every_field_of_it() {    let (h, secret) = switched_on();    let id = store_a_secret(&h, &secret, "Anthropic API key", "sk-test-000000000wxyz");    let answer = call_tool(&h, &secret, "dev_reveal_secret", json!({ "secretId": id }));    assert_eq!(answer["id"], json!(id));    assert_eq!(answer["name"], json!("Anthropic API key"));    assert_eq!(answer["service"], json!("anthropic"));    assert_eq!(answer["kind"], json!("api_key"));    assert_eq!(answer["binned"], json!(false));    assert_eq!(answer["payload"]["key"], json!("sk-test-000000000wxyz"));}/// RULE: The audit trail records which password a developer tool opened and never what it said.#[test]fn the_trail_names_the_secret_and_never_carries_its_value() {    let (h, secret) = switched_on();    let id = store_a_secret(&h, &secret, "Anthropic API key", "sk-test-000000000wxyz");    call_tool(&h, &secret, "dev_reveal_secret", json!({ "secretId": id }));    let lines = h.audit_lines();    let opened = lines        .iter()        .find(|line| line.tool == "dev_reveal_secret")        .expect("an audit line for the reveal");    assert!(opened.summary.contains("Anthropic API key"));    assert!(opened.summary.contains(&id));    for line in &lines {        assert!(            !line.summary.contains("sk-test-000000000wxyz"),            "{} put the value in the trail: {:?}",            line.tool,            line.summary        );    }}/// RULE: A binned password can still be opened, because the bin is a recoverable state and not an erasure.#[test]fn a_binned_secret_still_opens_and_says_it_is_binned() {    let (h, secret) = switched_on();    let id = store_a_secret(&h, &secret, "Old login", "hunter-2-invented");    call_tool(&h, &secret, "delete_secret", json!({ "id": id }));    let answer = call_tool(&h, &secret, "dev_reveal_secret", json!({ "secretId": id }));    assert_eq!(answer["binned"], json!(true));    assert_eq!(answer["payload"]["key"], json!("hunter-2-invented"));}#[test]fn a_secret_with_nothing_stored_in_it_is_refused_by_name() {    let (h, secret) = switched_on();    let id = "11111111-1111-4111-8111-111111111111";    h.db.run(        "INSERT INTO cotton_secrets (id, workspace_id, kind, name, created_at, updated_at) \         VALUES (?,?,?,?,?,?)",        &[            text(id),            text(&h.workspace_id),            text("api_key"),            text("A key nobody has pasted"),            text(NOW),            text(NOW),        ],    )    .expect("the secret row");    let answer = call_tool_raw(&h, &secret, "dev_reveal_secret", json!({ "secretId": id }));    assert!(answer.is_error);    assert!(answer.text.contains("nothing stored in it yet"));}#[test]fn a_secret_the_vault_will_not_open_is_refused_and_says_not_to_retry() {    let (h, secret) = switched_on();    let id = "22222222-2222-4222-8222-222222222222";    h.db.run(        "INSERT INTO cotton_secrets (id, workspace_id, kind, name, value_enc, vmk_version, \         created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",        &[            text(id),            text(&h.workspace_id),            text("api_key"),            text("Sealed for another row"),            // Sealed under a DIFFERENT row id, so the associated data does not            // match and the vault refuses — the same answer a tampered body or            // a wrong key version gets, on purpose.            text(&FakeVault::sealed("somebody-elses-row", "{\"kind\":\"api_key\",\"key\":\"x\"}")),            SqlValue::Integer(i64::from(FakeVault::VERSION)),            text(NOW),            text(NOW),        ],    )    .expect("the secret row");    let answer = call_tool_raw(&h, &secret, "dev_reveal_secret", json!({ "secretId": id }));    assert!(answer.is_error);    assert!(answer.text.contains("Do not retry"));}#[test]fn a_build_with_no_vault_refuses_the_reveal_by_name() {    let mut bag = FakeServices::new();    bag.with_dev_tools();    bag.services.vault = None;    let mut h = Harness::with_services(bag);    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let answer = call_tool_raw(        &h,        &secret,        "dev_reveal_secret",        json!({ "secretId": "33333333-3333-4333-8333-333333333333" }),    );    assert!(answer.is_error);    assert!(answer.text.starts_with("vault_unavailable:"));}