diff --git a/nvx-rs/README.md b/nvx-rs/README.md index e814382c9..69f274959 100644 --- a/nvx-rs/README.md +++ b/nvx-rs/README.md @@ -123,7 +123,7 @@ changes only when the module's purpose does. | [`nvx::exec`](#nvxexec) | The execution engine: the streams, credit, and outcome of an execution's two sides, without I/O, for any framing | | [`nvx::host::runtime`](#nvxhostruntime) | `Runtime`: what every launch shares, the runtime's files and their identity, the hypervisor and its probe, and the launch options | | [`nvx::host::vm`](#nvxhostvm) | The directory of a VM, private to the current user, with the fixed names of the files and endpoints of its launches | -| [`nvx::host::config`](#nvxhostconfig) | `VmConfig`: a VM's processors, memory, root, view, network, export, boot console, and cold-boot settings as one value, checked without reading the host | +| [`nvx::host::config`](#nvxhostconfig) | `VmConfig`, a VM's configuration as one value, and `CaptureConfig`, what a capture adds and the identity of its snapshots, checked without reading the host | | [`nvx::host::artifacts`](#nvxhostartifacts) | Locating the OpenVMM executable and the guest artifacts that a VM runs, and their runtime identity | | [`nvx::host::launch`](#nvxhostlaunch) | `LaunchSpec` and `VmmLaunch`: the OpenVMM command line of a managed microVM, its checks, and the inputs that it shares with an adapter's launch | | [`nvx::host::network`](#nvxhostnetwork) | The one lowering of a network posture into OpenVMM options, for the CLI and external orchestrators | @@ -483,9 +483,46 @@ path and checks no support of the host. It fails with an `nvx::Error` of kind root without an image or a scratch path, with a bound of an EROFS image or of 0, or with a RAM upper's cap outside 1 to 90 percent; a hostname that an activation record refuses; or an export that `ExportPlan::check` refuses for the guest -targets that the root reserves. The network's policy and the boot's command line -are checked where they are lowered, with the guest's address and NVX's own -tokens. +targets that the root reserves. Last, it checks a boot's capture with +`CaptureConfig::check`, below, and fails with its error. The network's policy +and the boot's command line are checked where they are lowered, with the +guest's address and NVX's own tokens. + +A `Boot` may also hold a `CaptureConfig`, what a capture of the VM adds to the +VM's configuration, which keeps the rest, such as the NIC, the console, and the +export: a `DiskCapture`, so far only `Fresh`, the `BlockGeometry`, length and +block sizes, of the placeholder of the image and of the dormant scratch that a +fresh capture of a blockless VM attaches, which each restore replaces with its +own; its processors and its memory in MiB, each a `Capacity`, what the VM boots +with and what a restore may grow it to; and the caller's `Invariants`, at most +64 settings that NVX keeps without interpreting them, each named by 1 to 64 +lowercase ASCII letters, digits, `.`, `-`, and `_` from a letter, with a value +of at most 256 printable ASCII characters. `Invariants` and `BlockGeometry` +belong here, and `nvx::host::template` re-exports them where they were. + +`CaptureConfig::check` checks a capture without reading the host. It fails with +an `nvx::Error` of kind `Unsupported` for processors at boot or a capacity other +than 1, 2, 4, or 8, more processors at boot than the capacity, no memory at +boot, a memory capacity below it or not a multiple of 128 MiB, or a disk whose +geometry the template's manifest would refuse: a logical block size that is not +a power of two of at least 512 bytes, a physical one that is not a power of two +of at least the logical one, or a length that is not a nonzero multiple of the +logical one. + +`CaptureConfig::identity` returns the `CaptureIdentity` that names the +snapshots of a capture of a VM of a `VmConfig` on a `Runtime`: the SHA-256 +digest, after the domain `nvx capture` and a NUL, of a fixed encoding of what +tells captures apart, which displays and serializes as 64 lowercase hexadecimal +digits. It identifies the captures that NVX supports, fresh captures of a +blockless VM, from the values alone: it reads nothing on the host and refuses +no configuration, which creating the capture checks. It digests the runtime's +identity, the versions of this crate's contracts, the hypervisor, and the +requested CPU profile; the capture's disks, processors, memory, and invariants; +and the VM's NIC's address, `DEFAULT_GUEST_NETWORK` when the configuration +names none, its console attachment, whether it exports host paths, and its +boot's command line. No path, launch option, view, network policy, or anything +of the VM's root is part of it, nor the VM's own processors and memory, for +which the capture's count. ### `nvx::host::artifacts` diff --git a/nvx-rs/public-api/linux.txt b/nvx-rs/public-api/linux.txt index 6be313fd4..204252140 100644 --- a/nvx-rs/public-api/linux.txt +++ b/nvx-rs/public-api/linux.txt @@ -1750,12 +1750,42 @@ fn nvx::host::artifacts::openvmm_executable mod nvx::host::cli (hidden) fn nvx::host::cli::main (hidden) mod nvx::host::config +struct nvx::host::config::BlockGeometry +field nvx::host::config::BlockGeometry::length +field nvx::host::config::BlockGeometry::logical_block_size +field nvx::host::config::BlockGeometry::physical_block_size struct nvx::host::config::Boot +field nvx::host::config::Boot::capture field nvx::host::config::Boot::command_line +struct nvx::host::config::Capacity +field nvx::host::config::Capacity::boot +field nvx::host::config::Capacity::capacity +struct nvx::host::config::CaptureConfig +method nvx::host::config::CaptureConfig::check +field nvx::host::config::CaptureConfig::disks +method nvx::host::config::CaptureConfig::identity +field nvx::host::config::CaptureConfig::invariants +field nvx::host::config::CaptureConfig::memory +field nvx::host::config::CaptureConfig::processors +struct nvx::host::config::CaptureIdentity enum nvx::host::config::ConsoleAttachment variant nvx::host::config::ConsoleAttachment::Disconnected variant nvx::host::config::ConsoleAttachment::Listener const nvx::host::config::DEFAULT_GUEST_NETWORK +enum nvx::host::config::DiskCapture +variant nvx::host::config::DiskCapture::Fresh +field nvx::host::config::DiskCapture::Fresh::image +field nvx::host::config::DiskCapture::Fresh::scratch +struct nvx::host::config::Invariants +const nvx::host::config::Invariants::MAX_NAME_LEN +const nvx::host::config::Invariants::MAX_SETTINGS +const nvx::host::config::Invariants::MAX_VALUE_LEN +method nvx::host::config::Invariants::get +method nvx::host::config::Invariants::is_empty +method nvx::host::config::Invariants::iter +method nvx::host::config::Invariants::len +method nvx::host::config::Invariants::new +method nvx::host::config::Invariants::with struct nvx::host::config::LayeredRoot field nvx::host::config::LayeredRoot::format field nvx::host::config::LayeredRoot::gpt_first_partition_bound diff --git a/nvx-rs/public-api/windows.txt b/nvx-rs/public-api/windows.txt index 0c4b96d4d..6d9434f1e 100644 --- a/nvx-rs/public-api/windows.txt +++ b/nvx-rs/public-api/windows.txt @@ -676,12 +676,42 @@ fn nvx::host::artifacts::openvmm_executable mod nvx::host::cli (hidden) fn nvx::host::cli::main (hidden) mod nvx::host::config +struct nvx::host::config::BlockGeometry +field nvx::host::config::BlockGeometry::length +field nvx::host::config::BlockGeometry::logical_block_size +field nvx::host::config::BlockGeometry::physical_block_size struct nvx::host::config::Boot +field nvx::host::config::Boot::capture field nvx::host::config::Boot::command_line +struct nvx::host::config::Capacity +field nvx::host::config::Capacity::boot +field nvx::host::config::Capacity::capacity +struct nvx::host::config::CaptureConfig +method nvx::host::config::CaptureConfig::check +field nvx::host::config::CaptureConfig::disks +method nvx::host::config::CaptureConfig::identity +field nvx::host::config::CaptureConfig::invariants +field nvx::host::config::CaptureConfig::memory +field nvx::host::config::CaptureConfig::processors +struct nvx::host::config::CaptureIdentity enum nvx::host::config::ConsoleAttachment variant nvx::host::config::ConsoleAttachment::Disconnected variant nvx::host::config::ConsoleAttachment::Listener const nvx::host::config::DEFAULT_GUEST_NETWORK +enum nvx::host::config::DiskCapture +variant nvx::host::config::DiskCapture::Fresh +field nvx::host::config::DiskCapture::Fresh::image +field nvx::host::config::DiskCapture::Fresh::scratch +struct nvx::host::config::Invariants +const nvx::host::config::Invariants::MAX_NAME_LEN +const nvx::host::config::Invariants::MAX_SETTINGS +const nvx::host::config::Invariants::MAX_VALUE_LEN +method nvx::host::config::Invariants::get +method nvx::host::config::Invariants::is_empty +method nvx::host::config::Invariants::iter +method nvx::host::config::Invariants::len +method nvx::host::config::Invariants::new +method nvx::host::config::Invariants::with struct nvx::host::config::LayeredRoot field nvx::host::config::LayeredRoot::format field nvx::host::config::LayeredRoot::gpt_first_partition_bound diff --git a/nvx-rs/src/host/config/mod.rs b/nvx-rs/src/host/config/mod.rs index 9825e42e7..4a9427141 100644 --- a/nvx-rs/src/host/config/mod.rs +++ b/nvx-rs/src/host/config/mod.rs @@ -1,14 +1,22 @@ //! The configuration of a VM, as one value that [`VmConfig::check`] checks without reading the //! host: the VM's processors and memory, its [`RootConfig`], the [`View`] that its workload has //! of it, its [`NetworkConfig`], the host paths that it exports, its [`ConsoleAttachment`], and -//! what only its cold boot takes, a [`Boot`]. +//! what only its cold boot takes, a [`Boot`], with what a capture of the VM adds, a +//! [`CaptureConfig`], whose [`CaptureIdentity`] names the capture's snapshots. +use std::collections::BTreeMap; +use std::fmt; use std::ops::RangeInclusive; use std::path::PathBuf; +use sha2::{Digest, Sha256}; + use super::filesystem::{ExportPlan, ReservedTargets}; use super::network::NetworkPolicy; +use super::platform::parse_hex32; +use super::runtime::Runtime; use crate::activation::{self, Journal, MAX_HOSTNAME_BYTES, OverlayMode, View}; +use crate::contract; use crate::error::{Error, Result}; use crate::net::Ipv4Cidr; use crate::protocol::root::{ImageFormat, RootImage}; @@ -20,6 +28,17 @@ pub const DEFAULT_GUEST_NETWORK: &str = "10.0.0.2/24"; /// The caps of a RAM upper that [`VmConfig::check`] accepts, in percent of the VM's memory. const RAM_UPPER_CAPS: RangeInclusive = 1..=90; +/// The processor counts of a microVM. +pub(crate) const PROCESSOR_COUNTS: [u32; 4] = [1, 2, 4, 8]; + +/// The size of the blocks in which a restore grows a VM's memory, in MiB, of which a capture's +/// memory capacity is a multiple. +const MEMORY_BLOCK_MIB: u64 = 128; + +/// The domain of a capture's identity: the bytes that precede what identifies the capture in its +/// digest. +const CAPTURE_DOMAIN: &[u8] = b"nvx capture\0"; + /// The configuration of a VM. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VmConfig { @@ -120,6 +139,221 @@ pub struct NicConfig { pub struct Boot { /// The caller's own kernel command-line tokens, to which NVX adds those of what it lowers. pub command_line: String, + /// What a capture of the VM adds, if the VM may be captured. + pub capture: Option, +} + +/// What a capture adds to the configuration of the VM that it captures: how the snapshot treats +/// the disks, the processors and the memory that the VM boots with and that a restore may grow +/// it to, and the caller's invariant settings. The capture VM's own configuration gives the +/// rest, such as its NIC, its console, and its export. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CaptureConfig { + /// How the snapshot treats the disks. + pub disks: DiskCapture, + /// The processors online at boot and their capacity: 1, 2, 4, or 8 each, and no more online + /// at boot than the capacity. + pub processors: Capacity, + /// The memory at boot and its capacity, in MiB: some memory at boot, and a capacity of at + /// least it, in multiples of 128 MiB. + pub memory: Capacity, + /// The caller's invariant settings, which NVX keeps without interpreting them. + pub invariants: Invariants, +} + +/// How a capture's snapshot treats the disks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum DiskCapture { + /// A fresh capture of a blockless VM, to which the capture attaches a placeholder of the + /// image and a dormant scratch, which each restore replaces with its own. + Fresh { + /// The placeholder of the image: its length is the longest that a restore may attach. + image: BlockGeometry, + /// The dormant scratch. + scratch: BlockGeometry, + }, +} + +/// A resource at boot, and the capacity to which a restore may grow it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Capacity { + /// The resource at boot. + pub boot: u64, + /// The capacity: at least the resource at boot. + pub capacity: u64, +} + +/// The length and block sizes of a sandbox block device. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct BlockGeometry { + /// The length that the device presents, in bytes: nonzero, and a multiple of the logical + /// block size. + pub length: u64, + /// The logical block size, in bytes: a power of two of at least 512. + pub logical_block_size: u32, + /// The physical block size, in bytes: a power of two of at least the logical block size. + pub physical_block_size: u32, +} + +impl BlockGeometry { + /// Explains why the geometry is invalid, if it is, as a phrase whose subject is a size, such + /// as "length 1000 is not a nonzero multiple of its logical block size". + pub(crate) fn problem(&self) -> Option { + if self.logical_block_size < 512 || !self.logical_block_size.is_power_of_two() { + Some(format!( + "logical block size {} is not a power of two of at least 512", + self.logical_block_size + )) + } else if self.physical_block_size < self.logical_block_size + || !self.physical_block_size.is_power_of_two() + { + Some(format!( + "physical block size {} is not a power of two of at least its logical block size", + self.physical_block_size + )) + } else if self.length == 0 + || !self + .length + .is_multiple_of(u64::from(self.logical_block_size)) + { + Some(format!( + "length {} is not a nonzero multiple of its logical block size", + self.length + )) + } else { + None + } + } +} + +/// The invariant settings of a template that its key holds beyond its machine, such as the +/// isolation and resource settings of its guest, by name: what its adapter fixes for the +/// template and every clone of it, and no restore changes. +/// +/// A name is 1 to [`MAX_NAME_LEN`](Self::MAX_NAME_LEN) bytes of lowercase ASCII letters, digits, +/// `.`, `-`, and `_`, which starts with a letter, and a value 0 to +/// [`MAX_VALUE_LEN`](Self::MAX_VALUE_LEN) printable ASCII characters, spaces included. A template +/// holds at most [`MAX_SETTINGS`](Self::MAX_SETTINGS) of them, in the order of their names. +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] +pub struct Invariants(BTreeMap); + +impl Invariants { + /// Most settings of a template. + pub const MAX_SETTINGS: usize = 64; + /// Longest name of a setting, in bytes. + pub const MAX_NAME_LEN: usize = 64; + /// Longest value of a setting, in bytes. + pub const MAX_VALUE_LEN: usize = 256; + + /// Returns no settings. + pub fn new() -> Self { + Self::default() + } + + /// Returns the settings with `name` set to `value`, which replaces any earlier value of + /// `name`. + /// + /// Fails with [`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported) for a name or a value + /// of another form than the [type](Self) allows, and for a new setting beyond + /// [`MAX_SETTINGS`](Self::MAX_SETTINGS). + pub fn with(mut self, name: &str, value: &str) -> crate::Result { + check_setting(name, value).map_err(Error::unsupported)?; + if !self.0.contains_key(name) && self.0.len() == Self::MAX_SETTINGS { + return Err(Error::unsupported(format!( + "a template holds at most {} invariant settings", + Self::MAX_SETTINGS + ))); + } + self.0.insert(name.to_owned(), value.to_owned()); + Ok(self) + } + + /// Returns the value of the setting `name`, if the settings hold it. + pub fn get(&self, name: &str) -> Option<&str> { + self.0.get(name).map(String::as_str) + } + + /// Returns the settings, in the order of their names. + pub fn iter(&self) -> impl Iterator { + self.0 + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + } + + /// Returns the number of settings. + pub fn len(&self) -> usize { + self.0.len() + } + + /// Returns whether there are no settings. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +/// Explains why `name` and `value` are not an invariant setting, if they are not. +pub(crate) fn check_setting(name: &str, value: &str) -> Result<(), String> { + let name_valid = (1..=Invariants::MAX_NAME_LEN).contains(&name.len()) + && name.starts_with(|first: char| first.is_ascii_lowercase()) + && name.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-' | b'_') + }); + if !name_valid { + return Err(format!( + "invariant setting {name:?} must be named by 1 to {} lowercase ASCII letters, digits, \ + '.', '-', or '_', starting with a letter", + Invariants::MAX_NAME_LEN + )); + } + if value.len() > Invariants::MAX_VALUE_LEN + || !value.bytes().all(|byte| (0x20..0x7f).contains(&byte)) + { + return Err(format!( + "the value of invariant setting {name:?} must hold at most {} printable ASCII \ + characters", + Invariants::MAX_VALUE_LEN + )); + } + Ok(()) +} + +/// The identity of a capture, which names its snapshots: the SHA-256 digest of what identifies +/// the capture, after the domain `nvx capture` and a NUL. [`CaptureConfig::identity`] returns it. +/// +/// It displays as 64 lowercase hexadecimal digits, and serializes as that text. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct CaptureIdentity([u8; 32]); + +impl fmt::Display for CaptureIdentity { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0 + .iter() + .try_for_each(|byte| write!(formatter, "{byte:02x}")) + } +} + +impl fmt::Debug for CaptureIdentity { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "CaptureIdentity({self})") + } +} + +impl serde::Serialize for CaptureIdentity { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> serde::Deserialize<'de> for CaptureIdentity { + fn deserialize>(deserializer: D) -> Result { + let text = ::deserialize(deserializer)?; + parse_hex32(&text).map(Self).ok_or_else(|| { + serde::de::Error::custom(format!( + "{text:?} is not a capture's identity, which is 64 hexadecimal digits" + )) + }) + } } impl VmConfig { @@ -131,7 +365,8 @@ impl VmConfig { /// path, with a bound of an EROFS image's first partition or a bound of 0, with a scratch upper /// without a path, or with a RAM upper whose cap is not 1 to 90 percent; a hostname that is /// empty, longer than [`MAX_HOSTNAME_BYTES`], or holds a NUL; and an export that - /// [`ExportPlan::check`] refuses for the root, whose error is the source. + /// [`ExportPlan::check`] refuses for the root, whose error is the source. Last, it checks a + /// boot's capture with [`CaptureConfig::check`], and fails with its error. /// /// The NIC's address is checked when it is built. The network's policy and the boot's command /// line are checked where they are lowered, with the guest's address and NVX's own tokens. @@ -159,6 +394,9 @@ impl VmConfig { Error::unsupported("the export plan is invalid").with_source(error) })?; } + if let Some(capture) = self.boot.as_ref().and_then(|boot| boot.capture.as_ref()) { + capture.check()?; + } Ok(()) } } @@ -200,5 +438,155 @@ impl LayeredRoot { } } +impl CaptureConfig { + /// Checks the capture's settings without reading the host. + /// + /// Fails with [`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported) for processors online + /// at boot or a processor capacity other than 1, 2, 4, or 8, more processors online at boot + /// than the capacity, no memory at boot, a memory capacity below the memory at boot or not a + /// multiple of 128 MiB, and a disk whose geometry is invalid. + pub fn check(&self) -> Result<()> { + let Capacity { boot, capacity } = self.processors; + let supported = + |count: u64| u32::try_from(count).is_ok_and(|count| PROCESSOR_COUNTS.contains(&count)); + if !supported(boot) || !supported(capacity) { + return Err(Error::unsupported(format!( + "a capture of {capacity} processors with {boot} online at boot needs 1, 2, 4, \ + or 8 of each" + ))); + } + if boot > capacity { + return Err(Error::unsupported(format!( + "a capture of {capacity} processors can't have {boot} online at boot" + ))); + } + let Capacity { boot, capacity } = self.memory; + if boot == 0 { + return Err(Error::unsupported("a capture needs memory at boot")); + } + if capacity < boot { + return Err(Error::unsupported(format!( + "a capture's memory capacity of {capacity} MiB is below its {boot} MiB at boot" + ))); + } + if !capacity.is_multiple_of(MEMORY_BLOCK_MIB) { + return Err(Error::unsupported(format!( + "a capture's memory capacity of {capacity} MiB is not a multiple of \ + {MEMORY_BLOCK_MIB} MiB" + ))); + } + match &self.disks { + DiskCapture::Fresh { image, scratch } => { + for (disk, geometry) in [("image", image), ("scratch", scratch)] { + if let Some(problem) = geometry.problem() { + return Err(Error::unsupported(format!( + "the {disk} disk of a capture is invalid: its {problem}" + ))); + } + } + } + } + Ok(()) + } + + /// Returns the identity of this capture of a VM of the configuration `config` on `runtime`, + /// which names its snapshots: equal for equal inputs, and another when anything that tells + /// captures apart differs. + /// + /// It identifies the captures that NVX supports, fresh captures of a blockless VM, from the + /// values alone: it reads nothing on the host, refuses no configuration, which creating the + /// capture checks, and digests nothing of the VM's root. It digests the runtime's identity, + /// the versions of the contracts that this crate speaks, the hypervisor, and the CPU profile + /// that the runtime requests; the capture's disks, processors, memory, and invariant + /// settings; and of the VM, its NIC's address, which is [`DEFAULT_GUEST_NETWORK`] when the + /// configuration names none, its console attachment, whether it exports host paths, and its + /// boot's command line. It digests no path, nothing of a launch's options or of the view that + /// each clone's activation sets, no network policy, which each restore replaces, and not the + /// VM's own processors and memory, for which the capture's count. + pub fn identity(&self, config: &VmConfig, runtime: &Runtime) -> CaptureIdentity { + let mut fed = Identifying(Sha256::new_with_prefix(CAPTURE_DOMAIN)); + let identity = &runtime.identity; + for artifact in [&identity.openvmm, &identity.kernel, &identity.initramfs] { + fed.text(artifact.as_str()); + } + fed.number(identity.boot_contract); + fed.text(&identity.control_contract); + fed.number(identity.control_session); + for version in [ + contract::SNAPSHOT_FORMAT_VERSION, + contract::DEVICE_STATE_SCHEMA_VERSION, + contract::TIME_ABI_VERSION, + contract::RESTORE_PACKET_VERSION, + u64::from(activation::VERSION), + ] { + fed.number(version); + } + fed.text(runtime.hypervisor.as_str()); + fed.optional_text(runtime.cpu_profile.as_deref()); + match &self.disks { + DiskCapture::Fresh { image, scratch } => { + fed.text("fresh"); + fed.geometry(image); + fed.geometry(scratch); + } + } + for resource in [self.processors, self.memory] { + fed.number(resource.boot); + fed.number(resource.capacity); + } + fed.number(self.invariants.len() as u64); + for (name, value) in self.invariants.iter() { + fed.text(name); + fed.text(value); + } + let address = config.network.as_ref().map(|network| { + network.guest_network.map_or_else( + || DEFAULT_GUEST_NETWORK.to_owned(), + |address| address.to_string(), + ) + }); + fed.optional_text(address.as_deref()); + fed.text(match config.console { + ConsoleAttachment::Listener => "listener", + ConsoleAttachment::Disconnected => "disconnected", + }); + fed.number(u64::from(config.filesystem.is_some())); + fed.optional_text(config.boot.as_ref().map(|boot| boot.command_line.as_str())); + CaptureIdentity(fed.0.finalize().into()) + } +} + +/// What identifies a capture, fed to its digest in a fixed order: each number in 8 bytes, and +/// each text after its length, so that no two sequences of values feed the same bytes. +struct Identifying(Sha256); + +impl Identifying { + /// Feeds a number. + fn number(&mut self, number: u64) { + self.0.update(number.to_be_bytes()); + } + + /// Feeds a text, after its length. + fn text(&mut self, text: &str) { + self.number(text.len() as u64); + self.0.update(text.as_bytes()); + } + + /// Feeds whether there is a text, and the text if there is one. + fn optional_text(&mut self, text: Option<&str>) { + self.number(u64::from(text.is_some())); + if let Some(text) = text { + self.text(text); + } + } + + /// Feeds a geometry: its length and its block sizes. + fn geometry(&mut self, geometry: &BlockGeometry) { + self.number(geometry.length); + self.number(u64::from(geometry.logical_block_size)); + self.number(u64::from(geometry.physical_block_size)); + } +} + #[cfg(test)] mod tests; diff --git a/nvx-rs/src/host/config/tests.rs b/nvx-rs/src/host/config/tests.rs index 09f1f1dd5..bea61e2b4 100644 --- a/nvx-rs/src/host/config/tests.rs +++ b/nvx-rs/src/host/config/tests.rs @@ -1,14 +1,18 @@ //! Tests of a VM's configuration and of its check, on paths that don't exist, since the check //! reads nothing on the host. +use std::collections::HashSet; use std::error::Error as _; +use std::time::Duration; use super::*; -use crate::ErrorKind; use crate::activation::MachineIdMode; use crate::host::filesystem::{Bind, ExportChild, Owner}; use crate::host::network::Access; +use crate::host::runtime::{ArtifactIdentity, GuestPowerAction, LaunchOptions, RuntimeIdentity}; +use crate::hypervisor::Hypervisor; use crate::uuid::Uuid; +use crate::{ErrorCode, ErrorKind}; /// Returns the path of `name` in a directory that doesn't exist. fn missing(name: &str) -> PathBuf { @@ -125,9 +129,11 @@ fn configurations_pass_with_or_without_a_nic_address_and_a_boot() { None, Some(Boot { command_line: String::new(), + capture: None, }), Some(Boot { command_line: "quiet loglevel=0".to_owned(), + capture: None, }), ]; for config in [blockless(), layered(erofs())] { @@ -255,3 +261,482 @@ fn an_export_passes_the_check_of_the_targets_that_its_root_reserves() { assert!(source.contains(target), "{source}"); } } + +#[test] +fn invariant_settings_have_one_form() { + let settings = Invariants::new() + .with("isolation.seccomp", "strict") + .unwrap() + .with("limits.pids", "512") + .unwrap() + .with("isolation.seccomp", "relaxed") + .unwrap(); + assert_eq!(settings.len(), 2); + assert!(!settings.is_empty()); + assert_eq!(settings.get("isolation.seccomp"), Some("relaxed")); + assert_eq!(settings.get("limits.cpu"), None); + assert_eq!( + settings.iter().collect::>(), + [("isolation.seccomp", "relaxed"), ("limits.pids", "512")] + ); + let long_name = "a".repeat(Invariants::MAX_NAME_LEN + 1); + let long_value = "v".repeat(Invariants::MAX_VALUE_LEN + 1); + for (name, value) in [ + ("", "value"), + ("Isolation", "value"), + ("1st", "value"), + ("with space", "value"), + (long_name.as_str(), "value"), + ("name", long_value.as_str()), + ("name", "line\nbreak"), + ("name", "tab\there"), + ("name", "é"), + ] { + let error = Invariants::new().with(name, value).unwrap_err(); + assert_eq!(error.code(), ErrorCode::Unsupported, "{name:?} {value:?}"); + } + assert!(Invariants::new().with("name", "").is_ok()); + let mut full = Invariants::new(); + for index in 0..Invariants::MAX_SETTINGS { + full = full.with(&format!("setting{index}"), "1").unwrap(); + } + assert!(full.clone().with("setting0", "2").is_ok()); + assert_eq!( + full.with("another", "1").unwrap_err().message(), + "a template holds at most 64 invariant settings" + ); +} + +#[test] +fn block_geometries_hold_whole_blocks_of_power_of_two_sizes() { + let valid = BlockGeometry { + length: 64 * 1024 * 1024, + logical_block_size: 512, + physical_block_size: 4096, + }; + assert_eq!(valid.problem(), None); + for (geometry, expected) in [ + ( + BlockGeometry { + logical_block_size: 256, + ..valid + }, + "logical block size 256 is not a power of two of at least 512", + ), + ( + BlockGeometry { + physical_block_size: 256, + ..valid + }, + "physical block size 256 is not a power of two of at least its logical block size", + ), + ( + BlockGeometry { + length: 1000, + ..valid + }, + "length 1000 is not a nonzero multiple of its logical block size", + ), + ] { + assert_eq!(geometry.problem().as_deref(), Some(expected)); + } +} + +/// Returns a fresh capture of 1 processor online of 2, and of 256 MiB of memory of 512. +fn capture() -> CaptureConfig { + let image = BlockGeometry { + length: 1024 * 1024 * 1024, + logical_block_size: 512, + physical_block_size: 4096, + }; + CaptureConfig { + disks: DiskCapture::Fresh { + image, + scratch: BlockGeometry { + length: 64 * 1024 * 1024, + ..image + }, + }, + processors: Capacity { + boot: 1, + capacity: 2, + }, + memory: Capacity { + boot: 256, + capacity: 512, + }, + invariants: Invariants::new() + .with("isolation.seccomp", "strict") + .unwrap(), + } +} + +#[test] +fn fresh_captures_pass_with_supported_processors_and_aligned_memory() { + for (processors, memory) in [ + ((1, 1), (1, 128)), + ((2, 4), (128, 128)), + ((1, 8), (256, 512)), + ((8, 8), (4096, 4096)), + ] { + let capture = CaptureConfig { + processors: Capacity { + boot: processors.0, + capacity: processors.1, + }, + memory: Capacity { + boot: memory.0, + capacity: memory.1, + }, + ..capture() + }; + capture.check().unwrap(); + } +} + +#[test] +fn each_refusal_of_a_capture_names_what_it_refuses() { + type Refusal = fn(&mut CaptureConfig); + let cases: &[(Refusal, &str)] = &[ + ( + |capture| capture.processors.boot = 3, + "a capture of 2 processors with 3 online at boot needs 1, 2, 4, or 8 of each", + ), + ( + |capture| capture.processors.boot = 0, + "with 0 online at boot", + ), + ( + |capture| capture.processors.capacity = 16, + "a capture of 16 processors with 1 online at boot", + ), + ( + |capture| { + capture.processors = Capacity { + boot: 4, + capacity: 2, + } + }, + "a capture of 2 processors can't have 4 online at boot", + ), + ( + |capture| capture.memory.boot = 0, + "a capture needs memory at boot", + ), + ( + |capture| { + capture.memory = Capacity { + boot: 512, + capacity: 384, + } + }, + "a capture's memory capacity of 384 MiB is below its 512 MiB at boot", + ), + ( + |capture| capture.memory.capacity = 600, + "a capture's memory capacity of 600 MiB is not a multiple of 128 MiB", + ), + ( + |capture| { + let DiskCapture::Fresh { image, .. } = &mut capture.disks; + image.logical_block_size = 256; + }, + "the image disk of a capture is invalid: its logical block size 256", + ), + ( + |capture| { + let DiskCapture::Fresh { scratch, .. } = &mut capture.disks; + scratch.length = 1000; + }, + "the scratch disk of a capture is invalid: its length 1000", + ), + ]; + for (change, expected) in cases { + let mut capture = capture(); + change(&mut capture); + let error = capture.check().unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Unsupported, "{error}"); + assert!(error.to_string().contains(expected), "{error}"); + } +} + +#[test] +fn the_check_of_a_configuration_checks_its_boots_capture() { + let booting = |capture: Option| VmConfig { + boot: Some(Boot { + command_line: String::new(), + capture, + }), + ..blockless() + }; + blockless().check().unwrap(); + booting(None).check().unwrap(); + booting(Some(capture())).check().unwrap(); + type Refusal = fn(&mut CaptureConfig); + let refusals: [Refusal; 2] = [ + |capture| capture.memory.boot = 0, + |capture| capture.processors.boot = 3, + ]; + for change in refusals { + let mut capture = capture(); + change(&mut capture); + let expected = capture.check().unwrap_err(); + let error = booting(Some(capture)).check().unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Unsupported, "{error}"); + assert_eq!(error.to_string(), expected.to_string()); + } +} + +/// Returns a runtime of artifacts that don't exist, under this crate's contracts. +fn runtime() -> Runtime { + let artifact = |digit: char| ArtifactIdentity::sha256(&digit.to_string().repeat(64)).unwrap(); + Runtime { + openvmm: missing("openvmm"), + kernel: missing("vmlinux"), + initramfs: missing("initramfs.cpio.gz"), + identity: RuntimeIdentity::new(artifact('a'), artifact('b'), artifact('c')), + hypervisor: Hypervisor::Kvm, + cpu_profile: None, + windows_breakaway: false, + options: LaunchOptions::default(), + } +} + +/// Returns the configuration of a VM that [`capture`] captures: blockless, with a NIC that names +/// no address under a policy that denies everything, a listener on its console, no export, and +/// a boot of one token. +fn captured() -> VmConfig { + VmConfig { + network: Some(NetworkConfig { + guest_network: None, + policy: NetworkPolicy::new(Access::Deny), + }), + boot: Some(Boot { + command_line: "quiet".to_owned(), + capture: Some(capture()), + }), + ..blockless() + } +} + +#[test] +fn equal_captures_have_one_identity_in_one_text() { + let identity = capture().identity(&captured(), &runtime()); + assert_eq!(identity, capture().identity(&captured(), &runtime())); + // A NIC that names no address takes the default one at a capture's cold boot. + let explicit = VmConfig { + network: Some(NetworkConfig { + guest_network: Some(Ipv4Cidr::parse(DEFAULT_GUEST_NETWORK).unwrap()), + policy: NetworkPolicy::new(Access::Deny), + }), + ..captured() + }; + assert_eq!(capture().identity(&explicit, &runtime()), identity); + + let text = identity.to_string(); + assert_eq!(text.len(), 64); + assert!( + text.bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + ); + assert_eq!(format!("{identity:?}"), format!("CaptureIdentity({text})")); + let json = serde_json::to_string(&identity).unwrap(); + assert_eq!(json, format!("\"{text}\"")); + assert_eq!( + serde_json::from_str::(&json).unwrap(), + identity + ); + assert_eq!( + serde_json::from_str::(&json.to_uppercase()).unwrap(), + identity + ); + for invalid in ["\"\"", "\"abc\"", "64"] { + assert!( + serde_json::from_str::(invalid).is_err(), + "{invalid}" + ); + } +} + +/// A change to the inputs of a capture's identity. +type Change = fn(&mut CaptureConfig, &mut VmConfig, &mut Runtime); + +#[test] +fn each_input_that_identifies_a_capture_changes_its_identity() { + let changes: &[(&str, Change)] = &[ + ("the OpenVMM", |_, _, runtime| { + runtime.identity.openvmm = ArtifactIdentity::new("openvmm-2").unwrap(); + }), + ("the kernel", |_, _, runtime| { + runtime.identity.kernel = ArtifactIdentity::new("vmlinux-2").unwrap(); + }), + ("the initramfs", |_, _, runtime| { + runtime.identity.initramfs = ArtifactIdentity::new("initramfs-2").unwrap(); + }), + ("the boot contract", |_, _, runtime| { + runtime.identity.boot_contract += 1 + }), + ("the control contract", |_, _, runtime| { + runtime.identity.control_contract.push('2'); + }), + ("the control session", |_, _, runtime| { + runtime.identity.control_session += 1 + }), + ("the hypervisor", |_, _, runtime| { + runtime.hypervisor = Hypervisor::Mshv + }), + ("the CPU profile", |_, _, runtime| { + runtime.cpu_profile = Some("auto".to_owned()); + }), + ("the image's length", |capture, _, _| { + let DiskCapture::Fresh { image, .. } = &mut capture.disks; + image.length *= 2; + }), + ("the image's logical blocks", |capture, _, _| { + let DiskCapture::Fresh { image, .. } = &mut capture.disks; + image.logical_block_size = 4096; + }), + ("the image's physical blocks", |capture, _, _| { + let DiskCapture::Fresh { image, .. } = &mut capture.disks; + image.physical_block_size = 512; + }), + ("the scratch's length", |capture, _, _| { + let DiskCapture::Fresh { scratch, .. } = &mut capture.disks; + scratch.length *= 2; + }), + ("the scratch's logical blocks", |capture, _, _| { + let DiskCapture::Fresh { scratch, .. } = &mut capture.disks; + scratch.logical_block_size = 4096; + }), + ("the scratch's physical blocks", |capture, _, _| { + let DiskCapture::Fresh { scratch, .. } = &mut capture.disks; + scratch.physical_block_size = 512; + }), + ("the processors at boot", |capture, _, _| { + capture.processors.boot = 2 + }), + ("the processor capacity", |capture, _, _| { + capture.processors.capacity = 4 + }), + ("the memory at boot", |capture, _, _| { + capture.memory.boot = 128 + }), + ("the memory capacity", |capture, _, _| { + capture.memory.capacity = 640 + }), + ("another setting", |capture, _, _| { + capture.invariants = capture + .invariants + .clone() + .with("limits.pids", "512") + .unwrap(); + }), + ("a setting's value", |capture, _, _| { + capture.invariants = capture + .invariants + .clone() + .with("isolation.seccomp", "x") + .unwrap(); + }), + ("a setting's name", |capture, _, _| { + capture.invariants = Invariants::new().with("isolation.mode", "strict").unwrap(); + }), + ("no NIC", |_, config, _| config.network = None), + ("the NIC's address", |_, config, _| { + config.network.as_mut().unwrap().guest_network = + Some(Ipv4Cidr::parse("10.1.0.2/24").unwrap()); + }), + ("the console", |_, config, _| { + config.console = ConsoleAttachment::Disconnected; + }), + ("an export", |_, config, _| { + config.filesystem = Some(export("/mnt/work")); + }), + ("the command line", |_, config, _| { + config + .boot + .as_mut() + .unwrap() + .command_line + .push_str(" debug"); + }), + ("no boot", |_, config, _| config.boot = None), + ]; + let base = capture().identity(&captured(), &runtime()); + let mut identities = HashSet::from([base]); + for (what, change) in changes { + let (mut capture, mut config, mut runtime) = (capture(), captured(), runtime()); + change(&mut capture, &mut config, &mut runtime); + assert!( + identities.insert(capture.identity(&config, &runtime)), + "{what}" + ); + } +} + +#[test] +fn what_each_launch_or_clone_sets_leaves_the_identity_alone() { + let changes: &[(&str, Change)] = &[ + ("the paths of the runtime", |_, _, runtime| { + runtime.openvmm = missing("other-openvmm"); + runtime.kernel = missing("other-vmlinux"); + runtime.initramfs = missing("other-initramfs"); + }), + ("the breakaway", |_, _, runtime| { + runtime.windows_breakaway = true + }), + ("the launch options", |_, _, runtime| { + runtime.options = LaunchOptions { + guest_shutdown: GuestPowerAction::Halt, + control_auth_timeout: Some(Duration::from_secs(9)), + }; + }), + ("the view", |_, config, _| { + config.view = View { + hostname: b"clone".to_vec(), + machine_id: MachineIdMode::Image, + }; + }), + ("the policy", |_, config, _| { + config.network.as_mut().unwrap().policy = NetworkPolicy::new(Access::Allow); + }), + ("the VM's processors and memory", |_, config, _| { + config.processors = 2; + config.memory_mib = 1024; + }), + // The VM of a supported capture is blockless, and each clone attaches its own root. + ("a layered root", |_, config, _| { + config.root = RootConfig::Layered(erofs()) + }), + ( + "a layered root's format, identity, bound, upper and overlay", + |_, config, _| { + config.root = RootConfig::Layered(LayeredRoot { + format: RootImage::gpt(Some(Uuid::from_bytes([7; 16]))), + gpt_first_partition_bound: Some(64 * 1024), + upper: UpperConfig::Scratch { + path: missing("scratch.ext4"), + journal: Journal::Forbidden, + }, + overlay: OverlayMode::UntrustedLowers, + ..erofs() + }); + }, + ), + ]; + let base = capture().identity(&captured(), &runtime()); + for (what, change) in changes { + let (mut capture, mut config, mut runtime) = (capture(), captured(), runtime()); + change(&mut capture, &mut config, &mut runtime); + assert_eq!(capture.identity(&config, &runtime), base, "{what}"); + } + // Of an export, only that there is one: not its paths or targets. + let with_export = |target| VmConfig { + filesystem: Some(export(target)), + ..captured() + }; + assert_eq!( + capture().identity(&with_export("/mnt/a"), &runtime()), + capture().identity(&with_export("/mnt/b"), &runtime()) + ); +} diff --git a/nvx-rs/src/host/mod.rs b/nvx-rs/src/host/mod.rs index 6594e7cd6..365e62d05 100644 --- a/nvx-rs/src/host/mod.rs +++ b/nvx-rs/src/host/mod.rs @@ -9,7 +9,8 @@ //! - [`config`] holds the configuration of a VM as one value, a [`VmConfig`](config::VmConfig), //! which it checks without reading the host: the VM's processors and memory, its root, the view //! that its workload has of it, its network, its export, its boot console, and what only its -//! cold boot takes. +//! cold boot takes, with what a capture of it adds, a [`CaptureConfig`](config::CaptureConfig), +//! whose identity names the capture's snapshots. //! - [`launch`] builds OpenVMM's command line from a [`LaunchSpec`](launch::LaunchSpec): the //! managed lifecycle, the workload identity, the kernel command line, and the network and //! filesystem options. diff --git a/nvx-rs/src/host/sandbox/geometry.rs b/nvx-rs/src/host/sandbox/geometry.rs index 840c2597b..fc88d3b8f 100644 --- a/nvx-rs/src/host/sandbox/geometry.rs +++ b/nvx-rs/src/host/sandbox/geometry.rs @@ -1,15 +1,6 @@ //! The block geometry of a sandbox block device, which the checks of its files read as OpenVMM -//! presents it, and which a template records for the devices of its capture. -//! [`template`](crate::host::template) re-exports what is public here. +//! presents it, and which a template records for the devices of its capture, from +//! [`config`](crate::host::config), where a capture's configuration names it. +//! [`template`](crate::host::template) re-exports it. -/// The length and block sizes of a sandbox block device. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct BlockGeometry { - /// The length that the device presents, in bytes: nonzero, and a multiple of the logical - /// block size. - pub length: u64, - /// The logical block size, in bytes: a power of two of at least 512. - pub logical_block_size: u32, - /// The physical block size, in bytes: a power of two of at least the logical block size. - pub physical_block_size: u32, -} +pub use crate::host::config::BlockGeometry; diff --git a/nvx-rs/src/host/template/key.rs b/nvx-rs/src/host/template/key.rs index ec3e4f6f3..54b63145b 100644 --- a/nvx-rs/src/host/template/key.rs +++ b/nvx-rs/src/host/template/key.rs @@ -1,7 +1,6 @@ //! The compatibility key of a template, [`TemplateKey`], and the [`CaptureClass`] of the capture //! that makes one. -use std::collections::BTreeMap; use std::fmt; use std::net::{Ipv4Addr, Ipv6Addr}; @@ -18,12 +17,15 @@ use super::manifest::{ use crate::activation; use crate::contract; use crate::error::{Error, Result}; +use crate::host::config::check_setting; use crate::host::platform::parse_hex32; use crate::host::sandbox::SandboxNetwork; use crate::host::sandbox::mount::MOUNT_TAG; use crate::host::store::{ArtifactIdentity, MAX_IDENTITY_LEN, RuntimeIdentity}; use crate::hypervisor::Hypervisor; +pub use crate::host::config::Invariants; + /// The domain of a key's identity: the bytes that precede its canonical encoding in the digest. const KEY_DOMAIN: &[u8] = b"nvx template key\0"; @@ -236,70 +238,8 @@ identity!( "a capture class's identity" ); -/// The invariant settings of a template that its key holds beyond its machine, such as the -/// isolation and resource settings of its guest, by name: what its adapter fixes for the -/// template and every clone of it, and no restore changes. -/// -/// A name is 1 to [`MAX_NAME_LEN`](Self::MAX_NAME_LEN) bytes of lowercase ASCII letters, digits, -/// `.`, `-`, and `_`, which starts with a letter, and a value 0 to -/// [`MAX_VALUE_LEN`](Self::MAX_VALUE_LEN) printable ASCII characters, spaces included. A template -/// holds at most [`MAX_SETTINGS`](Self::MAX_SETTINGS) of them, in the order of their names. -#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] -pub struct Invariants(BTreeMap); - +/// The canonical encoding of a template's invariant settings, which its key holds. impl Invariants { - /// Most settings of a template. - pub const MAX_SETTINGS: usize = 64; - /// Longest name of a setting, in bytes. - pub const MAX_NAME_LEN: usize = 64; - /// Longest value of a setting, in bytes. - pub const MAX_VALUE_LEN: usize = 256; - - /// Returns no settings. - pub fn new() -> Self { - Self::default() - } - - /// Returns the settings with `name` set to `value`, which replaces any earlier value of - /// `name`. - /// - /// Fails with [`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported) for a name or a value - /// of another form than the [type](Self) allows, and for a new setting beyond - /// [`MAX_SETTINGS`](Self::MAX_SETTINGS). - pub fn with(mut self, name: &str, value: &str) -> Result { - check_setting(name, value).map_err(|error| Error::unsupported(error.to_string()))?; - if !self.0.contains_key(name) && self.0.len() == Self::MAX_SETTINGS { - return Err(Error::unsupported(format!( - "a template holds at most {} invariant settings", - Self::MAX_SETTINGS - ))); - } - self.0.insert(name.to_owned(), value.to_owned()); - Ok(self) - } - - /// Returns the value of the setting `name`, if the settings hold it. - pub fn get(&self, name: &str) -> Option<&str> { - self.0.get(name).map(String::as_str) - } - - /// Returns the settings, in the order of their names. - pub fn iter(&self) -> impl Iterator { - self.0 - .iter() - .map(|(name, value)| (name.as_str(), value.as_str())) - } - - /// Returns the number of settings. - pub fn len(&self) -> usize { - self.0.len() - } - - /// Returns whether there are no settings. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } - /// Writes the settings: a list of names and values. fn write(&self, writer: &mut Writer) { let settings: Vec<(&str, &str)> = self.iter().collect(); @@ -314,7 +254,7 @@ impl Invariants { let settings = reader.list(Self::MAX_SETTINGS, "the invariant settings", |reader| { let name = reader.text(Self::MAX_NAME_LEN, "the name of a setting")?; let value = reader.text(Self::MAX_VALUE_LEN, "the value of a setting")?; - check_setting(name, value)?; + check_setting(name, value).map_err(CanonicalError::new)?; Ok((name.to_owned(), value.to_owned())) })?; if settings.windows(2).any(|pair| pair[0].0 >= pair[1].0) { @@ -322,34 +262,13 @@ impl Invariants { "the invariant settings are not in the strict order of their names", )); } - Ok(Self(settings.into_iter().collect())) - } -} - -/// Explains why `name` and `value` are not an invariant setting, if they are not. -fn check_setting(name: &str, value: &str) -> Result<(), CanonicalError> { - let name_valid = (1..=Invariants::MAX_NAME_LEN).contains(&name.len()) - && name.starts_with(|first: char| first.is_ascii_lowercase()) - && name.bytes().all(|byte| { - byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-' | b'_') - }); - if !name_valid { - return Err(CanonicalError::new(format!( - "invariant setting {name:?} must be named by 1 to {} lowercase ASCII letters, digits, \ - '.', '-', or '_', starting with a letter", - Invariants::MAX_NAME_LEN - ))); - } - if value.len() > Invariants::MAX_VALUE_LEN - || !value.bytes().all(|byte| (0x20..0x7f).contains(&byte)) - { - return Err(CanonicalError::new(format!( - "the value of invariant setting {name:?} must hold at most {} printable ASCII \ - characters", - Invariants::MAX_VALUE_LEN - ))); + settings + .iter() + .try_fold(Self::new(), |settings, (name, value)| { + settings.with(name, value) + }) + .map_err(|error| CanonicalError::new(error.message())) } - Ok(()) } /// The CPU profile that a capture requests: OpenVMM's `--cpu-profile`. diff --git a/nvx-rs/src/host/template/key/tests.rs b/nvx-rs/src/host/template/key/tests.rs index 2894fa09b..284634d71 100644 --- a/nvx-rs/src/host/template/key/tests.rs +++ b/nvx-rs/src/host/template/key/tests.rs @@ -806,51 +806,6 @@ fn keys_of_machines_that_no_manifest_describes_are_refused() { ); } -#[test] -fn invariant_settings_have_one_form() { - let settings = Invariants::new() - .with("isolation.seccomp", "strict") - .unwrap() - .with("limits.pids", "512") - .unwrap() - .with("isolation.seccomp", "relaxed") - .unwrap(); - assert_eq!(settings.len(), 2); - assert!(!settings.is_empty()); - assert_eq!(settings.get("isolation.seccomp"), Some("relaxed")); - assert_eq!(settings.get("limits.cpu"), None); - assert_eq!( - settings.iter().collect::>(), - [("isolation.seccomp", "relaxed"), ("limits.pids", "512")] - ); - let long_name = "a".repeat(Invariants::MAX_NAME_LEN + 1); - let long_value = "v".repeat(Invariants::MAX_VALUE_LEN + 1); - for (name, value) in [ - ("", "value"), - ("Isolation", "value"), - ("1st", "value"), - ("with space", "value"), - (long_name.as_str(), "value"), - ("name", long_value.as_str()), - ("name", "line\nbreak"), - ("name", "tab\there"), - ("name", "é"), - ] { - let error = Invariants::new().with(name, value).unwrap_err(); - assert_eq!(error.code(), ErrorCode::Unsupported, "{name:?} {value:?}"); - } - assert!(Invariants::new().with("name", "").is_ok()); - let mut full = Invariants::new(); - for index in 0..Invariants::MAX_SETTINGS { - full = full.with(&format!("setting{index}"), "1").unwrap(); - } - assert!(full.clone().with("setting0", "2").is_ok()); - assert_eq!( - full.with("another", "1").unwrap_err().message(), - "a template holds at most 64 invariant settings" - ); -} - #[test] fn a_key_identity_is_the_identity_that_names_a_clones_template() { let identity = network_key().identity(); diff --git a/nvx-rs/src/host/template/manifest.rs b/nvx-rs/src/host/template/manifest.rs index 166043aa2..76db5f900 100644 --- a/nvx-rs/src/host/template/manifest.rs +++ b/nvx-rs/src/host/template/manifest.rs @@ -107,8 +107,7 @@ pub(super) const CPUID_ENTRY_LEN: usize = 44; /// Most entries of a CPU profile's effective CPUID record. pub(super) const MAX_CPUID_ENTRIES: usize = 1024; -/// The processor counts of a microVM. -pub(super) const PROCESSOR_COUNTS: [u32; 4] = [1, 2, 4, 8]; +pub(super) use crate::host::config::PROCESSOR_COUNTS; /// Bytes of a SHA-256 digest. const SHA256_LEN: usize = 32; @@ -438,37 +437,6 @@ pub(super) struct Interrupts { pub(super) status_page_length: u64, } -impl BlockGeometry { - /// Explains why the geometry is invalid, if it is, as a phrase whose subject is a size, such - /// as "length 1000 is not a nonzero multiple of its logical block size". - pub(super) fn problem(&self) -> Option { - if self.logical_block_size < 512 || !self.logical_block_size.is_power_of_two() { - Some(format!( - "logical block size {} is not a power of two of at least 512", - self.logical_block_size - )) - } else if self.physical_block_size < self.logical_block_size - || !self.physical_block_size.is_power_of_two() - { - Some(format!( - "physical block size {} is not a power of two of at least its logical block size", - self.physical_block_size - )) - } else if self.length == 0 - || !self - .length - .is_multiple_of(u64::from(self.logical_block_size)) - { - Some(format!( - "length {} is not a nonzero multiple of its logical block size", - self.length - )) - } else { - None - } - } -} - /// The IPv6 identity of a machine's fixed NIC. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(super) struct Ipv6Identity { diff --git a/nvx-rs/src/host/template/manifest/tests.rs b/nvx-rs/src/host/template/manifest/tests.rs index 02ff0f900..d15972e06 100644 --- a/nvx-rs/src/host/template/manifest/tests.rs +++ b/nvx-rs/src/host/template/manifest/tests.rs @@ -742,20 +742,6 @@ fn manifests_of_invalid_machines_are_refused() { |spec| spec.contract().interrupt_mode.clear(), "names no interrupt delivery mode", ), - ( - |spec| spec.contract().blocks[0].logical_block_size = 256, - "has a distro block whose logical block size 256 is not a power of two of at least \ - 512", - ), - ( - |spec| spec.contract().blocks[1].physical_block_size = 256, - "has a scratch block whose physical block size 256 is not a power of two", - ), - ( - |spec| spec.contract().blocks[1].length = 1000, - "has a scratch block whose length 1000 is not a nonzero multiple of its logical \ - block size", - ), ( |spec| spec.time().host_clock = "utc".to_owned(), "has a time contract of the unknown host clock \"utc\"",