asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Entropy source abstraction for deterministic testing.
//!
//! This module provides a capability-friendly entropy interface with
//! deterministic and OS-backed implementations.

use crate::types::TaskId;
use crate::util::DetRng;
use parking_lot::Mutex;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

/// Core trait for entropy providers.
pub trait EntropySource: std::fmt::Debug + Send + Sync + 'static {
    /// Fill a buffer with entropy bytes.
    fn fill_bytes(&self, dest: &mut [u8]);

    /// Return the next random `u64`.
    fn next_u64(&self) -> u64;

    /// Fork this entropy source deterministically for a child task.
    fn fork(&self, task_id: TaskId) -> Arc<dyn EntropySource>;

    /// Stable identifier for tracing and diagnostics.
    fn source_id(&self) -> &'static str;
}

/// OS-backed entropy source for production use.
#[derive(Debug, Default, Clone, Copy)]
pub struct OsEntropy;

impl EntropySource for OsEntropy {
    #[inline]
    fn fill_bytes(&self, dest: &mut [u8]) {
        check_ambient_entropy("os");
        getrandom::fill(dest).expect("OS entropy failed");
    }

    #[inline]
    fn next_u64(&self) -> u64 {
        let mut buf = [0u8; 8];
        self.fill_bytes(&mut buf);
        u64::from_le_bytes(buf)
    }

    #[inline]
    fn fork(&self, _task_id: TaskId) -> Arc<dyn EntropySource> {
        Arc::new(Self)
    }

    #[inline]
    fn source_id(&self) -> &'static str {
        "os"
    }
}

/// Deterministic entropy source for lab runtime.
#[derive(Debug)]
pub struct DetEntropy {
    inner: Mutex<DetEntropyInner>,
    seed: u64,
}

#[derive(Debug)]
struct DetEntropyInner {
    rng: DetRng,
    fork_counter: u64,
}

impl DetEntropy {
    /// Create a deterministic entropy source from a seed.
    #[inline]
    #[must_use]
    pub fn new(seed: u64) -> Self {
        Self {
            inner: Mutex::new(DetEntropyInner {
                rng: DetRng::new(seed),
                fork_counter: 0,
            }),
            seed,
        }
    }

    fn with_fork_counter(seed: u64, fork_counter: u64) -> Self {
        Self {
            inner: Mutex::new(DetEntropyInner {
                rng: DetRng::new(seed),
                fork_counter,
            }),
            seed,
        }
    }

    #[inline]
    fn task_seed(task_id: TaskId) -> u64 {
        let idx = task_id.arena_index();
        ((u64::from(idx.generation())) << 32) | u64::from(idx.index())
    }

    #[inline]
    pub(crate) fn mix_seed(mut seed: u64) -> u64 {
        seed ^= seed >> 30;
        seed = seed.wrapping_mul(0xbf58_476d_1ce4_e5b9);
        seed ^= seed >> 27;
        seed = seed.wrapping_mul(0x94d0_49bb_1331_11eb);
        seed ^= seed >> 31;
        seed
    }
}

impl EntropySource for DetEntropy {
    #[inline]
    fn fill_bytes(&self, dest: &mut [u8]) {
        let mut inner = self.inner.lock();
        inner.rng.fill_bytes(dest);
    }

    #[inline]
    fn next_u64(&self) -> u64 {
        self.inner.lock().rng.next_u64()
    }

    #[inline]
    fn fork(&self, task_id: TaskId) -> Arc<dyn EntropySource> {
        let mut inner = self.inner.lock();
        let counter = inner.fork_counter;
        inner.fork_counter = inner.fork_counter.wrapping_add(1);
        drop(inner);

        let mut child_seed = self.seed.wrapping_add(0x9e37_79b9_7f4a_7c15);
        child_seed = child_seed.wrapping_add(Self::task_seed(task_id));
        child_seed = child_seed.wrapping_add(counter);
        child_seed = Self::mix_seed(child_seed);
        Arc::new(Self::with_fork_counter(child_seed, 0))
    }

    #[inline]
    fn source_id(&self) -> &'static str {
        "deterministic"
    }
}

/// Browser-labeled entropy source for browser-facing capability plumbing.
///
/// `BrowserEntropy` is an honest thin wrapper around the ambient `getrandom`
/// backend with a distinct `source_id()` of `"browser"`. On
/// `wasm32-unknown-unknown`, the configured `getrandom` JS backend resolves to
/// the browser CSPRNG (for example `crypto.getRandomValues()`); on non-browser
/// targets it still provides real entropy while preserving the browser-specific
/// identity used by routing, diagnostics, and capability policy.
#[derive(Debug, Default, Clone, Copy)]
pub struct BrowserEntropy;

impl EntropySource for BrowserEntropy {
    #[inline]
    fn fill_bytes(&self, dest: &mut [u8]) {
        check_ambient_entropy("browser");
        getrandom::fill(dest).expect("browser entropy failed");
    }

    #[inline]
    fn next_u64(&self) -> u64 {
        let mut buf = [0u8; 8];
        self.fill_bytes(&mut buf);
        u64::from_le_bytes(buf)
    }

    #[inline]
    fn fork(&self, _task_id: TaskId) -> Arc<dyn EntropySource> {
        Arc::new(Self)
    }

    #[inline]
    fn source_id(&self) -> &'static str {
        "browser"
    }
}

/// Thread-local deterministic entropy sources derived from a global seed.
#[derive(Debug, Clone)]
pub struct ThreadLocalEntropy {
    global_seed: u64,
}

impl ThreadLocalEntropy {
    /// Create a thread-local entropy factory from a global seed.
    #[inline]
    #[must_use]
    pub const fn new(global_seed: u64) -> Self {
        Self { global_seed }
    }

    /// Deterministically derive an entropy source for a worker index.
    #[must_use]
    #[inline]
    pub fn for_thread(&self, thread_index: usize) -> DetEntropy {
        let combined = self
            .global_seed
            .wrapping_add(0x9e37_79b9_7f4a_7c15)
            .wrapping_add(thread_index as u64);
        DetEntropy::new(DetEntropy::mix_seed(combined))
    }
}

// ============================================================================
// Strict entropy isolation (lab tooling)
// ============================================================================

static STRICT_ENTROPY: AtomicBool = AtomicBool::new(false);

/// Enable strict entropy isolation globally.
#[inline]
pub fn enable_strict_entropy() {
    STRICT_ENTROPY.store(true, Ordering::SeqCst);
}

/// Disable strict entropy isolation globally.
#[inline]
pub fn disable_strict_entropy() {
    STRICT_ENTROPY.store(false, Ordering::SeqCst);
}

/// Returns true if strict entropy isolation is enabled.
#[inline]
#[must_use]
pub fn strict_entropy_enabled() -> bool {
    STRICT_ENTROPY.load(Ordering::SeqCst)
}

/// Panic if strict entropy isolation is enabled.
#[inline]
pub fn check_ambient_entropy(source: &str) {
    assert!(
        !strict_entropy_enabled(),
        "ambient entropy source \"{source}\" used in strict mode; use Cx::random_* instead"
    );
}

/// RAII guard to enable strict entropy isolation for a scope.
#[derive(Debug)]
pub struct StrictEntropyGuard {
    previous: bool,
}

impl StrictEntropyGuard {
    /// Enables strict entropy isolation until dropped.
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        let previous = STRICT_ENTROPY.swap(true, Ordering::SeqCst);
        Self { previous }
    }
}

impl Default for StrictEntropyGuard {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for StrictEntropyGuard {
    fn drop(&mut self) {
        STRICT_ENTROPY.store(self.previous, Ordering::SeqCst);
    }
}

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

    // =========================================================================
    // DetEntropy Core Functionality
    // =========================================================================

    #[test]
    fn det_entropy_same_seed_same_sequence() {
        let e1 = DetEntropy::new(42);
        let e2 = DetEntropy::new(42);

        for _ in 0..32 {
            assert_eq!(e1.next_u64(), e2.next_u64());
        }
    }

    #[test]
    fn det_entropy_different_seeds_different_sequences() {
        let e1 = DetEntropy::new(12345);
        let e2 = DetEntropy::new(54321);

        let v1 = e1.next_u64();
        let v2 = e2.next_u64();
        assert_ne!(v1, v2, "Different seeds should produce different values");
    }

    #[test]
    fn det_entropy_fill_bytes_deterministic() {
        let e1 = DetEntropy::new(42);
        let e2 = DetEntropy::new(42);

        let mut buf1 = [0u8; 64];
        let mut buf2 = [0u8; 64];

        e1.fill_bytes(&mut buf1);
        e2.fill_bytes(&mut buf2);

        assert_eq!(buf1, buf2);
    }

    #[test]
    fn det_entropy_seed_42_matches_stable_vector() {
        let e = DetEntropy::new(42);

        assert_eq!(e.next_u64(), 0x0000_000A_9551_4AAA);

        let mut bytes = [0u8; 8];
        let e = DetEntropy::new(42);
        e.fill_bytes(&mut bytes);
        assert_eq!(bytes, [0xAA, 0x4A, 0x51, 0x95, 0x0A, 0x00, 0x00, 0x00]);
    }

    #[test]
    fn det_entropy_fork_deterministic() {
        let parent1 = DetEntropy::new(99);
        let parent2 = DetEntropy::new(99);
        let task = TaskId::new_for_test(7, 0);

        let child1 = parent1.fork(task);
        let child2 = parent2.fork(task);

        for _ in 0..16 {
            assert_eq!(child1.next_u64(), child2.next_u64());
        }
    }

    #[test]
    fn det_entropy_fork_different_tasks_different_sequences() {
        let parent = DetEntropy::new(42);

        let task1 = TaskId::new_for_test(1, 0);
        let task2 = TaskId::new_for_test(2, 0);

        let child1 = parent.fork(task1);
        let child2 = parent.fork(task2);

        assert_ne!(
            child1.next_u64(),
            child2.next_u64(),
            "Different task IDs should produce different children"
        );
    }

    #[test]
    fn det_entropy_sequential_forks_different() {
        let parent = DetEntropy::new(42);
        let task_id = TaskId::new_for_test(1, 0);

        let child1 = parent.fork(task_id);
        let child2 = parent.fork(task_id);

        assert_ne!(
            child1.next_u64(),
            child2.next_u64(),
            "Sequential forks of same task should differ (fork counter)"
        );
    }

    #[test]
    fn det_entropy_source_id() {
        let e = DetEntropy::new(42);
        assert_eq!(e.source_id(), "deterministic");
    }

    // =========================================================================
    // OsEntropy Tests
    // =========================================================================

    #[test]
    fn os_entropy_produces_different_values() {
        let os = OsEntropy;
        let v1 = os.next_u64();
        let v2 = os.next_u64();

        // Extremely unlikely to be equal
        assert_ne!(v1, v2, "OS entropy should produce different values");
    }

    #[test]
    fn os_entropy_fill_bytes_works() {
        let os = OsEntropy;
        let mut buf = [0u8; 32];
        os.fill_bytes(&mut buf);

        // Check not all zeros (astronomically unlikely with real entropy)
        assert!(
            buf.iter().any(|&b| b != 0),
            "OS entropy should produce non-zero bytes"
        );
    }

    #[test]
    fn os_entropy_source_id() {
        let os = OsEntropy;
        assert_eq!(os.source_id(), "os");
    }

    #[test]
    fn os_entropy_fork_returns_os_entropy() {
        let os = OsEntropy;
        let task_id = TaskId::new_for_test(1, 0);
        let forked = os.fork(task_id);
        assert_eq!(forked.source_id(), "os");
    }

    // =========================================================================
    // BrowserEntropy Tests
    // =========================================================================

    #[test]
    fn browser_entropy_source_id() {
        let entropy = BrowserEntropy;
        assert_eq!(entropy.source_id(), "browser");
    }

    #[test]
    fn browser_entropy_fork_preserves_browser_identity() {
        let entropy = BrowserEntropy;
        let task_id = TaskId::new_for_test(1, 0);
        let forked = entropy.fork(task_id);
        assert_eq!(forked.source_id(), "browser");
    }

    #[test]
    fn browser_entropy_fill_bytes_works() {
        let entropy = BrowserEntropy;
        let mut buf = [0u8; 32];
        entropy.fill_bytes(&mut buf);
        assert!(
            buf.iter().any(|&b| b != 0),
            "browser entropy should produce non-zero bytes"
        );
    }

    // =========================================================================
    // Edge Cases
    // =========================================================================

    #[test]
    fn det_entropy_zero_seed_works() {
        let e = DetEntropy::new(0);
        let _ = e.next_u64(); // Should not panic
    }

    #[test]
    fn det_entropy_max_seed_works() {
        let e = DetEntropy::new(u64::MAX);
        let _ = e.next_u64(); // Should not panic or overflow
    }

    #[test]
    fn det_entropy_fill_zero_bytes() {
        let e = DetEntropy::new(42);
        let mut buf: [u8; 0] = [];
        e.fill_bytes(&mut buf); // Should not panic
    }

    // =========================================================================
    // ThreadLocalEntropy Tests
    // =========================================================================

    #[test]
    fn thread_local_entropy_deterministic() {
        let tl1 = ThreadLocalEntropy::new(1234);
        let tl2 = ThreadLocalEntropy::new(1234);

        let e1 = tl1.for_thread(3);
        let e2 = tl2.for_thread(3);

        assert_eq!(e1.next_u64(), e2.next_u64());
    }

    #[test]
    fn thread_local_entropy_different_threads() {
        let tl = ThreadLocalEntropy::new(12345);

        let e0 = tl.for_thread(0);
        let e1 = tl.for_thread(1);

        assert_ne!(e0.next_u64(), e1.next_u64());
    }

    #[test]
    fn thread_local_entropy_zero_seed_not_correlated() {
        // Regression: global_seed=0 previously produced correlated thread seeds
        // because 0 * constant = 0, making seeds just 0, 1, 2, ...
        let tl = ThreadLocalEntropy::new(0);

        let e0 = tl.for_thread(0);
        let e1 = tl.for_thread(1);
        let e2 = tl.for_thread(2);

        let v0 = e0.next_u64();
        let v1 = e1.next_u64();
        let v2 = e2.next_u64();

        assert_ne!(v0, v1);
        assert_ne!(v1, v2);
        assert_ne!(v0, v2);
    }

    // =========================================================================
    // Thread Safety Tests
    // =========================================================================

    #[test]
    fn det_entropy_thread_safe() {
        use std::thread;

        let e = Arc::new(DetEntropy::new(42));
        let mut handles = vec![];

        for _ in 0..4 {
            let entropy = Arc::clone(&e);
            handles.push(thread::spawn(move || {
                for _ in 0..1000 {
                    let _ = entropy.next_u64();
                }
            }));
        }

        for handle in handles {
            handle.join().expect("thread panicked");
        }
    }
}