bux 0.9.0

Embedded micro-VM sandbox for running AI agents
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! VM state types and `SQLite` persistence.

use std::path::PathBuf;
use std::time::SystemTime;

use serde::{Deserialize, Serialize};

use crate::disk::DiskFormat;

/// VM lifecycle status.
///
/// ```text
/// Stopped ──► Running ──► Stopping ──► Stopped
///                │                        ▲
///                └────────────────────────┘
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Status {
    /// VM process is running.
    Running,
    /// A graceful shutdown has been requested; waiting for the process to exit.
    Stopping,
    /// VM has been stopped or exited.
    Stopped,
}

impl Status {
    /// Returns `true` if the VM process may still be alive.
    #[must_use]
    pub const fn is_active(self) -> bool {
        matches!(self, Self::Running | Self::Stopping)
    }

    /// Returns `true` if `exec()` can be called.
    #[must_use]
    pub const fn can_exec(self) -> bool {
        matches!(self, Self::Running)
    }

    /// Returns `true` if `stop()` can be called.
    #[must_use]
    pub const fn can_stop(self) -> bool {
        matches!(self, Self::Running)
    }

    /// Returns `true` if `remove()` can be called.
    #[must_use]
    pub const fn can_remove(self) -> bool {
        matches!(self, Self::Stopped)
    }

    /// Returns `true` if transitioning from `self` to `target` is valid.
    ///
    /// ```text
    /// Stopped ──► Running ──► Stopping ──► Stopped
    ///                │                        ▲
    ///                └────────────────────────┘
    /// ```
    #[must_use]
    pub const fn can_transition_to(self, target: Self) -> bool {
        matches!(
            (self, target),
            (Self::Stopped, Self::Running)
                | (Self::Running | Self::Stopping, Self::Stopped)
                | (Self::Running, Self::Stopping)
        )
    }
}

/// A virtio-fs shared directory.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct VirtioFs {
    /// Mount tag visible inside the guest.
    pub tag: String,
    /// Absolute host directory path.
    pub path: String,
    /// Guest mount point; the agent mounts this at PID 1 from `GuestBootConfig.volumes`.
    #[serde(default)]
    pub guest_path: String,
    /// Guest sees this share as read-only.
    #[serde(default)]
    pub read_only: bool,
}

/// A vsock port mapping.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct VsockPort {
    /// Guest-side vsock port number.
    pub port: u32,
    /// Host-side Unix socket path.
    pub path: String,
    /// `true` = guest listens, host connects (agent pattern).
    pub listen: bool,
}

/// Complete VM configuration persisted in `SQLite`.
///
/// Serialized as JSON inside the `SQLite` `config` column. The shim receives
/// a derived [`bux_shim::ShimConfig`], not this type directly.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct VmConfig {
    /// Number of virtual CPUs.
    pub vcpus: u8,
    /// RAM size in MiB.
    pub ram_mib: u32,

    /// Root filesystem directory path (virtiofs-based).
    #[serde(default)]
    pub rootfs: Option<String>,
    /// Root filesystem disk image path (block device-based).
    #[serde(default)]
    pub root_disk: Option<String>,
    /// Disk image format for `root_disk`.
    #[serde(default)]
    pub disk_format: DiskFormat,
    /// Shared base image path for QCOW2 overlay creation.
    ///
    /// When set, create builds a per-VM QCOW2 overlay backed by this image,
    /// then replaces `root_disk` with the overlay path and sets `disk_format`
    /// to [`DiskFormat::Qcow2`]. Consumed during spawn.
    #[serde(default)]
    pub base_disk: Option<String>,

    /// Executable path inside the VM.
    #[serde(default)]
    pub exec_path: Option<String>,
    /// Arguments passed to the executable.
    #[serde(default)]
    pub exec_args: Vec<String>,
    /// Environment variables (`KEY=VALUE`). Managed boot writes only `BUX_GUEST_CONFIG`.
    #[serde(default)]
    pub env: Option<Vec<String>>,

    /// TCP port mappings as concrete `"host:guest"` after resolution.
    #[serde(default)]
    pub ports: Vec<String>,

    /// Resolved published ports (set by Runtime after ephemeral probe).
    #[serde(default)]
    pub published_ports: Vec<crate::ports::PublishedPort>,

    /// virtio-fs shared directories.
    #[serde(default)]
    pub virtiofs: Vec<VirtioFs>,
    /// vsock port mappings (includes internal agent port).
    #[serde(default)]
    pub vsock_ports: Vec<VsockPort>,

    /// Guest network (gvproxy or offline).
    #[serde(default)]
    pub network: crate::options::NetworkSpec,

    /// When true, restart requires secret re-supply (`StartOptions.secrets`)
    /// if the Runtime process does not still hold memory-only secrets.
    ///
    /// Secret **values** are never stored in `SQLite`.
    #[serde(default)]
    pub secrets_required: bool,

    /// Workload env defaults for Phase A exec (`KEY=VALUE`). Not VM boot env.
    #[serde(default)]
    pub workload_env: Vec<String>,

    /// Workload working directory for Phase A exec. Not VM boot cwd.
    #[serde(default)]
    pub workload_workdir: Option<String>,

    /// Workload user for Phase A (`uid[:gid]` or `name[:group]`).
    ///
    /// Applied at exec time; not libkrun boot credentials.
    #[serde(default)]
    pub workload_user: Option<String>,

    /// Optional command the CLI may exec after the agent is ready.
    #[serde(default)]
    pub workload_cmd: Vec<String>,

    /// Requested security policy (persisted; applied at each spawn/start).
    #[serde(default)]
    pub security: crate::security::SecurityOptions,

    /// Actual security posture from the last successful spawn.
    #[serde(default)]
    pub security_status: crate::security::SecurityStatus,

    /// Remove VM state automatically when it stops.
    #[serde(default)]
    pub auto_remove: bool,

    /// Stop the VM after this many seconds of inactivity (`None` = never). Default off.
    #[serde(default)]
    pub auto_stop_secs: Option<u64>,

    /// Delete a stopped VM after this many seconds of inactivity (`None` = never). Default off.
    #[serde(default)]
    pub auto_delete_secs: Option<u64>,

    /// Last activity timestamp (exec, start, create). Used by the idle sweeper.
    #[serde(default, with = "crate::state::opt_system_time")]
    pub last_activity_at: Option<SystemTime>,

    /// Last fatal/recoverable error message (e.g. secrets re-supply required).
    #[serde(default)]
    pub last_error: Option<String>,

    /// Detached VM: no watchdog, no parent-death, Runtime Drop does not SIGTERM.
    #[serde(default)]
    pub detach: bool,

    /// Optional agent identity.
    #[serde(default)]
    pub agent_id: Option<String>,

    /// Optional tenant identity.
    #[serde(default)]
    pub tenant_id: Option<String>,
}

impl Default for VmConfig {
    fn default() -> Self {
        Self {
            vcpus: 1,
            ram_mib: 512,
            rootfs: None,
            root_disk: None,
            disk_format: DiskFormat::default(),
            base_disk: None,
            exec_path: None,
            exec_args: Vec::new(),
            env: None,
            ports: Vec::new(),
            published_ports: Vec::new(),
            virtiofs: Vec::new(),
            vsock_ports: Vec::new(),
            network: crate::options::NetworkSpec::default(),
            secrets_required: false,
            workload_env: Vec::new(),
            workload_workdir: None,
            workload_user: None,
            workload_cmd: Vec::new(),
            security: crate::security::SecurityOptions::default(),
            security_status: crate::security::SecurityStatus::default(),
            auto_remove: false,
            auto_stop_secs: None,
            auto_delete_secs: None,
            last_activity_at: None,
            last_error: None,
            detach: false,
            agent_id: None,
            tenant_id: None,
        }
    }
}

/// Serde helpers for `Option<SystemTime>` as optional f64 unix seconds.
pub(crate) mod opt_system_time {
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    /// Serialize optional activity timestamp as unix seconds.
    #[allow(clippy::ref_option, reason = "serde with signature")]
    pub(crate) fn serialize<S>(t: &Option<SystemTime>, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match t {
            Some(st) => {
                let secs = st
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs_f64();
                Some(secs).serialize(s)
            }
            None => None::<f64>.serialize(s),
        }
    }

    /// Deserialize optional activity timestamp from unix seconds.
    pub(crate) fn deserialize<'de, D>(d: D) -> Result<Option<SystemTime>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let v: Option<f64> = Option::deserialize(d)?;
        Ok(v.map(|secs| UNIX_EPOCH + Duration::from_secs_f64(secs.max(0.0))))
    }
}

/// Persisted state of a managed VM.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub(crate) struct VmState {
    /// Short hex identifier.
    pub id: String,
    /// Optional human-friendly name (unique across the runtime).
    pub name: Option<String>,
    /// Host PID of the VM process (matches `libc::pid_t`).
    pub pid: i32,
    /// OCI image reference (if pulled from a registry).
    pub image: Option<String>,
    /// Unix socket path for host↔guest communication.
    pub socket: PathBuf,
    /// Current lifecycle status.
    pub status: Status,
    /// VM configuration snapshot.
    pub config: VmConfig,
    /// Timestamp when the VM was created.
    pub created_at: SystemTime,
}

/// Generates a 12-character hex VM identifier.
#[cfg(unix)]
pub(crate) fn gen_id() -> String {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hasher};
    use std::time::UNIX_EPOCH;

    let mut h = RandomState::new().build_hasher();
    h.write_u64(u64::from(std::process::id()));
    h.write_u128(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos(),
    );
    // {:012x} is minimum width; mask to 48 bits so the hex is always exactly 12.
    format!("{:012x}", h.finish() & 0xffff_ffff_ffff_u64)
}

#[cfg(unix)]
mod db;

#[cfg(unix)]
pub(crate) use db::{SnapshotRow, StateDb};

#[cfg(test)]
#[cfg(unix)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::shadow_unrelated,
    clippy::indexing_slicing,
    reason = "test assertions use unwrap/indexing for clarity"
)]
mod tests {
    use std::time::SystemTime;

    use super::*;

    /// Creates a test `VmState` with the given ID and name.
    fn test_vm(id: &str, name: Option<&str>) -> VmState {
        VmState {
            id: id.to_owned(),
            name: name.map(ToOwned::to_owned),
            pid: 1234,
            image: Some("alpine:latest".to_owned()),
            socket: format!("/tmp/{id}.sock").into(),
            status: Status::Running,
            config: VmConfig {
                vcpus: 2,
                exec_path: Some("/bin/sh".to_owned()),
                ..VmConfig::default()
            },
            created_at: SystemTime::now(),
        }
    }

    /// Opens an in-memory `StateDb` for testing.
    fn open_test_db() -> StateDb {
        StateDb::open(":memory:").expect("open in-memory db")
    }

    #[test]
    fn insert_and_list() {
        let db = open_test_db();
        let vm = test_vm("aaa111bbb222", Some("myvm"));
        db.insert(&vm).unwrap();

        let all = db.list().unwrap();
        assert_eq!(all.len(), 1);
        assert_eq!(all[0].id, "aaa111bbb222");
        assert_eq!(all[0].name.as_deref(), Some("myvm"));
        assert_eq!(all[0].pid, 1234);
        assert_eq!(all[0].status, Status::Running);
    }

    #[test]
    fn get_by_name() {
        let db = open_test_db();
        db.insert(&test_vm("aaa111", Some("alpha"))).unwrap();
        db.insert(&test_vm("bbb222", Some("beta"))).unwrap();

        let found = db.get_by_name("alpha").unwrap().unwrap();
        assert_eq!(found.id, "aaa111");

        assert!(db.get_by_name("nonexistent").unwrap().is_none());
    }

    #[test]
    fn get_by_id_prefix() {
        let db = open_test_db();
        db.insert(&test_vm("abc123def456", None)).unwrap();
        db.insert(&test_vm("xyz789000111", None)).unwrap();

        // Exact match.
        let found = db.get_by_id_prefix("abc123def456").unwrap();
        assert_eq!(found.id, "abc123def456");

        // Unique prefix.
        let found = db.get_by_id_prefix("abc").unwrap();
        assert_eq!(found.id, "abc123def456");

        // No match → NotFound.
        assert!(db.get_by_id_prefix("zzz").is_err());
    }

    #[test]
    fn get_by_id_is_exact_only() {
        let db = open_test_db();
        db.insert(&test_vm("abc123def456", Some("alpha"))).unwrap();
        db.insert(&test_vm("abc999000111", None)).unwrap();

        assert_eq!(db.get_by_id("abc123def456").unwrap().id, "abc123def456");
        let ambiguous_prefix = db.get_by_id("abc").unwrap_err();
        assert!(
            matches!(ambiguous_prefix, crate::Error::NotFound(_)),
            "exact id lookup must not prefix-match, got {ambiguous_prefix:?}"
        );
        assert!(
            !matches!(ambiguous_prefix, crate::Error::Ambiguous(_)),
            "exact id lookup must not be Ambiguous, got {ambiguous_prefix:?}"
        );

        let unique_prefix = db.get_by_id("abc123def").unwrap_err();
        assert!(
            matches!(unique_prefix, crate::Error::NotFound(_)),
            "unique prefix must not match, got {unique_prefix:?}"
        );
        assert_eq!(
            db.get_by_id_prefix("abc123def").unwrap().id,
            "abc123def456",
            "prefix API still resolves a unique prefix"
        );

        let by_name = db.get_by_id("alpha").unwrap_err();
        assert!(
            matches!(by_name, crate::Error::NotFound(_)),
            "exact id lookup must not use vms.name, got {by_name:?}"
        );
    }

    #[test]
    fn ambiguous_prefix() {
        let db = open_test_db();
        db.insert(&test_vm("abc111", None)).unwrap();
        db.insert(&test_vm("abc222", None)).unwrap();

        let err = db.get_by_id_prefix("abc").unwrap_err();
        assert!(
            matches!(err, crate::Error::Ambiguous(_)),
            "expected Ambiguous, got {err:?}"
        );
    }

    #[test]
    fn update_status() {
        let db = open_test_db();
        db.insert(&test_vm("aaa111", None)).unwrap();

        db.update_status("aaa111", Status::Stopped).unwrap();
        let vm = db.get_by_id_prefix("aaa111").unwrap();
        assert_eq!(vm.status, Status::Stopped);
    }

    #[test]
    fn update_pid_status_persists_new_pid() {
        let db = open_test_db();
        db.insert(&test_vm("aaa111", None)).unwrap();

        db.update_pid_status("aaa111", 5678, Status::Running)
            .unwrap();
        let vm = db.get_by_id_prefix("aaa111").unwrap();
        assert_eq!(vm.pid, 5678);
        assert_eq!(vm.status, Status::Running);
    }

    #[test]
    fn update_name() {
        let db = open_test_db();
        db.insert(&test_vm("aaa111", Some("old"))).unwrap();

        db.update_name("aaa111", Some("new")).unwrap();
        assert!(db.get_by_name("old").unwrap().is_none());
        assert!(db.get_by_name("new").unwrap().is_some());
    }

    #[test]
    fn delete() {
        let db = open_test_db();
        db.insert(&test_vm("aaa111", None)).unwrap();
        assert_eq!(db.list().unwrap().len(), 1);

        db.delete("aaa111").unwrap();
        assert_eq!(db.list().unwrap().len(), 0);
    }

    #[test]
    fn duplicate_name_rejected() {
        let db = open_test_db();
        db.insert(&test_vm("aaa111", Some("dup"))).unwrap();

        let result = db.insert(&test_vm("bbb222", Some("dup")));
        assert!(result.is_err(), "duplicate name should be rejected");
    }

    #[test]
    fn pid_stored_as_i32() {
        let db = open_test_db();
        let mut vm = test_vm("aaa111", None);
        vm.pid = -1; // Negative PID should survive round-trip.
        db.insert(&vm).unwrap();

        let loaded = db.get_by_id_prefix("aaa111").unwrap();
        assert_eq!(loaded.pid, -1);
    }

    #[test]
    fn status_transitions() {
        assert!(Status::Stopped.can_transition_to(Status::Running));
        assert!(Status::Running.can_transition_to(Status::Stopping));
        assert!(Status::Running.can_transition_to(Status::Stopped));
        assert!(Status::Stopping.can_transition_to(Status::Stopped));

        assert!(!Status::Stopped.can_transition_to(Status::Stopping));
        assert!(!Status::Stopping.can_transition_to(Status::Running));
        assert!(!Status::Stopping.can_transition_to(Status::Stopping));

        assert!(Status::Running.can_stop());
        assert!(!Status::Stopping.can_stop());
        assert!(!Status::Stopped.can_stop());

        assert!(Status::Running.is_active());
        assert!(Status::Stopping.is_active());
        assert!(!Status::Stopped.is_active());
    }

    #[test]
    fn snapshot_crud() {
        let db = open_test_db();
        db.insert(&test_vm("vm1", Some("myvm"))).unwrap();

        let snap = SnapshotRow {
            id: "snap1".to_owned(),
            vm_id: "vm1".to_owned(),
            name: Some("backup1".to_owned()),
            disk_path: "/tmp/snap1.qcow2".to_owned(),
            disk_bytes: 1024 * 1024,
            created_at: SystemTime::now(),
        };
        db.insert_snapshot(&snap).unwrap();

        let snaps = db.list_snapshots("vm1").unwrap();
        assert_eq!(snaps.len(), 1);
        assert_eq!(snaps[0].id, "snap1");
        assert_eq!(snaps[0].name.as_deref(), Some("backup1"));
        assert_eq!(snaps[0].disk_bytes, 1024 * 1024);

        let loaded = db.get_snapshot("snap1").unwrap();
        assert_eq!(loaded.vm_id, "vm1");

        db.delete_snapshot("snap1").unwrap();
        assert_eq!(db.list_snapshots("vm1").unwrap().len(), 0);
    }

    #[test]
    fn base_disk_ref_counting() {
        let db = open_test_db();

        db.upsert_base_disk("bd1", "sha256:abc", "/tmp/base.raw")
            .unwrap();

        let bd = db.get_base_disk_by_digest("sha256:abc").unwrap().unwrap();
        assert_eq!(bd.ref_count, 0);

        db.incr_base_disk_ref("sha256:abc").unwrap();
        db.incr_base_disk_ref("sha256:abc").unwrap();
        let bd = db.get_base_disk_by_digest("sha256:abc").unwrap().unwrap();
        assert_eq!(bd.ref_count, 2);

        db.decr_base_disk_ref("sha256:abc").unwrap();
        db.decr_base_disk_ref("sha256:abc").unwrap();

        let orphans = db.orphaned_base_disks().unwrap();
        assert_eq!(orphans.len(), 1);
        assert_eq!(orphans[0].digest, "sha256:abc");

        db.delete_base_disk("bd1").unwrap();
        assert!(db.get_base_disk_by_digest("sha256:abc").unwrap().is_none());
    }

    #[test]
    fn vmconfig_json_defaults_identity_fields() {
        let cfg: VmConfig = serde_json::from_str(r#"{"vcpus":1,"ram_mib":512}"#).unwrap();
        assert!(
            cfg.agent_id.is_none(),
            "missing agent_id must deserialize as None"
        );
        assert!(
            cfg.tenant_id.is_none(),
            "missing tenant_id must deserialize as None"
        );
    }

    #[test]
    fn gen_id_is_exactly_12_lowercase_hex() {
        for _ in 0..256 {
            let id = gen_id();
            assert_eq!(
                id.len(),
                12,
                "gen_id must emit exactly 12 hex chars, got {id:?}"
            );
            assert!(
                id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')),
                "gen_id must be lowercase hex, got {id:?}"
            );
        }
    }

    #[test]
    fn format_012x_of_2_pow_48_is_length_13() {
        // {:012x} of 2^48 is 13 chars; dropping the gen_id mask would emit >12.
        assert_eq!(
            format!("{:012x}", 1u64 << 48).len(),
            13,
            "unmasked 2^48 must format wider than 12 so the mask stays required"
        );
    }
}