boxlite 0.9.4

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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! Runtime ID generation and validation.
//!
//! - Box IDs are *opaque server-issued identifiers*. Locally minted IDs use
//!   12-character Base62 (~71 bits of entropy) generated by [`BoxIDMint`],
//!   but [`BoxID::parse`] accepts any non-empty, URL/path-safe string up to
//!   [`BoxID::MAX_LENGTH`] characters — see the doc comment on [`BoxID`] for
//!   why we don't allow-list specific formats.
//! - Base disk IDs are 8-character Base62 strings (~48 bits of entropy)
//!   generated by [`BaseDiskIDMint`]. These are local-only and stay strict.

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 — an *opaque, server-issued* string.
///
/// BoxLite does not allow-list specific identifier formats. Local minting
/// uses 12-character Base62 (see [`BoxIDMint`]), but a remote REST server
/// is free to issue any format it wants — ULID, UUID, prefixed strings
/// (`sb_abc123`), namespaced strings (`box-2026-tenant-42`), etc. The SDK
/// stores whatever the server returns and passes it back verbatim. This
/// matches how comparable sandbox / container SDKs (E2B, Modal, Docker,
/// k8s, Stripe, AWS) treat resource identifiers.
///
/// The only client-side checks are anti-corruption guards:
/// - non-empty
/// - length ≤ [`BoxID::MAX_LENGTH`] (anti-DoS / anti-allocation)
/// - characters limited to ASCII alphanumeric, `-`, and `_` (URL- and
///   path-safe so the ID can be embedded in REST paths and on-disk
///   directory names without encoding surprises)
///
/// # Example
///
/// ```
/// use boxlite::runtime::id::{BoxID, BoxIDMint};
///
/// let id = BoxIDMint::mint();
/// assert_eq!(id.as_str().len(), 12);
/// assert!(BoxID::parse("01HJK4TNRPQSXYZ8WM6NCVT9R5").is_some()); // ULID
/// assert!(BoxID::parse("d406c59d-eb09-4bc3-9b3a-62455c7e8f32").is_some()); // UUID
/// assert!(BoxID::parse("sb_custom_1").is_some()); // server-prefix style
/// ```
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BoxID(String);

impl BoxID {
    /// Maximum accepted length for any box id, including server-issued
    /// formats. 128 is generous — covers a UUID with a tenant prefix
    /// several times over — while still rejecting pathological input.
    pub const MAX_LENGTH: usize = 128;

    /// Length of short box ID for display (8 chars). Real IDs may be
    /// shorter; [`BoxID::short`] is length-aware.
    pub const SHORT_LENGTH: usize = 8;

    /// Parse a BoxID from an existing string.
    ///
    /// Accepts any opaque server-issued identifier that satisfies
    /// [`BoxID::is_valid`]. Returns `None` for empty input, input longer
    /// than [`BoxID::MAX_LENGTH`], or input containing characters outside
    /// the URL/path-safe set.
    pub fn parse(s: &str) -> Option<Self> {
        if Self::is_valid(s) {
            Some(Self(s.to_string()))
        } else {
            None
        }
    }

    /// Check if a string is acceptable as a box id. See the [`BoxID`]
    /// type-level doc for the rationale; this is intentionally permissive
    /// — the server is the authority on identifier format.
    pub fn is_valid(s: &str) -> bool {
        let len = s.len();
        if len == 0 || len > Self::MAX_LENGTH {
            return false;
        }
        s.bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
    }

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

    /// Get the short form (up to 8 leading characters) for display.
    /// Truncates on `SHORT_LENGTH` boundary — safe for any id length,
    /// including ones the server might issue shorter than 8 chars.
    pub fn short(&self) -> &str {
        let n = self.0.len().min(Self::SHORT_LENGTH);
        &self.0[..n]
    }

    /// 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.
///
/// Local minting policy is independent of [`BoxID`] validation: the
/// validator is permissive (any opaque server-issued id works), but the
/// mint always emits 12-char Base62 for boxes started locally.
pub struct BoxIDMint;

impl BoxIDMint {
    /// Length of locally minted box IDs.
    pub const MINT_LENGTH: usize = 12;

    /// Mint a new unique box ID.
    pub fn mint() -> BoxID {
        BoxID(mint_base62::<{ Self::MINT_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(), BoxIDMint::MINT_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(), BoxIDMint::MINT_LENGTH);
        assert!(BoxID::is_valid(id.as_str()));
    }

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

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

    #[test]
    fn test_parse_accepts_uuid() {
        assert!(BoxID::parse("d406c59d-eb09-4bc3-9b3a-62455c7e8f32").is_some());
        assert!(BoxID::parse("00000000-0000-0000-0000-000000000000").is_some());
    }

    #[test]
    fn test_parse_accepts_server_prefix_styles() {
        // Stripe / E2B / AWS-style prefixed identifiers.
        assert!(BoxID::parse("sb_abc123XYZ").is_some());
        assert!(BoxID::parse("box-2026-tenant-42").is_some());
        assert!(BoxID::parse("i-0123456789abcdef").is_some());
        // Mixed underscore + hyphen + alphanumeric.
        assert!(BoxID::parse("a_b-c_1-2").is_some());
    }

    #[test]
    fn test_parse_accepts_boundary_lengths() {
        assert!(BoxID::parse("a").is_some(), "single char");
        let max = "a".repeat(BoxID::MAX_LENGTH);
        assert!(
            BoxID::parse(&max).is_some(),
            "MAX_LENGTH chars must be accepted"
        );
    }

    #[test]
    fn test_parse_rejects_empty_and_oversize() {
        assert!(BoxID::parse("").is_none(), "empty");
        let too_long = "a".repeat(BoxID::MAX_LENGTH + 1);
        assert!(
            BoxID::parse(&too_long).is_none(),
            "MAX_LENGTH+1 must be rejected"
        );
    }

    #[test]
    fn test_parse_rejects_unsafe_characters() {
        // Path-traversal / filesystem hazards.
        assert!(BoxID::parse("a/b").is_none(), "slash");
        assert!(BoxID::parse("a\\b").is_none(), "backslash");
        assert!(BoxID::parse("..").is_none(), "dot-dot");
        assert!(BoxID::parse("a.b").is_none(), "dot");
        // Whitespace.
        assert!(BoxID::parse(" abc").is_none(), "leading space");
        assert!(BoxID::parse("abc\n").is_none(), "trailing newline");
        // URL-unsafe punctuation.
        assert!(BoxID::parse("a:b").is_none(), "colon");
        assert!(BoxID::parse("a@b").is_none(), "at");
        assert!(BoxID::parse("a?b").is_none(), "question");
        assert!(BoxID::parse("a%b").is_none(), "percent");
    }

    #[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_short_truncates_long_id_safely() {
        // Server-issued UUIDs are 36 chars; short() must take the first 8.
        let id = BoxID::parse("d406c59d-eb09-4bc3-9b3a-62455c7e8f32").unwrap();
        assert_eq!(id.short(), "d406c59d");
        assert_eq!(id.short().len(), BoxID::SHORT_LENGTH);
    }

    #[test]
    fn test_short_returns_full_for_short_ids() {
        // If a server ever issues an id shorter than SHORT_LENGTH, short()
        // must not panic — it returns the whole id.
        let id = BoxID::parse("abc").unwrap();
        assert_eq!(id.short(), "abc");
        assert!(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(), BoxIDMint::MINT_LENGTH);
        }

        // Round-trip for any URL-safe id within the length bound.
        #[test]
        fn prop_parse_roundtrip_url_safe(s in "[0-9A-Za-z_-]{1,128}") {
            let id = BoxID::parse(&s).unwrap();
            prop_assert_eq!(id.as_str(), s.as_str());
        }

        // Anything containing a byte outside the URL-safe set must be
        // rejected, regardless of length within bounds.
        #[test]
        fn prop_parse_rejects_unsafe_bytes(s in ".{1,128}") {
            let safe = |b: u8| b.is_ascii_alphanumeric() || b == b'-' || b == b'_';
            prop_assume!(s.bytes().any(|b| !safe(b)));
            prop_assert!(BoxID::parse(&s).is_none());
        }

        // Empty and over-MAX_LENGTH must always be rejected.
        #[test]
        fn prop_parse_rejects_oversize(s in "[0-9A-Za-z_-]{129,200}") {
            prop_assert!(BoxID::parse(&s).is_none());
        }

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

        #[test]
        fn prop_display_matches_as_str(s in "[0-9A-Za-z_-]{1,128}") {
            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_-]{1,128}") {
            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);
        }
    }
}