#![cfg(all(feature = "hyperlight", target_arch = "x86_64"))]
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{
ExecutionRequest, FailurePhase, HyperlightRuntime, ScriptResponse,
};
use crate::mxc_common::script_runner::ScriptRunner;
use crate::mxc_common::validator::{
validate_common, validate_network_policy_support, NetworkPolicySupport,
};
use hyperlight_unikraft::hyperlight_host::HyperlightError;
use hyperlight_unikraft::{AppSandbox, Mount, SandboxBuilder, Snapshot, Yield};
#[cfg(target_os = "linux")]
pub fn is_kvm_available() -> bool {
std::fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/kvm")
.is_ok()
}
#[cfg(target_os = "windows")]
pub fn is_whp_available() -> bool {
use windows::core::w;
use windows::Win32::System::LibraryLoader::{LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32};
let module =
unsafe { LoadLibraryExW(w!("winhvplatform.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) };
module.is_ok()
}
#[derive(Debug)]
enum RunnerError {
Policy(String),
Unavailable(String),
Setup(String),
Launch(String),
Exec(String),
Timeout(String),
}
impl std::fmt::Display for RunnerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RunnerError::Policy(msg) => write!(f, "hyperlight policy error: {msg}"),
RunnerError::Unavailable(msg) => {
write!(f, "hyperlight is not available on this host: {msg}")
}
RunnerError::Setup(msg) => write!(f, "hyperlight setup error: {msg}"),
RunnerError::Launch(msg) | RunnerError::Exec(msg) | RunnerError::Timeout(msg) => {
write!(f, "hyperlight runtime error: {msg}")
}
}
}
}
impl RunnerError {
fn failure_phase(&self) -> FailurePhase {
match self {
RunnerError::Policy(_) => FailurePhase::Rejected,
RunnerError::Unavailable(_) => FailurePhase::BackendUnavailable,
RunnerError::Setup(_) | RunnerError::Launch(_) => FailurePhase::LaunchFailed,
RunnerError::Exec(_) => FailurePhase::PostLaunchFailed,
RunnerError::Timeout(_) => FailurePhase::Timeout,
}
}
fn to_response(&self) -> ScriptResponse {
ScriptResponse::failed(self.failure_phase(), &self.to_string())
}
}
const HOME_ENV: &str = "MXC_HYPERLIGHT_HOME";
const EXE_RELATIVE_HOME: &str = "mxc-hyperlight";
const CWD_RELATIVE_HOME: &str = ".mxc-hyperlight";
const DEFAULT_HOME_LEAF: &str = "mxc-hyperlight";
const INITRD_FILE: &str = "initrd.cpio";
const SNAPSHOT_DIR: &str = "snapshot";
const VERSION_FILE: &str = "VERSION";
const ROOTFS_TAG: &str = "initrd-v0.21.0";
const ROOTFS_PATH_IN_IMAGE: &str = "/initrd.cpio";
const GUEST_MOUNT_ROOT: &str = "/host";
const SETUP_BIN: &str = if cfg!(windows) {
"wxc-exec"
} else {
"lxc-exec"
};
struct RuntimeImage {
image: String,
scratch_mb: usize,
}
fn runtime_image(runtime: HyperlightRuntime) -> RuntimeImage {
let scratch_mb = match runtime {
HyperlightRuntime::Agent => 1536,
HyperlightRuntime::Python | HyperlightRuntime::PythonShell | HyperlightRuntime::Bash => 256,
HyperlightRuntime::Node => 512,
HyperlightRuntime::DotnetJit => 768,
};
RuntimeImage {
image: format!(
"ghcr.io/hyperlight-dev/hyperlight-unikraft/{}",
runtime.name()
),
scratch_mb,
}
}
const ERR_PROXY_POLICY: &str = "network proxy is not supported by the hyperlight backend";
const ERR_WORKDIR: &str =
"workingDirectory is not supported by the hyperlight backend -- guest has its own filesystem namespace";
fn no_install_source(runtime: HyperlightRuntime) -> String {
let name = runtime.name();
format!(
"no warmed {name} snapshot and no rootfs to install from. drop `{INITRD_FILE}` into \
the runtime's directory of the image home (or run `--setup-hyperlight={name}`)."
)
}
pub struct HyperlightScriptRunner {
guest: Option<Guest>,
rewind: Option<Arc<Snapshot>>,
active_home: Option<PathBuf>,
active_mounts: Vec<Mount>,
}
struct Guest {
sandbox: AppSandbox,
fresh: bool,
}
#[derive(Debug, Default)]
struct RunTiming {
restore_ms: f64,
call_ms: f64,
exit_code: i32,
}
enum RunError {
TimedOut(Duration),
Failed(String),
}
impl Default for HyperlightScriptRunner {
fn default() -> Self {
Self::new()
}
}
pub fn parse_runtimes(names: &[String]) -> Result<Vec<HyperlightRuntime>, String> {
if names.is_empty() {
return Ok(vec![HyperlightRuntime::default()]);
}
names.iter().map(|name| name.parse()).collect()
}
pub fn setup(
force: bool,
runtimes: &[HyperlightRuntime],
logger: &mut Logger,
) -> Result<PathBuf, String> {
let root = match std::env::var_os(HOME_ENV) {
Some(v) => PathBuf::from(v),
None => HyperlightScriptRunner::default_home(),
};
for &runtime in runtimes {
let home = root.join(runtime.name());
if !force && is_installed(&home, runtime) {
logger.log_line(&format!(
"hyperlight: {} snapshot already present at {:?}; nothing to do \
(pass --force to rebuild)",
runtime.name(),
home.join(SNAPSHOT_DIR)
));
continue;
}
std::fs::create_dir_all(&home).map_err(|e| format!("create image home {home:?}: {e}"))?;
if has_install_source(&home, runtime) {
logger.log_line(&format!(
"hyperlight setup: rootfs present at {:?}",
home.join(INITRD_FILE)
));
} else {
logger.log_line(&format!(
"hyperlight setup: pulling {}:{ROOTFS_TAG}",
runtime_image(runtime).image
));
pull_rootfs(&home.join(INITRD_FILE), runtime, logger)?;
std::fs::write(home.join(VERSION_FILE), version_stamp(runtime))
.map_err(|e| format!("write {VERSION_FILE}: {e}"))?;
}
let (_, persisted) = warm_snapshot(&home, runtime, logger).map_err(|e| e.to_string())?;
if !persisted {
return Err(format!(
"the snapshot could not be put in place at {:?}; the log above says why",
home.join(SNAPSHOT_DIR)
));
}
}
Ok(root)
}
impl HyperlightScriptRunner {
pub fn new() -> Self {
Self {
guest: None,
rewind: None,
active_home: None,
active_mounts: Vec::new(),
}
}
fn resolve_home(runtime: HyperlightRuntime) -> Result<PathBuf, RunnerError> {
let name = runtime.name();
let mut stale = None;
for root in Self::search_paths() {
let cand = root.join(name);
if is_installed(&cand, runtime) || has_install_source(&cand, runtime) {
return Ok(cand);
}
if stale.is_none() && cand.join(INITRD_FILE).is_file() {
stale = Some(cand);
}
}
let default = Self::default_home();
let hint = match stale {
Some(home) => format!(
"{home:?} holds a rootfs from another hyperlight-unikraft release; \
run `{SETUP_BIN} --setup-hyperlight={name}` to rebuild it."
),
None => format!(
"run `{SETUP_BIN} --setup-hyperlight={name}` \
(or drop `{INITRD_FILE}` into {:?}).",
default.join(name)
),
};
Err(RunnerError::Unavailable(format!(
"no hyperlight image found for the {name} runtime. searched ${HOME_ENV}, \
{default:?}, <exe>/{EXE_RELATIVE_HOME}/, <cwd>/{CWD_RELATIVE_HOME}/, each under \
`{name}/`. {hint}"
)))
}
fn search_paths() -> Vec<PathBuf> {
let mut paths = Vec::with_capacity(4);
if let Some(explicit) = std::env::var_os(HOME_ENV) {
paths.push(PathBuf::from(explicit));
}
paths.push(Self::default_home());
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
paths.push(dir.join(EXE_RELATIVE_HOME));
}
}
if let Ok(cwd) = std::env::current_dir() {
paths.push(cwd.join(CWD_RELATIVE_HOME));
}
paths
}
fn default_home() -> PathBuf {
os_data_home().join(DEFAULT_HOME_LEAF)
}
fn validate_policies(request: &ExecutionRequest) -> Result<(), RunnerError> {
if request.policy.network_proxy.is_enabled() {
return Err(RunnerError::Policy(ERR_PROXY_POLICY.to_string()));
}
if !request.working_directory.is_empty() {
return Err(RunnerError::Policy(ERR_WORKDIR.to_string()));
}
for denied in &request.policy.denied_paths {
for allowed in request
.policy
.readwrite_paths
.iter()
.chain(request.policy.readonly_paths.iter())
{
match path_relationship(allowed, denied) {
PathRelationship::Overlaps => {
return Err(RunnerError::Policy(format!(
"deniedPaths entry {denied:?} overlaps allow list path {allowed:?}; \
Hyperlight cannot safely expose overlapping allowed and denied \
host paths"
)));
}
PathRelationship::Separate => {}
PathRelationship::Unresolvable(reason) => {
return Err(RunnerError::Setup(format!(
"Hyperlight: cannot verify deniedPaths against allow lists because \
the host could not resolve {allowed:?} or {denied:?} ({reason}). \
With deniedPaths present, MXC fails closed rather than risk an \
unenforced deny."
)));
}
PathRelationship::Inaccessible(reason) => {
return Err(RunnerError::Policy(format!(
"Hyperlight: cannot verify deniedPaths against allow lists because \
the invoking user cannot access {allowed:?} or {denied:?} \
({reason}). Grant access to both paths, or remove the deniedPaths \
entry."
)));
}
#[cfg(target_os = "windows")]
PathRelationship::Ambiguous => {
return Err(RunnerError::Policy(format!(
"Hyperlight: cannot verify deniedPaths against allow lists because \
{allowed:?} or {denied:?} could not be resolved to a canonical \
location. With deniedPaths present, MXC fails closed rather than \
risk an unenforced deny. Ensure both paths are accessible, or remove \
the deniedPaths entry."
)));
}
}
}
}
Ok(())
}
fn mounts_from_policy(request: &ExecutionRequest) -> Result<Vec<Mount>, RunnerError> {
let mut mounts = Vec::new();
let mut seen_guest_paths = std::collections::HashSet::new();
let rw_iter = request.policy.readwrite_paths.iter().map(|p| (p, false));
let ro_iter = request.policy.readonly_paths.iter().map(|p| (p, true));
for (host, read_only) in rw_iter.chain(ro_iter) {
let host_path = PathBuf::from(host);
if !host_path.exists() {
let parent_ok = host_path
.parent()
.map(|p| p.as_os_str().is_empty() || p.exists())
.unwrap_or(false);
if !parent_ok {
return Err(RunnerError::Policy(format!(
"mount path {host:?} does not exist and its parent doesn't either; \
refusing to auto-create (fix the path or `mkdir -p` manually)"
)));
}
std::fs::create_dir_all(&host_path).map_err(|e| {
RunnerError::Setup(format!("auto-create mount dir {host:?}: {e}"))
})?;
}
let host_path = std::fs::canonicalize(&host_path)
.map_err(|e| RunnerError::Setup(format!("resolve mount path {host:?}: {e}")))?;
let basename = host_path
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| {
RunnerError::Policy(format!("mount path {host:?} has no filename component"))
})?;
if basename
.chars()
.any(|c| c.is_whitespace() || matches!(c, ':' | '[' | ']'))
{
return Err(RunnerError::Policy(format!(
"mount path {host:?}: the directory name may not contain whitespace, \
':' or brackets (it names the guest mount point)"
)));
}
let guest_path = format!("{GUEST_MOUNT_ROOT}/{basename}");
if !seen_guest_paths.insert(guest_path.clone()) {
return Err(RunnerError::Policy(format!(
"two mount paths collide on guest path {guest_path:?}; \
rename one of the host directories"
)));
}
mounts.push(if read_only {
Mount::ro(host_path, guest_path)
} else {
Mount::rw(host_path, guest_path)
});
}
Ok(mounts)
}
fn ensure_runtime(
&mut self,
home: &Path,
runtime: HyperlightRuntime,
mounts: Vec<Mount>,
logger: &mut Logger,
) -> Result<(&mut Guest, Arc<Snapshot>), RunnerError> {
let same_config =
self.active_home.as_deref() == Some(home) && mounts_equal(&self.active_mounts, &mounts);
if !same_config {
self.guest = None;
if self.active_home.as_deref() != Some(home) {
self.rewind = None;
}
self.active_home = Some(home.to_path_buf());
self.active_mounts = mounts;
}
let rewind = match self.rewind.clone() {
Some(rewind) => rewind,
None => {
configure_surrogates();
let rewind = load_persisted_snapshot(home, runtime, logger)?;
self.rewind = Some(rewind.clone());
rewind
}
};
let guest = match self.guest.take() {
Some(guest) => guest,
None => {
configure_surrogates();
Self::boot_from_snapshot(rewind.clone(), &self.active_mounts)?
}
};
Ok((self.guest.insert(guest), rewind))
}
fn boot_from_snapshot(rewind: Arc<Snapshot>, mounts: &[Mount]) -> Result<Guest, RunnerError> {
let builder = SandboxBuilder::from_snapshot(rewind)
.mounts(mounts.iter().cloned())
.output_limit(0);
let sandbox = builder
.boot()
.map_err(|e| RunnerError::Launch(format!("restore hyperlight snapshot: {e}")))?;
Ok(Guest {
sandbox,
fresh: true,
})
}
fn run_once(
guest: &mut Guest,
rewind: &Arc<Snapshot>,
code: &str,
timeout: Option<Duration>,
) -> Result<RunTiming, RunError> {
let mut timing = RunTiming::default();
if !guest.fresh {
let t = Instant::now();
guest
.sandbox
.restore(rewind.clone())
.map_err(|e| RunError::Failed(format!("rewind guest: {e}")))?;
timing.restore_ms = t.elapsed().as_secs_f64() * 1000.0;
}
guest.fresh = false;
let t = Instant::now();
let result = match timeout {
Some(timeout) => run_with_deadline(&mut guest.sandbox, code, timeout),
None => match guest.sandbox.run(code) {
Ok(()) => Ok(0),
Err(hyperlight_unikraft::Error::CallFailed { status }) => Ok(status),
Err(e) => Err(RunError::Failed(e.to_string())),
},
};
timing.call_ms = t.elapsed().as_secs_f64() * 1000.0;
let _ = guest.sandbox.drain_output();
timing.exit_code = result?;
if timing.exit_code < 0 {
return Err(RunError::Failed(format!(
"the guest driver could not run the call (status {})",
timing.exit_code
)));
}
Ok(timing)
}
fn execute_validated(
&mut self,
request: &ExecutionRequest,
logger: &mut Logger,
) -> ScriptResponse {
let runtime = request
.hyperlight
.as_ref()
.map(|h| h.runtime)
.unwrap_or_default();
let home = match Self::resolve_home(runtime) {
Ok(h) => h,
Err(e) => {
logger.log_line(&e.to_string());
return e.to_response();
}
};
let mounts = match Self::mounts_from_policy(request) {
Ok(m) => m,
Err(e) => {
logger.log_line(&e.to_string());
return e.to_response();
}
};
let (guest, rewind) = match self.ensure_runtime(&home, runtime, mounts, logger) {
Ok(pair) => pair,
Err(e) => {
logger.log_line(&e.to_string());
return e.to_response();
}
};
let timeout = (request.script_timeout > 0).then(|| {
logger.log_line(&format!(
"hyperlight: timeout set to {}ms",
request.script_timeout
));
Duration::from_millis(u64::from(request.script_timeout))
});
match Self::run_once(guest, &rewind, &request.script_code, timeout) {
Ok(timing) => {
logger.log_line(&format!(
"hyperlight: run ok (restore={:.1}ms call={:.1}ms exit={})",
timing.restore_ms, timing.call_ms, timing.exit_code
));
ScriptResponse {
exit_code: timing.exit_code,
..Default::default()
}
}
Err(failure) => {
self.guest = None;
let err = match failure {
RunError::TimedOut(timeout) => RunnerError::Timeout(format!(
"execution timed out after {:.1}s",
timeout.as_secs_f64()
)),
RunError::Failed(msg) => RunnerError::Exec(format!("run: {msg}")),
};
logger.log_line(&err.to_string());
err.to_response()
}
}
}
}
impl ScriptRunner for HyperlightScriptRunner {
fn validate_runner(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> {
Self::validate_policies(request).map_err(|e| e.to_response())?;
validate_network_policy_support(request, NetworkPolicySupport::default())?;
Ok(())
}
fn run(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
if let Err(response) = validate_common(request) {
return response;
}
if let Err(response) = self.validate_runner(request) {
return response;
}
if request.dry_run {
return ScriptResponse {
exit_code: 0,
..Default::default()
};
}
self.execute_validated(request, logger)
}
fn execute(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
if let Err(response) = self.validate_runner(request) {
return response;
}
self.execute_validated(request, logger)
}
}
fn run_with_deadline(
sandbox: &mut AppSandbox,
code: &str,
timeout: Duration,
) -> Result<i32, RunError> {
let deadline = Instant::now() + timeout;
let (finished_tx, finished_rx) = mpsc::channel::<()>();
let watchdog = {
let handle = sandbox.interrupt_handle();
std::thread::spawn(move || {
let mut wait = deadline.saturating_duration_since(Instant::now());
loop {
match finished_rx.recv_timeout(wait) {
Err(RecvTimeoutError::Timeout) => {}
_ => return,
}
if handle.kill() {
return;
}
wait = Duration::from_millis(10);
}
})
};
let outcome = drive_until(sandbox, code, deadline);
drop(finished_tx);
let _ = watchdog.join();
match outcome {
Ok(Some(status)) => Ok(status),
Ok(None) => Err(RunError::TimedOut(timeout)),
Err(hyperlight_unikraft::Error::Hyperlight(HyperlightError::ExecutionCanceledByHost())) => {
Err(RunError::TimedOut(timeout))
}
Err(e) => Err(RunError::Failed(e.to_string())),
}
}
fn drive_until(
sandbox: &mut AppSandbox,
code: &str,
deadline: Instant,
) -> Result<Option<i32>, hyperlight_unikraft::Error> {
sandbox.submit(code)?;
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Ok(None);
}
match sandbox.step(remaining)? {
Yield::CallDone => return Ok(Some(0)),
Yield::CallFailed { status } => return Ok(Some(status)),
Yield::Exited { status } => {
return Err(hyperlight_unikraft::Error::GuestExited { status })
}
Yield::Blocked { .. } => {}
}
}
}
fn warm_snapshot(
home: &Path,
runtime: HyperlightRuntime,
logger: &mut Logger,
) -> Result<(Arc<Snapshot>, bool), RunnerError> {
let snapshot_dir = home.join(SNAPSHOT_DIR);
logger.log_line(&format!(
"hyperlight: booting {:?} to warm a snapshot",
home.join(INITRD_FILE)
));
let t = Instant::now();
configure_surrogates();
let mut sandbox = rootfs_builder(home, runtime)
.boot()
.map_err(|e| RunnerError::Launch(format!("boot hyperlight rootfs: {e}")))?;
let staged = home.join(format!(".{SNAPSHOT_DIR}.{}.part", std::process::id()));
let _ = std::fs::remove_dir_all(&staged);
let snapshot = match sandbox.snapshot_to(&staged) {
Ok(snapshot) => snapshot,
Err(e) => {
let _ = std::fs::remove_dir_all(&staged);
return Err(RunnerError::Launch(format!(
"save snapshot to {staged:?}: {e}"
)));
}
};
let persisted = publish_snapshot(home, &staged, &snapshot_dir, logger);
logger.log_line(&format!(
"hyperlight: warm-up took {:.1}ms; snapshot at {snapshot_dir:?}",
t.elapsed().as_secs_f64() * 1000.0
));
Ok((snapshot, persisted))
}
fn publish_snapshot(home: &Path, staged: &Path, snapshot_dir: &Path, logger: &mut Logger) -> bool {
let old = home.join(format!(".{SNAPSHOT_DIR}.{}.old", std::process::id()));
let had_old = match std::fs::rename(snapshot_dir, &old) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => {
logger.log_line(&format!(
"hyperlight: set aside old snapshot {snapshot_dir:?}: {e}"
));
let _ = std::fs::remove_dir_all(staged);
return false;
}
};
let moved = std::fs::rename(staged, snapshot_dir);
if let Err(e) = &moved {
logger.log_line(&format!(
"hyperlight: move snapshot into place at {snapshot_dir:?}: {e}"
));
let _ = std::fs::remove_dir_all(staged);
}
match (moved, had_old) {
(Ok(()), true) => {
let _ = std::fs::remove_dir_all(&old);
true
}
(Ok(()), false) => true,
(Err(_), true) => {
if std::fs::rename(&old, snapshot_dir).is_ok() {
logger.log_line(&format!(
"hyperlight: old snapshot put back at {snapshot_dir:?}"
));
return false;
}
if hyperlight_unikraft::load_snapshot(snapshot_dir).is_ok() {
logger.log_line(&format!(
"hyperlight: another warm published {snapshot_dir:?} first"
));
let _ = std::fs::remove_dir_all(&old);
return true;
}
logger.log_line(&format!("hyperlight: old snapshot left at {old:?}"));
false
}
(Err(_), false) => {
let landed = hyperlight_unikraft::load_snapshot(snapshot_dir).is_ok();
if landed {
logger.log_line(&format!(
"hyperlight: another warm published {snapshot_dir:?} first"
));
}
landed
}
}
}
fn load_persisted_snapshot(
home: &Path,
runtime: HyperlightRuntime,
logger: &mut Logger,
) -> Result<Arc<Snapshot>, RunnerError> {
let snapshot_dir = home.join(SNAPSHOT_DIR);
let unloadable = match hyperlight_unikraft::load_snapshot(&snapshot_dir) {
Ok(snapshot) => {
logger.log_line(&format!("hyperlight: using image home {home:?}"));
return Ok(snapshot);
}
Err(e) => e,
};
if !has_install_source(home, runtime) {
return Err(RunnerError::Unavailable(no_install_source(runtime)));
}
logger.log_line(&match unloadable {
hyperlight_unikraft::Error::SnapshotRelease { saved_by, .. } => format!(
"hyperlight: the snapshot at {snapshot_dir:?} was saved by hyperlight-unikraft \
{saved_by}; warming one for this build from the rootfs"
),
e => format!(
"hyperlight: no snapshot to load at {snapshot_dir:?} ({e}); warming one from the \
rootfs"
),
});
let (snapshot, persisted) = warm_snapshot(home, runtime, logger)?;
if !persisted {
logger.log_line(
"hyperlight: running from the warm image in memory; the next run warms again",
);
}
Ok(snapshot)
}
fn rootfs_builder(home: &Path, runtime: HyperlightRuntime) -> SandboxBuilder {
SandboxBuilder::from_initrd(home.join(INITRD_FILE))
.scratch_mb(runtime_image(runtime).scratch_mb)
.output_limit(0)
}
fn pull_rootfs(dst: &Path, runtime: HyperlightRuntime, logger: &mut Logger) -> Result<(), String> {
let staged = dst.with_file_name(format!(".{INITRD_FILE}.{}.part", std::process::id()));
let pulled = oci::fetch_file(
&runtime_image(runtime).image,
ROOTFS_TAG,
ROOTFS_PATH_IN_IMAGE,
&staged,
logger,
);
if pulled.is_err() {
let _ = std::fs::remove_file(&staged);
}
pulled?;
let _ = std::fs::remove_file(dst);
if let Err(e) = std::fs::rename(&staged, dst) {
let _ = std::fs::remove_file(&staged);
return Err(format!("move rootfs into place at {dst:?}: {e}"));
}
Ok(())
}
mod oci {
use std::io::Read;
use std::path::Path;
use std::time::Duration;
use crate::mxc_common::encoding::lowercase_hex;
use crate::mxc_common::logger::Logger;
use sha2::{Digest, Sha256};
const MANIFEST_TYPES: &str = "application/vnd.oci.image.manifest.v1+json, \
application/vnd.oci.image.index.v1+json, \
application/vnd.docker.distribution.manifest.v2+json, \
application/vnd.docker.distribution.manifest.list.v2+json";
pub(super) fn fetch_file(
image: &str,
tag: &str,
path_in_image: &str,
dst: &Path,
logger: &mut Logger,
) -> Result<(), String> {
let (registry, repo) = image
.split_once('/')
.ok_or_else(|| format!("image {image:?} names no registry host"))?;
let agent = ureq::Agent::config_builder()
.timeout_resolve(Some(Duration::from_secs(30)))
.timeout_connect(Some(Duration::from_secs(30)))
.timeout_recv_response(Some(Duration::from_secs(60)))
.timeout_recv_body(Some(Duration::from_secs(30 * 60)))
.tls_config(
ureq::tls::TlsConfig::builder()
.provider(ureq::tls::TlsProvider::NativeTls)
.build(),
)
.build()
.new_agent();
let token = pull_token(&agent, registry, repo)?;
let get = |url: String, accept: &str| -> Result<ureq::Body, String> {
agent
.get(&url)
.header("Authorization", &format!("Bearer {token}"))
.header("Accept", accept)
.call()
.map(|response| response.into_body())
.map_err(|e| format!("GET {url}: {e}"))
};
let manifests_url = format!("https://{registry}/v2/{repo}/manifests");
let mut manifest = read_json(get(format!("{manifests_url}/{tag}"), MANIFEST_TYPES)?)?;
if let Some(entries) = manifest.get("manifests").and_then(|m| m.as_array()) {
let digest = entries
.iter()
.find(|m| {
m["platform"]["os"] == "linux" && m["platform"]["architecture"] == "amd64"
})
.and_then(|m| m["digest"].as_str())
.ok_or_else(|| format!("{image}:{tag} has no linux/amd64 manifest"))?
.to_string();
manifest = read_json(get(format!("{manifests_url}/{digest}"), MANIFEST_TYPES)?)?;
}
let layers = manifest["layers"]
.as_array()
.ok_or_else(|| format!("{image}:{tag}: manifest lists no layers"))?;
let wanted = path_in_image.trim_start_matches('/');
let mut found = false;
for layer in layers {
let digest = layer["digest"]
.as_str()
.ok_or_else(|| format!("{image}:{tag}: a layer has no digest"))?;
let media_type = layer["mediaType"].as_str().unwrap_or_default();
if media_type.ends_with("zstd") {
return Err(format!(
"{image}:{tag}: zstd-compressed layers are not supported"
));
}
let size_mib = layer["size"].as_u64().unwrap_or(0) / (1024 * 1024);
logger.log_line(&format!(
"hyperlight setup: downloading {image}:{tag} layer {digest} ({size_mib} MiB)"
));
let body = get(
format!("https://{registry}/v2/{repo}/blobs/{digest}"),
"application/octet-stream",
)?;
let mut blob = Digested::new(body.into_reader());
found |= extract(&mut blob, media_type.ends_with("gzip"), wanted, dst)?;
std::io::copy(&mut blob, &mut std::io::sink())
.map_err(|e| format!("read layer {digest}: {e}"))?;
let actual = blob.digest();
if actual != digest {
return Err(format!("layer {digest} arrived with digest {actual}"));
}
}
if found {
Ok(())
} else {
Err(format!("{image}:{tag} has no {path_in_image}"))
}
}
fn pull_token(agent: &ureq::Agent, registry: &str, repo: &str) -> Result<String, String> {
let url = format!("https://{registry}/token?scope=repository:{repo}:pull");
let body = agent
.get(&url)
.call()
.map(|response| response.into_body())
.map_err(|e| format!("GET {url}: {e}"))?;
read_json(body)?["token"]
.as_str()
.map(str::to_string)
.ok_or_else(|| format!("{registry} token response carries no token"))
}
fn read_json(mut body: ureq::Body) -> Result<serde_json::Value, String> {
let bytes = body
.read_to_vec()
.map_err(|e| format!("read response: {e}"))?;
serde_json::from_slice(&bytes).map_err(|e| format!("parse response: {e}"))
}
fn extract(
blob: &mut impl Read,
gzipped: bool,
wanted: &str,
dst: &Path,
) -> Result<bool, String> {
let reader: Box<dyn Read + '_> = if gzipped {
Box::new(flate2::read::GzDecoder::new(blob))
} else {
Box::new(blob)
};
let mut archive = tar::Archive::new(reader);
let mut found = false;
for entry in archive.entries().map_err(|e| format!("read layer: {e}"))? {
let mut entry = entry.map_err(|e| format!("read layer entry: {e}"))?;
let is_wanted = {
let path = entry.path().map_err(|e| format!("read layer entry: {e}"))?;
let name = path.to_string_lossy();
name.trim_start_matches("./").trim_start_matches('/') == wanted
};
if !is_wanted {
continue;
}
if !entry.header().entry_type().is_file() {
return Err(format!("{wanted} in the layer is not a regular file"));
}
let mut file =
std::fs::File::create(dst).map_err(|e| format!("create {dst:?}: {e}"))?;
let written =
std::io::copy(&mut entry, &mut file).map_err(|e| format!("write {dst:?}: {e}"))?;
if written == 0 {
return Err(format!("{wanted} in the layer is empty"));
}
found = true;
break;
}
Ok(found)
}
struct Digested<R> {
inner: R,
hasher: Sha256,
}
impl<R: Read> Digested<R> {
fn new(inner: R) -> Self {
Self {
inner,
hasher: Sha256::new(),
}
}
fn digest(&self) -> String {
let digest = lowercase_hex(&self.hasher.clone().finalize());
format!("sha256:{digest}")
}
}
impl<R: Read> Read for Digested<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.inner.read(buf)?;
self.hasher.update(&buf[..n]);
Ok(n)
}
}
}
fn configure_surrogates() {
#[cfg(windows)]
hyperlight_unikraft::configure_surrogates(0);
}
fn is_installed(home: &Path, runtime: HyperlightRuntime) -> bool {
stamp_matches(home, runtime)
&& hyperlight_unikraft::load_snapshot(home.join(SNAPSHOT_DIR)).is_ok()
}
fn has_install_source(home: &Path, runtime: HyperlightRuntime) -> bool {
home.join(INITRD_FILE).is_file() && stamp_matches(home, runtime)
}
fn version_stamp(runtime: HyperlightRuntime) -> String {
format!("rootfs: {}:{ROOTFS_TAG}\n", runtime_image(runtime).image)
}
fn stamp_matches(home: &Path, runtime: HyperlightRuntime) -> bool {
match std::fs::read_to_string(home.join(VERSION_FILE)) {
Ok(stamp) => stamp.trim() == version_stamp(runtime).trim(),
Err(e) => e.kind() == std::io::ErrorKind::NotFound,
}
}
fn path_relationship(allowed: &str, denied: &str) -> PathRelationship {
let (allowed, denied) = match (anchor_policy_path(allowed), anchor_policy_path(denied)) {
(Ok(allowed), Ok(denied)) => (allowed, denied),
(Err(e), _) | (_, Err(e)) => {
return PathRelationship::Unresolvable(format!(
"could not read the current directory: {e}"
));
}
};
match (
std::fs::canonicalize(&allowed),
std::fs::canonicalize(&denied),
) {
(Ok(allowed), Ok(denied)) => PathRelationship::from_overlaps(
denied.starts_with(&allowed) || allowed.starts_with(&denied),
),
(allowed_lookup, denied_lookup) => classify_unresolvable(
path_relationship_fallback(&allowed.to_string_lossy(), &denied.to_string_lossy()),
[&allowed_lookup, &denied_lookup],
),
}
}
fn classify_unresolvable(
relationship: PathRelationship,
lookups: [&std::io::Result<PathBuf>; 2],
) -> PathRelationship {
let access_denied = lookups
.iter()
.any(|lookup| matches!(lookup, Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied));
match relationship {
PathRelationship::Unresolvable(reason) if access_denied => {
PathRelationship::Inaccessible(reason)
}
other => other,
}
}
fn anchor_policy_path(path: &str) -> Result<PathBuf, std::io::Error> {
let path = Path::new(path);
if path.is_absolute() {
Ok(path.to_path_buf())
} else {
Ok(std::env::current_dir()?.join(path))
}
}
#[derive(Debug, PartialEq, Eq)]
enum PathRelationship {
Overlaps,
Separate,
#[cfg(target_os = "windows")]
Ambiguous,
Unresolvable(String),
Inaccessible(String),
}
impl PathRelationship {
fn from_overlaps(overlaps: bool) -> Self {
if overlaps {
Self::Overlaps
} else {
Self::Separate
}
}
}
#[cfg(target_os = "windows")]
fn path_relationship_fallback(allowed: &str, denied: &str) -> PathRelationship {
use crate::mxc_common::filesystem_canonical::canonicalize_allowing_absent_tail;
path_relationship_fallback_with(allowed, denied, canonicalize_allowing_absent_tail)
}
#[cfg(target_os = "windows")]
fn path_relationship_fallback_with(
allowed: &str,
denied: &str,
resolve: impl Fn(&str) -> crate::mxc_common::filesystem_canonical::PathCanonical,
) -> PathRelationship {
use crate::mxc_common::filesystem_canonical::PathCanonical;
match (resolve(allowed), resolve(denied)) {
(PathCanonical::Canonical(allowed_resolved), PathCanonical::Canonical(denied_resolved)) => {
let Some(allowed_norm) =
WindowsFallbackPath::parse_canonical(allowed, &allowed_resolved)
else {
return PathRelationship::Ambiguous;
};
let Some(denied_norm) = WindowsFallbackPath::parse_canonical(denied, &denied_resolved)
else {
return PathRelationship::Ambiguous;
};
return PathRelationship::from_overlaps(allowed_norm.overlaps(&denied_norm));
}
(PathCanonical::Unknown, _) => {
return PathRelationship::Unresolvable(format!("{allowed:?} could not be examined"));
}
(_, PathCanonical::Unknown) => {
return PathRelationship::Unresolvable(format!("{denied:?} could not be examined"));
}
_ => {}
}
PathRelationship::from_overlaps(
WindowsFallbackPath::parse(allowed).overlaps(&WindowsFallbackPath::parse(denied)),
)
}
#[cfg(target_os = "windows")]
#[derive(Debug, PartialEq, Eq)]
struct WindowsFallbackPath {
drive: Option<String>,
rooted: bool,
components: Vec<String>,
}
#[cfg(target_os = "windows")]
impl WindowsFallbackPath {
fn parse(path: &str) -> Self {
Self::parse_with_trailing_policy(path, has_verbatim_trim_sensitive_component(path))
}
fn parse_canonical(source: &str, resolved: &str) -> Option<Self> {
if has_trim_sensitive_component(source)
&& !has_verbatim_trim_sensitive_component(source)
&& has_trim_sensitive_component(resolved)
{
return None;
}
Some(Self::parse_with_trailing_policy(resolved, true))
}
fn parse_with_trailing_policy(path: &str, preserve_trailing_dots_and_spaces: bool) -> Self {
let (folded, verbatim) = normalize_windows_verbatim_prefix(&path.to_lowercase());
let bytes = folded.as_bytes();
let (drive, rest) =
if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
(Some(folded[..2].to_string()), &folded[2..])
} else {
(None, folded.as_str())
};
let rooted = rest.starts_with(['\\', '/']);
let mut components = Vec::new();
for segment in rest.split(['\\', '/']).filter(|s| !s.is_empty()) {
match segment {
"." => {}
".." => {
if components.last().is_some_and(|last| last != "..") {
components.pop();
} else if !rooted {
components.push("..".to_string());
}
}
_ => {
let component = if verbatim || preserve_trailing_dots_and_spaces {
segment
} else {
segment.trim_end_matches(['.', ' '])
};
if !component.is_empty() {
components.push(component.to_string());
}
}
}
}
Self {
drive,
rooted,
components,
}
}
fn overlaps(&self, denied: &Self) -> bool {
self.drive == denied.drive
&& self.rooted == denied.rooted
&& (denied.components.starts_with(&self.components)
|| self.components.starts_with(&denied.components))
}
}
#[cfg(target_os = "windows")]
fn normalize_windows_verbatim_prefix(path: &str) -> (String, bool) {
if let Some(rest) = path.strip_prefix(r"\\?\unc\") {
(format!(r"\\{rest}"), true)
} else if let Some(rest) = path.strip_prefix(r"\\?\") {
(rest.to_string(), true)
} else {
(path.to_string(), false)
}
}
#[cfg(target_os = "windows")]
fn has_verbatim_trim_sensitive_component(path: &str) -> bool {
normalize_windows_verbatim_prefix(&path.to_lowercase()).1 && has_trim_sensitive_component(path)
}
#[cfg(target_os = "windows")]
fn has_trim_sensitive_component(path: &str) -> bool {
let folded = path.to_lowercase();
let (normalized, _) = normalize_windows_verbatim_prefix(&folded);
normalized
.split(['\\', '/'])
.any(|segment| segment.ends_with(['.', ' ']))
}
#[cfg(not(target_os = "windows"))]
fn path_relationship_fallback(allowed: &str, denied: &str) -> PathRelationship {
let resolve = |path: &str| {
resolve_non_windows_fallback_path(Path::new(path))
.map_err(|e| PathRelationship::Unresolvable(format!("{path:?}: {e}")))
};
let (allowed, denied) = match (resolve(allowed), resolve(denied)) {
(Ok(allowed), Ok(denied)) => (allowed, denied),
(Err(unresolvable), _) | (_, Err(unresolvable)) => return unresolvable,
};
PathRelationship::from_overlaps(denied.starts_with(&allowed) || allowed.starts_with(&denied))
}
#[cfg(not(target_os = "windows"))]
fn resolve_non_windows_fallback_path(path: &Path) -> Result<PathBuf, std::io::Error> {
use std::io::ErrorKind;
use std::path::Component;
let mut tail: Vec<Component<'_>> = Vec::new();
let mut current = path;
loop {
match std::fs::canonicalize(current) {
Ok(resolved) => return Ok(append_non_windows_tail(resolved, &tail)),
Err(e) if e.kind() == ErrorKind::NotFound => {
let Some(parent) = current.parent() else {
return Ok(normalize_non_windows_fallback_path(path));
};
if let Some(component) = current.components().next_back() {
tail.push(component);
}
current = parent;
}
Err(e) => return Err(e),
}
}
}
#[cfg(not(target_os = "windows"))]
fn append_non_windows_tail(base: PathBuf, tail: &[std::path::Component<'_>]) -> PathBuf {
use std::path::Component;
let mut path = base;
for component in tail.iter().rev() {
match component {
Component::Normal(name) => path.push(name),
Component::ParentDir => {
path.pop();
}
Component::CurDir => {}
Component::RootDir => {}
Component::Prefix(_) => {
unreachable!("non-Windows paths cannot contain a Windows prefix")
}
}
}
path
}
#[cfg(not(target_os = "windows"))]
fn normalize_non_windows_fallback_path(path: &Path) -> PathBuf {
use std::path::Component;
let mut normalized = PathBuf::new();
let is_absolute = path.is_absolute();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
if !normalized.pop() && !is_absolute {
normalized.push(component.as_os_str());
}
}
_ => normalized.push(component.as_os_str()),
}
}
normalized
}
fn mounts_equal(a: &[Mount], b: &[Mount]) -> bool {
a.len() == b.len()
&& a.iter().zip(b.iter()).all(|(x, y)| {
x.host_path == y.host_path && x.guest_path == y.guest_path && x.readonly == y.readonly
})
}
fn os_data_home() -> PathBuf {
#[cfg(windows)]
{
if let Some(v) = std::env::var_os("LOCALAPPDATA") {
return PathBuf::from(v);
}
if let Some(v) = std::env::var_os("USERPROFILE") {
return PathBuf::from(v).join("AppData").join("Local");
}
PathBuf::from(".")
}
#[cfg(not(windows))]
{
if let Some(v) = std::env::var_os("XDG_DATA_HOME") {
let p = PathBuf::from(v);
if p.is_absolute() {
return p;
}
}
if let Some(v) = std::env::var_os("HOME") {
return PathBuf::from(v).join(".local").join("share");
}
PathBuf::from(".")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mxc_common::logger::Mode;
use crate::mxc_common::models::ContainerPolicy;
fn runner() -> HyperlightScriptRunner {
HyperlightScriptRunner::new()
}
fn fresh_tmp(tag: &str) -> PathBuf {
let tmp = std::env::temp_dir().join(format!("hl-runner-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).unwrap();
tmp
}
fn assert_denied_overlap_message(message: &str) {
assert!(message.contains("deniedPaths"), "got: {message}");
assert!(
message.contains("overlapping allowed and denied host paths"),
"got: {message}"
);
}
#[cfg(target_os = "windows")]
fn assert_denied_resolution_message(message: &str) {
assert!(
message.contains("cannot verify deniedPaths against allow lists"),
"got: {message}"
);
assert!(
message.contains("fails closed rather than risk an unenforced deny"),
"got: {message}"
);
}
#[test]
fn is_installed_false_on_empty_dir() {
let tmp = fresh_tmp("empty");
assert!(!is_installed(&tmp, HyperlightRuntime::Agent));
assert!(!has_install_source(&tmp, HyperlightRuntime::Agent));
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn has_install_source_true_when_rootfs_present() {
let tmp = fresh_tmp("install-src");
std::fs::write(tmp.join(INITRD_FILE), b"").unwrap();
assert!(has_install_source(&tmp, HyperlightRuntime::Agent));
assert!(!is_installed(&tmp, HyperlightRuntime::Agent)); let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn rootfs_stamped_for_another_release_is_not_an_install_source() {
let tmp = fresh_tmp("stale");
std::fs::write(tmp.join(INITRD_FILE), b"").unwrap();
let agent = HyperlightRuntime::Agent;
std::fs::write(
tmp.join(VERSION_FILE),
format!("rootfs: {}:initrd-v0.13.0\n", runtime_image(agent).image),
)
.unwrap();
assert!(!has_install_source(&tmp, agent));
assert!(!is_installed(&tmp, agent));
std::fs::write(tmp.join(VERSION_FILE), version_stamp(agent)).unwrap();
assert!(has_install_source(&tmp, agent));
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn rootfs_tag_follows_the_pinned_crate_release() {
let manifest =
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml")).unwrap();
let line = manifest
.lines()
.find(|l| l.starts_with("hyperlight-unikraft = "))
.expect("the crate dependency line");
let version = line
.split("version = \"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.expect("a pinned version");
let version = version
.strip_prefix('=')
.expect("an exact (`=`) requirement");
assert_eq!(ROOTFS_TAG, format!("initrd-v{version}"));
}
#[test]
fn a_runtime_only_takes_its_own_rootfs() {
let tmp = fresh_tmp("runtimes");
let agent = tmp.join(HyperlightRuntime::Agent.name());
let node = tmp.join(HyperlightRuntime::Node.name());
for dir in [&agent, &node] {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join(INITRD_FILE), b"").unwrap();
std::fs::write(
dir.join(VERSION_FILE),
version_stamp(HyperlightRuntime::Agent),
)
.unwrap();
}
assert!(has_install_source(&agent, HyperlightRuntime::Agent));
assert!(!has_install_source(&node, HyperlightRuntime::Node));
std::fs::write(
node.join(VERSION_FILE),
version_stamp(HyperlightRuntime::Node),
)
.unwrap();
assert!(has_install_source(&node, HyperlightRuntime::Node));
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn resolve_home_errors_when_nothing_configured() {
let empty = fresh_tmp("resolve-empty");
let saved: Vec<(&str, Option<std::ffi::OsString>)> = [
HOME_ENV,
"XDG_DATA_HOME",
"HOME",
"LOCALAPPDATA",
"USERPROFILE",
]
.iter()
.map(|k| (*k, std::env::var_os(k)))
.collect();
unsafe {
for (k, _) in &saved {
std::env::remove_var(k);
}
std::env::set_var("HOME", &empty);
std::env::set_var("USERPROFILE", &empty);
std::env::set_var("XDG_DATA_HOME", &empty);
std::env::set_var("LOCALAPPDATA", &empty);
}
let result = HyperlightScriptRunner::resolve_home(HyperlightRuntime::Agent);
unsafe {
for (k, v) in &saved {
match v {
Some(val) => std::env::set_var(k, val),
None => std::env::remove_var(k),
}
}
}
let _ = std::fs::remove_dir_all(&empty);
let err = result.unwrap_err();
assert!(
err.to_string().contains("no hyperlight image found"),
"got: {err}"
);
}
#[test]
fn policy_accepts_readwrite_paths_and_builds_mounts() {
let tmp = fresh_tmp("mount");
let request = ExecutionRequest {
policy: ContainerPolicy {
readwrite_paths: vec![tmp.to_string_lossy().to_string()],
..Default::default()
},
..Default::default()
};
let mounts = HyperlightScriptRunner::mounts_from_policy(&request).unwrap();
assert_eq!(mounts.len(), 1);
assert_eq!(
mounts[0].guest_path,
format!("/host/{}", tmp.file_name().unwrap().to_string_lossy())
);
assert!(!mounts[0].readonly);
assert_eq!(mounts[0].host_path, std::fs::canonicalize(&tmp).unwrap());
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn policy_marks_readonly_paths() {
let tmp = fresh_tmp("mount-ro");
let request = ExecutionRequest {
policy: ContainerPolicy {
readonly_paths: vec![tmp.to_string_lossy().to_string()],
..Default::default()
},
..Default::default()
};
let mounts = HyperlightScriptRunner::mounts_from_policy(&request).unwrap();
assert_eq!(mounts.len(), 1);
assert!(mounts[0].readonly);
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn policy_rejects_mount_collision_on_same_basename() {
let a = std::env::temp_dir().join(format!("hl-col-a-{}/same", std::process::id()));
let b = std::env::temp_dir().join(format!("hl-col-b-{}/same", std::process::id()));
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
let request = ExecutionRequest {
policy: ContainerPolicy {
readwrite_paths: vec![
a.to_string_lossy().to_string(),
b.to_string_lossy().to_string(),
],
..Default::default()
},
..Default::default()
};
let err = HyperlightScriptRunner::mounts_from_policy(&request).unwrap_err();
assert!(
err.to_string().contains("collide on guest path"),
"got: {err}"
);
let _ = std::fs::remove_dir_all(a.parent().unwrap());
let _ = std::fs::remove_dir_all(b.parent().unwrap());
}
#[test]
fn policy_rejects_mount_name_the_kernel_cannot_carry() {
let tmp = fresh_tmp("mount-bad").join("with space");
std::fs::create_dir_all(&tmp).unwrap();
let request = ExecutionRequest {
policy: ContainerPolicy {
readwrite_paths: vec![tmp.to_string_lossy().to_string()],
..Default::default()
},
..Default::default()
};
let err = HyperlightScriptRunner::mounts_from_policy(&request).unwrap_err();
assert!(
err.to_string().contains("may not contain whitespace"),
"got: {err}"
);
let _ = std::fs::remove_dir_all(tmp.parent().unwrap());
}
#[test]
fn policy_rejects_denied_overlapping_allow() {
let mut r = runner();
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec!["/tmp/x".to_string()],
denied_paths: vec!["/tmp/x".to_string()],
..Default::default()
},
..Default::default()
};
let mut logger = Logger::new(Mode::Buffer);
let resp = r.run(&request, &mut logger);
assert_eq!(resp.failure_phase, FailurePhase::Rejected);
assert_eq!(resp.exit_code, FailurePhase::Rejected.failure_exit_code());
assert_denied_overlap_message(&resp.error_message);
}
#[test]
fn policy_rejects_denied_descendant_of_allowed_mount() {
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec!["/tmp/hyperlight-allowed".to_string()],
denied_paths: vec!["/tmp/hyperlight-allowed/secret".to_string()],
..Default::default()
},
..Default::default()
};
let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
assert_denied_overlap_message(&err.to_string());
}
#[test]
fn policy_rejects_allowed_mount_inside_denied_parent() {
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec!["/tmp/hyperlight-denied-parent/child".to_string()],
denied_paths: vec!["/tmp/hyperlight-denied-parent".to_string()],
..Default::default()
},
..Default::default()
};
let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
assert_denied_overlap_message(&err.to_string());
}
#[cfg(unix)]
#[test]
fn policy_rejects_denied_overlap_when_allow_is_symlink_alias() {
let tmp = fresh_tmp("deny-symlink-alias");
let real = tmp.join("real");
let link = tmp.join("link");
std::fs::create_dir_all(&real).unwrap();
match std::os::unix::fs::symlink(&real, &link) {
Ok(()) => {}
Err(e)
if e.kind() == std::io::ErrorKind::Unsupported
|| e.kind() == std::io::ErrorKind::PermissionDenied =>
{
let _ = std::fs::remove_dir_all(&tmp);
return;
}
Err(e) => panic!("create symlink {link:?} -> {real:?}: {e}"),
}
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec![link.to_string_lossy().to_string()],
denied_paths: vec![real.join("secret").to_string_lossy().to_string()],
..Default::default()
},
..Default::default()
};
let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
assert_denied_overlap_message(&err.to_string());
let _ = std::fs::remove_dir_all(&tmp);
}
#[cfg(unix)]
#[test]
fn an_inaccessible_host_path_is_a_policy_rejection() {
use std::os::unix::fs::PermissionsExt;
let tmp = fresh_tmp("deny-unresolvable");
let locked = tmp.join("locked");
std::fs::create_dir_all(locked.join("inner")).unwrap();
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
let restore = || {
let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755));
let _ = std::fs::remove_dir_all(&tmp);
};
if std::fs::canonicalize(locked.join("inner")).is_ok() {
restore();
return;
}
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec![locked.join("inner").to_string_lossy().to_string()],
denied_paths: vec![tmp.join("secret").to_string_lossy().to_string()],
..Default::default()
},
..Default::default()
};
let resp = runner().run(&request, &mut Logger::new(Mode::Buffer));
restore();
assert_eq!(resp.failure_phase, FailurePhase::Rejected);
assert_eq!(resp.exit_code, FailurePhase::Rejected.failure_exit_code());
assert!(
resp.error_message
.contains("the invoking user cannot access"),
"got: {}",
resp.error_message
);
}
#[test]
fn only_permission_denied_makes_an_unresolvable_path_a_policy_fault() {
use std::io::{Error, ErrorKind};
let classify = |kind: ErrorKind| {
classify_unresolvable(
PathRelationship::Unresolvable("x".to_string()),
[&Ok(PathBuf::new()), &Err(Error::from(kind))],
)
};
assert_eq!(
classify(ErrorKind::PermissionDenied),
PathRelationship::Inaccessible("x".to_string())
);
assert_eq!(
classify(ErrorKind::Other),
PathRelationship::Unresolvable("x".to_string())
);
}
#[test]
fn policy_rejects_denied_absolute_descendant_of_missing_relative_mount() {
let relative_mount = format!("hyperlight-relative-{}", std::process::id());
let denied = std::env::current_dir()
.unwrap()
.join(&relative_mount)
.join("secret");
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec![relative_mount],
denied_paths: vec![denied.to_string_lossy().to_string()],
..Default::default()
},
..Default::default()
};
let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
assert_denied_overlap_message(&err.to_string());
}
#[cfg(target_os = "windows")]
#[test]
fn policy_rejects_denied_missing_windows_case_variant_allow_overlap() {
let mut r = runner();
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec![
"C:\\MXC\\HyperlightMissingCase\\temp\\..\\PRIVATECACHE\\\\".to_string()
],
denied_paths: vec!["c:/mxc//hyperlightmissingcase/./privatecache".to_string()],
..Default::default()
},
..Default::default()
};
let mut logger = Logger::new(Mode::Buffer);
let resp = r.run(&request, &mut logger);
assert_eq!(resp.failure_phase, FailurePhase::Rejected);
assert_eq!(resp.exit_code, FailurePhase::Rejected.failure_exit_code());
assert_denied_overlap_message(&resp.error_message);
}
#[cfg(target_os = "windows")]
#[test]
fn policy_rejects_denied_missing_windows_verbatim_allow_overlap() {
let mut r = runner();
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec![
"\\\\?\\C:\\MXC\\HyperlightVerbatim\\temp\\..\\PRIVATECACHE\\".to_string(),
],
denied_paths: vec!["c:/mxc/hyperlightverbatim/privatecache".to_string()],
..Default::default()
},
..Default::default()
};
let mut logger = Logger::new(Mode::Buffer);
let resp = r.run(&request, &mut logger);
assert_eq!(resp.failure_phase, FailurePhase::Rejected);
assert_eq!(resp.exit_code, FailurePhase::Rejected.failure_exit_code());
assert_denied_overlap_message(&resp.error_message);
}
#[cfg(target_os = "windows")]
#[test]
fn policy_rejects_denied_missing_windows_trailing_dot_allow_overlap() {
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec![
"C:\\MXC\\HyperlightTrailingDot\\temp\\..\\PRIVATECACHE.\\".to_string()
],
denied_paths: vec!["c:/mxc/hyperlighttrailingdot/privatecache".to_string()],
..Default::default()
},
..Default::default()
};
let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
assert_denied_resolution_message(&err.to_string());
}
#[cfg(target_os = "windows")]
#[test]
fn policy_keeps_verbatim_windows_trailing_dot_distinct() {
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
policy: ContainerPolicy {
readwrite_paths: vec![
"\\\\?\\C:\\MXC\\HyperlightVerbatimDot\\PRIVATECACHE.".to_string()
],
denied_paths: vec!["c:/mxc/hyperlightverbatimdot/privatecache".to_string()],
..Default::default()
},
..Default::default()
};
HyperlightScriptRunner::validate_policies(&request).unwrap();
}
#[cfg(target_os = "windows")]
#[test]
fn fallback_reports_unresolved_windows_paths_as_host_failures() {
use crate::mxc_common::filesystem_canonical::PathCanonical;
assert!(matches!(
path_relationship_fallback_with(
"C:\\MXC\\HyperlightUnknown\\allow",
"C:\\MXC\\HyperlightUnknown\\deny",
|_| PathCanonical::Unknown,
),
PathRelationship::Unresolvable(_)
));
}
#[cfg(target_os = "windows")]
#[test]
fn fallback_canonicalizes_verbatim_trailing_dot_alias_ancestors() {
use crate::mxc_common::filesystem_canonical::PathCanonical;
assert_eq!(
path_relationship_fallback_with(
"\\\\?\\C:\\link\\cache.",
"\\\\?\\C:\\real\\cache.",
|path| match path {
"\\\\?\\C:\\link\\cache." => {
PathCanonical::Canonical("C:\\real\\cache.".to_string())
}
"\\\\?\\C:\\real\\cache." => {
PathCanonical::Canonical("C:\\real\\cache.".to_string())
}
_ => PathCanonical::Absent,
},
),
PathRelationship::Overlaps
);
}
#[cfg(target_os = "windows")]
#[test]
fn fallback_never_separates_mixed_spelling_of_same_dotted_canonical_tree() {
use crate::mxc_common::filesystem_canonical::PathCanonical;
let relationship =
path_relationship_fallback_with("C:\\link\\child", "\\\\?\\C:\\real.\\child", |path| {
match path {
"C:\\link\\child" | "\\\\?\\C:\\real.\\child" => {
PathCanonical::Canonical("C:\\real.\\child".to_string())
}
_ => PathCanonical::Absent,
}
});
assert!(
matches!(
relationship,
PathRelationship::Overlaps | PathRelationship::Ambiguous
),
"same resolved tree must overlap or fail closed, got {relationship:?}"
);
}
#[cfg(target_os = "windows")]
#[test]
fn fallback_fails_closed_when_dotted_canonical_component_provenance_is_ambiguous() {
use crate::mxc_common::filesystem_canonical::PathCanonical;
assert_eq!(
path_relationship_fallback_with(
"C:\\link.\\child",
"\\\\?\\C:\\real.\\child",
|path| match path {
"C:\\link.\\child" | "\\\\?\\C:\\real.\\child" => {
PathCanonical::Canonical("C:\\real.\\child".to_string())
}
_ => PathCanonical::Absent,
},
),
PathRelationship::Ambiguous
);
}
#[cfg(not(target_os = "windows"))]
#[test]
fn fallback_path_comparison_stays_case_sensitive_off_windows() {
assert_eq!(
path_relationship("/tmp/mxc-missing-case", "/tmp/mxc-missing-case"),
PathRelationship::Overlaps
);
assert_eq!(
path_relationship("/tmp/MXC-MISSING-CASE", "/tmp/mxc-missing-case"),
PathRelationship::Separate
);
}
#[test]
fn omitted_network_policy_is_valid_and_keeps_guest_disconnected() {
runner()
.validate_runner(&ExecutionRequest::default())
.unwrap();
}
#[test]
fn explicit_directional_allow_is_rejected_before_boot() {
let mut request = ExecutionRequest::default();
request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
default: crate::mxc_common::models::NetworkAction::Allow,
..Default::default()
});
let error = runner().validate_runner(&request).unwrap_err();
assert!(error.error_message.contains("network.egress.default"));
}
#[test]
fn direct_execute_rejects_network_policy_before_boot() {
let mut request = ExecutionRequest {
script_code: "print('x')".to_string(),
..Default::default()
};
request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
default: crate::mxc_common::models::NetworkAction::Allow,
..Default::default()
});
let mut r = runner();
let mut logger = Logger::new(Mode::Buffer);
let response = r.execute(&request, &mut logger);
assert!(response.error_message.contains("network.egress.default"));
}
#[test]
fn dry_run_validates_without_booting() {
let mut request = ExecutionRequest {
script_code: "print('x')".to_string(),
dry_run: true,
..Default::default()
};
let mut r = runner();
let mut logger = Logger::new(Mode::Buffer);
assert_eq!(r.run(&request, &mut logger).exit_code, 0);
request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
default: crate::mxc_common::models::NetworkAction::Allow,
..Default::default()
});
let response = r.run(&request, &mut logger);
assert!(response.error_message.contains("network.egress.default"));
}
#[test]
fn policy_rejects_working_directory() {
let mut r = runner();
let request = ExecutionRequest {
script_code: "print('x')".to_string(),
working_directory: "C:/tmp".to_string(),
..Default::default()
};
let mut logger = Logger::new(Mode::Buffer);
let resp = r.run(&request, &mut logger);
assert_eq!(resp.failure_phase, FailurePhase::Rejected);
assert_eq!(resp.exit_code, FailurePhase::Rejected.failure_exit_code());
assert!(resp.error_message.contains(ERR_WORKDIR));
}
#[test]
fn a_host_without_an_image_blames_the_host() {
let resp =
RunnerError::Unavailable(no_install_source(HyperlightRuntime::Agent)).to_response();
assert_eq!(resp.failure_phase, FailurePhase::BackendUnavailable);
assert_eq!(resp.exit_code, -1);
assert!(resp.error_message.contains("not available on this host"));
}
#[test]
fn run_faults_keep_the_generic_backend_error_code() {
for (err, phase) in [
(
RunnerError::Setup("mount".to_string()),
FailurePhase::LaunchFailed,
),
(
RunnerError::Launch("boot".to_string()),
FailurePhase::LaunchFailed,
),
(
RunnerError::Exec("run".to_string()),
FailurePhase::PostLaunchFailed,
),
(
RunnerError::Timeout("deadline".to_string()),
FailurePhase::Timeout,
),
] {
let resp = err.to_response();
assert_eq!(resp.failure_phase, phase, "{err}");
assert_eq!(resp.exit_code, -1, "{err}");
}
}
}