Cotton code
49 lines · 1.7 KB · RustRaw
use super::{base64url_bytes, uuid_v4, Random, SystemRandom};/// A source that hands out a known sequence — the whole point of the seam.#[derive(Debug)]struct Fixed(Vec<u8>);impl Random for Fixed {    fn fill(&self, out: &mut [u8]) {        for (index, byte) in out.iter_mut().enumerate() {            *byte = self.0[index % self.0.len()];        }    }}#[test]fn a_uuid_says_it_is_a_v4_whatever_the_source_handed_over() {    // All-zero bytes: a source that got the version and variant bits wrong    // would produce `00000000-0000-0000-0000-000000000000`, which readers    // treat as "no id" rather than as an id.    let id = uuid_v4(&Fixed(vec![0x00]));    assert_eq!(id, "00000000-0000-4000-8000-000000000000");    // And with every bit set the other way, the same two nibbles are pinned.    let id = uuid_v4(&Fixed(vec![0xff]));    assert_eq!(id, "ffffffff-ffff-4fff-bfff-ffffffffffff");}#[test]fn a_secret_is_base64url_with_no_padding() {    // Padding would be `=`, which is legal in a URL only when escaped — and a    // token is pasted into forms, headers and shell commands.    let secret = base64url_bytes(&Fixed(vec![0xfb, 0xff]), 32);    assert!(!secret.contains('='));    assert!(!secret.contains('+'));    assert!(!secret.contains('/'));    // 32 bytes is 43 base64 characters unpadded.    assert_eq!(secret.len(), 43);}#[test]fn the_systems_own_source_does_not_hand_back_the_same_bytes_twice() {    let random = SystemRandom;    let mut a = [0u8; 32];    let mut b = [0u8; 32];    random.fill(&mut a);    random.fill(&mut b);    assert_ne!(a, b);    // And it is not simply leaving the buffer alone.    assert_ne!(a, [0u8; 32]);}