microsandbox-network 0.5.2

Networking types and smoltcp engine for the microsandbox project.
Documentation
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
//! Fluent builder API for [`NetworkConfig`].
//!
//! Used by `SandboxBuilder::network(|n| n.port(8080, 80).policy(...))`.

use std::net::IpAddr;
use std::path::PathBuf;

use ipnetwork::{Ipv4Network, Ipv6Network};

use crate::config::{DnsConfig, InterfaceOverrides, NetworkConfig, PortProtocol, PublishedPort};
use crate::dns::Nameserver;
use crate::policy::{BuildError, NetworkPolicy};
use crate::secrets::config::{HostPattern, SecretEntry, SecretInjection, ViolationAction};
use crate::tls::TlsConfig;

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Fluent builder for [`NetworkConfig`].
#[derive(Clone)]
pub struct NetworkBuilder {
    config: NetworkConfig,
    errors: Vec<BuildError>,
}

/// Fluent builder for [`DnsConfig`].
pub struct DnsBuilder {
    config: DnsConfig,
}

/// Fluent builder for [`TlsConfig`].
pub struct TlsBuilder {
    config: TlsConfig,
}

/// Fluent builder for a single [`SecretEntry`].
///
/// ```ignore
/// SecretBuilder::new()
///     .env("OPENAI_API_KEY")
///     .value(api_key)
///     .allow_host("api.openai.com")
///     .build()
/// ```
pub struct SecretBuilder {
    env_var: Option<String>,
    value: Option<String>,
    placeholder: Option<String>,
    allowed_hosts: Vec<HostPattern>,
    injection: SecretInjection,
    on_violation: Option<ViolationAction>,
    require_tls_identity: bool,
}

/// Fluent builder for a [`ViolationAction`].
#[derive(Default)]
pub struct ViolationActionBuilder {
    action: ViolationAction,
}

//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------

impl NetworkBuilder {
    /// Start building a network configuration with defaults.
    pub fn new() -> Self {
        Self {
            config: NetworkConfig::default(),
            errors: Vec::new(),
        }
    }

    /// Start building from an existing network configuration.
    pub fn from_config(config: NetworkConfig) -> Self {
        Self {
            config,
            errors: Vec::new(),
        }
    }

    /// Enable or disable networking.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    /// Publish a TCP port: `host_port` on the host maps to `guest_port` in the guest.
    pub fn port(self, host_port: u16, guest_port: u16) -> Self {
        self.port_bind(
            IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
            host_port,
            guest_port,
        )
    }

    /// Publish a UDP port.
    pub fn port_udp(self, host_port: u16, guest_port: u16) -> Self {
        self.port_udp_bind(
            IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
            host_port,
            guest_port,
        )
    }

    /// Publish a TCP port on a specific host bind address.
    pub fn port_bind(self, host_bind: IpAddr, host_port: u16, guest_port: u16) -> Self {
        self.add_port(host_bind, host_port, guest_port, PortProtocol::Tcp)
    }

    /// Publish a UDP port on a specific host bind address.
    pub fn port_udp_bind(self, host_bind: IpAddr, host_port: u16, guest_port: u16) -> Self {
        self.add_port(host_bind, host_port, guest_port, PortProtocol::Udp)
    }

    fn add_port(
        mut self,
        host_bind: IpAddr,
        host_port: u16,
        guest_port: u16,
        protocol: PortProtocol,
    ) -> Self {
        self.config.ports.push(PublishedPort {
            host_port,
            guest_port,
            protocol,
            host_bind,
        });
        self
    }

    /// Set the network policy.
    pub fn policy(mut self, policy: NetworkPolicy) -> Self {
        self.config.policy = policy;
        self
    }

    /// Configure DNS interception via a closure.
    ///
    /// ```ignore
    /// .dns(|d| d
    ///     .nameservers(["1.1.1.1".parse::<Nameserver>()?])
    ///     .rebind_protection(false)
    /// )
    /// ```
    pub fn dns(mut self, f: impl FnOnce(DnsBuilder) -> DnsBuilder) -> Self {
        self.config.dns = f(DnsBuilder::new()).build();
        self
    }

    /// Configure TLS interception via a closure.
    pub fn tls(mut self, f: impl FnOnce(TlsBuilder) -> TlsBuilder) -> Self {
        self.config.tls = f(TlsBuilder::new()).build();
        self
    }

    /// Add a secret via a closure builder.
    ///
    /// ```ignore
    /// .secret(|s| s
    ///     .env("OPENAI_API_KEY")
    ///     .value(api_key)
    ///     .allow_host("api.openai.com")
    /// )
    /// ```
    pub fn secret(mut self, f: impl FnOnce(SecretBuilder) -> SecretBuilder) -> Self {
        self.config
            .secrets
            .secrets
            .push(f(SecretBuilder::new()).build());
        self
    }

    /// Shorthand: add a secret with env var, value, placeholder, and allowed host.
    pub fn secret_env(
        mut self,
        env_var: impl Into<String>,
        value: impl Into<String>,
        placeholder: impl Into<String>,
        allowed_host: impl Into<String>,
    ) -> Self {
        self.config.secrets.secrets.push(SecretEntry {
            env_var: env_var.into(),
            value: value.into(),
            placeholder: placeholder.into(),
            allowed_hosts: vec![HostPattern::Exact(allowed_host.into())],
            injection: SecretInjection::default(),
            on_violation: None,
            require_tls_identity: true,
        });
        self
    }

    /// Set the violation action for secrets.
    pub fn on_secret_violation(
        mut self,
        f: impl FnOnce(ViolationActionBuilder) -> ViolationActionBuilder,
    ) -> Self {
        self.config.secrets.on_violation = f(ViolationActionBuilder::default()).build();
        self
    }

    /// Set the maximum number of concurrent connections.
    pub fn max_connections(mut self, max: usize) -> Self {
        self.config.max_connections = Some(max);
        self
    }

    /// Set guest interface overrides.
    pub fn interface(mut self, overrides: InterfaceOverrides) -> Self {
        self.config.interface = overrides;
        self
    }

    /// Set the IPv4 pool used to derive per-sandbox `/30` guest subnets.
    ///
    /// The default is `172.16.0.0/12`. Pools must be at least `/30`.
    pub fn ipv4_pool(mut self, pool: Ipv4Network) -> Self {
        if pool.prefix() > 30 {
            self.errors.push(BuildError::InvalidIpv4Pool {
                raw: pool.to_string(),
            });
        } else {
            self.config.interface.ipv4_pool = Some(pool);
        }
        self
    }

    /// Set the IPv6 pool used to derive per-sandbox `/64` guest prefixes.
    ///
    /// The default is `fd42:6d73:62::/48`. Pools must be at least `/64`.
    pub fn ipv6_pool(mut self, pool: Ipv6Network) -> Self {
        if pool.prefix() > 64 {
            self.errors.push(BuildError::InvalidIpv6Pool {
                raw: pool.to_string(),
            });
        } else {
            self.config.interface.ipv6_pool = Some(pool);
        }
        self
    }

    /// Whether to ship the host's trusted root CAs into the guest at
    /// boot. Default: false. Opt in when running behind a corporate
    /// TLS-inspecting proxy (Cloudflare Warp Zero Trust, Zscaler,
    /// Netskope, ...) whose gateway CA is trusted on the host but
    /// unknown to the guest's stock Mozilla bundle.
    pub fn trust_host_cas(mut self, enabled: bool) -> Self {
        self.config.trust_host_cas = enabled;
        self
    }

    /// Consume the builder and return the configuration.
    ///
    /// Surfaces the first [`BuildError`] accumulated by any nested
    /// builder (currently [`DnsBuilder`]). Errors stored on the
    /// network builder itself flow through here too.
    pub fn build(mut self) -> Result<NetworkConfig, BuildError> {
        if let Some(err) = self.errors.drain(..).next() {
            return Err(err);
        }
        Ok(self.config)
    }
}

impl DnsBuilder {
    /// Start building DNS configuration with defaults.
    pub fn new() -> Self {
        Self {
            config: DnsConfig::default(),
        }
    }

    /// Enable or disable DNS rebinding protection. Default: true.
    pub fn rebind_protection(mut self, enabled: bool) -> Self {
        self.config.rebind_protection = enabled;
        self
    }

    /// Set the upstream nameservers to forward queries to. When one or
    /// more are set, the interceptor uses these instead of the
    /// nameservers in the host's `/etc/resolv.conf`. Replaces any
    /// previously-set nameservers. Each element is any type convertible
    /// into [`Nameserver`] (`SocketAddr`, `IpAddr`, or a parsed
    /// string via `"dns.google:53".parse::<Nameserver>()?`).
    pub fn nameservers<I>(mut self, nameservers: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<Nameserver>,
    {
        self.config.nameservers = nameservers.into_iter().map(Into::into).collect();
        self
    }

    /// Set the per-DNS-query timeout in milliseconds. Default: 5000.
    pub fn query_timeout_ms(mut self, ms: u64) -> Self {
        self.config.query_timeout_ms = ms;
        self
    }

    /// Consume the builder and return the configuration.
    pub fn build(self) -> DnsConfig {
        self.config
    }
}

impl Default for DnsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TlsBuilder {
    /// Start building TLS configuration.
    pub fn new() -> Self {
        Self {
            config: TlsConfig {
                enabled: true,
                ..TlsConfig::default()
            },
        }
    }

    /// Add a domain to the bypass list (no MITM). Supports `*.suffix` wildcards.
    pub fn bypass(mut self, pattern: impl Into<String>) -> Self {
        self.config.bypass.push(pattern.into());
        self
    }

    /// Enable or disable upstream server certificate verification.
    pub fn verify_upstream(mut self, verify: bool) -> Self {
        self.config.verify_upstream = verify;
        self
    }

    /// Set the ports to intercept.
    pub fn intercepted_ports(mut self, ports: Vec<u16>) -> Self {
        self.config.intercepted_ports = ports;
        self
    }

    /// Enable or disable QUIC blocking on intercepted ports.
    pub fn block_quic(mut self, block: bool) -> Self {
        self.config.block_quic_on_intercept = block;
        self
    }

    /// Add a CA certificate PEM file to trust for upstream server verification.
    ///
    /// Useful when the upstream server uses a self-signed or private CA certificate.
    /// Can be called multiple times to add several CAs.
    pub fn upstream_ca_cert(mut self, path: impl Into<PathBuf>) -> Self {
        self.config.upstream_ca_cert.push(path.into());
        self
    }

    /// Set a custom interception CA certificate PEM file path.
    pub fn intercept_ca_cert(mut self, path: impl Into<PathBuf>) -> Self {
        self.config.intercept_ca.cert_path = Some(path.into());
        self
    }

    /// Set a custom interception CA private key PEM file path.
    pub fn intercept_ca_key(mut self, path: impl Into<PathBuf>) -> Self {
        self.config.intercept_ca.key_path = Some(path.into());
        self
    }

    /// Consume the builder and return the configuration.
    pub fn build(self) -> TlsConfig {
        self.config
    }
}

impl SecretBuilder {
    /// Start building a secret.
    pub fn new() -> Self {
        Self {
            env_var: None,
            value: None,
            placeholder: None,
            allowed_hosts: Vec::new(),
            injection: SecretInjection::default(),
            on_violation: None,
            require_tls_identity: true,
        }
    }

    /// Set the environment variable to expose the placeholder as (required).
    pub fn env(mut self, var: impl Into<String>) -> Self {
        self.env_var = Some(var.into());
        self
    }

    /// Set the secret value (required).
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }

    /// Set a custom placeholder string.
    /// If not set, auto-generated as `$MSB_<env_var>`.
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// Add an allowed host (exact match).
    pub fn allow_host(mut self, host: impl Into<String>) -> Self {
        self.allowed_hosts.push(HostPattern::Exact(host.into()));
        self
    }

    /// Add an allowed host with wildcard pattern (e.g., `*.openai.com`).
    pub fn allow_host_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.allowed_hosts
            .push(HostPattern::Wildcard(pattern.into()));
        self
    }

    /// Allow for any host. **Dangerous**: secret can be exfiltrated to any
    /// destination. Requires explicit acknowledgment.
    pub fn allow_any_host_dangerous(mut self, i_understand_the_risk: bool) -> Self {
        if i_understand_the_risk {
            self.allowed_hosts.push(HostPattern::Any);
        }
        self
    }

    /// Set the violation action for this secret.
    pub fn on_violation(
        mut self,
        f: impl FnOnce(ViolationActionBuilder) -> ViolationActionBuilder,
    ) -> Self {
        self.on_violation = Some(f(ViolationActionBuilder::default()).build());
        self
    }

    /// Require verified TLS identity before substituting (default: true).
    pub fn require_tls_identity(mut self, enabled: bool) -> Self {
        self.require_tls_identity = enabled;
        self
    }

    /// Configure header injection (default: true).
    pub fn inject_headers(mut self, enabled: bool) -> Self {
        self.injection.headers = enabled;
        self
    }

    /// Configure Basic Auth injection (default: true).
    pub fn inject_basic_auth(mut self, enabled: bool) -> Self {
        self.injection.basic_auth = enabled;
        self
    }

    /// Configure query parameter injection (default: false).
    pub fn inject_query(mut self, enabled: bool) -> Self {
        self.injection.query_params = enabled;
        self
    }

    /// Configure body injection (default: false).
    pub fn inject_body(mut self, enabled: bool) -> Self {
        self.injection.body = enabled;
        self
    }

    /// Consume the builder and return a [`SecretEntry`].
    ///
    /// # Panics
    /// Panics if `env` or `value` was not set.
    pub fn build(self) -> SecretEntry {
        let env_var = self.env_var.expect("SecretBuilder: .env() is required");
        let value = self.value.expect("SecretBuilder: .value() is required");
        let placeholder = self
            .placeholder
            .unwrap_or_else(|| format!("$MSB_{env_var}"));

        SecretEntry {
            env_var,
            value,
            placeholder,
            allowed_hosts: self.allowed_hosts,
            injection: self.injection,
            on_violation: self.on_violation,
            require_tls_identity: self.require_tls_identity,
        }
    }
}

impl ViolationActionBuilder {
    /// Start building a violation action.
    pub fn new() -> Self {
        Self::default()
    }

    /// Start building from an existing action.
    pub fn from_action(action: ViolationAction) -> Self {
        action.into()
    }

    /// Block the request silently.
    pub fn block(mut self) -> Self {
        self.action = ViolationAction::Block;
        self
    }

    /// Block the request and emit a warning log.
    pub fn block_and_log(mut self) -> Self {
        self.action = ViolationAction::BlockAndLog;
        self
    }

    /// Block the request and terminate the sandbox.
    pub fn block_and_terminate(mut self) -> Self {
        self.action = ViolationAction::BlockAndTerminate;
        self
    }

    /// Allow a host to receive secret placeholders without substitution.
    pub fn passthrough_host(mut self, host: impl Into<String>) -> Self {
        self.push_passthrough_host(HostPattern::Exact(host.into()));
        self
    }

    /// Allow hosts matching a wildcard pattern to receive secret placeholders without substitution.
    pub fn passthrough_host_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.push_passthrough_host(HostPattern::Wildcard(pattern.into()));
        self
    }

    /// Allow any host to receive secret placeholders without substitution.
    pub fn passthrough_all_hosts(mut self, i_understand_the_risk: bool) -> Self {
        if i_understand_the_risk {
            self.push_passthrough_host(HostPattern::Any);
        }
        self
    }

    /// Helper to accumulate passthrough hosts into the current action.
    fn push_passthrough_host(&mut self, host: HostPattern) {
        match self.action {
            ViolationAction::Passthrough(ref mut hosts) => hosts.push(host),
            _ => self.action = ViolationAction::Passthrough(vec![host]),
        }
    }

    /// Consume the builder and return the action.
    pub fn build(self) -> ViolationAction {
        self.action
    }
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------

impl Default for NetworkBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for TlsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for SecretBuilder {
    fn default() -> Self {
        Self::new()
    }
}
impl From<ViolationAction> for ViolationActionBuilder {
    fn from(action: ViolationAction) -> Self {
        Self { action }
    }
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    /// Network builder happy path returns the config unchanged.
    #[test]
    fn network_builder_happy_path_returns_config() {
        let cfg = NetworkBuilder::new()
            .dns(|d| d.rebind_protection(false))
            .build()
            .unwrap();
        assert!(!cfg.dns.rebind_protection);
    }

    #[test]
    fn port_bind_sets_host_bind() {
        let bind = "0.0.0.0".parse().unwrap();
        let cfg = NetworkBuilder::new()
            .port_bind(bind, 8080, 80)
            .port_udp_bind(bind, 5353, 53)
            .build()
            .unwrap();

        assert_eq!(cfg.ports[0].host_bind, bind);
        assert_eq!(cfg.ports[0].host_port, 8080);
        assert_eq!(cfg.ports[0].guest_port, 80);
        assert_eq!(cfg.ports[0].protocol, PortProtocol::Tcp);
        assert_eq!(cfg.ports[1].host_bind, bind);
        assert_eq!(cfg.ports[1].protocol, PortProtocol::Udp);
    }

    #[test]
    fn network_builder_sets_global_passthrough_action() {
        let cfg = NetworkBuilder::new()
            .on_secret_violation(|v| {
                v.passthrough_host("api.anthropic.com")
                    .passthrough_host_pattern("*.anthropic.com")
            })
            .build()
            .unwrap();

        assert_eq!(
            cfg.secrets.on_violation,
            ViolationAction::Passthrough(vec![
                HostPattern::Exact("api.anthropic.com".into()),
                HostPattern::Wildcard("*.anthropic.com".into()),
            ])
        );
    }

    #[test]
    fn secret_builder_sets_violation_action() {
        let secret = SecretBuilder::new()
            .env("TOKEN")
            .value("secret-value")
            .allow_host("api.github.com")
            .on_violation(|v| {
                v.passthrough_host("api.anthropic.com")
                    .passthrough_host_pattern("*.anthropic.com")
            })
            .build();

        assert_eq!(
            secret.on_violation,
            Some(ViolationAction::Passthrough(vec![
                HostPattern::Exact("api.anthropic.com".into()),
                HostPattern::Wildcard("*.anthropic.com".into()),
            ])),
        );
    }

    #[test]
    fn violation_action_builder_blocking_call_replaces_passthrough_policy() {
        let action = ViolationActionBuilder::default()
            .passthrough_host("google.com")
            .block_and_terminate()
            .passthrough_host("facebook.com")
            .build();

        assert_eq!(
            action,
            ViolationAction::Passthrough(vec![HostPattern::Exact("facebook.com".into())])
        );
    }

    #[test]
    fn violation_action_builder_accumulates_passthrough_hosts() {
        let action = ViolationActionBuilder::default()
            .block()
            .passthrough_host("google.com")
            .passthrough_host("facebook.com")
            .build();

        assert_eq!(
            action,
            ViolationAction::Passthrough(vec![
                HostPattern::Exact("google.com".into()),
                HostPattern::Exact("facebook.com".into()),
            ]),
        );
    }
}