Cotton code
1254 lines · 49.8 KB · RustRaw
//! The status ladder, port by port.//!//! The TypeScript these come from: `serverMoved.test.ts`, `serverErrors.test.ts`,//! `serverNoContent.test.ts`, `serverReaders.test.ts`, `deviceRefusal.test.ts`,//! `terminalNote.security.test.ts`, `pairingPhone.security.test.ts` (the//! transport half) and `pairingPhoneFixes.security.test.ts`.use std::sync::Arc;use super::*;use crate::identity::DeviceIdentity;use crate::seams::{FixedClock, SeededRandom};use crate::transport::refusal::{self, RefusalKind, RefusalMemory, Refuser};use crate::transport::scripted::{RememberedAddress, Reply, ScriptedExchange};use crate::transport::signer::RequestSigner;use crate::transport::{ClientRequest, Exchange, RefusalAware, ServerFetch};const SEED: [u8; 32] = [7u8; 32];const HOME: &str = "https://studio.relay.cottondb.com";struct Fixture {    transport: SignedHttp,    exchange: Arc<ScriptedExchange>,    refusals: Arc<RefusalMemory>,    clock: FixedClock,}fn fixture(address: Arc<RememberedAddress>, replies: Vec<Reply>) -> Fixture {    fixture_with(address, replies, Arc::new(RefusalMemory::default()))}/// The same, over a memory the suite already made — one read off a file an/// older build wrote.fn fixture_with(    address: Arc<RememberedAddress>,    replies: Vec<Reply>,    refusals: Arc<RefusalMemory>,) -> Fixture {    let exchange = ScriptedExchange::new(replies);    let clock = FixedClock::default_start();    let signer = RequestSigner::new(        Arc::new(DeviceIdentity::from_secret(&SEED).expect("an identity")),        Arc::new(clock.clone()),        Arc::new(SeededRandom::default()),    );    let transport = SignedHttp::new(        signer,        Arc::clone(&address) as Arc<dyn ServerAddress>,        Arc::clone(&refusals),        Arc::clone(&exchange) as Arc<dyn Exchange>,        Arc::new(clock.clone()),    );    Fixture {        transport,        exchange,        refusals,        clock,    }}fn home(replies: Vec<Reply>) -> Fixture {    fixture(RememberedAddress::at(HOME), replies)}fn pull() -> ClientRequest {    ClientRequest::get("/v1/sync/pull?workspaceId=ws-1&since=0")}fn push() -> ClientRequest {    ClientRequest::post_json("/v1/sync/push", br#"{"ops":[]}"#.to_vec())}#[test]fn only_a_duplicate_connection_refusal_carries_its_existing_id() {    // Preserve exactly the server's existing-row handle for Connect recovery,    // without turning every refusal body into untyped app error details.    for (status, code, id, expected) in [        (            409,            "connection_exists",            serde_json::json!("invented-harbor"),            Some("invented-harbor"),        ),        (            409,            "connection_exists",            serde_json::json!("  invented-harbor  "),            Some("invented-harbor"),        ),        (409, "connection_exists", serde_json::json!("   "), None),        (409, "connection_exists", serde_json::json!(7), None),        (409, "connection_exists", serde_json::Value::Null, None),        (            403,            "connection_exists",            serde_json::json!("invented-harbor"),            None,        ),        (            409,            "another_mac",            serde_json::json!("invented-harbor"),            None,        ),    ] {        let f = home(vec![Reply::json(            status,            &serde_json::json!({                "code": code, "error": "Invented refusal", "id": id            })            .to_string(),        )]);        let refusal = f            .transport            .call(ClientRequest::post_json(                "/v1/connections/browser",                b"{}".to_vec(),            ))            .unwrap_err();        assert_eq!(refusal.existing_connection_id.as_deref(), expected);        assert_eq!(refusal.code.as_deref(), Some(code));        assert_eq!(f.exchange.calls(), 1);    }}// ── The address ───────────────────────────────────────────────────────────#[test]fn a_device_that_has_joined_nothing_is_told_so_rather_than_reaching_a_default() {    // There is no default server and there never was: a phone learns one by    // joining it.    let f = fixture(RememberedAddress::none(), Vec::new());    let refusal = f.transport.call(pull()).expect_err("a refusal");    assert_eq!(refusal.code.as_deref(), Some("no_server"));    assert_eq!(refusal.message, NO_SERVER);    assert_eq!(f.exchange.calls(), 0, "nothing went out");}// ── 426 ───────────────────────────────────────────────────────────────────#[test]fn a_426_is_upgrade_required_by_status_whatever_code_the_body_carried() {    let f = home(vec![Reply::json(        426,        r#"{"error":"this build folds schema 44; the file is at 45","code":"something_else"}"#,    )]);    let refusal = f.transport.call(pull()).expect_err("a refusal");    assert_eq!(refusal.code.as_deref(), Some("upgrade_required"));    assert_eq!(f.exchange.calls(), 1, "surfaced, never silently retried");    assert!(f.refusals.standing().is_none(), "not a device refusal");}// ── 403 device_clock ──────────────────────────────────────────────────────#[test]fn a_clock_refusal_adopts_the_servers_time_retries_once_and_records_nothing() {    // The phone's clock is two minutes slow. `FixedClock::default_start()` is    // 2026-09-08T10:00:00Z = 1_788_861_600; the server says two minutes later.    let f = home(vec![        Reply::json(            403,            r#"{"code":"device_clock","error":"the clock is off","serverTime":1788861720}"#,        ),        Reply::ok(r#"{"ops":[],"lastSeq":0,"hasMore":false}"#),    ]);    let answer = f.transport.call(pull()).expect("an answer");    assert_eq!(answer.status, 200);    assert_eq!(f.exchange.calls(), 2);    assert_eq!(f.refusals.clock_offset_ms(HOME), 120_000);    assert!(        f.refusals.standing().is_none(),        "a phone that has just been told the time is not a device anybody refused"    );    assert_eq!(f.refusals.clock_hold_until(HOME), None);    // And the retry signed with the correction.    let corrected = cotton_core::device::signature::parse_device_sig_header(        f.exchange            .nth(1)            .header(cotton_core::device::signature::DEVICE_SIG_HEADER)            .expect("a signature"),    )    .expect("a signature");    assert_eq!(corrected.ts, 1_788_861_720);}#[test]fn a_second_clock_refusal_in_one_chain_holds_that_origin_for_a_minute() {    let f = home(vec![        Reply::json(403, r#"{"code":"device_clock","serverTime":1788861720}"#),        Reply::json(403, r#"{"code":"device_clock","serverTime":1788861720}"#),    ]);    let refusal = f.transport.call(pull()).expect_err("a refusal");    assert_eq!(refusal.code.as_deref(), Some("device_clock"));    assert_eq!(f.exchange.calls(), 2, "corrected once, then given up on");    assert_eq!(        f.refusals.clock_hold_until(HOME),        Some(f.clock.now().timestamp_millis() + refusal::CLOCK_HOLD_MS)    );}#[test]fn a_held_origin_is_refused_locally_and_the_hold_is_not_re_armed_from_inside_itself() {    let f = home(vec![        Reply::json(403, r#"{"code":"device_clock","serverTime":1788861720}"#),        Reply::json(403, r#"{"code":"device_clock","serverTime":1788861720}"#),    ]);    let _ = f.transport.call(pull()).expect_err("a refusal");    let held_until = f.refusals.clock_hold_until(HOME).expect("a hold");    let refusal = f.transport.call(pull()).expect_err("a refusal");    assert_eq!(refusal.message, CLOCK_HELD);    assert_eq!(f.exchange.calls(), 2, "nothing was sent");    assert_eq!(        f.refusals.clock_hold_until(HOME),        Some(held_until),        "a hold that re-armed itself would never lift"    );}#[test]fn a_hold_lifts_when_its_minute_is_up() {    let f = home(vec![        Reply::json(403, r#"{"code":"device_clock","serverTime":1788861720}"#),        Reply::json(403, r#"{"code":"device_clock","serverTime":1788861720}"#),        Reply::ok(r#"{"ops":[],"lastSeq":0,"hasMore":false}"#),    ]);    let _ = f.transport.call(pull()).expect_err("a refusal");    f.clock.advance(chrono::Duration::seconds(61));    let answer = f.transport.call(pull()).expect("an answer");    assert_eq!(answer.status, 200);}#[test]fn a_clock_refusal_with_nothing_readable_holds_at_once_rather_than_retrying_blind() {    let f = home(vec![Reply::json(403, r#"{"code":"device_clock"}"#)]);    let refusal = f.transport.call(pull()).expect_err("a refusal");    assert_eq!(refusal.code.as_deref(), Some("device_clock"));    assert_eq!(f.exchange.calls(), 1);    assert!(f.refusals.clock_hold_until(HOME).is_some());}#[test]fn the_date_header_is_read_when_the_body_names_no_time() {    let f = home(vec![        Reply::json(403, r#"{"code":"device_clock"}"#)            .with_header("date", "Tue, 08 Sep 2026 10:02:00 GMT"),        Reply::ok(r#"{"ops":[],"lastSeq":0,"hasMore":false}"#),    ]);    f.transport.call(pull()).expect("an answer");    assert_eq!(f.refusals.clock_offset_ms(HOME), 120_000);}#[test]fn a_server_time_that_is_a_string_of_digits_is_seconds_and_an_iso_one_is_an_instant() {    for (body, expected) in [        (            r#"{"code":"device_clock","serverTime":"1788861720"}"#,            120_000,        ),        (            r#"{"code":"device_clock","serverTime":"2026-09-08T10:02:00Z"}"#,            120_000,        ),    ] {        let f = home(vec![            Reply::json(403, body),            Reply::ok(r#"{"ops":[],"lastSeq":0,"hasMore":false}"#),        ]);        f.transport.call(pull()).expect("an answer");        assert_eq!(f.refusals.clock_offset_ms(HOME), expected, "{body}");    }}// ── The four terminal refusals ────────────────────────────────────────────#[test]fn a_device_refusal_is_recorded_and_every_later_owner_route_is_refused_without_sending() {    let f = home(vec![Reply::json(        403,        r#"{"code":"device_revoked","error":"this device's access was revoked","serverName":"studio"}"#,    )]);    let refusal = f.transport.call(pull()).expect_err("a refusal");    assert_eq!(refusal.code.as_deref(), Some("device_revoked"));    let standing = f.refusals.standing_terminal().expect("a note");    assert_eq!(standing.kind, RefusalKind::Revoked);    assert_eq!(standing.server_url.as_deref(), Some(HOME));    assert_eq!(standing.server_name.as_deref(), Some("studio"));    let again = f.transport.call(push()).expect_err("a refusal");    assert_eq!(again.code.as_deref(), Some("device_revoked"));    assert_eq!(        owner_requests(&f),        1,        "retrying a decision only a person can reverse is a battery, not a fix"    );}#[test]fn a_pairing_route_still_goes_out_while_a_terminal_refusal_stands() {    // The way back in.    let f = home(vec![        Reply::json(403, r#"{"code":"device_revoked"}"#),        Reply::json(            202,            r#"{"pending":true,"pairingId":"p1","digits":"046219"}"#,        ),    ]);    let _ = f.transport.call(pull()).expect_err("a refusal");    let answer = f        .transport        .call(ClientRequest::post_json("/v1/devices/pair", b"{}".to_vec()))        .expect("an answer");    assert_eq!(answer.status, 202);    assert!(        f.refusals.standing_terminal().is_some(),        "and a 202 on a pairing route does not clear the note"    );}#[test]fn a_bad_signature_on_an_owner_route_is_terminal_and_on_a_pairing_route_is_not() {    let owner = home(vec![Reply::json(401, r#"{"code":"device_bad_signature"}"#)]);    let _ = owner.transport.call(pull()).expect_err("a refusal");    assert_eq!(        owner.refusals.standing_terminal().expect("a note").kind,        RefusalKind::BadSignature    );    let pairing = home(vec![Reply::json(401, r#"{"code":"device_bad_signature"}"#)]);    let _ = pairing        .transport        .call(ClientRequest::post_json("/v1/devices/pair", b"{}".to_vec()))        .expect_err("a refusal");    assert!(        pairing.refusals.standing().is_none(),        "Join's own sentence carries it; a standing note would paint over the way out"    );}#[test]fn a_401_with_no_code_or_somebody_elses_records_nothing() {    for body in [        "",        "<html>a proxy said no</html>",        r#"{"error":"nope"}"#,        r#"{"code":"something_else"}"#,    ] {        let f = home(vec![Reply::new(401, body.as_bytes().to_vec())]);        let _ = f.transport.call(pull()).expect_err("a refusal");        assert!(f.refusals.standing().is_none(), "{body}");    }}#[test]fn a_403_with_a_code_this_build_has_no_opinion_about_records_nothing() {    let f = home(vec![Reply::json(403, r#"{"code":"scope_refused"}"#)]);    let refusal = f.transport.call(pull()).expect_err("a refusal");    assert_eq!(refusal.code.as_deref(), Some("scope_refused"));    assert!(f.refusals.standing().is_none());}#[test]fn a_clock_note_never_paints_over_a_terminal_one() {    let f = home(vec![        Reply::json(403, r#"{"code":"device_revoked"}"#),        Reply::json(403, r#"{"code":"device_clock"}"#),    ]);    let _ = f.transport.call(pull()).expect_err("a refusal");    // A pairing route still goes out, and this one answers a clock refusal.    let _ = f        .transport        .call(ClientRequest::post_json("/v1/devices/pair", b"{}".to_vec()))        .expect_err("a refusal");    assert_eq!(        f.refusals.standing().expect("a note").kind,        RefusalKind::Revoked,        "the clock is a condition; revocation is a decision"    );    assert!(        f.refusals.clock_hold_until(HOME).is_some(),        "the hold is still set — only the NOTE is left alone"    );}#[test]fn a_refusal_body_longer_than_four_hundred_bytes_is_not_read_for_a_code() {    // A refusal envelope is a hundred bytes. A body longer than this is a    // captive portal, and reading it whole to be disappointed by it is reading    // somebody else's page into memory.    let padding = "x".repeat(500);    let f = home(vec![Reply::json(        403,        &format!(r#"{{"padding":"{padding}","code":"device_revoked"}}"#),    )]);    let _ = f.transport.call(pull()).expect_err("a refusal");    assert!(f.refusals.standing().is_none());}// ── The ordinary answers ──────────────────────────────────────────────────#[test]fn a_204_answers_an_empty_body_rather_than_a_failure() {    let f = home(vec![Reply::new(204, Vec::new())]);    let answer = f.transport.call(pull()).expect("an answer");    assert_eq!(answer.status, 204);    assert!(answer.body.is_empty());}#[test]fn retry_after_travels_so_the_loop_waits_as_long_as_the_server_asked() {    let f = home(vec![        Reply::json(429, r#"{"code":"rate_limited"}"#).with_header("retry-after", "300")    ]);    let refusal = f.transport.call(pull()).expect_err("a refusal");    assert_eq!(refusal.retry_after_seconds, Some(300));    assert_eq!(refusal.code.as_deref(), Some("rate_limited"));    assert!(        f.refusals.standing().is_none(),        "429 is not about this device"    );}#[test]fn the_last_refusal_is_what_the_cycle_asks_so_a_terminal_one_stops_the_loop() {    let f = home(vec![Reply::json(403, r#"{"code":"device_not_approved"}"#)]);    let _ = f.transport.call(pull()).expect_err("a refusal");    let last = f.transport.last_refusal().expect("a refusal");    assert!(last.is_terminal_device_refusal());    // And a good answer clears it, so a later failure is not read as this one.    let ok = home(vec![Reply::ok("{}")]);    ok.transport.call(pull()).expect("an answer");    assert!(ok.transport.last_refusal().is_none());}#[test]fn the_request_carries_the_two_device_headers_and_no_bearer() {    let f = home(vec![Reply::ok("{}")]);    f.transport.call(push()).expect("an answer");    let seen = f.exchange.only();    assert!(seen.header("x-cotton-device").is_some());    assert!(seen.header("x-cotton-device-sig").is_some());    assert_eq!(seen.header("content-type"), Some("application/json"));    assert!(        seen.header("authorization").is_none(),        "the device signature is the whole credential"    );    assert_eq!(seen.body, br#"{"ops":[]}"#, "the body as the hash saw it");}// ── the erase a revocation can carry ──────────────────────────────────────#[test]fn a_revocation_the_owner_marked_as_an_erase_is_recorded_with_the_flag() {    // `DELETE /v1/devices/approved/{id} {"erase":true}` files the row as    // `revoked_reason = "erased"`, and this 403 is how the phone finds out.    let f = home(vec![Reply::json(        403,        r#"{"code":"device_revoked","error":"this device's access was revoked","erase":true}"#,    )]);    f.transport.call(pull()).expect_err("a refusal");    let standing = f.refusals.standing_terminal().expect("a note");    assert_eq!(standing.kind, RefusalKind::Revoked);    assert!(standing.erase, "the screen takes the second verb without asking");}#[test]fn a_revocation_that_says_nothing_records_no_erase() {    let f = home(vec![Reply::json(403, r#"{"code":"device_revoked"}"#)]);    f.transport.call(pull()).expect_err("a refusal");    assert!(!f.refusals.standing_terminal().expect("a note").erase);}#[test]fn only_a_revocation_may_carry_an_erase_and_no_other_refusal_can_wipe_a_phone() {    // THE ONE THIS GUARDS AGAINST: a server — or something between — answering    // `403 {"code":"device_not_approved","erase":true}` and taking somebody's    // photographs off their phone. The erase is the answer to a REVOKE the    // owner ticked a box on, and `device_revoked` is the only code that says so.    for code in ["device_not_approved", "device_clock"] {        let f = home(vec![Reply::json(            403,            &format!(r#"{{"code":"{code}","erase":true}}"#),        )]);        f.transport.call(pull()).expect_err("a refusal");        let standing = f.refusals.standing().expect("a note");        assert!(!standing.erase, "{code} must not be able to wipe a device");    }}#[test]fn an_erase_that_is_not_a_boolean_said_nothing() {    // A string is not a `true`. The safe reading of a body this build cannot    // parse is the one that ASKS the person.    let f = home(vec![Reply::json(        403,        r#"{"code":"device_revoked","erase":"true"}"#,    )]);    f.transport.call(pull()).expect_err("a refusal");    assert!(!f.refusals.standing_terminal().expect("a note").erase);}// ── a verdict belongs to the machine that gave it ─────────────────────────//// 2026-09-28: mac-b, a stale Mac, held the household's relay name for sixty// seconds and answered a headless server's peer sync `403 device_not_approved`// — its copy lacked the approval. The note stopped that server for two hours// without once asking mac-a, which had it approved, because the name is the same// whichever Mac answers it.use cotton_core::device::server_id::SERVER_ID_HEADER;/// A refusal, said by a named machine.fn refused_by(tag: &str, body: &str) -> Reply {    Reply::json(403, body).with_header(SERVER_ID_HEADER, tag)}/// `GET /health`, answered by a named machine.fn answered_by(tag: &str) -> Reply {    Reply::ok(r#"{"ok":true}"#).with_header(SERVER_ID_HEADER, tag)}const NOT_APPROVED: &str = r#"{"code":"device_not_approved","serverName":"studio"}"#;const EXCHANGED: &str = r#"{"workspaceId":"ws-1","ops":[],"cursors":{},"hasMore":false,"schemaVersion":1,"appliedRows":{},"rejected":[],"seen":{}}"#;/// Requests that asked about THIS DEVICE — everything but the question of who/// answers the name.fn owner_requests(f: &Fixture) -> usize {    f.exchange        .seen()        .iter()        .filter(|seen| seen.path != ANSWERER_PROBE_PATH)        .count()}#[test]fn a_refusal_records_which_machine_said_it() {    let f = home(vec![refused_by("mac-b", NOT_APPROVED)]);    f.transport.call(pull()).expect_err("a refusal");    let standing = f.refusals.standing_terminal().expect("a note");    assert_eq!(standing.refuser, Refuser::Server("mac-b".to_string()));    assert_eq!(standing.server_url.as_deref(), Some(HOME), "and still the name");}#[test]fn the_same_machine_keeps_its_verdict_without_being_asked_about_this_device_again() {    let f = home(vec![refused_by("mac-b", NOT_APPROVED), answered_by("mac-b")]);    f.transport.call(pull()).expect_err("a refusal");    let again = f.transport.call(pull()).expect_err("the same verdict");    assert_eq!(again.code.as_deref(), Some("device_not_approved"));    assert_eq!(owner_requests(&f), 1, "the refused question never went out again");    let probe = f.exchange.nth(1);    assert_eq!(probe.path, ANSWERER_PROBE_PATH);    assert!(        probe.header("x-cotton-device-sig").is_none(),        "the name is asked about itself, unsigned — never about this device"    );    // And for a minute the name is not even asked who answers it.    f.transport.call(pull()).expect_err("the same verdict");    assert_eq!(f.exchange.calls(), 2);    f.clock.advance(chrono::Duration::milliseconds(        refusal::ANSWERER_QUIET_MS,    ));    // The script has run out, so the name does not answer — which is not a    // different machine either.    f.transport.call(pull()).expect_err("the same verdict");    assert_eq!(f.exchange.calls(), 3, "asked once more after the minute");    assert_eq!(owner_requests(&f), 1);}#[test]fn another_machine_answering_the_name_is_asked_once_and_its_yes_clears_the_note() {    // mac-a has the name back, and has this device approved.    let dir = tempfile::tempdir().expect("a temp dir");    let path = dir.path().join("client").join("refusal.json");    let f = fixture_with(        RememberedAddress::at(HOME),        vec![            refused_by("mac-b", NOT_APPROVED),            answered_by("mac-a"),            Reply::ok(EXCHANGED).with_header(SERVER_ID_HEADER, "mac-a"),            Reply::ok(EXCHANGED).with_header(SERVER_ID_HEADER, "mac-a"),        ],        Arc::new(RefusalMemory::at(&path)),    );    f.transport.call(pull()).expect_err("mac-b's refusal");    assert!(path.exists(), "mac-b's verdict was written down");    f.transport.call(pull()).expect("mac-a admits this device");    assert!(f.refusals.standing().is_none(), "the verdict was mac-b's, and it goes");    assert!(!path.exists(), "and so does the file");    f.transport.call(pull()).expect("an ordinary answer");    assert_eq!(        f.exchange.calls(),        4,        "no note, so nothing asks the name who answers it any more"    );}#[test]fn another_machine_that_refuses_too_replaces_the_note_and_then_keeps_its_own() {    let f = home(vec![        refused_by("mac-b", NOT_APPROVED),        answered_by("mac-a"),        refused_by("mac-a", r#"{"code":"device_revoked"}"#),        answered_by("mac-a"),    ]);    f.transport.call(pull()).expect_err("mac-b's refusal");    let refusal = f.transport.call(pull()).expect_err("mac-a's refusal");    assert_eq!(refusal.code.as_deref(), Some("device_revoked"));    let standing = f.refusals.standing_terminal().expect("a note");    assert_eq!(standing.kind, RefusalKind::Revoked);    assert_eq!(standing.refuser, Refuser::Server("mac-a".to_string()));    f.transport.call(pull()).expect_err("mac-a's verdict, held");    assert_eq!(owner_requests(&f), 2, "ONE fresh attempt, then mac-a's own verdict holds");}#[test]fn a_name_that_answers_without_a_tag_is_not_a_reason_to_ask_again() {    // It might be mac-b itself, on a build older than the header.    let f = home(vec![        refused_by("mac-b", NOT_APPROVED),        Reply::ok(r#"{"ok":true}"#),    ]);    f.transport.call(pull()).expect_err("a refusal");    f.transport.call(pull()).expect_err("the same verdict");    assert_eq!(owner_requests(&f), 1);}#[test]fn a_note_from_a_server_that_named_nobody_is_asked_again_when_a_named_machine_answers() {    // mac-b on an older build refused without a tag; a machine that names itself    // is at least not that build, and gets its one attempt.    let f = home(vec![        Reply::json(403, NOT_APPROVED),        answered_by("mac-a"),        Reply::ok(EXCHANGED),    ]);    f.transport.call(pull()).expect_err("an unnamed refusal");    assert_eq!(        f.refusals.standing_terminal().expect("a note").refuser,        Refuser::Unnamed    );    f.transport.call(pull()).expect("mac-a admits this device");    assert!(f.refusals.standing().is_none());}/// A `refusal.json` whose note recorded no machine, as an older build wrote/// it — Mine's, in today's file shape.fn older_builds_note(path: &std::path::Path, code: &str, kind: &str) {    std::fs::create_dir_all(path.parent().expect("a parent")).expect("the directory");    std::fs::write(        path,        format!(            r#"{{"mine":{{"kind":"{kind}","code":"{code}","serverUrl":"{HOME}","serverName":"studio","at":"2026-09-28T10:00:00.000Z","servingEpoch":null}}}}"#        ),    )    .expect("the note");}#[test]fn an_older_builds_note_is_stale_after_one_retry_that_clears_it_when_admitted() {    let dir = tempfile::tempdir().expect("a temp dir");    let path = dir.path().join("refusal.json");    older_builds_note(&path, "device_not_approved", "not_approved");    let f = fixture_with(        RememberedAddress::at(HOME),        vec![Reply::ok(EXCHANGED).with_header(SERVER_ID_HEADER, "mac-a")],        Arc::new(RefusalMemory::at(&path)),    );    f.transport.call(pull()).expect("the one retry, admitted");    assert_eq!(f.exchange.calls(), 1, "no question first: the note named no machine to compare");    assert!(f.refusals.standing().is_none());    assert!(!path.exists());}#[test]fn an_older_builds_note_refused_again_becomes_a_note_about_that_machine_and_never_loops() {    let dir = tempfile::tempdir().expect("a temp dir");    let path = dir.path().join("refusal.json");    older_builds_note(&path, "device_not_approved", "not_approved");    let f = fixture_with(        RememberedAddress::at(HOME),        vec![refused_by("mac-a", NOT_APPROVED), answered_by("mac-a")],        Arc::new(RefusalMemory::at(&path)),    );    f.transport.call(pull()).expect_err("refused on the retry too");    assert_eq!(        RefusalMemory::at(&path).standing().expect("a note").refuser,        Refuser::Server("mac-a".to_string()),        "the note on disk is now mac-a's, and is held against mac-a"    );    f.transport.call(pull()).expect_err("mac-a's verdict, held");    assert_eq!(owner_requests(&f), 1, "one fresh attempt, never a loop");}#[test]fn an_older_builds_note_refused_again_by_a_server_that_names_nobody_is_spent_all_the_same() {    // The retry is spent by being ANSWERED — so a relaunch does not buy    // another one, and neither does the next call.    let dir = tempfile::tempdir().expect("a temp dir");    let path = dir.path().join("refusal.json");    older_builds_note(&path, "device_not_approved", "not_approved");    let f = fixture_with(        RememberedAddress::at(HOME),        vec![Reply::json(403, NOT_APPROVED), Reply::ok(r#"{"ok":true}"#)],        Arc::new(RefusalMemory::at(&path)),    );    f.transport.call(pull()).expect_err("refused on the retry");    f.transport.call(pull()).expect_err("the verdict, held");    assert_eq!(owner_requests(&f), 1);    assert_eq!(        RefusalMemory::at(&path).standing().expect("a note").refuser,        Refuser::Unnamed    );}#[test]fn an_older_builds_retry_that_reached_nobody_is_not_spent() {    // Offline is not an attempt: nothing was asked, so the next call may ask.    let dir = tempfile::tempdir().expect("a temp dir");    let path = dir.path().join("refusal.json");    older_builds_note(&path, "device_not_approved", "not_approved");    let f = fixture_with(        RememberedAddress::at(HOME),        Vec::new(),        Arc::new(RefusalMemory::at(&path)),    );    let refusal = f.transport.call(pull()).expect_err("nobody answered");    assert_eq!(refusal.status, 0);    assert_eq!(        f.refusals.standing().expect("the note stands").refuser,        Refuser::Unrecorded    );}#[test]fn the_live_sockets_headers_never_take_the_fresh_attempt() {    // The socket's answer never comes back through the ladder, so it could    // neither clear nor replace the note: the loop's own request does that.    let dir = tempfile::tempdir().expect("a temp dir");    let path = dir.path().join("refusal.json");    older_builds_note(&path, "device_not_approved", "not_approved");    let f = fixture_with(        RememberedAddress::at(HOME),        Vec::new(),        Arc::new(RefusalMemory::at(&path)),    );    let refused = f        .transport        .upgrade_headers(&format!("{}/v1/live", HOME.replace("http", "ws")))        .expect_err("refused from the note");    assert_eq!(refused.code.as_deref(), Some("device_not_approved"));    assert_eq!(f.exchange.calls(), 0);}// ── and a revocation the owner marked as an erase still acts ──────────────#[test]fn an_erase_from_the_same_machine_stands_flag_and_all_without_asking_again() {    // The owner revoked this device with "erase" on mac-a; mac-a still answers the    // name. Nothing about the machine check may soften that: the note stands,    // the flag stands, and the refused question is never put again.    let dir = tempfile::tempdir().expect("a temp dir");    let path = dir.path().join("refusal.json");    let f = fixture_with(        RememberedAddress::at(HOME),        vec![            refused_by("mac-a", r#"{"code":"device_revoked","erase":true}"#),            answered_by("mac-a"),        ],        Arc::new(RefusalMemory::at(&path)),    );    f.transport.call(pull()).expect_err("revoked, with an erase");    f.transport.call(pull()).expect_err("the same verdict, held");    assert_eq!(owner_requests(&f), 1);    let held = RefusalMemory::at(&path).standing().expect("the note outlives a relaunch");    assert_eq!(held.kind, RefusalKind::Revoked);    assert!(held.erase, "the screen still takes the second verb without asking");    assert_eq!(held.refuser, Refuser::Server("mac-a".to_string()));}/// RULE: A device_revoked note is never re-asked of another machine answering the name, so a stale Mac can never clear a revocation or the erase it carries; only pairing goes out.#[test]fn a_revocation_is_never_re_asked_of_another_machine_erase_and_all() {    // mac-b gave the note; mac-a answers the name now. A revocation is not a    // verdict a stale copy gives wrongly, so nothing goes out — not even the    // question of who answers the name — and the flag stands.    let f = home(vec![        refused_by("mac-b", r#"{"code":"device_revoked","erase":true}"#),        answered_by("mac-a"),        Reply::ok(EXCHANGED).with_header(SERVER_ID_HEADER, "mac-a"),    ]);    f.transport.call(pull()).expect_err("mac-b's revocation");    let again = f.transport.call(pull()).expect_err("held, whoever answers");    assert_eq!(again.code.as_deref(), Some("device_revoked"));    assert_eq!(f.exchange.calls(), 1, "neither the probe nor the owner request went out");    let held = f.refusals.standing_terminal().expect("a note");    assert!(held.erase);    assert_eq!(held.refuser, Refuser::Server("mac-b".to_string()));}#[test]fn a_revocation_without_an_erase_is_not_re_asked_either() {    let f = home(vec![        refused_by("mac-b", r#"{"code":"device_revoked"}"#),        answered_by("mac-a"),        Reply::ok(EXCHANGED).with_header(SERVER_ID_HEADER, "mac-a"),    ]);    f.transport.call(pull()).expect_err("mac-b's revocation");    f.transport.call(pull()).expect_err("held");    assert_eq!(f.exchange.calls(), 1);    assert_eq!(        f.refusals.standing_terminal().expect("a note").kind,        RefusalKind::Revoked    );}// ── The whole call's deadline, over a real socket ─────────────────────────#[test]fn the_body_read_waits_only_for_what_is_left_and_never_overruns_by_a_read() {    // The exchange's own deadline is generous (thirty seconds); the CALL's is    // one second. The head arrives at once and then nothing — so a check made    // before each read, with the read itself free to block for the socket's    // whole window, would end at thirty seconds rather than one.    let port =        crate::transport::scripted::silent_after(b"HTTP/1.1 200 OK\r\nContent-Length: 100000\r\n\r\n");    let refused = crate::transport::scripted::finishes(Duration::from_secs(4), move || {        let origin = Origin::parse(&format!("http://127.0.0.1:{port}")).expect("an origin");        let authority = origin.authority();        let answer = crate::transport::SocketExchange            .send(                &origin,                &super::super::http1::Http1Request {                    method: "GET",                    path: "/",                    authority: &authority,                    headers: Vec::new(),                    body: None,                },                Duration::from_secs(30),            )            .expect("the head");        let clock = crate::seams::SystemClock;        let deadline_ms = clock.now().timestamp_millis() + 1_000;        read_whole(answer, &clock, deadline_ms).map(|_| ())    })    .expect_err("a body that never ends was read whole");    assert!(refused.message.contains("longer than this route waits"), "{refused:?}");}/// ONE CEILING FOR THE WHOLE CALL, the clock retry included: a refusal that/// took forty seconds to arrive leaves the corrected retry twenty, never a/// fresh sixty — and one that took the whole ceiling is the answer.#[test]fn the_clock_retry_gets_what_the_first_try_left_of_the_ceiling() {    for (took_ms, retried_within) in [(40_000_u64, Some(20_000_u64)), (60_000, None)] {        let clock = FixedClock::default_start();        let exchange = ScriptedExchange::on_clock(            vec![                Reply::json(403, r#"{"code":"device_clock","serverTime":1788861720}"#)                    .after_ms(took_ms),                Reply::ok(r#"{"ops":[],"lastSeq":0,"hasMore":false}"#),            ],            &clock,        );        let transport = SignedHttp::new(            RequestSigner::new(                Arc::new(DeviceIdentity::from_secret(&SEED).expect("an identity")),                Arc::new(clock.clone()),                Arc::new(SeededRandom::default()),            ),            RememberedAddress::at(HOME) as Arc<dyn ServerAddress>,            Arc::new(RefusalMemory::default()),            Arc::clone(&exchange) as Arc<dyn Exchange>,            Arc::new(clock.clone()),        );        let answer = transport.call(pull());        match retried_within {            Some(left) => {                assert_eq!(answer.expect("the retry answered").status, 200);                assert_eq!(                    exchange.nth(1).ceiling,                    std::time::Duration::from_millis(left),                    "a refusal after {took_ms} ms"                );            }            None => {                let refusal = answer.expect_err("nothing was left to retry in");                assert_eq!(refusal.code.as_deref(), Some("device_clock"));                assert_eq!(exchange.calls(), 1, "not retried with no time left");            }        }    }}#[test]fn a_body_read_after_open_asks_the_guard_so_a_hold_taken_in_between_is_caught() {    // `open` returns with the head read and the body still on the wire. A    // caller that took the file before reading it would wait on the network    // inside the hold — the one thing the guard exists to refuse.    let fixture = home(vec![Reply::ok(r#"{"ops":[]}"#)]);    let mut answer = fixture.transport.open(&pull()).expect("an answer");    let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {        let _held = cotton_store::held::holding("the served file");        let mut body = Vec::new();        let _ = std::io::Read::read_to_end(&mut answer, &mut body);    }));    let message = caught        .expect_err("a body read inside a hold panics in a debug build")        .downcast::<String>()        .map(|text| *text)        .unwrap_or_default();    assert!(message.contains("the body of a signed answer"), "{message}");    // And outside a hold the same answer reads as it always did.    let fixture = home(vec![Reply::ok(r#"{"ops":[]}"#)]);    let mut answer = fixture.transport.open(&pull()).expect("an answer");    let mut body = Vec::new();    std::io::Read::read_to_end(&mut answer, &mut body).expect("the body");    assert_eq!(body, br#"{"ops":[]}"#);}// ── which app the server is, under every signed request ───────────────────mod which_app {    use super::*;    use cotton_core::flavor::Flavor;    const DEV_HOME: &str = "https://studio-dev.relay.cottondb.com";    const LAN: &str = "http://192.168.1.14:8791";    fn as_app(base: &str, app: Flavor, replies: Vec<Reply>) -> Fixture {        let mut f = fixture(RememberedAddress::at(base), replies);        f.transport = f.transport.as_app(Some(app));        f    }    fn health(flavor: Option<&str>) -> Reply {        match flavor {            Some(flavor) => Reply::ok(&format!(r#"{{"ok":true,"schemaVersion":1,"flavor":"{flavor}"}}"#)),            None => Reply::ok(r#"{"ok":true,"schemaVersion":1}"#),        }    }    fn signed(f: &Fixture) -> usize {        f.exchange            .seen()            .iter()            .filter(|seen| seen.header("x-cotton-device-sig").is_some())            .count()    }    /// RULE: A Cotton Dev device signs nothing to the real household — a remembered relay name that is CottonDB's is refused with no request at all.    #[test]    fn a_remembered_real_name_is_refused_before_anything_goes_out() {        let f = as_app(HOME, Flavor::Dev, vec![health(Some("dev")), Reply::ok("{}")]);        for request in [pull(), push()] {            let refusal = f.transport.call(request).expect_err("a refusal");            assert_eq!(refusal.code.as_deref(), Some(OTHER_APP));            assert!(refusal.message.contains("studio"), "{}", refusal.message);        }        assert!(f.transport.upgrade_headers("/v1/live").is_err(), "the live socket too");        assert_eq!(f.exchange.calls(), 0, "nothing went out");        assert!(f.refusals.standing_terminal().is_none(), "and nothing was recorded against this device");    }    /// RULE: A Cotton Dev device remembering a LAN address signs nothing to a server that says it is real, or says nothing (the frozen real one).    #[test]    fn a_lan_server_that_is_not_cotton_dev_is_asked_and_refused_before_the_key() {        for said in [None, Some("real"), Some("staging")] {            let f = as_app(LAN, Flavor::Dev, vec![health(said), Reply::ok("{}"), health(said), Reply::ok("{}")]);            let refusal = f.transport.call(push()).expect_err("a refusal");            assert_eq!(refusal.code.as_deref(), Some(OTHER_APP), "{said:?}");            assert_eq!(signed(&f), 0, "{said:?}: the push was never signed");            assert_eq!(f.exchange.seen()[0].path, "/health");            // A refusal is not remembered as an answer: asked again, refused again.            assert!(f.transport.call(push()).is_err());            assert_eq!(signed(&f), 0);        }    }    /// The real app refuses a Cotton Dev server the same way.    #[test]    fn the_real_app_refuses_a_cotton_dev_server_and_a_cotton_dev_name() {        let f = as_app(LAN, Flavor::Real, vec![health(Some("dev")), Reply::ok("{}")]);        assert_eq!(f.transport.call(pull()).expect_err("a refusal").code.as_deref(), Some(OTHER_APP));        assert_eq!(signed(&f), 0);        let f = as_app(DEV_HOME, Flavor::Real, vec![health(None), Reply::ok("{}")]);        assert_eq!(f.transport.call(pull()).expect_err("a refusal").code.as_deref(), Some(OTHER_APP));        assert_eq!(f.exchange.calls(), 0);    }    #[test]    fn this_app_s_server_is_asked_once_and_every_request_after_goes_straight_out() {        let f = as_app(DEV_HOME, Flavor::Dev, vec![health(Some("dev")), Reply::ok("{}"), Reply::ok("{}")]);        f.transport.call(pull()).expect("an answer");        f.transport.call(push()).expect("an answer");        let paths: Vec<String> = f.exchange.seen().iter().map(|seen| seen.path.clone()).collect();        assert_eq!(paths[0], "/health");        assert_eq!(paths.len(), 3, "one question, then the two requests: {paths:?}");        assert_eq!(signed(&f), 2);        // The frozen real server says nothing, and the real app takes it.        let f = as_app(HOME, Flavor::Real, vec![health(None), Reply::ok("{}")]);        f.transport.call(pull()).expect("an answer");    }    /// A relay's 502 while the Mac behind it sleeps is no word about which app    /// it is: the request fails as unanswered, not as the other app's, and the    /// next one asks again.    #[test]    fn a_health_that_did_not_answer_is_not_a_server_saying_it_is_real() {        let f = as_app(            DEV_HOME,            Flavor::Dev,            vec![Reply::new(502, b"bad gateway".to_vec()), health(Some("dev")), Reply::ok("{}")],        );        let refusal = f.transport.call(pull()).expect_err("unanswered");        assert_ne!(refusal.code.as_deref(), Some(OTHER_APP));        assert_eq!(refusal.status, 502);        f.transport.call(pull()).expect("asked again, and answered");    }    #[test]    fn a_process_that_declared_nothing_has_no_rule_to_apply() {        let f = fixture(RememberedAddress::at(HOME), vec![Reply::ok("{}")]);        f.transport.call(pull()).expect("an answer");        assert_eq!(f.exchange.calls(), 1, "no question was asked");    }}// ── The database a request names ──────────────────────────────────────────//// The server opens the ONE file a signed request names// (`cotton_core::device::database`), so the transport adds `database=` to// every request it signs — in the query, under the signature.#[test]fn every_signed_request_names_the_database_its_address_knows_and_signs_it() {    let f = fixture(        RememberedAddress::at_in(HOME, "ws-1"),        vec![Reply::ok("{}"), Reply::ok("{}")],    );    f.transport        .call(ClientRequest::get("/v1/devices/approved"))        .expect("answered");    f.transport        .call(ClientRequest::get("/v1/repos/r1/history?limit=5"))        .expect("answered");    let seen = f.exchange.seen();    assert_eq!(seen[0].path, "/v1/devices/approved?database=ws-1");    assert_eq!(seen[1].path, "/v1/repos/r1/history?limit=5&database=ws-1");}#[test]fn a_pairing_route_and_the_database_listing_name_no_database() {    let f = fixture(        RememberedAddress::at_in(HOME, "ws-1"),        vec![Reply::ok("{}"), Reply::ok("{}")],    );    f.transport        .call(ClientRequest::post_json("/v1/devices/pair", b"{}".to_vec()))        .expect("answered");    f.transport        .call(ClientRequest::get("/v1/me/databases"))        .expect("answered");    let paths: Vec<String> = f.exchange.seen().into_iter().map(|seen| seen.path).collect();    assert_eq!(paths, ["/v1/devices/pair", "/v1/me/databases"]);}#[test]fn a_database_the_caller_already_named_wins() {    // The join names the database it was approved for before the device has    // remembered one.    let f = fixture(RememberedAddress::at_in(HOME, "ws-1"), vec![Reply::ok("{}")]);    f.transport        .call(ClientRequest::post_json("/v1/me?database=ws-approved", b"{}".to_vec()))        .expect("answered");    assert_eq!(f.exchange.only().path, "/v1/me?database=ws-approved");}#[test]fn a_device_that_knows_no_database_invents_none() {    // The server answers `database_required`; this side does not guess.    let f = home(vec![Reply::ok("{}")]);    f.transport        .call(ClientRequest::get("/v1/devices/approved"))        .expect("answered");    assert_eq!(f.exchange.only().path, "/v1/devices/approved");}#[test]fn the_socket_url_names_the_database_it_signs() {    let f = fixture(RememberedAddress::at_in(HOME, "ws-1"), Vec::new());    let (url, _headers) = f        .transport        .upgrade_headers("wss://studio.relay.cottondb.com/v1/sessions/attach?session=s1")        .expect("headers");    assert_eq!(        url,        "wss://studio.relay.cottondb.com/v1/sessions/attach?session=s1&database=ws-1"    );}// ── Another person's Mac decides nothing about Mine (4 Oct 2026) ──────────//// Being removed from somebody's shared database answered `403 device_revoked`// to the listing at THEIR Mac — a database-less request, keyed Mine — and the// note was filed under Mine, so the phone refused every owner route to every// server, its own household included, until it was paired again. Walked on// two simulators (ws-mac-b-share1): the member could not claim an invite to a// second database, and its own sync was stopped.const FOREIGN: &str = "http://192.168.1.91:9790";#[test]fn a_revocation_from_another_persons_mac_is_never_filed_against_mine() {    let f = home(vec![        Reply::json(403, r#"{"code":"device_revoked","error":"this device was revoked"}"#),        Reply::ok(r#"{"ops":[],"lastSeq":0,"hasMore":false}"#),    ]);    let refusal = f        .transport        .call_at(FOREIGN, ClientRequest::get("/v1/me/databases"))        .expect_err("the foreign Mac's refusal is still handed back");    assert_eq!(refusal.code.as_deref(), Some("device_revoked"));    assert!(        f.refusals.standing_terminal().is_none(),        "a stranger's verdict is not a note about Mine"    );    f.transport.call(pull()).expect("home still answers");    assert_eq!(owner_requests(&f), 2, "the home request went out");}#[test]fn a_revocation_from_another_persons_mac_about_one_of_its_databases_stops_that_place_only() {    let f = home(vec![        Reply::json(403, r#"{"code":"device_revoked"}"#),        Reply::ok(r#"{"ops":[],"lastSeq":0,"hasMore":false}"#),    ]);    let _ = f        .transport        .call_at(FOREIGN, ClientRequest::get("/v1/sync/exchange?database=garden"))        .expect_err("a refusal");    assert!(        f.refusals.standing_for(&refusal::NoteKey::Place("garden".into())).is_some(),        "the place it was removed from keeps its note"    );    assert!(f.refusals.standing_terminal().is_none());    f.transport.call(pull()).expect("home still answers");    let again = f        .transport        .call_at(FOREIGN, ClientRequest::get("/v1/sync/exchange?database=garden"))        .expect_err("the place stays refused");    assert_eq!(again.code.as_deref(), Some("device_revoked"));    assert_eq!(owner_requests(&f), 2, "and refused without sending");}#[test]fn a_mine_note_a_foreign_mac_wrote_before_the_fix_is_dropped_on_the_next_request() {    // The note a poisoned phone already holds on disk.    let refusals = Arc::new(RefusalMemory::default());    refusals.note_for(        refusal::NoteKey::Mine,        Some(refusal::DeviceRefusal {            kind: RefusalKind::Revoked,            code: "device_revoked".into(),            server_url: Some(FOREIGN.into()),            server_name: None,            at: "2026-10-04T15:12:10.841Z".into(),            erase: false,            serving_epoch: Some(1),            refuser: Refuser::Unrecorded,            device: None,        }),    );    let f = fixture_with(        RememberedAddress::at(HOME),        vec![Reply::ok(r#"{"ops":[],"lastSeq":0,"hasMore":false}"#)],        refusals,    );    f.transport.call(pull()).expect("home answers again");    assert_eq!(owner_requests(&f), 1, "the request went out, not refused locally");    assert!(f.refusals.standing().is_none(), "and the stranger's note is gone");}#[test]fn a_mine_note_the_household_itself_wrote_still_stands() {    let refusals = Arc::new(RefusalMemory::default());    refusals.note_for(        refusal::NoteKey::Mine,        Some(refusal::DeviceRefusal {            kind: RefusalKind::Revoked,            code: "device_revoked".into(),            server_url: Some(HOME.into()),            server_name: Some("studio".into()),            at: "2026-10-04T15:12:10.841Z".into(),            erase: false,            serving_epoch: None,            refuser: Refuser::Unrecorded,            device: None,        }),    );    let f = fixture_with(RememberedAddress::at(HOME), Vec::new(), refusals);    let refusal = f.transport.call(pull()).expect_err("still refused");    assert_eq!(refusal.code.as_deref(), Some("device_revoked"));    assert_eq!(owner_requests(&f), 0, "and without sending");}#[test]fn an_invite_claim_still_goes_out_while_a_terminal_refusal_stands() {    let f = home(vec![        Reply::json(403, r#"{"code":"device_revoked"}"#),        Reply::json(202, r#"{"pairingId":"p1","serverDeviceId":"mac-1"}"#),    ]);    let _ = f.transport.call(pull()).expect_err("a refusal");    let answer = f        .transport        .call(ClientRequest::post_json(            "/v1/invites/inv-1/claim?database=garden",            b"{}".to_vec(),        ))        .expect("the claim went out");    assert_eq!(answer.status, 202);}/// RULE: The way a device last reached its Mac is said in a person's words — "directly", "over the relay" — and a request to the household's own origin went over the relay only when that origin is a relay name (sync programme, lane A: Last synced says the time and the route).#[test]fn the_way_a_request_went_is_said_in_a_persons_words() {    assert_eq!(Way::Relay.words(), "over the relay");    assert_eq!(Way::Address.words(), "directly");    let relay = cotton_core::device::pairing::relay_origin_for_name("studio").expect("a relay origin");    assert_eq!(Way::to_origin(Some(&relay)), Way::Relay);    assert_eq!(Way::to_origin(Some("https://study.tail1234.ts.net")), Way::Address);    assert_eq!(Way::to_origin(Some("http://192.168.1.14:53012/")), Way::Address);    assert_eq!(Way::to_origin(None), Way::Address);}