use std::cell::Cell;
use std::fs::{self, File};
use std::io::{ErrorKind, Read, Seek, SeekFrom, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::{mpsc, Condvar, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
use crate::mxc_common::filesystem_resolve::{resolve_mount_order, FsIntent};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainerPolicy, ProxyAddress, ProxyHostPin};
use nix::errno::Errno;
use nix::fcntl::{fcntl, FcntlArg, FdFlag, OFlag};
use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
use nix::unistd::{access, dup2, pipe2, AccessFlags};
use tempfile::TempDir;
use crate::bwrap_common::bwrap_command::COMMAND_TAIL;
use crate::bwrap_common::network_rules::{
payload_file_name, render_filter_payloads, EgressPlan, IngressPlan, RuleFamily,
};
use crate::bwrap_common::probe_exec;
const STARTUP_TIMEOUT: Duration = Duration::from_secs(5);
const XTABLES_LOCK_WAIT: Duration = Duration::from_secs(5);
const XTABLES_LOCK_PATH: &str = "/run/xtables.lock";
fn rule_install_timeout(transactions: usize, script_timeout_ms: u32) -> Duration {
let waits = XTABLES_LOCK_WAIT
.checked_mul(u32::try_from(transactions).unwrap_or(u32::MAX))
.unwrap_or(RULE_INSTALL_CEILING);
let budget = waits
.saturating_add(RULE_INSTALL_HEADROOM)
.min(RULE_INSTALL_CEILING);
if script_timeout_ms == 0 {
return budget;
}
budget
.min(Duration::from_millis(u64::from(script_timeout_ms)))
.max(RULE_INSTALL_FLOOR)
}
const RULE_INSTALL_HEADROOM: Duration = Duration::from_secs(20);
const RULE_INSTALL_CEILING: Duration = Duration::from_secs(120);
const RULE_INSTALL_FLOOR: Duration =
Duration::from_secs(STARTUP_TIMEOUT.as_secs() + XTABLES_LOCK_WAIT.as_secs());
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const PRE_FLIGHT_BUDGET: Duration = Duration::from_secs(3);
const SLIRP_HOST_GATEWAY: &str = "10.0.2.2";
pub(crate) const SLIRP_HOST_GATEWAY_IP: Ipv4Addr = Ipv4Addr::new(10, 0, 2, 2);
const SLIRP_NETWORK: &str = "10.0.2.0/24";
const SANDBOX_HOSTS_PATH: &str = "/etc/hosts";
const EGRESS_CHAIN: &str = "MXC_EGRESS";
const INGRESS_CHAIN: &str = "MXC_INGRESS";
const SUPERVISOR_PID_FD: RawFd = 3;
const SUPERVISOR_EXIT_FD: RawFd = 4;
const SUPERVISOR_LIVENESS_FD: RawFd = 5;
const FD_STAGING_BASE: RawFd = 10;
const SUPERVISOR_SCRIPT: &str = r#"
set -eu
state_dir="$1"
lock_wait="$2"
# Inherited descriptors are remapped to fixed numbers by the parent (see
# `remap_descriptors`): 3 is the parent's PID pipe, 4 is slirp's exit pipe.
# They are hardcoded rather than passed in argv because /bin/sh is dash on
# Debian/Ubuntu, which rejects a *variable* descriptor >= 10 ("Bad fd number")
# at parse time -- a failure that depends on how many files the parent happens
# to hold open, so it surfaces nondeterministically and never in unit tests.
printf ready > "$state_dir/userns.ready"
# Block on the parent-owned PID pipe rather than polling for a file: if the
# parent dies before it can publish the PID, the read ends at EOF and this
# supervisor exits instead of spinning forever as an orphan.
if ! IFS= read -r child_pid <&3; then
child_pid="${child_pid:-}"
fi
exec 3<&-
if [ -z "$child_pid" ]; then
echo "mxc: parent exited before publishing the sandbox PID" >&2
exit 1
fi
# slirp signals readiness internally so the supervisor, not slirp, decides when
# the sandbox is ready -- the rules below must be in place first. Descriptor 9
# is safe to hardcode: the parent hands this child exactly 0-4, so nothing else
# can be sitting on it.
exec 9> "$state_dir/slirp.internal"
slirp4netns --configure --mtu=65520 \
--ready-fd 9 --exit-fd 4 \
"$child_pid" tap0 &
slirp_pid=$!
trap 'kill "$slirp_pid" 2>/dev/null || true' TERM INT
while [ ! -s "$state_dir/slirp.internal" ]; do
if ! kill -0 "$slirp_pid" 2>/dev/null; then
echo "slirp4netns exited before signalling readiness" >&2
exit 1
fi
sleep 0.01
done
ns="/proc/$child_pid/ns/net"
# Network filtering in both directions, programmed here because it needs
# CAP_NET_ADMIN in the owning user namespace, which this supervisor holds
# (`--keep-caps`) and the caller does not.
#
# Each family's rules arrive as one or more `iptables-restore` transactions,
# numbered so this glob applies them in order. Both built-in hooks travel in
# the *last* transaction of a family, so a hook is never live over a partially
# built chain and the rules cannot be observed half-installed. Splitting is
# forced by the kernel: one restore is one bounded netlink transaction, and a
# large host list would otherwise exceed it and install nothing. The payloads
# are rendered in Rust from parsed addresses, so nothing here echoes caller
# text.
#
# -w matters only on the legacy backend, the one that takes a lock: nsenter
# enters the network namespace but not the mount namespace, so concurrent
# sandboxes contend for the *host's* /run/xtables.lock, and set -e turns a lost
# race into a dead supervisor. nf_tables takes no lock and ignores the wait.
# A backend that cannot take the lock at all is refused by probe_dependencies.
# -n keeps the restore additive, so it never clears a table it did not write
# and so a later transaction appends to the chain an earlier one declared.
#
# A rejected transaction applies nothing, so a host that cannot support a rule
# fails closed here rather than starting an unenforced sandbox. The most likely
# cause is worth naming, because iptables reports it only as "Invalid argument".
conntrack_hint="mxc: could not install the sandbox network policy. If the error above says \
'Invalid argument', this host is missing the nf_conntrack kernel module that the inbound \
connection-state match requires, and an unprivileged sandbox cannot load it."
for payload in "$state_dir"/rules.v4.*; do
nsenter --net="$ns" -- iptables-restore -w "$lock_wait" -n "$payload" || { echo "$conntrack_hint" >&2; exit 1; }
done
# No IPv6 payload is written when the kernel has no IPv6 stack (see
# `rule_families`), and an unmatched glob expands to itself. IPv4 has no such
# guard, so a missing IPv4 payload still fails the restore and kills the
# supervisor.
for payload in "$state_dir"/rules.v6.*; do
[ -e "$payload" ] || continue
nsenter --net="$ns" -- ip6tables-restore -w "$lock_wait" -n "$payload" || { echo "$conntrack_hint" >&2; exit 1; }
done
# Signalled by path, not through a descriptor: this is a plain file the parent
# polls, so it needs no shell redirection and cannot hit dash's fd limit.
printf ready > "$state_dir/slirp.ready"
wait "$slirp_pid"
"#;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProxyEgress {
ip: Ipv4Addr,
port: u16,
pin: Option<ProxyHostPin>,
}
impl ProxyEgress {
pub(crate) fn pin(&self) -> Option<&ProxyHostPin> {
self.pin.as_ref()
}
pub(crate) fn plan(&self) -> EgressPlan {
EgressPlan::for_proxy(self.ip, self.port)
}
}
#[derive(Debug)]
pub(crate) struct SandboxProxy {
address: ProxyAddress,
egress: ProxyEgress,
}
impl SandboxProxy {
pub(crate) fn resolve(configured: &ProxyAddress) -> Result<Self, String> {
Self::resolve_with(configured, resolve_ipv4)
}
pub(crate) fn check_without_resolving(configured: &ProxyAddress) -> Result<(), String> {
let (needs_lookup, checked) = Self::inspect_without_resolving(configured);
if needs_lookup {
return Ok(());
}
checked
}
fn inspect_without_resolving(configured: &ProxyAddress) -> (bool, Result<(), String>) {
let asked_to_resolve = Cell::new(false);
let checked = Self::resolve_with(configured, |_, _| {
asked_to_resolve.set(true);
Err(String::new())
});
(asked_to_resolve.get(), checked.map(|_| ()))
}
fn resolve_with(
configured: &ProxyAddress,
resolve: impl Fn(&str, u16) -> Result<Ipv4Addr, String>,
) -> Result<Self, String> {
if configured.port() == 0 {
return Err("Bubblewrap: proxy-only egress requires a non-zero proxy port".to_string());
}
let host = configured.host().trim_matches(['[', ']']);
let is_reserved_loopback_name = host.eq_ignore_ascii_case("localhost");
if let Ok(ip) = host.parse::<Ipv4Addr>() {
return if ip.is_loopback() || ip.is_unspecified() {
Ok(Self::rewritten(configured)?)
} else {
reject_slirp_reserved(ip, host)?;
Ok(Self {
address: configured.clone(),
egress: ProxyEgress {
ip,
port: configured.port(),
pin: None,
},
})
};
}
if let Ok(ip) = host.parse::<Ipv6Addr>() {
if ip.is_unspecified() {
return Self::rewritten(configured);
}
if ip.is_loopback() {
return Err(format!(
"Bubblewrap: proxy address '{}' uses the IPv6 loopback, which the private \
network namespace cannot reach; bind the proxy to 127.0.0.1 or a dual-stack \
wildcard address instead. The egress rule is emitted with IPv4 iptables.",
configured.host()
));
}
return Err(ipv6_unsupported(host));
}
if is_reserved_loopback_name {
return Self::rewritten(configured);
}
let resolved = resolve(host, configured.port())?;
reject_slirp_reserved(resolved, host)?;
let ip = sandbox_facing_ip(resolved);
let pin = configured
.host_pin(IpAddr::V4(ip))
.map_err(|error| format!("Bubblewrap: {error}"))?;
Ok(Self {
address: configured.clone(),
egress: ProxyEgress {
ip,
port: configured.port(),
pin,
},
})
}
fn rewritten(configured: &ProxyAddress) -> Result<Self, String> {
Ok(Self {
address: rewrite_to_gateway(configured)?,
egress: ProxyEgress {
ip: SLIRP_HOST_GATEWAY_IP,
port: configured.port(),
pin: None,
},
})
}
pub(crate) fn address(&self) -> &ProxyAddress {
&self.address
}
pub(crate) fn egress(&self) -> &ProxyEgress {
&self.egress
}
}
fn sandbox_facing_ip(resolved: Ipv4Addr) -> Ipv4Addr {
if resolved.is_loopback() || resolved.is_unspecified() {
SLIRP_HOST_GATEWAY_IP
} else {
resolved
}
}
fn reject_slirp_reserved(resolved: Ipv4Addr, host: &str) -> Result<(), String> {
if !SLIRP_NETWORK_OCTETS.eq(&resolved.octets()[..3]) {
return Ok(());
}
Err(format!(
"Bubblewrap: proxy endpoint '{host}' is {resolved}, which is inside the sandbox's own \
network ({SLIRP_NETWORK}); there that address is slirp's own, not the host's \
{resolved}, so the egress rule would open an unrelated service. Bind the proxy to \
127.0.0.1 -- which is translated to the gateway deliberately -- or give it an address \
outside {SLIRP_NETWORK}."
))
}
const SLIRP_NETWORK_OCTETS: [u8; 3] = [10, 0, 2];
const RESOLVE_TIMEOUT: Duration = Duration::from_secs(15);
const RESOLVE_TIMEOUT_LABEL: &str = "mxc-proxy-resolve";
fn with_deadline<T: Send + 'static>(
label: &str,
timeout: Duration,
work: impl FnOnce() -> T + Send + 'static,
) -> Result<Result<T, mpsc::RecvTimeoutError>, std::io::Error> {
let (sender, receiver) = mpsc::channel();
thread::Builder::new()
.name(label.to_string())
.spawn(move || {
let _ = sender.send(work());
})?;
Ok(receiver.recv_timeout(timeout))
}
fn resolve_ipv4(host: &str, port: u16) -> Result<Ipv4Addr, String> {
let query = host.to_string();
let waited = with_deadline(RESOLVE_TIMEOUT_LABEL, RESOLVE_TIMEOUT, move || {
lookup_ipv4(&query, port)
})
.map_err(|error| {
format!("Bubblewrap: could not start the lookup of proxy host '{host}': {error}")
})?;
match waited {
Ok(resolved) => resolved,
Err(mpsc::RecvTimeoutError::Timeout) => Err(format!(
"Bubblewrap: resolving proxy host '{host}' exceeded {}s. The proxy endpoint is \
resolved on the host because DNS is closed inside the sandbox, so an unresponsive \
host resolver blocks the sandbox from starting. Check the host's DNS configuration, \
or give the proxy as an IPv4 address to skip resolution.",
RESOLVE_TIMEOUT.as_secs()
)),
Err(mpsc::RecvTimeoutError::Disconnected) => Err(format!(
"Bubblewrap: the lookup of proxy host '{host}' ended without an answer."
)),
}
}
fn lookup_ipv4(host: &str, port: u16) -> Result<Ipv4Addr, String> {
let resolved: Vec<IpAddr> = (host, port)
.to_socket_addrs()
.map_err(|error| {
format!(
"Bubblewrap: could not resolve proxy host '{host}': {error}. The proxy endpoint \
is resolved on the host because DNS is closed inside the sandbox."
)
})?
.map(|addr| addr.ip())
.collect();
if let Some(IpAddr::V4(ip)) = resolved.iter().find(|ip| ip.is_ipv4()) {
return Ok(*ip);
}
if resolved.is_empty() {
Err(format!(
"Bubblewrap: proxy host '{host}' did not resolve to any address."
))
} else {
Err(ipv6_unsupported(host))
}
}
fn ipv6_unsupported(host: &str) -> String {
format!(
"Bubblewrap: proxy-only egress requires an IPv4 proxy endpoint, but '{host}' is reachable \
over IPv6 only. The egress rule is emitted with IPv4 iptables, so an IPv6 endpoint would \
be silently dropped. Use an IPv4 proxy address."
)
}
pub(crate) struct BwrapStartup {
info_reader: File,
info_writer: Option<OwnedFd>,
gate_reader: Option<OwnedFd>,
gate_writer: Option<OwnedFd>,
inheritable: Vec<RawFd>,
}
impl BwrapStartup {
pub(crate) fn prepare_command(&self, command: &mut Command) {
inherit_descriptors(command, self.inheritable.clone());
}
pub(crate) fn child_spawned(&mut self) {
self.info_writer.take();
self.gate_reader.take();
}
pub(crate) fn child_pid(&mut self, child: &mut Child) -> Result<u32, String> {
set_nonblocking(self.info_reader.as_raw_fd())?;
let deadline = Instant::now() + STARTUP_TIMEOUT;
let mut json = Vec::new();
let mut chunk = [0_u8; 512];
loop {
match self.info_reader.read(&mut chunk) {
Ok(0) => {}
Ok(count) => json.extend_from_slice(&chunk[..count]),
Err(error) if error.kind() == ErrorKind::WouldBlock => {}
Err(error) => {
return Err(format!(
"Bubblewrap: failed to read bwrap child information: {error}"
));
}
}
if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&json) {
if let Some(pid) = value.get("child-pid").and_then(|pid| pid.as_u64()) {
return u32::try_from(pid).map_err(|_| {
format!("Bubblewrap: bwrap reported an out-of-range child PID: {pid}")
});
}
return Err(format!(
"Bubblewrap: bwrap child information omitted 'child-pid': {value}"
));
}
if let Some(status) = child
.try_wait()
.map_err(|error| format!("Bubblewrap: failed to inspect bwrap startup: {error}"))?
{
return Err(format!(
"Bubblewrap: bwrap exited before publishing child information ({status})"
));
}
if Instant::now() >= deadline {
return Err("Bubblewrap: timed out waiting for bwrap child information".into());
}
thread::sleep(Duration::from_millis(10));
}
}
pub(crate) fn release(mut self) -> Result<(), String> {
let writer = self
.gate_writer
.take()
.ok_or_else(|| "Bubblewrap: workload startup gate is already closed".to_string())?;
File::from(writer)
.write_all(&[1])
.map_err(|error| format!("Bubblewrap: failed to release workload startup: {error}"))
}
}
fn rule_families(kernel_ipv6: bool) -> &'static [RuleFamily] {
if kernel_ipv6 {
&[RuleFamily::V4, RuleFamily::V6]
} else {
&[RuleFamily::V4]
}
}
fn kernel_supports_ipv6() -> bool {
ipv6_probe_means_supported(socket(
AddressFamily::Inet6,
SockType::Datagram,
SockFlag::SOCK_CLOEXEC,
None,
))
}
fn ipv6_probe_means_supported(probe: nix::Result<OwnedFd>) -> bool {
!matches!(probe, Err(Errno::EAFNOSUPPORT))
}
fn warn_skipped_ipv6_rules(kernel_ipv6: bool, logger: &mut Logger) {
if kernel_ipv6 {
return;
}
logger.warning_line(
"WARNING: Bubblewrap did not install IPv6 firewall rules: the kernel reports \
no IPv6 support (EAFNOSUPPORT), so the sandbox cannot send IPv6 traffic and \
the IPv4 rules alone enforce the network policy.",
);
}
pub(crate) struct ProxyNetworkNamespace {
state_dir: TempDir,
supervisor: Child,
exit_writer: Option<OwnedFd>,
pid_writer: Option<OwnedFd>,
userns: Option<File>,
hosts: Option<PathBuf>,
liveness_reader: Option<OwnedFd>,
transactions: usize,
script_timeout_ms: u32,
}
impl ProxyNetworkNamespace {
pub(crate) fn start(
plan: &EgressPlan,
ingress: &IngressPlan,
pin: Option<&ProxyHostPin>,
logger: &mut Logger,
script_timeout_ms: u32,
) -> Result<Self, String> {
let state_dir = tempfile::Builder::new()
.prefix("mxc-bwrap-proxy-")
.tempdir()
.map_err(|error| {
format!("Bubblewrap: failed to create proxy-network state: {error}")
})?;
let kernel_ipv6 = kernel_supports_ipv6();
warn_skipped_ipv6_rules(kernel_ipv6, logger);
let mut transactions = 0usize;
for &family in rule_families(kernel_ipv6) {
let payloads =
render_filter_payloads(plan, ingress, family, EGRESS_CHAIN, INGRESS_CHAIN);
transactions += payloads.len();
for (index, payload) in payloads.iter().enumerate() {
let path = state_dir
.path()
.join(payload_file_name(family, index, payloads.len()));
std::fs::write(&path, payload).map_err(|error| {
format!("Bubblewrap: failed to write network rules to {path:?}: {error}")
})?;
}
}
let stderr_path = state_dir.path().join("supervisor.stderr");
let stderr = File::create(&stderr_path).map_err(|error| {
format!("Bubblewrap: failed to create proxy-network diagnostics: {error}")
})?;
let (exit_reader, exit_writer) =
pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
let (pid_reader, pid_writer) =
pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
let (liveness_reader, liveness_writer) =
pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
set_nonblocking(liveness_reader.as_raw_fd())?;
let mut command = Command::new("unshare");
command
.args([
"--user",
"--map-current-user",
"--keep-caps",
"--",
"sh",
"-c",
SUPERVISOR_SCRIPT,
"mxc-bwrap-proxy-supervisor",
])
.arg(state_dir.path())
.arg(XTABLES_LOCK_WAIT.as_secs().to_string())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr));
remap_descriptors(
&mut command,
[
(pid_reader.as_raw_fd(), SUPERVISOR_PID_FD),
(exit_reader.as_raw_fd(), SUPERVISOR_EXIT_FD),
(liveness_writer.as_raw_fd(), SUPERVISOR_LIVENESS_FD),
],
);
let mut supervisor = command.spawn().map_err(|error| {
format!("Bubblewrap: failed to start proxy-network supervisor: {error}")
})?;
drop(exit_reader);
drop(pid_reader);
drop(liveness_writer);
if let Err(error) = wait_for_file(
state_dir.path().join("userns.ready"),
&mut supervisor,
&stderr_path,
"user namespace startup",
STARTUP_TIMEOUT,
) {
terminate_child(&mut supervisor);
return Err(error);
}
let userns_path = format!("/proc/{}/ns/user", supervisor.id());
let userns = match File::open(&userns_path) {
Ok(file) => file,
Err(error) => {
terminate_child(&mut supervisor);
return Err(format!(
"Bubblewrap: failed to open proxy user namespace {userns_path}: {error}"
));
}
};
logger.log_line("Bubblewrap: created rootless proxy network namespace supervisor");
let hosts = match pin {
Some(pin) => {
let path = state_dir.path().join("hosts");
if let Err(error) = write_pinned_hosts(&path, pin) {
terminate_child(&mut supervisor);
return Err(error);
}
logger.log_line(&format!(
"Bubblewrap: pinned proxy host '{}' to {} for the sandbox",
pin.hostname(),
pin.ip()
));
Some(path)
}
None => None,
};
Ok(Self {
state_dir,
supervisor,
exit_writer: Some(exit_writer),
pid_writer: Some(pid_writer),
userns: Some(userns),
hosts,
liveness_reader: Some(liveness_reader),
transactions,
script_timeout_ms,
})
}
pub(crate) fn configure_bwrap(
&self,
args: &mut Vec<String>,
logger: &mut Logger,
) -> Result<BwrapStartup, String> {
let (info_reader, info_writer) =
pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
let (gate_reader, gate_writer) =
pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
let userns = self
.userns
.as_ref()
.ok_or_else(|| "Bubblewrap: proxy user namespace is already handed off".to_string())?;
if let Some(hosts) = &self.hosts {
let path = hosts
.to_str()
.ok_or_else(|| "Bubblewrap: proxy hosts pin path is not valid UTF-8".to_string())?;
if insert_hosts_bind(args, path)? {
logger.log_line(
"Bubblewrap: the proxy host pin overrides an earlier mount of \
/etc/hosts; the sandbox sees the pinned file",
);
}
}
let runtime_args = [
"--userns".to_string(),
userns.as_raw_fd().to_string(),
"--info-fd".to_string(),
info_writer.as_raw_fd().to_string(),
"--block-fd".to_string(),
gate_reader.as_raw_fd().to_string(),
];
args.splice(0..0, runtime_args);
Ok(BwrapStartup {
inheritable: vec![
userns.as_raw_fd(),
info_writer.as_raw_fd(),
gate_reader.as_raw_fd(),
],
info_reader: File::from(info_reader),
info_writer: Some(info_writer),
gate_reader: Some(gate_reader),
gate_writer: Some(gate_writer),
})
}
pub(crate) fn userns_handed_off(&mut self) {
self.userns.take();
}
pub(crate) fn attach(&mut self, child_pid: u32, logger: &mut Logger) -> Result<(), String> {
let mut writer = self
.pid_writer
.take()
.map(File::from)
.ok_or_else(|| "Bubblewrap: sandbox PID was already published".to_string())?;
writer
.write_all(format!("{child_pid}\n").as_bytes())
.map_err(|error| format!("Bubblewrap: failed to publish bwrap child PID: {error}"))?;
drop(writer);
wait_for_file(
self.state_dir.path().join("slirp.ready"),
&mut self.supervisor,
&self.state_dir.path().join("supervisor.stderr"),
"slirp4netns startup and network rule installation",
rule_install_timeout(self.transactions, self.script_timeout_ms),
)?;
logger.log_line(
"Bubblewrap: slirp4netns configured the private network namespace and the network \
rules are in force",
);
Ok(())
}
pub(crate) fn check_alive(&mut self) -> Result<(), String> {
match self.supervisor.try_wait() {
Ok(None) => Ok(()),
Ok(Some(status)) => Err(format!(
"Bubblewrap: the proxy network supervisor exited ({status}) after signalling \
readiness but before the workload started, leaving the sandbox with no \
network provider ({})",
stderr_detail(&self.state_dir.path().join("supervisor.stderr"))
)),
Err(error) => Err(format!(
"Bubblewrap: failed to inspect the proxy network supervisor before starting \
the workload: {error}"
)),
}
}
pub(crate) fn take_liveness_watch(&mut self) -> Option<OwnedFd> {
self.liveness_reader.take()
}
pub(crate) fn lost_provider_detail(&mut self) -> String {
let status = match self.supervisor.try_wait() {
Ok(Some(status)) => format!("exited with {status}"),
Ok(None) => "is still running, so slirp4netns died on its own".to_string(),
Err(error) => format!("could not be inspected: {error}"),
};
format!(
"Bubblewrap: the sandbox lost its network provider while the workload was \
running; the proxy network supervisor {status} ({})",
stderr_detail(&self.state_dir.path().join("supervisor.stderr"))
)
}
pub(crate) fn stop(&mut self, logger: &mut Logger) {
self.pid_writer.take();
self.exit_writer.take();
let deadline = Instant::now() + SHUTDOWN_TIMEOUT;
loop {
match self.supervisor.try_wait() {
Ok(Some(status)) => {
if !status.success() {
logger.log_line(&format!(
"WARNING: Bubblewrap: proxy network supervisor exited with {status} \
({})",
stderr_detail(&self.state_dir.path().join("supervisor.stderr"))
));
}
return;
}
Ok(None) if Instant::now() < deadline => {
thread::sleep(Duration::from_millis(10));
}
Ok(None) => {
logger.log_line(&format!(
"WARNING: Bubblewrap: slirp4netns did not stop promptly; terminating it \
({})",
stderr_detail(&self.state_dir.path().join("supervisor.stderr"))
));
terminate_child(&mut self.supervisor);
return;
}
Err(error) => {
logger.log_line(&format!(
"WARNING: Bubblewrap: failed to inspect slirp4netns shutdown: {error}"
));
terminate_child(&mut self.supervisor);
return;
}
}
}
}
}
impl Drop for ProxyNetworkNamespace {
fn drop(&mut self) {
let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
self.stop(&mut logger);
}
}
fn rewrite_to_gateway(address: &ProxyAddress) -> Result<ProxyAddress, String> {
if let Some(original_url) = &address.original_url {
let mut url = url::Url::parse(original_url).map_err(|error| {
format!("Bubblewrap: failed to translate proxy URL for private networking: {error}")
})?;
url.set_host(Some(SLIRP_HOST_GATEWAY)).map_err(|_| {
"Bubblewrap: failed to translate proxy URL host for private networking".to_string()
})?;
return Ok(ProxyAddress::from_url(
url.as_str(),
SLIRP_HOST_GATEWAY.to_string(),
address.port(),
));
}
Ok(ProxyAddress::new(
SLIRP_HOST_GATEWAY.to_string(),
address.port(),
))
}
#[derive(Debug)]
struct ProbeOutput {
status: ExitStatus,
stdout: String,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum DeadlineSource {
Command,
Budget,
}
#[derive(Clone, Copy)]
struct ProbeBudget {
deadline: Option<Instant>,
}
impl ProbeBudget {
fn unbounded() -> Self {
Self { deadline: None }
}
fn total(budget: Duration) -> Self {
Self {
deadline: Some(Instant::now() + budget),
}
}
fn command_deadline(self) -> (Instant, DeadlineSource) {
let per_command = Instant::now() + PROBE_TIMEOUT;
match self.deadline {
Some(total) if total < per_command => (total, DeadlineSource::Budget),
_ => (per_command, DeadlineSource::Command),
}
}
fn is_exhausted(self) -> bool {
self.deadline
.is_some_and(|deadline| Instant::now() >= deadline)
}
}
fn run_probe(
mut command: Command,
label: &str,
budget: ProbeBudget,
) -> Result<ProbeOutput, String> {
if budget.is_exhausted() {
return Err(format!(
"Bubblewrap: ran out of time before checking '{label}' \
(the host took longer than {PRE_FLIGHT_BUDGET:?} to answer earlier checks)"
));
}
let (deadline, deadline_source) = budget.command_deadline();
let timed_out = |cleanup_error: Option<std::io::Error>| {
let reason = match deadline_source {
DeadlineSource::Command => format!(
"Bubblewrap: '{label}' did not respond within {PROBE_TIMEOUT:?}; \
the host's {label} installation appears to be hung"
),
DeadlineSource::Budget => format!(
"Bubblewrap: gave up while checking '{label}' after the host took \
longer than {PRE_FLIGHT_BUDGET:?} to answer the dependency checks"
),
};
match cleanup_error {
Some(error) => {
format!("{reason}; failed to terminate it, so it may still be running: {error}")
}
None => reason,
}
};
match probe_exec::run_bounded(&mut command, deadline) {
Ok(captured) => {
if captured.stdout.truncated || captured.stderr.truncated {
return Err(format!(
"Bubblewrap: '{label}' produced more than {} bytes of output; \
refusing to judge a truncated banner",
probe_exec::MAX_PROBE_OUTPUT_BYTES
));
}
Ok(ProbeOutput {
status: captured.status,
stdout: String::from_utf8_lossy(&captured.stdout.bytes).into_owned(),
})
}
Err(probe_exec::ProbeFailure::Spawn(error)) => Err(format!("{error}")),
Err(probe_exec::ProbeFailure::TimedOut { cleanup_error }) => Err(timed_out(cleanup_error)),
Err(probe_exec::ProbeFailure::Wait { stage, error }) => Err(format!(
"failed while {} '{label}': {error}",
stage.as_str()
)),
Err(probe_exec::ProbeFailure::Internal(detail)) => {
Err(format!("failed to inspect '{label}': {detail}"))
}
}
}
const PRIVATE_NAMESPACE_PROBE_ARGS: [&str; 8] = [
"--user",
"--map-current-user",
"--keep-caps",
"--net",
"--",
"sh",
"-c",
":",
];
fn check_private_namespaces(
command: Command,
use_case: PrivateNetworkUse,
budget: ProbeBudget,
) -> Result<(), String> {
let requirement = use_case.requirement();
let userns = run_probe(command, "unshare", budget).map_err(|error| {
format!("Bubblewrap: {requirement} requires private user and network namespaces: {error}")
})?;
if !userns.status.success() {
return Err(namespace_probe_error(userns.status, use_case));
}
Ok(())
}
fn shell_failed_to_start(code: i32) -> bool {
matches!(code, 126 | 127)
}
fn namespace_probe_error(status: ExitStatus, use_case: PrivateNetworkUse) -> String {
let requirement = use_case.requirement();
if status.code().is_some_and(shell_failed_to_start) {
return format!(
"Bubblewrap: {requirement} requires 'sh' on PATH inside the sandbox namespace \
(the proxy supervisor runs as 'sh -c'), which this host could not start. \
Install a POSIX shell or {}.",
use_case.remedy()
);
}
format!(
"Bubblewrap: {requirement} requires unprivileged user and network namespaces, \
which this host refused (unshare --user --net exited with {status}). On Ubuntu 24.04+ \
this is usually AppArmor's 'kernel.apparmor_restrict_unprivileged_userns=1': give \
the caller an AppArmor profile that permits userns, or clear that sysctl on an \
ephemeral host. Otherwise enable the namespaces (for example 'sysctl -w \
kernel.unprivileged_userns_clone=1', or raise 'user.max_user_namespaces' / \
'user.max_net_namespaces') or {}.",
use_case.remedy()
)
}
fn write_pinned_hosts(path: &Path, pin: &ProxyHostPin) -> Result<(), String> {
let existing = match fs::read_to_string(SANDBOX_HOSTS_PATH) {
Ok(contents) => contents,
Err(error) if error.kind() == ErrorKind::NotFound => String::new(),
Err(error) => {
return Err(format!(
"Bubblewrap: failed to read {SANDBOX_HOSTS_PATH} while pinning the proxy host: \
{error}"
))
}
};
let contents = format!(
"{}\n{}",
pin.hosts_line(),
strip_host_from_hosts(&existing, pin.hostname())
);
fs::write(path, contents)
.map_err(|error| format!("Bubblewrap: failed to write the proxy hosts pin: {error}"))
}
fn strip_host_from_hosts(contents: &str, hostname: &str) -> String {
let mut out = String::with_capacity(contents.len());
for line in contents.lines() {
let (body, comment) = match line.split_once('#') {
Some((body, comment)) => (body, Some(comment)),
None => (line, None),
};
let mut fields = body.split_whitespace();
let Some(address) = fields.next() else {
out.push_str(line);
out.push('\n');
continue;
};
let names: Vec<&str> = fields.collect();
if !names.iter().any(|name| name.eq_ignore_ascii_case(hostname)) {
out.push_str(line);
out.push('\n');
continue;
}
let kept: Vec<&str> = names
.into_iter()
.filter(|name| !name.eq_ignore_ascii_case(hostname))
.collect();
if kept.is_empty() {
if let Some(comment) = comment {
out.push('#');
out.push_str(comment);
out.push('\n');
}
continue;
}
out.push_str(address);
for name in kept {
out.push(' ');
out.push_str(name);
}
if let Some(comment) = comment {
out.push_str(" #");
out.push_str(comment);
}
out.push('\n');
}
out
}
pub(crate) fn check_hosts_pin_against_policy(
configured: &ProxyAddress,
policy: &ContainerPolicy,
) -> Result<(), String> {
let (needs_pin, _) = SandboxProxy::inspect_without_resolving(configured);
if !needs_pin || !hosts_file_is_denied(policy) {
return Ok(());
}
Err(format!(
"Bubblewrap: the proxy endpoint '{}' is a hostname, which is reached by pinning it in \
the sandbox's {SANDBOX_HOSTS_PATH}, but the filesystem policy denies that path. The pin \
is applied after every policy mount, so honouring it would expose the file the policy \
masks. Remove {SANDBOX_HOSTS_PATH} from deniedPaths, or give the proxy an IP address, \
which needs no pin.",
configured.host()
))
}
fn hosts_file_is_denied(policy: &ContainerPolicy) -> bool {
resolve_mount_order(policy)
.iter()
.rfind(|mount| covers_hosts_file(&mount.path))
.is_some_and(|mount| mount.intent == FsIntent::Denied)
}
fn covers_hosts_file(path: &str) -> bool {
let path = path.trim_end_matches('/');
path == SANDBOX_HOSTS_PATH
|| SANDBOX_HOSTS_PATH
.strip_prefix(path)
.is_some_and(|rest| rest.starts_with('/'))
}
fn command_separator(args: &[String]) -> Result<usize, String> {
args.len()
.checked_sub(COMMAND_TAIL.len() + 1)
.filter(|&separator| args[separator..separator + COMMAND_TAIL.len()] == COMMAND_TAIL[..])
.ok_or_else(|| "Bubblewrap: argument list has no command separator".to_string())
}
fn insert_hosts_bind(args: &mut Vec<String>, hosts_path: &str) -> Result<bool, String> {
let separator = command_separator(args)?;
let overrides = args[..separator]
.iter()
.any(|arg| arg == SANDBOX_HOSTS_PATH);
args.splice(
separator..separator,
[
"--ro-bind".to_string(),
hosts_path.to_string(),
SANDBOX_HOSTS_PATH.to_string(),
],
);
Ok(overrides)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PrivateNetworkUse {
ProxyOnlyEgress,
FirewallEnforcement,
}
impl PrivateNetworkUse {
fn requirement(self) -> &'static str {
match self {
Self::ProxyOnlyEgress => "network.proxy",
Self::FirewallEnforcement => "network.enforcementMode='firewall'",
}
}
fn remedy(self) -> &'static str {
match self {
Self::ProxyOnlyEgress => "omit network.proxy",
Self::FirewallEnforcement => "select a different network.enforcementMode",
}
}
fn mechanism(self) -> &'static str {
match self {
Self::ProxyOnlyEgress => "proxy-only egress",
Self::FirewallEnforcement => "firewall enforcement",
}
}
}
pub fn probe_proxy_enforcement() -> Result<(), String> {
supervise_preflight(PRE_FLIGHT_BUDGET, || {
probe_dependencies_uncached(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::total(PRE_FLIGHT_BUDGET),
)
})
}
fn supervise_preflight<F>(budget: Duration, walk: F) -> Result<(), String>
where
F: FnOnce() -> Result<(), String> + Send + 'static,
{
supervise_preflight_with(&PREFLIGHT_GATE, budget, walk)
}
fn supervise_preflight_with<F>(
gate: &'static PreflightGate,
budget: Duration,
walk: F,
) -> Result<(), String>
where
F: FnOnce() -> Result<(), String> + Send + 'static,
{
let deadline = Instant::now() + budget;
let Some(slot) = gate.claim_until(deadline) else {
return Err(format!(
"Bubblewrap: an earlier proxy-enforcement pre-flight probe did not return within \
{budget:?}, so this host cannot be confirmed"
));
};
let (sender, receiver) = mpsc::sync_channel(1);
let worker = thread::Builder::new()
.name("mxc-proxy-preflight".to_string())
.spawn(move || {
let _slot = slot;
let _ = sender.send(walk());
});
if let Err(error) = worker {
return Err(format!(
"Bubblewrap: could not start the proxy-enforcement pre-flight probe: {error}"
));
}
match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
Ok(result) => result,
Err(mpsc::RecvTimeoutError::Timeout) => Err(format!(
"Bubblewrap: the host did not answer the proxy-enforcement dependency \
checks within {budget:?}"
)),
Err(mpsc::RecvTimeoutError::Disconnected) => {
Err("Bubblewrap: the proxy-enforcement pre-flight probe stopped unexpectedly".into())
}
}
}
struct PreflightGate {
in_flight: Mutex<bool>,
available: Condvar,
}
static PREFLIGHT_GATE: PreflightGate = PreflightGate::new();
impl PreflightGate {
const fn new() -> Self {
Self {
in_flight: Mutex::new(false),
available: Condvar::new(),
}
}
fn claim_until(&'static self, deadline: Instant) -> Option<PreflightSlot> {
let mut in_flight = self
.in_flight
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
loop {
if !*in_flight {
*in_flight = true;
return Some(PreflightSlot(self));
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return None;
}
let (next, wait) = self
.available
.wait_timeout(in_flight, remaining)
.unwrap_or_else(|poisoned| poisoned.into_inner());
in_flight = next;
if wait.timed_out() && *in_flight {
return None;
}
}
}
}
struct PreflightSlot(&'static PreflightGate);
impl Drop for PreflightSlot {
fn drop(&mut self) {
let mut in_flight = self
.0
.in_flight
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
*in_flight = false;
self.0.available.notify_one();
}
}
pub(crate) fn probe_dependencies(use_case: PrivateNetworkUse) -> Result<(), String> {
static PROBED: OnceLock<()> = OnceLock::new();
probe_dependencies_caching(
&PROBED,
use_case,
ProbeBudget::unbounded(),
real_probe_command,
)
}
fn probe_dependencies_caching<F>(
cache: &OnceLock<()>,
use_case: PrivateNetworkUse,
budget: ProbeBudget,
command: F,
) -> Result<(), String>
where
F: Fn(&str, &[&str]) -> Command,
{
if cache.get().is_none() {
probe_stable_dependencies(use_case, budget, &command)?;
let _ = cache.set(());
}
check_private_namespaces(
command("unshare", &PRIVATE_NAMESPACE_PROBE_ARGS),
use_case,
budget,
)
}
const RULE_TOOL_PROBES: [(&str, &str, bool); 5] = [
("nsenter", "--version", false),
("iptables", "--version", true),
("ip6tables", "--version", true),
("iptables-restore", "--version", true),
("ip6tables-restore", "--version", true),
];
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SupervisorCommandCoverage {
Probed,
Exempt(&'static str),
}
#[cfg(test)]
const EXPECTED_SUPERVISOR_SCRIPT_DIGEST: u64 = 0x5855_540d_dc42_997c;
#[cfg(test)]
const SUPERVISOR_EXTERNAL_COMMANDS: &[(&str, SupervisorCommandCoverage)] = &[
("slirp4netns", SupervisorCommandCoverage::Probed),
("nsenter", SupervisorCommandCoverage::Probed),
("iptables-restore", SupervisorCommandCoverage::Probed),
("ip6tables-restore", SupervisorCommandCoverage::Probed),
(
"sleep",
SupervisorCommandCoverage::Exempt(
"coreutils; cannot realistically be absent on a host that already \
has util-linux and iptables",
),
),
];
fn real_probe_command(program: &str, args: &[&str]) -> Command {
let mut command = Command::new(program);
command.args(args);
command
}
fn probe_dependencies_uncached(
use_case: PrivateNetworkUse,
budget: ProbeBudget,
) -> Result<(), String> {
probe_dependencies_with(use_case, budget, real_probe_command)
}
fn probe_dependencies_with<F>(
use_case: PrivateNetworkUse,
budget: ProbeBudget,
command: F,
) -> Result<(), String>
where
F: Fn(&str, &[&str]) -> Command,
{
probe_stable_dependencies(use_case, budget, &command)?;
check_private_namespaces(
command("unshare", &PRIVATE_NAMESPACE_PROBE_ARGS),
use_case,
budget,
)
}
fn probe_stable_dependencies<F>(
use_case: PrivateNetworkUse,
budget: ProbeBudget,
command: &F,
) -> Result<(), String>
where
F: Fn(&str, &[&str]) -> Command,
{
let requirement = use_case.requirement();
let slirp = run_probe(
command("slirp4netns", &["--version"]),
"slirp4netns",
budget,
)
.map_err(|error| {
format!(
"Bubblewrap: {requirement} requires 'slirp4netns' on PATH: {error}. \
Install slirp4netns or {}.",
use_case.remedy()
)
})?;
if !slirp.status.success() {
return Err(format!(
"Bubblewrap: {requirement} requires a working slirp4netns installation \
(slirp4netns --version exited with {})",
slirp.status
));
}
let unshare =
run_probe(command("unshare", &["--help"]), "unshare", budget).map_err(|error| {
format!("Bubblewrap: {requirement} requires util-linux 'unshare' on PATH: {error}")
})?;
if !unshare.status.success()
|| !unshare.stdout.contains("--map-current-user")
|| !unshare.stdout.contains("--keep-caps")
{
return Err(format!(
"Bubblewrap: {requirement} requires util-linux unshare with \
--map-current-user and --keep-caps support"
));
}
for (binary, probe, has_backend) in RULE_TOOL_PROBES {
let output = run_probe(command(binary, &[probe]), binary, budget).map_err(|error| {
format!(
"Bubblewrap: {requirement} requires '{binary}' on PATH to enforce {}: {error}",
use_case.mechanism()
)
})?;
if !output.status.success() {
return Err(format!(
"Bubblewrap: {requirement} requires a working '{binary}' installation \
({binary} {probe} exited with {})",
output.status
));
}
if has_backend {
iptables_backend_is_usable(
binary,
&output.stdout,
Path::new(XTABLES_LOCK_PATH),
use_case,
)?;
}
}
Ok(())
}
fn iptables_backend_is_usable(
binary: &str,
banner: &str,
lock: &Path,
use_case: PrivateNetworkUse,
) -> Result<(), String> {
if banner.contains("nf_tables") {
return Ok(());
}
if lock_is_writable(lock) {
return Ok(());
}
Err(format!(
"Bubblewrap: {} requires an iptables backend the sandbox supervisor can \
drive without privilege, but '{binary}' resolves to the legacy backend ({}) and \
'{}' is not writable by this user. The {} rules are installed by an \
unprivileged supervisor in a user namespace, which keeps the caller's uid, so the \
root-owned lock is unreachable and every rule would fail. Select the nf_tables \
backend (for example: update-alternatives --set {binary} /usr/sbin/{binary}-nft), \
or make '{}' writable.",
use_case.requirement(),
banner.trim(),
lock.display(),
use_case.mechanism(),
lock.display()
))
}
fn lock_is_writable(lock: &Path) -> bool {
let target = if lock.exists() {
lock
} else {
match lock.parent() {
Some(parent) => parent,
None => return false,
}
};
access(target, AccessFlags::W_OK).is_ok()
}
const MAX_STDERR_TAIL: u64 = 2048;
fn stderr_detail(path: &std::path::Path) -> String {
let text = read_stderr_tail(path);
let text = text.trim();
if text.is_empty() {
return "no stderr output".to_string();
}
format!("stderr: {text}")
}
fn read_stderr_tail(path: &std::path::Path) -> String {
let Ok(mut file) = File::open(path) else {
return String::new();
};
let len = file.metadata().map(|metadata| metadata.len()).unwrap_or(0);
if len > MAX_STDERR_TAIL && file.seek(SeekFrom::End(-(MAX_STDERR_TAIL as i64))).is_err() {
return String::new();
}
let mut buffer = Vec::new();
if file.take(MAX_STDERR_TAIL).read_to_end(&mut buffer).is_err() {
return String::new();
}
String::from_utf8_lossy(&buffer).into_owned()
}
fn wait_for_file(
path: impl AsRef<std::path::Path>,
child: &mut Child,
stderr_path: &std::path::Path,
component: &str,
timeout: Duration,
) -> Result<(), String> {
let path = path.as_ref();
let deadline = Instant::now() + timeout;
loop {
if fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0) {
return Ok(());
}
if let Some(status) = child.try_wait().map_err(|error| {
format!("Bubblewrap: failed to inspect {component} startup: {error}")
})? {
return Err(format!(
"Bubblewrap: {component} exited during startup ({status}): {}",
stderr_detail(stderr_path)
));
}
if Instant::now() >= deadline {
return Err(format!(
"Bubblewrap: timed out waiting for {component} after {timeout:?} ({})",
stderr_detail(stderr_path)
));
}
thread::sleep(Duration::from_millis(10));
}
}
fn inherit_descriptors(command: &mut Command, fds: Vec<RawFd>) {
unsafe {
command.pre_exec(move || {
for fd in &fds {
fcntl(*fd, FcntlArg::F_SETFD(FdFlag::empty())).map_err(std::io::Error::from)?;
}
Ok(())
});
}
}
fn remap_descriptors<const N: usize>(command: &mut Command, mapping: [(RawFd, RawFd); N]) {
unsafe {
command.pre_exec(move || {
let mut staged = [-1; N];
for (index, (source, _)) in mapping.iter().enumerate() {
staged[index] = fcntl(*source, FcntlArg::F_DUPFD_CLOEXEC(FD_STAGING_BASE))
.map_err(std::io::Error::from)?;
}
for (index, (_, target)) in mapping.iter().enumerate() {
dup2(staged[index], *target).map_err(std::io::Error::from)?;
}
Ok(())
});
}
}
fn set_nonblocking(fd: RawFd) -> Result<(), String> {
let flags = fcntl(fd, FcntlArg::F_GETFL)
.map_err(|error| format!("Bubblewrap: failed to read descriptor flags: {error}"))?;
let flags = OFlag::from_bits_truncate(flags);
fcntl(fd, FcntlArg::F_SETFL(flags | OFlag::O_NONBLOCK))
.map(|_| ())
.map_err(|error| format!("Bubblewrap: failed to make descriptor nonblocking: {error}"))
}
fn terminate_child(child: &mut Child) {
let _ = child.kill();
let _ = child.wait();
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mxc_common::models::NetworkEnforcementCompatibility;
#[test]
fn work_that_outlives_its_deadline_is_abandoned() {
let started = Instant::now();
let waited = with_deadline("mxc-test-deadline", Duration::from_millis(50), || {
thread::sleep(Duration::from_secs(30));
"an answer that arrives too late"
})
.expect("the worker thread starts");
assert!(
matches!(waited, Err(mpsc::RecvTimeoutError::Timeout)),
"the wait must end on the deadline rather than on the work"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"the caller waited {:?}, so the deadline did not bound it",
started.elapsed()
);
}
#[test]
fn work_that_finishes_within_its_deadline_returns_its_answer() {
let waited = with_deadline("mxc-test-deadline", Duration::from_secs(30), || 7)
.expect("the worker thread starts");
assert_eq!(waited, Ok(7));
}
#[test]
fn the_resolver_bound_survives_one_dead_nameserver() {
assert!(RESOLVE_TIMEOUT > Duration::from_secs(10));
}
#[test]
fn gateway_constants_agree() {
assert_eq!(SLIRP_HOST_GATEWAY_IP.to_string(), SLIRP_HOST_GATEWAY);
assert!(SLIRP_NETWORK.starts_with(&format!(
"{}.{}.{}.",
SLIRP_NETWORK_OCTETS[0], SLIRP_NETWORK_OCTETS[1], SLIRP_NETWORK_OCTETS[2]
)));
assert_eq!(SLIRP_HOST_GATEWAY_IP.octets()[..3], SLIRP_NETWORK_OCTETS);
}
#[test]
fn egress_rejects_a_hostname_resolving_into_the_sandbox_network() {
let address = ProxyAddress::new("proxy.example".into(), 3128);
let error = SandboxProxy::resolve_with(&address, resolver([10, 0, 2, 2]))
.expect_err("the slirp gateway must not be pinned as if it were a host address");
assert!(
error.contains("10.0.2.0/24") && error.contains("127.0.0.1"),
"error should name the reserved range and the supported alternative: {error}"
);
}
#[test]
fn egress_rejects_every_address_in_the_sandbox_network() {
for octets in [[10, 0, 2, 3], [10, 0, 2, 100], [10, 0, 2, 50]] {
let address = ProxyAddress::new("proxy.example".into(), 3128);
assert!(
SandboxProxy::resolve_with(&address, resolver(octets)).is_err(),
"{octets:?} is on-link inside the namespace and cannot name a host endpoint"
);
let literal = ProxyAddress::new(Ipv4Addr::from(octets).to_string(), 3128);
assert!(
SandboxProxy::resolve(&literal).is_err(),
"{octets:?} must be rejected as a literal too, not only as an answer"
);
}
}
#[test]
fn rejecting_the_sandbox_network_leaves_the_loopback_translation_intact() {
let address = ProxyAddress::new("proxy.example".into(), 3128);
let resolved = SandboxProxy::resolve_with(&address, resolver([127, 0, 0, 1]))
.expect("a loopback answer is translated, not rejected");
assert_eq!(resolved.egress().ip, SLIRP_HOST_GATEWAY_IP);
}
#[test]
fn egress_accepts_an_address_just_outside_the_sandbox_network() {
let address = ProxyAddress::new("proxy.example".into(), 3128);
let resolved = SandboxProxy::resolve_with(&address, resolver([10, 0, 3, 2]))
.expect("10.0.3.2 is a normal routable answer");
assert_eq!(resolved.egress().ip, Ipv4Addr::new(10, 0, 3, 2));
}
#[test]
fn egress_opens_the_gateway_for_a_loopback_literal() {
let address = ProxyAddress::new("127.0.0.1".into(), 8080);
let resolved = SandboxProxy::resolve(&address).unwrap();
assert_eq!(resolved.address().host(), SLIRP_HOST_GATEWAY);
assert_eq!(resolved.egress().ip.to_string(), SLIRP_HOST_GATEWAY);
assert_eq!(resolved.egress().port, 8080);
assert!(resolved.egress().pin().is_none());
}
#[test]
fn egress_accepts_a_routable_ipv4_proxy() {
let address = ProxyAddress::new("10.1.2.3".into(), 3128);
let resolved = SandboxProxy::resolve(&address).unwrap();
assert_eq!(resolved.address().host(), "10.1.2.3");
assert_eq!(resolved.egress().ip.to_string(), "10.1.2.3");
assert_eq!(resolved.egress().port, 3128);
assert!(resolved.egress().pin().is_none());
}
fn resolver(ip: [u8; 4]) -> impl Fn(&str, u16) -> Result<Ipv4Addr, String> {
move |_, _| Ok(Ipv4Addr::from(ip))
}
#[test]
fn pins_a_hostname_and_keeps_its_url() {
let address = ProxyAddress::from_url(
"http://proxy.corp.example:3128/",
"proxy.corp.example".into(),
3128,
);
let resolved = SandboxProxy::resolve_with(&address, resolver([10, 1, 2, 3])).unwrap();
assert_eq!(
resolved.address().to_url(),
"http://proxy.corp.example:3128/"
);
let pin = resolved.egress().pin().expect("hostname must be pinned");
assert_eq!(pin.hostname(), "proxy.corp.example");
assert_eq!(pin.ip().to_string(), "10.1.2.3");
assert_eq!(resolved.egress().ip.to_string(), "10.1.2.3");
}
#[test]
fn pins_a_loopback_hostname_to_the_gateway() {
let address = ProxyAddress::from_url("http://proxy.local:3128", "proxy.local".into(), 3128);
let resolved = SandboxProxy::resolve_with(&address, resolver([127, 0, 1, 1])).unwrap();
let pin = resolved.egress().pin().expect("hostname must be pinned");
assert_eq!(pin.ip().to_string(), SLIRP_HOST_GATEWAY);
assert_eq!(resolved.egress().ip.to_string(), SLIRP_HOST_GATEWAY);
}
#[test]
fn rewrites_localhost_instead_of_pinning_it() {
let address = ProxyAddress::from_url("http://localhost:3128/", "localhost".into(), 3128);
let resolved =
SandboxProxy::resolve_with(&address, |_, _| panic!("localhost must not be resolved"))
.unwrap();
assert_eq!(resolved.address().host(), SLIRP_HOST_GATEWAY);
assert!(resolved.egress().pin().is_none());
assert_eq!(resolved.egress().ip.to_string(), SLIRP_HOST_GATEWAY);
}
#[test]
fn the_pre_flight_check_defers_every_verdict_that_needs_a_lookup() {
let named = ProxyAddress::new("proxy.this-name-cannot-exist.invalid".into(), 3128);
assert!(
SandboxProxy::check_without_resolving(&named).is_ok(),
"a hostname's verdict belongs to the lookup in `run`"
);
}
#[test]
fn the_pre_flight_check_still_rejects_what_no_lookup_could_rescue() {
for unusable in [
ProxyAddress::new("[::1]".into(), 3128),
ProxyAddress::new("2001:db8::1".into(), 3128),
ProxyAddress::new("127.0.0.1".into(), 0),
] {
assert!(
SandboxProxy::check_without_resolving(&unusable).is_err(),
"endpoint '{}' is unusable regardless of DNS",
unusable.host()
);
}
}
#[test]
fn a_denied_ancestor_counts_as_denying_the_hosts_file() {
let denied_parent = ContainerPolicy {
denied_paths: vec!["/etc".into()],
..Default::default()
};
assert!(hosts_file_is_denied(&denied_parent));
let regranted = ContainerPolicy {
denied_paths: vec!["/etc".into()],
readonly_paths: vec![SANDBOX_HOSTS_PATH.into()],
..Default::default()
};
assert!(
!hosts_file_is_denied(®ranted),
"a more specific grant beneath the denial takes effect"
);
let unrelated = ContainerPolicy {
denied_paths: vec!["/etc/hostname".into(), "/etc/hosts.allow".into()],
..Default::default()
};
assert!(
!hosts_file_is_denied(&unrelated),
"a sibling with a shared prefix must not be mistaken for the file"
);
}
#[test]
fn pins_a_routable_hostname_to_its_resolved_address() {
assert_eq!(
sandbox_facing_ip(Ipv4Addr::new(10, 1, 2, 3)),
Ipv4Addr::new(10, 1, 2, 3)
);
assert_eq!(
sandbox_facing_ip(Ipv4Addr::new(127, 0, 0, 1)),
SLIRP_HOST_GATEWAY_IP
);
assert_eq!(
sandbox_facing_ip(Ipv4Addr::UNSPECIFIED),
SLIRP_HOST_GATEWAY_IP
);
}
#[test]
fn egress_rejects_an_ipv6_proxy() {
let loopback = ProxyAddress::new("[::1]".into(), 8080);
let error = SandboxProxy::resolve(&loopback).unwrap_err();
assert!(
error.contains("IPv4"),
"error should explain the IPv4 requirement: {error}"
);
let routable = ProxyAddress::new("2001:db8::1".into(), 8080);
assert!(SandboxProxy::resolve(&routable).is_err());
}
#[test]
fn egress_rejects_an_unresolvable_hostname() {
let address = ProxyAddress::from_url(
"http://proxy.corp.invalid:3128",
"proxy.corp.invalid".into(),
3128,
);
let error = SandboxProxy::resolve(&address).unwrap_err();
assert!(
error.contains("proxy.corp.invalid"),
"error should name the offending host: {error}"
);
}
#[test]
fn rejects_an_ipv6_loopback_proxy_instead_of_translating_it() {
for host in ["[::1]", "::1"] {
let address = ProxyAddress::new(host.into(), 8080);
let error = SandboxProxy::resolve(&address).unwrap_err();
assert!(
error.contains("IPv6 loopback"),
"error should name the unreachable address family: {error}"
);
}
}
#[test]
fn ipv6_loopback_rejection_leaves_the_ipv6_wildcard_translatable() {
let address = ProxyAddress::new("[::]".into(), 8080);
let translated = SandboxProxy::resolve(&address).unwrap();
assert_eq!(translated.address().host(), SLIRP_HOST_GATEWAY);
}
#[test]
fn egress_rejects_a_zero_port() {
let address = ProxyAddress::new("10.0.2.2".into(), 0);
let error = SandboxProxy::resolve(&address).unwrap_err();
assert!(
error.contains("non-zero"),
"error should explain the port requirement: {error}"
);
}
fn normalised_script() -> String {
SUPERVISOR_SCRIPT.replace(r#" -w "$lock_wait""#, "")
}
fn test_pin() -> ProxyHostPin {
ProxyAddress::new("proxy.example".into(), 3128)
.host_pin(IpAddr::V4(SLIRP_HOST_GATEWAY_IP))
.expect("hostname must be pinnable")
.expect("a hostname needs a pin")
}
#[test]
fn pinned_hosts_file_puts_the_pin_first() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("hosts");
write_pinned_hosts(&path, &test_pin()).unwrap();
let contents = fs::read_to_string(&path).unwrap();
assert_eq!(
contents.lines().next().unwrap(),
format!("{SLIRP_HOST_GATEWAY} proxy.example")
);
}
#[test]
fn a_competing_mapping_for_the_pinned_name_is_removed() {
let stripped = strip_host_from_hosts(
"127.0.0.1 localhost\n127.0.0.1 proxy.example\n10.9.9.9 proxy.example\n",
"proxy.example",
);
assert_eq!(stripped, "127.0.0.1 localhost\n");
}
#[test]
fn stripping_the_pinned_name_keeps_the_other_names_on_its_line() {
let stripped =
strip_host_from_hosts("127.0.0.1 localhost proxy.example\n", "proxy.example");
assert_eq!(stripped, "127.0.0.1 localhost\n");
}
#[test]
fn stripping_the_pinned_name_ignores_case() {
let stripped = strip_host_from_hosts("127.0.0.1 Proxy.EXAMPLE\n", "proxy.example");
assert_eq!(stripped, "");
}
#[test]
fn stripping_leaves_unrelated_lines_byte_for_byte() {
let original = "127.0.0.1\tlocalhost\n\n# a comment\n::1\tip6-localhost ip6-loopback\n";
assert_eq!(strip_host_from_hosts(original, "proxy.example"), original);
}
#[test]
fn stripping_an_entire_entry_keeps_its_trailing_comment() {
let stripped =
strip_host_from_hosts("10.9.9.9 proxy.example # operator note\n", "proxy.example");
assert_eq!(stripped, "# operator note\n");
}
#[test]
fn the_written_hosts_file_has_exactly_one_mapping_for_the_pinned_name() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("hosts");
write_pinned_hosts(&path, &test_pin()).unwrap();
let written = fs::read_to_string(&path).unwrap();
let matches = written
.lines()
.filter(|line| {
let body = line.split('#').next().unwrap_or("");
body.split_whitespace()
.skip(1)
.any(|name| name.eq_ignore_ascii_case("proxy.example"))
})
.count();
assert_eq!(
matches, 1,
"exactly one mapping may survive for the pinned name:\n{written}"
);
}
#[test]
fn pinned_hosts_file_keeps_the_host_entries() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("hosts");
write_pinned_hosts(&path, &test_pin()).unwrap();
let written = fs::read_to_string(&path).unwrap();
let host_file = fs::read_to_string(SANDBOX_HOSTS_PATH).unwrap_or_default();
for line in host_file.lines().filter(|line| {
!line.trim().is_empty()
&& !line
.split('#')
.next()
.unwrap_or("")
.split_whitespace()
.skip(1)
.any(|name| name.eq_ignore_ascii_case("proxy.example"))
}) {
assert!(
written.contains(line),
"host entry should be preserved: {line}"
);
}
}
#[test]
fn hosts_bind_is_applied_after_policy_mounts() {
let mut args = vec![
"--ro-bind-try".to_string(),
"/etc".to_string(),
"/etc".to_string(),
"--bind".to_string(),
"/etc/hosts".to_string(),
"/etc/hosts".to_string(),
];
args.extend(command_tail());
insert_hosts_bind(&mut args, "/tmp/pin/hosts").unwrap();
let pin = args
.windows(3)
.position(|window| window == ["--ro-bind", "/tmp/pin/hosts", SANDBOX_HOSTS_PATH])
.expect("pin bind should be present");
let policy = args
.windows(3)
.position(|window| window == ["--bind", "/etc/hosts", "/etc/hosts"])
.expect("policy mount should be retained");
let separator = command_separator(&args).unwrap();
assert!(pin > policy, "pin must be applied after the policy mount");
assert!(pin < separator, "pin must precede the command separator");
}
#[test]
fn hosts_bind_reports_an_overridden_policy_mount() {
let mut args = vec![
"--bind".to_string(),
"/custom/hosts".to_string(),
"/etc/hosts".to_string(),
];
args.extend(command_tail());
assert!(insert_hosts_bind(&mut args, "/tmp/pin/hosts").unwrap());
let mut untouched = vec!["--ro-bind-try".to_string()];
untouched.extend(command_tail());
assert!(!insert_hosts_bind(&mut untouched, "/tmp/pin/hosts").unwrap());
}
#[test]
fn hosts_bind_requires_a_command_separator() {
let mut args = vec!["--ro-bind-try".to_string(), "/etc".to_string()];
assert!(insert_hosts_bind(&mut args, "/tmp/pin/hosts").is_err());
}
fn command_tail() -> Vec<String> {
COMMAND_TAIL
.iter()
.map(|arg| arg.to_string())
.chain(["echo hello".to_string()])
.collect()
}
#[test]
fn a_caller_supplied_separator_value_is_not_mistaken_for_the_command() {
let mut args = vec![
"--setenv".to_string(),
"FOO".to_string(),
"--".to_string(),
"--ro-bind-try".to_string(),
"/etc".to_string(),
"/etc".to_string(),
];
args.extend(command_tail());
let decoy = 2;
insert_hosts_bind(&mut args, "/tmp/pin/hosts").unwrap();
assert_eq!(
args[..=decoy],
["--setenv", "FOO", "--"],
"the environment value must survive the splice intact"
);
let pin = args
.windows(3)
.position(|window| window == ["--ro-bind", "/tmp/pin/hosts", SANDBOX_HOSTS_PATH])
.expect("pin bind should be present");
assert!(
pin > decoy,
"the pin must be spliced at the command, not at the decoy value"
);
assert_eq!(
args[args.len() - COMMAND_TAIL.len() - 1..],
["--", "sh", "-c", "echo hello"],
"the command must remain last"
);
}
fn script_offset(needle: &str) -> usize {
normalised_script()
.find(needle)
.unwrap_or_else(|| panic!("supervisor script should contain {needle:?}"))
}
#[test]
fn script_signals_readiness_only_after_rules_are_installed() {
let last_restore = script_offset("ip6tables-restore");
let ready = script_offset(r#"printf ready > "$state_dir/slirp.ready""#);
assert!(
last_restore < ready,
"readiness must be signalled after the final restore"
);
}
#[test]
fn the_script_hardcodes_no_rule_of_its_own() {
for line in normalised_script().lines() {
for fragment in [" -j ACCEPT", " -j DROP", " -d ", " -A ", " -N "] {
assert!(
!line.contains(fragment),
"the script names a rule that did not come from the payload: {line}"
);
}
}
}
#[test]
fn script_restores_both_families() {
script_offset("-- iptables-restore ");
script_offset("-- ip6tables-restore ");
}
#[test]
fn script_installs_rules_synchronously() {
let rules_start = script_offset("-- iptables-restore ");
let ready = script_offset(r#"printf ready > "$state_dir/slirp.ready""#);
let script = normalised_script();
let region = &script[rules_start..ready];
for line in region.lines().filter(|line| line.contains("nsenter")) {
assert!(
!line.trim_end().ends_with('&'),
"rule must not be backgrounded: {line}"
);
assert!(
!line.contains('('),
"rule must not run in a subshell: {line}"
);
}
}
#[test]
fn translates_loopback_literal_to_slirp_gateway() {
let address = ProxyAddress::new("127.0.0.1".into(), 8080);
let resolved = SandboxProxy::resolve(&address).unwrap();
assert_eq!(resolved.address().host(), SLIRP_HOST_GATEWAY);
assert_eq!(resolved.address().port(), 8080);
assert_eq!(resolved.address().to_url(), "http://10.0.2.2:8080");
}
#[test]
fn translates_loopback_url_without_losing_url_components() {
let address =
ProxyAddress::from_url("http://user:pass@127.0.0.1:3128/", "127.0.0.1".into(), 3128);
let resolved = SandboxProxy::resolve(&address).unwrap();
assert_eq!(resolved.address().host(), SLIRP_HOST_GATEWAY);
assert_eq!(resolved.address().port(), 3128);
assert_eq!(
resolved.address().to_url(),
"http://user:pass@10.0.2.2:3128/"
);
}
#[test]
fn leaves_a_routable_literal_proxy_unchanged() {
let address = ProxyAddress::from_url("https://10.1.2.3:8443", "10.1.2.3".into(), 8443);
let resolved = SandboxProxy::resolve(&address).unwrap();
assert_eq!(resolved.address().to_url(), address.to_url());
}
#[test]
fn translates_wildcard_proxy_to_slirp_gateway() {
let address = ProxyAddress::new("0.0.0.0".into(), 8080);
let translated = SandboxProxy::resolve(&address).unwrap();
assert_eq!(translated.address().host(), SLIRP_HOST_GATEWAY);
assert_eq!(translated.address().port(), 8080);
}
#[test]
fn translates_bracketed_ipv6_wildcard_proxy_to_slirp_gateway() {
let address = ProxyAddress::from_url("http://[::]:3128/", "[::]".into(), 3128);
let translated = SandboxProxy::resolve(&address).unwrap();
assert_eq!(translated.address().host(), SLIRP_HOST_GATEWAY);
assert_eq!(translated.address().port(), 3128);
assert_eq!(translated.address().to_url(), "http://10.0.2.2:3128/");
}
#[test]
fn inherited_descriptors_reach_only_the_prepared_child() {
let (reader, _writer) = pipe2(OFlag::O_CLOEXEC).expect("pipe");
let fd = reader.as_raw_fd();
let probe = format!("test -e /proc/self/fd/{fd} && echo present || echo absent");
let mut prepared = Command::new("sh");
prepared.arg("-c").arg(&probe);
inherit_descriptors(&mut prepared, vec![fd]);
let prepared_out = prepared.output().expect("spawn prepared child");
let bystander = Command::new("sh")
.arg("-c")
.arg(&probe)
.output()
.expect("spawn bystander child");
assert_eq!(
String::from_utf8_lossy(&prepared_out.stdout).trim(),
"present",
"the prepared child did not inherit the descriptor"
);
assert_eq!(
String::from_utf8_lossy(&bystander.stdout).trim(),
"absent",
"an unrelated child inherited the descriptor"
);
let flags = FdFlag::from_bits_truncate(fcntl(fd, FcntlArg::F_GETFD).expect("F_GETFD"));
assert!(
flags.contains(FdFlag::FD_CLOEXEC),
"the parent's own descriptor was left inheritable"
);
}
#[test]
fn remapped_descriptors_land_on_fixed_numbers_from_any_source() {
let (reader, writer) = pipe2(OFlag::O_CLOEXEC).expect("pipe");
let high = fcntl(reader.as_raw_fd(), FcntlArg::F_DUPFD_CLOEXEC(20)).expect("dup high");
assert!(high >= 20, "test needs a two-digit source descriptor");
File::from(writer).write_all(b"4242\n").expect("write pid");
let mut command = Command::new("sh");
command
.arg("-c")
.arg(format!(
"IFS= read -r v <&{SUPERVISOR_PID_FD}; printf %s \"$v\""
));
remap_descriptors(&mut command, [(high, SUPERVISOR_PID_FD)]);
let out = command.output().expect("spawn remapped child");
assert!(
out.status.success(),
"remapped child failed: {}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(
String::from_utf8_lossy(&out.stdout),
"4242",
"the pipe did not arrive on the fixed descriptor"
);
}
#[test]
fn remapping_survives_a_source_already_on_a_target_number() {
let (a_reader, a_writer) = pipe2(OFlag::O_CLOEXEC).expect("pipe");
let (b_reader, b_writer) = pipe2(OFlag::O_CLOEXEC).expect("pipe");
let a = a_reader.as_raw_fd();
let b = b_reader.as_raw_fd();
File::from(a_writer).write_all(b"AAA\n").expect("write a");
File::from(b_writer).write_all(b"BBB\n").expect("write b");
let mapping = [(a, b), (b, SUPERVISOR_PID_FD)];
let mut command = Command::new("sh");
command.arg("-c").arg(format!(
"printf 'first=%s second=%s' \
\"$(cat /proc/self/fd/{b})\" \"$(cat /proc/self/fd/{SUPERVISOR_PID_FD})\""
));
remap_descriptors(&mut command, mapping);
let out = command.output().expect("spawn remapped child");
assert_eq!(
String::from_utf8_lossy(&out.stdout),
"first=AAA second=BBB",
"a source sitting on another target was clobbered during remap"
);
}
#[test]
fn supervisor_script_parses_under_the_shell_that_runs_it() {
let out = Command::new("sh")
.arg("-n")
.arg("-c")
.arg(SUPERVISOR_SCRIPT)
.output()
.expect("spawn sh");
assert!(
out.status.success(),
"supervisor script is not valid /bin/sh: {}",
String::from_utf8_lossy(&out.stderr)
);
}
#[test]
fn supervisor_script_never_redirects_to_a_variable_descriptor() {
for line in SUPERVISOR_SCRIPT.lines() {
let code = line.trim();
if code.starts_with('#') {
continue;
}
assert!(
!code.contains(">&$") && !code.contains("<&$"),
"variable descriptor redirection breaks dash for fd >= 10: {code}"
);
assert!(
!code.contains("}>") && !code.contains("}<"),
"varfd allocation is a bash-ism; dash parses it as a word: {code}"
);
}
}
#[test]
fn every_rule_command_waits_for_the_xtables_lock() {
let code: Vec<&str> = SUPERVISOR_SCRIPT
.lines()
.map(str::trim)
.filter(|line| !line.starts_with('#'))
.collect();
let restores: Vec<&&str> = code
.iter()
.filter(|line| line.contains("tables-restore"))
.collect();
assert_eq!(
restores.len(),
2,
"one restore call site per family; the per-family loop is what scales"
);
for restore in &restores {
assert!(
restore.contains(r#"-w "$lock_wait""#),
"restore may fail instantly on a contended host lock: {restore}"
);
assert!(
restore.contains(" -n "),
"restore without -n flushes tables it did not write: {restore}"
);
}
assert!(
!code
.iter()
.any(|line| line.contains("-- iptables ") || line.contains("-- ip6tables ")),
"rule installation must go through iptables-restore, not per-rule calls"
);
}
#[test]
fn rule_install_budget_covers_every_transaction_blocking_on_the_lock() {
for transactions in [2usize, 5, 11] {
let budget = rule_install_timeout(transactions, 0);
assert!(
budget > XTABLES_LOCK_WAIT * transactions as u32,
"a fully contended host would time out before -w could succeed, and the \
budget also covers slirp startup, so it needs headroom above the lock \
waits: {transactions} transactions got {budget:?}"
);
}
}
#[test]
fn the_rule_install_budget_is_bounded_however_large_the_policy_is() {
assert_eq!(rule_install_timeout(usize::MAX, 0), RULE_INSTALL_CEILING);
assert!(
rule_install_timeout(2, 0) < RULE_INSTALL_CEILING,
"an ordinary policy must not be charged the ceiling"
);
}
#[test]
fn rule_install_budget_never_outlasts_the_requested_deadline() {
let deadline = Duration::from_secs(25);
assert!(rule_install_timeout(2, 0) > deadline, "premise");
assert_eq!(rule_install_timeout(2, 25_000), deadline);
}
#[test]
fn the_deadline_clamp_stops_at_the_startup_floor() {
assert_eq!(rule_install_timeout(2, 1_000), RULE_INSTALL_FLOOR);
}
#[test]
fn an_absent_deadline_leaves_the_budget_unclamped() {
assert!(rule_install_timeout(2, 0) > RULE_INSTALL_FLOOR);
}
fn plan_with_rule_count(count: usize) -> EgressPlan {
let mut request = crate::mxc_common::models::ExecutionRequest {
network_enforcement_compatibility: NetworkEnforcementCompatibility::Strict,
..Default::default()
};
request.policy.allowed_hosts = (0..count)
.map(|n| format!("10.0.{}.{}", n / 256, n % 256))
.collect();
EgressPlan::for_policy(&request).expect("literal addresses must build a plan")
}
#[test]
fn a_rejected_transaction_surfaces_the_conntrack_hint() {
let plan = plan_with_rule_count(3);
for transaction in 1..=2 {
let mut supervisor =
spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), Some(transaction), false);
supervisor.publish_sandbox_pid();
let status = supervisor.wait_for_exit();
assert!(
!status.success(),
"transaction {transaction} failed but the supervisor lived on"
);
let stderr = supervisor.stderr();
assert!(
stderr.contains("nf_conntrack"),
"a rejected transaction must name the missing kernel module, got: {stderr}"
);
}
}
#[test]
fn the_script_globs_match_the_rendered_payload_names() {
for family in [RuleFamily::V4, RuleFamily::V6] {
let glob = format!("\"$state_dir\"/{}*", family.payload_prefix());
assert!(
SUPERVISOR_SCRIPT.contains(&glob),
"the script has no glob {glob} for the payloads the renderer writes"
);
assert!(
payload_file_name(family, 0, 1).starts_with(family.payload_prefix()),
"the renderer stopped using the prefix the glob matches"
);
}
}
#[test]
fn the_supervisor_leaves_ipv6_disabled_in_the_namespace() {
assert!(
!SUPERVISOR_SCRIPT.contains("--enable-ipv6"),
"slirp4netns must not offer IPv6 while the ingress chain lacks ICMPv6 exemptions"
);
}
#[test]
fn ipv6_rules_are_dropped_only_when_the_kernel_lacks_ipv6() {
assert_eq!(rule_families(true), [RuleFamily::V4, RuleFamily::V6]);
assert_eq!(rule_families(false), [RuleFamily::V4]);
}
#[test]
fn skipping_the_ipv6_rules_is_a_retained_warning() {
let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
warn_skipped_ipv6_rules(false, &mut logger);
let out = logger.warnings().join("\n");
assert!(
out.contains("did not install IPv6 firewall rules"),
"must say the IPv6 rules were skipped: {out}"
);
assert!(
logger.get_buffer().is_empty(),
"the warning must travel as a retained warning, not as buffer output"
);
let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
warn_skipped_ipv6_rules(true, &mut logger);
assert!(
logger.warnings().is_empty(),
"IPv6 rules installed, no warning"
);
}
#[test]
fn only_eafnosupport_counts_as_a_kernel_without_ipv6() {
assert!(!ipv6_probe_means_supported(Err(Errno::EAFNOSUPPORT)));
for errno in [
Errno::EMFILE,
Errno::ENFILE,
Errno::ENOBUFS,
Errno::ENOMEM,
Errno::EACCES,
Errno::EPROTONOSUPPORT,
] {
assert!(ipv6_probe_means_supported(Err(errno)), "{errno}");
}
let socket = socket(
AddressFamily::Inet,
SockType::Datagram,
SockFlag::SOCK_CLOEXEC,
None,
)
.expect("an IPv4 socket stands in for a successful probe");
assert!(ipv6_probe_means_supported(Ok(socket)));
}
#[test]
fn probe_gives_up_on_a_hung_binary_instead_of_blocking_forever() {
let mut command = Command::new("sleep");
command.arg("120");
let started = Instant::now();
let error = run_probe(command, "wedged-tool", ProbeBudget::unbounded())
.expect_err("a hung probe must not succeed");
let elapsed = started.elapsed();
assert!(
error.contains("wedged-tool"),
"the error must name the tool that hung, got: {error}"
);
assert!(
elapsed < PROBE_TIMEOUT * 3,
"probe took {elapsed:?}, expected to give up near {PROBE_TIMEOUT:?}"
);
}
#[test]
fn an_aggregate_budget_bounds_the_walk_tighter_than_one_command_timeout() {
let mut command = Command::new("sleep");
command.arg("120");
let started = Instant::now();
let error = run_probe(command, "wedged-tool", ProbeBudget::total(Duration::ZERO))
.expect_err("a hung probe must not succeed");
let elapsed = started.elapsed();
assert!(
elapsed < PROBE_TIMEOUT,
"an exhausted budget still waited {elapsed:?}, the per-command ceiling"
);
assert!(
error.contains("ran out of time"),
"an exhausted budget must blame the budget, not the tool, got: {error}"
);
}
#[test]
fn an_exec_failure_is_told_apart_from_a_refused_namespace() {
assert!(shell_failed_to_start(126));
assert!(shell_failed_to_start(127));
assert!(!shell_failed_to_start(1));
assert!(!shell_failed_to_start(0));
}
fn exit_status(code: i32) -> ExitStatus {
Command::new("sh")
.args(["-c", &format!("exit {code}")])
.status()
.expect("sh must run")
}
#[test]
fn a_refused_namespace_names_every_knob_that_could_be_responsible() {
let error = namespace_probe_error(exit_status(1), PrivateNetworkUse::ProxyOnlyEgress);
assert!(error.contains("refused"), "got: {error}");
for knob in [
"kernel.apparmor_restrict_unprivileged_userns",
"kernel.unprivileged_userns_clone",
"user.max_user_namespaces",
"user.max_net_namespaces",
] {
assert!(error.contains(knob), "must mention {knob}, got: {error}");
}
}
#[test]
fn a_shell_that_cannot_start_is_not_reported_as_a_refused_namespace() {
for code in [126, 127] {
let error =
namespace_probe_error(exit_status(code), PrivateNetworkUse::ProxyOnlyEgress);
assert!(error.contains("'sh'"), "must name the shell, got: {error}");
assert!(
!error.contains("apparmor"),
"must not offer namespace remedies, got: {error}"
);
}
}
fn on_path(tool: &str) -> bool {
Command::new("sh")
.args(["-c", &format!("command -v {tool} >/dev/null 2>&1")])
.status()
.is_ok_and(|status| status.success())
}
fn namespaces_are_available() -> bool {
Command::new("unshare")
.args([
"--user",
"--map-current-user",
"--keep-caps",
"--net",
"--",
"sh",
"-c",
":",
])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
fn iptables_uses_nf_tables() -> bool {
Command::new("iptables")
.arg("--version")
.output()
.is_ok_and(|output| String::from_utf8_lossy(&output.stdout).contains("nf_tables"))
}
#[test]
fn supervisor_script_changes_force_a_dependency_re_review() {
let digest = SUPERVISOR_SCRIPT
.bytes()
.filter(|byte| *byte != b'\r')
.fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
});
assert_eq!(
digest, EXPECTED_SUPERVISOR_SCRIPT_DIGEST,
"SUPERVISOR_SCRIPT changed. Re-check that probe_dependencies_uncached probes every \
binary the script runs (including those passed to `nsenter --`), update \
SUPERVISOR_EXTERNAL_COMMANDS, then set EXPECTED_SUPERVISOR_SCRIPT_DIGEST to {digest:#x}."
);
}
#[test]
fn every_listed_supervisor_command_is_actually_invoked() {
for (name, _) in SUPERVISOR_EXTERNAL_COMMANDS {
assert!(
SUPERVISOR_SCRIPT.contains(name),
"SUPERVISOR_EXTERNAL_COMMANDS lists '{name}', but SUPERVISOR_SCRIPT no longer \
runs it; drop the entry"
);
}
}
#[test]
fn commands_marked_probed_are_in_the_dependency_walk() {
let mut probed: Vec<&str> = vec!["slirp4netns", "unshare"];
probed.extend(RULE_TOOL_PROBES.iter().map(|(binary, _, _)| *binary));
for (name, coverage) in SUPERVISOR_EXTERNAL_COMMANDS {
if *coverage == SupervisorCommandCoverage::Probed {
assert!(
probed.contains(name),
"'{name}' is marked Probed but probe_dependencies_uncached never checks it"
);
}
}
}
#[test]
fn the_rule_tools_the_supervisor_runs_are_probed() {
for binary in ["nsenter", "iptables-restore", "ip6tables-restore"] {
assert!(
SUPERVISOR_SCRIPT.contains(binary),
"expected the supervisor to run '{binary}'"
);
assert!(
RULE_TOOL_PROBES
.iter()
.any(|(probed, _, _)| *probed == binary),
"the supervisor runs '{binary}' but the pre-flight walk never probes it"
);
}
}
#[test]
fn the_namespace_probe_covers_the_supervisor_shell() {
assert!(shell_failed_to_start(126));
assert!(shell_failed_to_start(127));
assert!(!shell_failed_to_start(1));
}
#[test]
fn the_cache_remembers_tools_but_re_checks_namespaces() {
use std::cell::RefCell;
let log = RefCell::new(Vec::new());
let counting = |program: &str, args: &[&str]| {
log.borrow_mut()
.push(format!("{program} {}", args.join(" ")));
walk_stub_for(program, None)
};
let namespace_runs = || {
log.borrow()
.iter()
.filter(|call| call.contains("--map-current-user"))
.count()
};
let stable_runs = || {
log.borrow()
.iter()
.filter(|call| call.starts_with("slirp4netns"))
.count()
};
let cache = OnceLock::new();
let run = |use_case| {
let _ =
probe_dependencies_caching(&cache, use_case, ProbeBudget::unbounded(), counting);
(stable_runs(), namespace_runs())
};
let after_first = run(PrivateNetworkUse::ProxyOnlyEgress);
let after_second = run(PrivateNetworkUse::ProxyOnlyEgress);
let after_other_use_case = run(PrivateNetworkUse::FirewallEnforcement);
assert_eq!(
after_second.0, after_first.0,
"a warm cache must not re-run the tool checks"
);
assert_eq!(
after_other_use_case.0, after_first.0,
"the cache is shared across use cases, which ask the same questions"
);
assert!(
after_second.1 > after_first.1 && after_other_use_case.1 > after_second.1,
"the namespace check must run on every call, warm cache or not: {after_first:?} \
then {after_second:?} then {after_other_use_case:?}"
);
}
#[test]
fn a_failed_walk_is_retried_rather_than_remembered() {
use std::cell::Cell;
let attempts = Cell::new(0_u32);
let cache = OnceLock::new();
let failing = |_: &str, _: &[&str]| {
attempts.set(attempts.get() + 1);
let mut command = Command::new("sh");
command.args(["-c", "exit 1"]);
command
};
probe_dependencies_caching(
&cache,
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
failing,
)
.expect_err("a host whose tooling fails must not be reported usable");
let after_first = attempts.get();
probe_dependencies_caching(
&cache,
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
failing,
)
.expect_err("the failure must not have been cached");
assert!(
attempts.get() > after_first,
"a failed walk must be re-run, not remembered"
);
}
#[test]
fn a_refused_namespace_is_reported_through_the_real_probe_path() {
let mut command = Command::new("sh");
command.args(["-c", "exit 1"]);
let error = check_private_namespaces(
command,
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
)
.expect_err("a non-zero namespace probe must fail the walk");
assert!(error.contains("refused"), "got: {error}");
assert!(
error.contains("kernel.apparmor_restrict_unprivileged_userns"),
"the refusal must still name the likely knobs, got: {error}"
);
}
#[test]
fn a_shell_exec_failure_is_reported_through_the_real_probe_path() {
for code in [126, 127] {
let mut command = Command::new("sh");
command.args(["-c", &format!("exit {code}")]);
let error = check_private_namespaces(
command,
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
)
.expect_err("an exec failure must fail the walk");
assert!(error.contains("'sh'"), "must name the shell, got: {error}");
assert!(
!error.contains("apparmor"),
"must not offer namespace remedies, got: {error}"
);
}
}
#[test]
fn a_granted_namespace_passes_the_real_probe_path() {
let mut command = Command::new("sh");
command.args(["-c", ":"]);
assert!(check_private_namespaces(
command,
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
)
.is_ok());
}
#[test]
fn the_namespace_probe_asks_for_both_namespaces_as_the_supervisor_does() {
let command = real_probe_command("unshare", &PRIVATE_NAMESPACE_PROBE_ARGS);
assert_eq!(command.get_program(), "unshare");
let args: Vec<String> = command
.get_args()
.map(|arg| arg.to_string_lossy().into_owned())
.collect();
for flag in ["--user", "--map-current-user", "--keep-caps", "--net"] {
assert!(
args.iter().any(|arg| arg == flag),
"the probe must request {flag}, got: {args:?}"
);
}
assert!(
args.windows(2)
.any(|pair| pair[0] == "sh" && pair[1] == "-c"),
"the probe must run the supervisor's shell, got: {args:?}"
);
}
fn walk_where_only(missing: Option<&'static str>) -> impl Fn(&str, &[&str]) -> Command {
move |program, _args| {
if Some(program) == missing {
return Command::new("mxc-probe-absent-tool-for-tests");
}
walk_stub_for(program, None)
}
}
fn walk_stub_for(program: &str, override_script: Option<&str>) -> Command {
let script = override_script.unwrap_or(match program {
"unshare" => "printf '%s\\n' '--map-current-user --keep-caps'",
"iptables" | "ip6tables" | "iptables-restore" | "ip6tables-restore" => {
"printf '%s\\n' 'iptables v1.8.9 (nf_tables)'"
}
_ => ":",
});
let mut command = Command::new("sh");
command.args(["-c", script]);
command
}
#[test]
fn the_dependency_walk_succeeds_when_every_tool_answers() {
assert_eq!(
probe_dependencies_with(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
walk_where_only(None),
),
Ok(())
);
}
#[test]
fn every_missing_tool_is_named_in_the_refusal() {
for tool in [
"slirp4netns",
"unshare",
"nsenter",
"iptables",
"ip6tables",
"iptables-restore",
"ip6tables-restore",
] {
let error = probe_dependencies_with(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
walk_where_only(Some(tool)),
)
.expect_err("a missing tool must fail the walk");
assert!(
error.contains(tool),
"a missing '{tool}' must be named, got: {error}"
);
assert!(
error.contains("network.proxy"),
"the refusal must name the config that required it, got: {error}"
);
}
}
#[test]
fn a_refusal_names_the_use_case_that_required_the_tool() {
let error = probe_dependencies_with(
PrivateNetworkUse::FirewallEnforcement,
ProbeBudget::unbounded(),
walk_where_only(Some("slirp4netns")),
)
.expect_err("a missing tool must fail the walk");
assert!(error.contains("enforcementMode"), "got: {error}");
assert!(!error.contains("omit network.proxy"), "got: {error}");
}
#[test]
fn a_tool_that_exits_non_zero_is_reported_as_a_broken_installation() {
let factory = |program: &str, _args: &[&str]| {
if program == "nsenter" {
return walk_stub_for(program, Some("exit 3"));
}
walk_stub_for(program, None)
};
let error = probe_dependencies_with(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
factory,
)
.expect_err("a broken tool must fail the walk");
assert!(error.contains("nsenter"), "got: {error}");
assert!(
error.contains("working"),
"a broken install must not be reported as missing, got: {error}"
);
}
#[test]
fn an_unshare_missing_the_required_flags_is_refused() {
for banner in [
"printf '%s\\n' 'usage: unshare'",
"printf '%s\\n' '--map-current-user'",
"printf '%s\\n' '--keep-caps'",
] {
let factory = move |program: &str, _args: &[&str]| {
if program == "unshare" {
return walk_stub_for(program, Some(banner));
}
walk_stub_for(program, None)
};
let error = probe_dependencies_with(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
factory,
)
.expect_err("an unshare without both flags must fail the walk");
assert!(
error.contains("--map-current-user") && error.contains("--keep-caps"),
"the refusal must name the flags it needs, got: {error}"
);
}
}
#[test]
fn a_walk_that_never_returns_still_answers_at_the_budget() {
static GATE: PreflightGate = PreflightGate::new();
let budget = Duration::from_millis(300);
let started = Instant::now();
let error = supervise_preflight_with(&GATE, budget, move || {
thread::sleep(Duration::from_secs(120));
Ok(())
})
.expect_err("a walk that never returns must not report support");
let elapsed = started.elapsed();
assert!(
elapsed < budget + Duration::from_secs(1),
"supervision must return at the budget, took {elapsed:?}"
);
assert!(
elapsed >= budget,
"it must actually wait out the budget, took {elapsed:?}"
);
assert!(
error.contains(&format!("{budget:?}")),
"the timeout must name the budget that ran out, got: {error}"
);
}
#[test]
fn a_walk_that_answers_is_reported_verbatim() {
static GATE: PreflightGate = PreflightGate::new();
assert_eq!(
supervise_preflight_with(&GATE, Duration::from_secs(5), || Ok(())),
Ok(())
);
assert_eq!(
supervise_preflight_with(&GATE, Duration::from_secs(5), || Err(
"slirp4netns missing".into()
)),
Err("slirp4netns missing".to_string())
);
}
#[test]
fn a_stranded_walk_refuses_the_next_caller_instead_of_stranding_another() {
static GATE: PreflightGate = PreflightGate::new();
let budget = Duration::from_millis(200);
supervise_preflight_with(&GATE, budget, || {
thread::sleep(Duration::from_secs(120));
Ok(())
})
.expect_err("the stranded walk must time out");
let error = supervise_preflight_with(&GATE, budget, || {
panic!("the gate must refuse before a second worker is started")
})
.expect_err("a host with a stranded probe cannot be confirmed");
assert!(
error.contains("did not return within"),
"the refusal must say a probe is still outstanding, got: {error}"
);
}
#[test]
fn an_overlapping_healthy_walk_is_waited_for_not_refused() {
static GATE: PreflightGate = PreflightGate::new();
let budget = Duration::from_secs(5);
let first = thread::spawn(move || {
supervise_preflight_with(&GATE, budget, || {
thread::sleep(Duration::from_millis(300));
Ok(())
})
});
thread::sleep(Duration::from_millis(50));
let second = supervise_preflight_with(&GATE, budget, || Ok(()));
assert_eq!(first.join().expect("first walk"), Ok(()));
assert_eq!(
second,
Ok(()),
"a caller overlapping a healthy walk must get the real answer"
);
}
#[test]
fn a_panicking_walk_releases_the_slot() {
static GATE: PreflightGate = PreflightGate::new();
let _ = supervise_preflight_with(&GATE, Duration::from_secs(5), || {
panic!("walk exploded");
});
assert_eq!(
supervise_preflight_with(&GATE, Duration::from_secs(5), || Ok(())),
Ok(()),
"the slot must survive a panicking walk"
);
}
#[test]
fn the_advisory_probe_returns_within_its_budget() {
let started = Instant::now();
let _ = probe_proxy_enforcement();
let elapsed = started.elapsed();
assert!(
elapsed < PRE_FLIGHT_BUDGET * 2,
"the advisory probe must honor its budget, took {elapsed:?}"
);
}
#[test]
fn the_whole_dependency_walk_passes_on_a_host_that_meets_every_requirement() {
const CHECKED_TOOLS: [&str; 8] = [
"slirp4netns",
"unshare",
"sh",
"nsenter",
"iptables",
"ip6tables",
"iptables-restore",
"ip6tables-restore",
];
let missing: Vec<&str> = CHECKED_TOOLS
.into_iter()
.filter(|tool| !on_path(tool))
.collect();
let equipped =
missing.is_empty() && namespaces_are_available() && iptables_uses_nf_tables();
let started = Instant::now();
let result = probe_proxy_enforcement();
let elapsed = started.elapsed();
assert!(
elapsed < PRE_FLIGHT_BUDGET * 2,
"the walk must stay near its budget, took {elapsed:?}"
);
if let Err(error) = result {
let out_of_budget =
error.contains("ran out of time") || error.contains("gave up while checking");
assert!(
!equipped || out_of_budget,
"a host with every dependency must pass the walk unless the \
pre-flight budget ran out, got: {error}"
);
if out_of_budget {
assert!(
CHECKED_TOOLS.iter().any(|tool| error.contains(tool)),
"a budget-exhausted walk must still name the check it \
abandoned, got: {error}"
);
} else {
assert!(
missing.iter().any(|tool| error.contains(tool))
|| error.contains("namespaces")
|| error.contains("iptables")
|| error.contains("ip6tables"),
"a failure must name what is missing or unusable, got: {error}"
);
}
}
}
#[test]
fn a_probe_returns_while_a_descendant_still_holds_its_output() {
let mut command = Command::new("sh");
command.args(["-c", "sleep 10 & echo banner"]);
let started = Instant::now();
let output = run_probe(command, "sh", ProbeBudget::unbounded())
.expect("the direct child exits immediately");
assert!(output.stdout.contains("banner"));
assert!(
started.elapsed() < Duration::from_secs(5),
"reading output must not wait for the descendant, took {:?}",
started.elapsed()
);
}
#[test]
fn a_clamped_command_blames_the_budget_rather_than_the_tool() {
let mut command = Command::new("sleep");
command.arg("120");
let error = run_probe(
command,
"innocent-tool",
ProbeBudget::total(Duration::from_millis(200)),
)
.expect_err("a hung probe must not succeed");
assert!(
!error.contains("hung"),
"a budget-clamped command must not be called hung, got: {error}"
);
assert!(
error.contains(&format!("{PRE_FLIGHT_BUDGET:?}")),
"the error must name the budget that ran out, got: {error}"
);
}
#[test]
fn a_command_that_outlives_its_own_ceiling_is_reported_as_hung() {
let budget = ProbeBudget::unbounded();
let (_, source) = budget.command_deadline();
assert_eq!(
source,
DeadlineSource::Command,
"an unbounded walk must attribute timeouts to the command itself"
);
}
#[test]
fn a_live_budget_clamps_a_hung_command_to_the_time_remaining() {
let mut command = Command::new("sleep");
command.arg("120");
let started = Instant::now();
let error = run_probe(
command,
"wedged-tool",
ProbeBudget::total(Duration::from_millis(200)),
)
.expect_err("a hung probe must not succeed");
let elapsed = started.elapsed();
assert!(
elapsed < PROBE_TIMEOUT,
"the command ran {elapsed:?}, ignoring the {:?} budget it was given",
Duration::from_millis(200)
);
assert!(
error.contains("wedged-tool"),
"a command that hung inside its budget must still name the tool, got: {error}"
);
}
#[test]
fn probe_returns_stdout_of_a_well_behaved_binary() {
let mut command = Command::new("sh");
command.args(["-c", "echo probe-stdout-marker"]);
let probe = run_probe(command, "echo", ProbeBudget::unbounded())
.expect("a fast probe must succeed");
assert!(
probe.status.success(),
"expected success, got {:?}",
probe.status
);
assert!(
probe.stdout.contains("probe-stdout-marker"),
"stdout was not captured, got: {:?}",
probe.stdout
);
}
#[test]
fn an_oversized_stream_is_refused_on_either_side() {
for stream in ["1", "2"] {
let mut command = Command::new("sh");
command.args([
"-c",
&format!(
"echo ok; dd if=/dev/zero bs=1024 count={} >&{stream} 2>/dev/null",
(probe_exec::MAX_PROBE_OUTPUT_BYTES / 1024) + 8
),
]);
let error = run_probe(command, "flooding-tool", ProbeBudget::unbounded())
.expect_err("a truncated stream must not be judged");
assert!(
error.contains("refusing to judge a truncated banner"),
"stream {stream} must be refused, got: {error}"
);
}
}
#[test]
fn probe_reports_a_failing_binary_without_treating_it_as_a_hang() {
let mut command = Command::new("sh");
command.args(["-c", "exit 3"]);
let probe = run_probe(command, "failing", ProbeBudget::unbounded())
.expect("a clean non-zero exit is not an error");
assert!(!probe.status.success(), "expected a non-zero exit status");
}
fn unreachable_lock(dir: &TempDir) -> std::path::PathBuf {
dir.path().join("no-such-dir").join("xtables.lock")
}
#[test]
fn the_nft_backend_is_accepted_even_when_the_lock_is_unreachable() {
let dir = tempfile::tempdir().expect("tempdir");
assert!(
iptables_backend_is_usable(
"iptables",
"iptables v1.8.10 (nf_tables)\n",
&unreachable_lock(&dir),
PrivateNetworkUse::ProxyOnlyEgress
)
.is_ok(),
"the nf_tables backend takes no lock, so an unreachable lock must not refuse it"
);
}
#[test]
fn the_legacy_backend_is_refused_when_it_could_not_take_the_lock() {
let dir = tempfile::tempdir().expect("tempdir");
let error = iptables_backend_is_usable(
"iptables",
"iptables v1.8.10 (legacy)\n",
&unreachable_lock(&dir),
PrivateNetworkUse::ProxyOnlyEgress,
)
.expect_err("a legacy backend with an unreachable lock cannot install rules");
assert!(
error.contains("iptables") && error.contains("nf_tables"),
"the error must name the binary and the backend to switch to: {error}"
);
}
#[test]
fn a_firewall_request_is_never_advised_about_the_proxy() {
let dir = tempfile::tempdir().expect("tempdir");
let error = iptables_backend_is_usable(
"iptables",
"iptables v1.8.10 (legacy)\n",
&unreachable_lock(&dir),
PrivateNetworkUse::FirewallEnforcement,
)
.expect_err("a legacy backend with an unreachable lock cannot install rules");
assert!(
!error.contains("network.proxy"),
"a firewall-only request must not be told about a field it never set: {error}"
);
assert!(
error.contains("network.enforcementMode='firewall'"),
"the error must name what the caller configured: {error}"
);
}
#[test]
fn a_proxy_request_is_never_advised_about_the_enforcement_mode() {
let dir = tempfile::tempdir().expect("tempdir");
let error = iptables_backend_is_usable(
"iptables",
"iptables v1.8.10 (legacy)\n",
&unreachable_lock(&dir),
PrivateNetworkUse::ProxyOnlyEgress,
)
.expect_err("a legacy backend with an unreachable lock cannot install rules");
assert!(
error.contains("network.proxy") && !error.contains("enforcementMode"),
"a proxy request must keep the proxy wording: {error}"
);
}
#[test]
fn each_private_network_use_names_itself_distinctly() {
let proxy = PrivateNetworkUse::ProxyOnlyEgress;
let firewall = PrivateNetworkUse::FirewallEnforcement;
for (a, b) in [
(proxy.requirement(), firewall.requirement()),
(proxy.remedy(), firewall.remedy()),
(proxy.mechanism(), firewall.mechanism()),
] {
assert!(!a.is_empty() && !b.is_empty(), "wording must not be empty");
assert_ne!(a, b, "the two use cases must not share wording");
}
}
#[test]
fn the_legacy_backend_is_accepted_when_the_lock_is_writable() {
let dir = tempfile::tempdir().expect("tempdir");
let lock = dir.path().join("xtables.lock");
fs::write(&lock, b"").expect("create lock");
assert!(
iptables_backend_is_usable(
"iptables",
"iptables v1.8.10 (legacy)\n",
&lock,
PrivateNetworkUse::ProxyOnlyEgress
)
.is_ok(),
"a legacy backend that can take its lock installs rules fine"
);
}
#[test]
fn an_absent_lock_in_a_writable_directory_is_usable() {
let dir = tempfile::tempdir().expect("tempdir");
assert!(
lock_is_writable(&dir.path().join("xtables.lock")),
"the lock is created on demand, so a writable directory is enough"
);
}
#[test]
fn a_banner_without_a_backend_marker_is_treated_as_legacy() {
let dir = tempfile::tempdir().expect("tempdir");
assert!(
iptables_backend_is_usable(
"iptables",
"iptables v1.6.1\n",
&unreachable_lock(&dir),
PrivateNetworkUse::ProxyOnlyEgress
)
.is_err(),
"a pre-1.8 build is legacy-only and must not be assumed usable"
);
}
#[test]
fn stderr_detail_keeps_the_tail_and_stays_bounded() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("supervisor.stderr");
let mut noise = "x".repeat(MAX_STDERR_TAIL as usize * 4);
noise.push_str("\nfatal: the-actual-failure\n");
fs::write(&path, &noise).expect("write stderr");
let detail = stderr_detail(&path);
assert!(
detail.contains("fatal: the-actual-failure"),
"the tail (where the failure is) was dropped: {detail}"
);
assert!(
detail.len() <= MAX_STDERR_TAIL as usize + 64,
"quoted stderr was not bounded, got {} bytes",
detail.len()
);
}
#[test]
fn stderr_detail_reports_absence_rather_than_an_empty_string() {
let dir = tempfile::tempdir().expect("tempdir");
let missing = dir.path().join("does-not-exist");
assert_eq!(stderr_detail(&missing), "no stderr output");
let empty = dir.path().join("empty.stderr");
fs::write(&empty, " \n").expect("write stderr");
assert_eq!(stderr_detail(&empty), "no stderr output");
}
const TEST_CHAIN: &str = "mxc-test-chain";
const TEST_INGRESS_CHAIN: &str = "mxc-test-ingress";
const FAKE_NSENTER: &str = r#"#!/bin/sh
count=$(cat "$MXC_TEST_COUNT" 2>/dev/null || echo 0)
count=$((count + 1))
printf '%s' "$count" > "$MXC_TEST_COUNT"
printf '%s\n' "$*" >> "$MXC_TEST_ARGS"
if [ "${MXC_TEST_FAIL_AT:-0}" = "$count" ]; then
echo "fake nsenter: forced failure on rule $count" >&2
exit 1
fi
tool=""
payload=""
for arg in "$@"; do
case "$arg" in
iptables-restore|ip6tables-restore) tool="${arg%-restore}" ;;
-*) ;;
*) [ -f "$arg" ] && payload="$arg" ;;
esac
done
if [ -n "$tool" ] && [ -z "$payload" ]; then
echo "fake nsenter: ${tool}-restore was given no payload file" >&2
exit 1
fi
if [ -n "$tool" ] && [ -n "$payload" ]; then
while IFS= read -r line; do
printf '%s %s\n' "$tool" "$line" >> "$MXC_TEST_PAYLOAD"
done < "$payload"
fi
exit 0
"#;
const FAKE_SLIRP: &str = r#"#!/bin/sh
echo $$ > "$MXC_TEST_SLIRP_PID"
if [ "${MXC_TEST_SLIRP_DIES:-0}" = "1" ]; then
echo "fake slirp4netns: exiting before readiness" >&2
exit 1
fi
printf ready >&9
exec sleep 30
"#;
struct FakeSupervisor {
dir: TempDir,
child: Child,
pid_writer: Option<File>,
_exit_writer: OwnedFd,
}
impl FakeSupervisor {
fn state_dir(&self) -> std::path::PathBuf {
self.dir.path().join("state")
}
fn rule_invocations(&self) -> u32 {
fs::read_to_string(self.dir.path().join("rules.count"))
.ok()
.and_then(|value| value.trim().parse().ok())
.unwrap_or(0)
}
fn signalled_ready(&self) -> bool {
self.state_dir().join("slirp.ready").exists()
}
fn rule_log(&self) -> Vec<String> {
fs::read_to_string(self.dir.path().join("rules.args"))
.unwrap_or_default()
.lines()
.map(str::to_owned)
.collect()
}
fn chain_rules(&self) -> Vec<String> {
let prefix = format!(" -A {TEST_CHAIN} ");
fs::read_to_string(self.dir.path().join("rules.payload"))
.unwrap_or_default()
.lines()
.filter_map(|line| {
let (tool, rest) = line.split_once(&prefix)?;
Some(format!("{tool} {rest}"))
})
.collect()
}
fn payload_lines(&self) -> Vec<String> {
fs::read_to_string(self.dir.path().join("rules.payload"))
.unwrap_or_default()
.lines()
.map(str::to_owned)
.collect()
}
fn stderr(&self) -> String {
stderr_detail(&self.dir.path().join("supervisor.stderr"))
}
fn publish_sandbox_pid(&mut self) {
let mut writer = self.pid_writer.take().expect("pid writer");
writer.write_all(b"4242\n").expect("publish pid");
}
fn abandon_without_publishing_pid(&mut self) {
drop(self.pid_writer.take());
}
fn wait_for_exit(&mut self) -> ExitStatus {
let deadline = Instant::now() + Duration::from_secs(20);
while Instant::now() < deadline {
if let Some(status) = self.child.try_wait().expect("try_wait") {
return status;
}
thread::sleep(Duration::from_millis(10));
}
panic!(
"supervisor did not exit; stderr: {}, rules run: {}",
self.stderr(),
self.rule_invocations()
);
}
fn wait_until_ready(&mut self) {
let deadline = Instant::now() + Duration::from_secs(20);
while Instant::now() < deadline {
if self.signalled_ready() {
return;
}
if let Some(status) = self.child.try_wait().expect("try_wait") {
panic!(
"supervisor exited ({status}) without signalling readiness; \
stderr: {}, rules run: {}",
self.stderr(),
self.rule_invocations()
);
}
thread::sleep(Duration::from_millis(10));
}
panic!(
"supervisor never signalled readiness; stderr: {}",
self.stderr()
);
}
}
impl Drop for FakeSupervisor {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
if let Ok(pid) = fs::read_to_string(self.dir.path().join("slirp.pid")) {
let pid = pid.trim();
if !pid.is_empty() {
let _ = Command::new("kill")
.args(["-9", pid])
.stderr(Stdio::null())
.status();
}
}
}
}
fn install_stub(path: &std::path::Path, body: &str) {
fs::write(path, body).expect("write stub");
let mut perms = fs::metadata(path).expect("stat stub").permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
fs::set_permissions(path, perms).expect("chmod stub");
}
fn spawn_fake_supervisor(fail_at: Option<u32>, slirp_dies: bool) -> FakeSupervisor {
spawn_fake_supervisor_with_plan(
&EgressPlan::for_proxy(SLIRP_HOST_GATEWAY_IP, 3128),
&denied_ingress(),
fail_at,
slirp_dies,
)
}
fn denied_ingress() -> IngressPlan {
IngressPlan::for_policy(&Default::default())
}
fn spawn_fake_supervisor_with_plan(
plan: &EgressPlan,
ingress: &IngressPlan,
fail_at: Option<u32>,
slirp_dies: bool,
) -> FakeSupervisor {
spawn_fake_supervisor_with_families(plan, ingress, rule_families(true), fail_at, slirp_dies)
}
fn spawn_fake_supervisor_with_families(
plan: &EgressPlan,
ingress: &IngressPlan,
families: &[RuleFamily],
fail_at: Option<u32>,
slirp_dies: bool,
) -> FakeSupervisor {
let dir = tempfile::tempdir().expect("tempdir");
let bin = dir.path().join("bin");
let state = dir.path().join("state");
fs::create_dir_all(&bin).expect("bin dir");
fs::create_dir_all(&state).expect("state dir");
for &family in families {
let payloads =
render_filter_payloads(plan, ingress, family, TEST_CHAIN, TEST_INGRESS_CHAIN);
for (index, payload) in payloads.iter().enumerate() {
fs::write(
state.join(payload_file_name(family, index, payloads.len())),
payload,
)
.expect("rules payload");
}
}
install_stub(&bin.join("nsenter"), FAKE_NSENTER);
install_stub(&bin.join("slirp4netns"), FAKE_SLIRP);
let stderr = File::create(dir.path().join("supervisor.stderr")).expect("stderr");
let (exit_reader, exit_writer) = pipe2(OFlag::O_CLOEXEC).expect("exit pipe");
let (pid_reader, pid_writer) = pipe2(OFlag::O_CLOEXEC).expect("pid pipe");
let path = format!(
"{}:{}",
bin.display(),
std::env::var("PATH").unwrap_or_default()
);
let mut command = Command::new("sh");
command
.args(["-c", SUPERVISOR_SCRIPT, "mxc-test-supervisor"])
.arg(&state)
.arg("1")
.env("PATH", path)
.env("MXC_TEST_COUNT", dir.path().join("rules.count"))
.env("MXC_TEST_ARGS", dir.path().join("rules.args"))
.env("MXC_TEST_PAYLOAD", dir.path().join("rules.payload"))
.env("MXC_TEST_SLIRP_PID", dir.path().join("slirp.pid"))
.env(
"MXC_TEST_FAIL_AT",
fail_at.map(|n| n.to_string()).unwrap_or_default(),
)
.env("MXC_TEST_SLIRP_DIES", if slirp_dies { "1" } else { "0" })
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr));
remap_descriptors(
&mut command,
[
(pid_reader.as_raw_fd(), SUPERVISOR_PID_FD),
(exit_reader.as_raw_fd(), SUPERVISOR_EXIT_FD),
],
);
let child = command.spawn().expect("spawn supervisor");
drop(exit_reader);
drop(pid_reader);
FakeSupervisor {
dir,
child,
pid_writer: Some(File::from(pid_writer)),
_exit_writer: exit_writer,
}
}
#[test]
fn each_family_is_restored_from_its_own_payload_in_one_transaction() {
let mut supervisor = spawn_fake_supervisor(None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
let calls = supervisor.rule_log();
assert_eq!(calls.len(), 2, "{calls:?}");
for (call, tool) in calls.iter().zip(["iptables-restore", "ip6tables-restore"]) {
assert!(call.contains(tool), "{calls:?}");
assert!(call.contains(" -n "), "restore must be additive: {call}");
}
for tool in ["iptables", "ip6tables"] {
let lines: Vec<String> = supervisor
.payload_lines()
.into_iter()
.filter_map(|line| line.strip_prefix(&format!("{tool} ")).map(str::to_owned))
.collect();
assert_eq!(lines.first().map(String::as_str), Some("*filter"), "{tool}");
assert_eq!(
lines[lines.len() - 3],
format!("-A OUTPUT -j {TEST_CHAIN}"),
"the {tool} egress hook must be committed with its chain"
);
assert_eq!(
lines[lines.len() - 2],
format!("-A INPUT -j {TEST_INGRESS_CHAIN}"),
"the {tool} ingress hook must be committed with its chain"
);
assert_eq!(lines.last().map(String::as_str), Some("COMMIT"), "{tool}");
}
}
#[test]
fn a_kernel_without_ipv6_is_enforced_by_the_ipv4_rules_alone() {
let mut supervisor = spawn_fake_supervisor_with_families(
&EgressPlan::for_proxy(SLIRP_HOST_GATEWAY_IP, 3128),
&denied_ingress(),
rule_families(false),
None,
false,
);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
let calls = supervisor.rule_log();
assert_eq!(calls.len(), 1, "{calls:?}");
assert!(calls[0].contains("iptables-restore"), "{calls:?}");
assert!(!calls[0].contains("ip6tables-restore"), "{calls:?}");
let lines = supervisor.payload_lines();
assert!(
lines.contains(&format!("iptables -A OUTPUT -j {TEST_CHAIN}")),
"the IPv4 egress hook must still be installed: {lines:?}"
);
assert!(
lines.iter().all(|line| line.starts_with("iptables ")),
"{lines:?}"
);
}
#[test]
fn a_missing_ipv4_payload_still_kills_the_supervisor() {
let mut supervisor = spawn_fake_supervisor_with_families(
&EgressPlan::for_proxy(SLIRP_HOST_GATEWAY_IP, 3128),
&denied_ingress(),
&[RuleFamily::V6],
None,
false,
);
supervisor.publish_sandbox_pid();
let status = supervisor.wait_for_exit();
assert!(!status.success(), "{status}");
assert!(
!supervisor.signalled_ready(),
"readiness must never follow a missing IPv4 payload"
);
assert!(
!supervisor
.rule_log()
.iter()
.any(|call| call.contains("ip6tables-restore")),
"the supervisor must stop at the first failed family"
);
}
#[test]
fn the_supervisor_installs_the_inbound_chain_alongside_the_outbound_one() {
let mut supervisor = spawn_fake_supervisor(None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
for tool in ["iptables", "ip6tables"] {
let lines: Vec<String> = supervisor
.payload_lines()
.into_iter()
.filter_map(|line| line.strip_prefix(&format!("{tool} ")).map(str::to_owned))
.collect();
assert!(
lines.contains(&format!(":{TEST_INGRESS_CHAIN} - [0:0]")),
"{tool} must declare the inbound chain: {lines:?}"
);
assert!(
lines
.iter()
.any(|line| line.contains("ESTABLISHED,RELATED -j ACCEPT")),
"{tool} must keep replies flowing: {lines:?}"
);
}
assert_eq!(
supervisor.rule_log().len(),
2,
"the inbound chain must not cost an extra transaction"
);
}
#[test]
fn the_supervisor_signals_readiness_only_after_every_rule_is_installed() {
let mut supervisor = spawn_fake_supervisor(None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
assert_eq!(
supervisor.rule_invocations(),
2,
"readiness was signalled after a different number of restores than the \
startup budget is sized for; stderr: {}",
supervisor.stderr()
);
}
#[test]
fn a_policy_plan_installs_a_fixed_number_of_commands() {
for rule_count in [0, 1, 5, 50] {
let plan = plan_with_rule_count(rule_count);
let mut supervisor =
spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
assert_eq!(
supervisor.rule_invocations(),
2,
"a {rule_count}-rule policy installed the wrong number of commands; \
stderr: {}",
supervisor.stderr()
);
assert_eq!(
supervisor
.chain_rules()
.iter()
.filter(|rule| rule.contains(" -d "))
.count(),
rule_count,
"a {rule_count}-rule policy reached iptables with the wrong rule count"
);
}
}
#[test]
fn a_policy_too_large_for_one_transaction_is_split_and_still_arrives_whole() {
let rule_count = 2000;
let plan = plan_with_rule_count(rule_count);
let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
assert!(
supervisor.rule_invocations() > 2,
"a {rule_count}-rule policy must not fit two transactions, or this test \
is not exercising the split"
);
let installed: Vec<String> = supervisor
.chain_rules()
.into_iter()
.filter(|rule| rule.contains(" -d "))
.collect();
assert_eq!(
installed.len(),
rule_count,
"splitting dropped rules; stderr: {}",
supervisor.stderr()
);
for (index, rule) in installed.iter().enumerate() {
let expected = format!(" -d 10.0.{}.{} ", index / 256, index % 256);
assert!(
rule.contains(&expected),
"rule {index} arrived out of order: {rule}"
);
}
}
#[test]
fn a_failed_rule_kills_the_supervisor_instead_of_signalling_readiness() {
let plan = plan_with_rule_count(3);
for rule in 1..=2 {
let mut supervisor =
spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), Some(rule), false);
supervisor.publish_sandbox_pid();
let status = supervisor.wait_for_exit();
assert!(
!status.success(),
"restore {rule} failed but the supervisor exited successfully; stderr: {}",
supervisor.stderr()
);
assert!(
!supervisor.signalled_ready(),
"restore {rule} failed yet the sandbox was signalled ready -- it would \
have run with unenforced egress"
);
assert_eq!(
supervisor.rule_invocations(),
rule,
"restore {rule} failed but the script carried on installing rules"
);
}
}
#[test]
fn a_block_policy_accepts_only_its_allowlist_and_closes_both_families() {
let mut request = crate::mxc_common::models::ExecutionRequest::default();
request.policy.default_network_policy = crate::mxc_common::models::NetworkPolicy::Block;
request.policy.allowed_hosts = vec!["203.0.113.7".into(), "2001:db8::/32".into()];
let plan = EgressPlan::for_policy(&request).expect("literals must build a plan");
let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
assert_eq!(
supervisor.chain_rules(),
vec![
"iptables -o lo -j ACCEPT".to_string(),
"iptables -d 203.0.113.7 -j ACCEPT".to_string(),
"iptables -j DROP".to_string(),
"ip6tables -o lo -j ACCEPT".to_string(),
"ip6tables -d 2001:db8::/32 -j ACCEPT".to_string(),
"ip6tables -j DROP".to_string(),
],
"stderr: {}",
supervisor.stderr()
);
}
#[test]
fn an_allow_policy_denies_its_blocklist_before_the_open_terminal() {
let mut request = crate::mxc_common::models::ExecutionRequest::default();
request.policy.default_network_policy = crate::mxc_common::models::NetworkPolicy::Allow;
request.policy.blocked_hosts = vec!["198.51.100.0/24".into()];
request.policy.allowed_hosts = vec!["198.51.100.9".into()];
let plan = EgressPlan::for_policy(&request).expect("literals must build a plan");
let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
let rules = supervisor.chain_rules();
let deny = rules
.iter()
.position(|rule| rule == "iptables -d 198.51.100.0/24 -j DROP")
.expect("the deny must be installed");
let allow = rules
.iter()
.position(|rule| rule == "iptables -d 198.51.100.9 -j ACCEPT")
.expect("the allow must be installed");
let terminal = rules
.iter()
.position(|rule| rule == "iptables -j ACCEPT")
.expect("an allow policy must end in ACCEPT");
assert!(
deny < allow,
"the narrower deny must be evaluated first, or it never matches: {rules:?}"
);
assert!(
allow < terminal,
"the open terminal must come last: {rules:?}"
);
}
#[test]
fn the_proxy_posture_is_unchanged_by_the_rule_list() {
let plan = EgressPlan::for_proxy(Ipv4Addr::new(10, 1, 2, 3), 3128);
let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
assert_eq!(
supervisor.chain_rules(),
vec![
"iptables -o lo -j ACCEPT".to_string(),
"iptables -p tcp -d 10.1.2.3 --dport 3128 -j ACCEPT".to_string(),
"iptables -j DROP".to_string(),
"ip6tables -o lo -j ACCEPT".to_string(),
"ip6tables -j DROP".to_string(),
],
"stderr: {}",
supervisor.stderr()
);
}
#[test]
fn a_v4_only_policy_still_closes_ipv6() {
let mut request = crate::mxc_common::models::ExecutionRequest::default();
request.policy.default_network_policy = crate::mxc_common::models::NetworkPolicy::Block;
request.policy.allowed_hosts = vec!["203.0.113.7".into()];
let plan = EgressPlan::for_policy(&request).expect("literals must build a plan");
let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
supervisor.publish_sandbox_pid();
supervisor.wait_until_ready();
assert!(
supervisor
.chain_rules()
.contains(&"ip6tables -j DROP".to_string()),
"IPv6 was left open by a v4-only policy: {:?}",
supervisor.chain_rules()
);
}
#[test]
fn the_supervisor_gives_up_when_slirp_dies_before_signalling_readiness() {
let mut supervisor = spawn_fake_supervisor(None, true);
supervisor.publish_sandbox_pid();
let status = supervisor.wait_for_exit();
assert!(!status.success(), "a dead slirp must fail the startup");
assert!(!supervisor.signalled_ready());
assert!(
supervisor.stderr().contains("before signalling readiness"),
"the failure must say slirp never came up: {}",
supervisor.stderr()
);
assert_eq!(
supervisor.rule_invocations(),
0,
"rules were installed against a namespace with no connectivity"
);
}
#[test]
fn the_supervisor_exits_when_the_parent_never_publishes_the_sandbox_pid() {
let mut supervisor = spawn_fake_supervisor(None, false);
supervisor.abandon_without_publishing_pid();
let status = supervisor.wait_for_exit();
assert!(
!status.success(),
"an unpublished PID must fail the startup"
);
assert!(!supervisor.signalled_ready());
assert!(
supervisor.stderr().contains("before publishing"),
"the failure must name the missing PID: {}",
supervisor.stderr()
);
assert_eq!(supervisor.rule_invocations(), 0);
}
fn namespace_running(script: &str) -> ProxyNetworkNamespace {
let state_dir = tempfile::tempdir().expect("tempdir");
let stderr = File::create(state_dir.path().join("supervisor.stderr")).expect("stderr");
let supervisor = Command::new("sh")
.args(["-c", script])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr))
.spawn()
.expect("spawn supervisor");
ProxyNetworkNamespace {
state_dir,
supervisor,
exit_writer: None,
pid_writer: None,
userns: None,
hosts: None,
liveness_reader: None,
transactions: 0,
script_timeout_ms: 0,
}
}
fn await_exit(namespace: &mut ProxyNetworkNamespace) {
let deadline = Instant::now() + Duration::from_secs(20);
while Instant::now() < deadline {
if namespace.supervisor.try_wait().expect("try_wait").is_some() {
return;
}
thread::sleep(Duration::from_millis(10));
}
panic!("supervisor did not exit");
}
#[test]
fn the_gate_check_passes_while_the_supervisor_is_running() {
let mut network = namespace_running("sleep 30");
assert!(
network.check_alive().is_ok(),
"a running supervisor must not block the workload"
);
}
#[test]
fn the_gate_check_refuses_a_supervisor_that_died_after_signalling_readiness() {
let mut network = namespace_running("echo 'slirp4netns: crashed' >&2; exit 1");
await_exit(&mut network);
let error = network
.check_alive()
.expect_err("a dead supervisor must not reach the workload");
assert!(
error.contains("no network provider"),
"the failure must name the lost provider rather than read as a workload \
error: {error}"
);
assert!(
error.contains("slirp4netns: crashed"),
"the failure must carry what the supervisor wrote: {error}"
);
}
#[test]
fn the_gate_check_refuses_even_a_supervisor_that_exited_cleanly() {
let mut network = namespace_running("exit 0");
await_exit(&mut network);
assert!(
network.check_alive().is_err(),
"a successful exit still leaves the sandbox with no route"
);
}
}