boxlite 0.9.0

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
//! Gvproxy configuration structures

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Local DNS zone configuration
///
/// Defines local DNS records served by the gateway's embedded DNS server.
/// Queries not matching any zone are forwarded to the host's system DNS.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DnsZone {
    /// Zone name (e.g., "myapp.local.", "." for root)
    pub name: String,
    /// Exact A records within this zone.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub records: Vec<DnsRecord>,
    /// Default IP for unmatched queries in this zone
    pub default_ip: String,
}

/// Exact A record within a local DNS zone.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DnsRecord {
    /// Record label within the zone (e.g., "host" in "boxlite.internal.")
    pub name: String,
    /// IPv4 address returned for this record
    pub ip: String,
}

/// Port mapping configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PortMapping {
    /// Host port to bind
    pub host_port: u16,
    /// Guest port to forward to
    pub guest_port: u16,
}

/// Network configuration for gvproxy instance
///
/// This structure encapsulates all configuration needed to create a gvproxy
/// virtual network, replacing the previous approach of hardcoding values in Go.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GvproxyConfig {
    /// Unix socket path for the network tap interface.
    /// Caller-provided to ensure each box gets a unique, collision-free path.
    pub socket_path: PathBuf,

    /// Virtual network subnet (e.g., "192.168.127.0/24")
    pub subnet: String,

    /// Gateway IP address (gvproxy's IP)
    pub gateway_ip: String,

    /// Gateway MAC address
    pub gateway_mac: String,

    /// Guest IP address
    pub guest_ip: String,

    /// Virtual host IP address that routes to host loopback services
    pub host_ip: String,

    /// Guest MAC address
    pub guest_mac: String,

    /// MTU for the virtual network
    pub mtu: u16,

    /// Port mappings: (host_port, guest_port)
    pub port_mappings: Vec<PortMapping>,

    /// Local DNS zones for the gateway's embedded DNS server
    pub dns_zones: Vec<DnsZone>,

    /// DNS search domains
    pub dns_search_domains: Vec<String>,

    /// Enable debug logging in gvproxy
    pub debug: bool,

    /// Optional pcap file path for packet capture (for debugging)
    /// Records all network traffic to a file readable by Wireshark
    /// Set via config or BOXLITE_NET_CAPTURE_FILE environment variable
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_file: Option<String>,

    /// Network allowlist for DNS sinkhole filtering.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allow_net: Vec<String>,

    /// Secrets for MITM proxy injection into outbound HTTP(S) requests.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secrets: Vec<GvproxySecretConfig>,

    /// PEM-encoded MITM CA certificate (generated by Rust, consumed by Go).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ca_cert_pem: Option<String>,

    /// PEM-encoded MITM CA private key (PKCS8 format, consumed by Go).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ca_key_pem: Option<String>,
}

/// Secret configuration for gvproxy MITM proxy.
///
/// JSON field names match the Go `SecretConfig` struct in gvproxy-bridge.
#[derive(Clone, Serialize, Deserialize)]
pub struct GvproxySecretConfig {
    pub name: String,
    pub hosts: Vec<String>,
    pub placeholder: String,
    pub value: String,
}

impl std::fmt::Debug for GvproxySecretConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GvproxySecretConfig")
            .field("name", &self.name)
            .field("hosts", &self.hosts)
            .field("placeholder", &self.placeholder)
            .field("value", &"[REDACTED]")
            .finish()
    }
}

impl From<&crate::runtime::options::Secret> for GvproxySecretConfig {
    fn from(s: &crate::runtime::options::Secret) -> Self {
        Self {
            name: s.name.clone(),
            hosts: s.hosts.clone(),
            placeholder: s.placeholder.clone(),
            value: s.value.clone(),
        }
    }
}

/// Create a config with network defaults for the given socket path.
fn defaults_with_socket_path(socket_path: PathBuf) -> GvproxyConfig {
    use crate::net::constants::*;

    GvproxyConfig {
        socket_path,
        subnet: SUBNET.to_string(),
        gateway_ip: GATEWAY_IP.to_string(),
        gateway_mac: GATEWAY_MAC_STRING.to_string(),
        guest_ip: GUEST_IP.to_string(),
        host_ip: HOST_IP.to_string(),
        guest_mac: GUEST_MAC_STRING.to_string(),
        mtu: DEFAULT_MTU,
        port_mappings: Vec::new(),
        dns_zones: vec![boxlite_internal_dns_zone()],
        dns_search_domains: DNS_SEARCH_DOMAINS.iter().map(|s| s.to_string()).collect(),
        debug: false,
        capture_file: None,
        allow_net: Vec::new(),
        secrets: Vec::new(),
        ca_cert_pem: None,
        ca_key_pem: None,
    }
}

fn boxlite_internal_dns_zone() -> DnsZone {
    use crate::net::constants::{HOST_ALIAS_LABEL, HOST_ALIAS_ZONE, HOST_IP};

    DnsZone {
        name: HOST_ALIAS_ZONE.to_string(),
        records: vec![DnsRecord {
            name: HOST_ALIAS_LABEL.to_string(),
            ip: HOST_IP.to_string(),
        }],
        // Empty default_ip means this zone only serves the exact `host` record.
        default_ip: String::new(),
    }
}

impl GvproxyConfig {
    /// Create a new configuration with the given socket path and port mappings
    ///
    /// Uses default values for all other network settings.
    ///
    /// # Arguments
    ///
    /// * `socket_path` - Caller-provided Unix socket path (must be unique per box)
    /// * `port_mappings` - List of (host_port, guest_port) tuples
    pub fn new(socket_path: PathBuf, port_mappings: Vec<(u16, u16)>) -> Self {
        let mut config = Self {
            port_mappings: port_mappings
                .into_iter()
                .map(|(host_port, guest_port)| PortMapping {
                    host_port,
                    guest_port,
                })
                .collect(),
            ..defaults_with_socket_path(socket_path)
        };

        // Check environment variable for capture file
        if let Ok(capture_file) = std::env::var("BOXLITE_NET_CAPTURE_FILE")
            && !capture_file.is_empty()
        {
            tracing::info!(
                capture_file,
                "Enabling packet capture from BOXLITE_NET_CAPTURE_FILE"
            );
            config.capture_file = Some(capture_file);
        }

        // Enable debug mode when capturing
        if config.capture_file.is_some() {
            config.debug = true;
            tracing::info!("Enabling gvproxy debug mode for packet capture");
        }

        config
    }

    /// Enable debug logging
    pub fn with_debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }

    /// Add custom DNS zones after the built-in BoxLite zones.
    ///
    /// This method appends; repeated calls keep earlier zones in place.
    pub fn with_dns_zones(mut self, dns_zones: Vec<DnsZone>) -> Self {
        self.dns_zones.extend(dns_zones);
        self
    }

    /// Set custom MTU
    pub fn with_mtu(mut self, mtu: u16) -> Self {
        self.mtu = mtu;
        self
    }

    /// Enable packet capture to pcap file
    ///
    /// Records all network traffic to a file that can be analyzed with Wireshark.
    /// This is a debugging feature and should not be enabled in production.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use boxlite::net::gvproxy::GvproxyConfig;
    /// use std::path::PathBuf;
    ///
    /// let config = GvproxyConfig::new(PathBuf::from("/tmp/network.sock"), vec![(8080, 80)])
    ///     .with_capture_file("/tmp/network.pcap".to_string());
    /// ```
    pub fn with_capture_file(mut self, capture_file: String) -> Self {
        self.capture_file = Some(capture_file);
        self
    }

    /// Set network allowlist for DNS sinkhole filtering.
    pub fn with_allow_net(mut self, allow_net: Vec<String>) -> Self {
        self.allow_net = allow_net;
        self
    }

    /// Set secrets for MITM proxy injection.
    pub fn with_secrets(mut self, secrets: Vec<GvproxySecretConfig>) -> Self {
        self.secrets = secrets;
        self
    }

    /// Set the MITM CA certificate and key (generated by Rust, consumed by Go).
    pub fn with_ca(mut self, cert_pem: String, key_pem: String) -> Self {
        self.ca_cert_pem = Some(cert_pem);
        self.ca_key_pem = Some(key_pem);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::net::constants::{HOST_ALIAS_LABEL, HOST_ALIAS_ZONE, HOST_HOSTNAME, HOST_IP};

    fn test_socket_path() -> PathBuf {
        PathBuf::from("/tmp/test-gvproxy.sock")
    }

    #[test]
    fn test_new_config_defaults() {
        let config = GvproxyConfig::new(test_socket_path(), vec![]);
        assert_eq!(config.socket_path, test_socket_path());
        assert_eq!(config.subnet, "192.168.127.0/24");
        assert_eq!(config.gateway_ip, "192.168.127.1");
        assert_eq!(config.guest_ip, "192.168.127.2");
        assert_eq!(config.host_ip, HOST_IP);
        assert_eq!(config.mtu, 1500);
        assert!(!config.debug);
        assert_eq!(config.dns_zones.len(), 1);
        assert_eq!(config.dns_zones[0].name, HOST_ALIAS_ZONE);
        assert_eq!(
            config.dns_zones[0].records,
            vec![DnsRecord {
                name: HOST_ALIAS_LABEL.to_string(),
                ip: HOST_IP.to_string(),
            }]
        );
        assert!(config.dns_zones[0].default_ip.is_empty());
    }

    #[test]
    fn test_new_with_port_mappings() {
        let config = GvproxyConfig::new(test_socket_path(), vec![(8080, 80), (8443, 443)]);
        assert_eq!(config.port_mappings.len(), 2);
        assert_eq!(config.port_mappings[0].host_port, 8080);
        assert_eq!(config.port_mappings[0].guest_port, 80);
    }

    #[test]
    fn test_builder_pattern() {
        let config = GvproxyConfig::new(test_socket_path(), vec![(8080, 80)])
            .with_debug(true)
            .with_mtu(9000);

        assert!(config.debug);
        assert_eq!(config.mtu, 9000);
    }

    #[test]
    fn test_serialization() {
        let config = GvproxyConfig::new(test_socket_path(), vec![(8080, 80)]);
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: GvproxyConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config.subnet, deserialized.subnet);
        assert_eq!(config.socket_path, deserialized.socket_path);
        assert_eq!(config.host_ip, deserialized.host_ip);
        assert_eq!(config.port_mappings.len(), deserialized.port_mappings.len());
        assert_eq!(config.dns_zones, deserialized.dns_zones);
    }

    #[test]
    fn test_capture_file_builder() {
        let config = GvproxyConfig::new(test_socket_path(), vec![(8080, 80)])
            .with_capture_file("/tmp/test.pcap".to_string());

        assert_eq!(config.capture_file, Some("/tmp/test.pcap".to_string()));
    }

    #[test]
    fn test_capture_file_serialization() {
        // Without capture file - should not include field in JSON
        let config = GvproxyConfig::new(test_socket_path(), vec![(8080, 80)]);
        let json = serde_json::to_string(&config).unwrap();
        assert!(!json.contains("capture_file"));

        // With capture file - should include field in JSON
        let config_with_capture = config.with_capture_file("/tmp/test.pcap".to_string());
        let json_with_capture = serde_json::to_string(&config_with_capture).unwrap();
        assert!(json_with_capture.contains("capture_file"));
        assert!(json_with_capture.contains("/tmp/test.pcap"));

        // Deserialize and verify
        let deserialized: GvproxyConfig = serde_json::from_str(&json_with_capture).unwrap();
        assert_eq!(
            deserialized.capture_file,
            Some("/tmp/test.pcap".to_string())
        );
    }

    #[test]
    fn test_new_config_no_capture_by_default() {
        let config = GvproxyConfig::new(test_socket_path(), vec![]);
        assert_eq!(config.capture_file, None);
    }

    #[test]
    fn test_socket_path_survives_json_serialization() {
        // Regression test: socket_path must appear in the JSON sent to Go's gvproxy_create.
        // If this field is missing, Go would fall back to generating /tmp/gvproxy-{id}.sock,
        // which was the root cause of the socket collision bug.

        let socket_path = PathBuf::from("/home/user/.boxlite/boxes/my-box/sockets/net.sock");
        let config = GvproxyConfig::new(socket_path.clone(), vec![(8080, 80)]);

        let json = serde_json::to_string(&config).unwrap();

        // CRITICAL: JSON must contain the socket_path field
        assert!(
            json.contains("socket_path"),
            "JSON must include socket_path field"
        );
        assert!(
            json.contains("/home/user/.boxlite/boxes/my-box/sockets/net.sock"),
            "JSON must contain the actual socket path value"
        );

        // Verify round-trip
        let deserialized: GvproxyConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.socket_path, socket_path);
    }

    // ========================================================================
    // Secret config tests
    // ========================================================================

    fn test_secret() -> crate::runtime::options::Secret {
        crate::runtime::options::Secret {
            name: "openai".to_string(),
            hosts: vec!["api.openai.com".to_string()],
            placeholder: "<BOXLITE_SECRET:openai>".to_string(),
            value: "sk-test-super-secret-key-12345".to_string(),
        }
    }

    #[test]
    fn test_gvproxy_secret_config_from_secret() {
        let secret = test_secret();
        let config = GvproxySecretConfig::from(&secret);
        assert_eq!(config.name, "openai");
        assert_eq!(config.hosts, vec!["api.openai.com"]);
        assert_eq!(config.placeholder, "<BOXLITE_SECRET:openai>");
        assert_eq!(config.value, "sk-test-super-secret-key-12345");
    }

    #[test]
    fn test_gvproxy_config_with_secrets() {
        let secret = test_secret();
        let gvproxy_secret = GvproxySecretConfig::from(&secret);
        let config = GvproxyConfig::new(test_socket_path(), vec![(8080, 80)])
            .with_secrets(vec![gvproxy_secret]);
        assert_eq!(config.secrets.len(), 1);
        assert_eq!(config.secrets[0].name, "openai");
    }

    #[test]
    fn test_gvproxy_config_secrets_serialization() {
        let secret = test_secret();
        let gvproxy_secret = GvproxySecretConfig::from(&secret);
        let config =
            GvproxyConfig::new(test_socket_path(), vec![]).with_secrets(vec![gvproxy_secret]);

        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("\"secrets\""));
        assert!(json.contains("\"name\""));
        assert!(json.contains("\"placeholder\""));

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let secrets = value.get("secrets").unwrap().as_array().unwrap();
        assert_eq!(secrets.len(), 1);
        assert_eq!(secrets[0]["name"], "openai");
        assert_eq!(secrets[0]["placeholder"], "<BOXLITE_SECRET:openai>");
        assert_eq!(secrets[0]["hosts"][0], "api.openai.com");
    }

    #[test]
    fn test_gvproxy_config_no_secrets_default() {
        let config = GvproxyConfig::new(test_socket_path(), vec![]);
        assert!(config.secrets.is_empty());
        let json = serde_json::to_string(&config).unwrap();
        // secrets field is skipped when empty due to skip_serializing_if
        assert!(
            !json.contains("\"secrets\""),
            "empty secrets should be omitted from JSON"
        );
    }

    #[test]
    fn test_gvproxy_secret_config_serde_roundtrip() {
        let secret = test_secret();
        let gvproxy_secret = GvproxySecretConfig::from(&secret);
        let json = serde_json::to_string(&gvproxy_secret).unwrap();
        let deserialized: GvproxySecretConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.name, gvproxy_secret.name);
        assert_eq!(deserialized.hosts, gvproxy_secret.hosts);
        assert_eq!(deserialized.placeholder, gvproxy_secret.placeholder);
        assert_eq!(deserialized.value, gvproxy_secret.value);
    }

    #[test]
    fn test_two_configs_have_different_socket_paths_in_json() {
        // Regression test: two concurrent boxes creating gvproxy configs.
        // OLD CODE: Both would serialize to identical JSON (no socket_path field),
        //           and Go would generate /tmp/gvproxy-1.sock for both → collision.
        // NEW CODE: Each config carries its own unique socket_path.

        let config_a = GvproxyConfig::new(
            PathBuf::from("/boxes/box-a/sockets/net.sock"),
            vec![(8080, 80)],
        );
        let config_b = GvproxyConfig::new(
            PathBuf::from("/boxes/box-b/sockets/net.sock"),
            vec![(8080, 80)],
        );

        let json_a = serde_json::to_string(&config_a).unwrap();
        let json_b = serde_json::to_string(&config_b).unwrap();

        // CRITICAL: Same port mappings but different socket paths → different JSON
        assert_ne!(
            json_a, json_b,
            "Two configs with different socket paths must produce different JSON"
        );
        assert_ne!(config_a.socket_path, config_b.socket_path);
    }

    #[test]
    fn test_with_dns_zones_preserves_builtin_host_alias() {
        let config = GvproxyConfig::new(test_socket_path(), vec![]).with_dns_zones(vec![DnsZone {
            name: "example.internal.".to_string(),
            records: vec![DnsRecord {
                name: "api".to_string(),
                ip: "192.168.127.10".to_string(),
            }],
            default_ip: String::new(),
        }]);

        assert_eq!(config.dns_zones.len(), 2);
        assert_eq!(config.dns_zones[0].name, HOST_ALIAS_ZONE);
        assert_eq!(config.dns_zones[1].name, "example.internal.");
    }

    #[test]
    fn test_with_dns_zones_appends_across_multiple_calls() {
        let config = GvproxyConfig::new(test_socket_path(), vec![])
            .with_dns_zones(vec![DnsZone {
                name: "one.internal.".to_string(),
                records: vec![],
                default_ip: "192.168.127.10".to_string(),
            }])
            .with_dns_zones(vec![DnsZone {
                name: "two.internal.".to_string(),
                records: vec![],
                default_ip: "192.168.127.11".to_string(),
            }]);

        assert_eq!(config.dns_zones.len(), 3);
        assert_eq!(config.dns_zones[0].name, HOST_ALIAS_ZONE);
        assert_eq!(config.dns_zones[1].name, "one.internal.");
        assert_eq!(config.dns_zones[2].name, "two.internal.");
    }

    #[test]
    fn test_serialization_contains_host_alias_record() {
        let config = GvproxyConfig::new(test_socket_path(), vec![]);
        let json = serde_json::to_string(&config).unwrap();

        assert!(json.contains(&format!("\"host_ip\":\"{HOST_IP}\"")));
        assert!(json.contains(&format!("\"name\":\"{HOST_ALIAS_ZONE}\"")));
        assert!(json.contains("\"records\""));
        assert!(json.contains(&format!("\"name\":\"{HOST_ALIAS_LABEL}\"")));
        assert!(json.contains(&format!("\"ip\":\"{HOST_IP}\"")));
    }

    #[test]
    fn test_host_hostname_matches_built_in_zone() {
        let zone = boxlite_internal_dns_zone();
        let record = zone.records.first().expect("built-in host alias record");

        assert_eq!(zone.name, HOST_ALIAS_ZONE);
        assert_eq!(record.name, HOST_ALIAS_LABEL);
        assert_eq!(
            HOST_HOSTNAME,
            format!("{}.{}", record.name, zone.name.trim_end_matches('.'))
        );
    }
}