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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! 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,
}

/// 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.
///
/// `Debug` is implemented manually (see below) because the derived form would
/// print the raw `ca_key_pem` — a PKCS8 CA private key — which must never
/// land in a log file.
#[derive(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,

    /// Unix socket path for gvproxy's control API (ServicesMux: dynamic port
    /// forwarding / DNS / DHCP leases / stats). Empty means it is not exposed.
    #[serde(default)]
    pub control_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,

    /// 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>,

    /// Per-direction bandwidth cap for the guest link. Absent means unlimited.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rate_limit: Option<GvproxyRateLimit>,
}

/// Token buckets handed to the Go bridge, one per direction. Field names match
/// `RateLimitConfig` in gvproxy-bridge/shaper.go; the two must stay in sync.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GvproxyRateLimit {
    /// Internet to guest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rx: Option<GvproxyTokenBucket>,
    /// Guest to internet.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tx: Option<GvproxyTokenBucket>,
}

/// Firecracker's bucket shape: a capacity in bytes and the time to refill it.
/// Sustained rate is `size * 1000 / refill_time_ms` bytes per second.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GvproxyTokenBucket {
    pub size: u64,
    pub refill_time_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub one_time_burst: Option<u64>,
}

/// Refill period for a derived bucket. Fixed at 100ms: short enough to keep the
/// burst small, long enough that the shaper is not waking on every frame.
const RATE_LIMIT_REFILL_MS: u64 = 100;

impl From<crate::runtime::advanced_options::NetworkRateLimit> for GvproxyRateLimit {
    fn from(limit: crate::runtime::advanced_options::NetworkRateLimit) -> Self {
        Self {
            rx: bucket_from_kbps(limit.rx_kbps),
            tx: bucket_from_kbps(limit.tx_kbps),
        }
    }
}

/// Kilobits per second to a token bucket. `None` and `0` both mean unlimited,
/// so this is the one place the user-facing unit is converted.
///
/// `size` is not floored here even though the bridge floors bucket *capacity* at
/// one maximum frame. The bridge derives the sustained rate from this exact
/// (size, refill_time_ms) pair and keeps the capacity floor in a separate field,
/// so raising `size` to that floor would not enlarge the burst — it would raise
/// the rate itself, silently lifting every cap below ~5.2 Mbit/s.
fn bucket_from_kbps(kbps: Option<u64>) -> Option<GvproxyTokenBucket> {
    let kbps = kbps.filter(|k| *k > 0)?;
    // kbit/s -> byte/s is * 1000 / 8, i.e. * 125.
    let bytes_per_sec = kbps.saturating_mul(125);
    Some(GvproxyTokenBucket {
        size: bytes_per_sec / (1000 / RATE_LIMIT_REFILL_MS),
        refill_time_ms: RATE_LIMIT_REFILL_MS,
        one_time_burst: None,
    })
}

/// 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 GvproxyConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Treat `ca_key_pem` (PKCS8 private key) and `ca_cert_pem` as
        // sensitive: render only their presence. `secrets` already redacts
        // via `GvproxySecretConfig::Debug`.
        f.debug_struct("GvproxyConfig")
            .field("socket_path", &self.socket_path)
            .field("control_socket_path", &self.control_socket_path)
            .field("subnet", &self.subnet)
            .field("gateway_ip", &self.gateway_ip)
            .field("gateway_mac", &self.gateway_mac)
            .field("guest_ip", &self.guest_ip)
            .field("host_ip", &self.host_ip)
            .field("guest_mac", &self.guest_mac)
            .field("mtu", &self.mtu)
            .field("dns_zones", &self.dns_zones)
            .field("dns_search_domains", &self.dns_search_domains)
            .field("debug", &self.debug)
            .field("capture_file", &self.capture_file)
            .field("allow_net", &self.allow_net)
            .field("secrets", &self.secrets)
            .field(
                "ca_cert_pem",
                &self.ca_cert_pem.as_ref().map(|_| "[REDACTED]"),
            )
            .field(
                "ca_key_pem",
                &self.ca_key_pem.as_ref().map(|_| "[REDACTED]"),
            )
            .field("rate_limit", &self.rate_limit)
            .finish()
    }
}

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,
        control_socket_path: PathBuf::new(),
        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,
        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,
        rate_limit: 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.
    ///
    /// Uses default values for all other network settings.
    ///
    /// # Arguments
    ///
    /// * `socket_path` - Caller-provided Unix socket path (must be unique per box)
    pub fn new(socket_path: PathBuf) -> Self {
        let mut config = 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
    }

    /// Set gvproxy's control socket path (`gvproxy-ctl.sock`). When set, gvproxy
    /// binds its ServicesMux there so the boxlite core can drive runtime control.
    pub fn with_control_socket_path(mut self, path: PathBuf) -> Self {
        self.control_socket_path = path;
        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"))
    ///     .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 per-direction rate limit. An unlimited value is left off the
    /// wire entirely rather than serialized as an empty object.
    pub fn with_rate_limit(
        mut self,
        limit: crate::runtime::advanced_options::NetworkRateLimit,
    ) -> Self {
        self.rate_limit = if limit.is_unlimited() {
            None
        } else {
            Some(limit.into())
        };
        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());
        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_builder_pattern() {
        let config = GvproxyConfig::new(test_socket_path())
            .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());
        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.dns_zones, deserialized.dns_zones);
    }

    #[test]
    fn test_capture_file_builder() {
        let config =
            GvproxyConfig::new(test_socket_path()).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());
        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());
        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());

        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()).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()).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());
        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"));
        let config_b = GvproxyConfig::new(PathBuf::from("/boxes/box-b/sockets/net.sock"));

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

        // CRITICAL: Different socket paths must produce 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()).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())
            .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());
        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('.'))
        );
    }

    #[test]
    fn kbps_converts_to_a_bucket_at_the_configured_rate() {
        use crate::runtime::advanced_options::NetworkRateLimit;

        // 10 Mbit/s = 1_250_000 B/s; one 100ms refill period is 125_000 bytes.
        let limit: GvproxyRateLimit = NetworkRateLimit {
            tx_kbps: Some(10_000),
            rx_kbps: None,
        }
        .into();

        let tx = limit.tx.expect("tx bucket");
        assert_eq!(tx.refill_time_ms, 100);
        assert_eq!(tx.size, 125_000);
        // size * 1000 / refill_time_ms is the rate the bridge derives.
        assert_eq!(tx.size * 1000 / tx.refill_time_ms, 1_250_000);
        assert!(limit.rx.is_none(), "an unset direction stays unlimited");
    }

    #[test]
    fn maximum_rate_limit_maps_to_bridge_bucket_limit() {
        use crate::runtime::advanced_options::{AdvancedBoxOptions, NetworkRateLimit};
        use crate::runtime::options::BoxOptions;

        // Independent wire bound enforced by TokenBucketConfig.validate in shaper.go.
        const BRIDGE_MAX_BUCKET_BYTES: u64 = (1_u64 << 62) / 1000;

        let mut advanced = AdvancedBoxOptions::default();
        advanced.network_rate_limit = NetworkRateLimit {
            tx_kbps: Some(NetworkRateLimit::MAX_KBPS),
            rx_kbps: Some(NetworkRateLimit::MAX_KBPS),
        };
        let opts = BoxOptions {
            advanced,
            ..Default::default()
        };
        opts.sanitize_common().unwrap();
        let limit: GvproxyRateLimit = opts.advanced.network_rate_limit.into();

        for bucket in [limit.tx.unwrap(), limit.rx.unwrap()] {
            assert_eq!(bucket.size, BRIDGE_MAX_BUCKET_BYTES);
            assert_eq!(bucket.refill_time_ms, RATE_LIMIT_REFILL_MS);
        }
    }

    /// The bridge reads the sustained rate back out of (size, refill_time_ms), so
    /// a slow cap must serialize its true 100ms window even when that is far
    /// below one maximum frame. Flooring it here would raise the rate instead of
    /// the burst and lift every cap under ~5.2 Mbit/s to that floor.
    #[test]
    fn slow_rates_keep_their_configured_rate() {
        use crate::runtime::advanced_options::NetworkRateLimit;

        let limit: GvproxyRateLimit = NetworkRateLimit {
            tx_kbps: Some(64), // 8000 B/s; a 100ms window is only 800 bytes
            rx_kbps: None,
        }
        .into();

        let tx = limit.tx.expect("tx bucket");
        assert_eq!(tx.size, 800);
        assert_eq!(
            tx.size * 1000 / tx.refill_time_ms,
            8000,
            "rate must survive"
        );
    }

    #[test]
    fn zero_and_none_both_mean_unlimited() {
        use crate::runtime::advanced_options::NetworkRateLimit;

        for limit in [
            NetworkRateLimit::default(),
            NetworkRateLimit {
                tx_kbps: Some(0),
                rx_kbps: Some(0),
            },
        ] {
            assert!(limit.is_unlimited());
            let config = GvproxyConfig::new(test_socket_path()).with_rate_limit(limit);
            assert!(
                config.rate_limit.is_none(),
                "an unlimited cap must not reach the wire at all"
            );
        }
    }

    /// The Go side reads these keys by name (gvproxy-bridge/shaper.go). A rename
    /// on either side silently disables shaping, so pin the shape.
    #[test]
    fn rate_limit_serializes_with_the_keys_the_bridge_reads() {
        use crate::runtime::advanced_options::NetworkRateLimit;

        let config = GvproxyConfig::new(test_socket_path()).with_rate_limit(NetworkRateLimit {
            tx_kbps: Some(10_000),
            rx_kbps: Some(20_000),
        });
        let json: serde_json::Value = serde_json::to_value(&config).unwrap();

        let limit = &json["rate_limit"];
        assert_eq!(limit["tx"]["size"], 125_000);
        assert_eq!(limit["tx"]["refill_time_ms"], 100);
        assert_eq!(limit["rx"]["size"], 250_000);
        assert!(
            limit["tx"].get("one_time_burst").is_none(),
            "an unset burst must be omitted, not sent as null"
        );
    }

    #[test]
    fn default_config_omits_rate_limit_from_the_wire() {
        let json: serde_json::Value =
            serde_json::to_value(GvproxyConfig::new(test_socket_path())).unwrap();
        assert!(json.get("rate_limit").is_none());
    }
}