Cotton code
220 lines · 7.2 KB · RustRaw
//! The port of `apps/cotton/__tests__/replica/serverSigning.test.ts` and//! `oneSigner.test.ts`.use super::*;// `signed_path` is core's own; this module no longer wraps it.use cotton_core::device::signature::signed_path;use crate::seams::{FixedClock, SeededRandom};use cotton_core::device::signature::{    device_signed_string, parse_device_sig_header, DEVICE_HEADER, DEVICE_SIG_HEADER,    EMPTY_BODY_HASH,};/// Synthetic, fixed, and not a key anything real was ever signed with.const SEED: [u8; 32] = [7u8; 32];fn signer() -> RequestSigner {    RequestSigner::new(        Arc::new(DeviceIdentity::from_secret(&SEED).expect("an identity")),        Arc::new(FixedClock::default_start()),        Arc::new(SeededRandom::default()),    )}fn header_of(headers: &[(&'static str, String); 2], name: &str) -> String {    headers        .iter()        .find(|(key, _)| *key == name)        .map(|(_, value)| value.clone())        .unwrap_or_else(|| panic!("no {name}"))}#[test]fn the_two_headers_are_the_device_id_and_ts_dot_nonce_dot_signature() {    let signer = signer();    let headers = signer.headers(        &SignRequest {            origin: "https://studio.relay.cottondb.com",            method: "GET",            path: "/v1/sync/pull?since=0",            body: None,        },        0,    );    assert_eq!(header_of(&headers, DEVICE_HEADER), signer.device_id());    assert_eq!(        signer.device_id().len(),        43,        "the raw public key, base64url"    );    let parsed =        parse_device_sig_header(&header_of(&headers, DEVICE_SIG_HEADER)).expect("a signature");    // `FixedClock::default_start()` is 2026-09-08T10:00:00Z.    assert_eq!(parsed.ts, 1_788_861_600);    assert_eq!(parsed.nonce, "", "a read signs no nonce");}#[test]fn a_write_carries_a_fresh_twenty_two_character_nonce_and_two_writes_never_share_one() {    let signer = signer();    let request = SignRequest {        origin: "https://studio.relay.cottondb.com",        method: "POST",        path: "/v1/sync/push",        body: Some(br#"{"ops":[]}"#),    };    let first =        parse_device_sig_header(&header_of(&signer.headers(&request, 0), DEVICE_SIG_HEADER))            .expect("a signature");    let second =        parse_device_sig_header(&header_of(&signer.headers(&request, 0), DEVICE_SIG_HEADER))            .expect("a signature");    assert_eq!(first.nonce.len(), 22);    assert_ne!(first.nonce, second.nonce, "the server keeps a replay table");}#[test]fn the_signature_verifies_against_the_string_the_server_rebuilds() {    use ed25519_dalek::{Signature, Verifier, VerifyingKey};    let signer = signer();    let body = br#"{"ops":[{"opId":"01"}]}"#;    let headers = signer.headers(        &SignRequest {            origin: "https://studio.relay.cottondb.com",            method: "POST",            path: "/v1/sync/push",            body: Some(body),        },        0,    );    let parsed =        parse_device_sig_header(&header_of(&headers, DEVICE_SIG_HEADER)).expect("a signature");    let message = device_signed_string(&cotton_core::device::signature::DeviceSignedInput {        origin: "https://studio.relay.cottondb.com",        method: "POST",        path: "/v1/sync/push",        ts: parsed.ts,        nonce: &parsed.nonce,        body: Some(body),    });    assert_eq!(        message.split('\n').count(),        7,        "seven fields, newline joined"    );    let key_bytes: [u8; 32] = cotton_core::device::base64url::base64url_decode(&signer.device_id())        .expect("the id decodes")        .try_into()        .expect("32 bytes");    let key = VerifyingKey::from_bytes(&key_bytes).expect("a public key");    key.verify(message.as_bytes(), &Signature::from_bytes(&parsed.sig))        .expect("the server would accept this");}#[test]fn an_absent_body_and_an_empty_one_sign_the_same_way() {    let message = |body: Option<&[u8]>| {        device_signed_string(&cotton_core::device::signature::DeviceSignedInput {            origin: "https://x.invalid",            method: "POST",            path: "/v1/me",            ts: 1,            nonce: "n",            body,        })    };    assert_eq!(message(None), message(Some(b"")));    assert!(message(None).ends_with(EMPTY_BODY_HASH));}#[test]fn the_clock_offset_moves_the_timestamp_and_nothing_else() {    let signer = signer();    let request = SignRequest {        origin: "https://x.invalid",        method: "GET",        path: "/v1/me/server",        body: None,    };    let plain =        parse_device_sig_header(&header_of(&signer.headers(&request, 0), DEVICE_SIG_HEADER))            .expect("a signature");    let shifted = parse_device_sig_header(&header_of(        &signer.headers(&request, 90_000),        DEVICE_SIG_HEADER,    ))    .expect("a signature");    assert_eq!(shifted.ts - plain.ts, 90);}#[test]fn an_offset_that_runs_the_clock_backwards_floors_rather_than_truncating_towards_zero() {    // `div_euclid`, not `/`: a negative millisecond count divided towards zero    // rounds a timestamp UP, which is a second in the FUTURE — and the server    // refuses a future timestamp at the edge of its window.    let signer = RequestSigner::new(        Arc::new(DeviceIdentity::from_secret(&SEED).expect("an identity")),        Arc::new(FixedClock::new(            chrono::DateTime::parse_from_rfc3339("1970-01-01T00:00:00.500Z")                .expect("an instant")                .with_timezone(&chrono::Utc),        )),        Arc::new(SeededRandom::default()),    );    let header = header_of(        &signer.headers(            &SignRequest {                origin: "https://x.invalid",                method: "GET",                path: "/v1/me",                body: None,            },            -1_000,        ),        DEVICE_SIG_HEADER,    );    // -500 ms floors to -1, never to 0. (The header's own grammar admits only    // digits, so a clock this far out is refused by the server rather than    // parsed — which is the honest outcome and not this function's to fix.)    assert!(header.starts_with("-1."), "{header}");}#[test]fn nothing_this_module_emits_is_an_authorization_header() {    // The bearer went with pairing PR 6: the signature is the whole    // credential. `no_bearer_tests.rs` reads the SOURCE; this reads the    // headers.    let headers = signer().headers(        &SignRequest {            origin: "https://x.invalid",            method: "POST",            path: "/v1/sync/push",            body: Some(b"{}"),        },        0,    );    for (name, _) in &headers {        assert!(            !name.eq_ignore_ascii_case("authorization"),            "{name} is a bearer"        );    }    assert_eq!(headers.len(), 2, "two headers and no third");}#[test]fn the_path_is_the_pathname_plus_the_raw_search_as_the_server_reads_it_back() {    assert_eq!(        signed_path("https://x.invalid/v1/sync/pull?since=3&limit=500").expect("a path"),        "/v1/sync/pull?since=3&limit=500"    );    assert_eq!(signed_path("https://x.invalid").expect("a path"), "/");    assert_eq!(        signed_path("https://x.invalid/v1/../me").expect("a path"),        "/me"    );    assert!(signed_path("not a url").is_err());}