Cotton code
516 lines · 20.7 KB · RustRaw
//! The token format, as vectors. Every value here is invented.use super::*;const WORKSPACE: &str = "ws_01JB0000000000000000000000";const GRANT: &str = "grant_01JB111111111111111111111";const OTHER_WORKSPACE: &str = "ws_01JB9999999999999999999999";/// The device id a digest names as its writer — base64url, as a real one is. Invented.const MAC: &str = "c3ludGhldGljLW1hYy1kZXZpY2UtaWQtZm9yLXRlc3Rz";fn vmk(byte: u8) -> Vmk {    Vmk::from_bytes([byte; 32])}fn key(byte: u8, workspace: &str, version: u32) -> [u8; 32] {    *token_key(&vmk(byte), workspace, version)}fn access(generation_free: i64) -> TokenClaims {    TokenClaims {        kind: TokenKind::Access,        vmk_version: 3,        issued_at_ms: generation_free,        expires_at_ms: generation_free + 3_600_000,        generation: 0,        workspace_id: WORKSPACE.to_string(),        grant_id: GRANT.to_string(),    }}fn refresh(generation: u32) -> TokenClaims {    TokenClaims {        kind: TokenKind::Refresh,        vmk_version: 3,        issued_at_ms: 0,        expires_at_ms: 0,        generation,        workspace_id: WORKSPACE.to_string(),        grant_id: GRANT.to_string(),    }}// ── the round trip ──────────────────────────────────────────────────────────#[test]fn an_access_token_round_trips_every_field_it_carries() {    let k = key(1, WORKSPACE, 3);    let claims = access(1_800_000_000_000);    let token = mint(&k, &claims).expect("mints");    assert!(token.starts_with(ACCESS_PREFIX));    assert_eq!(verify_with(&token, &k), Some(claims));}#[test]fn a_refresh_token_round_trips_and_carries_its_generation() {    let k = key(1, WORKSPACE, 3);    let claims = refresh(12);    let token = mint(&k, &claims).expect("mints");    assert!(token.starts_with(REFRESH_PREFIX));    assert_eq!(verify_with(&token, &k).expect("verifies").generation, 12);}#[test]fn a_refresh_token_is_a_pure_function_of_its_grant_and_generation() {    // THE PROPERTY THE WHOLE RETRY PATH RESTS ON: two Macs, or two concurrent    // presentations on one Mac, arrive at the same successor rather than    // forking the chain.    let k = key(1, WORKSPACE, 3);    assert_eq!(mint(&k, &refresh(9)), mint(&k, &refresh(9)));    assert_ne!(mint(&k, &refresh(9)), mint(&k, &refresh(10)));}#[test]fn an_access_token_may_not_claim_a_generation_and_a_refresh_may_not_claim_a_clock() {    let k = key(1, WORKSPACE, 3);    let mut bad = access(1);    bad.generation = 4;    assert_eq!(mint(&k, &bad), None);    let mut clocked = refresh(2);    clocked.expires_at_ms = 5;    assert_eq!(mint(&k, &clocked), None);}#[test]fn an_empty_or_oversized_id_is_refused_rather_than_truncated() {    let k = key(1, WORKSPACE, 3);    let mut empty = access(1);    empty.grant_id = String::new();    assert_eq!(mint(&k, &empty), None);    let mut long = access(1);    long.workspace_id = "w".repeat(256);    assert_eq!(mint(&k, &long), None);}// ── the key ─────────────────────────────────────────────────────────────────#[test]fn the_key_is_stable_for_one_workspace_at_one_version() {    assert_eq!(key(7, WORKSPACE, 2), key(7, WORKSPACE, 2));}#[test]fn a_different_master_key_a_different_workspace_or_a_different_version_is_a_different_key() {    let base = key(7, WORKSPACE, 2);    assert_ne!(base, key(8, WORKSPACE, 2));    assert_ne!(base, key(7, OTHER_WORKSPACE, 2));    assert_ne!(base, key(7, WORKSPACE, 3));}#[test]fn the_token_key_is_not_the_sealing_key() {    // Domain separation, said as a test: a token can never be made to open a    // password and a password's ciphertext can never verify as a token.    let master = vmk(5);    let token = *token_key(&master, WORKSPACE, 1);    assert_ne!(token, *master.expose());}#[test]fn a_workspace_whose_name_is_a_prefix_of_another_derives_a_different_key() {    // The info string is NUL-delimited, so `ws_1` + version 23 and `ws_12` +    // version 3 cannot collide by concatenation.    let master = vmk(5);    assert_ne!(*token_key(&master, "ws_1", 23), *token_key(&master, "ws_12", 3));}// ── the refusals ────────────────────────────────────────────────────────────#[test]fn a_token_signed_under_another_workspaces_key_does_not_verify() {    let token = mint(&key(1, WORKSPACE, 3), &access(1)).expect("mints");    assert_eq!(verify_with(&token, &key(1, OTHER_WORKSPACE, 3)), None);}#[test]fn a_token_signed_under_a_retired_version_does_not_verify_under_the_current_one() {    let token = mint(&key(1, WORKSPACE, 3), &access(1)).expect("mints");    assert_eq!(verify_with(&token, &key(1, WORKSPACE, 4)), None);}#[test]fn every_single_bit_of_the_body_is_covered_by_the_tag() {    let k = key(1, WORKSPACE, 3);    let token = mint(&k, &access(1_800_000_000_000)).expect("mints");    let body = token.strip_prefix(ACCESS_PREFIX).expect("prefixed");    let bytes = URL_SAFE_NO_PAD.decode(body).expect("decodes");    for index in 0..bytes.len() {        for bit in 0..8u8 {            let mut flipped = bytes.clone();            flipped[index] ^= 1 << bit;            let candidate = format!("{ACCESS_PREFIX}{}", URL_SAFE_NO_PAD.encode(&flipped));            assert_eq!(                verify_with(&candidate, &k),                None,                "a flipped bit at {index}:{bit} verified"            );        }    }}#[test]fn the_prefix_and_the_body_must_agree_about_which_family_this_is() {    let k = key(1, WORKSPACE, 3);    let token = mint(&k, &refresh(1)).expect("mints");    let swapped = format!(        "{ACCESS_PREFIX}{}",        token.strip_prefix(REFRESH_PREFIX).expect("prefixed")    );    // A `ctr_` re-labelled `cta_` would be a refresh token spent at `/v1/mcp`.    assert_eq!(verify_with(&swapped, &k), None);    assert_eq!(selector(&swapped), None);}#[test]fn nonsense_is_refused_and_never_panics() {    let k = key(1, WORKSPACE, 3);    for candidate in [        "",        "cta_",        "ctr_",        "cta_!!!!",        "cta_AAAA",        "ctn_pasted-token-of-the-other-family",        "Bearer cta_whatever",        &format!("{ACCESS_PREFIX}{}", URL_SAFE_NO_PAD.encode([0u8; 80])),    ] {        assert_eq!(verify_with(candidate, &k), None, "{candidate} verified");        assert!(!is_signed_token(candidate) || selector(candidate).is_some());    }}#[test]fn a_body_with_bytes_after_the_grant_id_is_refused_rather_than_read_twice() {    let k = key(1, WORKSPACE, 3);    let claims = access(1);    let mut body = write_body(&claims, SCHEME).expect("writes");    body.push(b'x');    let tag = tag_of(&k, &body);    let mut whole = body.clone();    whole.extend_from_slice(&tag);    let token = format!("{ACCESS_PREFIX}{}", URL_SAFE_NO_PAD.encode(&whole));    // The tag is honest — the trailing byte is inside the signed region — and    // it is still refused, because two readings of one token is how a parser    // and a verifier come to disagree.    assert_eq!(verify_with(&token, &k), None);}#[test]fn a_body_naming_another_scheme_is_refused_rather_than_guessed_at() {    let k = key(1, WORKSPACE, 3);    let mut body = write_body(&access(1), SCHEME).expect("writes");    body[0] = SCHEME + 1;    let mut whole = body.clone();    whole.extend_from_slice(&tag_of(&k, &body));    let token = format!("{ACCESS_PREFIX}{}", URL_SAFE_NO_PAD.encode(&whole));    assert_eq!(verify_with(&token, &k), None);}// ── the selector ────────────────────────────────────────────────────────────#[test]fn the_selector_names_the_workspace_and_version_before_any_key_is_held() {    let mut claims = access(1);    claims.vmk_version = 6;    let token = mint(&key(1, WORKSPACE, 6), &claims).expect("mints");    let selector = selector(&token).expect("reads");    assert_eq!(selector.kind, TokenKind::Access);    assert_eq!(selector.scheme, SCHEME);    assert_eq!(selector.vmk_version, 6);    assert_eq!(selector.workspace_id, WORKSPACE);    assert_eq!(selector.grant_id, claims.grant_id);}#[test]fn a_pasted_token_of_the_other_family_is_not_a_signed_token() {    assert!(!is_signed_token("ctn_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));    assert_eq!(selector("ctn_AAAA"), None);}#[test]fn an_opaque_token_of_the_old_scheme_is_not_mistaken_for_a_signed_one() {    // 32 random bytes behind `cta_` — what every token this product minted    // before this scheme looked like. It decodes, and it is 32 bytes, which is    // far short of a body and a tag.    let opaque = format!("{ACCESS_PREFIX}{}", URL_SAFE_NO_PAD.encode([9u8; 32]));    assert_eq!(selector(&opaque), None);    assert!(!is_signed_token(&opaque));}// ── every rule the minter keeps, the verifier keeps ─────────────────────────//// THE KEY IS NOT THE SERVER'S ALONE. Every paired device unwraps the workspace// master key, so "the minter is our own `mint`" is an assumption, not a fact. A// rule enforced only on the way out binds the honest path and nothing else.#[test]fn an_access_token_carrying_a_generation_is_refused_at_both_ends() {    let k = key(1, WORKSPACE, 3);    let mut claims = access(1_700_000_000_000);    claims.generation = 1;    assert!(mint(&k, &claims).is_none(), "the minter refuses it");    // And so does the verifier, against a token something else signed.    let forged = forge(&k, &claims);    assert!(verify_with(&forged, &k).is_none(), "the verifier refuses it");}#[test]fn an_access_token_that_claims_more_life_than_the_scheme_grants_is_refused() {    let k = key(1, WORKSPACE, 3);    let mut claims = access(1_700_000_000_000);    claims.expires_at_ms = claims.issued_at_ms + MAX_ACCESS_LIFE_MS + 1;    assert!(mint(&k, &claims).is_none());    assert!(        verify_with(&forge(&k, &claims), &k).is_none(),        "a century-long access token is refused however well it is signed"    );    // The ceiling itself is inside.    claims.expires_at_ms = claims.issued_at_ms + MAX_ACCESS_LIFE_MS;    let token = mint(&k, &claims).expect("the ceiling is allowed");    assert!(verify_with(&token, &k).is_some());}#[test]fn an_access_token_that_expires_before_it_was_issued_is_refused() {    let k = key(1, WORKSPACE, 3);    let mut claims = access(1_700_000_000_000);    claims.expires_at_ms = claims.issued_at_ms - 1;    assert!(mint(&k, &claims).is_none());    assert!(verify_with(&forge(&k, &claims), &k).is_none());    // And a pair of extremes cannot overflow its way past the check.    claims.issued_at_ms = i64::MIN;    claims.expires_at_ms = i64::MAX;    assert!(mint(&k, &claims).is_none());    assert!(verify_with(&forge(&k, &claims), &k).is_none());}/// A correctly SIGNED token for claims `mint` would refuse — what a device that/// holds the master key but not this code can produce.fn forge(key: &[u8; 32], claims: &TokenClaims) -> String {    let body = write_body(claims, SCHEME).expect("the body is writable");    let mut out = body.clone();    out.extend_from_slice(&tag_of(key, &body));    format!(        "{}{}",        claims.kind.prefix(),        base64::engine::Engine::encode(&URL_SAFE_NO_PAD, &out)    )}// ── scheme 2: a refresh token that carries bytes no row holds ───────────────const NONCE: [u8; NONCE_LEN] = [0x5a; NONCE_LEN];#[test]fn a_sealed_refresh_token_round_trips_and_names_scheme_two() {    let k = key(1, WORKSPACE, 3);    let claims = refresh(12);    let token = mint_refresh(&k, &claims, &NONCE).expect("mints");    assert!(token.starts_with(REFRESH_PREFIX));    assert_eq!(verify_with(&token, &k), Some(claims.clone()));    assert_eq!(selector(&token).expect("a selector").scheme, SCHEME_SEALED);    assert_eq!(claims_unverified(&token), Some(claims));}/// RULE: Two refresh tokens over the same claims differ by their nonce, so the old key and the synced row do not rebuild a live one.#[test]fn two_nonces_over_one_set_of_claims_are_two_tokens() {    // The old key and the synced row do not rebuild a live refresh token —    // every field but the nonce is on the row, so the nonce is the    // whole of the difference.    let k = key(1, WORKSPACE, 3);    let one = mint_refresh(&k, &refresh(4), &[1; NONCE_LEN]).expect("mints");    let two = mint_refresh(&k, &refresh(4), &[2; NONCE_LEN]).expect("mints");    assert_ne!(one, two);    assert_ne!(refresh_digest(4, &one, MAC), refresh_digest(4, &two, MAC));}#[test]fn only_a_refresh_token_with_no_clock_is_minted_sealed() {    let k = key(1, WORKSPACE, 3);    assert_eq!(mint_refresh(&k, &access(1_800_000_000_000), &NONCE), None);    let mut clocked = refresh(1);    clocked.issued_at_ms = 5;    assert_eq!(mint_refresh(&k, &clocked, &NONCE), None);}#[test]fn a_scheme_one_refresh_token_still_verifies_but_is_never_read_unverified() {    // A token handed out before store version 45 keeps working under the key    // it names; after a rotation nothing admits it, because every byte of it    // is rebuildable from the old key and the row.    let k = key(1, WORKSPACE, 3);    let token = mint(&k, &refresh(7)).expect("mints");    assert_eq!(verify_with(&token, &k).expect("verifies").generation, 7);    assert_eq!(selector(&token).expect("a selector").scheme, SCHEME);    assert_eq!(claims_unverified(&token), None);}#[test]fn an_access_token_is_never_scheme_two_and_never_read_unverified() {    let k = key(1, WORKSPACE, 3);    let access_token = mint(&k, &access(1_800_000_000_000)).expect("mints");    assert_eq!(claims_unverified(&access_token), None);    // A scheme-2 body under the access prefix, signed with the real key: the    // layout exists for refresh tokens only.    let sealed = mint_refresh(&k, &refresh(0), &NONCE).expect("mints");    let (_, rest) = sealed.split_at(REFRESH_PREFIX.len());    let mut bytes = URL_SAFE_NO_PAD.decode(rest).expect("base64");    bytes[1] = 1; // kind: access    let split = bytes.len() - TAG_LEN;    let tag = tag_of(&k, &bytes[..split]);    bytes[split..].copy_from_slice(&tag);    let forged = format!("{ACCESS_PREFIX}{}", URL_SAFE_NO_PAD.encode(&bytes));    assert_eq!(verify_with(&forged, &k), None);    assert_eq!(claims_unverified(&forged), None);}#[test]fn a_sealed_body_with_a_short_or_long_nonce_is_refused() {    let k = key(1, WORKSPACE, 3);    for delta in [-1isize, 1] {        let mut body = write_body(&refresh(2), SCHEME_SEALED).expect("a body");        let len = (NONCE_LEN as isize + delta) as usize;        body.extend(std::iter::repeat_n(7u8, len));        let mut bytes = body.clone();        bytes.extend_from_slice(&tag_of(&k, &body));        let token = format!("{REFRESH_PREFIX}{}", URL_SAFE_NO_PAD.encode(&bytes));        assert_eq!(verify_with(&token, &k), None, "a nonce of {len} bytes verified");        assert_eq!(claims_unverified(&token), None, "a nonce of {len} bytes was read");        assert_eq!(selector(&token), None, "a nonce of {len} bytes selected a key");    }}#[test]fn a_tampered_sealed_token_reads_unverified_but_its_digest_is_another() {    // `claims_unverified` checks no tag by design; what stands between a    // tampered token and admission is the digest over the WHOLE string.    let k = key(1, WORKSPACE, 3);    let token = mint_refresh(&k, &refresh(3), &NONCE).expect("mints");    let stored = refresh_digest(3, &token, MAC);    let mut tampered = token.clone();    tampered.pop();    tampered.push(if token.ends_with('A') { 'B' } else { 'A' });    assert!(refresh_digest_matches(&stored, 3, &token));    assert!(!refresh_digest_matches(&stored, 3, &tampered));    assert!(!refresh_digest_matches(&stored, 4, &token), "the generation is part of the value");    assert!(!refresh_digest_matches("", 3, &token));    assert!(        refresh_digest_matches(&refresh_digest(3, &token, "another-mac"), 3, &token),        "the token is matched whoever wrote its digest; WHO is asked separately"    );}/// RULE: A stored refresh digest names the device that wrote it, and a value with no well-formed writer admits no token.#[test]fn a_stored_digest_names_its_writer_and_one_without_a_writer_admits_nothing() {    // The writer is who a digest dies with: the sync route accepts a digest    // only from the device it names, and a revocation reaches every grant    // whose current digest the revoked device wrote. A value without one is    // one nobody can be held to, so it matches nothing.    let k = key(1, WORKSPACE, 3);    let token = mint_refresh(&k, &refresh(3), &NONCE).expect("mints");    let stored = refresh_digest(3, &token, MAC);    assert_eq!(refresh_digest_writer(&stored), Some(MAC));    let bare = &stored[..DIGEST_BODY_LEN];    assert_eq!(refresh_digest_writer(bare), None);    assert!(!refresh_digest_matches(bare, 3, &token));    for writer in ["", "a mac", "mac\n", &"x".repeat(DIGEST_WRITER_MAX + 1)] {        let odd = format!("{bare}:{writer}");        assert_eq!(refresh_digest_writer(&odd), None, "{writer:?} is not a device id");        assert!(!refresh_digest_matches(&odd, 3, &token));    }    assert_eq!(        refresh_digest_writer(&refresh_digest(3, &token, "device:test")),        Some("device:test")    );}#[test]fn the_successor_nonce_is_a_function_of_the_whole_predecessor() {    let k = key(1, WORKSPACE, 3);    let one = mint_refresh(&k, &refresh(3), &[1; NONCE_LEN]).expect("mints");    let two = mint_refresh(&k, &refresh(3), &[2; NONCE_LEN]).expect("mints");    assert_eq!(successor_nonce(&one), successor_nonce(&one), "a retry arrives at the same one");    assert_ne!(successor_nonce(&one), successor_nonce(&two));    assert_ne!(        successor_nonce(&one)[..],        Sha256::digest(one.as_bytes())[..NONCE_LEN],        "domain-separated from a bare hash of the token"    );}/// RULE: The successor of a token the key alone could have made is a keyed function of that token — the same on a retry, and never the successor a digest-vouched predecessor gets.#[test]fn the_successor_of_a_rebuildable_token_is_keyed_and_reproducible() {    let k = key(1, WORKSPACE, 3);    let one = mint_refresh(&k, &refresh(3), &[1; NONCE_LEN]).expect("mints");    let two = mint_refresh(&k, &refresh(3), &[2; NONCE_LEN]).expect("mints");    assert_eq!(        rebuildable_successor_nonce(&k, &one),        rebuildable_successor_nonce(&k, &one),        "a retry arrives at the same successor"    );    assert_ne!(rebuildable_successor_nonce(&k, &one), rebuildable_successor_nonce(&k, &two));    assert_ne!(        rebuildable_successor_nonce(&k, &one),        rebuildable_successor_nonce(&key(1, WORKSPACE, 4), &one),        "keyed: another key, another successor"    );    assert_ne!(        rebuildable_successor_nonce(&k, &one),        successor_nonce(&one),        "never the successor a digest-vouched predecessor gets"    );}#[test]fn a_stored_digest_names_its_generation_first_and_sorts_by_it() {    let token = "ctr_invented";    let low = refresh_digest(9, token, MAC);    let high = refresh_digest(10, token, MAC);    assert_eq!(low.len(), DIGEST_BODY_LEN + 1 + MAC.len());    assert!(low.starts_with("0000000009:"));    assert!(high > low, "text order is generation order");    assert!(        refresh_digest(10, token, "a") > refresh_digest(9, token, "zzzz"),        "whoever wrote it, the generation decides the order"    );    assert!(refresh_digest(u32::MAX, token, MAC).starts_with("4294967295:"));}/// RULE: A stored refresh digest is compared with the presented token's digest in constant time (`subtle`'s `ct_eq`), never with `==`, so the time a refusal takes says nothing about how much of the digest matched.#[test]fn a_refresh_digest_is_compared_in_constant_time() {    let source = include_str!("tokens.rs");    let start = source        .find("pub fn refresh_digest_matches(")        .expect("the comparison is in tokens.rs");    let body = &source[start..];    let body = &body[..body.find("\n}\n").expect("the function ends")];    assert!(body.contains(".ct_eq("), "the digest comparison is not constant time");    assert!(        !body.contains(" == expected") && !body.contains("expected ==") && !body.contains(".eq("),        "the digest is compared with a short-circuiting equality"    );    // And it still answers: the right token matches, a different one does not.    let stored = refresh_digest(3, "ctr_an_invented_token", "mac-invented");    assert!(refresh_digest_matches(&stored, 3, "ctr_an_invented_token"));    assert!(!refresh_digest_matches(&stored, 3, "ctr_another_invented_token"));    assert!(!refresh_digest_matches(&stored, 4, "ctr_an_invented_token"));}