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, FromRawFd, 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, PoisonError};
use std::thread;
use std::time::{Duration, Instant};
use crate::mxc_common::filesystem_resolve::{resolve_mount_order, FsIntent};
use crate::mxc_common::filesystem_symlink::resolve_through_symlinks;
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainerPolicy, ProxyAddress, ProxyHostPin};
use crate::mxc_common::sandbox_process::group_kill;
use crate::mxc_common::termination_signals;
use nix::errno::Errno;
use nix::fcntl::{fcntl, FcntlArg, FdFlag, OFlag};
use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
use nix::sys::wait::{waitid, Id, WaitPidFlag, WaitStatus};
use nix::unistd::{access, dup2, pipe2, AccessFlags, Pid};
use tempfile::TempDir;
use crate::bwrap_common::bwrap_command::{path_is_denied, PolicyMount, COMMAND_TAIL};
use crate::bwrap_common::host_tools::{self, LookupError};
use crate::bwrap_common::identity::{read_as_workload, RootIdentity};
use crate::bwrap_common::network_rules::{
payload_file_name, render_filter_payloads, EgressPlan, IngressPlan, RuleFamily,
};
use crate::bwrap_common::probe_exec;
use crate::bwrap_common::resolver_file::{resolver_target_is_denied, sandbox_mount_path};
pub(crate) 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 SANDBOX_RESOLV_CONF_PATH: &str = "/etc/resolv.conf";
const SLIRP_DNS_FORWARDER: &str = "10.0.2.3";
pub(crate) const SLIRP_DNS_FORWARDER_IP: Ipv4Addr = Ipv4Addr::new(10, 0, 2, 3);
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"
# Use the absolute tool paths checked by the parent.
nsenter="$3"
ip="$4"
slirp4netns="$5"
iptables_restore="$6"
ip6tables_restore="$7"
sleep="$8"
unshare="$9"
slirp_sandbox="${10}"
# Dash redirections need fixed single-digit descriptors.
# 3 carries the sandbox PID and reaches EOF if the parent exits before sending it.
# 4 controls slirp's lifetime.
printf ready > "$state_dir/userns.ready"
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
# Wait for Bubblewrap's loopback setup before slirp creates the same address.
ns="/proc/$child_pid/ns/net"
while :; do
loopback=$("$nsenter" --net="$ns" -- "$ip" -4 -o address show dev lo up) || {
echo "mxc: failed to query Bubblewrap loopback readiness" >&2
exit 1
}
case "$loopback" in
*" inet 127.0.0.1/8 "*) break ;;
esac
"$sleep" 0.01
done
# Slirp readiness alone must not release the workload.
exec 9> "$state_dir/slirp.internal"
# A root supervisor keeps host privileges, so slirp sheds them before it handles packets.
# Slirp's sandbox detaches its old root, so a private mount namespace keeps host mounts in place.
if [ "$slirp_sandbox" = yes ]; then
set -- "$unshare" --mount --propagation private -- \
"$slirp4netns" --enable-sandbox --enable-seccomp
else
set -- "$slirp4netns"
fi
"$@" --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
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."
# One restore is one bounded kernel transaction, so large rule sets arrive in several.
# The final transaction installs the hooks after the earlier rules exist.
for payload in "$state_dir"/rules.v4.*; do
# -w waits for the host's legacy xtables lock, which concurrent sandboxes share
# because nsenter keeps the host's mount namespace. -n preserves earlier transactions.
"$nsenter" --net="$ns" -- "$iptables_restore" -w "$lock_wait" -n "$payload" || { echo "$conntrack_hint" >&2; exit 1; }
done
# A kernel without IPv6 has no IPv6 payloads.
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
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,
}
#[derive(Debug)]
pub(crate) enum ProxyResolveError {
Rejected(String),
Lookup(String),
}
impl ProxyResolveError {
pub(crate) fn message(&self) -> &str {
match self {
Self::Rejected(message) | Self::Lookup(message) => message,
}
}
}
impl std::fmt::Display for ProxyResolveError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.message())
}
}
impl From<String> for ProxyResolveError {
fn from(message: String) -> Self {
Self::Rejected(message)
}
}
impl SandboxProxy {
pub(crate) fn resolve(configured: &ProxyAddress) -> Result<Self, ProxyResolveError> {
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.map_err(|error| error.message().to_string())
}
fn inspect_without_resolving(
configured: &ProxyAddress,
) -> (bool, Result<(), ProxyResolveError>) {
let asked_to_resolve = Cell::new(false);
let checked = Self::resolve_with(configured, |_, _| {
asked_to_resolve.set(true);
Err(ProxyResolveError::Lookup(String::new()))
});
(asked_to_resolve.get(), checked.map(|_| ()))
}
fn resolve_with(
configured: &ProxyAddress,
resolve: impl Fn(&str, u16) -> Result<Ipv4Addr, ProxyResolveError>,
) -> Result<Self, ProxyResolveError> {
if configured.port() == 0 {
return Err(
"Bubblewrap: proxy-only egress requires a non-zero proxy port"
.to_string()
.into(),
);
}
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 Ok(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()
)
.into());
}
return Err(ipv6_unsupported(host).into());
}
if is_reserved_loopback_name {
return Ok(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, ProxyResolveError> {
let query = host.to_string();
let waited = with_deadline(RESOLVE_TIMEOUT_LABEL, RESOLVE_TIMEOUT, move || {
lookup_ipv4(&query, port)
})
.map_err(|error| {
ProxyResolveError::Lookup(format!(
"Bubblewrap: could not start the lookup of proxy host '{host}': {error}"
))
})?;
match waited {
Ok(resolved) => resolved,
Err(mpsc::RecvTimeoutError::Timeout) => Err(ProxyResolveError::Lookup(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(ProxyResolveError::Lookup(format!(
"Bubblewrap: the lookup of proxy host '{host}' ended without an answer."
))),
}
}
fn lookup_ipv4(host: &str, port: u16) -> Result<Ipv4Addr, ProxyResolveError> {
let resolved: Vec<IpAddr> = (host, port)
.to_socket_addrs()
.map_err(|error| {
ProxyResolveError::Lookup(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(ProxyResolveError::Lookup(format!(
"Bubblewrap: proxy host '{host}' did not resolve to any address."
)))
} else {
Err(ipv6_unsupported(host).into())
}
}
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>,
_pins: Vec<File>,
}
impl BwrapStartup {
pub(crate) fn configure(args: &mut Vec<String>) -> Result<Self, String> {
let (info_reader, info_writer) = pipe_above_stdio()?;
let (gate_reader, gate_writer) = pipe_above_stdio()?;
args.splice(
0..0,
[
"--info-fd".to_string(),
info_writer.as_raw_fd().to_string(),
"--block-fd".to_string(),
gate_reader.as_raw_fd().to_string(),
],
);
Ok(Self {
inheritable: vec![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),
_pins: Vec::new(),
})
}
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: &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 has_exited_unreaped(child.id())
.map_err(|error| format!("Bubblewrap: failed to inspect bwrap startup: {error}"))?
{
return Err("Bubblewrap: bwrap exited before publishing child information".into());
}
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: Supervisor,
exit_writer: Option<OwnedFd>,
pid_writer: Option<OwnedFd>,
userns: Option<File>,
hosts: Option<PathBuf>,
resolver: Option<(String, String)>,
liveness_reader: Option<OwnedFd>,
transactions: usize,
script_timeout_ms: u32,
}
impl ProxyNetworkNamespace {
#[allow(clippy::too_many_arguments)]
pub(crate) fn start(
tools: &NetworkTools,
plan: &EgressPlan,
ingress: &IngressPlan,
pin: Option<&ProxyHostPin>,
resolver: Option<&ResolverPin>,
logger: &mut Logger,
script_timeout_ms: u32,
workload_userns: Option<&File>,
identity: Option<RootIdentity>,
) -> 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) = pipe_above_stdio()?;
let (pid_reader, pid_writer) = pipe_above_stdio()?;
let (liveness_reader, liveness_writer) = pipe_above_stdio()?;
set_nonblocking(liveness_reader.as_raw_fd())?;
let mut command = if workload_userns.is_some() {
Command::new(&tools.sh)
} else {
let mut command = Command::new(&tools.unshare);
command
.args(["--user", "--map-current-user", "--keep-caps", "--"])
.arg(&tools.sh);
command
};
let slirp_sandbox = if workload_userns.is_some() {
"yes"
} else {
"no"
};
termination_signals::unblock_in_child(&mut command);
command
.args(["-c", SUPERVISOR_SCRIPT, "mxc-bwrap-proxy-supervisor"])
.arg(state_dir.path())
.arg(XTABLES_LOCK_WAIT.as_secs().to_string())
.args(tools.supervisor_arguments())
.arg(slirp_sandbox)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr))
.process_group(0);
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(Supervisor::new).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,
) {
let _ = supervisor.terminate();
return Err(format!(
"{error}. If unshare was refused, check AppArmor's \
kernel.apparmor_restrict_unprivileged_userns setting and the \
kernel.unprivileged_userns_clone and user.max_user_namespaces limits"
));
}
let userns_path = format!("/proc/{}/ns/user", supervisor.id());
let userns = match workload_userns
.map(File::try_clone)
.unwrap_or_else(|| File::open(&userns_path))
.and_then(|file| above_stdio(file).map_err(std::io::Error::from))
{
Ok(file) => file,
Err(error) => {
let _ = supervisor.terminate();
return Err(format!(
"Bubblewrap: failed to open proxy user namespace {userns_path}: {error}"
));
}
};
logger.log_line("Bubblewrap: created private network supervisor");
let hosts = match pin {
Some(pin) => {
let path = state_dir.path().join("hosts");
if let Err(error) = write_pinned_hosts(&path, pin, identity) {
let _ = supervisor.terminate();
return Err(error);
}
logger.log_line(&format!(
"Bubblewrap: pinned proxy host '{}' to {} for the sandbox",
pin.hostname(),
pin.ip()
));
Some(path)
}
None => None,
};
let resolver = stage_resolver(resolver, state_dir.path(), logger);
Ok(Self {
state_dir,
supervisor,
exit_writer: Some(exit_writer),
pid_writer: Some(pid_writer),
userns: Some(userns),
hosts,
resolver,
liveness_reader: Some(liveness_reader),
transactions,
script_timeout_ms,
})
}
pub(crate) fn resolver_pinned(&self) -> bool {
self.resolver.is_some()
}
pub(crate) fn configure_bwrap(
&self,
args: &mut Vec<String>,
logger: &mut Logger,
) -> Result<BwrapStartup, String> {
let userns = self
.userns
.as_ref()
.ok_or_else(|| "Bubblewrap: proxy user namespace is already handed off".to_string())?;
let mut pins = Vec::new();
if let Some(hosts) = &self.hosts {
let file = open_pin(hosts)?;
if insert_hosts_bind(args, file.as_raw_fd())? {
logger.log_line(
"Bubblewrap: the proxy host pin overrides an earlier mount of \
/etc/hosts; the sandbox sees the pinned file",
);
}
pins.push(file);
}
if let Some((source, destination)) = &self.resolver {
let file = open_pin(Path::new(source))?;
if insert_pin_bind(args, file.as_raw_fd(), destination)? {
logger.log_line(&format!(
"Bubblewrap: the resolver pin overrides an earlier mount of {destination}; \
the sandbox sees the pinned file"
));
}
pins.push(file);
}
let mut startup = BwrapStartup::configure(args)?;
args.splice(
0..0,
["--userns".to_string(), userns.as_raw_fd().to_string()],
);
startup.inheritable.push(userns.as_raw_fd());
startup
.inheritable
.extend(pins.iter().map(AsRawFd::as_raw_fd));
startup._pins = pins;
Ok(startup)
}
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 timeout = rule_install_timeout(self.transactions, self.script_timeout_ms);
self.attach_within(child_pid, timeout, logger)
}
fn attach_within(
&mut self,
child_pid: u32,
timeout: Duration,
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",
timeout,
)?;
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.poll() {
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.poll() {
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.poll() {
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"))
));
let _ = self.supervisor.terminate();
return;
}
Err(error) => {
logger.log_line(&format!(
"WARNING: Bubblewrap: failed to inspect slirp4netns shutdown: {error}"
));
let _ = self.supervisor.terminate();
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_FLAGS: [&str; 5] =
["--user", "--map-current-user", "--keep-caps", "--net", "--"];
fn private_namespace_probe<F>(tools: &NetworkTools, command: &F) -> Command
where
F: Fn(&Path, &[&str]) -> Command,
{
let mut probe = command(&tools.unshare, &PRIVATE_NAMESPACE_PROBE_FLAGS);
probe.arg(&tools.sh).args(["-c", ":"]);
probe
}
fn check_private_namespaces(
command: Command,
shell: &Path,
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, shell, use_case));
}
Ok(())
}
fn shell_failed_to_start(code: i32) -> bool {
matches!(code, 126 | 127)
}
fn namespace_probe_error(status: ExitStatus, shell: &Path, use_case: PrivateNetworkUse) -> String {
let requirement = use_case.requirement();
if status.code().is_some_and(shell_failed_to_start) {
return format!(
"Bubblewrap: {requirement} runs its network supervisor with '{}', which could not \
start inside the new namespace. Install a working POSIX shell or {}.",
shell.display(),
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,
identity: Option<RootIdentity>,
) -> Result<(), String> {
let existing = match read_as_workload(identity, Path::new(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
}
#[derive(Debug)]
pub(crate) struct ResolverPin {
destination: String,
contents: String,
}
impl ResolverPin {
pub(crate) fn for_host(
policy: &ContainerPolicy,
mounts: &[PolicyMount],
identity: Option<RootIdentity>,
logger: &mut Logger,
) -> Option<Self> {
Self::from_resolver(
Path::new(SANDBOX_RESOLV_CONF_PATH),
policy,
mounts,
identity,
logger,
)
}
pub(crate) fn from_resolver(
resolver_path: &Path,
policy: &ContainerPolicy,
mounts: &[PolicyMount],
identity: Option<RootIdentity>,
logger: &mut Logger,
) -> Option<Self> {
let shown = resolver_path.display();
let host_contents = match read_as_workload(identity, resolver_path) {
Ok(contents) => contents,
Err(error) if error.kind() == ErrorKind::NotFound => return None,
Err(error) => {
logger.warning_line(&format!(
"WARNING: Bubblewrap: {shown} could not be read ({error}), so the sandbox \
keeps whatever resolver it inherits and names may not resolve inside it."
));
return None;
}
};
if !resolvers_are_loopback_only(&host_contents) {
return None;
}
let destination = match resolver_target_of(resolver_path) {
Ok(destination) => destination,
Err(reason) => {
logger.warning_line(&format!(
"WARNING: Bubblewrap: the host resolves through a loopback nameserver, which \
the sandbox's private network namespace cannot reach, and {reason}. Names \
will not resolve inside the sandbox; point {shown} at a routable nameserver."
));
return None;
}
};
let destination_text = match destination.to_str() {
Some(text) => text.to_string(),
None => {
logger.warning_line(&format!(
"WARNING: Bubblewrap: the host resolves through a loopback nameserver, but \
{} is not valid UTF-8 and cannot be named to bwrap, so the sandbox keeps \
the host's unreachable resolver. Names will not resolve inside the sandbox.",
destination.display()
));
return None;
}
};
let sandbox_destination = sandbox_mount_path(&destination_text);
let covering_mount = mounts
.iter()
.rfind(|mount| Path::new(&sandbox_destination).starts_with(&mount.destination));
if resolver_target_is_denied(policy, &destination)
|| covering_mount.is_some_and(|mount| mount.intent == FsIntent::Denied)
{
logger.warning_line(&format!(
"WARNING: Bubblewrap: the host resolves through a loopback nameserver, but the \
filesystem policy denies {destination_text}, so the sandbox keeps the host's \
unreachable resolver. Names will not resolve inside the sandbox; remove that \
path from deniedPaths to let the sandbox use slirp's forwarder."
));
return None;
}
if policy_names_path(policy, &resolver_path.to_string_lossy())
|| policy_names_path(policy, &destination_text)
|| covering_mount.is_some_and(|mount| {
Path::new(&mount.destination) == Path::new(&sandbox_destination)
})
{
logger.warning_line(&format!(
"WARNING: Bubblewrap: the filesystem policy mounts its own resolver, so the \
sandbox keeps it rather than slirp's forwarder — but that file names only \
loopback nameservers, which the sandbox's private network namespace cannot \
reach, so names will not resolve inside it. Point {shown} at a routable \
nameserver, or drop the grant on it to let the sandbox use slirp's forwarder."
));
return None;
}
Some(Self {
destination: destination_text,
contents: render_pinned_resolv_conf(&host_contents),
})
}
fn stage(&self, directory: &Path) -> Result<(String, String), String> {
let source = directory.join("resolv.conf");
fs::write(&source, &self.contents)
.map_err(|error| format!("Bubblewrap: failed to write the resolver pin: {error}"))?;
let source = source.to_str().ok_or_else(|| {
format!(
"Bubblewrap: the staged resolver path {} is not valid UTF-8",
source.display()
)
})?;
Ok((source.to_string(), sandbox_mount_path(&self.destination)))
}
}
fn stage_resolver(
resolver: Option<&ResolverPin>,
directory: &Path,
logger: &mut Logger,
) -> Option<(String, String)> {
let resolver = resolver?;
match resolver.stage(directory) {
Ok(staged) => {
logger.log_line(&format!(
"Bubblewrap: the host resolves through a loopback nameserver, so the sandbox \
reads {} with nameserver {SLIRP_DNS_FORWARDER}",
staged.1
));
Some(staged)
}
Err(error) => {
logger.warning_line(&format!(
"WARNING: {error}. The sandbox keeps the host's loopback nameserver, which its \
private network namespace cannot reach, so names will not resolve inside it."
));
None
}
}
}
fn resolvers_are_loopback_only(contents: &str) -> bool {
let mut saw_ipv4_loopback = false;
for value in nameserver_values(contents) {
let literal = value.split('%').next().unwrap_or(value);
match literal.parse::<IpAddr>() {
Ok(address) if address.is_loopback() => saw_ipv4_loopback |= address.is_ipv4(),
_ => return false,
}
}
saw_ipv4_loopback
}
fn render_pinned_resolv_conf(contents: &str) -> String {
let mut out = format!("nameserver {SLIRP_DNS_FORWARDER}\n");
for line in contents.lines().filter(|line| {
directive_keyword(line).is_some_and(|keyword| CARRIED_DIRECTIVES.contains(&keyword))
}) {
out.push_str(line);
out.push('\n');
}
out
}
const CARRIED_DIRECTIVES: &[&str] = &["search", "domain", "sortlist", "options"];
fn directive_keyword(line: &str) -> Option<&str> {
if line.starts_with(char::is_whitespace) {
return None;
}
line.split_whitespace().next()
}
fn nameserver_values(contents: &str) -> impl Iterator<Item = &str> {
contents
.lines()
.filter(|line| is_nameserver_line(line))
.filter_map(|line| line.split_whitespace().nth(1))
}
fn is_nameserver_line(line: &str) -> bool {
directive_keyword(line) == Some("nameserver")
}
fn resolver_target_of(start: &Path) -> Result<PathBuf, String> {
let resolved = resolve_through_symlinks(start)
.ok_or_else(|| format!("{} is not a resolvable path", start.display()))?;
if let Some(error) = resolved.error {
return Err(format!(
"{} could not be resolved ({error})",
start.display()
));
}
let resolved = resolved.path;
let metadata = fs::symlink_metadata(&resolved)
.map_err(|error| format!("{} could not be read ({error})", resolved.display()))?;
if !metadata.file_type().is_file() {
return Err(format!(
"{} does not resolve to a regular file",
resolved.display()
));
}
Ok(resolved)
}
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 {
path_is_denied(policy, SANDBOX_HOSTS_PATH)
}
fn policy_names_path(policy: &ContainerPolicy, target: &str) -> bool {
resolve_mount_order(policy)
.iter()
.any(|mount| mount.path.trim_end_matches('/') == target)
}
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_pin_bind(
args: &mut Vec<String>,
source: RawFd,
destination: &str,
) -> Result<bool, String> {
let separator = command_separator(args)?;
let overrides = args[..separator].iter().any(|arg| arg == destination);
args.splice(
separator..separator,
[
"--ro-bind-data".to_string(),
source.to_string(),
destination.to_string(),
],
);
Ok(overrides)
}
fn insert_hosts_bind(args: &mut Vec<String>, hosts: RawFd) -> Result<bool, String> {
insert_pin_bind(args, hosts, SANDBOX_HOSTS_PATH)
}
fn open_pin(path: &Path) -> Result<File, String> {
File::open(path)
.and_then(|file| above_stdio(file).map_err(std::io::Error::from))
.map_err(|error| {
format!(
"Bubblewrap: could not open generated pin {}: {error}",
path.display()
)
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PrivateNetworkUse {
ProxyOnlyEgress,
FirewallEnforcement,
}
impl PrivateNetworkUse {
fn requirement(self) -> &'static str {
match self {
Self::ProxyOnlyEgress => "runtimeConfig.networkProxy",
Self::FirewallEnforcement => "network.egress",
}
}
fn remedy(self) -> &'static str {
match self {
Self::ProxyOnlyEgress => "omit runtimeConfig.networkProxy",
Self::FirewallEnforcement => "use ruleless network.egress.default='deny'",
}
}
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),
)
.map(|_| ())
})
}
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();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct NetworkTools {
unshare: PathBuf,
sh: PathBuf,
slirp4netns: PathBuf,
nsenter: PathBuf,
ip: PathBuf,
iptables: PathBuf,
ip6tables: PathBuf,
iptables_restore: PathBuf,
ip6tables_restore: PathBuf,
sleep: PathBuf,
}
impl NetworkTools {
fn find<L>(use_case: PrivateNetworkUse, find: L) -> Result<Self, String>
where
L: Fn(&str) -> Result<PathBuf, LookupError>,
{
let tool = |name: &str| {
find(name).map_err(|error| {
format!(
"Bubblewrap: {} requires '{name}', which {error}. Install it or {}.",
use_case.requirement(),
use_case.remedy()
)
})
};
Ok(Self {
unshare: tool("unshare")?,
sh: tool("sh")?,
slirp4netns: tool("slirp4netns")?,
nsenter: tool("nsenter")?,
ip: tool("ip")?,
iptables: tool("iptables")?,
ip6tables: tool("ip6tables")?,
iptables_restore: tool("iptables-restore")?,
ip6tables_restore: tool("ip6tables-restore")?,
sleep: tool("sleep")?,
})
}
fn tool_probes(&self) -> [(&'static str, &Path, &'static str, bool); 7] {
[
("nsenter", &self.nsenter, "--version", false),
("ip", &self.ip, "-Version", false),
("iptables", &self.iptables, "--version", true),
("ip6tables", &self.ip6tables, "--version", true),
(
"iptables-restore",
&self.iptables_restore,
"--version",
true,
),
(
"ip6tables-restore",
&self.ip6tables_restore,
"--version",
true,
),
("sleep", &self.sleep, "0", false),
]
}
fn supervisor_arguments(&self) -> [&Path; 7] {
[
&self.nsenter,
&self.ip,
&self.slirp4netns,
&self.iptables_restore,
&self.ip6tables_restore,
&self.sleep,
&self.unshare,
]
}
}
pub(crate) fn probe_dependencies(use_case: PrivateNetworkUse) -> Result<NetworkTools, String> {
static APPROVED: Mutex<Option<NetworkTools>> = Mutex::new(None);
probe_dependencies_caching(
&APPROVED,
use_case,
ProbeBudget::unbounded(),
host_tools::find,
real_probe_command,
)
}
fn probe_dependencies_caching<L, F>(
approved: &Mutex<Option<NetworkTools>>,
use_case: PrivateNetworkUse,
budget: ProbeBudget,
find: L,
command: F,
) -> Result<NetworkTools, String>
where
L: Fn(&str) -> Result<PathBuf, LookupError>,
F: Fn(&Path, &[&str]) -> Command,
{
let tools = NetworkTools::find(use_case, find)?;
let already_approved = approved
.lock()
.unwrap_or_else(PoisonError::into_inner)
.as_ref()
== Some(&tools);
if !already_approved {
probe_stable_dependencies(use_case, budget, &tools, &command)?;
*approved.lock().unwrap_or_else(PoisonError::into_inner) = Some(tools.clone());
}
Ok(tools)
}
pub(crate) fn probe_private_namespaces(
tools: &NetworkTools,
use_case: PrivateNetworkUse,
) -> Result<(), String> {
check_private_namespaces(
private_namespace_probe(tools, &real_probe_command),
&tools.sh,
use_case,
ProbeBudget::unbounded(),
)
}
#[cfg(test)]
const EXPECTED_SUPERVISOR_SCRIPT_DIGEST: u64 = 0xc1a5_bc1d_c051_a6fd;
#[cfg(test)]
const SUPERVISOR_EXTERNAL_COMMANDS: &[&str] = &[
"slirp4netns",
"nsenter",
"ip",
"iptables-restore",
"ip6tables-restore",
"sleep",
"unshare",
];
fn real_probe_command(program: &Path, args: &[&str]) -> Command {
let mut command = Command::new(program);
command.args(args);
command
}
fn probe_dependencies_uncached(
use_case: PrivateNetworkUse,
budget: ProbeBudget,
) -> Result<NetworkTools, String> {
probe_dependencies_with(use_case, budget, host_tools::find, real_probe_command)
}
fn probe_dependencies_with<L, F>(
use_case: PrivateNetworkUse,
budget: ProbeBudget,
find: L,
command: F,
) -> Result<NetworkTools, String>
where
L: Fn(&str) -> Result<PathBuf, LookupError>,
F: Fn(&Path, &[&str]) -> Command,
{
let tools = probe_dependencies_caching(&Mutex::new(None), use_case, budget, find, &command)?;
check_private_namespaces(
private_namespace_probe(&tools, &command),
&tools.sh,
use_case,
budget,
)?;
Ok(tools)
}
fn probe_stable_dependencies<F>(
use_case: PrivateNetworkUse,
budget: ProbeBudget,
tools: &NetworkTools,
command: &F,
) -> Result<(), String>
where
F: Fn(&Path, &[&str]) -> Command,
{
let requirement = use_case.requirement();
let slirp4netns = tools.slirp4netns.display();
let slirp = run_probe(
command(&tools.slirp4netns, &["--version"]),
"slirp4netns",
budget,
)
.map_err(|error| {
format!(
"Bubblewrap: {requirement} requires 'slirp4netns' ({slirp4netns}): {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_path = tools.unshare.display();
let unshare =
run_probe(command(&tools.unshare, &["--help"]), "unshare", budget).map_err(|error| {
format!(
"Bubblewrap: {requirement} requires util-linux 'unshare' ({unshare_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 ({unshare_path})"
));
}
for (binary, path, probe, has_backend) in tools.tool_probes() {
let output = run_probe(command(path, &[probe]), binary, budget).map_err(|error| {
format!(
"Bubblewrap: {requirement} requires '{binary}' ({}) to enforce {}: {error}",
path.display(),
use_case.mechanism()
)
})?;
if !output.status.success() {
return Err(format!(
"Bubblewrap: {requirement} requires a working '{binary}' installation \
({} {probe} exited with {})",
path.display(),
output.status
));
}
if has_backend {
iptables_backend_is_usable(
binary,
path,
&output.stdout,
Path::new(XTABLES_LOCK_PATH),
use_case,
)?;
}
}
Ok(())
}
fn iptables_backend_is_usable(
binary: &str,
path: &Path,
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(),
path.display(),
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 Supervisor,
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.poll().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));
}
}
pub(crate) 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(())
});
}
}
pub(crate) fn above_stdio(file: File) -> Result<File, Errno> {
let fd = fcntl(
file.as_raw_fd(),
FcntlArg::F_DUPFD_CLOEXEC(libc::STDERR_FILENO + 1),
)?;
Ok(unsafe { File::from_raw_fd(fd) })
}
pub(crate) fn pipe_above_stdio() -> Result<(OwnedFd, OwnedFd), String> {
let (reader, writer) =
pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
let lift = |end: OwnedFd| {
above_stdio(File::from(end))
.map(OwnedFd::from)
.map_err(|error| format!("Bubblewrap: failed to move a pipe above stdio: {error}"))
};
Ok((lift(reader)?, lift(writer)?))
}
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}"))
}
pub(crate) fn startup_output(
child: &mut Child,
pty: Option<&crate::mxc_pty::LivePty>,
) -> Result<String, String> {
if let Some(pty) = pty {
let output = pty
.read_available_output(64 * 1024)
.map_err(|error| format!("Bubblewrap: failed to read startup PTY output: {error}"))?;
return Ok(String::from_utf8_lossy(&output).trim().to_string());
}
let Some(stderr) = child.stderr.as_mut() else {
return Ok(String::new());
};
set_nonblocking(stderr.as_raw_fd())?;
let mut output = Vec::new();
let mut buffer = [0; 4096];
while output.len() < 64 * 1024 {
match stderr.read(&mut buffer) {
Ok(0) => break,
Ok(count) => output.extend_from_slice(&buffer[..count]),
Err(error) if error.kind() == ErrorKind::WouldBlock => break,
Err(error) => {
return Err(format!(
"Bubblewrap: failed to read startup stderr: {error}"
))
}
}
}
Ok(String::from_utf8_lossy(&output).trim().to_string())
}
struct Supervisor {
child: Child,
exit: Option<ExitStatus>,
}
impl Supervisor {
fn new(child: Child) -> Self {
Self { child, exit: None }
}
fn id(&self) -> u32 {
self.child.id()
}
fn poll(&mut self) -> std::io::Result<Option<ExitStatus>> {
if self.exit.is_none() && has_exited_unreaped(self.child.id())? {
self.terminate()?;
}
Ok(self.exit)
}
fn terminate(&mut self) -> std::io::Result<ExitStatus> {
if let Some(status) = self.exit {
return Ok(status);
}
group_kill(&mut self.child)?;
let status = self.child.wait()?;
self.exit = Some(status);
Ok(status)
}
}
pub(crate) fn has_exited_unreaped(pid: u32) -> std::io::Result<bool> {
waitid(
Id::Pid(Pid::from_raw(pid as i32)),
WaitPidFlag::WEXITED | WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT,
)
.map(|status| status != WaitStatus::StillAlive)
.map_err(std::io::Error::from)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bwrap_common::bwrap_command::{COMPAT_RUN_LINK, COMPAT_RUN_TARGET};
#[test]
fn child_information_failure_keeps_the_launcher_unreaped_for_cleanup() {
let mut startup = BwrapStartup {
info_reader: File::open("/dev/null").expect("empty child information"),
info_writer: None,
gate_reader: None,
gate_writer: None,
inheritable: Vec::new(),
_pins: Vec::new(),
};
let mut child = Command::new("sh")
.args(["-c", "exit 7"])
.spawn()
.expect("start failing launcher");
let result = startup.child_pid(&child);
let exited_unreaped = has_exited_unreaped(child.id());
let status = child.wait().expect("reap launcher");
assert!(result
.expect_err("missing child information must fail startup")
.contains("bwrap exited before publishing child information"));
assert!(
matches!(exited_unreaped, Ok(true)),
"startup reaped the process-group leader before cleanup: {exited_unreaped:?}"
);
assert_eq!(status.code(), Some(7));
}
#[test]
fn startup_stderr_returns_the_child_diagnostic() {
let mut child = Command::new("sh")
.args(["-c", "printf 'namespace refused\\n' >&2"])
.stderr(Stdio::piped())
.spawn()
.expect("start diagnostic child");
assert!(child.wait().expect("wait for diagnostic child").success());
assert_eq!(
startup_output(&mut child, None).expect("read startup stderr"),
"namespace refused"
);
}
#[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");
let ProxyResolveError::Rejected(error) = error else {
panic!("a reserved answer is a policy refusal: {error}");
};
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, ProxyResolveError> {
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.message().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();
let ProxyResolveError::Lookup(error) = error else {
panic!("an unresolvable name is a lookup failure: {error}");
};
assert!(
error.contains("proxy.corp.invalid"),
"error should name the offending host: {error}"
);
}
#[test]
fn a_failed_lookup_is_not_reported_as_a_refusal() {
let address = ProxyAddress::new("proxy.example".into(), 3128);
let error = SandboxProxy::resolve_with(&address, |_, _| {
Err(ProxyResolveError::Lookup("timed out".into()))
})
.unwrap_err();
assert!(matches!(error, ProxyResolveError::Lookup(_)), "{error}");
}
#[test]
fn static_rejections_are_refusals() {
for host in ["[::1]", "2001:db8::1", "10.0.2.2"] {
let address = ProxyAddress::new(host.into(), 8080);
let error = SandboxProxy::resolve(&address).unwrap_err();
assert!(
matches!(error, ProxyResolveError::Rejected(_)),
"{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.message().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.message().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(), None).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(), None).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(), None).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, 17).unwrap();
let pin = args
.windows(3)
.position(|window| window == ["--ro-bind-data", "17", 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, 17).unwrap());
let mut untouched = vec!["--ro-bind-try".to_string()];
untouched.extend(command_tail());
assert!(!insert_hosts_bind(&mut untouched, 17).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, 17).is_err());
}
const SYSTEMD_RESOLVED_STUB: &str = "nameserver 127.0.0.53\noptions edns0 trust-ad\n\
search corp.example\n";
#[test]
fn forwarder_constants_agree() {
assert_eq!(SLIRP_DNS_FORWARDER_IP.to_string(), SLIRP_DNS_FORWARDER);
}
#[test]
fn a_loopback_stub_resolver_is_pinned() {
assert!(resolvers_are_loopback_only(SYSTEMD_RESOLVED_STUB));
assert!(resolvers_are_loopback_only("nameserver 127.0.0.1\n"));
}
#[test]
fn a_routable_resolver_is_left_alone() {
assert!(!resolvers_are_loopback_only("nameserver 8.8.8.8\n"));
assert!(!resolvers_are_loopback_only(
"nameserver 127.0.0.53\nnameserver 8.8.8.8\n"
));
}
#[test]
fn a_resolver_list_without_an_ipv4_entry_is_left_alone() {
assert!(!resolvers_are_loopback_only("nameserver ::1\n"));
assert!(!resolvers_are_loopback_only("search corp.example\n"));
assert!(!resolvers_are_loopback_only(""));
}
#[test]
fn an_unreadable_nameserver_is_left_alone() {
assert!(!resolvers_are_loopback_only("nameserver localhost\n"));
assert!(!resolvers_are_loopback_only("nameserver 127.0.0.999\n"));
assert!(!resolvers_are_loopback_only("nameserver\n"));
}
#[test]
fn an_indented_directive_is_not_a_nameserver() {
assert!(!is_nameserver_line(" nameserver 8.8.8.8"));
assert!(resolvers_are_loopback_only(
"nameserver 127.0.0.53\n nameserver 8.8.8.8\n"
));
assert_eq!(
render_pinned_resolv_conf("nameserver 127.0.0.53\n nameserver 8.8.8.8\n"),
"nameserver 10.0.2.3\n"
);
}
#[test]
fn a_nameserver_line_ignores_trailing_fields() {
assert!(resolvers_are_loopback_only(
"nameserver 127.0.0.53 # stub\n"
));
}
#[test]
fn the_pinned_resolver_keeps_every_other_directive() {
let pinned = render_pinned_resolv_conf(SYSTEMD_RESOLVED_STUB);
assert_eq!(
pinned,
"nameserver 10.0.2.3\noptions edns0 trust-ad\nsearch corp.example\n"
);
}
#[test]
fn the_pinned_resolver_carries_no_host_commentary() {
let pinned = render_pinned_resolv_conf(
"# generated by something\nnameserver 127.0.0.53\ndomain corp.example\n\
sortlist 10.0.0.0/8\nbogus-directive value\n",
);
assert_eq!(
pinned,
"nameserver 10.0.2.3\ndomain corp.example\nsortlist 10.0.0.0/8\n"
);
}
#[test]
fn the_pinned_resolver_replaces_every_nameserver() {
let pinned =
render_pinned_resolv_conf("nameserver 127.0.0.53\nnameserver 127.0.0.54\n# comment\n");
assert_eq!(pinned, "nameserver 10.0.2.3\n");
assert_eq!(nameserver_values(&pinned).collect::<Vec<_>>(), ["10.0.2.3"]);
}
fn host_with_resolver(dir: &tempfile::TempDir, contents: &str) -> PathBuf {
let root = std::fs::canonicalize(dir.path()).expect("tempdir canonicalizes");
let path = root.join("resolv.conf");
fs::write(&path, contents).expect("fixture resolver");
path
}
fn buffer_logger() -> Logger {
Logger::new(crate::mxc_common::logger::Mode::Buffer)
}
#[test]
fn the_decision_pins_a_loopback_host() {
let dir = tempfile::tempdir().unwrap();
let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
let mut logger = buffer_logger();
let pin = ResolverPin::from_resolver(
&resolver,
&ContainerPolicy::default(),
&[],
None,
&mut logger,
)
.expect("a loopback stub is pinned");
assert_eq!(pin.destination, resolver);
assert!(pin.contents.contains("nameserver 10.0.2.3"));
assert!(pin.contents.contains("search corp.example"));
assert!(logger.warnings().is_empty(), "{:?}", logger.warnings());
}
#[test]
fn the_decision_declines_a_routable_host() {
let dir = tempfile::tempdir().unwrap();
let resolver = host_with_resolver(&dir, "nameserver 8.8.8.8\n");
let mut logger = buffer_logger();
assert!(ResolverPin::from_resolver(
&resolver,
&ContainerPolicy::default(),
&[],
None,
&mut logger
)
.is_none());
assert!(logger.warnings().is_empty(), "{:?}", logger.warnings());
}
#[test]
fn the_decision_is_silent_when_there_is_no_resolver() {
let dir = tempfile::tempdir().unwrap();
let absent = dir.path().join("absent.conf");
let mut logger = buffer_logger();
assert!(ResolverPin::from_resolver(
&absent,
&ContainerPolicy::default(),
&[],
None,
&mut logger
)
.is_none());
assert!(logger.warnings().is_empty(), "{:?}", logger.warnings());
}
#[test]
fn the_decision_declines_a_denied_destination() {
let dir = tempfile::tempdir().unwrap();
let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
let policy = ContainerPolicy {
denied_paths: vec![resolver.to_string_lossy().into_owned()],
..Default::default()
};
let mut logger = buffer_logger();
assert!(ResolverPin::from_resolver(&resolver, &policy, &[], None, &mut logger).is_none());
let out = logger.warnings().join("\n");
assert!(out.contains("deniedPaths"), "must name the remedy: {out}");
}
#[test]
fn resolver_pins_respect_translated_file_grants_and_masks() {
let dir = tempfile::tempdir().unwrap();
let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
let file = resolver.to_string_lossy().into_owned();
let parent = resolver.parent().unwrap().to_string_lossy().into_owned();
for (intent, destination, pinned, warning) in [
(
FsIntent::ReadWrite,
file.clone(),
false,
"mounts its own resolver",
),
(FsIntent::ReadOnly, file, false, "mounts its own resolver"),
(
FsIntent::Denied,
parent.clone(),
false,
"filesystem policy denies",
),
(FsIntent::ReadOnly, parent, true, ""),
] {
let mounts = vec![PolicyMount {
source: "/run/resolvconf/resolv.conf".into(),
destination,
intent,
readonly_overlay: None,
}];
let mut logger = buffer_logger();
let pin = ResolverPin::from_resolver(
&resolver,
&ContainerPolicy::default(),
&mounts,
None,
&mut logger,
);
assert_eq!(pin.is_some(), pinned, "{mounts:?}");
if !pinned {
assert!(logger.warnings().join("\n").contains(warning));
}
}
}
#[test]
fn the_decision_declines_a_caller_supplied_resolver() {
let dir = tempfile::tempdir().unwrap();
let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
let policy = ContainerPolicy {
readonly_paths: vec![resolver.to_string_lossy().into_owned()],
..Default::default()
};
let mut logger = buffer_logger();
assert!(ResolverPin::from_resolver(&resolver, &policy, &[], None, &mut logger).is_none());
let out = logger.warnings().join("\n");
assert!(
out.contains("loopback"),
"the resolver they mounted cannot be reached either: {out}"
);
}
#[test]
fn the_decision_declines_a_caller_supplied_resolver_through_a_symlink() {
use crate::mxc_common::models::ContainerPolicy;
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
fs::create_dir_all(root.join("run/systemd/resolve")).unwrap();
fs::create_dir_all(root.join("etc")).unwrap();
let target = root.join("run/systemd/resolve/stub-resolv.conf");
fs::write(&target, SYSTEMD_RESOLVED_STUB).unwrap();
let link = root.join("etc/resolv.conf");
std::os::unix::fs::symlink(&target, &link).unwrap();
for grant in [link.clone(), target.clone()] {
for policy in [
ContainerPolicy {
readonly_paths: vec![grant.to_string_lossy().into_owned()],
..Default::default()
},
ContainerPolicy {
readwrite_paths: vec![grant.to_string_lossy().into_owned()],
..Default::default()
},
] {
let mut logger = buffer_logger();
assert!(
ResolverPin::from_resolver(&link, &policy, &[], None, &mut logger).is_none(),
"a grant on {} is the caller claiming the resolver",
grant.display()
);
}
}
}
#[test]
fn the_decision_declines_an_unresolvable_chain() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
let first = root.join("first.conf");
let second = root.join("second.conf");
std::os::unix::fs::symlink(&second, &first).unwrap();
std::os::unix::fs::symlink(&first, &second).unwrap();
let mut logger = buffer_logger();
assert!(ResolverPin::from_resolver(
&first,
&ContainerPolicy::default(),
&[],
None,
&mut logger
)
.is_none());
let out = logger.warnings().join("\n");
assert!(out.contains("could not be read"), "got: {out}");
}
#[test]
fn the_decision_compares_policy_against_the_canonical_destination() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
fs::create_dir_all(root.join("real")).unwrap();
fs::write(root.join("real/stub.conf"), SYSTEMD_RESOLVED_STUB).unwrap();
std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap();
let policy = ContainerPolicy {
denied_paths: vec![root.join("real").to_string_lossy().into_owned()],
..Default::default()
};
let mut logger = buffer_logger();
assert!(
ResolverPin::from_resolver(
&root.join("link/stub.conf"),
&policy,
&[],
None,
&mut logger
)
.is_none(),
"a denial of the canonical directory must stop the pin reached by an alias"
);
let out = logger.warnings().join("\n");
assert!(out.contains("deniedPaths"), "must name the remedy: {out}");
}
#[test]
fn a_staging_failure_gives_up_the_pin_rather_than_the_run() {
let dir = tempfile::tempdir().unwrap();
let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
let mut logger = buffer_logger();
let pin = ResolverPin::from_resolver(
&resolver,
&ContainerPolicy::default(),
&[],
None,
&mut logger,
)
.expect("a loopback stub is pinned");
let staged = stage_resolver(
Some(&pin),
Path::new("/mxc-absent-staging-dir"),
&mut logger,
);
assert!(
staged.is_none(),
"a failed stage leaves the sandbox unpinned"
);
let out = logger.warnings().join("\n");
assert!(
out.contains("loopback nameserver"),
"the degradation must be reported: {out}"
);
assert!(
logger.get_buffer().is_empty(),
"the warning must travel as a retained warning, not as buffer output"
);
}
#[test]
fn staging_reports_the_pin_it_mounted() {
let dir = tempfile::tempdir().unwrap();
let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
let mut logger = buffer_logger();
let pin = ResolverPin::from_resolver(
&resolver,
&ContainerPolicy::default(),
&[],
None,
&mut logger,
)
.expect("a loopback stub is pinned");
let staging = tempfile::tempdir().unwrap();
let (source, destination) = stage_resolver(Some(&pin), staging.path(), &mut logger)
.expect("staging into a real dir");
assert_eq!(fs::read_to_string(&source).unwrap(), pin.contents);
assert_eq!(destination, resolver.to_string_lossy());
assert!(
logger.warnings().is_empty(),
"a successful pin is not a degradation: {:?}",
logger.warnings()
);
}
#[test]
fn staging_nothing_is_silent() {
let dir = tempfile::tempdir().unwrap();
let mut logger = buffer_logger();
assert!(stage_resolver(None, dir.path(), &mut logger).is_none());
assert!(logger.warnings().is_empty());
assert!(logger.get_buffer().is_empty());
}
#[test]
fn the_mount_path_follows_the_sandbox_compat_symlink() {
assert_eq!(
sandbox_mount_path("/var/run/NetworkManager/resolv.conf"),
"/run/NetworkManager/resolv.conf"
);
}
#[test]
fn the_mount_path_leaves_other_spellings_alone() {
assert_eq!(
sandbox_mount_path("/run/systemd/resolve/stub-resolv.conf"),
"/run/systemd/resolve/stub-resolv.conf"
);
assert_eq!(
sandbox_mount_path("/var/running/resolv.conf"),
"/var/running/resolv.conf"
);
assert_eq!(sandbox_mount_path("/etc/resolv.conf"), "/etc/resolv.conf");
assert_eq!(sandbox_mount_path(COMPAT_RUN_LINK), COMPAT_RUN_LINK);
}
#[test]
fn the_compat_symlink_the_rewrite_assumes_is_the_one_emitted() {
let args = crate::bwrap_common::bwrap_command::build_args(
&crate::mxc_common::models::ExecutionRequest {
script_code: "echo hi".into(),
..Default::default()
},
None,
);
let emitted = args
.windows(3)
.any(|w| w[0] == "--symlink" && w[1] == COMPAT_RUN_TARGET && w[2] == COMPAT_RUN_LINK);
assert!(
emitted,
"the sandbox must be given `--symlink {COMPAT_RUN_TARGET} {COMPAT_RUN_LINK}` for the \
resolver rewrite to be correct; got: {args:?}"
);
}
#[test]
fn staging_rewrites_the_mount_but_keeps_the_host_destination() {
let pin = ResolverPin {
destination: "/var/run/NetworkManager/resolv.conf".to_string(),
contents: format!("nameserver {SLIRP_DNS_FORWARDER}\n"),
};
let mut logger = buffer_logger();
let staging = tempfile::tempdir().unwrap();
let (_, destination) =
stage_resolver(Some(&pin), staging.path(), &mut logger).expect("staging succeeds");
assert_eq!(destination, "/run/NetworkManager/resolv.conf");
assert_eq!(pin.destination, "/var/run/NetworkManager/resolv.conf");
}
#[test]
fn the_resolver_target_follows_the_link_chain() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
fs::create_dir_all(root.join("run/systemd/resolve")).unwrap();
fs::create_dir_all(root.join("etc")).unwrap();
let stub = root.join("run/systemd/resolve/stub-resolv.conf");
fs::write(&stub, SYSTEMD_RESOLVED_STUB).unwrap();
std::os::unix::fs::symlink(&stub, root.join("etc/resolv.conf")).unwrap();
assert_eq!(resolver_target_of(&root.join("etc/resolv.conf")), Ok(stub));
}
#[test]
fn the_resolver_target_resolves_a_relative_link() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
fs::create_dir_all(root.join("run/resolvconf")).unwrap();
fs::create_dir_all(root.join("etc")).unwrap();
let real = root.join("run/resolvconf/resolv.conf");
fs::write(&real, SYSTEMD_RESOLVED_STUB).unwrap();
std::os::unix::fs::symlink(
"../run/resolvconf/resolv.conf",
root.join("etc/resolv.conf"),
)
.unwrap();
assert_eq!(resolver_target_of(&root.join("etc/resolv.conf")), Ok(real));
}
#[test]
fn the_resolver_target_resolves_a_symlinked_ancestor() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
fs::create_dir_all(root.join("run/res/v1")).unwrap();
fs::create_dir_all(root.join("etc")).unwrap();
let real = root.join("run/res/v1/stub.conf");
fs::write(&real, SYSTEMD_RESOLVED_STUB).unwrap();
std::os::unix::fs::symlink(root.join("run/res/v1"), root.join("run/res/current")).unwrap();
std::os::unix::fs::symlink(
root.join("run/res/current/stub.conf"),
root.join("etc/resolv.conf"),
)
.unwrap();
assert_eq!(resolver_target_of(&root.join("etc/resolv.conf")), Ok(real));
}
#[test]
fn the_resolver_target_folds_dotdot_under_a_symlinked_ancestor() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
fs::create_dir_all(root.join("run/resolvconf")).unwrap();
fs::create_dir_all(root.join("etc")).unwrap();
let real = root.join("run/other.conf");
fs::write(&real, SYSTEMD_RESOLVED_STUB).unwrap();
std::os::unix::fs::symlink(root.join("run/resolvconf"), root.join("etc/link")).unwrap();
std::os::unix::fs::symlink(
root.join("etc/link/../other.conf"),
root.join("etc/resolv.conf"),
)
.unwrap();
assert_eq!(resolver_target_of(&root.join("etc/resolv.conf")), Ok(real));
}
#[test]
fn the_resolver_target_handles_a_regular_file_and_a_broken_link() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
let regular = root.join("resolv.conf");
fs::write(®ular, SYSTEMD_RESOLVED_STUB).unwrap();
assert_eq!(resolver_target_of(®ular), Ok(regular.clone()));
let dangling = root.join("dangling");
std::os::unix::fs::symlink(root.join("absent"), &dangling).unwrap();
assert!(resolver_target_of(&dangling).is_err());
}
#[test]
fn the_resolver_target_gives_up_on_a_link_loop() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
let first = root.join("first");
let second = root.join("second");
std::os::unix::fs::symlink(&second, &first).unwrap();
std::os::unix::fs::symlink(&first, &second).unwrap();
let error = resolver_target_of(&first).expect_err("a loop has no target");
assert!(error.contains("could not be resolved"), "got: {error}");
}
#[test]
fn the_resolver_target_refuses_a_directory() {
let dir = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(dir.path()).unwrap();
fs::create_dir(root.join("adir")).unwrap();
assert!(resolver_target_of(&root.join("adir")).is_err());
}
#[test]
fn a_denied_resolver_path_is_detected() {
let denied = ContainerPolicy {
denied_paths: vec!["/run/systemd/resolve".into()],
..Default::default()
};
assert!(path_is_denied(
&denied,
"/run/systemd/resolve/stub-resolv.conf"
));
assert!(!path_is_denied(&denied, "/etc/resolv.conf"));
let regranted = ContainerPolicy {
denied_paths: vec!["/run/systemd/resolve".into()],
readonly_paths: vec!["/run/systemd/resolve/stub-resolv.conf".into()],
..Default::default()
};
assert!(!path_is_denied(
®ranted,
"/run/systemd/resolve/stub-resolv.conf"
));
}
#[test]
fn a_caller_supplied_resolver_is_recognized() {
let supplied = ContainerPolicy {
readonly_paths: vec!["/etc/resolv.conf".into()],
..Default::default()
};
assert!(policy_names_path(&supplied, "/etc/resolv.conf"));
let whole_etc = ContainerPolicy {
readonly_paths: vec!["/etc".into()],
..Default::default()
};
assert!(!policy_names_path(&whole_etc, "/etc/resolv.conf"));
}
#[test]
fn the_resolver_bind_lands_after_the_policy_mounts() {
let mut args = vec![
"--ro-bind-try".to_string(),
"/run/systemd/resolve".to_string(),
"/run/systemd/resolve".to_string(),
];
args.extend(command_tail());
let overrides =
insert_pin_bind(&mut args, 17, "/run/systemd/resolve/stub-resolv.conf").unwrap();
assert!(!overrides, "a parent directory mount is not the same path");
let pin = args
.windows(3)
.position(|window| {
window
== [
"--ro-bind-data",
"17",
"/run/systemd/resolve/stub-resolv.conf",
]
})
.expect("pin bind should be present");
assert!(pin > 0, "pin must follow the baseline mount");
assert_eq!(
args[args.len() - COMMAND_TAIL.len() - 1..],
["--", "sh", "-c", "echo hello"]
);
}
#[test]
fn the_resolver_bind_reports_overriding_an_earlier_mount() {
let mut args = vec![
"--ro-bind".to_string(),
"/custom/resolv.conf".to_string(),
"/etc/resolv.conf".to_string(),
];
args.extend(command_tail());
assert!(
insert_pin_bind(&mut args, 17, "/etc/resolv.conf").unwrap(),
"an earlier mount of the same path is an override"
);
}
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, 17).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-data", "17", 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(r#""$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(r#"-- "$iptables_restore" "#);
script_offset(r#"-- "$ip6tables_restore" "#);
}
#[test]
fn script_installs_rules_synchronously() {
let rules_start = script_offset(r#"-- "$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(r#"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| {
[
"-- iptables ",
"-- ip6tables ",
r#""$iptables""#,
r#""$ip6tables""#,
]
.iter()
.any(|call| line.contains(call))
}),
"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 directional_plan(
default: crate::mxc_common::models::NetworkAction,
allowed: &[&str],
denied: &[&str],
) -> EgressPlan {
use crate::mxc_common::models::{NetworkEgressPolicy, NetworkPeer, NetworkRule};
let rule = |cidr: &&str| NetworkRule {
to: vec![NetworkPeer {
cidr: cidr.parse().expect("test CIDR"),
except: vec![],
}],
ports: vec![],
};
let mut request = crate::mxc_common::models::ExecutionRequest::default();
request.policy.network_egress = Some(NetworkEgressPolicy {
default,
allow: allowed.iter().map(rule).collect(),
deny: denied.iter().map(rule).collect(),
});
EgressPlan::for_request(&request).expect("directional rules must build a plan")
}
fn plan_with_rule_count(count: usize) -> EgressPlan {
let addresses: Vec<String> = (0..count)
.map(|n| format!("10.0.{}.{}/32", n / 256, n % 256))
.collect();
directional_plan(
crate::mxc_common::models::NetworkAction::Deny,
&addresses.iter().map(String::as_str).collect::<Vec<_>>(),
&[],
)
}
#[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),
Path::new("/usr/bin/sh"),
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),
Path::new("/usr/bin/sh"),
PrivateNetworkUse::ProxyOnlyEgress,
);
assert!(
error.contains("'/usr/bin/sh'"),
"must name the shell, got: {error}"
);
assert!(
!error.contains("apparmor"),
"must not offer namespace remedies, got: {error}"
);
}
}
fn is_installed(tool: &str) -> bool {
host_tools::find(tool).is_ok()
}
fn namespaces_are_available() -> bool {
let (Ok(unshare), Ok(sh)) = (host_tools::find("unshare"), host_tools::find("sh")) else {
return false;
};
Command::new(unshare)
.args(PRIVATE_NAMESPACE_PROBE_FLAGS)
.arg(sh)
.args(["-c", ":"])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
fn iptables_uses_nf_tables() -> bool {
host_tools::find("iptables").is_ok_and(|iptables| {
Command::new(iptables)
.arg("--version")
.output()
.is_ok_and(|output| String::from_utf8_lossy(&output.stdout).contains("nf_tables"))
})
}
fn script_variable(tool: &str) -> String {
format!(r#""${}""#, tool.replace('-', "_"))
}
#[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 every binary the script runs \
(including those passed to `nsenter --`) arrives as a checked path from \
NetworkTools::supervisor_arguments and is probed by the dependency walk, 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(&script_variable(name)),
"SUPERVISOR_EXTERNAL_COMMANDS lists '{name}', but SUPERVISOR_SCRIPT no longer \
runs it; drop the entry"
);
}
}
#[test]
fn every_supervisor_command_is_in_the_dependency_walk() {
let tools = tools_in(Path::new("/mxc-test-tools"));
let mut probed: Vec<&str> = vec!["slirp4netns", "unshare"];
probed.extend(tools.tool_probes().iter().map(|(name, ..)| *name));
for name in SUPERVISOR_EXTERNAL_COMMANDS {
assert!(
probed.contains(name),
"the supervisor runs '{name}' but probe_dependencies_uncached never checks it"
);
}
}
#[test]
fn the_rule_tools_the_supervisor_runs_are_probed() {
let tools = tools_in(Path::new("/mxc-test-tools"));
for binary in ["nsenter", "ip", "iptables-restore", "ip6tables-restore"] {
assert!(
SUPERVISOR_SCRIPT.contains(&script_variable(binary)),
"expected the supervisor to run '{binary}'"
);
assert!(
tools
.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_without_allocating_namespaces() {
use std::cell::RefCell;
let log = RefCell::new(Vec::new());
let counting = |program: &Path, args: &[&str]| {
log.borrow_mut()
.push(format!("{} {}", tool_name(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 approved = Mutex::new(None);
let run = |use_case| {
probe_dependencies_caching(
&approved,
use_case,
ProbeBudget::unbounded(),
lookup_where_only(None),
counting,
)
.expect("tool checks should succeed");
(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_first.0, 1, "the tool check must run on a cold cache");
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_eq!(
(after_first.1, after_second.1, after_other_use_case.1),
(0, 0, 0),
"launch dependency checks must not allocate namespaces"
);
}
#[test]
fn a_different_tool_selection_is_checked_before_it_is_used() {
use std::cell::Cell;
let stable_runs = Cell::new(0_u32);
let counting = |program: &Path, _args: &[&str]| {
if tool_name(program) == "slirp4netns" {
stable_runs.set(stable_runs.get() + 1);
}
walk_stub_for(program, None)
};
let approved = Mutex::new(None);
let run = |directory: &'static str| {
let tools = probe_dependencies_caching(
&approved,
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
|name: &str| Ok(Path::new(directory).join(name)),
counting,
)
.expect("every tool answers");
assert_eq!(tools, tools_in(Path::new(directory)));
stable_runs.get()
};
assert_eq!(run("/first"), 1);
assert_eq!(
run("/first"),
1,
"the approved files must not be re-checked"
);
assert_eq!(run("/second"), 2, "different files must be checked first");
}
#[test]
fn a_failed_walk_is_retried_rather_than_remembered() {
use std::cell::Cell;
let attempts = Cell::new(0_u32);
let approved = Mutex::new(None);
let failing = |_: &Path, _: &[&str]| {
attempts.set(attempts.get() + 1);
let mut command = Command::new("sh");
command.args(["-c", "exit 1"]);
command
};
probe_dependencies_caching(
&approved,
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
lookup_where_only(None),
failing,
)
.expect_err("a host whose tooling fails must not be reported usable");
let after_first = attempts.get();
probe_dependencies_caching(
&approved,
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
lookup_where_only(None),
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,
Path::new("/usr/bin/sh"),
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,
Path::new("/usr/bin/sh"),
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
)
.expect_err("an exec failure must fail the walk");
assert!(
error.contains("'/usr/bin/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,
Path::new("/usr/bin/sh"),
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
)
.is_ok());
}
#[test]
fn the_namespace_probe_asks_for_both_namespaces_as_the_supervisor_does() {
let tools = tools_in(Path::new("/mxc-test-tools"));
let command = private_namespace_probe(&tools, &real_probe_command);
assert_eq!(command.get_program(), tools.unshare.as_os_str());
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| Path::new(&pair[0]) == tools.sh && pair[1] == "-c"),
"the probe must run the supervisor's shell, got: {args:?}"
);
}
fn tool_name(program: &Path) -> &str {
program
.file_name()
.and_then(|name| name.to_str())
.unwrap_or_default()
}
fn tools_in(directory: &Path) -> NetworkTools {
NetworkTools::find(PrivateNetworkUse::ProxyOnlyEgress, |name| {
Ok(directory.join(name))
})
.expect("every tool is found")
}
fn lookup_where_only(
missing: Option<&'static str>,
) -> impl Fn(&str) -> Result<PathBuf, LookupError> {
move |name| {
if Some(name) == missing {
return Err(LookupError::NotFound);
}
Ok(Path::new("/mxc-test-tools").join(name))
}
}
fn walk_stub(program: &Path, _args: &[&str]) -> Command {
walk_stub_for(program, None)
}
fn walk_stub_for(program: &Path, override_script: Option<&str>) -> Command {
let script = override_script.unwrap_or(match tool_name(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(),
lookup_where_only(None),
walk_stub,
),
Ok(tools_in(Path::new("/mxc-test-tools")))
);
}
#[test]
fn every_missing_tool_is_named_in_the_refusal() {
for tool in [
"slirp4netns",
"unshare",
"sh",
"nsenter",
"ip",
"iptables",
"ip6tables",
"iptables-restore",
"ip6tables-restore",
"sleep",
] {
let error = probe_dependencies_with(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
lookup_where_only(Some(tool)),
walk_stub,
)
.expect_err("a missing tool must fail the walk");
assert!(
error.contains(&format!("'{tool}'")),
"a missing '{tool}' must be named, got: {error}"
);
assert!(
error.contains("/usr/sbin"),
"the refusal must say where the tool was looked for, got: {error}"
);
assert!(
error.contains("runtimeConfig.networkProxy"),
"the refusal must name the config that required it, got: {error}"
);
}
}
#[test]
fn a_found_tool_that_cannot_start_is_reported_at_its_path() {
let factory = |program: &Path, args: &[&str]| {
if tool_name(program) == "nsenter" {
return Command::new("/mxc-probe-absent-directory/nsenter");
}
walk_stub(program, args)
};
let error = probe_dependencies_with(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
lookup_where_only(None),
factory,
)
.expect_err("a tool that cannot start must fail the walk");
assert!(error.contains("/mxc-test-tools/nsenter"), "got: {error}");
}
#[test]
fn a_refusal_names_the_use_case_that_required_the_tool() {
let error = probe_dependencies_with(
PrivateNetworkUse::FirewallEnforcement,
ProbeBudget::unbounded(),
lookup_where_only(Some("slirp4netns")),
walk_stub,
)
.expect_err("a missing tool must fail the walk");
assert!(error.contains("network.egress"), "got: {error}");
assert!(
!error.contains("omit runtimeConfig.networkProxy"),
"got: {error}"
);
}
#[test]
fn a_tool_that_exits_non_zero_is_reported_as_a_broken_installation() {
let tools = tools_in(Path::new("/mxc-test-tools"));
for (broken, path, ..) in tools.tool_probes() {
let factory = |program: &Path, _args: &[&str]| {
if tool_name(program) == broken {
return walk_stub_for(program, Some("exit 3"));
}
walk_stub_for(program, None)
};
let error = probe_dependencies_with(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
lookup_where_only(None),
factory,
)
.expect_err("a broken tool must fail the walk");
assert!(error.contains(&path.display().to_string()), "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: &Path, _args: &[&str]| {
if tool_name(program) == "unshare" {
return walk_stub_for(program, Some(banner));
}
walk_stub_for(program, None)
};
let error = probe_dependencies_with(
PrivateNetworkUse::ProxyOnlyEgress,
ProbeBudget::unbounded(),
lookup_where_only(None),
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; 10] = [
"slirp4netns",
"unshare",
"sh",
"nsenter",
"ip",
"iptables",
"ip6tables",
"iptables-restore",
"ip6tables-restore",
"sleep",
];
let missing: Vec<&str> = CHECKED_TOOLS
.into_iter()
.filter(|tool| !is_installed(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",
Path::new("/usr/sbin/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",
Path::new("/usr/sbin/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}"
);
assert!(
error.contains("/usr/sbin/iptables"),
"the error must name the file that was checked: {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",
Path::new("/usr/sbin/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("runtimeConfig.networkProxy"),
"a firewall-only request must not be told about a field it never set: {error}"
);
assert!(
error.contains("network.egress"),
"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",
Path::new("/usr/sbin/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("runtimeConfig.networkProxy") && !error.contains("network.egress"),
"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",
Path::new("/usr/sbin/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",
Path::new("/usr/sbin/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
PATH=$MXC_TEST_STUB_PATH
case "$*" in
*" -- "*/ip" "*)
if [ ! -e "$MXC_TEST_LOOPBACK_QUERY" ]; then
printf '%s\n' "$*" > "$MXC_TEST_LOOPBACK_QUERY"
fi
if [ "$(cat "$MXC_TEST_LOOPBACK_STATE")" = "error" ]; then
echo "fake nsenter: sandbox network namespace disappeared" >&2
exit 1
fi
cat "$MXC_TEST_LOOPBACK_STATE"
exit 0
;;
esac
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##*/}"
tool="${tool%-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
PATH=$MXC_TEST_STUB_PATH
echo $$ > "$MXC_TEST_SLIRP_PID"
case "$(cat "$MXC_TEST_LOOPBACK_STATE")" in
*" inet 127.0.0.1/8 "*) ;;
*)
echo "fake slirp4netns: started before Bubblewrap initialized loopback" >&2
exit 1
;;
esac
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,
tools: NetworkTools,
child: Supervisor,
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.poll().expect("poll") {
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.poll().expect("poll") {
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.terminate();
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 stub_tools(bin: &Path) -> NetworkTools {
NetworkTools::find(PrivateNetworkUse::ProxyOnlyEgress, |name| match name {
"sh" | "sleep" => host_tools::find(name),
_ => Ok(bin.join(name)),
})
.expect("the host has sh and sleep")
}
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");
fs::write(
dir.path().join("loopback.state"),
"1: lo inet 127.0.0.1/8 scope host lo\n",
)
.expect("loopback state");
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 tools = stub_tools(&bin);
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 mut command = Command::new(&tools.sh);
command
.args(["-c", SUPERVISOR_SCRIPT, "mxc-test-supervisor"])
.arg(&state)
.arg("1")
.args(tools.supervisor_arguments())
.arg("no")
.env("PATH", dir.path().join("no-tools"))
.env(
"MXC_TEST_STUB_PATH",
std::env::var_os("PATH").unwrap_or_default(),
)
.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_LOOPBACK_QUERY", dir.path().join("loopback.query"))
.env("MXC_TEST_LOOPBACK_STATE", dir.path().join("loopback.state"))
.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 = Supervisor::new(command.spawn().expect("spawn supervisor"));
drop(exit_reader);
drop(pid_reader);
FakeSupervisor {
dir,
tools,
child,
pid_writer: Some(File::from(pid_writer)),
_exit_writer: exit_writer,
}
}
#[test]
fn slirp_waits_for_bubblewrap_to_initialize_loopback() {
for pending in ["", "1: lo inet 127.0.0.2/8 scope host lo\n"] {
let mut supervisor = spawn_fake_supervisor(None, false);
let state = supervisor.dir.path().join("loopback.state");
fs::write(&state, pending).expect("pending loopback state");
supervisor.publish_sandbox_pid();
wait_for_file(
supervisor.dir.path().join("loopback.query"),
&mut supervisor.child,
&supervisor.dir.path().join("supervisor.stderr"),
"loopback readiness query",
Duration::from_secs(20),
)
.expect("loopback must be queried before slirp starts");
assert!(
!supervisor.dir.path().join("slirp.pid").exists(),
"slirp started while loopback was not ready: {}",
supervisor.stderr()
);
assert_eq!(supervisor.rule_invocations(), 0);
assert!(!supervisor.signalled_ready());
let query = fs::read_to_string(supervisor.dir.path().join("loopback.query"))
.expect("query arguments");
assert_eq!(
query.trim(),
format!(
"--net=/proc/4242/ns/net -- {} -4 -o address show dev lo up",
supervisor.tools.ip.display()
)
);
fs::write(&state, "1: lo inet 127.0.0.1/8 scope host lo\n")
.expect("initialized loopback state");
supervisor.wait_until_ready();
assert_eq!(supervisor.rule_invocations(), 2);
}
}
#[test]
fn a_failed_loopback_query_stops_startup_before_slirp() {
let mut supervisor = spawn_fake_supervisor(None, false);
fs::write(supervisor.dir.path().join("loopback.state"), "error")
.expect("failed loopback state");
supervisor.publish_sandbox_pid();
let status = supervisor.wait_for_exit();
assert!(!status.success(), "{status}");
assert!(
supervisor
.stderr()
.contains("network namespace disappeared"),
"{}",
supervisor.stderr()
);
assert!(
supervisor
.stderr()
.contains("failed to query Bubblewrap loopback readiness"),
"{}",
supervisor.stderr()
);
assert!(
!supervisor.dir.path().join("slirp.pid").exists(),
"slirp must not start after a failed loopback query"
);
assert_eq!(supervisor.rule_invocations(), 0);
assert!(!supervisor.signalled_ready());
}
#[test]
fn pending_loopback_uses_the_existing_network_startup_deadline() {
let mut supervisor = spawn_fake_supervisor(None, false);
fs::write(supervisor.dir.path().join("loopback.state"), "")
.expect("pending loopback state");
supervisor.publish_sandbox_pid();
wait_for_file(
supervisor.dir.path().join("loopback.query"),
&mut supervisor.child,
&supervisor.dir.path().join("supervisor.stderr"),
"loopback readiness query",
Duration::from_secs(20),
)
.expect("loopback query must start before the deadline is tested");
let error = wait_for_file(
supervisor.state_dir().join("slirp.ready"),
&mut supervisor.child,
&supervisor.dir.path().join("supervisor.stderr"),
"slirp4netns startup and network rule installation",
Duration::ZERO,
)
.expect_err("pending loopback must not bypass the network startup deadline");
assert!(error.contains("timed out"), "{error}");
assert!(!supervisor.dir.path().join("slirp.pid").exists());
assert_eq!(supervisor.rule_invocations(), 0);
assert!(!supervisor.signalled_ready());
}
#[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 + 1,
"a {rule_count}-rule policy plus the host-loopback drop 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 ") && rule.ends_with(" -j ACCEPT"))
.collect();
assert_eq!(
installed.len(),
rule_count,
"splitting dropped rules; stderr: {}",
supervisor.stderr()
);
for (index, rule) in installed.iter().enumerate() {
let expected = format!(
"iptables -d 10.0.{}.{}/32 -j ACCEPT",
index / 256,
index % 256
);
assert_eq!(rule, &expected, "rule {index} arrived out of order");
}
}
#[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_deny_policy_accepts_only_its_allow_rules_and_closes_both_families() {
let plan = directional_plan(
crate::mxc_common::models::NetworkAction::Deny,
&["203.0.113.7/32", "2001:db8::/32"],
&[],
);
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 10.0.2.2/32 -j DROP".to_string(),
"iptables -d 203.0.113.7/32 -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_deny_rules_before_the_open_terminal() {
let plan = directional_plan(
crate::mxc_common::models::NetworkAction::Allow,
&["198.51.100.9/32"],
&["198.51.100.0/24"],
);
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/32 -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 plan = directional_plan(
crate::mxc_common::models::NetworkAction::Deny,
&["203.0.113.7/32"],
&[],
);
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()
.map(Supervisor::new)
.expect("spawn supervisor");
namespace_with(state_dir, supervisor)
}
fn namespace_with(state_dir: TempDir, supervisor: Supervisor) -> ProxyNetworkNamespace {
ProxyNetworkNamespace {
state_dir,
supervisor,
exit_writer: None,
pid_writer: None,
userns: None,
hosts: None,
resolver: None,
liveness_reader: None,
transactions: 0,
script_timeout_ms: 0,
}
}
const BLOCKING_NSENTER: &str =
"#!/bin/sh\necho $$ > \"$MXC_TEST_BLOCKED_PID\"\nexec sleep 300\n";
fn process_is_gone(pid: u32) -> bool {
match fs::read_to_string(format!("/proc/{pid}/stat")) {
Err(_) => true,
Ok(stat) => stat
.rsplit(')')
.next()
.is_some_and(|rest| rest.trim_start().starts_with('Z')),
}
}
#[test]
fn a_blocked_loopback_query_fails_attach_without_opening_the_gate_or_leaking_children() {
let state_dir = tempfile::tempdir().expect("tempdir");
let bin = state_dir.path().join("bin");
fs::create_dir_all(&bin).expect("bin dir");
install_stub(&bin.join("nsenter"), BLOCKING_NSENTER);
let tools = stub_tools(&bin);
let blocked_pid_path = state_dir.path().join("blocked.pid");
let stderr = File::create(state_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 mut command = Command::new(&tools.sh);
command
.args(["-c", SUPERVISOR_SCRIPT, "mxc-test-supervisor"])
.arg(state_dir.path())
.arg("1")
.args(tools.supervisor_arguments())
.arg("no")
.env("MXC_TEST_BLOCKED_PID", &blocked_pid_path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr))
.process_group(0);
remap_descriptors(
&mut command,
[
(pid_reader.as_raw_fd(), SUPERVISOR_PID_FD),
(exit_reader.as_raw_fd(), SUPERVISOR_EXIT_FD),
],
);
let supervisor = Supervisor::new(command.spawn().expect("spawn supervisor"));
drop(exit_reader);
drop(pid_reader);
let mut network = ProxyNetworkNamespace {
state_dir,
supervisor,
exit_writer: Some(exit_writer),
pid_writer: Some(pid_writer),
userns: Some(File::open("/dev/null").expect("stand-in namespace handle")),
hosts: None,
resolver: None,
liveness_reader: None,
transactions: 0,
script_timeout_ms: 0,
};
let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
let mut startup = network
.configure_bwrap(&mut Vec::new(), &mut logger)
.expect("startup descriptors");
let gate = startup.gate_reader.take().expect("gate reader");
set_nonblocking(gate.as_raw_fd()).expect("nonblocking gate");
let mut gate = File::from(gate);
let error = network
.attach_within(4242, Duration::from_secs(3), &mut logger)
.and_then(|()| startup.release())
.expect_err("a blocked loopback query must fail the startup");
assert!(
error.contains(
"timed out waiting for slirp4netns startup and network rule installation"
),
"{error}"
);
let mut byte = [0_u8; 1];
assert_eq!(
gate.read(&mut byte)
.expect_err("the gate is still held")
.kind(),
ErrorKind::WouldBlock,
"nothing may open the workload gate after a failed attach"
);
let deadline = Instant::now() + Duration::from_secs(10);
while !blocked_pid_path.exists() && Instant::now() < deadline {
thread::sleep(Duration::from_millis(10));
}
let blocked_pid: u32 = fs::read_to_string(&blocked_pid_path)
.unwrap_or_else(|error| {
panic!(
"the loopback query must have started: {error}; supervisor stderr: {}",
stderr_detail(&network.state_dir.path().join("supervisor.stderr"))
)
})
.trim()
.parse()
.expect("blocked pid");
network.stop(&mut logger);
assert!(
network.supervisor.poll().expect("poll").is_some(),
"the supervisor must be reaped"
);
let deadline = Instant::now() + Duration::from_secs(5);
while !process_is_gone(blocked_pid) && Instant::now() < deadline {
thread::sleep(Duration::from_millis(10));
}
assert!(
process_is_gone(blocked_pid),
"the blocked nsenter child {blocked_pid} outlived the supervisor"
);
}
#[test]
fn a_supervisor_that_exits_early_does_not_leave_its_group_running() {
for observe in ["poll", "stop"] {
let dir = tempfile::tempdir().expect("tempdir");
let pid_path = dir.path().join("blocked.pid");
let mut command = Command::new("sh");
command
.args(["-c", "sleep 300 & echo $! > \"$1\"", "mxc-test-supervisor"])
.arg(&pid_path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.process_group(0);
let mut supervisor = Supervisor::new(command.spawn().expect("spawn supervisor"));
let deadline = Instant::now() + Duration::from_secs(20);
let blocked_pid: u32 = loop {
if let Ok(pid) = fs::read_to_string(&pid_path) {
if let Ok(pid) = pid.trim().parse() {
break pid;
}
}
assert!(Instant::now() < deadline, "the blocked child never started");
thread::sleep(Duration::from_millis(10));
};
if observe == "poll" {
let deadline = Instant::now() + Duration::from_secs(20);
while supervisor.poll().expect("poll").is_none() {
assert!(Instant::now() < deadline, "supervisor did not exit");
thread::sleep(Duration::from_millis(10));
}
} else {
let mut network =
namespace_with(tempfile::tempdir().expect("state dir"), supervisor);
let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
network.stop(&mut logger);
}
let deadline = Instant::now() + Duration::from_secs(5);
while !process_is_gone(blocked_pid) && Instant::now() < deadline {
thread::sleep(Duration::from_millis(10));
}
assert!(
process_is_gone(blocked_pid),
"{observe}: the blocked child {blocked_pid} outlived the supervisor"
);
}
}
fn await_exit(namespace: &mut ProxyNetworkNamespace) {
let deadline = Instant::now() + Duration::from_secs(20);
while Instant::now() < deadline {
if namespace.supervisor.poll().expect("poll").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"
);
}
}