use std::collections::HashSet;
use crate::mxc_common::filesystem_resolve::FsIntent;
#[cfg(any(target_os = "linux", test))]
use crate::mxc_common::models::ContainerPolicy;
use crate::mxc_common::models::{ExecutionRequest, NetworkAction, ProxyAddress};
use crate::mxc_common::proxy_env::{is_managed_proxy_key, PROXY_SET_KEYS};
pub(crate) const COMMAND_TAIL: [&str; 3] = ["--", "sh", "-c"];
const BASELINE_RO_BIND_PATHS: &[&str] = &[
"/bin",
"/sbin",
"/lib",
"/lib32",
"/lib64",
"/libx32",
"/usr/bin",
"/usr/sbin",
"/usr/lib",
"/usr/lib32",
"/usr/lib64",
"/usr/libexec",
"/usr/share",
"/etc",
"/run/systemd/resolve",
"/run/NetworkManager",
"/run/resolvconf",
"/mnt/wsl/resolv.conf",
];
pub(crate) const COMPAT_RUN_LINK: &str = "/var/run";
pub(crate) const COMPAT_RUN_TARGET: &str = "/run";
#[cfg(any(target_os = "linux", test))]
pub(crate) fn resolver_target_without_matching_mount(
policy: &ContainerPolicy,
target: &str,
) -> bool {
if target == "/"
|| !target.starts_with('/')
|| target.split('/').any(|part| part == "." || part == "..")
{
return false;
}
let mut policy_mounts = policy
.readwrite_paths
.iter()
.chain(&policy.readonly_paths)
.chain(&policy.denied_paths)
.map(String::as_str);
for mount in BASELINE_RO_BIND_PATHS
.iter()
.copied()
.chain(["/dev", "/proc", "/tmp", "/var/run"])
.chain(policy_mounts.clone())
{
if !mount.starts_with('/')
|| mount.split('/').any(|part| part == "." || part == "..")
|| paths_overlap(target, mount)
{
return false;
}
}
!policy_mounts.any(|mount| paths_overlap("/etc/resolv.conf", mount))
}
#[cfg(any(target_os = "linux", test))]
fn paths_overlap(a: &str, b: &str) -> bool {
let a = std::path::Path::new(a);
let b = std::path::Path::new(b);
a.starts_with(b) || b.starts_with(a)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ResolvedNetworkMode {
Isolated,
FirewallEnforced,
ProxyOnly,
}
impl ResolvedNetworkMode {
pub(crate) fn from_request(request: &ExecutionRequest, proxy_active: bool) -> Self {
if proxy_active {
return Self::ProxyOnly;
}
let egress = request.policy.network_egress.as_ref();
if egress.is_none_or(|egress| {
egress.default == NetworkAction::Deny
&& egress.allow.is_empty()
&& egress.deny.is_empty()
}) {
Self::Isolated
} else {
Self::FirewallEnforced
}
}
pub(crate) fn uses_external_userns(self) -> bool {
matches!(self, Self::ProxyOnly | Self::FirewallEnforced)
}
}
pub fn directional_network_rejection(request: &ExecutionRequest) -> Option<&'static str> {
let egress = request.policy.network_egress.as_ref();
let ingress = request.policy.network_ingress.as_ref();
if egress.is_none() && ingress.is_none() {
return None;
}
if let Some(ingress) = ingress {
if ingress.default == NetworkAction::Allow {
return Some(BWRAP_INGRESS_DEFAULT_ALLOW);
}
if ingress.host_loopback == NetworkAction::Allow {
return Some(BWRAP_HOST_LOOPBACK_ALLOW);
}
}
None
}
pub const BWRAP_INGRESS_DEFAULT_ALLOW: &str =
"Bubblewrap: network.ingress.default='allow' is not supported. The sandbox runs in a \
private network namespace reached through slirp, which has no route in until a host \
port is forwarded to it, and the schema carries no port list to forward. A listener \
inside the sandbox is reachable from the sandbox only. Use \
network.ingress.default='deny'.";
pub const BWRAP_HOST_LOOPBACK_ALLOW: &str =
"Bubblewrap: network.ingress.hostLoopback='allow' is not supported. The sandbox's \
loopback belongs to its own network namespace and is not the host's, so the host \
cannot dial a sandbox listener and nothing bridges the two. Use \
network.ingress.hostLoopback='deny'.";
#[cfg(any(target_os = "linux", test))]
pub(crate) const BWRAP_PROXY_DIRECTIONAL_EGRESS: &str =
"Bubblewrap: runtimeConfig.networkProxy cannot be combined with direct network.egress rules \
or default='allow'. \
A proxy resolves to proxy-only egress, whose chain opens the proxy endpoint alone and \
never reads network.egress, so the rules would be dropped in silence. Use \
network.egress.default='deny' with no allow/deny rules (the proxy-only posture), or \
remove runtimeConfig.networkProxy and express the policy with network.egress.";
#[cfg(any(target_os = "linux", test))]
pub(crate) fn proxy_with_egress_rejection(request: &ExecutionRequest) -> Option<&'static str> {
let proxy = &request.policy.network_proxy;
if !proxy.is_enabled() {
return None;
}
request
.policy
.network_egress
.as_ref()
.is_some_and(|egress| {
egress.default != NetworkAction::Deny
|| !egress.allow.is_empty()
|| !egress.deny.is_empty()
})
.then_some(BWRAP_PROXY_DIRECTIONAL_EGRESS)
}
const DEFAULT_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
const DEFAULT_TERM: &str = "xterm-256color";
fn start_directory(request: &ExecutionRequest) -> Option<String> {
Some(request.working_directory.as_str())
.filter(|dir| !dir.is_empty())
.map(crate::mxc_common::models::sandbox_absolute_path)
}
#[cfg(any(target_os = "linux", test))]
pub(crate) fn cwd_without_matching_mount(request: &ExecutionRequest) -> Option<String> {
let dir = start_directory(request)?;
if dir == "/"
|| !request.working_directory.starts_with('/')
|| request
.working_directory
.split('/')
.any(|part| part == "." || part == "..")
{
return None;
}
let mounts = BASELINE_RO_BIND_PATHS
.iter()
.copied()
.chain(["/dev", "/proc", "/tmp", "/var/run"])
.chain(
request
.policy
.readwrite_paths
.iter()
.chain(&request.policy.readonly_paths)
.chain(&request.policy.denied_paths)
.map(String::as_str),
);
for mount in mounts {
if !mount.starts_with('/') || mount.split('/').any(|part| part == "." || part == "..") {
return None;
}
if path_is_within(&dir, mount) || path_is_within(mount, &dir) {
return None;
}
}
Some(dir)
}
#[cfg(any(target_os = "linux", test))]
fn path_is_within(path: &str, parent: &str) -> bool {
std::path::Path::new(path).starts_with(parent)
}
fn default_env(request: &ExecutionRequest) -> Vec<(String, String)> {
let mut entries = vec![("PATH".to_string(), DEFAULT_PATH.to_string())];
if let Some(home) = start_directory(request) {
entries.push(("HOME".to_string(), home));
}
entries.push(("TERM".to_string(), DEFAULT_TERM.to_string()));
entries
}
fn resolved_env(request: &ExecutionRequest) -> Vec<String> {
crate::mxc_common::default_env::resolve_env(request, || default_env(request))
}
pub fn build_args(request: &ExecutionRequest, proxy_address: Option<&ProxyAddress>) -> Vec<String> {
build_args_classified(request, proxy_address, &HashSet::new())
}
pub fn build_args_classified(
request: &ExecutionRequest,
proxy_address: Option<&ProxyAddress>,
denied_files: &HashSet<String>,
) -> Vec<String> {
let network_mode = ResolvedNetworkMode::from_request(request, proxy_address.is_some());
build_args_classified_with_mode(request, proxy_address, denied_files, network_mode)
}
pub(crate) fn build_args_classified_with_mode(
request: &ExecutionRequest,
proxy_address: Option<&ProxyAddress>,
denied_files: &HashSet<String>,
network_mode: ResolvedNetworkMode,
) -> Vec<String> {
let mut args = Vec::new();
if !network_mode.uses_external_userns() {
args.push("--unshare-user".into());
}
args.extend(
["--unshare-pid", "--unshare-ipc", "--unshare-uts"]
.into_iter()
.map(String::from),
);
args.push("--die-with-parent".into());
args.push("--unshare-net".into());
for path in BASELINE_RO_BIND_PATHS {
args.extend(["--ro-bind-try".into(), (*path).into(), (*path).into()]);
}
args.extend([
"--symlink".into(),
COMPAT_RUN_TARGET.into(),
COMPAT_RUN_LINK.into(),
]);
args.extend(["--dev".into(), "/dev".into()]);
args.extend(["--proc".into(), "/proc".into()]);
args.extend(["--tmpfs".into(), "/tmp".into()]);
for mount in crate::mxc_common::filesystem_resolve::resolve_mount_order(&request.policy) {
match mount.intent {
FsIntent::ReadWrite => {
args.extend(["--bind".into(), mount.path.clone(), mount.path.clone()]);
}
FsIntent::ReadOnly => {
args.extend(["--ro-bind".into(), mount.path.clone(), mount.path.clone()]);
}
FsIntent::Denied => {
if denied_files.contains(&mount.path) {
args.extend(["--ro-bind".into(), "/dev/null".into(), mount.path.clone()]);
} else {
args.extend(["--tmpfs".into(), mount.path.clone()]);
}
}
}
}
if let Some(dir) = start_directory(request) {
args.extend(["--chdir".into(), dir]);
}
args.push("--clearenv".into());
for env_str in resolved_env(request) {
if let Some((key, value)) = env_str.split_once('=') {
if proxy_address.is_some() && is_managed_proxy_key(key) {
continue;
}
args.extend(["--setenv".into(), key.into(), value.into()]);
}
}
if let Some(addr) = proxy_address {
let url = addr.to_url();
for key in PROXY_SET_KEYS {
args.extend(["--setenv".into(), (*key).into(), url.clone()]);
}
}
args.extend(COMMAND_TAIL.iter().map(|arg| arg.to_string()));
args.push(request.script_code.clone());
args
}
#[cfg(test)]
mod tests {
use super::*;
fn base_request() -> ExecutionRequest {
ExecutionRequest {
script_code: "echo hello".into(),
working_directory: "/home/user".into(),
..Default::default()
}
}
#[test]
fn resolver_target_hint_requires_no_mount_overlap() {
let mut policy = ContainerPolicy::default();
assert!(resolver_target_without_matching_mount(
&policy,
"/opt/private/resolv.conf"
));
for no_warning in [
"/run/systemd/resolve/resolv.conf",
"/var/run/NetworkManager/resolv.conf",
"/mnt/wsl/resolv.conf",
"/etc/resolv.conf",
"/tmp/resolv.conf",
] {
assert!(
!resolver_target_without_matching_mount(&policy, no_warning),
"unexpected advisory for {no_warning}"
);
}
policy.readonly_paths = vec!["/opt/private".into()];
assert!(!resolver_target_without_matching_mount(
&policy,
"/opt/private/resolv.conf"
));
for mount in ["/opt/private/", "/opt//private/"] {
policy.readonly_paths = vec![mount.into()];
assert!(
!resolver_target_without_matching_mount(&policy, "/opt/private/resolv.conf"),
"{mount}"
);
}
policy.readonly_paths = vec!["/opt/private/resolv.conf/child".into()];
assert!(!resolver_target_without_matching_mount(
&policy,
"/opt/private/resolv.conf"
));
policy.readonly_paths = vec!["/opt/private2".into()];
assert!(resolver_target_without_matching_mount(
&policy,
"/opt/private/resolv.conf"
));
policy.readonly_paths = vec!["/".into()];
assert!(!resolver_target_without_matching_mount(
&policy,
"/opt/private/resolv.conf"
));
}
#[test]
fn resolver_diagnostic_recognizes_every_emitted_mount_destination() {
let mut with_policy = base_request();
with_policy.policy.readwrite_paths = vec!["/home/user/data".into()];
with_policy.policy.readonly_paths = vec!["/opt/private".into()];
with_policy.policy.denied_paths = vec!["/srv/blocked".into()];
for request in [base_request(), with_policy] {
let args = build_args(&request, None);
for triple in args.windows(3) {
if matches!(
triple[0].as_str(),
"--ro-bind-try" | "--ro-bind" | "--bind" | "--symlink"
) {
assert!(
!resolver_target_without_matching_mount(&request.policy, &triple[2]),
"unrecognized mount destination: {triple:?}"
);
}
}
for pair in args.windows(2) {
if matches!(pair[0].as_str(), "--dev" | "--proc" | "--tmpfs") {
assert!(
!resolver_target_without_matching_mount(&request.policy, &pair[1]),
"unrecognized virtual mount destination: {pair:?}"
);
}
}
}
}
#[test]
fn cwd_hint_requires_a_nonoverlapping_absolute_path() {
let mut request = base_request();
assert_eq!(
cwd_without_matching_mount(&request).as_deref(),
Some("/home/user")
);
request.working_directory = "/".into();
assert_eq!(cwd_without_matching_mount(&request), None);
request.working_directory = "".into();
assert_eq!(cwd_without_matching_mount(&request), None);
request.working_directory = "home/user".into();
assert_eq!(cwd_without_matching_mount(&request), None);
request.working_directory = "/home/../home/user".into();
assert_eq!(cwd_without_matching_mount(&request), None);
}
#[test]
fn cwd_overlap_is_inconclusive_in_either_direction() {
let mut request = base_request();
for cwd in ["/etc", "/etc/project", "/usr", "/tmp/work", "/var"] {
request.working_directory = cwd.into();
assert_eq!(cwd_without_matching_mount(&request), None, "{cwd}");
}
for mount in [
"/home",
"/home/user",
"/home/user/",
"/home//user/",
"/home/user/data",
"/home//user/data/",
] {
request.working_directory = "/home/user".into();
request.policy.readonly_paths = vec![mount.into()];
assert_eq!(cwd_without_matching_mount(&request), None, "{mount}");
}
for mount in ["/home/user2", "/home/user2/"] {
request.policy.readonly_paths = vec![mount.into()];
assert_eq!(
cwd_without_matching_mount(&request).as_deref(),
Some("/home/user"),
"{mount}"
);
}
request.policy.readonly_paths = vec!["/alias/../home/user".into()];
assert_eq!(cwd_without_matching_mount(&request), None);
request.policy.readonly_paths = vec!["/".into()];
assert_eq!(cwd_without_matching_mount(&request), None);
request.policy.readonly_paths.clear();
request.policy.denied_paths = vec!["/home/user/hidden".into()];
assert_eq!(cwd_without_matching_mount(&request), None);
}
#[test]
fn cwd_proof_uses_the_mounted_baseline_and_virtual_roots() {
let request = base_request();
let args = build_args(&request, None);
for mount in BASELINE_RO_BIND_PATHS {
assert!(
args.windows(3)
.any(|a| { a == ["--ro-bind-try", *mount, *mount] }),
"{mount}"
);
}
for (flag, path) in [
("--dev", "/dev"),
("--proc", "/proc"),
("--tmpfs", "/tmp"),
("--symlink", "/var/run"),
] {
assert!(
args.windows(2).any(|a| a[0] == flag && a[1] == path)
|| (flag == "--symlink"
&& args.windows(3).any(|a| a == ["--symlink", "/run", path])),
"{flag} {path}"
);
}
}
#[test]
fn ambiguous_resolver_paths_and_shadowed_link_do_not_warn() {
let mut policy = ContainerPolicy::default();
for target in ["relative/resolv.conf", "/opt/../secret/resolv.conf", "/"] {
assert!(!resolver_target_without_matching_mount(&policy, target));
}
policy.denied_paths = vec!["/etc".into()];
assert!(!resolver_target_without_matching_mount(
&policy,
"/opt/private/resolv.conf"
));
policy.denied_paths = vec!["/etc//".into()];
assert!(!resolver_target_without_matching_mount(
&policy,
"/opt/private/resolv.conf"
));
policy.denied_paths = vec!["/alias/../etc".into()];
assert!(!resolver_target_without_matching_mount(
&policy,
"/opt/private/resolv.conf"
));
}
#[test]
fn cwd_diagnostic_recognizes_every_emitted_mount_destination() {
let mut request = base_request();
let args = build_args(&request, None);
for triple in args.windows(3) {
if matches!(
triple[0].as_str(),
"--ro-bind-try" | "--ro-bind" | "--bind" | "--symlink"
) {
request.working_directory = triple[2].clone();
assert!(
cwd_without_matching_mount(&request).is_none(),
"unrecognized mount destination: {triple:?}"
);
}
}
for pair in args.windows(2) {
if matches!(pair[0].as_str(), "--dev" | "--proc" | "--tmpfs") {
request.working_directory = pair[1].clone();
assert!(
cwd_without_matching_mount(&request).is_none(),
"unrecognized virtual mount destination: {pair:?}"
);
}
}
}
mod env {
use super::*;
fn request() -> ExecutionRequest {
ExecutionRequest::default()
}
fn value<'a>(entries: &'a [String], key: &str) -> Option<&'a str> {
entries
.iter()
.find_map(|kv| kv.strip_prefix(&format!("{key}=")))
}
#[test]
fn a_direct_sdk_request_gets_the_default_block() {
let r = ExecutionRequest::default();
assert_eq!(value(&resolved_env(&r), "PATH"), Some(DEFAULT_PATH));
}
#[test]
fn an_omitted_env_gets_the_default_block() {
let mut r = request();
r.env = None;
r.working_directory = "/workspace".into();
let entries = resolved_env(&r);
assert_eq!(value(&entries, "PATH"), Some(DEFAULT_PATH));
assert_eq!(value(&entries, "HOME"), Some("/workspace"));
assert_eq!(value(&entries, "TERM"), Some(DEFAULT_TERM));
}
#[test]
fn the_default_path_covers_sbin() {
for dir in ["/usr/sbin", "/sbin", "/usr/bin", "/bin"] {
assert!(
DEFAULT_PATH.split(':').any(|entry| entry == dir),
"{dir} must be on the default PATH"
);
}
}
#[test]
fn an_explicitly_empty_env_stays_empty() {
let mut r = request();
r.env = Some(vec![]);
assert!(resolved_env(&r).is_empty());
}
#[test]
fn a_supplied_env_is_used_verbatim() {
let mut r = request();
r.env = Some(vec!["FOO=bar".into()]);
assert_eq!(resolved_env(&r), vec!["FOO=bar".to_string()]);
}
#[test]
fn inherit_default_env_layers_over_the_default_block() {
let mut r = request();
r.env = Some(vec!["FOO=bar".into(), "PATH=/only/mine".into()]);
r.inherit_default_env = true;
let entries = resolved_env(&r);
assert_eq!(value(&entries, "FOO"), Some("bar"));
assert_eq!(value(&entries, "TERM"), Some(DEFAULT_TERM));
assert_eq!(value(&entries, "PATH"), Some("/only/mine"));
assert_eq!(
entries.iter().filter(|kv| kv.starts_with("PATH=")).count(),
1
);
}
#[test]
fn home_follows_the_directory_the_child_starts_in() {
let mut r = request();
r.env = None;
r.working_directory = "/workspace".into();
assert_eq!(value(&resolved_env(&r), "HOME"), Some("/workspace"));
}
#[test]
fn a_caller_entry_without_a_value_reaches_no_setenv() {
for inherit in [false, true] {
let mut r = base_request();
r.env = Some(vec!["FEATURE_FLAG".into(), "FOO=bar".into()]);
r.inherit_default_env = inherit;
let args = build_args(&r, None);
assert!(
!args.iter().any(|a| a == "FEATURE_FLAG"),
"a valueless entry must not be set (inherit {inherit}): {args:?}"
);
assert!(
args.windows(3)
.any(|w| w[0] == "--setenv" && w[1] == "FOO" && w[2] == "bar"),
"the well-formed entry must survive (inherit {inherit}): {args:?}"
);
}
}
#[test]
fn a_policy_grant_alone_does_not_become_home() {
let mut r = request();
r.env = None;
r.working_directory = String::new();
r.policy.readwrite_paths = vec![std::env::temp_dir().display().to_string()];
assert_eq!(value(&resolved_env(&r), "HOME"), None);
let args = build_args(&r, None);
assert!(
!args.iter().any(|a| a == "--chdir"),
"a policy grant must not chdir the child: {args:?}"
);
}
#[test]
fn home_and_chdir_agree() {
for cwd in ["", "/workspace", "work", "./work", "a/../b", "/x/../y/./z"] {
let mut r = request();
r.env = None;
r.working_directory = cwd.into();
let args = build_args(&r, None);
let chdir = args
.windows(2)
.find(|w| w[0] == "--chdir")
.map(|w| w[1].clone());
let home = value(&resolved_env(&r), "HOME").map(str::to_string);
assert_eq!(
home, chdir,
"HOME must name the directory the child starts in (cwd {cwd:?})"
);
}
}
#[test]
fn a_relative_start_directory_is_anchored_to_the_sandbox_root() {
for (cwd, expected) in [
("work", "/work"),
("./work", "/work"),
("a/../b", "/b"),
("/x/../y/./z", "/y/z"),
] {
let mut r = request();
r.env = None;
r.working_directory = cwd.into();
assert_eq!(value(&resolved_env(&r), "HOME"), Some(expected));
}
}
#[test]
fn the_default_block_reaches_the_argument_list() {
let mut r = base_request();
r.env = None;
let args = build_args(&r, None);
let pos = args
.windows(3)
.position(|w| w[0] == "--setenv" && w[1] == "PATH" && w[2] == DEFAULT_PATH);
assert!(pos.is_some(), "PATH must be set via --setenv: {args:?}");
let clearenv = args.iter().position(|a| a == "--clearenv").unwrap();
assert!(
pos.unwrap() > clearenv,
"--setenv must follow --clearenv, else it is wiped"
);
}
}
#[test]
fn an_omitted_network_policy_is_isolated() {
let request = ExecutionRequest { ..base_request() };
assert_eq!(
ResolvedNetworkMode::from_request(&request, false),
ResolvedNetworkMode::Isolated
);
}
#[test]
fn basic_args_contain_namespace_flags() {
let args = build_args(&base_request(), None);
assert!(args.contains(&"--unshare-user".to_string()));
assert!(args.contains(&"--unshare-pid".to_string()));
assert!(args.contains(&"--unshare-ipc".to_string()));
assert!(args.contains(&"--unshare-uts".to_string()));
}
#[test]
fn basic_args_request_die_with_parent() {
let args = build_args(&base_request(), None);
assert!(args.contains(&"--die-with-parent".to_string()));
}
#[test]
fn a_directional_rule_selects_the_namespace_whose_chain_is_programmed() {
let request = directional_egress_request(NetworkAction::Deny, true);
assert_eq!(
ResolvedNetworkMode::from_request(&request, false),
ResolvedNetworkMode::FirewallEnforced
);
}
#[test]
fn a_ruleless_directional_policy_still_honors_the_inbound_posture() {
let denied = directional_egress_request(NetworkAction::Deny, false);
assert_eq!(
ResolvedNetworkMode::from_request(&denied, false),
ResolvedNetworkMode::Isolated
);
let allowed = directional_egress_request(NetworkAction::Allow, false);
let mode = ResolvedNetworkMode::from_request(&allowed, false);
assert_eq!(mode, ResolvedNetworkMode::FirewallEnforced);
assert!(build_args(&allowed, None).contains(&"--unshare-net".to_string()));
}
#[test]
fn no_directional_posture_shares_the_host_namespace() {
for default in [NetworkAction::Allow, NetworkAction::Deny] {
for with_rule in [false, true] {
let request = directional_egress_request(default, with_rule);
assert!(
build_args(&request, None).contains(&"--unshare-net".to_string()),
"default={default:?} with_rule={with_rule} omitted --unshare-net"
);
}
}
}
#[test]
fn a_directional_section_does_not_divert_a_proxy_run() {
let mut request = directional_egress_request(NetworkAction::Deny, false);
request.policy.network_proxy.address = Some(ProxyAddress::new("127.0.0.1".into(), 3128));
assert_eq!(
ResolvedNetworkMode::from_request(&request, true),
ResolvedNetworkMode::ProxyOnly
);
}
#[test]
fn an_ingress_only_directional_request_still_gets_a_private_namespace() {
use crate::mxc_common::models::NetworkIngressPolicy;
let mut request = base_request();
request.policy.network_ingress = Some(NetworkIngressPolicy::default());
let mode = ResolvedNetworkMode::from_request(&request, false);
assert_eq!(mode, ResolvedNetworkMode::Isolated);
assert!(build_args(&request, None).contains(&"--unshare-net".to_string()));
}
fn directional_egress_request(default: NetworkAction, with_rule: bool) -> ExecutionRequest {
use crate::mxc_common::models::{NetworkEgressPolicy, NetworkRule};
let mut request = base_request();
request.policy.network_egress = Some(NetworkEgressPolicy {
default,
allow: if with_rule {
vec![NetworkRule::default()]
} else {
Vec::new()
},
deny: Vec::new(),
});
request
}
fn directional_request(
ingress_default: NetworkAction,
host_loopback: NetworkAction,
) -> ExecutionRequest {
use crate::mxc_common::models::{NetworkEgressPolicy, NetworkIngressPolicy};
let mut request = base_request();
request.policy.network_egress = Some(NetworkEgressPolicy::default());
request.policy.network_ingress = Some(NetworkIngressPolicy {
default: ingress_default,
host_loopback,
});
request
}
#[test]
fn an_inbound_accepting_directional_posture_is_refused() {
let request = directional_request(NetworkAction::Allow, NetworkAction::Deny);
assert_eq!(
directional_network_rejection(&request),
Some(BWRAP_INGRESS_DEFAULT_ALLOW)
);
}
#[test]
fn a_host_loopback_accepting_posture_is_refused() {
let request = directional_request(NetworkAction::Deny, NetworkAction::Allow);
assert_eq!(
directional_network_rejection(&request),
Some(BWRAP_HOST_LOOPBACK_ALLOW)
);
}
#[test]
fn a_fully_denied_directional_posture_is_accepted() {
let request = directional_request(NetworkAction::Deny, NetworkAction::Deny);
assert_eq!(directional_network_rejection(&request), None);
}
#[test]
fn only_external_runtime_proxies_are_accepted() {
let mut request = directional_egress_request(NetworkAction::Deny, false);
request.policy.network_proxy.address = Some(ProxyAddress::new("127.0.0.1".into(), 3128));
assert!(proxy_with_egress_rejection(&request).is_none());
request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
default: NetworkAction::Allow,
..Default::default()
});
assert_eq!(
proxy_with_egress_rejection(&request),
Some(BWRAP_PROXY_DIRECTIONAL_EGRESS)
);
}
#[test]
fn filesystem_policy_produces_correct_mounts() {
let mut r = base_request();
r.policy.readwrite_paths = vec!["/workspace".into()];
r.policy.readonly_paths = vec!["/data".into()];
r.policy.denied_paths = vec!["/secrets".into()];
let args = build_args(&r, None);
let rw_pos = args.iter().position(|a| a == "--bind").unwrap();
assert_eq!(args[rw_pos + 1], "/workspace");
assert_eq!(args[rw_pos + 2], "/workspace");
args.windows(3)
.position(|w| w[0] == "--ro-bind" && w[1] == "/data" && w[2] == "/data")
.expect("readonly policy path /data should produce a --ro-bind mount");
let tmpfs_positions: Vec<_> = args
.iter()
.enumerate()
.filter(|(_, a)| *a == "--tmpfs")
.collect();
let secrets_mount = tmpfs_positions
.iter()
.find(|(i, _)| args[i + 1] == "/secrets");
assert!(
secrets_mount.is_some(),
"denied path should be tmpfs-masked"
);
}
fn policy_mount_pos(args: &[String], op: &str, path: &str) -> usize {
let dest_offset = if op == "--tmpfs" { 1 } else { 2 };
(0..args.len())
.rev()
.find(|&i| args[i] == op && args.get(i + dest_offset).map(String::as_str) == Some(path))
.unwrap_or_else(|| panic!("expected `{op} ... {path}` in args: {args:?}"))
}
#[test]
fn deep_denied_child_masks_rw_parent() {
let mut r = base_request();
r.policy.readwrite_paths = vec!["/data".into()];
r.policy.denied_paths = vec!["/data/secrets".into()];
let args = build_args(&r, None);
let parent = policy_mount_pos(&args, "--bind", "/data");
let child = policy_mount_pos(&args, "--tmpfs", "/data/secrets");
assert!(
child > parent,
"denied /data/secrets (pos {child}) must come after rw /data (pos {parent}) \
so it masks the subtree: {args:?}"
);
}
#[test]
fn deep_rw_child_survives_denied_parent() {
let mut r = base_request();
r.policy.readwrite_paths = vec!["/data/secrets".into()];
r.policy.denied_paths = vec!["/data".into()];
let args = build_args(&r, None);
let parent = policy_mount_pos(&args, "--tmpfs", "/data");
let child = policy_mount_pos(&args, "--bind", "/data/secrets");
assert!(
child > parent,
"rw /data/secrets (pos {child}) must come after denied /data (pos {parent}) \
so the deep bind is not shadowed by the mask: {args:?}"
);
}
#[test]
fn denied_directory_is_masked_with_tmpfs() {
let mut r = base_request();
r.policy.denied_paths = vec!["/secrets".into()];
let denied_files = HashSet::new();
let args = build_args_classified(&r, None, &denied_files);
policy_mount_pos(&args, "--tmpfs", "/secrets");
assert!(
args.windows(3)
.all(|w| !(w[0] == "--ro-bind" && w[1] == "/dev/null" && w[2] == "/secrets")),
"a directory denied path must not be masked with /dev/null: {args:?}"
);
}
#[test]
fn denied_file_is_masked_with_dev_null() {
let mut r = base_request();
r.policy.denied_paths = vec!["/etc/shadow".into()];
let denied_files = HashSet::from(["/etc/shadow".to_string()]);
let args = build_args_classified(&r, None, &denied_files);
let pos = args
.windows(3)
.position(|w| w[0] == "--ro-bind" && w[1] == "/dev/null" && w[2] == "/etc/shadow");
assert!(
pos.is_some(),
"a file denied path must be masked with `--ro-bind /dev/null`: {args:?}"
);
assert!(
args.windows(2)
.all(|w| !(w[0] == "--tmpfs" && w[1] == "/etc/shadow")),
"a file denied path must not be tmpfs-masked: {args:?}"
);
}
#[test]
fn mixed_denied_file_and_dir_masks_each_correctly() {
let mut r = base_request();
r.policy.readwrite_paths = vec!["/data".into()];
r.policy.denied_paths = vec!["/data/secret.txt".into(), "/cache".into()];
let denied_files = HashSet::from(["/data/secret.txt".to_string()]);
let args = build_args_classified(&r, None, &denied_files);
let parent = policy_mount_pos(&args, "--bind", "/data");
let file_mask = policy_mount_pos(&args, "--ro-bind", "/data/secret.txt");
assert!(
file_mask > parent,
"deep denied file mask (pos {file_mask}) must come after rw /data (pos {parent}): {args:?}"
);
assert_eq!(args[file_mask + 1], "/dev/null");
policy_mount_pos(&args, "--tmpfs", "/cache");
}
#[test]
fn nested_denied_dir_and_child_file_mask_each_correctly() {
let mut r = base_request();
r.policy.denied_paths = vec!["/data/secret".into(), "/data/secret/key".into()];
let denied_files = HashSet::from(["/data/secret/key".to_string()]);
let args = build_args_classified(&r, None, &denied_files);
let parent = policy_mount_pos(&args, "--tmpfs", "/data/secret");
let child = policy_mount_pos(&args, "--ro-bind", "/data/secret/key");
assert_eq!(
args[child + 1],
"/dev/null",
"nested denied file must be masked with /dev/null: {args:?}"
);
assert!(
child > parent,
"child file mask (pos {child}) must come after parent tmpfs (pos {parent}) \
so it lands inside the masked subtree: {args:?}"
);
}
#[test]
fn environment_variables_are_set() {
let mut r = base_request();
r.env = Some(vec!["FOO=bar".into(), "PATH=/usr/bin".into()]);
let args = build_args(&r, None);
assert!(args.contains(&"--clearenv".to_string()));
let foo_pos = args.iter().position(|a| a == "FOO").unwrap();
assert_eq!(args[foo_pos - 1], "--setenv");
assert_eq!(args[foo_pos + 1], "bar");
}
#[test]
fn working_directory_is_set() {
let args = build_args(&base_request(), None);
let chdir_pos = args.iter().position(|a| a == "--chdir").unwrap();
assert_eq!(args[chdir_pos + 1], "/home/user");
}
#[test]
fn command_is_last() {
let args = build_args(&base_request(), None);
let sep = args.iter().position(|a| a == "--").unwrap();
assert_eq!(args[sep + 1], "sh");
assert_eq!(args[sep + 2], "-c");
assert_eq!(args[sep + 3], "echo hello");
}
#[test]
fn empty_working_directory_omits_chdir() {
let mut r = base_request();
r.working_directory = String::new();
let args = build_args(&r, None);
assert!(!args.contains(&"--chdir".to_string()));
}
#[test]
fn policy_mounts_under_tmp_are_not_shadowed_by_standard_tmpfs() {
let mut r = base_request();
r.policy.readwrite_paths = vec!["/tmp/workspace".into()];
r.policy.readonly_paths = vec!["/tmp/data".into()];
r.policy.denied_paths = vec!["/tmp/secrets".into()];
let args = build_args(&r, None);
let tmpfs_tmp_pos = args
.windows(2)
.position(|w| w[0] == "--tmpfs" && w[1] == "/tmp")
.expect("standard --tmpfs /tmp must be present");
let assert_after = |op: &str, target: &str| {
let pos = args
.windows(2)
.position(|w| w[0] == op && w[1] == target)
.unwrap_or_else(|| panic!("missing {} {}", op, target));
assert!(
pos > tmpfs_tmp_pos,
"{} {} (pos {}) must come after --tmpfs /tmp (pos {}) \
or it will be shadowed",
op,
target,
pos,
tmpfs_tmp_pos
);
};
assert_after("--bind", "/tmp/workspace");
assert_after("--ro-bind", "/tmp/data");
assert_after("--tmpfs", "/tmp/secrets");
}
#[test]
fn proxy_active_uses_private_network_and_external_user_namespace() {
let r = base_request();
let addr = ProxyAddress::new("127.0.0.1".into(), 12345);
let args = build_args(&r, Some(&addr));
assert!(
args.contains(&"--unshare-net".to_string()),
"proxy mode must use a private network namespace"
);
assert!(
!args.contains(&"--unshare-user".to_string()),
"the runner supplies proxy mode's pre-created user namespace"
);
}
#[test]
fn proxy_active_injects_env_vars() {
let r = base_request();
let addr = ProxyAddress::new("127.0.0.1".into(), 7777);
let args = build_args(&r, Some(&addr));
for key in &[
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"http_proxy",
"https_proxy",
"all_proxy",
] {
let pos = args
.iter()
.position(|a| a == *key)
.unwrap_or_else(|| panic!("missing --setenv {} in {:?}", key, args));
assert_eq!(args[pos - 1], "--setenv");
}
let http_pos = args.iter().position(|a| a == "HTTP_PROXY").unwrap();
assert_eq!(args[http_pos + 1], "http://127.0.0.1:7777");
}
#[test]
fn proxy_active_does_not_exempt_loopback_via_no_proxy() {
let r = base_request();
let addr = ProxyAddress::new("127.0.0.1".into(), 7777);
let args = build_args(&r, Some(&addr));
assert!(
!args.iter().any(|a| a == "NO_PROXY" || a == "no_proxy"),
"proxy mode must not emit NO_PROXY/no_proxy --setenv pairs: {:?}",
args,
);
}
#[test]
fn proxy_active_strips_caller_supplied_proxy_env() {
let mut r = base_request();
r.env = Some(vec![
"FOO=bar".into(),
"HTTP_PROXY=http://attacker.example:9999".into(),
"https_proxy=http://attacker.example:9999".into(),
"ALL_PROXY=http://attacker.example:9999".into(),
"FTP_PROXY=http://attacker.example:9999".into(),
"ftp_proxy=http://attacker.example:9999".into(),
"NO_PROXY=*".into(),
"PATH=/usr/bin".into(),
]);
let addr = ProxyAddress::new("127.0.0.1".into(), 9000);
let args = build_args(&r, Some(&addr));
assert!(
!args.iter().any(|a| a == "http://attacker.example:9999"),
"caller-supplied proxy URL must be stripped"
);
assert!(args.iter().any(|a| a == "FOO"));
assert!(args.iter().any(|a| a == "PATH"));
let http_pos = args.iter().position(|a| a == "HTTP_PROXY").unwrap();
assert_eq!(args[http_pos + 1], "http://127.0.0.1:9000");
for key in ["FTP_PROXY", "ftp_proxy"] {
let pos = args
.iter()
.position(|arg| arg == key)
.unwrap_or_else(|| panic!("missing --setenv {key} in {args:?}"));
assert_eq!(args[pos + 1], "http://127.0.0.1:9000");
}
for key in ["NO_PROXY", "no_proxy"] {
assert!(
!args.iter().any(|arg| arg == key),
"proxy mode must not emit caller-controlled {key}: {args:?}"
);
}
}
#[test]
fn proxy_inactive_leaves_caller_supplied_proxy_env_intact() {
let mut r = base_request();
r.env = Some(vec!["HTTP_PROXY=http://caller.example:8080".into()]);
let args = build_args(&r, None);
let pos = args.iter().position(|a| a == "HTTP_PROXY").unwrap();
assert_eq!(args[pos + 1], "http://caller.example:8080");
}
#[test]
fn baseline_does_not_bind_mount_host_root() {
let args = build_args(&base_request(), None);
let root_bind = args
.windows(3)
.any(|w| (w[0] == "--ro-bind" || w[0] == "--bind") && w[1] == "/" && w[2] == "/");
assert!(
!root_bind,
"baseline must not bind-mount host / into the sandbox; got: {:?}",
args
);
}
#[test]
fn baseline_emits_required_ro_bind_try_paths() {
let args = build_args(&base_request(), None);
let required = [
"/bin",
"/sbin",
"/lib",
"/lib64",
"/usr/bin",
"/usr/lib",
"/usr/share",
"/etc",
];
for path in required {
let found = args
.windows(3)
.any(|w| w[0] == "--ro-bind-try" && w[1] == path && w[2] == path);
assert!(
found,
"baseline must emit `--ro-bind-try {} {}` so sandboxed processes \
can find sh / libc / system config",
path, path
);
}
}
#[test]
fn baseline_does_not_expose_usr_local() {
let args = build_args(&base_request(), None);
let usr_whole = args
.windows(3)
.any(|w| matches!(w[0].as_str(), "--ro-bind" | "--ro-bind-try") && w[1] == "/usr");
assert!(
!usr_whole,
"baseline must bind /usr subpaths individually so /usr/local is \
not implicitly exposed; got: {:?}",
args
);
let usr_local = args.windows(3).any(|w| {
matches!(w[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try")
&& w[1] == "/usr/local"
});
assert!(!usr_local, "baseline must not expose /usr/local by default");
}
#[test]
fn baseline_excludes_confidential_paths() {
let args = build_args(&base_request(), None);
for forbidden in [
"/home",
"/root",
"/opt",
"/srv",
"/var",
"/sys",
"/run/user",
"/run/dbus",
] {
let exposed = args.windows(2).any(|w| {
matches!(w[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try")
&& w[1] == forbidden
});
assert!(
!exposed,
"baseline must not bind-mount {} — that would re-expose \
confidential host state",
forbidden
);
}
}
#[test]
fn baseline_includes_dns_stub_resolver_dirs() {
let args = build_args(&base_request(), None);
for path in [
"/run/systemd/resolve",
"/run/NetworkManager",
"/run/resolvconf",
] {
let found = args
.windows(3)
.any(|w| w[0] == "--ro-bind-try" && w[1] == path && w[2] == path);
assert!(
found,
"baseline must emit `--ro-bind-try {} {}` so the sandbox can read \
/etc/resolv.conf when it is a symlink",
path, path
);
}
}
#[test]
fn baseline_recreates_var_run_compat_symlink() {
let args = build_args(&base_request(), None);
let found = args
.windows(3)
.any(|w| w[0] == "--symlink" && w[1] == "/run" && w[2] == "/var/run");
assert!(
found,
"baseline must emit `--symlink /run /var/run` so /etc/resolv.conf \
symlinks routed through /var/run/... resolve; got: {:?}",
args
);
let var_bound = args.windows(2).any(|w| {
matches!(w[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try") && w[1] == "/var"
});
assert!(!var_bound, "compat symlink must not bind host /var");
}
#[test]
fn baseline_includes_wsl_resolv_conf() {
let args = build_args(&base_request(), None);
let found = args.windows(3).any(|w| {
w[0] == "--ro-bind-try"
&& w[1] == "/mnt/wsl/resolv.conf"
&& w[2] == "/mnt/wsl/resolv.conf"
});
assert!(
found,
"baseline must emit `--ro-bind-try /mnt/wsl/resolv.conf ...` so DNS \
works under WSL; got: {:?}",
args
);
let mnt_whole = args.windows(2).any(|w| {
matches!(w[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try")
&& (w[1] == "/mnt" || w[1] == "/mnt/wsl")
});
assert!(
!mnt_whole,
"baseline must not expose /mnt or /mnt/wsl wholesale"
);
}
#[test]
fn baseline_mounts_precede_policy_mounts() {
let mut r = base_request();
r.policy.readwrite_paths = vec!["/etc/policy-writable".into()];
let args = build_args(&r, None);
let baseline_etc = args
.windows(3)
.position(|w| w[0] == "--ro-bind-try" && w[1] == "/etc" && w[2] == "/etc")
.expect("baseline /etc bind missing");
let policy_bind = args
.windows(3)
.position(|w| w[0] == "--bind" && w[1] == "/etc/policy-writable")
.expect("policy bind missing");
assert!(
policy_bind > baseline_etc,
"policy mount at /etc/policy-writable (pos {}) must come after \
baseline /etc bind (pos {}) so the policy mount wins",
policy_bind,
baseline_etc
);
}
}