//! Every expected string here was printed by RUNNING the TypeScript//! (`deviceSignedMessage`, `signedPath`, `bodyHashHex`,//! `formatDeviceSigHeader`) and pasted verbatim — including the ones a reader//! would be tempted to reason out, because the whole point of a third spelling//! of a signed string is that reasoning is exactly what must not decide it.usesuper::*;/// The signed string, byte for byte the server's `signedString()`.////// THIS LITERAL IS PINNED IN THREE FILES, and they must agree:/// `crates/cotton-server/src/devices/device_auth_tests.rs` (the server's own),/// `crates/cotton-client/src/identity.rs` (the client's), and here./// If either side changes the string, all three change in the same PR, or one/// of them fails.#[test]fn the_signed_string_is_the_servers_byte_for_byte() {let message = device_signed_string(&DeviceSignedInput { origin: "https://alice.relay.cottondb.com", method: "post", path: "/v1/sync/push", ts: 1, nonce: "n", body: None, }); assert_eq!( message,"cotton-device-v1\nhttps://alice.relay.cottondb.com\nPOST\n/v1/sync/push\n1\nn\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" );// The bytes an Ed25519 key signs are that string's UTF-8. assert_eq!( device_signed_message(&DeviceSignedInput { origin: "https://alice.relay.cottondb.com", method: "post", path: "/v1/sync/push", ts: 1, nonce: "n", body: None, }), message.into_bytes() );}/// Vectors: four more whole messages, printed by the TypeScript.#[test]fn spells_the_whole_message_the_way_the_typescript_does() { assert_eq!( device_signed_string(&DeviceSignedInput { origin: "https://a.relay.cottondb.com", method: "POST", path: "/v1/x", ts: 1_788_429_600, nonce: "AAAAAAAAAAAAAAAAAAAAAA", body: Some(br#"{"ops":[]}"#), }),"cotton-device-v1\nhttps://a.relay.cottondb.com\nPOST\n/v1/x\n1788429600\nAAAAAAAAAAAAAAAAAAAAAA\nb2f0effc1a37cecc88986e93381ca24c017e5b7a288ea14a9462ae9b4c466f0c" ); assert_eq!( device_signed_string(&DeviceSignedInput { origin: "http://127.0.0.1:8790", method: "GET", path: "/v1/sync/pull?since=0&b=%20", ts: 1, nonce: "", body: None, }),"cotton-device-v1\nhttp://127.0.0.1:8790\nGET\n/v1/sync/pull?since=0&b=%20\n1\n\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ); assert_eq!( device_signed_string(&DeviceSignedInput { origin: "https://a.relay.cottondb.com", method: "get", path: "/v1/x", ts: 999_999_999_999, nonce: "", body: Some(b""), }),"cotton-device-v1\nhttps://a.relay.cottondb.com\nGET\n/v1/x\n999999999999\n\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" );// A mixed-case method upper-cases; a non-ASCII path and body travel as// their UTF-8 bytes. assert_eq!( device_signed_string(&DeviceSignedInput { origin: "https://a.relay.cottondb.com", method: "PaTcH", path: "/v1/café", ts: 0, nonce: "n", body: Some("\u{1F600}".as_bytes()), }),"cotton-device-v1\nhttps://a.relay.cottondb.com\nPATCH\n/v1/café\n0\nn\nf0443a342c5ef54783a111b51ba56c938e474c32324d90c3a60c9c8e3a37e2d9" );}/// The body hash is over the raw bytes AS SENT — the serialised string itself,/// never a re-serialisation — and an absent body hashes like an empty one, so/// a GET and a bodyless POST sign the same way and no form is optional.#[test]fn hashes_the_body_bytes_as_sent_and_treats_absent_and_empty_alike() {let with_body = device_signed_string(&DeviceSignedInput { origin: "https://a.relay.cottondb.com", method: "POST", path: "/v1/x", ts: 1, nonce: "n", body: Some(br#"{"ops":[]}"#), });let fields: Vec<&str> = with_body.split('\n').collect(); assert_eq!(fields.len(), 7);// Vector: sha256('{"ops":[]}'), computed by a second implementation// (Node's `createHash`) in the TypeScript test. assert_eq!( fields[6],"b2f0effc1a37cecc88986e93381ca24c017e5b7a288ea14a9462ae9b4c466f0c" ); assert!(fields[6].len() == 64 && fields[6].bytes().all(|b| b.is_ascii_hexdigit())); assert!(fields[6].chars().all(|c| !c.is_ascii_uppercase()));let empty = device_signed_string(&DeviceSignedInput { origin: "https://a.relay.cottondb.com", method: "GET", path: "/v1/x", ts: 1, nonce: "", body: Some(b""), });let absent = device_signed_string(&DeviceSignedInput { origin: "https://a.relay.cottondb.com", method: "GET", path: "/v1/x", ts: 1, nonce: "", body: None, }); assert_eq!(empty, absent); assert!(absent.ends_with(EMPTY_BODY_HASH));}/// Vectors for `bodyHashHex` on its own, printed by the TypeScript.#[test]fn body_hash_hex_vectors() { assert_eq!(body_hash_hex(None), EMPTY_BODY_HASH); assert_eq!(body_hash_hex(Some(b"")), EMPTY_BODY_HASH); assert_eq!( body_hash_hex(Some(b"hello")),"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" ); assert_eq!( body_hash_hex(Some("é\u{1F600}".as_bytes())),"1184d1f608158eea09d297565575892231550c403aaa913008d867a97cfd5c76" ); assert_eq!( body_hash_hex(Some(&[b'a'; 1000])),"41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3" );}/// The server's aff79127 rule: the query is signed, raw as sent.#[test]fn signs_the_pathname_plus_the_raw_search_exactly_as_sent() {let path = signed_path("http://127.0.0.1:8790/v1/sync/pull?since=0&b=%20").unwrap();let message = device_signed_string(&DeviceSignedInput { origin: "http://127.0.0.1:8790", method: "GET", path: &path, ts: 1, nonce: "", body: None, });let fields: Vec<&str> = message.split('\n').collect(); assert_eq!(fields.len(), 7); assert_eq!(fields[3], "/v1/sync/pull?since=0&b=%20"); assert_eq!(fields[5], "");}/// `signedPath` is `URL.pathname + URL.search` — encoded as sent, no `?` when/// there is no query.#[test]fn signed_path_is_pathname_plus_search() {let path = |url: &str| signed_path(url).unwrap(); assert_eq!( path("https://alice.relay.cottondb.com/v1/sync/pull"),"/v1/sync/pull" ); assert_eq!( path("https://alice.relay.cottondb.com/v1/x?b=2&a=1"),"/v1/x?b=2&a=1" ); assert_eq!( path("https://alice.relay.cottondb.com/v1/a%20b?q=%2F"),"/v1/a%20b?q=%2F" ); assert_eq!(path("https://alice.relay.cottondb.com/v1/x?"), "/v1/x"); assert_eq!(path("https://alice.relay.cottondb.com/v1/x#frag"), "/v1/x");}/// Vectors: the WHATWG behaviours a hand-rolled `pathname + search` would get/// wrong, each printed by Node's `new URL`.#[test]fn signed_path_is_whatwg_not_string_surgery() {let path = |url: &str| signed_path(url).unwrap();// No path at all is `/`. assert_eq!(path("https://alice.relay.cottondb.com"), "/");// Dot segments are resolved before the string is signed. assert_eq!(path("https://alice.relay.cottondb.com/v1/../x"), "/x");// An empty segment is NOT collapsed. assert_eq!(path("https://alice.relay.cottondb.com/v1//x"), "/v1//x");// Non-ASCII is percent-encoded, upper-case hex, in path and query alike. assert_eq!( path("https://alice.relay.cottondb.com/v1/café?q=é"),"/v1/caf%C3%A9?q=%C3%A9" );// A space in the query encodes; an already-encoded escape keeps its own// case (`%2f` is not re-cased to `%2F`) — "raw as sent" means raw. assert_eq!( path("https://alice.relay.cottondb.com/v1/x?q=a b"),"/v1/x?q=a%20b" ); assert_eq!( path("https://alice.relay.cottondb.com/v1/x?q=%2f"),"/v1/x?q=%2f" ); assert_eq!(path("https://alice.relay.cottondb.com/v1/x?#frag"), "/v1/x");// A `wss://` upgrade reads the same as its https twin — the live channel// signs for the https origin like every other route. assert_eq!( path("wss://alice.relay.cottondb.com/v1/live?since=3"),"/v1/live?since=3" ); assert_eq!(path("https://[::1]:8790/v1/x?a=1"), "/v1/x?a=1");}/// The TypeScript throws a `TypeError: Invalid URL`; a pure library returns it.#[test]fn signed_path_refuses_something_that_is_not_a_url() { assert_eq!(signed_path("/v1/x"), Err(InvalidUrl)); assert_eq!(signed_path("not a url"), Err(InvalidUrl)); assert_eq!(InvalidUrl.to_string(), "Invalid URL");}#[test]fn the_header_names_are_the_servers_lower_case() { assert_eq!(DEVICE_HEADER, "x-cotton-device"); assert_eq!(DEVICE_SIG_HEADER, "x-cotton-device-sig"); assert_eq!(DEVICE_SIG_CONTEXT, "cotton-device-v1");}#[test]fn the_window_is_the_relays() { assert_eq!(MAX_DEVICE_CLOCK_SKEW_SECONDS, 120);}// ── the header grammar <ts>.<nonce>.<sig> ────────────────────────────────────#[test]fn round_trips_a_writes_header() {let sig = [7u8; 64];let header = format_device_sig_header(42, "abc", &sig); assert_eq!(header.split('.').count(), 3); assert_eq!( parse_device_sig_header(&header),Some(DeviceSigHeader { ts: 42, nonce: "abc".to_string(), sig }) );}/// Vectors: three whole headers, printed by the TypeScript's/// `formatDeviceSigHeader`.#[test]fn header_vectors() { assert_eq!( format_device_sig_header(42, "abc", &[7u8; 64]),"42.abc.BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBw" ); assert_eq!( format_device_sig_header(42, "", &[0u8; 64]),"42..AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" ); assert_eq!( format_device_sig_header(1_788_429_600, "AAAAAAAAAAAAAAAAAAAAAA", &[255u8; 64]),"1788429600.AAAAAAAAAAAAAAAAAAAAAA._____________________________________________________________________________________w" );}/// A read carries an empty nonce, as `<ts>..<sig>`.#[test]fn carries_an_empty_nonce_on_a_read() {let header = format_device_sig_header(42, "", &[7u8; 64]); assert!(header.starts_with("42..")); assert_eq!( parse_device_sig_header(&header).map(|parsed| parsed.nonce),Some(String::new()) );}#[test]fn refuses_a_header_with_the_wrong_shape() { assert_eq!(parse_device_sig_header(""), None); assert_eq!(parse_device_sig_header("42.abc"), None); assert_eq!(parse_device_sig_header("x.abc.AAAA"), None); assert_eq!(parse_device_sig_header("42.abc.not base64url!"), None);// A signature that is not 64 bytes is not a signature. assert_eq!(parse_device_sig_header("42.abc.AAAA"), None);// A fourth field is not the grammar (a nonce never carries a dot). assert_eq!(parse_device_sig_header("42.abc.def.ghi"), None);}/// Vectors for the `ts` and nonce grammars, each answer read out of the/// TypeScript rather than reasoned about.#[test]fn header_grammar_vectors() {let sig = "A".repeat(86);// Thirteen digits is one too many for `\d{1,12}`. assert_eq!( parse_device_sig_header(&format!("1234567890123.abc.{sig}")),None );// A leading zero parses: `Number("042")` is 42. assert_eq!( parse_device_sig_header(&format!("042.abc.{sig}")).map(|parsed| parsed.ts),Some(42) );// The nonce is base64url only. assert_eq!(parse_device_sig_header(&format!("42.ab+c.{sig}")), None);// Twelve digits is the widest `ts` the grammar admits. assert_eq!( parse_device_sig_header(&format!("999999999999.abc.{sig}")).map(|parsed| parsed.ts),Some(999_999_999_999) );}