eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! Random secrets (dashboard auth token, approval and login-session ids).

use crate::error::{Error, Result};
use std::fmt::Write;

/// `bytes` bytes from the OS CSPRNG, hex-encoded (so `2 * bytes` characters).
pub fn random_hex(bytes: usize) -> Result<String> {
    let mut buf = vec![0u8; bytes];
    getrandom::getrandom(&mut buf)
        .map_err(|e| Error::Config(format!("cannot read OS randomness: {e}")))?;
    let mut out = String::with_capacity(bytes * 2);
    for b in buf {
        let _ = write!(out, "{b:02x}");
    }
    Ok(out)
}

/// A fresh 256-bit token, hex-encoded.
pub fn generate() -> Result<String> {
    random_hex(32)
}

/// Equality that does not stop at the first differing byte.
pub fn constant_time_eq(a: &str, b: &str) -> bool {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    let mut diff = a.len() ^ b.len();
    for i in 0..a.len().max(b.len()) {
        diff |= usize::from(a.get(i).copied().unwrap_or(0) ^ b.get(i).copied().unwrap_or(0));
    }
    diff == 0
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tokens_are_hex_and_distinct() {
        let (a, b) = (generate().unwrap(), generate().unwrap());
        assert_eq!(a.len(), 64);
        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
        assert_ne!(a, b);
        assert_eq!(random_hex(4).unwrap().len(), 8);
    }

    #[test]
    fn constant_time_eq_matches_normal_equality() {
        assert!(constant_time_eq("abc", "abc"));
        assert!(!constant_time_eq("abc", "abd"));
        assert!(!constant_time_eq("abc", "abcd"));
        assert!(!constant_time_eq("", "a"));
        assert!(constant_time_eq("", ""));
    }
}