NetworkPolicy
NetworkPolicy::builder()
Example
Example
NetworkPolicyBuilder to configure rules and per-direction defaults. The first matching rule wins in each direction. build() validates string inputs (.ip, .cidr, .domain, .domain_suffix) and returns a BuildError for invalid input.
Returns
NetworkPolicy::none()
SandboxBuilder::disable_network().
NetworkPolicy::allow_all()
NetworkPolicy::from_profiles()
NetworkProfile values. Duplicate profiles are ignored, the generated rules use canonical Public, Private, Host order, and every non-empty profile set receives exactly one narrow gateway DNS rule. An empty profile set permits no egress and adds no DNS. Ingress defaults to allow, preserving published-port behavior.
Example
Example
Instance methods
These methods consumeself and return a modified policy, so they chain off a profile or a built policy. Each prepends its rules, so a later deny outranks a catch-all allow like allow public under first-match-wins. All return Result<NetworkPolicy, DomainNameError> because the names are parsed eagerly.
policy.allow_domain()
Example
Example
Domain egress rule. Single-name sugar over allow_domains().
policy.deny_domain()
Domain egress rule. Single-name sugar over deny_domains().
policy.allow_domains()
Example
Example
Domain egress rule per name.
Parameters
namesIntoIterator<Item = AsRef<str>>policy.deny_domains()
Example
Example
Domain egress rule per name. Prepending lets the denies outrank catch-all allows.
policy.allow_domain_suffix()
DomainSuffix egress rule. Single-suffix sugar over allow_domain_suffixes().
policy.deny_domain_suffix()
DomainSuffix egress rule. Single-suffix sugar over deny_domain_suffixes().
policy.allow_domain_suffixes()
DomainSuffix egress rule per suffix. Suffixes match the apex domain and every subdomain (label-aligned).
policy.deny_domain_suffixes()
Example
Example
DomainSuffix egress rule per suffix.
NetworkPolicyBuilder
Fluent builder forNetworkPolicy.
policy.default_deny()
default_egress and default_ingress to Deny.
policy.default_allow()
default_egress and default_ingress to Allow.
policy.default_egress()
Parameters
actionActionpolicy.default_ingress()
Parameters
actionActionpolicy.egress()
Example
Example
rule() with direction pre-set to Egress.
policy.ingress()
rule() with direction pre-set to Ingress.
policy.any()
rule() with direction pre-set to Any. Rules committed inside apply in both directions.
policy.rule()
Example
Example
.egress(), .ingress(), or .any() before any rule-adder, otherwise build() returns BuildError::DirectionNotSet.
policy.build()
NetworkPolicy. Lazy-parses every .ip() / .cidr() / .domain() / .domain_suffix() input and validates the direction-set and ICMP-egress-only invariants. It also emits a tracing::warn! for each shadowed rule pair, meaning a rule fully covered by an earlier one in the same direction. The shadow check covers only Ip / Cidr / Group destinations. Builds still succeed when a shadow is detected. Returns the first BuildError encountered.
Returns
RuleBuilder
Builder for one policy-rule batch.rule.egress()
Egress for subsequent rule-adders. Last-write-wins.
rule.ingress()
Ingress for subsequent rule-adders. Last-write-wins.
rule.any()
Any for subsequent rule-adders. Rules committed after this apply in both directions. Last-write-wins.
rule.tcp()
Tcp to the protocols set.
rule.udp()
Udp to the protocols set.
rule.icmpv4()
Icmpv4 to the protocols set. Egress-only: an ICMP protocol on an Ingress or Any rule fails build with BuildError::IngressDoesNotSupportIcmp.
rule.icmpv6()
Icmpv6 to the protocols set. Egress-only; same rule as icmpv4().
rule.port()
Parameters
portu16rule.port_range()
Parameters
lou16hiu16lo > hi records BuildError::InvalidPortRange.rule.ports()
port() once per element.
rule.allow_public()
Public group: every IP not in another named category. A matching deny_public() exists for each allow_* group adder below.
rule.allow_private()
Private group (RFC1918 + ULA + CGN).
rule.allow_loopback()
Loopback group (127.0.0.0/8, ::1): the guest’s own loopback, not the host. To reach a service on the host’s localhost use allow_host() instead. See the loopback-vs-host watch-out.
rule.allow_link_local()
LinkLocal group (169.254.0.0/16, fe80::/10). Excludes the metadata IP 169.254.169.254.
rule.allow_meta()
Metadata group (169.254.169.254). Dangerous on cloud hosts: exposes IAM credentials.
rule.allow_multicast()
Multicast group (224.0.0.0/4, ff00::/8).
rule.allow_host()
Host group: per-sandbox gateway IPs that back host.microsandbox.internal. This is the right shortcut for “let the sandbox reach my host’s localhost”, not allow_loopback().
rule.deny_public()
Public group. Per-group deny_* adders mirror the allow_* set: deny_private(), deny_loopback(), deny_link_local(), deny_meta(), deny_multicast(), and deny_host().
rule.allow_local()
Loopback + LinkLocal + Host. Each uses the closure’s current state. Metadata is intentionally not included; opt in via allow_meta() separately.
rule.deny_local()
Loopback + LinkLocal + Host. Metadata is intentionally not included.
rule.allow_domains()
Example
Example
Domain rule per name, inheriting the closure’s current direction / protocol / port state. Lazy-parse: invalid names surface as BuildError::InvalidDomain from build().
rule.deny_domains()
Domain rule per name.
rule.allow_domain_suffixes()
DomainSuffix rule per suffix.
rule.deny_domain_suffixes()
DomainSuffix rule per suffix.
rule.allow()
Example
Example
Allow. The returned RuleDestinationBuilder requires exactly one destination call to commit; dropping it without one adds no rule.
rule.deny()
Deny.
RuleDestinationBuilder
Builder for a rule destination.destination.ip()
Destination::Cidr of the IP as /32 (v4) or /128 (v6). The string is parsed at build(); invalid values surface as BuildError::InvalidIp.
destination.cidr()
Destination::Cidr. Invalid values surface as BuildError::InvalidCidr.
destination.domain()
Destination::Domain. Matches only when a cached hostname for the remote IP equals this name (after canonicalization).
destination.domain_suffix()
Destination::DomainSuffix. Matches the apex domain itself and any subdomain. A single-label suffix (e.g. com) is rejected at build as BuildError::InvalidDomain.
destination.group()
Destination::Group for callers who already hold a DestinationGroup value.
destination.any()
Destination::Any: matches every remote.
NetworkBuilder
Builder for the sandbox’s network stack, used inSandboxBuilder::network(|n| n...). Every setter returns Self, so calls chain. Errors accumulated by nested builders cascade up: the outermost SandboxBuilder::build() surfaces them as MicrosandboxError::NetworkBuilder(BuildError).
network.policy()
Example
Example
NetworkPolicy.
Parameters
policyNetworkPolicynetwork.port()
127.0.0.1. Equivalent to SandboxBuilder::port().
Parameters
host_portu16guest_portu16network.port_udp()
127.0.0.1.
network.port_bind()
0.0.0.0.
Parameters
host_bindIpAddrhost_portu16guest_portu16network.port_udp_bind()
network.dns()
Example
Example
DnsBuilder.
network.tls()
TlsBuilder.
network.trust_host_cas()
false. Opt in when egress HTTPS inside the sandbox needs to work behind corporate MITM proxies (Cloudflare Warp Zero Trust, Zscaler, Netskope, etc.). Those proxies install a gateway CA on the host that’s unknown to the guest’s stock Mozilla bundle.
network.http()
deny_response(true) to return 403 Forbidden for supported HTTP requests, including HTTPS on intercepted ports. Optionally set deny_message to customize the body; {host} names the blocked hostname. Setting a message alone does not enable responses. Enabling requires a supporting local runtime; cloud rejects it. See What a denied HTTP request sees.
HttpBuilder::build() returns HttpConfig, stored in NetworkConfig.http:
None uses the built-in message; Some(String::new()) sends an empty body.
network.strict()
true. Plain HTTP exposes that authority in Host; HTTPS only exposes it when TLS interception is enabled and not bypassed. Without that visibility, strict mode denies HTTPS that would otherwise be allowed only by a hostname rule.
network.tcp_accept_queue_size()
1024. Accepts 1..=i32::MAX; other values record BuildError::InvalidTcpAcceptQueueSize. Connections arriving while the queue is full never reach the sandbox, so raise this when a burst of parallel connections, such as a reverse proxy fanning out one page load, exceeds it. The host kernel caps the effective depth at net.core.somaxconn on Linux (4,096 by default) or kern.ipc.somaxconn on macOS (128 by default). Runtimes that predate the setting are refused with an upgrade-required error rather than silently ignoring it.
RestoreBuilder, ForkBuilder, and ForkManyBuilder expose the same tcp_accept_queue_size() for the listeners a child publishes.
network.nat64_prefix()
/96 prefix for policy classification. Destinations inside NAT64 prefixes are evaluated against both their IPv6 address and the embedded IPv4 address, so translated private, loopback, link-local, and metadata IPv4 addresses retain their normal policy groups. The well-known 64:ff9b::/96 prefix is configured by default.
Parameters
prefixIpv6Network/96.network.max_udp_connections()
network.max_tcp_connections()
max_connections remains a deprecated alias for this builder method. The last call sets the TCP limit. Either method can be combined with the UDP limit.
RestoreBuilder::max_tcp_connections and RestoreBuilder::max_udp_connections set the destination limits. RestoreBuilder::max_connections remains a deprecated TCP alias; the last TCP setter call wins.
Parameters
maxusizenetwork.rate_limiter()
Example
Example
network.ipv4_pool()
/30 guest subnets. Defaults to 172.16.0.0/12. A pool with a prefix longer than /30 records BuildError::InvalidIpv4Pool.
Parameters
poolIpv4Network/30 or shorter.network.ipv6_pool()
/64 guest prefixes. Defaults to fd42:6d73:62::/48. A pool with a prefix longer than /64 records BuildError::InvalidIpv6Pool.
network.interface()
ipv4_pool() and ipv6_pool(), which validate the prefix. Unset fields fall back to values derived deterministically from the sandbox slot. See InterfaceOverrides.
Parameters
overridesInterfaceOverridesnetwork.enabled()
true. To fully turn networking off, prefer SandboxBuilder::disable_network(), which also sets the policy to NetworkPolicy::none().
network.secret_violation_action()
allow_placeholder_for().
network.secret()
SandboxBuilder::secret(). See SecretBuilder for the full API. A companion secret_env(env_var, value, placeholder, allowed_host) shorthand and secret_entry(SecretEntry) are also available on NetworkBuilder.
Parameters
DnsBuilder
Builder for DNS interception, used inNetworkBuilder::dns(|d| d...). Owns rebind protection, nameserver pinning, and the per-query timeout. Every setter returns Self.
dns.nameservers()
/etc/resolv.conf (or, on macOS, the SystemConfiguration dynamic store). Each element converts into Nameserver: a SocketAddr, an IpAddr, or a parsed string via "dns.google:53".parse::<Nameserver>()?.
Parameters
nameserversIntoIterator<Item = Into<Nameserver>>dns.query_timeout_ms()
5000.
dns.rebind_protection()
true.
TlsBuilder
Builder for TLS interception, used inNetworkBuilder::tls(|t| t...). Creating it enables interception. Every setter returns Self.
tls.bypass()
"*.internal.corp"). Use for domains with certificate pinning. Can be called multiple times.
Parameters
patternimpl Into<String>*.suffix wildcards.tls.intercepted_ports()
[443].
tls.verify_upstream()
true. Set to false only for self-signed servers.
tls.block_quic()
true.
tls.intercept_ca_cert()
intercept_ca_key() to provide a stable CA across sandbox restarts. If unset, a CA is auto-generated and persisted.
tls.intercept_ca_key()
tls.upstream_ca_cert()
tls.upstream_ca_cert_for()
pattern. Pattern syntax matches bypass(): exact hosts and *.suffix wildcards are supported.
tls.verify_upstream_for()
pattern. Pattern syntax matches bypass(): exact hosts and *.suffix wildcards are supported. Setting verify to false is the proxy-side equivalent of curl -k for matching hosts; TLS interception still runs.
NetworkRateLimiterBuilder
Groups local rate limits by traffic direction. Supplied toNetworkBuilder::rate_limiter().
.egress()
.ingress()
RateLimiterBuilder
Builder for one direction’s rate limiter, supplied toNetworkRateLimiterBuilder::egress() or ingress(). A limiter caps bandwidth (bytes) and packet rate (frames) independently; leaving a bucket unset leaves that dimension unlimited. Buckets start full plus their one-time burst and refill continuously. Every setter returns Self.
Validation runs at NetworkBuilder::build(). Each of these surfaces as BuildError: a limiter with neither bucket, a zero bucket size or refill interval, a burst without its bucket, or a refill interval that does not fit in u64 milliseconds.
.bandwidth()
size bytes per refill_time. Size accepts a bare u64 byte count or the unit helpers from microsandbox::size::SizeExt (1.mib(), 512.kib()).
Parameters
sizeimpl Into<Bytes>refill_timeDuration.bandwidth_burst()
bandwidth().
.ops()
count frames per refill_time.
.ops_burst()
ops().
Rule
Held by NetworkPolicy
A single policy rule. Thedestination interpretation is direction-dependent: egress destination, or ingress peer/source. ports is always the guest-side port (egress destination port / ingress listening port).
Rule::allow_egress()
Egress
Rule::deny_egress()
Egress
Rule::allow_ingress()
Ingress
Rule::deny_ingress()
Ingress
Rule::allow_any()
Any
Rule::deny_any()
Any
Rule::allow_dns()
Group::Host); the one-liner for opening DNS under deny-by-default. See DNS as egress.
Rule::deny_dns()
PortRange
Held by Rule · added by port() · port_range()
An inclusive port range.PortRange::single()
PortRange::range()
PortRange::contains()
port falls within the range
DomainName
Held by Destination::Domain / DomainSuffix
A validated, canonical DNS name.name.as_str()
name.try_into_suffix()
DomainSuffix; single-label names (e.g. com) are rejected
Types
NetworkProfile
Composable high-level access category accepted byNetworkPolicy::from_profiles().
Action
Used by Rule · NetworkPolicy · default_egress()
Direction
Used by Rule
Destination
Held by Rule · committed by RuleDestinationBuilder
DestinationGroup
Held by Destination · committed by RuleBuilder group adders
Groups are disjoint with one carve-out:Metadata takes precedence over LinkLocal for 169.254.169.254, and Host over Private when the gateway IPs sit in CGN/ULA ranges.
Protocol
Held by Rule · set by RuleBuilder protocol setters
Ingress or Any carrying an ICMP protocol fails build with BuildError::IngressDoesNotSupportIcmp.
Nameserver
Used by nameservers()
An upstream DNS server, either a literal address or a hostname resolved at interceptor startup via the host’s OS resolver. Serializes as a single string. Construct viaFrom<SocketAddr>, From<IpAddr>, or str::parse (errors with ParseNameserverError).
1.1.1.1, 1.1.1.1:5353, 2606:4700:4700::1111, [2606:4700:4700::1111]:53, dns.google, dns.google:53. A bare IP or hostname defaults to port 53.
InterfaceOverrides
Used by interface()
Per-sandbox guest interface overrides. Every field is optional; an omitted field is derived deterministically from the sandbox slot. Most callers only touch the pools viaipv4_pool() / ipv6_pool() rather than constructing this directly.
NetworkRateLimiterConfig
Built by NetworkRateLimiterBuilder · used by rate_limiter()
Network rate limits grouped by direction. An omitted direction is unlimited.RateLimiterConfig
Built by RateLimiterBuilder · held by NetworkRateLimiterConfig
Rate limiter for one traffic direction. A missing bucket leaves that dimension unlimited.TokenBucketConfig
Held by RateLimiterConfig
One token bucket of a rate limiter. The bucket starts full and refills continuously atsize tokens per refill_time_ms; the one-time burst is spent before the regular budget and never refills.
BuildError
Returned by NetworkPolicyBuilder::build() · wrapped by NetworkBuilder
Errors surfaced by the builders’build() methods. The same enum covers NetworkPolicy::builder(), DnsBuilder, and NetworkBuilder; the network and DNS builders accumulate lazily, so the first failure surfaces from the outermost build() in the chain.
SandboxBuilder::build(), BuildError is wrapped as MicrosandboxError::NetworkBuilder(BuildError).
SecretViolationAction
Used by secret_violation_action()
Action taken when a secret placeholder is sent to a disallowed host. Also documented on the Secrets page, where it pairs withSecretBuilder.