boxlite 0.10.1

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
//! Container service interface.

use boxlite_shared::{
    BindMount, BoxliteError, BoxliteResult, CaCert,
    ContainerAdvancedOptions as ProtoContainerAdvancedOptions,
    ContainerCapabilities as ProtoContainerCapabilities, ContainerClient,
    ContainerConfig as ProtoContainerConfig, ContainerDevice, ContainerInitErrorKind,
    ContainerInitRequest, DiskRootfs, LinuxOptions, MergedRootfs, MountOptions, OverlayRootfs,
    RootfsInit, container_init_response,
};
use tonic::transport::Channel;

use crate::images::ContainerImageConfig;
use crate::runtime::advanced_options::{
    ContainerCapabilities, ResolvedContainerSecurityConfig, ResolvedLinuxSecurity,
    ResolvedMountSecurity,
};
use crate::volumes::ContainerMount;

/// Container rootfs initialization strategy.
/// Guest constructs paths from container_id using its own layout knowledge.
#[derive(Debug, Clone)]
pub enum ContainerRootfsInitConfig {
    /// Single merged rootfs - guest constructs path from container_id
    #[allow(dead_code)] // Reserved for future merged rootfs mode
    Merged,
    /// Overlayfs from multiple layers - guest constructs paths from container_id and layer_names
    #[allow(dead_code)] // Reserved for future overlayfs mode
    Overlay {
        /// Layer directory names (e.g., "sha256-abc123")
        layer_names: Vec<String>,
        /// Whether to copy layers to disk before overlayfs (default: true)
        copy_layers: bool,
    },
    /// Disk-based rootfs - block device mounted directly as container rootfs
    DiskImage {
        /// Block device path (e.g., "/dev/vda")
        device: String,
        /// Whether to format the device before mounting
        need_format: bool,
        /// Whether to resize filesystem after mounting to fill disk
        need_resize: bool,
    },
}

impl ContainerRootfsInitConfig {
    pub(crate) fn into_proto(self) -> RootfsInit {
        match self {
            ContainerRootfsInitConfig::Merged => RootfsInit {
                strategy: Some(boxlite_shared::rootfs_init::Strategy::Merged(
                    MergedRootfs {},
                )),
            },
            ContainerRootfsInitConfig::Overlay {
                layer_names,
                copy_layers,
            } => RootfsInit {
                strategy: Some(boxlite_shared::rootfs_init::Strategy::Overlay(
                    OverlayRootfs {
                        layer_names,
                        copy_layers,
                    },
                )),
            },
            ContainerRootfsInitConfig::DiskImage {
                device,
                need_format,
                need_resize,
            } => RootfsInit {
                strategy: Some(boxlite_shared::rootfs_init::Strategy::Disk(DiskRootfs {
                    device,
                    need_format,
                    need_resize,
                })),
            },
        }
    }
}

/// Everything needed to create one container in the guest.
///
/// Keeping this as a request object makes the host-to-guest boundary explicit
/// and prevents each new container option from widening [`ContainerInterface::init`].
pub struct ContainerInitConfig {
    pub container_id: String,
    pub image: ContainerImageConfig,
    pub rootfs: ContainerRootfsInitConfig,
    pub mounts: Vec<ContainerMount>,
    pub ca_certs: Vec<String>,
    pub tty: bool,
    /// Guest device nodes to reproduce inside the OCI workload.
    pub devices: Vec<ContainerDevice>,
    pub advanced: ContainerAdvancedConfig,
}

#[derive(Debug, Clone, Default)]
pub struct ContainerAdvancedConfig {
    pub capabilities: ContainerCapabilities,
    pub(crate) linux: ResolvedLinuxSecurity,
    pub(crate) mount: ResolvedMountSecurity,
}

impl From<ResolvedContainerSecurityConfig> for ContainerAdvancedConfig {
    fn from(value: ResolvedContainerSecurityConfig) -> Self {
        Self {
            capabilities: value.capabilities,
            linux: value.linux,
            mount: value.mount,
        }
    }
}

/// Container service interface.
pub struct ContainerInterface {
    client: ContainerClient<Channel>,
}

impl ContainerInterface {
    /// Create from a channel.
    pub fn new(channel: Channel) -> Self {
        Self {
            client: ContainerClient::new(channel),
        }
    }

    /// Create the container — rootfs, image config, mounts. Does **not** run
    /// init; call [`Self::start`] for that. Creation and start are separate so
    /// the host can attach to the main command in between. Returns the
    /// container id on success.
    pub async fn init(&mut self, config: ContainerInitConfig) -> BoxliteResult<String> {
        let ContainerInitConfig {
            container_id,
            image,
            rootfs,
            mounts,
            ca_certs,
            tty,
            devices,
            advanced,
        } = config;

        let proto_config = ProtoContainerConfig {
            entrypoint: image.final_cmd(),
            env: image.env.clone(),
            workdir: image.working_dir.clone(),
            user: image.user.clone(),
            // Not an image property: `run -t` decides it, and init is the
            // process it applies to (OCI `process.terminal`).
            tty,
            advanced: Some(ProtoContainerAdvancedOptions {
                capabilities: Some(ProtoContainerCapabilities {
                    add: advanced.capabilities.add,
                    drop: advanced.capabilities.drop,
                }),
                linux: Some(LinuxOptions {
                    readonly_paths: advanced.linux.readonly_paths,
                }),
                mount: Some(MountOptions {
                    // The only guest-side mount host policy ever overrides
                    // today (see `advanced_options::mount_options`).
                    source: "/sys".to_string(),
                    destination: "/sys".to_string(),
                    options: advanced.mount.options,
                }),
            }),
        };

        // Convert ContainerMount to proto BindMount
        // Uses convention-based paths - guest will construct full path from volume_name
        let proto_mounts: Vec<BindMount> = mounts
            .into_iter()
            .map(|m| BindMount {
                volume_name: m.volume_name,
                destination: m.destination,
                read_only: m.read_only,
                owner_uid: m.owner_uid,
                owner_gid: m.owner_gid,
                subpath: m.subpath.unwrap_or_default(),
            })
            .collect();

        tracing::debug!(container_id = %container_id, "Sending ContainerInit request");
        tracing::trace!(
            container_id = %container_id,
            entrypoint = ?image.entrypoint,
            cmd = ?image.cmd,
            user = %image.user,
            workdir = %image.working_dir,
            env_count = image.env.len(),
            advanced = ?proto_config.advanced,
            rootfs = ?rootfs,
            mounts_count = proto_mounts.len(),
            device_count = devices.len(),
            "Container configuration"
        );

        let request = ContainerInitRequest {
            container_id: container_id.clone(),
            container_config: Some(proto_config),
            rootfs: Some(rootfs.into_proto()),
            mounts: proto_mounts,
            ca_certs: ca_certs.into_iter().map(|pem| CaCert { pem }).collect(),
            // Init's session id = container_id. The host declares it here so
            // `LiteBox::attach()` can address the main command with the same id
            // it sent, instead of both sides separately hard-coding it.
            execution_id: container_id.clone(),
            devices,
        };

        let response = self
            .client
            .init(request)
            .await
            .map_err(map_container_init_status)?
            .into_inner();

        match response.result {
            Some(container_init_response::Result::Success(success)) => {
                tracing::debug!(container_id = %success.container_id, "Container initialized");
                Ok(success.container_id)
            }
            Some(container_init_response::Result::Error(err)) => {
                tracing::error!(container_id = %container_id, "Container init failed: {}", err.reason);
                let reason = format!("Container init failed: {}", err.reason);
                match ContainerInitErrorKind::try_from(err.kind) {
                    Ok(ContainerInitErrorKind::Unsupported) => {
                        Err(BoxliteError::Unsupported(reason))
                    }
                    _ => Err(BoxliteError::Internal(reason)),
                }
            }
            None => Err(BoxliteError::Internal(
                "ContainerInit response missing result".to_string(),
            )),
        }
    }

    /// Run the init process of a created container.
    ///
    /// The second half of docker's create → attach → start: the caller has
    /// attached to the main command's session, so nothing it prints and no code
    /// it exits with can be missed, however fast it finishes.
    pub async fn start(&mut self, container_id: &str) -> BoxliteResult<()> {
        use boxlite_shared::{ContainerStartRequest, container_start_response};

        let response = match self
            .client
            .start(ContainerStartRequest {
                container_id: container_id.to_string(),
            })
            .await
        {
            Ok(response) => response.into_inner(),
            // A guest agent that predates #988 has no `Container.Start`; tonic
            // answers the unknown method with `Unimplemented`. On that agent the
            // fused `Container.Init` — still called on every boot — already
            // started the container, so `Start` is a redundant no-op here.
            // Treat it as started rather than surfacing a cryptic gRPC error;
            // the code must be read before `?` flattens it into `Rpc(String)`.
            // (Recreate the box to regain attach-before-start semantics.)
            Err(status) if status.code() == tonic::Code::Unimplemented => {
                tracing::warn!(
                    container_id = %container_id,
                    "guest agent predates Container.Start (pre-#988); its Init already \
                     started the container — treating as started"
                );
                return Ok(());
            }
            Err(status) => return Err(status.into()),
        };

        match response.result {
            Some(container_start_response::Result::Success(_)) => {
                tracing::debug!(container_id = %container_id, "Container started");
                Ok(())
            }
            Some(container_start_response::Result::Error(err)) => {
                tracing::error!(container_id = %container_id, "Container start failed: {}", err.reason);
                Err(BoxliteError::Internal(format!(
                    "Container start failed: {}",
                    err.reason
                )))
            }
            None => Err(BoxliteError::Internal(
                "ContainerStart response missing result".to_string(),
            )),
        }
    }
}

fn map_container_init_status(status: tonic::Status) -> BoxliteError {
    if status.code() == tonic::Code::InvalidArgument {
        return BoxliteError::InvalidArgument(status.message().to_owned());
    }
    status.into()
}

#[cfg(test)]
mod tests {
    use super::*;
    use boxlite_shared::{
        Container as ContainerService, ContainerInitRequest, ContainerInitResponse,
        ContainerInitSuccess, ContainerServer, ContainerStartRequest, ContainerStartResponse,
        ContainerStartSuccess, container_init_response, container_start_response,
    };
    use std::sync::{Arc, Mutex};
    use tonic::transport::{Endpoint, Server};
    use tonic::{Request, Response, Status};

    #[test]
    fn container_init_preserves_invalid_argument_status() {
        let error = map_container_init_status(Status::invalid_argument(
            "unknown Linux capability 'CAP_FUTURE'",
        ));

        assert!(matches!(error, BoxliteError::InvalidArgument(_)));
        assert_eq!(error.http().0, 400);
    }

    /// How the stub guest answers `Container.Start`.
    #[derive(Clone, Copy)]
    enum StartReply {
        /// Emulates a pre-#988 agent that lacks the method: tonic answers an
        /// unknown method with `Unimplemented` (empty message).
        Unimplemented,
        /// A genuine server-side failure that must NOT be swallowed.
        RealError,
        /// A current agent that starts the container.
        Success,
    }

    struct StubGuest {
        start_reply: StartReply,
        /// Last `Container.Init` request the stub saw, for wire assertions.
        seen_init: Arc<Mutex<Option<ContainerInitRequest>>>,
    }

    #[tonic::async_trait]
    impl ContainerService for StubGuest {
        async fn init(
            &self,
            request: Request<ContainerInitRequest>,
        ) -> Result<Response<ContainerInitResponse>, Status> {
            let request = request.into_inner();
            let container_id = request.container_id.clone();
            *self.seen_init.lock().unwrap() = Some(request);
            Ok(Response::new(ContainerInitResponse {
                result: Some(container_init_response::Result::Success(
                    ContainerInitSuccess { container_id },
                )),
            }))
        }

        async fn start(
            &self,
            request: Request<ContainerStartRequest>,
        ) -> Result<Response<ContainerStartResponse>, Status> {
            let container_id = request.into_inner().container_id;
            match self.start_reply {
                StartReply::Unimplemented => Err(Status::unimplemented("")),
                StartReply::RealError => Err(Status::internal("guest blew up")),
                StartReply::Success => Ok(Response::new(ContainerStartResponse {
                    result: Some(container_start_response::Result::Success(
                        ContainerStartSuccess { container_id },
                    )),
                })),
            }
        }
    }

    /// Serve `StubGuest` on an ephemeral loopback port and return a
    /// `ContainerInterface` wired to it.
    async fn interface_for(start_reply: StartReply) -> ContainerInterface {
        interface_recording(start_reply, Arc::new(Mutex::new(None))).await
    }

    async fn interface_recording(
        start_reply: StartReply,
        seen_init: Arc<Mutex<Option<ContainerInitRequest>>>,
    ) -> ContainerInterface {
        // Bind with std to learn a free port, then hand the address to tonic.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);

        tokio::spawn(async move {
            Server::builder()
                .add_service(ContainerServer::new(StubGuest {
                    start_reply,
                    seen_init,
                }))
                .serve(addr)
                .await
                .unwrap();
        });

        let endpoint = Endpoint::from_shared(format!("http://{addr}")).unwrap();
        let mut attempts = 0;
        let channel = loop {
            match endpoint.connect().await {
                Ok(channel) => break channel,
                Err(e) => {
                    attempts += 1;
                    assert!(
                        attempts < 100,
                        "stub guest never accepted a connection: {e}"
                    );
                    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
                }
            }
        };
        ContainerInterface::new(channel)
    }

    /// #988 regression: a guest agent that predates `Container.Start` answers
    /// with gRPC `Unimplemented`. Its fused `Container.Init` already started the
    /// container, so the host must treat the missing method as "already started"
    /// rather than surfacing `code=16`. Without the degrade this returns
    /// `BoxliteError::Rpc` and the restarted box fails to come up.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn container_start_tolerates_unimplemented_from_legacy_guest() {
        let mut iface = interface_for(StartReply::Unimplemented).await;
        let result = iface.start("box-legacy").await;
        assert!(
            result.is_ok(),
            "legacy guest (Start Unimplemented) must be tolerated, got {result:?}"
        );
    }

    /// The degrade must be narrow: a real server-side error on `Start` still
    /// surfaces as an error, never swallowed as "started".
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn container_start_propagates_real_error() {
        let mut iface = interface_for(StartReply::RealError).await;
        let result = iface.start("box-broken").await;
        assert!(
            result.is_err(),
            "a real Start error must not be swallowed: {result:?}"
        );
    }

    /// Normal path against a current guest is unaffected.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn container_start_ok_on_success() {
        let mut iface = interface_for(StartReply::Success).await;
        assert!(iface.start("box-ok").await.is_ok());
    }

    /// Devices are container-scoped, so they must reach the guest on the
    /// request itself rather than inside the process config — and init's
    /// session id must equal the container id, the rule `LiteBox::attach()`
    /// relies on. Asserted on what actually crossed the wire.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn container_init_sends_devices_and_session_id() {
        let seen = Arc::new(Mutex::new(None));
        let mut iface = interface_recording(StartReply::Success, Arc::clone(&seen)).await;

        iface
            .init(ContainerInitConfig {
                container_id: "container-1".to_string(),
                image: crate::images::ContainerImageConfig::default(),
                rootfs: ContainerRootfsInitConfig::Merged,
                mounts: Vec::new(),
                ca_certs: Vec::new(),
                tty: true,
                devices: vec![ContainerDevice {
                    source: "/dev/kvm".to_string(),
                    destination: "/dev/kvm".to_string(),
                    file_mode: Some(0o666),
                }],
                advanced: ContainerAdvancedConfig {
                    capabilities: crate::runtime::advanced_options::ContainerCapabilities {
                        add: vec!["ALL".into()],
                        ..Default::default()
                    },
                    linux: ResolvedLinuxSecurity {
                        readonly_paths: Vec::new(),
                    },
                    mount: ResolvedMountSecurity {
                        options: vec![
                            "rbind".to_string(),
                            "nosuid".to_string(),
                            "noexec".to_string(),
                            "nodev".to_string(),
                        ],
                    },
                },
            })
            .await
            .unwrap();

        let request = seen.lock().unwrap().take().expect("guest saw Init");
        assert_eq!(request.devices.len(), 1);
        assert_eq!(request.devices[0].destination, "/dev/kvm");
        assert_eq!(request.devices[0].file_mode, Some(0o666));
        assert_eq!(request.container_id, "container-1");
        assert_eq!(request.execution_id, "container-1");
        let container_config = request.container_config.expect("process config");
        // Non-default, so it proves the field is threaded rather than defaulted.
        assert!(container_config.tty);
        let advanced = container_config.advanced.expect("advanced options");
        // Non-default resolved values, so they prove the fields are threaded
        // verbatim rather than defaulted or recomputed on the way to the wire.
        // capabilities is flat on this message (not nested under a process
        // submessage the way linux/mount are) — see ContainerAdvancedOptions
        // in service.proto for why.
        assert_eq!(
            advanced.capabilities.expect("capabilities").add,
            vec!["ALL".to_string()]
        );
        assert!(
            advanced
                .linux
                .expect("linux options")
                .readonly_paths
                .is_empty()
        );
        let mount = advanced.mount.expect("mount options");
        assert_eq!(mount.source, "/sys");
        assert_eq!(mount.destination, "/sys");
        assert!(!mount.options.contains(&"rro".to_string()));
    }
}