Cotton code
106 lines · 5.6 KB · RustRaw
//! SLOW READS ON DEV (coordinator, 26 Nov 2026): an invented account for timing the object's reads from outside.//!//! A fresh phone (the shared core through its C ABI, opened as Words) signs in to an invented number on the dev//! Worker, founds the account's key, and keeps `{ server, database, credential }` in COTTON_SLOW_OUT (mode 600, never//! printed) for the slow-reads admin script to plant the account to size and time its reads.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker), COTTON_WALK_CODE_FILE, COTTON_SLOW_NUMBER (an invented number)//! and COTTON_SLOW_OUT are set. Never point it at the live server.use std::ffi::{c_char, CStr, CString};use std::path::PathBuf;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free};use serde_json::{json, Value};use sha2::{Digest, Sha256};fn var(name: &str) -> Option<String> {    std::env::var(name).ok().filter(|v| !v.trim().is_empty())}fn home(path: &str) -> PathBuf {    match path.strip_prefix("~/") {        Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),        None => PathBuf::from(path),    }}fn take(text: *mut c_char) -> String {    if text.is_null() {        return String::new();    }    // SAFETY: an owned string from the C ABI, freed once with its own free.    let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();    unsafe { cotton_string_free(text) };    owned}#[test]fn an_invented_account_for_timing_reads() {    let (Some(server), Some(number), Some(out)) = (var("COTTON_WALK_SERVER"), var("COTTON_SLOW_NUMBER"), var("COTTON_SLOW_OUT")) else {        eprintln!("SKIPPED: no COTTON_WALK_SERVER, COTTON_SLOW_NUMBER and COTTON_SLOW_OUT");        return;    };    assert!(server.contains("-dev") || server.contains("localhost"), "dev only, not {server}");    let otp = var("COTTON_WALK_CODE_FILE").map(|f| std::fs::read_to_string(home(&f)).expect("the dev code file").trim().to_string()).expect("the dev sign-in code");    let container = tempfile::tempdir().expect("a tempdir");    std::fs::create_dir_all(container.path().join("cotton")).expect("the container");    let seed = format!("cotton slow reads {number} {:?}", std::time::SystemTime::now());    let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours/notes/flavour.json");    let mut manifest: Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("the manifest")).expect("JSON");    manifest["business"]["server"] = json!(server);    let config = json!({        "containerPath": container.path().join("cotton").to_string_lossy(),        "appVersion": "headless-slow-reads",        "timeZone": "Asia/Kolkata",        "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())),        "flavor": "dev",        "manifest": manifest,    });    let text = CString::new(config.to_string()).unwrap();    let mut error: *mut c_char = std::ptr::null_mut();    // SAFETY: a NUL-terminated config and a writable error slot.    let handle = unsafe { cotton_open(text.as_ptr(), &mut error) };    assert!(!handle.is_null(), "cotton_open: {}", take(error));    let call = |method: &str, request: Value| -> Result<Value, String> {        let m = CString::new(method).unwrap();        let r = CString::new(request.to_string()).unwrap();        // SAFETY: a live handle and NUL-terminated strings.        let answer: Value = serde_json::from_str(&take(unsafe { cotton_call(handle, m.as_ptr(), r.as_ptr()) })).unwrap();        if answer["ok"] == json!(true) { Ok(answer["data"].clone()) } else { Err(format!("{method}: {}", answer["error"])) }    };    call("personal.standLocal", json!({ "signedOut": true })).unwrap();    let challenge = call("personal.code", json!({ "server": server, "phone": number })).unwrap();    let mut ask = json!({ "server": server, "challengeId": challenge["challengeId"], "code": otp });    if let Some(d) = challenge.get("databaseId").filter(|d| !d.is_null()) {        ask["databaseId"] = d.clone();    }    let answer = call("personal.signIn", ask).unwrap();    let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).expect("a database").to_string();    let credential = answer["credential"].as_str().expect("a credential").to_string();    call("personal.connect", json!({ "server": server, "databaseId": database, "credential": credential, "deviceName": "slow reads", "appVersion": "headless-slow-reads", "unmetered": true })).unwrap();    let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));    for _ in 0..20 {        let status = call("seal.status", json!({})).unwrap();        if status["keyHeld"] == json!(true) {            break;        }        if status["needsKey"] == json!(true) && status["founds"] == json!(true) {            let _ = call("vault.unlock", json!({ "privateKey": private_key, "name": "slow reads" }));        }        let _ = call("sync.now", json!({}));        std::thread::sleep(std::time::Duration::from_secs(2));    }    let kept = json!({ "server": server, "database": database, "credential": credential });    std::fs::write(home(&out), kept.to_string()).expect("the out file");    #[cfg(unix)]    {        use std::os::unix::fs::PermissionsExt as _;        std::fs::set_permissions(home(&out), std::fs::Permissions::from_mode(0o600)).unwrap();    }    println!("SLOW READS account ready, database {database}; credential kept in {out}");    // SAFETY: the pointer cotton_open answered, closed once.    unsafe { cotton_close(handle) };}