Cotton code
58 lines · 2.1 KB · RustRaw
//! Where every random byte on this server comes from.//!//! The clock has `Clock` for exactly this reason and randomness needs the same//! treatment for a better one: a credential is decided ONCE and can never be//! looked at again, so a suite that cannot say what bytes a mint drew can only//! assert that the result has the right shape. Behind this seam it can assert//! the value, and the shape claim stops being a guess.//!//! It is NOT a place to put a fixed value on a real server. `SystemRandom` is//! the operating system's own generator, and the only other implementation in//! the tree is a test's.//!//! There is no TypeScript original: `node:crypto`'s `randomBytes` and//! `randomUUID` were reached for directly wherever they were needed. That is//! the thing being fixed — `tokens.ts`'s `generateToken` is untestable for the//! same reason a wall-clock `new Date()` is.use std::fmt;/// Fill a buffer with unpredictable bytes.pub trait Random: Send + Sync + fmt::Debug {    fn fill(&self, out: &mut [u8]);}/// The operating system's generator — what a real server runs on.#[derive(Debug, Default)]pub struct SystemRandom;impl Random for SystemRandom {    fn fill(&self, out: &mut [u8]) {        use rand::RngCore;        rand::rngs::OsRng.fill_bytes(out);    }}/// A v4 UUID from this source — the id every minted row carries.////// Version and variant bits are set here rather than trusted from the source,/// because a UUID that does not say it is a v4 is a string other readers will/// reject.pub fn uuid_v4(random: &dyn Random) -> String {    let mut bytes = [0u8; 16];    random.fill(&mut bytes);    bytes[6] = (bytes[6] & 0x0f) | 0x40;    bytes[8] = (bytes[8] & 0x3f) | 0x80;    cotton_store::protocol::uuid::format_uuid_v4(&bytes)}/// `n` bytes, base64url, no padding — how a secret is spelled on the wire.pub fn base64url_bytes(random: &dyn Random, n: usize) -> String {    use base64::Engine;    let mut bytes = vec![0u8; n];    random.fill(&mut bytes);    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)}#[cfg(test)]mod tests;