boxlite 0.9.3

Embeddable virtual machine runtime for secure, isolated code execution
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
//! Runtime ID generation and validation.
//!
//! - Box IDs are 12-character Base62 strings (~71 bits of entropy) generated by
//!   [`BoxIDMint`]. Legacy 26-character ULID IDs are also accepted.
//! - Base disk IDs are 8-character Base62 strings (~48 bits of entropy)
//!   generated by [`BaseDiskIDMint`].

use rand::RngCore;
use rusqlite::ToSql;
use rusqlite::types::{ToSqlOutput, ValueRef};
use serde::{Deserialize, Serialize};
use std::fmt;

const BASE62_ALPHABET: &[u8; 62] =
    b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

fn mint_base62<const N: usize>() -> String {
    let mut rng = rand::rng();
    let mut buf = [0u8; N];
    for b in &mut buf {
        // Modulo bias is negligible: 2^32 % 62 = 16, bias < 0.000004%.
        *b = BASE62_ALPHABET[(rng.next_u32() % 62) as usize];
    }
    // SAFETY: BASE62_ALPHABET contains only ASCII bytes, so this is valid UTF-8.
    String::from_utf8(buf.to_vec()).unwrap()
}

// ============================================================================
// BOX ID
// ============================================================================

/// Box identifier.
///
/// New boxes use 12-character Base62 strings (~71 bits entropy).
/// Legacy boxes may use 26-character ULID strings. Both formats are accepted.
///
/// # Example
///
/// ```
/// use boxlite::runtime::id::{BoxID, BoxIDMint};
///
/// let id = BoxIDMint::mint();
/// assert_eq!(id.as_str().len(), 12);
/// assert_eq!(id.short().len(), 8);
/// ```
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BoxID(String);

impl BoxID {
    /// Length of new box IDs (12-char Base62).
    pub const FULL_LENGTH: usize = 12;

    /// Length of legacy box IDs (26-char ULID).
    pub const LEGACY_LENGTH: usize = 26;

    /// Length of short box ID for display (8 chars).
    pub const SHORT_LENGTH: usize = 8;

    /// Parse a BoxID from an existing string.
    ///
    /// Accepts 12-char Base62 (new format) or 26-char ULID (legacy format).
    pub fn parse(s: &str) -> Option<Self> {
        if Self::is_valid(s) {
            Some(Self(s.to_string()))
        } else {
            None
        }
    }

    /// Check if a string is a valid box ID format (12-char Base62 or 26-char ULID).
    pub fn is_valid(s: &str) -> bool {
        (s.len() == Self::FULL_LENGTH || s.len() == Self::LEGACY_LENGTH)
            && s.bytes().all(|b| b.is_ascii_alphanumeric())
    }

    /// Get the full box ID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Get the short form (first 8 characters) for display.
    pub fn short(&self) -> &str {
        &self.0[..Self::SHORT_LENGTH]
    }

    /// Check if this ID starts with the given prefix.
    pub fn starts_with(&self, prefix: &str) -> bool {
        self.0.starts_with(prefix)
    }
}

impl fmt::Display for BoxID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for BoxID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "BoxID({})", self.short())
    }
}

impl AsRef<str> for BoxID {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::borrow::Borrow<str> for BoxID {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl ToSql for BoxID {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(ToSqlOutput::Borrowed(ValueRef::Text(self.0.as_bytes())))
    }
}

// ============================================================================
// BOX ID MINT
// ============================================================================

/// Generates unique 12-character Base62 box IDs.
///
/// Uses cryptographically random bytes mapped to the Base62 alphabet.
/// Each character encodes ~5.95 bits, yielding ~71 bits of entropy total.
pub struct BoxIDMint;

impl BoxIDMint {
    /// Mint a new unique box ID.
    pub fn mint() -> BoxID {
        BoxID(mint_base62::<{ BoxID::FULL_LENGTH }>())
    }
}

// ============================================================================
// BASE DISK ID
// ============================================================================

/// Base disk identifier.
///
/// Base disks use 8-character Base62 strings (~48 bits entropy).
///
/// # Example
///
/// ```
/// use boxlite::runtime::id::{BaseDiskID, BaseDiskIDMint};
///
/// let id = BaseDiskIDMint::mint();
/// assert_eq!(id.as_str().len(), 8);
/// assert_eq!(id.short().len(), 8);
/// assert!(BaseDiskID::is_valid(id.as_str()));
/// ```
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BaseDiskID(String);

impl BaseDiskID {
    /// Length of base disk IDs (8-char Base62).
    pub const FULL_LENGTH: usize = 8;

    /// Length of short base disk ID for display (8 chars).
    pub const SHORT_LENGTH: usize = 8;

    /// Parse a BaseDiskID from an existing string.
    ///
    /// Accepts only strict 8-character Base62 IDs.
    pub fn parse(s: &str) -> Option<Self> {
        if Self::is_valid(s) {
            Some(Self(s.to_string()))
        } else {
            None
        }
    }

    /// Check if a string is a valid base disk ID format (8-char Base62).
    pub fn is_valid(s: &str) -> bool {
        s.len() == Self::FULL_LENGTH && s.bytes().all(|b| b.is_ascii_alphanumeric())
    }

    /// Get the full base disk ID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Get the short form for display (same as full ID for base disks).
    pub fn short(&self) -> &str {
        &self.0[..Self::SHORT_LENGTH]
    }

    /// Check if this ID starts with the given prefix.
    pub fn starts_with(&self, prefix: &str) -> bool {
        self.0.starts_with(prefix)
    }
}

impl fmt::Display for BaseDiskID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl fmt::Debug for BaseDiskID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "BaseDiskID({})", self.short())
    }
}

impl AsRef<str> for BaseDiskID {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::borrow::Borrow<str> for BaseDiskID {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl ToSql for BaseDiskID {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(ToSqlOutput::Borrowed(ValueRef::Text(self.0.as_bytes())))
    }
}

// ============================================================================
// BASE DISK ID MINT
// ============================================================================

/// Generates unique 8-character Base62 base disk IDs.
///
/// Uses cryptographically random bytes mapped to the Base62 alphabet.
/// Each character encodes ~5.95 bits, yielding ~48 bits of entropy total.
pub struct BaseDiskIDMint;

impl BaseDiskIDMint {
    /// Mint a new unique base disk ID.
    pub fn mint() -> BaseDiskID {
        BaseDiskID(mint_base62::<{ BaseDiskID::FULL_LENGTH }>())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use std::collections::HashSet;

    #[test]
    fn test_mint_length() {
        let id = BoxIDMint::mint();
        assert_eq!(id.as_str().len(), BoxID::FULL_LENGTH);
    }

    #[test]
    fn test_mint_uniqueness() {
        let ids: HashSet<String> = (0..1000)
            .map(|_| BoxIDMint::mint().as_str().to_string())
            .collect();
        assert_eq!(ids.len(), 1000, "all 1000 minted IDs should be unique");
    }

    #[test]
    fn test_mint_alphabet() {
        for _ in 0..100 {
            let id = BoxIDMint::mint();
            for ch in id.as_str().chars() {
                assert!(ch.is_ascii_alphanumeric(), "unexpected char: {ch}");
            }
        }
    }

    #[test]
    fn test_mint_produces_valid_id() {
        let id = BoxIDMint::mint();
        assert_eq!(id.as_str().len(), BoxID::FULL_LENGTH);
        assert!(BoxID::is_valid(id.as_str()));
    }

    #[test]
    fn test_parse_valid() {
        assert!(BoxID::parse("aB3cD4eF5gH6").is_some());
        assert!(BoxID::parse("000000000000").is_some());
        assert!(BoxID::parse("zzzzzzzzzzzz").is_some());
    }

    #[test]
    fn test_parse_legacy_ulid() {
        assert!(BoxID::parse("01HJK4TNRPQSXYZ8WM6NCVT9R1").is_some());
        assert!(BoxID::parse("01234567890123456789012345").is_some());
    }

    #[test]
    fn test_parse_invalid() {
        assert!(BoxID::parse("abc").is_none(), "too short");
        assert!(BoxID::parse("aB3cD4eF5gH6X").is_none(), "13 chars");
        assert!(BoxID::parse("aB3cD4eF5g-!").is_none(), "non-alphanumeric");
        assert!(
            BoxID::parse("0123456789012345678901234").is_none(),
            "25 chars"
        );
    }

    #[test]
    fn test_short() {
        let id = BoxID::parse("aB3cD4eF5gH6").unwrap();
        assert_eq!(id.short(), "aB3cD4eF");
        assert_eq!(id.short().len(), BoxID::SHORT_LENGTH);
    }

    #[test]
    fn test_display() {
        let id = BoxID::parse("aB3cD4eF5gH6").unwrap();
        assert_eq!(format!("{id}"), "aB3cD4eF5gH6");
    }

    #[test]
    fn test_debug() {
        let id = BoxID::parse("aB3cD4eF5gH6").unwrap();
        let debug = format!("{id:?}");
        assert_eq!(debug, "BoxID(aB3cD4eF)");
    }

    #[test]
    fn test_starts_with() {
        let id = BoxID::parse("aB3cD4eF5gH6").unwrap();
        assert!(id.starts_with("aB3"));
        assert!(!id.starts_with("xyz"));
    }

    #[test]
    fn test_base_disk_mint_length() {
        let id = BaseDiskIDMint::mint();
        assert_eq!(id.as_str().len(), BaseDiskID::FULL_LENGTH);
    }

    #[test]
    fn test_base_disk_mint_uniqueness() {
        let ids: HashSet<String> = (0..1000)
            .map(|_| BaseDiskIDMint::mint().as_str().to_string())
            .collect();
        assert_eq!(ids.len(), 1000, "all 1000 minted IDs should be unique");
    }

    #[test]
    fn test_base_disk_mint_alphabet() {
        for _ in 0..100 {
            let id = BaseDiskIDMint::mint();
            for ch in id.as_str().chars() {
                assert!(ch.is_ascii_alphanumeric(), "unexpected char: {ch}");
            }
        }
    }

    #[test]
    fn test_base_disk_mint_produces_valid_id() {
        let id = BaseDiskIDMint::mint();
        assert_eq!(id.as_str().len(), BaseDiskID::FULL_LENGTH);
        assert!(BaseDiskID::is_valid(id.as_str()));
    }

    #[test]
    fn test_base_disk_parse_valid() {
        assert!(BaseDiskID::parse("aB3cD4eF").is_some());
        assert!(BaseDiskID::parse("00000000").is_some());
        assert!(BaseDiskID::parse("zzzzzzzz").is_some());
    }

    #[test]
    fn test_base_disk_parse_invalid() {
        assert!(BaseDiskID::parse("abc").is_none(), "too short");
        assert!(BaseDiskID::parse("aB3cD4eF5").is_none(), "9 chars");
        assert!(BaseDiskID::parse("aB3cD4-_").is_none(), "non-alphanumeric");
    }

    #[test]
    fn test_base_disk_short() {
        let id = BaseDiskID::parse("aB3cD4eF").unwrap();
        assert_eq!(id.short(), "aB3cD4eF");
        assert_eq!(id.short().len(), BaseDiskID::SHORT_LENGTH);
    }

    #[test]
    fn test_base_disk_display() {
        let id = BaseDiskID::parse("aB3cD4eF").unwrap();
        assert_eq!(format!("{id}"), "aB3cD4eF");
    }

    #[test]
    fn test_base_disk_debug() {
        let id = BaseDiskID::parse("aB3cD4eF").unwrap();
        let debug = format!("{id:?}");
        assert_eq!(debug, "BaseDiskID(aB3cD4eF)");
    }

    #[test]
    fn test_base_disk_starts_with() {
        let id = BaseDiskID::parse("aB3cD4eF").unwrap();
        assert!(id.starts_with("aB3"));
        assert!(!id.starts_with("xyz"));
    }

    // ========================================================================
    // Property-based tests
    // ========================================================================

    proptest! {
        #[test]
        fn prop_mint_always_valid(_seed in any::<u64>()) {
            let id = BoxIDMint::mint();
            prop_assert!(BoxID::is_valid(id.as_str()));
            prop_assert_eq!(id.as_str().len(), BoxID::FULL_LENGTH);
        }

        #[test]
        fn prop_parse_roundtrip_12(s in "[0-9A-Za-z]{12}") {
            let id = BoxID::parse(&s).unwrap();
            prop_assert_eq!(id.as_str(), s.as_str());
        }

        #[test]
        fn prop_parse_roundtrip_26(s in "[0-9A-Za-z]{26}") {
            let id = BoxID::parse(&s).unwrap();
            prop_assert_eq!(id.as_str(), s.as_str());
        }

        #[test]
        fn prop_parse_rejects_wrong_length(s in "[0-9A-Za-z]{1,50}") {
            prop_assume!(s.len() != BoxID::FULL_LENGTH && s.len() != BoxID::LEGACY_LENGTH);
            prop_assert!(BoxID::parse(&s).is_none());
        }

        #[test]
        fn prop_parse_rejects_non_alphanumeric(s in ".{12}") {
            prop_assume!(s.bytes().any(|b| !b.is_ascii_alphanumeric()));
            prop_assert!(BoxID::parse(&s).is_none());
        }

        #[test]
        fn prop_short_is_prefix_of_full(s in "[0-9A-Za-z]{12}") {
            let id = BoxID::parse(&s).unwrap();
            prop_assert!(id.as_str().starts_with(id.short()));
            prop_assert_eq!(id.short().len(), BoxID::SHORT_LENGTH);
        }

        #[test]
        fn prop_display_matches_as_str(s in "[0-9A-Za-z]{12}") {
            let id = BoxID::parse(&s).unwrap();
            prop_assert_eq!(format!("{id}"), id.as_str());
        }

        #[test]
        fn prop_serde_roundtrip(s in "[0-9A-Za-z]{12}") {
            let id = BoxID::parse(&s).unwrap();
            let json = serde_json::to_string(&id).unwrap();
            let back: BoxID = serde_json::from_str(&json).unwrap();
            prop_assert_eq!(id, back);
        }

        #[test]
        fn prop_base_disk_mint_always_valid(_seed in any::<u64>()) {
            let id = BaseDiskIDMint::mint();
            prop_assert!(BaseDiskID::is_valid(id.as_str()));
            prop_assert_eq!(id.as_str().len(), BaseDiskID::FULL_LENGTH);
        }

        #[test]
        fn prop_base_disk_parse_roundtrip(s in "[0-9A-Za-z]{8}") {
            let id = BaseDiskID::parse(&s).unwrap();
            prop_assert_eq!(id.as_str(), s.as_str());
        }

        #[test]
        fn prop_base_disk_parse_rejects_wrong_length(s in "[0-9A-Za-z]{1,50}") {
            prop_assume!(s.len() != BaseDiskID::FULL_LENGTH);
            prop_assert!(BaseDiskID::parse(&s).is_none());
        }

        #[test]
        fn prop_base_disk_parse_rejects_non_alphanumeric(s in ".{8}") {
            prop_assume!(s.bytes().any(|b| !b.is_ascii_alphanumeric()));
            prop_assert!(BaseDiskID::parse(&s).is_none());
        }

        #[test]
        fn prop_base_disk_display_matches_as_str(s in "[0-9A-Za-z]{8}") {
            let id = BaseDiskID::parse(&s).unwrap();
            prop_assert_eq!(format!("{id}"), id.as_str());
        }

        #[test]
        fn prop_base_disk_serde_roundtrip(s in "[0-9A-Za-z]{8}") {
            let id = BaseDiskID::parse(&s).unwrap();
            let json = serde_json::to_string(&id).unwrap();
            let back: BaseDiskID = serde_json::from_str(&json).unwrap();
            prop_assert_eq!(id, back);
        }
    }
}