//! The five owner-HTTP families, one case per method, against a scripted //! transport. //! //! **What each case asserts is what actually went out** — the verb, the path //! and the body bytes — and what came back. That is the whole contract of these //! methods: they hold no state, they compute no answer, and the one thing that //! can be wrong about them is the request. A double above `ServerFetch` rather //! than below it is right here for the same reason `cotton-client`'s own double //! is below it: everything THAT crate has to prove (the signature, the moved //! follow, the clock correction) happens under this seam and is already proved //! there, and re-proving it through the FFI would be the same assertions over a //! slower fixture. //! //! Every fixture is synthetic — a device of zeroes, a name nobody has //! ([nothing-real-ever-goes-in-cotton-s-public-tree]). use std::collections::VecDeque; use std::sync::Mutex; use cotton_client::transport::{ClientAnswer, ClientRequest, ServerFetch, ServerRefusal}; use serde_json::{json, Value}; pub(super) fn browser_wire( replies: Vec, ) -> ( cotton_client::transport::signed_http::SignedHttp, std::sync::Arc, ) { use cotton_client::identity::DeviceIdentity; use cotton_client::seams::{FixedClock, SeededRandom}; use cotton_client::transport::refusal::RefusalMemory; use cotton_client::transport::scripted::{RememberedAddress, ScriptedExchange}; use cotton_client::transport::signer::RequestSigner; use std::sync::Arc; let exchange = ScriptedExchange::new(replies); let clock = FixedClock::default_start(); let signer = RequestSigner::new( Arc::new(DeviceIdentity::from_secret(&[7; 32]).unwrap()), Arc::new(clock.clone()), Arc::new(SeededRandom::default()), ); let fetch = cotton_client::transport::signed_http::SignedHttp::new( signer, RememberedAddress::at("https://invented-harbor.example.test"), Arc::new(RefusalMemory::default()), exchange.clone(), Arc::new(clock), ); (fetch, exchange) } use crate::methods::MethodError; // ── the double ──────────────────────────────────────────────────────────── /// A server that answers from a script, and remembers what it was asked. #[derive(Debug, Default)] struct Scripted { replies: Mutex>>, seen: Mutex>, } impl Scripted { /// One 200 with this JSON body. fn answering(body: &str) -> Scripted { Scripted::new([Ok(ClientAnswer { status: 200, body: body.as_bytes().to_vec(), })]) } /// One 204 with nothing in it, which is what a DELETE answers. fn empty() -> Scripted { Scripted::new([Ok(ClientAnswer { status: 204, body: Vec::new(), })]) } fn refusing(refusal: ServerRefusal) -> Scripted { Scripted::new([Err(refusal)]) } fn new(replies: impl IntoIterator>) -> Scripted { Scripted { replies: Mutex::new(replies.into_iter().collect()), seen: Mutex::new(Vec::new()), } } /// The ONE request this case asked about — loud when there was not exactly /// one, so a test can never read index 0 of an empty record and pass. fn only(&self) -> ClientRequest { let seen = self.seen.lock().expect("the record"); assert_eq!(seen.len(), 1, "expected one request, saw {}", seen.len()); seen[0].clone() } fn calls(&self) -> usize { self.seen.lock().expect("the record").len() } } impl ServerFetch for Scripted { fn call(&self, request: ClientRequest) -> Result { self.seen.lock().expect("the record").push(request); self.replies .lock() .expect("the script") .pop_front() // Loud rather than an implicit 200: a script that ran out is a case // asserting against an answer nobody wrote. .unwrap_or_else(|| Err(ServerRefusal::offline("the script ran out of answers"))) } } /// The body a request carried, as JSON. fn body_of(request: &ClientRequest) -> Value { let bytes = request.body.clone().unwrap_or_default(); serde_json::from_slice(&bytes).unwrap_or_else(|error| { panic!( "the body was not JSON ({error}): {}", String::from_utf8_lossy(&bytes) ) }) } fn ok(answer: Result) -> Value { answer.unwrap_or_else(|error| panic!("refused: {} — {}", error.code, error.message)) } // ── devices.* ───────────────────────────────────────────────────────────── #[test] fn the_approved_list_is_one_get_and_is_handed_over_whole() { let server = Scripted::answering(r#"{"devices":[{"deviceId":"d1"}],"thisDevice":"d1"}"#); let answer = ok(super::devices::over(&server, "devices.list", &json!({}))); let sent = server.only(); assert_eq!(sent.method, "GET"); assert_eq!(sent.path, "/v1/devices/approved"); assert!(sent.body.is_none(), "a GET carries no body"); // `thisDevice` survives: the list marks its own row with the server's // answer rather than comparing ids in the app. assert_eq!(answer["thisDevice"], json!("d1")); } #[test] fn approving_a_pending_device_echoes_the_rows_digits_to_that_pairings_own_route() { let server = Scripted::answering(r#"{"approved":true,"device":{"deviceId":"d2"}}"#); ok(super::devices::over( &server, "devices.approvePending", &json!({ "pairingId": "p1", "digits": "409271" }), )); let sent = server.only(); assert_eq!(sent.method, "POST"); assert_eq!(sent.path, "/v1/devices/pending/p1/approve"); assert_eq!(body_of(&sent), json!({ "digits": "409271" })); } #[test] fn an_echo_that_is_not_six_digits_never_leaves_the_device() { // Not a keypad guard any more — nobody types these. It catches a SCREEN // that lost track of which request the person was looking at, which is the // thing the echo exists to prove. for typed in ["40927", "4092711", "40927a", " "] { let server = Scripted::answering("{}"); let error = super::devices::over( &server, "devices.approvePending", &json!({ "pairingId": "p1", "digits": typed }), ) .expect_err("a refusal"); assert_eq!(error.code, "bad_request", "{typed}"); assert_eq!(server.calls(), 0, "{typed} was not worth a round trip"); } } #[test] fn declining_sends_an_empty_object_because_the_signature_is_over_the_bytes_as_sent() { let server = Scripted::answering(r#"{"ok":true}"#); ok(super::devices::over( &server, "devices.declinePending", &json!({ "pairingId": "p 1" }), )); let sent = server.only(); assert_eq!(sent.method, "POST"); // And the space is escaped, because the path is signed exactly as sent. assert_eq!(sent.path, "/v1/devices/pending/p%201/decline"); assert_eq!(body_of(&sent), json!({})); } #[test] fn revoking_is_a_delete_that_says_out_loud_it_is_not_an_erase() { let server = Scripted::empty(); let answer = ok(super::devices::over( &server, "devices.revoke", &json!({ "deviceId": "d/4" }), )); let sent = server.only(); assert_eq!(sent.method, "DELETE"); assert_eq!(sent.path, "/v1/devices/approved/d%2F4"); // The flag is SPELLED rather than omitted: the server reads every shape // but a literal `{"erase": true}` as an ordinary removal, so `false` costs // nothing and says which of the two verbs was pressed. assert_eq!(body_of(&sent), json!({ "erase": false })); // An empty body is `null`, not a parse failure — the caller only wanted to // know it worked. assert_eq!(answer, Value::Null); } /// *Remove and erase* — the second verb on a device row. #[test] fn removing_and_erasing_is_the_same_route_with_the_flag_up() { let server = Scripted::empty(); ok(super::devices::over( &server, "devices.revoke", &json!({ "deviceId": "d4", "erase": true }), )); let sent = server.only(); assert_eq!(sent.method, "DELETE"); assert_eq!(sent.path, "/v1/devices/approved/d4"); assert_eq!(body_of(&sent), json!({ "erase": true })); } /// Anything but a literal `true` is an ordinary removal. /// /// The crate is the last place this can be got wrong, and the wrong literal /// here is somebody's photographs: `owner::flag` answers `true` for /// `Value::Bool(true)` and for nothing else, so a screen that sent the STRING /// `"true"` removes a device rather than wiping it. #[test] fn only_a_boolean_true_asks_for_an_erase() { let server = Scripted::empty(); ok(super::devices::over( &server, "devices.revoke", &json!({ "deviceId": "d4", "erase": "true" }), )); assert_eq!(body_of(&server.only()), json!({ "erase": false })); } #[test] fn renaming_is_a_patch_carrying_only_the_name() { let server = Scripted::answering(r#"{"ok":true}"#); ok(super::devices::over( &server, "devices.rename", &json!({ "deviceId": "d5", "name": "The kitchen Mac" }), )); let sent = server.only(); assert_eq!(sent.method, "PATCH"); assert_eq!(sent.path, "/v1/devices/approved/d5"); assert_eq!(body_of(&sent), json!({ "name": "The kitchen Mac" })); } #[test] fn a_refusal_carries_the_servers_own_code_and_the_status_the_screen_branches_on() { // `useApprovedDevices` does NOT retry a 4xx, so the status has to survive // the boundary or a 401 becomes a permanent skeleton. let server = Scripted::refusing( ServerRefusal::new("this device is not approved", 401).with_code("device_revoked"), ); let error = super::devices::over(&server, "devices.list", &json!({})).expect_err("a refusal"); assert_eq!(error.code, "device_revoked"); assert_eq!(error.message, "this device is not approved"); assert_eq!(error.details["status"], json!(401)); } /// RULE: Transport status stays in details; paper gets the server's sentence. /// Strip only the transport's exact status prefix, never words inside the refusal. #[test] fn a_server_refusals_transport_prefix_is_not_its_sentence() { for (message, status, expected) in [ ("server 400: This repository has not been cloned.", 400, "This repository has not been cloned."), ("This repository has not been cloned.", 400, "This repository has not been cloned."), ("server 503: The service is away.", 400, "server 503: The service is away."), ] { let refusal = ServerRefusal::new(message, status).with_code("not_held").retry_after(30); let error = super::owner::refused(refusal); assert_eq!(error.message, expected); assert_eq!(error.code, "not_held"); assert_eq!(error.details, json!({"status": status, "retryAfterSeconds": 30})); } } #[test] fn a_refusal_with_no_code_of_its_own_gets_one_word_rather_than_six() { let server = Scripted::refusing(ServerRefusal::new("no", 500)); let error = super::devices::over(&server, "devices.list", &json!({})).expect_err("a refusal"); assert_eq!(error.code, super::owner::SERVER_REFUSED); assert_eq!(error.details["status"], json!(500)); } #[test] fn a_retry_after_the_server_named_travels_with_the_refusal() { let server = Scripted::refusing( ServerRefusal::new("too many", 429) .with_code("rate_limited") .retry_after(90), ); let error = super::devices::over(&server, "devices.list", &json!({})).expect_err("a refusal"); assert_eq!(error.details["retryAfterSeconds"], json!(90)); } // ── the seam's own rules ────────────────────────────────────────────────── #[test] fn an_answer_that_is_not_json_is_a_named_refusal_rather_than_a_panic() { let server = Scripted::answering("a gateway said something"); let error = super::devices::over(&server, "devices.list", &json!({})).expect_err("a refusal"); assert_eq!(error.code, "unreadable_answer"); } #[test] fn a_path_segment_is_escaped_exactly_the_way_encode_uri_component_escapes_one() { // The unreserved set, and everything else percent-encoded — because the // signature is over the path AS SENT, so an unescaped character would be // signed as one thing and routed as another. assert_eq!(super::owner::segment("aZ09-_.!~*'()"), "aZ09-_.!~*'()"); assert_eq!(super::owner::segment("project:p1"), "project%3Ap1"); assert_eq!(super::owner::segment("a/b c"), "a%2Fb%20c"); // Multi-byte: escaped byte by byte, upper case, as `encodeURIComponent` // does. assert_eq!(super::owner::segment("é"), "%C3%A9"); } /// RULE: Every owner method implemented on the phone is advertised in the client partition and complete method registry, so discovery cannot hide a supported operation. #[test] fn every_method_this_lane_answers_is_in_the_phones_partition_and_in_all_methods() { let declared: Vec<&str> = super::devices::METHODS .iter() .chain(super::google::METHODS.iter()) .chain(super::spotify::METHODS.iter()) .chain(super::whatsapp::METHODS.iter()) .chain(super::settings_writes::METHODS.iter()) .copied() .collect(); let answered = crate::phone::method_names(); for method in &declared { assert!( crate::methods::CLIENT_METHODS.contains(method), "{method} is answered and not in the client half's partition" ); assert!( crate::methods::ALL_METHODS.contains(method), "{method} is not in ALL_METHODS, so the partition test cannot see it" ); assert!( answered.contains(&(*method).to_string()), "{method} is declared and not offered" ); } } #[test] fn every_name_in_the_client_partition_carrying_one_of_these_prefixes_is_answered() { // The reverse of the test above, and the one that actually rots: add // `devices.somethingNew` to `CLIENT_METHODS`, forget the arm, and the phone // is OFFERED a method that answers `unknown_method` when a screen calls it. // A method table is a promise, and this is the half that checks it is kept. let declared: Vec<&str> = super::devices::METHODS .iter() .chain(super::google::METHODS.iter()) .chain(super::spotify::METHODS.iter()) .chain(super::settings_writes::METHODS.iter()) .chain(super::media::METHODS.iter()) .copied() .collect(); // The prefixes 4h added, and the only ones this test may speak for: // a name outside them belongs to another lane's arm. for prefix in [ "devices.", "google.", "spotify.", "settings.", ] { for &name in crate::methods::CLIENT_METHODS { if !name.starts_with(prefix) { continue; } assert!( declared.contains(&name), "{name} is offered to the phone and no module claims it" ); } } } #[test] fn a_name_inside_one_of_these_families_that_no_module_answers_is_told_so() { let server = Scripted::answering("{}"); let error = super::devices::over(&server, "devices.nonesuch", &json!({})).expect_err("a refusal"); assert_eq!(error.code, "unknown_method"); assert_eq!(server.calls(), 0); } /// RULE: An unreachable Mac cannot make a removed device disappear or claim revocation succeeded; removal stays pending until the serving Mac confirms it. #[test] fn device_removal_without_a_mac_stays_pending() { use cotton_client::transport::scripted::Reply; let dir = tempfile::tempdir().unwrap(); let journal = dir.path().join("removals.json"); let (fetch, _) = browser_wire(vec![Reply::json(503, r#"{"code":"unavailable","error":"offline"}"#)]); let fetch = fetch.with_device_removals(journal.clone()); let answer = super::devices::over(&fetch, "devices.revoke", &json!({"deviceId":"synthetic-phone", "database":"invented-database"})) .expect("an offline removal is pending, never reported as applied"); assert_eq!(answer["pending"], true); assert_ne!(answer["ok"], true); assert!(cotton_client::transport::device_removals::pending(&journal, "invented-database", "synthetic-phone").unwrap()); drop(fetch); // The first signed request of the next process applies the saved removal // before its ordinary read. A memory-only retry would lose this request. let (fetch, wire) = browser_wire(vec![Reply::ok(r#"{"ok":true}"#), Reply::ok("{}")]); let fetch = fetch.with_device_removals(journal.clone()); fetch.call(ClientRequest::get("/v1/me/server")).unwrap(); let sent = wire.seen(); assert_eq!(sent[0].method, "DELETE"); assert_eq!(sent[0].path, "/v1/devices/approved/synthetic-phone?database=invented-database"); assert_eq!(serde_json::from_slice::(&sent[0].body).unwrap(), json!({"erase":false})); assert_eq!(sent[1].path, "/v1/me/server"); assert!(!cotton_client::transport::device_removals::pending(&journal, "invented-database", "synthetic-phone").unwrap()); } /// RULE: A queued erase is never downgraded by a later ordinary Remove while the Mac is unreachable; retries carry exactly the stronger request the owner already made. #[test] fn device_removal_retry_keeps_an_explicit_erase() { use cotton_client::transport::scripted::Reply; let dir = tempfile::tempdir().unwrap(); let journal = dir.path().join("removals.json"); let (fetch, _) = browser_wire(vec![Reply::new(503, b"offline".to_vec()), Reply::new(503, b"offline".to_vec())]); let fetch = fetch.with_device_removals(journal.clone()); for erase in [true, false] { let pending = super::devices::over(&fetch, "devices.revoke", &json!({"deviceId":"synthetic-phone", "database":"invented-database", "erase":erase})).unwrap(); assert_eq!(pending["pending"], true); } drop(fetch); let (fetch, wire) = browser_wire(vec![Reply::ok(r#"{"ok":true}"#), Reply::ok("{}")]); let fetch = fetch.with_device_removals(journal); fetch.call(ClientRequest::get("/v1/me/server")).unwrap(); assert_eq!(serde_json::from_slice::(&wire.seen()[0].body).unwrap(), json!({"erase":true})); } /// RULE: Pending removal is promised only after durable storage is configured; a transport with no journal refuses before sending rather than losing the request on restart. #[test] fn device_removal_never_promises_a_memory_only_retry() { let (fetch, wire) = browser_wire(Vec::new()); let refused = super::devices::over(&fetch, "devices.revoke", &json!({"deviceId":"synthetic-phone"})).unwrap_err(); assert_eq!(refused.code, "removal_unconfigured"); assert!(wire.seen().is_empty()); }