capsule_core/ambient.rs
1//! The ambient inputs a caller injects: wall-clock time and identifier randomness.
2//!
3//! The stateless core reads no clock and draws no identifier itself ([crate docs](crate)). Where a core operation mints a UUIDv7 — an account's user and device ids, an MLS
4//! intent id, a federation `group_id` — it takes an [`IdSource`], built from a [`Clock`] and an
5//! [`Rng`] the caller implements. `capsule-library` supplies the system implementations; tests
6//! supply a fixed clock and a seeded source, so every minted identifier is reproducible.
7//!
8//! [`Rng`] is for **identifiers only**. Key material, salts and nonces never come from an
9//! injectable source: they are drawn from the OS CSPRNG behind [`crate::crypto::rng`], the one
10//! sanctioned exception.
11//!
12//! [`IdSource`]: crate::ambient::IdSource
13//! [`Clock`]: crate::ambient::Clock
14//! [`Rng`]: crate::ambient::Rng
15
16use jiff::Timestamp;
17use uuid::Uuid;
18
19/// A source of wall-clock time.
20pub trait Clock: Send + Sync {
21 /// The current instant.
22 fn now(&self) -> Timestamp;
23}
24
25/// A source of random bytes for **identifiers** (never key material; see the module docs).
26pub trait Rng: Send + Sync {
27 /// Fill `buf` with random bytes.
28 fn fill_bytes(&self, buf: &mut [u8]);
29}
30
31/// Mints UUIDv7 identifiers from an injected [`Clock`] and [`Rng`].
32///
33/// Cheap to copy: it borrows both sources, so one value is threaded through a call chain.
34#[derive(Clone, Copy)]
35pub struct IdSource<'a> {
36 clock: &'a dyn Clock,
37 rng: &'a dyn Rng,
38}
39
40impl std::fmt::Debug for IdSource<'_> {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 f.debug_struct("IdSource").finish_non_exhaustive()
43 }
44}
45
46impl<'a> IdSource<'a> {
47 /// An identifier source over `clock` and `rng`.
48 pub fn new(clock: &'a dyn Clock, rng: &'a dyn Rng) -> Self {
49 Self { clock, rng }
50 }
51
52 /// A fresh UUIDv7: the clock's Unix milliseconds followed by 74 random bits.
53 ///
54 /// An instant before the Unix epoch stamps as `0`; the identifier stays well-formed and
55 /// unique by its random bits.
56 pub fn uuid_v7(&self) -> Uuid {
57 let now = self.clock.now();
58 let millis = u64::try_from(now.as_millisecond()).unwrap_or(0);
59 let mut random = [0u8; 10];
60 self.rng.fill_bytes(&mut random);
61 let id = uuid::Builder::from_unix_timestamp_millis(millis, &random).into_uuid();
62 tracing::trace!(%id, millis, "minted UUIDv7");
63 id
64 }
65}
66
67#[cfg(any(test, feature = "test-support"))]
68pub mod testing;
69
70#[cfg(test)]
71mod tests;