Cotton code
248 lines · 8.6 KB · RustRaw
//! Its `RELAY_NAME_PATTERN` case — the byte-equality read of//! `packages/relay/src/protocol/names.ts` — is NOT here: it is already ported,//! once, as `relay_name_pattern_is_byte_equal_to_the_relays` in//! `src/handles_tests.rs`, against [`crate::handles::RELAY_NAME_PATTERN_SOURCE`].//! Two copies of that read would be two places to update when the relay lane//! moves its file, which is the failure the case exists to catch.//!//! Every expected string below was printed by running the TypeScript.use super::*;/// 32 bytes of base64url — the shape of a device id.fn device_id() -> String {    "A".repeat(43)}const RELAY: &str = "https://example.relay.cottondb.com";// ── relay origins — the pair QR is pinned to https on the relay ──────────────#[test]fn builds_and_reads_back_a_relay_origin() {    assert_eq!(relay_origin_for_name("example").as_deref(), Some(RELAY));    assert_eq!(relay_name_of(RELAY), Some("example"));}#[test]fn refuses_an_origin_that_is_not_exactly_a_relay_one() {    for origin in [        "http://example.relay.cottondb.com",        "https://example.relay.cottondb.com/x",        "https://example.relay.cottondb.com/",        "https://evil.com",        "https://EXAMPLE.relay.cottondb.com",        "https://x.relay.cottondb.com.evil.com",        "https://relay.cottondb.com",    ] {        assert_eq!(relay_name_of(origin), None, "{origin}");    }}#[test]fn refuses_a_name_the_relay_would_refuse() {    for name in ["", "-a", "a", "A", &"a".repeat(32), "a b"] {        assert_eq!(relay_origin_for_name(name), None, "{name:?}");    }}/// Vectors: the edges of `^[a-z0-9][a-z0-9-]{1,30}$`, and the shapes a/// hand-rolled origin check gets wrong.#[test]fn relay_name_vectors() {    assert_eq!(        relay_origin_for_name("ab").as_deref(),        Some("https://ab.relay.cottondb.com")    );    assert_eq!(        relay_origin_for_name(&"a".repeat(31)).as_deref(),        Some("https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.relay.cottondb.com")    );    // A digit may lead, and an all-digit name is a name to the RELAY — which    // is where this predicate differs from the store's `isRelayName`.    assert_eq!(        relay_origin_for_name("12").as_deref(),        Some("https://12.relay.cottondb.com")    );    assert_eq!(relay_name_of("https://12.relay.cottondb.com"), Some("12"));    assert_eq!(        relay_name_of("https://a-b-c.relay.cottondb.com"),        Some("a-b-c")    );    assert_eq!(relay_name_of("https://-bad.relay.cottondb.com"), None);    // A deeper subdomain is not a relay origin: the captured name may hold no    // dot.    assert_eq!(relay_name_of("https://a.b.relay.cottondb.com"), None);}// ── codes ───────────────────────────────────────────────────────────────────#[test]fn refuses_a_code_that_is_not_eight_crockford_characters() {    // The alphabet is the CONSENT PAGE's now — the eight-character pairing    // code retired with `cotton-pair:` — so every one of these is asked of    // `normalize_user_code`, which is the only door into it.    assert_eq!(normalize_user_code("abc"), None);    // U is not crockford32.    assert_eq!(normalize_user_code("abcdefgu"), None);    assert_eq!(normalize_user_code("abcdefgh1"), None);}#[test]fn shapes_a_user_code_as_xxxx_xxxx() {    assert_eq!(        normalize_user_code(" ab12-cd34 ").as_deref(),        Some("AB12-CD34")    );    assert_eq!(        normalize_user_code("i1o0-l1ab").as_deref(),        Some("1100-11AB")    );    assert_eq!(        normalize_user_code("ab12cd34").as_deref(),        Some("AB12-CD34")    );    assert_eq!(        normalize_user_code("AB12-CD34").as_deref(),        Some("AB12-CD34")    );    assert_eq!(normalize_user_code("ab12-cd3"), None);}/// Vectors: the confusable folding and the whitespace rule, each answer/// printed by the TypeScript.#[test]fn code_vectors() {    assert_eq!(        normalize_user_code("IL-OO-il-oo").as_deref(),        Some("1100-1100")    );    assert_eq!(        normalize_user_code("ZZZZZZZZ").as_deref(),        Some("ZZZZ-ZZZZ")    );    assert_eq!(        normalize_user_code("ab 12 cd 34").as_deref(),        Some("AB12-CD34")    );    // Ten digits is two too many, however legal each character is.    assert_eq!(normalize_user_code("0123456789"), None);    // `toUpperCase()` can LENGTHEN a string: "ß" becomes "SS", so six letters    // behind it make eight characters and a legal code.    assert_eq!(        normalize_user_code("ßabcdef").as_deref(),        Some("SSAB-CDEF")    );    assert_eq!(        normalize_user_code("il-oo-il-oo").as_deref(),        Some("1100-1100")    );    assert_eq!(        normalize_user_code("00000000").as_deref(),        Some("0000-0000")    );    assert_eq!(        normalize_user_code("abcdefgh").as_deref(),        Some("ABCD-EFGH")    );}// ── the two QR payloads round-trip ───────────────────────────────────────────/// `cotton-pair:` and `cotton-device:` are retired, and nothing here parses/// either.////// `cotton-pair:` carried the eight-character pairing code a join used to begin/// with; `cotton-device:` carried a phone's own key for an admitted device to/// scan and approve. A join begins with no secret now — the device presents its/// key, the server answers six digits, and the approving device reads those/// digits off its own pending list — so both grammars went with the routes that/// read them. The guard is that neither prefix reaches a parser: the ONE that/// remains refuses them like any other text, which is what a phone handed an/// old symbol should do.#[test]fn the_retired_prefixes_reach_no_parser() {    let pair = format!(r#"cotton-pair:{{"v":1,"server":"{RELAY}","code":"AB12CD34"}}"#);    assert_eq!(parse_oauth_payload(&pair), None);    let device = format!(        r#"cotton-device:{{"v":1,"deviceId":"{}","name":"Test Phone"}}"#,        device_id()    );    assert_eq!(parse_oauth_payload(&device), None);}#[test]fn cotton_oauth_round_trips() {    let payload = OauthPayload {        server: RELAY.to_string(),        code: "AB12-CD34".to_string(),    };    assert_eq!(        parse_oauth_payload(&build_oauth_payload(&payload)),        Some(payload)    );    assert_eq!(        parse_oauth_payload(            r#"cotton-oauth:{"v":1,"server":"http://evil.com","code":"AB12-CD34"}"#        ),        None    );}/// Vectors: the exact strings a QR symbol carries, printed by the/// TypeScript's `JSON.stringify` — key order and escaping included.#[test]fn payload_string_vectors() {    assert_eq!(        build_oauth_payload(&OauthPayload {            server: RELAY.to_string(),            code: "AB12-CD34".to_string(),        }),        r#"cotton-oauth:{"v":1,"server":"https://example.relay.cottondb.com","code":"AB12-CD34"}"#    );}/// Vectors: what the parsers accept and refuse at the JSON grammar's edges.#[test]fn payload_parsing_vectors() {    // A lower-case, hyphenated code normalises on the way in. Asked of the    // OAUTH payload, which is the only one left — these vectors are about the    // JSON grammar rather than about which prefix carries it.    assert_eq!(        parse_oauth_payload(&format!(            r#"cotton-oauth:{{"v":1,"server":"{RELAY}","code":"ab12-cd34"}}"#        ))        .map(|payload| payload.code),        Some("AB12-CD34".to_string())    );    // `1.0` IS `1` as a JSON number; `"1"` is not.    assert!(parse_oauth_payload(&format!(        r#"cotton-oauth:{{"v":1.0,"server":"{RELAY}","code":"AB12CD34"}}"#    ))    .is_some());    assert_eq!(        parse_oauth_payload(&format!(            r#"cotton-oauth:{{"v":"1","server":"{RELAY}","code":"AB12CD34"}}"#        )),        None    );    // An array and a null are not payloads.    assert_eq!(parse_oauth_payload("cotton-oauth:[1,2]"), None);    assert_eq!(parse_oauth_payload("cotton-oauth:null"), None);    // Unknown keys are ignored, not refused.    assert!(parse_oauth_payload(&format!(        r#"cotton-oauth:{{"v":1,"server":"{RELAY}","code":"AB12CD34","x":9}}"#    ))    .is_some());}#[test]fn the_platforms_include_linux_servers() {    assert_eq!(        DevicePlatform::ALL.map(DevicePlatform::as_str),        ["ios", "android", "mac", "linux"]    );    assert_eq!(DevicePlatform::parse("ios"), Some(DevicePlatform::Ios));    assert_eq!(DevicePlatform::parse("toaster"), None);    assert_eq!(DevicePlatform::Mac.to_string(), "mac");}