diff --git a/nvx-rs/src/contract.rs b/nvx-rs/src/contract.rs index 68cb838bf..8579a2821 100644 --- a/nvx-rs/src/contract.rs +++ b/nvx-rs/src/contract.rs @@ -131,62 +131,4 @@ pub fn manifest_is_compatible(manifest: &serde_json::Value) -> bool { } #[cfg(all(test, feature = "host"))] -mod tests { - use serde_json::json; - - use super::*; - - #[test] - fn release_manifests_must_match_every_bundled_contract() { - let manifest = json!({ - "openvmm": { - "microvm_abi_version": MICROVM_ABI_VERSION, - "time_abi_version": TIME_ABI_VERSION, - "restore_packet_version": RESTORE_PACKET_VERSION, - "control_session_protocol_version": CONTROL_SESSION_PROTOCOL_VERSION, - "control_contract_revision": CONTROL_CONTRACT_REVISION, - } - }); - assert!(manifest_is_compatible(&manifest)); - for field in [ - "microvm_abi_version", - "time_abi_version", - "restore_packet_version", - "control_session_protocol_version", - "control_contract_revision", - ] { - let mut incompatible = manifest.clone(); - incompatible["openvmm"][field] = serde_json::Value::Null; - assert!(!manifest_is_compatible(&incompatible), "{field}"); - } - } - - #[test] - fn mismatches_name_each_field_with_its_expected_and_declared_values() { - // A release from before time ABI 2 declares the control revision but neither the time - // ABI nor the restore packet, so naming the revision alone would not tell what differs. - let manifest = json!({ - "openvmm": { - "microvm_abi_version": MICROVM_ABI_VERSION, - "control_session_protocol_version": 2, - "control_contract_revision": CONTROL_CONTRACT_REVISION, - } - }); - assert_eq!( - manifest_mismatches(&manifest), - [ - format!("time_abi_version: expected {TIME_ABI_VERSION}, found none"), - format!("restore_packet_version: expected {RESTORE_PACKET_VERSION}, found none"), - format!( - "control_session_protocol_version: expected \ - {CONTROL_SESSION_PROTOCOL_VERSION}, found 2" - ), - ] - ); - let other = json!({"openvmm": {"control_contract_revision": "other"}}); - assert!(manifest_mismatches(&other).contains(&format!( - "control_contract_revision: expected \"{CONTROL_CONTRACT_REVISION}\", found \"other\"" - ))); - assert_eq!(manifest_mismatches(&json!({})).len(), 5); - } -} +mod tests; diff --git a/nvx-rs/src/contract/tests.rs b/nvx-rs/src/contract/tests.rs new file mode 100644 index 000000000..f52a923d2 --- /dev/null +++ b/nvx-rs/src/contract/tests.rs @@ -0,0 +1,57 @@ +use serde_json::json; + +use super::*; + +#[test] +fn release_manifests_must_match_every_bundled_contract() { + let manifest = json!({ + "openvmm": { + "microvm_abi_version": MICROVM_ABI_VERSION, + "time_abi_version": TIME_ABI_VERSION, + "restore_packet_version": RESTORE_PACKET_VERSION, + "control_session_protocol_version": CONTROL_SESSION_PROTOCOL_VERSION, + "control_contract_revision": CONTROL_CONTRACT_REVISION, + } + }); + assert!(manifest_is_compatible(&manifest)); + for field in [ + "microvm_abi_version", + "time_abi_version", + "restore_packet_version", + "control_session_protocol_version", + "control_contract_revision", + ] { + let mut incompatible = manifest.clone(); + incompatible["openvmm"][field] = serde_json::Value::Null; + assert!(!manifest_is_compatible(&incompatible), "{field}"); + } +} + +#[test] +fn mismatches_name_each_field_with_its_expected_and_declared_values() { + // A release from before time ABI 2 declares the control revision but neither the time + // ABI nor the restore packet, so naming the revision alone would not tell what differs. + let manifest = json!({ + "openvmm": { + "microvm_abi_version": MICROVM_ABI_VERSION, + "control_session_protocol_version": 2, + "control_contract_revision": CONTROL_CONTRACT_REVISION, + } + }); + assert_eq!( + manifest_mismatches(&manifest), + [ + format!("time_abi_version: expected {TIME_ABI_VERSION}, found none"), + format!("restore_packet_version: expected {RESTORE_PACKET_VERSION}, found none"), + format!( + "control_session_protocol_version: expected \ + {CONTROL_SESSION_PROTOCOL_VERSION}, found 2" + ), + ] + ); + let other = json!({"openvmm": {"control_contract_revision": "other"}}); + assert!(manifest_mismatches(&other).contains(&format!( + "control_contract_revision: expected \"{CONTROL_CONTRACT_REVISION}\", found \"other\"" + ))); + assert_eq!(manifest_mismatches(&json!({})).len(), 5); +} diff --git a/nvx-rs/src/error.rs b/nvx-rs/src/error.rs index a8db44e7b..9cfdf3701 100644 --- a/nvx-rs/src/error.rs +++ b/nvx-rs/src/error.rs @@ -401,103 +401,4 @@ impl std::error::Error for Error { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn errors_keep_their_kind_message_and_cause() { - let cause = std::io::Error::other("disk full"); - let error = Error::io("cannot write /state/runtime.json").with_source(cause); - assert_eq!(error.kind(), ErrorKind::Io); - assert_eq!(error.code(), ErrorCode::Io); - assert_eq!(error.to_string(), "cannot write /state/runtime.json"); - assert_eq!( - std::error::Error::source(&error).unwrap().to_string(), - "disk full" - ); - let (kind, message, source) = error.into_parts(); - assert_eq!(kind, ErrorKind::Io); - assert_eq!(message, "cannot write /state/runtime.json"); - assert_eq!(source.unwrap().to_string(), "disk full"); - assert_eq!(ErrorKind::TimedOut.to_string(), "timed-out"); - } - - #[test] - fn codes_determine_kinds() { - let error = Error::new(ErrorCode::SandboxExited, "sandbox x stopped unexpectedly"); - assert_eq!(error.code(), ErrorCode::SandboxExited); - assert_eq!(error.kind(), ErrorKind::Exited); - assert_eq!(error.into_parts().0, ErrorKind::Exited); - assert_eq!( - Error::new(ErrorKind::TimedOut, "late").code(), - ErrorCode::TimedOut - ); - assert_eq!(Error::unsupported("no").code(), ErrorCode::Unsupported); - assert_eq!( - ErrorCode::SandboxNotRunning.to_string(), - "sandbox-not-running" - ); - } - - #[test] - fn every_kind_has_a_code_of_its_own_spelling() { - for kind in [ - ErrorKind::Unavailable, - ErrorKind::Unsupported, - ErrorKind::Exited, - ErrorKind::Io, - ErrorKind::NotFound, - ErrorKind::Protocol, - ErrorKind::TimedOut, - ErrorKind::Other, - ] { - let code = ErrorCode::from(kind); - assert_eq!(code.kind(), kind); - assert_eq!(code.as_str(), kind.as_str()); - } - } - - #[test] - fn codes_are_unique_lowercase_words_joined_by_hyphens() { - let mut seen = std::collections::HashSet::new(); - for code in ErrorCode::ALL { - let spelling = code.as_str(); - assert!(seen.insert(spelling), "{spelling} repeats"); - assert!( - spelling - .split('-') - .all(|word| !word.is_empty() && word.bytes().all(|b| b.is_ascii_lowercase())), - "{spelling}" - ); - // A finer code is never spelled as a kind, whose code it would shadow. - if ErrorCode::from(code.kind()) != *code { - assert_ne!(spelling, code.kind().as_str()); - } - } - assert_eq!(seen.len(), ErrorCode::ALL.len()); - } - - #[test] - fn the_readme_documents_every_code_with_its_kind() { - // The table of the README's "Error codes" section lists each code and its kind, in the - // order of `ErrorCode::ALL`. - let readme = include_str!("../README.md"); - let documented: Vec<(String, String)> = readme - .lines() - .skip_while(|line| *line != "### Error codes") - .skip(1) - .take_while(|line| !line.starts_with('#')) - .filter_map(|line| { - let cells: Vec<&str> = line.trim_matches('|').split('|').map(str::trim).collect(); - let code = cells.first()?.strip_prefix('`')?.strip_suffix('`')?; - let kind = cells.get(1)?.strip_prefix('`')?.strip_suffix('`')?; - Some((code.to_owned(), kind.to_owned())) - }) - .collect(); - let expected: Vec<(String, String)> = ErrorCode::ALL - .iter() - .map(|code| (code.as_str().to_owned(), format!("{:?}", code.kind()))) - .collect(); - assert_eq!(documented, expected); - } -} +mod tests; diff --git a/nvx-rs/src/error/tests.rs b/nvx-rs/src/error/tests.rs new file mode 100644 index 000000000..ea926d394 --- /dev/null +++ b/nvx-rs/src/error/tests.rs @@ -0,0 +1,98 @@ +use super::*; + +#[test] +fn errors_keep_their_kind_message_and_cause() { + let cause = std::io::Error::other("disk full"); + let error = Error::io("cannot write /state/runtime.json").with_source(cause); + assert_eq!(error.kind(), ErrorKind::Io); + assert_eq!(error.code(), ErrorCode::Io); + assert_eq!(error.to_string(), "cannot write /state/runtime.json"); + assert_eq!( + std::error::Error::source(&error).unwrap().to_string(), + "disk full" + ); + let (kind, message, source) = error.into_parts(); + assert_eq!(kind, ErrorKind::Io); + assert_eq!(message, "cannot write /state/runtime.json"); + assert_eq!(source.unwrap().to_string(), "disk full"); + assert_eq!(ErrorKind::TimedOut.to_string(), "timed-out"); +} + +#[test] +fn codes_determine_kinds() { + let error = Error::new(ErrorCode::SandboxExited, "sandbox x stopped unexpectedly"); + assert_eq!(error.code(), ErrorCode::SandboxExited); + assert_eq!(error.kind(), ErrorKind::Exited); + assert_eq!(error.into_parts().0, ErrorKind::Exited); + assert_eq!( + Error::new(ErrorKind::TimedOut, "late").code(), + ErrorCode::TimedOut + ); + assert_eq!(Error::unsupported("no").code(), ErrorCode::Unsupported); + assert_eq!( + ErrorCode::SandboxNotRunning.to_string(), + "sandbox-not-running" + ); +} + +#[test] +fn every_kind_has_a_code_of_its_own_spelling() { + for kind in [ + ErrorKind::Unavailable, + ErrorKind::Unsupported, + ErrorKind::Exited, + ErrorKind::Io, + ErrorKind::NotFound, + ErrorKind::Protocol, + ErrorKind::TimedOut, + ErrorKind::Other, + ] { + let code = ErrorCode::from(kind); + assert_eq!(code.kind(), kind); + assert_eq!(code.as_str(), kind.as_str()); + } +} + +#[test] +fn codes_are_unique_lowercase_words_joined_by_hyphens() { + let mut seen = std::collections::HashSet::new(); + for code in ErrorCode::ALL { + let spelling = code.as_str(); + assert!(seen.insert(spelling), "{spelling} repeats"); + assert!( + spelling + .split('-') + .all(|word| !word.is_empty() && word.bytes().all(|b| b.is_ascii_lowercase())), + "{spelling}" + ); + // A finer code is never spelled as a kind, whose code it would shadow. + if ErrorCode::from(code.kind()) != *code { + assert_ne!(spelling, code.kind().as_str()); + } + } + assert_eq!(seen.len(), ErrorCode::ALL.len()); +} + +#[test] +fn the_readme_documents_every_code_with_its_kind() { + // The table of the README's "Error codes" section lists each code and its kind, in the + // order of `ErrorCode::ALL`. + let readme = include_str!("../../README.md"); + let documented: Vec<(String, String)> = readme + .lines() + .skip_while(|line| *line != "### Error codes") + .skip(1) + .take_while(|line| !line.starts_with('#')) + .filter_map(|line| { + let cells: Vec<&str> = line.trim_matches('|').split('|').map(str::trim).collect(); + let code = cells.first()?.strip_prefix('`')?.strip_suffix('`')?; + let kind = cells.get(1)?.strip_prefix('`')?.strip_suffix('`')?; + Some((code.to_owned(), kind.to_owned())) + }) + .collect(); + let expected: Vec<(String, String)> = ErrorCode::ALL + .iter() + .map(|code| (code.as_str().to_owned(), format!("{:?}", code.kind()))) + .collect(); + assert_eq!(documented, expected); +} diff --git a/nvx-rs/src/gpt/crc.rs b/nvx-rs/src/gpt/crc.rs index e4803cf58..b6bce2eac 100644 --- a/nvx-rs/src/gpt/crc.rs +++ b/nvx-rs/src/gpt/crc.rs @@ -69,30 +69,4 @@ pub(super) fn crc32(bytes: &[u8]) -> u32 { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_crc_matches_the_ieee_check_values() { - // The standard check value of CRC-32/ISO-HDLC, and two values that zlib computes. - assert_eq!(crc32(b"123456789"), 0xCBF4_3926); - assert_eq!(crc32(b""), 0); - assert_eq!(crc32(&[0; 4]), 0x2144_DF1C); - assert_eq!( - crc32(b"The quick brown fox jumps over the lazy dog"), - 0x414F_A339 - ); - } - - #[test] - fn a_crc_over_parts_equals_one_over_the_whole() { - let bytes: Vec = (0..=255).cycle().take(1000).collect(); - let parts = Crc32::new() - .update(&bytes[..1]) - .update(&bytes[1..500]) - .update(&[]) - .update(&bytes[500..]) - .finish(); - assert_eq!(parts, crc32(&bytes)); - } -} +mod tests; diff --git a/nvx-rs/src/gpt/crc/tests.rs b/nvx-rs/src/gpt/crc/tests.rs new file mode 100644 index 000000000..7d7d5cdaf --- /dev/null +++ b/nvx-rs/src/gpt/crc/tests.rs @@ -0,0 +1,25 @@ +use super::*; + +#[test] +fn the_crc_matches_the_ieee_check_values() { + // The standard check value of CRC-32/ISO-HDLC, and two values that zlib computes. + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + assert_eq!(crc32(b""), 0); + assert_eq!(crc32(&[0; 4]), 0x2144_DF1C); + assert_eq!( + crc32(b"The quick brown fox jumps over the lazy dog"), + 0x414F_A339 + ); +} + +#[test] +fn a_crc_over_parts_equals_one_over_the_whole() { + let bytes: Vec = (0..=255).cycle().take(1000).collect(); + let parts = Crc32::new() + .update(&bytes[..1]) + .update(&bytes[1..500]) + .update(&[]) + .update(&bytes[500..]) + .finish(); + assert_eq!(parts, crc32(&bytes)); +} diff --git a/nvx-rs/src/guest/time/decoders.rs b/nvx-rs/src/guest/time/decoders.rs index 0ab8e77e5..a323a224b 100644 --- a/nvx-rs/src/guest/time/decoders.rs +++ b/nvx-rs/src/guest/time/decoders.rs @@ -1260,7 +1260,7 @@ mod tests { use proptest::prelude::*; use super::*; - use crate::protocol::cmdline::model; + use crate::protocol::cmdline::tests::model; /// A valid packet header without memory ranges, of generation 1. fn valid_header() -> [u8; PACKET_HEADER_SIZE] { diff --git a/nvx-rs/src/host/launch.rs b/nvx-rs/src/host/launch.rs index ceec1a02f..c5ff22d8b 100644 --- a/nvx-rs/src/host/launch.rs +++ b/nvx-rs/src/host/launch.rs @@ -575,7 +575,7 @@ mod tests { use super::*; use crate::ErrorKind; use crate::host::filesystem::{Bind, ExportChild, Owner}; - use crate::protocol::cmdline::model; + use crate::protocol::cmdline::tests::model; fn spec() -> LaunchSpec { LaunchSpec::new( diff --git a/nvx-rs/src/host/sandbox/specification.rs b/nvx-rs/src/host/sandbox/specification.rs index a7d7998c0..0546d2123 100644 --- a/nvx-rs/src/host/sandbox/specification.rs +++ b/nvx-rs/src/host/sandbox/specification.rs @@ -11,7 +11,7 @@ use super::mount::{aggregate_child_name, parse_mount_value, validate_mount_targe use super::tests::{exported, host_text}; use super::*; use crate::ErrorKind; -use crate::protocol::cmdline::model; +use crate::protocol::cmdline::tests::model; const UUID: &str = "11111111-2222-3333-4444-555555555555"; diff --git a/nvx-rs/src/hypervisor.rs b/nvx-rs/src/hypervisor.rs index 370da4226..9cb73bc08 100644 --- a/nvx-rs/src/hypervisor.rs +++ b/nvx-rs/src/hypervisor.rs @@ -104,42 +104,4 @@ impl FromStr for Hypervisor { } #[cfg(test)] -mod tests { - use super::*; - use crate::ErrorKind; - - #[test] - fn hypervisors_parse_their_openvmm_spelling() { - for hypervisor in [Hypervisor::Kvm, Hypervisor::Mshv, Hypervisor::Whp] { - assert_eq!( - hypervisor.as_str().parse::().unwrap(), - hypervisor - ); - #[cfg(feature = "serde")] - { - assert_eq!( - serde_json::to_string(&hypervisor).unwrap(), - format!("\"{hypervisor}\"") - ); - assert_eq!( - serde_json::from_str::(&format!("\"{hypervisor}\"")).unwrap(), - hypervisor - ); - } - } - let error = "hyperv".parse::().unwrap_err(); - assert_eq!(error.kind(), ErrorKind::Unavailable); - assert_eq!( - error.message(), - "unknown hypervisor \"hyperv\"; choose kvm, mshv, or whp" - ); - } - - #[test] - fn the_platform_default_runs_on_the_host() { - if let Some(hypervisor) = Hypervisor::platform_default() { - assert!(hypervisor.supported_on_host()); - } - assert!(!(Hypervisor::Kvm.supported_on_host() && Hypervisor::Whp.supported_on_host())); - } -} +mod tests; diff --git a/nvx-rs/src/hypervisor/tests.rs b/nvx-rs/src/hypervisor/tests.rs new file mode 100644 index 000000000..a9957e86d --- /dev/null +++ b/nvx-rs/src/hypervisor/tests.rs @@ -0,0 +1,37 @@ +use super::*; +use crate::ErrorKind; + +#[test] +fn hypervisors_parse_their_openvmm_spelling() { + for hypervisor in [Hypervisor::Kvm, Hypervisor::Mshv, Hypervisor::Whp] { + assert_eq!( + hypervisor.as_str().parse::().unwrap(), + hypervisor + ); + #[cfg(feature = "serde")] + { + assert_eq!( + serde_json::to_string(&hypervisor).unwrap(), + format!("\"{hypervisor}\"") + ); + assert_eq!( + serde_json::from_str::(&format!("\"{hypervisor}\"")).unwrap(), + hypervisor + ); + } + } + let error = "hyperv".parse::().unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Unavailable); + assert_eq!( + error.message(), + "unknown hypervisor \"hyperv\"; choose kvm, mshv, or whp" + ); +} + +#[test] +fn the_platform_default_runs_on_the_host() { + if let Some(hypervisor) = Hypervisor::platform_default() { + assert!(hypervisor.supported_on_host()); + } + assert!(!(Hypervisor::Kvm.supported_on_host() && Hypervisor::Whp.supported_on_host())); +} diff --git a/nvx-rs/src/net/cidr.rs b/nvx-rs/src/net/cidr.rs index fa4398d3f..8f1a6ca2d 100644 --- a/nvx-rs/src/net/cidr.rs +++ b/nvx-rs/src/net/cidr.rs @@ -188,243 +188,4 @@ fn mask(address: u128, prefix: u8, width: u8) -> u128 { } #[cfg(test)] -mod tests { - use super::*; - - fn cidr(value: &str) -> Cidr { - Cidr::parse(value).unwrap() - } - - fn from_ipv4_bits(bits: u32, prefix: u8) -> Cidr { - Cidr { - address: IpAddr::V4(Ipv4Addr::from(bits)), - prefix, - } - } - - #[test] - fn parsing_requires_canonical_networks() { - assert_eq!(cidr("192.0.2.1").to_string(), "192.0.2.1/32"); - assert_eq!(cidr("10.0.0.0/8").to_string(), "10.0.0.0/8"); - assert_eq!(cidr("0.0.0.0/0").to_string(), "0.0.0.0/0"); - assert_eq!(cidr("2001:db8::/32").to_string(), "2001:db8::/32"); - assert_eq!(cidr("2001:db8::1").to_string(), "2001:db8::1/128"); - assert_eq!(cidr("::/0").to_string(), "::/0"); - assert!(cidr("2001:db8::/32").is_ipv6() && !cidr("10.0.0.0/8").is_ipv6()); - assert_eq!(Cidr::everything(false), cidr("0.0.0.0/0")); - assert_eq!(Cidr::everything(true), cidr("::/0")); - for invalid in [ - "10.0.0.1/8", - "10.0.0.0/33", - "10.0.0.0/08", - "0.0.0.0/00", - "10.0.0.0/+8", - "192.0.2.1/+32", - "0.0.0.0/+0", - "2001:db8::/+32", - "2001:db8::/129", - "example.com", - "10.0.0.0/", - "2001:db8::1/32", - "fe80::1%eth0", - ] { - assert!(Cidr::parse(invalid).is_err(), "{invalid}"); - } - } - - #[test] - fn masked_parsing_clears_host_bits_as_openvmm_does() { - let masked = |value: &str| Cidr::parse_masked(value).unwrap().to_string(); - assert_eq!(masked("10.0.0.1/8"), "10.0.0.0/8"); - assert_eq!(masked("192.0.2.7"), "192.0.2.7/32"); - assert_eq!(masked("2001:db8::1/32"), "2001:db8::/32"); - assert_eq!(masked("2001:db8::1"), "2001:db8::1/128"); - assert_eq!(masked("::ffff:192.0.2.1/96"), "::ffff:0.0.0.0/96"); - // OpenVMM reads the prefix length as `u8::from_str` does. - assert_eq!(masked("10.0.0.0/08"), "10.0.0.0/8"); - assert_eq!(masked("10.0.0.0/+8"), "10.0.0.0/8"); - for invalid in [ - "10.0.0.0/33", - "2001:db8::/129", - "10.0.0.0/", - "10.0.0.0/-1", - "10.0.0.0/255.0.0.0", - "10.0.0.0/8/8", - "010.0.0.0/8", - "example.com", - "fe80::1%eth0", - ] { - assert!(Cidr::parse_masked(invalid).is_err(), "{invalid}"); - } - } - - #[test] - fn containment_is_family_aware() { - let outer = cidr("10.0.0.0/8"); - assert!(outer.contains(cidr("10.1.0.0/16"))); - assert!(outer.contains(outer)); - assert!(!outer.contains(cidr("11.0.0.0/16"))); - assert!(!outer.contains(cidr("::/0"))); - let v6 = cidr("2001:db8::/32"); - assert!(v6.contains(cidr("2001:db8:1::/48"))); - assert!(!v6.contains(cidr("2001:db9::/48"))); - // ::/96 and 0.0.0.0/0 span the same integers but never contain each other. - assert!(!cidr("::/96").contains(cidr("0.0.0.0/0"))); - assert!(!cidr("0.0.0.0/0").contains(cidr("::/96"))); - } - - #[test] - fn subtraction_covers_exactly_the_remainder() { - let subtract = |network: &str, excluded: &[Cidr]| { - cidr(network).subtract(excluded, usize::MAX).unwrap() - }; - let rendered = |networks: Vec| -> Vec { - networks.iter().map(ToString::to_string).collect() - }; - assert_eq!( - rendered(subtract("10.0.0.0/8", &[cidr("10.0.0.0/9")])), - ["10.128.0.0/9"] - ); - assert_eq!( - rendered(subtract("10.0.0.0/30", &[cidr("10.0.0.1")])), - ["10.0.0.0/32", "10.0.0.2/31"] - ); - assert!(subtract("10.1.0.0/16", &[cidr("10.0.0.0/8")]).is_empty()); - assert_eq!( - subtract("10.0.0.0/8", &[cidr("11.0.0.0/8")]), - [cidr("10.0.0.0/8")] - ); - // An exclusion of the other family excludes nothing. - assert_eq!(subtract("0.0.0.0/0", &[cidr("::/96")]), [cidr("0.0.0.0/0")]); - assert_eq!(subtract("::/96", &[cidr("0.0.0.0/0")]), [cidr("::/96")]); - // Every remaining address is outside the exclusions, and the sizes add up. - let excluded = [cidr("10.0.0.0/24"), cidr("10.0.7.0/24")]; - let remainder = subtract("10.0.0.0/16", &excluded); - let covered: u64 = remainder - .iter() - .map(|cidr| 1u64 << (32 - u32::from(cidr.prefix))) - .sum(); - assert_eq!(covered, (1 << 16) - 2 * 256); - assert!( - remainder - .iter() - .all(|cidr| !excluded.iter().any(|exclusion| exclusion.overlaps(*cidr))) - ); - } - - #[test] - fn ipv6_subtraction_covers_exactly_the_remainder() { - let remainder = cidr("2001:db8::/32") - .subtract( - &[cidr("2001:db8:1::/48"), cidr("2001:db8:8000::/33")], - usize::MAX, - ) - .unwrap(); - let rendered: Vec = remainder.iter().map(ToString::to_string).collect(); - assert_eq!( - rendered, - [ - "2001:db8::/48", - "2001:db8:2::/47", - "2001:db8:4::/46", - "2001:db8:8::/45", - "2001:db8:10::/44", - "2001:db8:20::/43", - "2001:db8:40::/42", - "2001:db8:80::/41", - "2001:db8:100::/40", - "2001:db8:200::/39", - "2001:db8:400::/38", - "2001:db8:800::/37", - "2001:db8:1000::/36", - "2001:db8:2000::/35", - "2001:db8:4000::/34", - ] - ); - let host = cidr("2001:db8::1:123"); - assert_eq!( - cidr("2001:db8::1:122/127") - .subtract(&[host], usize::MAX) - .unwrap(), - [cidr("2001:db8::1:122")] - ); - assert_eq!( - cidr("::/0").subtract(&[cidr("::/1")], usize::MAX).unwrap(), - [cidr("8000::/1")] - ); - } - - /// The direct recursion that rescans every exclusion at each split, as a reference. - fn reference_subtract(network: Cidr, excluded: &[Cidr]) -> Vec { - if excluded.iter().any(|exclusion| exclusion.contains(network)) { - return Vec::new(); - } - if !excluded.iter().any(|exclusion| exclusion.overlaps(network)) { - return vec![network]; - } - network - .halves() - .into_iter() - .flat_map(|half| reference_subtract(half, excluded)) - .collect() - } - - #[test] - fn partitioned_subtraction_matches_the_direct_recursion() { - // A linear congruential generator keeps the cases deterministic. - let mut state = 0x2545_f491_u32; - let mut next = move || { - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - state - }; - for network in [cidr("10.0.0.0/16"), cidr("2001:db8::/112")] { - let low_bits = network.bits() as u32; - for _ in 0..500 { - let count = next() % 32; - let excluded: Vec = (0..count) - .map(|_| { - let prefix = 12 + (next() % 21) as u8; - // Most exclusions fall inside the network; some cover it or lie - // elsewhere. - let bits = if next() % 4 == 0 { - next() - } else { - low_bits | (next() & 0xffff) - }; - if network.is_ipv6() { - let prefix = prefix + 96; - let address = - (network.bits() & !u128::from(u32::MAX)) | u128::from(bits); - network.with_bits(mask(address, prefix, 128), prefix) - } else { - from_ipv4_bits(mask(u128::from(bits), prefix, 32) as u32, prefix) - } - }) - .collect(); - assert_eq!( - network.subtract(&excluded, usize::MAX).unwrap(), - reference_subtract(network, &excluded), - "{excluded:?}" - ); - } - } - } - - #[test] - fn subtraction_stops_once_the_remainder_exceeds_its_limit() { - // 512 evenly spaced addresses split the address space into 512 * 23 networks. - let excluded: Vec = (0..512u32) - .map(|index| from_ipv4_bits(index << 23, 32)) - .collect(); - let everything = Cidr::everything(false); - let size = |limit| { - everything - .subtract(&excluded, limit) - .map(|remainder| remainder.len()) - }; - assert_eq!(size(usize::MAX), Some(512 * 23)); - assert_eq!(size(512 * 23), Some(512 * 23)); - assert_eq!(size(512 * 23 - 1), None); - assert_eq!(size(256), None); - } -} +mod tests; diff --git a/nvx-rs/src/net/cidr/tests.rs b/nvx-rs/src/net/cidr/tests.rs new file mode 100644 index 000000000..5fba04396 --- /dev/null +++ b/nvx-rs/src/net/cidr/tests.rs @@ -0,0 +1,235 @@ +use super::*; + +fn cidr(value: &str) -> Cidr { + Cidr::parse(value).unwrap() +} + +fn from_ipv4_bits(bits: u32, prefix: u8) -> Cidr { + Cidr { + address: IpAddr::V4(Ipv4Addr::from(bits)), + prefix, + } +} + +#[test] +fn parsing_requires_canonical_networks() { + assert_eq!(cidr("192.0.2.1").to_string(), "192.0.2.1/32"); + assert_eq!(cidr("10.0.0.0/8").to_string(), "10.0.0.0/8"); + assert_eq!(cidr("0.0.0.0/0").to_string(), "0.0.0.0/0"); + assert_eq!(cidr("2001:db8::/32").to_string(), "2001:db8::/32"); + assert_eq!(cidr("2001:db8::1").to_string(), "2001:db8::1/128"); + assert_eq!(cidr("::/0").to_string(), "::/0"); + assert!(cidr("2001:db8::/32").is_ipv6() && !cidr("10.0.0.0/8").is_ipv6()); + assert_eq!(Cidr::everything(false), cidr("0.0.0.0/0")); + assert_eq!(Cidr::everything(true), cidr("::/0")); + for invalid in [ + "10.0.0.1/8", + "10.0.0.0/33", + "10.0.0.0/08", + "0.0.0.0/00", + "10.0.0.0/+8", + "192.0.2.1/+32", + "0.0.0.0/+0", + "2001:db8::/+32", + "2001:db8::/129", + "example.com", + "10.0.0.0/", + "2001:db8::1/32", + "fe80::1%eth0", + ] { + assert!(Cidr::parse(invalid).is_err(), "{invalid}"); + } +} + +#[test] +fn masked_parsing_clears_host_bits_as_openvmm_does() { + let masked = |value: &str| Cidr::parse_masked(value).unwrap().to_string(); + assert_eq!(masked("10.0.0.1/8"), "10.0.0.0/8"); + assert_eq!(masked("192.0.2.7"), "192.0.2.7/32"); + assert_eq!(masked("2001:db8::1/32"), "2001:db8::/32"); + assert_eq!(masked("2001:db8::1"), "2001:db8::1/128"); + assert_eq!(masked("::ffff:192.0.2.1/96"), "::ffff:0.0.0.0/96"); + // OpenVMM reads the prefix length as `u8::from_str` does. + assert_eq!(masked("10.0.0.0/08"), "10.0.0.0/8"); + assert_eq!(masked("10.0.0.0/+8"), "10.0.0.0/8"); + for invalid in [ + "10.0.0.0/33", + "2001:db8::/129", + "10.0.0.0/", + "10.0.0.0/-1", + "10.0.0.0/255.0.0.0", + "10.0.0.0/8/8", + "010.0.0.0/8", + "example.com", + "fe80::1%eth0", + ] { + assert!(Cidr::parse_masked(invalid).is_err(), "{invalid}"); + } +} + +#[test] +fn containment_is_family_aware() { + let outer = cidr("10.0.0.0/8"); + assert!(outer.contains(cidr("10.1.0.0/16"))); + assert!(outer.contains(outer)); + assert!(!outer.contains(cidr("11.0.0.0/16"))); + assert!(!outer.contains(cidr("::/0"))); + let v6 = cidr("2001:db8::/32"); + assert!(v6.contains(cidr("2001:db8:1::/48"))); + assert!(!v6.contains(cidr("2001:db9::/48"))); + // ::/96 and 0.0.0.0/0 span the same integers but never contain each other. + assert!(!cidr("::/96").contains(cidr("0.0.0.0/0"))); + assert!(!cidr("0.0.0.0/0").contains(cidr("::/96"))); +} + +#[test] +fn subtraction_covers_exactly_the_remainder() { + let subtract = + |network: &str, excluded: &[Cidr]| cidr(network).subtract(excluded, usize::MAX).unwrap(); + let rendered = + |networks: Vec| -> Vec { networks.iter().map(ToString::to_string).collect() }; + assert_eq!( + rendered(subtract("10.0.0.0/8", &[cidr("10.0.0.0/9")])), + ["10.128.0.0/9"] + ); + assert_eq!( + rendered(subtract("10.0.0.0/30", &[cidr("10.0.0.1")])), + ["10.0.0.0/32", "10.0.0.2/31"] + ); + assert!(subtract("10.1.0.0/16", &[cidr("10.0.0.0/8")]).is_empty()); + assert_eq!( + subtract("10.0.0.0/8", &[cidr("11.0.0.0/8")]), + [cidr("10.0.0.0/8")] + ); + // An exclusion of the other family excludes nothing. + assert_eq!(subtract("0.0.0.0/0", &[cidr("::/96")]), [cidr("0.0.0.0/0")]); + assert_eq!(subtract("::/96", &[cidr("0.0.0.0/0")]), [cidr("::/96")]); + // Every remaining address is outside the exclusions, and the sizes add up. + let excluded = [cidr("10.0.0.0/24"), cidr("10.0.7.0/24")]; + let remainder = subtract("10.0.0.0/16", &excluded); + let covered: u64 = remainder + .iter() + .map(|cidr| 1u64 << (32 - u32::from(cidr.prefix))) + .sum(); + assert_eq!(covered, (1 << 16) - 2 * 256); + assert!( + remainder + .iter() + .all(|cidr| !excluded.iter().any(|exclusion| exclusion.overlaps(*cidr))) + ); +} + +#[test] +fn ipv6_subtraction_covers_exactly_the_remainder() { + let remainder = cidr("2001:db8::/32") + .subtract( + &[cidr("2001:db8:1::/48"), cidr("2001:db8:8000::/33")], + usize::MAX, + ) + .unwrap(); + let rendered: Vec = remainder.iter().map(ToString::to_string).collect(); + assert_eq!( + rendered, + [ + "2001:db8::/48", + "2001:db8:2::/47", + "2001:db8:4::/46", + "2001:db8:8::/45", + "2001:db8:10::/44", + "2001:db8:20::/43", + "2001:db8:40::/42", + "2001:db8:80::/41", + "2001:db8:100::/40", + "2001:db8:200::/39", + "2001:db8:400::/38", + "2001:db8:800::/37", + "2001:db8:1000::/36", + "2001:db8:2000::/35", + "2001:db8:4000::/34", + ] + ); + let host = cidr("2001:db8::1:123"); + assert_eq!( + cidr("2001:db8::1:122/127") + .subtract(&[host], usize::MAX) + .unwrap(), + [cidr("2001:db8::1:122")] + ); + assert_eq!( + cidr("::/0").subtract(&[cidr("::/1")], usize::MAX).unwrap(), + [cidr("8000::/1")] + ); +} + +/// The direct recursion that rescans every exclusion at each split, as a reference. +fn reference_subtract(network: Cidr, excluded: &[Cidr]) -> Vec { + if excluded.iter().any(|exclusion| exclusion.contains(network)) { + return Vec::new(); + } + if !excluded.iter().any(|exclusion| exclusion.overlaps(network)) { + return vec![network]; + } + network + .halves() + .into_iter() + .flat_map(|half| reference_subtract(half, excluded)) + .collect() +} + +#[test] +fn partitioned_subtraction_matches_the_direct_recursion() { + // A linear congruential generator keeps the cases deterministic. + let mut state = 0x2545_f491_u32; + let mut next = move || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + state + }; + for network in [cidr("10.0.0.0/16"), cidr("2001:db8::/112")] { + let low_bits = network.bits() as u32; + for _ in 0..500 { + let count = next() % 32; + let excluded: Vec = (0..count) + .map(|_| { + let prefix = 12 + (next() % 21) as u8; + // Most exclusions fall inside the network; some cover it or lie + // elsewhere. + let bits = if next() % 4 == 0 { + next() + } else { + low_bits | (next() & 0xffff) + }; + if network.is_ipv6() { + let prefix = prefix + 96; + let address = (network.bits() & !u128::from(u32::MAX)) | u128::from(bits); + network.with_bits(mask(address, prefix, 128), prefix) + } else { + from_ipv4_bits(mask(u128::from(bits), prefix, 32) as u32, prefix) + } + }) + .collect(); + assert_eq!( + network.subtract(&excluded, usize::MAX).unwrap(), + reference_subtract(network, &excluded), + "{excluded:?}" + ); + } + } +} + +#[test] +fn subtraction_stops_once_the_remainder_exceeds_its_limit() { + // 512 evenly spaced addresses split the address space into 512 * 23 networks. + let excluded: Vec = (0..512u32) + .map(|index| from_ipv4_bits(index << 23, 32)) + .collect(); + let everything = Cidr::everything(false); + let size = |limit| { + everything + .subtract(&excluded, limit) + .map(|remainder| remainder.len()) + }; + assert_eq!(size(usize::MAX), Some(512 * 23)); + assert_eq!(size(512 * 23), Some(512 * 23)); + assert_eq!(size(512 * 23 - 1), None); + assert_eq!(size(256), None); +} diff --git a/nvx-rs/src/net/mod.rs b/nvx-rs/src/net/mod.rs index c19215cfa..13e78edb8 100644 --- a/nvx-rs/src/net/mod.rs +++ b/nvx-rs/src/net/mod.rs @@ -47,50 +47,4 @@ fn guest_address(value: &str) -> Option<(u32, u32)> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn guest_networks_follow_openvmm_rules() { - for valid in ["10.0.0.2/24", "192.168.7.10/30", "172.16.0.200/16"] { - assert!(is_valid_guest_network(valid), "{valid}"); - } - for invalid in [ - "10.0.0.0/24", - "10.0.0.255/24", - "10.0.0.1/24", - "10.0.0.5/30", - "10.0.0.2", - "10.0.0.2/31", - "10.0.0.2/024", - "fd00::2/64", - ] { - assert!(!is_valid_guest_network(invalid), "{invalid}"); - assert_eq!(guest_gateway(invalid), None, "{invalid}"); - } - } - - #[test] - fn the_gateway_is_the_first_address_of_the_guest_network() { - for (network, gateway) in [ - ("10.0.0.2/24", [10, 0, 0, 1]), - ("192.168.7.10/30", [192, 168, 7, 9]), - ("172.16.0.200/16", [172, 16, 0, 1]), - ("10.255.255.254/8", [10, 0, 0, 1]), - ] { - assert_eq!( - guest_gateway(network), - Some(std::net::Ipv4Addr::from(gateway)), - "{network}" - ); - } - } - - #[test] - fn hostnames_are_lowercase_labels() { - assert!(is_valid_hostname("nvx-sandbox")); - for invalid in ["", "-a", "a-", "A", "a.b", &"a".repeat(64)] { - assert!(!is_valid_hostname(invalid), "{invalid:?}"); - } - } -} +mod tests; diff --git a/nvx-rs/src/net/tests.rs b/nvx-rs/src/net/tests.rs new file mode 100644 index 000000000..a48f1776e --- /dev/null +++ b/nvx-rs/src/net/tests.rs @@ -0,0 +1,45 @@ +use super::*; + +#[test] +fn guest_networks_follow_openvmm_rules() { + for valid in ["10.0.0.2/24", "192.168.7.10/30", "172.16.0.200/16"] { + assert!(is_valid_guest_network(valid), "{valid}"); + } + for invalid in [ + "10.0.0.0/24", + "10.0.0.255/24", + "10.0.0.1/24", + "10.0.0.5/30", + "10.0.0.2", + "10.0.0.2/31", + "10.0.0.2/024", + "fd00::2/64", + ] { + assert!(!is_valid_guest_network(invalid), "{invalid}"); + assert_eq!(guest_gateway(invalid), None, "{invalid}"); + } +} + +#[test] +fn the_gateway_is_the_first_address_of_the_guest_network() { + for (network, gateway) in [ + ("10.0.0.2/24", [10, 0, 0, 1]), + ("192.168.7.10/30", [192, 168, 7, 9]), + ("172.16.0.200/16", [172, 16, 0, 1]), + ("10.255.255.254/8", [10, 0, 0, 1]), + ] { + assert_eq!( + guest_gateway(network), + Some(std::net::Ipv4Addr::from(gateway)), + "{network}" + ); + } +} + +#[test] +fn hostnames_are_lowercase_labels() { + assert!(is_valid_hostname("nvx-sandbox")); + for invalid in ["", "-a", "a-", "A", "a.b", &"a".repeat(64)] { + assert!(!is_valid_hostname(invalid), "{invalid:?}"); + } +} diff --git a/nvx-rs/src/protocol/cmdline.rs b/nvx-rs/src/protocol/cmdline.rs index aff2a0423..bd7a76b78 100644 --- a/nvx-rs/src/protocol/cmdline.rs +++ b/nvx-rs/src/protocol/cmdline.rs @@ -416,6 +416,4 @@ fn integer(text: &[u8], base: u32) -> (u64, usize) { } #[cfg(test)] -pub(crate) mod model; -#[cfg(test)] -mod tests; +pub(crate) mod tests; diff --git a/nvx-rs/src/protocol/cmdline/tests.rs b/nvx-rs/src/protocol/cmdline/tests.rs index 4a6e65948..777c939d2 100644 --- a/nvx-rs/src/protocol/cmdline/tests.rs +++ b/nvx-rs/src/protocol/cmdline/tests.rs @@ -12,6 +12,8 @@ use proptest::prelude::*; use super::*; +pub(crate) mod model; + /// The MMIO base of the scratch block device of a layered root. const SCRATCH: u64 = 0xd000_6000; diff --git a/nvx-rs/src/protocol/cmdline/model.rs b/nvx-rs/src/protocol/cmdline/tests/model.rs similarity index 100% rename from nvx-rs/src/protocol/cmdline/model.rs rename to nvx-rs/src/protocol/cmdline/tests/model.rs diff --git a/nvx-rs/src/protocol/nvxs/record.rs b/nvx-rs/src/protocol/nvxs/record.rs index adea7d8ee..c409cd391 100644 --- a/nvx-rs/src/protocol/nvxs/record.rs +++ b/nvx-rs/src/protocol/nvxs/record.rs @@ -500,15 +500,6 @@ impl RecordParser { } } - /// Returns the capacity of the payload buffer, which tests check against the declared - /// length. - #[cfg(test)] - pub(super) fn payload_capacity(&self) -> usize { - self.body - .as_ref() - .map_or(0, |(_, payload)| payload.capacity()) - } - /// Consumes bytes of the record in progress; [`push`](Self::push) records a failure. fn accept(&mut self, input: &[u8]) -> Result<(usize, Option), RecordError> { let mut consumed = 0; @@ -564,3 +555,6 @@ impl fmt::Debug for RecordParser { .finish() } } + +#[cfg(test)] +mod tests; diff --git a/nvx-rs/src/protocol/nvxs/record/tests.rs b/nvx-rs/src/protocol/nvxs/record/tests.rs new file mode 100644 index 000000000..0b44e1ec5 --- /dev/null +++ b/nvx-rs/src/protocol/nvxs/record/tests.rs @@ -0,0 +1,13 @@ +//! What the tests of the `NVXS` session read of a record parser beyond its public API. + +use super::RecordParser; + +impl RecordParser { + /// Returns the capacity of the payload buffer, which tests check against the declared + /// length. + pub(in crate::protocol::nvxs) fn payload_capacity(&self) -> usize { + self.body + .as_ref() + .map_or(0, |(_, payload)| payload.capacity()) + } +} diff --git a/nvx-rs/src/protocol/share.rs b/nvx-rs/src/protocol/share.rs index 825b59e5b..ca1a9a378 100644 --- a/nvx-rs/src/protocol/share.rs +++ b/nvx-rs/src/protocol/share.rs @@ -62,71 +62,4 @@ pub fn reservation(target: &[u8]) -> Option { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_reserved_targets_and_characters_are_pinned() { - assert_eq!( - RESERVED_MOUNT_TARGETS, - [ - "/proc", - "/sys", - "/dev", - "/.nvx-agent", - "/etc/machine-id", - "/etc/resolv.conf", - "/run/nvx/time" - ] - ); - assert_eq!(RESERVED_EXACT_MOUNT_TARGETS, ["/etc", "/run", "/run/nvx"]); - assert_eq!(RESERVED_TARGET_CHARACTERS, "\0\\=,\""); - } - - #[test] - fn a_target_is_reserved_in_a_tree_or_at_an_exact_path() { - for (target, tree) in [ - ("/proc", "/proc"), - ("/proc/self", "/proc"), - ("/sys/fs/cgroup", "/sys"), - ("/dev/shm", "/dev"), - ("/.nvx-agent/tool", "/.nvx-agent"), - ("/etc/machine-id", "/etc/machine-id"), - ("/etc/machine-id/x", "/etc/machine-id"), - ("/etc/resolv.conf", "/etc/resolv.conf"), - ("/etc/resolv.conf/x", "/etc/resolv.conf"), - ("/run/nvx/time", "/run/nvx/time"), - ("/run/nvx/time/state", "/run/nvx/time"), - ] { - assert_eq!( - reservation(target.as_bytes()), - Some(Reservation::Tree(tree)), - "{target}" - ); - } - for target in ["/etc", "/run", "/run/nvx"] { - assert_eq!( - reservation(target.as_bytes()), - Some(Reservation::Exact), - "{target}" - ); - } - for target in [ - "/workspace", - "/procs", - "/devices", - "/.nvx-agents", - "/etc/app", - "/etc/machine-ids", - "/etc/resolv.conf.d", - "/etc/resolvconf", - "/run/app", - "/run/nvx/state", - "/run/nvx/timer", - "/", - "", - ] { - assert_eq!(reservation(target.as_bytes()), None, "{target}"); - } - } -} +mod tests; diff --git a/nvx-rs/src/protocol/share/tests.rs b/nvx-rs/src/protocol/share/tests.rs new file mode 100644 index 000000000..3dcaac944 --- /dev/null +++ b/nvx-rs/src/protocol/share/tests.rs @@ -0,0 +1,66 @@ +use super::*; + +#[test] +fn the_reserved_targets_and_characters_are_pinned() { + assert_eq!( + RESERVED_MOUNT_TARGETS, + [ + "/proc", + "/sys", + "/dev", + "/.nvx-agent", + "/etc/machine-id", + "/etc/resolv.conf", + "/run/nvx/time" + ] + ); + assert_eq!(RESERVED_EXACT_MOUNT_TARGETS, ["/etc", "/run", "/run/nvx"]); + assert_eq!(RESERVED_TARGET_CHARACTERS, "\0\\=,\""); +} + +#[test] +fn a_target_is_reserved_in_a_tree_or_at_an_exact_path() { + for (target, tree) in [ + ("/proc", "/proc"), + ("/proc/self", "/proc"), + ("/sys/fs/cgroup", "/sys"), + ("/dev/shm", "/dev"), + ("/.nvx-agent/tool", "/.nvx-agent"), + ("/etc/machine-id", "/etc/machine-id"), + ("/etc/machine-id/x", "/etc/machine-id"), + ("/etc/resolv.conf", "/etc/resolv.conf"), + ("/etc/resolv.conf/x", "/etc/resolv.conf"), + ("/run/nvx/time", "/run/nvx/time"), + ("/run/nvx/time/state", "/run/nvx/time"), + ] { + assert_eq!( + reservation(target.as_bytes()), + Some(Reservation::Tree(tree)), + "{target}" + ); + } + for target in ["/etc", "/run", "/run/nvx"] { + assert_eq!( + reservation(target.as_bytes()), + Some(Reservation::Exact), + "{target}" + ); + } + for target in [ + "/workspace", + "/procs", + "/devices", + "/.nvx-agents", + "/etc/app", + "/etc/machine-ids", + "/etc/resolv.conf.d", + "/etc/resolvconf", + "/run/app", + "/run/nvx/state", + "/run/nvx/timer", + "/", + "", + ] { + assert_eq!(reservation(target.as_bytes()), None, "{target}"); + } +} diff --git a/nvx-rs/src/protocol/status.rs b/nvx-rs/src/protocol/status.rs index 3b5d15f1d..45c54a57d 100644 --- a/nvx-rs/src/protocol/status.rs +++ b/nvx-rs/src/protocol/status.rs @@ -117,70 +117,4 @@ pub fn describe(status: u8) -> Option<&'static str> { } #[cfg(test)] -mod tests { - use super::*; - - /// Every status that the module names, in its order. - const ALL: [u8; 18] = [ - TIME_CONFORMANCE, - TIME_VIOLATION, - TIME_REPAIR, - REPAIR_RESTORE, - REPAIR_PROCESSORS, - REPAIR_MEMORY_TARGET, - REPAIR_MEMORY, - REPAIR_RESEED, - REPAIR_FINISH, - ACTIVATION_DEADLINE, - ACTIVATION_PROTOCOL, - ACTIVATION_RECORD, - ACTIVATION_RESOURCES, - ACTIVATION_ROOT, - ACTIVATION_WORKLOAD, - ACTIVATION_EXPORT, - ACTIVATION_NETWORK, - ACTIVATION_ORDER, - ]; - - #[test] - fn the_statuses_are_pinned() { - assert_eq!( - ALL, - [ - 193, 194, 195, 40, 41, 42, 43, 44, 45, 50, 51, 52, 53, 54, 55, 56, 57, 58 - ] - ); - assert_eq!(TIME_STATUSES, 193..=195); - assert_eq!(REPAIR_STATUSES, 40..=45); - assert_eq!(ACTIVATION_STATUSES, 50..=58); - } - - #[test] - fn each_status_has_a_class_and_a_meaning_of_its_own() { - let mut meanings = Vec::new(); - for status in ALL { - let classes = [&TIME_STATUSES, &REPAIR_STATUSES, &ACTIVATION_STATUSES] - .into_iter() - .filter(|statuses| statuses.contains(&status)) - .count(); - assert_eq!(classes, 1, "{status}"); - meanings.push(describe(status).unwrap()); - } - meanings.sort_unstable(); - meanings.dedup(); - assert_eq!(meanings.len(), ALL.len()); - // The ranges hold no other status, and the module names no other. - for status in 0..=u8::MAX { - assert_eq!( - describe(status).is_some(), - ALL.contains(&status), - "{status}" - ); - } - // None is a success, the generic failure, a usage error, a sandbox setup failure, or a - // status that a shell gives a command that it cannot run or that a signal ended. - for reserved in [0, 1, 2, 125, 126, 127, 128, 129, 137, 143, 255] { - assert!(!ALL.contains(&reserved), "{reserved}"); - } - } -} +mod tests; diff --git a/nvx-rs/src/protocol/status/tests.rs b/nvx-rs/src/protocol/status/tests.rs new file mode 100644 index 000000000..3b8be12e0 --- /dev/null +++ b/nvx-rs/src/protocol/status/tests.rs @@ -0,0 +1,65 @@ +use super::*; + +/// Every status that the module names, in its order. +const ALL: [u8; 18] = [ + TIME_CONFORMANCE, + TIME_VIOLATION, + TIME_REPAIR, + REPAIR_RESTORE, + REPAIR_PROCESSORS, + REPAIR_MEMORY_TARGET, + REPAIR_MEMORY, + REPAIR_RESEED, + REPAIR_FINISH, + ACTIVATION_DEADLINE, + ACTIVATION_PROTOCOL, + ACTIVATION_RECORD, + ACTIVATION_RESOURCES, + ACTIVATION_ROOT, + ACTIVATION_WORKLOAD, + ACTIVATION_EXPORT, + ACTIVATION_NETWORK, + ACTIVATION_ORDER, +]; + +#[test] +fn the_statuses_are_pinned() { + assert_eq!( + ALL, + [ + 193, 194, 195, 40, 41, 42, 43, 44, 45, 50, 51, 52, 53, 54, 55, 56, 57, 58 + ] + ); + assert_eq!(TIME_STATUSES, 193..=195); + assert_eq!(REPAIR_STATUSES, 40..=45); + assert_eq!(ACTIVATION_STATUSES, 50..=58); +} + +#[test] +fn each_status_has_a_class_and_a_meaning_of_its_own() { + let mut meanings = Vec::new(); + for status in ALL { + let classes = [&TIME_STATUSES, &REPAIR_STATUSES, &ACTIVATION_STATUSES] + .into_iter() + .filter(|statuses| statuses.contains(&status)) + .count(); + assert_eq!(classes, 1, "{status}"); + meanings.push(describe(status).unwrap()); + } + meanings.sort_unstable(); + meanings.dedup(); + assert_eq!(meanings.len(), ALL.len()); + // The ranges hold no other status, and the module names no other. + for status in 0..=u8::MAX { + assert_eq!( + describe(status).is_some(), + ALL.contains(&status), + "{status}" + ); + } + // None is a success, the generic failure, a usage error, a sandbox setup failure, or a + // status that a shell gives a command that it cannot run or that a signal ended. + for reserved in [0, 1, 2, 125, 126, 127, 128, 129, 137, 143, 255] { + assert!(!ALL.contains(&reserved), "{reserved}"); + } +} diff --git a/nvx-rs/src/testing/fake_openvmm.rs b/nvx-rs/src/testing/fake_openvmm.rs index 39bdaacc5..99435aa96 100644 --- a/nvx-rs/src/testing/fake_openvmm.rs +++ b/nvx-rs/src/testing/fake_openvmm.rs @@ -2673,708 +2673,4 @@ fn serve(options: &Options, capability: &[u8; CAPABILITY_LEN]) -> io::Result<()> } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shells_raise_shlvl_like_busybox() { - let level = |value: &str| { - let mut environment = vec![("SHLVL".to_owned(), value.to_owned())]; - start_shell(&mut environment, "/work"); - assert_eq!(environment[1], ("PWD".to_owned(), "/work".to_owned())); - environment.swap_remove(0).1 - }; - assert_eq!(level("1"), "2"); - assert_eq!(level("7x"), "8"); - assert_eq!(level(" +3"), "4"); - assert_eq!(level("nothing"), "1"); - assert_eq!(level("4294967295"), "0"); - assert_eq!(level("-1"), "0"); - assert_eq!(level("-3"), "4294967294"); - let mut fresh = Environment::new(); - start_shell(&mut fresh, "/"); - assert_eq!(fresh[0], ("SHLVL".to_owned(), "1".to_owned())); - } - - #[test] - fn the_current_guest_advertises_every_required_feature() { - assert_eq!(GUEST_FEATURES, GuestFeatures::REQUIRED); - assert!(GUEST_FEATURES.missing(GuestFeatures::REQUIRED).is_empty()); - } - - #[test] - fn mount_children_resolve_to_hosts_of_their_kind() { - let temporary = tempfile::tempdir().unwrap(); - let directory = temporary.path().to_str().unwrap().to_owned(); - let file = temporary.path().join("file").to_str().unwrap().to_owned(); - fs::write(&file, b"").unwrap(); - for (value, index, host) in [ - (format!("0,{directory},rw"), Some(0), &directory), - (format!("1,{file},ro,file"), Some(1), &file), - // Without an index, any name goes, as for the children of a sandbox's aggregate. - (format!("digest,{directory},ro"), None, &directory), - ] { - assert_eq!(mount_child_host(&value, index), Ok(PathBuf::from(host))); - } - for (value, index) in [ - (format!("1,{directory},rw"), Some(0)), - (format!("0,{file},rw"), None), - (format!("0,{directory},ro,file"), None), - (format!("0,{directory}-missing,rw"), None), - (format!("0,{directory},wo"), None), - (format!("0,{directory}"), None), - ("0".to_owned(), None), - ] { - assert_eq!( - mount_child_host(&value, index), - Err(format!("invalid --mount-child {value}")) - ); - } - } - - /// Returns a directory with a kernel, an initramfs, a share with a `hidden` directory, and a - /// snapshot directory, and the parse of the command line that `arguments` gives with the - /// paths of that directory in place of `{dir}`. - fn parse_run(arguments: &[&str]) -> (tempfile::TempDir, Result) { - let temporary = tempfile::tempdir().unwrap(); - let root = temporary.path(); - fs::write(root.join("vmlinux"), b"kernel").unwrap(); - fs::write(root.join("initramfs.cpio.gz"), b"initrd").unwrap(); - fs::create_dir_all(root.join("share").join("hidden")).unwrap(); - fs::create_dir(root.join("snapshot")).unwrap(); - let directory = root.to_str().unwrap(); - let arguments: Vec = arguments - .iter() - .map(|argument| argument.replace("{dir}", directory)) - .collect(); - let options = parse("openvmm", &arguments); - (temporary, options) - } - - /// The options of every run, before those of its boot or restore. - const RUN: [&str; 7] = [ - "--single-process", - "--machine", - "microvm", - "--processors", - "4", - "--hypervisor", - "kvm", - ]; - - fn run_with<'a>(extra: &[&'a str]) -> Vec<&'a str> { - RUN.iter().chain(extra).copied().collect() - } - - #[test] - fn runs_boot_or_restore_without_a_lifecycle() { - let boot = run_with(&[ - "--memory", - "128M", - "--memory-capacity", - "1024M", - "--kernel", - "{dir}/vmlinux", - "--initrd", - "{dir}/initramfs.cpio.gz", - "--cpu-profile", - "host", - "--mount", - "/data,{dir}/share,rw", - "--mount-deny", - "hidden", - ]); - let (temporary, options) = parse_run(&boot); - let options = options.unwrap(); - assert_eq!(options.lifecycle, Lifecycle::Run); - assert!(!options.sandbox); - assert_eq!(options.restore, None); - assert_eq!(options.exit_status, None); - assert_eq!( - options.args_dump, - temporary.path().join("fake-openvmm-.json") - ); - let restore = run_with(&[ - "--restore-snapshot", - "{dir}/snapshot", - "--restore-processors", - "2", - "--restore-memory", - "512M", - "--restore-ready-path", - "{dir}/ready.sock", - "--cmdline", - "fake_exit_status=3", - "--microvm-report", - "{dir}/share/report.json", - ]); - let (temporary, options) = parse_run(&restore); - let options = options.unwrap(); - let snapshot = temporary.path().join("snapshot"); - assert_eq!(options.restore.as_ref(), Some(&snapshot)); - assert_eq!(options.exit_status, Some(3)); - // A restore has no kernel, so the command line goes next to the snapshot. - assert_eq!( - options.args_dump, - temporary.path().join("fake-openvmm-share.json") - ); - // A restored NIC keeps the addressing that its snapshot saved, so a restore takes the - // network profile and policy without `--net`. - let networked = run_with(&[ - "--restore-snapshot", - "{dir}/snapshot", - "--network-profile", - "portable", - "--network-egress", - "deny", - "--network-egress-allow", - "10.0.0.1/32:tcp:443", - "--host-loopback", - "deny", - ]); - let (temporary, options) = parse_run(&networked); - let options = options.unwrap(); - assert_eq!(options.restore, Some(temporary.path().join("snapshot"))); - assert!(options.network.requested); - assert_eq!(options.network.mode, "rules"); - assert_eq!(options.network.allow, 1); - assert_eq!(options.network.host_loopback, "deny"); - // A restore that replaces the policy of a NIC template may publish the guest's listeners - // and forward host ports. - let replaced = run_with(&[ - "--restore-snapshot", - "{dir}/snapshot", - "--restore-network-policy", - "--network-profile", - "portable", - "--network-egress", - "allow", - "--network-ingress", - "allow", - "--host-loopback", - "allow", - "--host-loopback-forward", - "tcp:3000:8080", - ]); - let (_temporary, options) = parse_run(&replaced); - let options = options.unwrap(); - assert_eq!(options.network.mode, "allow-all"); - assert_eq!(options.network.host_loopback, "allow"); - } - - #[test] - fn runs_refuse_what_their_boot_or_restore_does_not_take() { - const KERNEL: [&str; 4] = [ - "--kernel", - "{dir}/vmlinux", - "--initrd", - "{dir}/initramfs.cpio.gz", - ]; - fn boot(extra: &[&'static str]) -> Vec<&'static str> { - let mut arguments = vec!["--memory", "128M"]; - arguments.extend(KERNEL); - arguments.extend(extra); - run_with(&arguments) - } - fn restore(extra: &[&'static str]) -> Vec<&'static str> { - let mut arguments = vec!["--restore-snapshot", "{dir}/snapshot"]; - arguments.extend(extra); - run_with(&arguments) - } - let kernel = KERNEL; - let cases: Vec<(Vec<&str>, &str)> = vec![ - ( - restore(&["--memory", "128M"]), - "a restore takes no --memory", - ), - (restore(&kernel), "a restore takes no --kernel"), - ( - restore(&["--restore-processors", "8"]), - "--restore-processors cannot exceed --processors", - ), - ( - restore(&["--restore-memory", "1G"]), - "--restore-memory must be given in MiB", - ), - ( - restore(&["--net", "10.0.0.2/24", "--network-profile", "portable"]), - "restore takes microVM network addressing from saved state", - ), - ( - restore(&["--network-profile", "open"]), - "--network-profile must be portable, not open", - ), - ( - boot(&["--network-profile", "portable"]), - "--network-profile portable requires --net or --restore-snapshot", - ), - ( - boot(&["--restore-network-policy"]), - "--restore-network-policy requires --restore-snapshot", - ), - ( - restore(&[ - "--network-profile", - "portable", - "--network-ingress", - "allow", - ]), - "microVM snapshots do not support --network-ingress allow, whose published guest \ - listeners are live host attachments, except at a restore with \ - --restore-network-policy", - ), - ( - restore(&[ - "--network-profile", - "portable", - "--host-loopback", - "allow", - "--host-loopback-forward", - "tcp:3000:8080", - ]), - "microVM snapshots do not support --host-loopback allow, whose published guest \ - listeners are live host attachments, except at a restore with \ - --restore-network-policy", - ), - ( - boot(&["--restore-processors", "2"]), - "--restore-processors requires --restore-snapshot", - ), - ( - boot(&["--memory-capacity", "2"]), - "--memory-capacity must be given in MiB", - ), - ( - boot(&["--cpu-profile", "host", "--cpu-profile", "auto"]), - "--cpu-profile must be given at most once", - ), - ( - boot(&["--microvm-workload-identity", "1000:1000"]), - "a microVM run takes no --microvm-workload-identity", - ), - ( - boot(&["--virtio-console", "none"]), - "a microVM run takes no --virtio-console", - ), - ( - boot(&["--mount", "/data,{dir}/share,ro", "--mount-deny", "missing"]), - "invalid --mount-deny missing", - ), - ( - boot(&["--mount-allow", "hidden"]), - "invalid --mount-allow hidden", - ), - ]; - for (arguments, message) in cases { - let (_temporary, options) = parse_run(&arguments); - assert_eq!(options.err().as_deref(), Some(message), "{arguments:?}"); - } - let mut missing = RUN.to_vec(); - missing.truncate(3); - missing.extend(["--hypervisor", "kvm", "--memory", "128M"]); - let (_temporary, options) = parse_run(&missing); - assert_eq!( - options.err().as_deref(), - Some("--processors must be given exactly once") - ); - } - - #[test] - fn launches_with_a_lifecycle_take_no_options_of_a_run() { - for option in ["--processors", "--cpu-profile", "--restore-snapshot"] { - let arguments = [ - "--single-process", - "--microvm-lifecycle", - "managed", - option, - "1", - ]; - let (_temporary, options) = parse_run(&arguments); - assert_eq!( - options.err(), - Some(format!("unsupported argument {option}")), - "{option}" - ); - } - } - - /// The command line of a template's capture, with `{dir}` in place of the directory of - /// [`parse_capture`]. - const CAPTURE: &[&str] = &[ - "--machine", - "microvm", - "--microvm-sandbox-block", - "distro:file:{dir}/placeholder,ro", - "--microvm-sandbox-block", - "scratch:file:{dir}/transaction/scratch.raw", - "--processors", - "2", - "--memory", - "512M", - "--memory-capacity", - "2048M", - "--snapshot-destination", - "{dir}/transaction/snapshot", - "--snapshot-tier", - "platform", - "--snapshot-block-identity", - "generation", - "--snapshot-generation-id", - "0123456789abcdef0123456789ABCDEF", - "--single-process", - "--hypervisor", - "kvm", - "--cpu-profile", - "auto", - "--kernel", - "{dir}/vmlinux", - "--initrd", - "{dir}/initramfs.cpio.gz", - "--cmdline", - "nvx_sandbox=1", - "--virtio-console", - "none", - "--microvm-control-console", - "listen={dir}/transaction/control.sock", - "--microvm-control-auth-stdin", - "--microvm-report", - "{dir}/transaction/outcome.json", - ]; - - /// Returns a directory with a kernel, an initramfs, a placeholder, and a transaction with a - /// scratch disk, the directory and the transaction private to the current user, as the - /// directory of a control console's socket must be, and the parse of the command line that - /// `arguments` gives with the path of that directory in place of `{dir}`. - fn parse_capture(arguments: &[&str]) -> (tempfile::TempDir, Result) { - parse_capture_in(arguments, |_| {}) - } - - /// Returns the directory of [`parse_capture`], and the parse of `arguments` there once - /// `prepare` has changed the directory. - fn parse_capture_in( - arguments: &[&str], - prepare: impl FnOnce(&Path), - ) -> (tempfile::TempDir, Result) { - let temporary = tempfile::tempdir().unwrap(); - let root = temporary.path(); - fs::write(root.join("vmlinux"), b"kernel").unwrap(); - fs::write(root.join("initramfs.cpio.gz"), b"initrd").unwrap(); - fs::write(root.join("placeholder"), [0; 512]).unwrap(); - fs::create_dir(root.join("transaction")).unwrap(); - fs::write(root.join("transaction").join("scratch.raw"), [0; 512]).unwrap(); - #[cfg(unix)] - for directory in [root.to_owned(), root.join("transaction")] { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap(); - } - prepare(root); - let directory = root.to_str().unwrap(); - let arguments: Vec = arguments - .iter() - .map(|argument| argument.replace("{dir}", directory)) - .collect(); - let options = parse("openvmm", &arguments); - (temporary, options) - } - - /// Returns the command line of [`CAPTURE`] with `value` in place of the value of `option`. - fn capture_with(option: &str, value: &'static str) -> Vec<&'static str> { - let mut arguments = CAPTURE.to_vec(); - let at = arguments.iter().position(|given| *given == option).unwrap(); - arguments[at + 1] = value; - arguments - } - - #[test] - fn captures_boot_their_template_cold_on_their_block_devices() { - let (temporary, options) = parse_capture(CAPTURE); - let options = options.unwrap(); - let root = temporary.path(); - assert_eq!(options.lifecycle, Lifecycle::Capture); - assert!(options.sandbox); - assert_eq!(options.restore, None); - let blocks: Vec<_> = options - .blocks - .iter() - .map(|block| (block.role.as_str(), block.path.clone(), block.read_only)) - .collect(); - assert_eq!( - blocks, - [ - ("distro", root.join("placeholder"), true), - ( - "scratch", - root.join("transaction").join("scratch.raw"), - false - ), - ] - ); - let capture = options.capture.as_ref().unwrap(); - assert_eq!( - capture.destination, - root.join("transaction").join("snapshot") - ); - assert_eq!(capture.memory, 512 * MIB); - assert_eq!(capture.scenario, root.join(CAPTURE_SCENARIO_NAME)); - assert_eq!( - options.endpoint, - format!("{}/transaction/control.sock", root.to_str().unwrap()) - ); - assert_eq!( - options.blocks_dump, - root.join("fake-openvmm-transaction-blocks.json") - ); - assert!(options.workload.is_empty()); - assert!(options.children.is_empty()); - } - - #[test] - fn captures_may_limit_the_processors_online_at_boot() { - // The capture of `CAPTURE` has 2 processors. - for command_line in ["nvx_sandbox=1 maxcpus=1", "nvx_sandbox=1 maxcpus=2"] { - let (_temporary, options) = parse_capture(&capture_with("--cmdline", command_line)); - assert_eq!(options.err(), None, "{command_line}"); - } - } - - #[cfg(unix)] - #[test] - fn captures_listen_in_the_directory_of_their_snapshot_destination() { - let (temporary, options) = parse_capture(&capture_with( - "--microvm-control-console", - "listen={dir}/control.sock", - )); - let namespace = fs::canonicalize(temporary.path().join("transaction")).unwrap(); - assert_eq!( - options.err(), - Some(format!( - "microVM console socket must be inside the snapshot parent namespace {}", - namespace.display() - )) - ); - } - - #[cfg(unix)] - #[test] - fn control_consoles_listen_in_a_private_directory_of_their_user() { - use std::os::unix::fs::{PermissionsExt, symlink}; - - let refusal = "microVM control endpoint parent must be a non-symlink directory owned by \ - OpenVMM with mode 0700"; - // OpenVMM takes exactly the mode 0700. - for mode in [0o750, 0o701, 0o1700] { - let (_temporary, options) = parse_capture_in(CAPTURE, |root| { - let transaction = root.join("transaction"); - fs::set_permissions(transaction, fs::Permissions::from_mode(mode)).unwrap(); - }); - assert_eq!(options.err().as_deref(), Some(refusal), "{mode:o}"); - } - // It follows no link to the socket's directory, even to a private one. - let (_temporary, options) = parse_capture_in( - &capture_with( - "--microvm-control-console", - "listen={dir}/link/control.sock", - ), - |root| symlink(root.join("transaction"), root.join("link")).unwrap(), - ); - assert_eq!(options.err().as_deref(), Some(refusal)); - let (temporary, options) = parse_capture(&capture_with( - "--microvm-control-console", - "listen={dir}/missing/control.sock", - )); - let missing = format!( - "failed to inspect microVM control endpoint parent {}: ", - temporary.path().join("missing").display() - ); - let error = options.err().unwrap(); - assert!(error.starts_with(&missing), "{error}"); - } - - #[cfg(unix)] - #[test] - fn a_restore_listens_in_the_directory_of_the_snapshot_that_it_restores() { - use std::os::unix::fs::PermissionsExt; - - let temporary = tempfile::tempdir().unwrap(); - let (clone, generation) = ( - temporary.path().join("clone"), - temporary.path().join("generation"), - ); - for directory in [&clone, &generation] { - fs::create_dir(directory).unwrap(); - fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap(); - } - let endpoint = clone.join("control.sock"); - let endpoint = endpoint.to_str().unwrap(); - assert_eq!( - check_control_console(endpoint, Some(&clone.join("snapshot"))), - Ok(()) - ); - // A VM that restores a snapshot elsewhere cannot listen in its own directory. - assert_eq!( - check_control_console(endpoint, Some(&generation.join("snapshot"))), - Err(format!( - "microVM console socket must be inside the snapshot parent namespace {}", - fs::canonicalize(&generation).unwrap().display() - )) - ); - // Without a snapshot, the socket's directory alone counts. - assert_eq!(check_control_console(endpoint, None), Ok(())); - } - - #[test] - fn captures_refuse_what_a_template_does_not_take() { - let mut lifecycle = CAPTURE.to_vec(); - lifecycle.extend(["--microvm-lifecycle", "managed"]); - let mut runtime = CAPTURE.to_vec(); - runtime.extend([ - "--microvm-sandbox-block", - "runtime:file:{dir}/placeholder,ro", - ]); - let mut aggregate = CAPTURE.to_vec(); - aggregate.extend(["--mount-aggregate", "/run/nvx/shares"]); - let mut identity = CAPTURE.to_vec(); - identity.extend(["--microvm-workload-identity", "1000:1000"]); - let mut unbounded = CAPTURE.to_vec(); - let at = unbounded - .iter() - .position(|given| *given == "--memory-capacity") - .unwrap(); - unbounded.drain(at..at + 2); - let mut without_blocks = CAPTURE.to_vec(); - without_blocks.drain(2..6); - let invalid_generation = "invalid --snapshot-generation-id"; - let capacity = "--memory-capacity must be a multiple of 128 MiB no smaller than --memory"; - let cases: Vec<(Vec<&str>, String)> = - vec![ - ( - lifecycle, - "a capture takes no --microvm-lifecycle".to_owned(), - ), - ( - runtime, - "a capture takes a distro layer and a scratch disk".to_owned(), - ), - (aggregate, "a capture takes no --mount-aggregate".to_owned()), - ( - identity, - "a capture takes no --microvm-workload-identity".to_owned(), - ), - ( - unbounded, - "--memory-capacity must be given exactly once".to_owned(), - ), - ( - without_blocks, - "a capture takes sandbox block devices".to_owned(), - ), - ( - capture_with("--memory-capacity", "2000M"), - capacity.to_owned(), - ), - (capture_with("--memory-capacity", "256M"), capacity.to_owned()), - ( - capture_with("--snapshot-tier", "process"), - "--snapshot-tier must be platform, not process".to_owned(), - ), - ( - capture_with("--snapshot-block-identity", "path"), - "--snapshot-block-identity must be generation, not path".to_owned(), - ), - ( - capture_with("--snapshot-generation-id", "00000000000000000000000000000000"), - format!("{invalid_generation} 00000000000000000000000000000000"), - ), - ( - capture_with("--snapshot-generation-id", "0123456789abcdef0123456789abcde"), - format!("{invalid_generation} 0123456789abcdef0123456789abcde"), - ), - ( - capture_with("--snapshot-generation-id", "0123456789abcdef0123456789abcdeg"), - format!("{invalid_generation} 0123456789abcdef0123456789abcdeg"), - ), - ( - capture_with("--cmdline", "nvx_sandbox=1 nvx_hostname=tenant"), - CAPTURE_COMMAND_LINE.to_owned(), - ), - // OpenVMM records a limit of the processors online at boot in its canonical form - // alone, of a count that a microVM supports, and at most its processors. - ( - capture_with("--cmdline", "nvx_sandbox=1 maxcpus=01"), - CAPTURE_COMMAND_LINE.to_owned(), - ), - ( - capture_with("--cmdline", "nvx_sandbox=1 maxcpus=3"), - CAPTURE_COMMAND_LINE.to_owned(), - ), - ( - capture_with("--cmdline", "nvx_sandbox=1 maxcpus=4"), - CAPTURE_COMMAND_LINE.to_owned(), - ), - ( - capture_with("--cmdline", "nvx_sandbox=1 maxcpus=1 maxcpus=1"), - CAPTURE_COMMAND_LINE.to_owned(), - ), - ( - capture_with("--snapshot-destination", "{dir}/transaction"), - "the snapshot destination {dir}/transaction exists".to_owned(), - ), - ( - capture_with("--snapshot-destination", "{dir}/missing/snapshot"), - "the directory of the snapshot destination {dir}/missing/snapshot does not exist" - .to_owned(), - ), - ( - capture_with("--virtio-console", "stdio"), - "--virtio-console must be none, not stdio".to_owned(), - ), - ( - capture_with("--microvm-control-console", "listen="), - "--microvm-control-console must name its endpoint after listen=".to_owned(), - ), - ]; - for (arguments, message) in cases { - let (temporary, options) = parse_capture(&arguments); - let message = message.replace("{dir}", temporary.path().to_str().unwrap()); - assert_eq!(options.err(), Some(message), "{arguments:?}"); - } - } - - #[test] - fn capture_scenarios_take_defaults_and_refuse_unknown_fields() { - let scenario: Scenario = serde_json::from_str(r#"{"manifest": "manifest.bin"}"#).unwrap(); - assert_eq!(scenario.manifest, Path::new("manifest.bin")); - assert_eq!(scenario.state_len, 0); - assert_eq!(scenario.outcome, CaptureOutcome::Publish); - assert_eq!(scenario.status, 1); - assert_eq!(scenario.active, None); - assert_eq!(scenario.delay_ms, 0); - assert!(!scenario.keep_memory); - let scenario: Scenario = serde_json::from_str( - r#"{"manifest": "m", "stateLen": 512, "outcome": "publish-then-hang", "status": 3, - "active": "a", "delayMs": 5, "keepMemory": true}"#, - ) - .unwrap(); - assert_eq!( - ( - scenario.state_len, - scenario.outcome, - scenario.status, - scenario.delay_ms, - scenario.keep_memory - ), - (512, CaptureOutcome::PublishThenHang, 3, 5, true) - ); - assert_eq!(scenario.active.as_deref(), Some(Path::new("a"))); - for refused in [ - r#"{}"#, - r#"{"manifest": "m", "outcome": "succeed"}"#, - r#"{"manifest": "m", "memory": 1}"#, - ] { - assert!( - serde_json::from_str::(refused).is_err(), - "{refused}" - ); - } - } -} +mod tests; diff --git a/nvx-rs/src/testing/fake_openvmm/tests.rs b/nvx-rs/src/testing/fake_openvmm/tests.rs new file mode 100644 index 000000000..233ec9de9 --- /dev/null +++ b/nvx-rs/src/testing/fake_openvmm/tests.rs @@ -0,0 +1,714 @@ +use super::*; + +#[test] +fn shells_raise_shlvl_like_busybox() { + let level = |value: &str| { + let mut environment = vec![("SHLVL".to_owned(), value.to_owned())]; + start_shell(&mut environment, "/work"); + assert_eq!(environment[1], ("PWD".to_owned(), "/work".to_owned())); + environment.swap_remove(0).1 + }; + assert_eq!(level("1"), "2"); + assert_eq!(level("7x"), "8"); + assert_eq!(level(" +3"), "4"); + assert_eq!(level("nothing"), "1"); + assert_eq!(level("4294967295"), "0"); + assert_eq!(level("-1"), "0"); + assert_eq!(level("-3"), "4294967294"); + let mut fresh = Environment::new(); + start_shell(&mut fresh, "/"); + assert_eq!(fresh[0], ("SHLVL".to_owned(), "1".to_owned())); +} + +#[test] +fn the_current_guest_advertises_every_required_feature() { + assert_eq!(GUEST_FEATURES, GuestFeatures::REQUIRED); + assert!(GUEST_FEATURES.missing(GuestFeatures::REQUIRED).is_empty()); +} + +#[test] +fn mount_children_resolve_to_hosts_of_their_kind() { + let temporary = tempfile::tempdir().unwrap(); + let directory = temporary.path().to_str().unwrap().to_owned(); + let file = temporary.path().join("file").to_str().unwrap().to_owned(); + fs::write(&file, b"").unwrap(); + for (value, index, host) in [ + (format!("0,{directory},rw"), Some(0), &directory), + (format!("1,{file},ro,file"), Some(1), &file), + // Without an index, any name goes, as for the children of a sandbox's aggregate. + (format!("digest,{directory},ro"), None, &directory), + ] { + assert_eq!(mount_child_host(&value, index), Ok(PathBuf::from(host))); + } + for (value, index) in [ + (format!("1,{directory},rw"), Some(0)), + (format!("0,{file},rw"), None), + (format!("0,{directory},ro,file"), None), + (format!("0,{directory}-missing,rw"), None), + (format!("0,{directory},wo"), None), + (format!("0,{directory}"), None), + ("0".to_owned(), None), + ] { + assert_eq!( + mount_child_host(&value, index), + Err(format!("invalid --mount-child {value}")) + ); + } +} + +/// Returns a directory with a kernel, an initramfs, a share with a `hidden` directory, and a +/// snapshot directory, and the parse of the command line that `arguments` gives with the +/// paths of that directory in place of `{dir}`. +fn parse_run(arguments: &[&str]) -> (tempfile::TempDir, Result) { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path(); + fs::write(root.join("vmlinux"), b"kernel").unwrap(); + fs::write(root.join("initramfs.cpio.gz"), b"initrd").unwrap(); + fs::create_dir_all(root.join("share").join("hidden")).unwrap(); + fs::create_dir(root.join("snapshot")).unwrap(); + let directory = root.to_str().unwrap(); + let arguments: Vec = arguments + .iter() + .map(|argument| argument.replace("{dir}", directory)) + .collect(); + let options = parse("openvmm", &arguments); + (temporary, options) +} + +/// The options of every run, before those of its boot or restore. +const RUN: [&str; 7] = [ + "--single-process", + "--machine", + "microvm", + "--processors", + "4", + "--hypervisor", + "kvm", +]; + +fn run_with<'a>(extra: &[&'a str]) -> Vec<&'a str> { + RUN.iter().chain(extra).copied().collect() +} + +#[test] +fn runs_boot_or_restore_without_a_lifecycle() { + let boot = run_with(&[ + "--memory", + "128M", + "--memory-capacity", + "1024M", + "--kernel", + "{dir}/vmlinux", + "--initrd", + "{dir}/initramfs.cpio.gz", + "--cpu-profile", + "host", + "--mount", + "/data,{dir}/share,rw", + "--mount-deny", + "hidden", + ]); + let (temporary, options) = parse_run(&boot); + let options = options.unwrap(); + assert_eq!(options.lifecycle, Lifecycle::Run); + assert!(!options.sandbox); + assert_eq!(options.restore, None); + assert_eq!(options.exit_status, None); + assert_eq!( + options.args_dump, + temporary.path().join("fake-openvmm-.json") + ); + let restore = run_with(&[ + "--restore-snapshot", + "{dir}/snapshot", + "--restore-processors", + "2", + "--restore-memory", + "512M", + "--restore-ready-path", + "{dir}/ready.sock", + "--cmdline", + "fake_exit_status=3", + "--microvm-report", + "{dir}/share/report.json", + ]); + let (temporary, options) = parse_run(&restore); + let options = options.unwrap(); + let snapshot = temporary.path().join("snapshot"); + assert_eq!(options.restore.as_ref(), Some(&snapshot)); + assert_eq!(options.exit_status, Some(3)); + // A restore has no kernel, so the command line goes next to the snapshot. + assert_eq!( + options.args_dump, + temporary.path().join("fake-openvmm-share.json") + ); + // A restored NIC keeps the addressing that its snapshot saved, so a restore takes the + // network profile and policy without `--net`. + let networked = run_with(&[ + "--restore-snapshot", + "{dir}/snapshot", + "--network-profile", + "portable", + "--network-egress", + "deny", + "--network-egress-allow", + "10.0.0.1/32:tcp:443", + "--host-loopback", + "deny", + ]); + let (temporary, options) = parse_run(&networked); + let options = options.unwrap(); + assert_eq!(options.restore, Some(temporary.path().join("snapshot"))); + assert!(options.network.requested); + assert_eq!(options.network.mode, "rules"); + assert_eq!(options.network.allow, 1); + assert_eq!(options.network.host_loopback, "deny"); + // A restore that replaces the policy of a NIC template may publish the guest's listeners + // and forward host ports. + let replaced = run_with(&[ + "--restore-snapshot", + "{dir}/snapshot", + "--restore-network-policy", + "--network-profile", + "portable", + "--network-egress", + "allow", + "--network-ingress", + "allow", + "--host-loopback", + "allow", + "--host-loopback-forward", + "tcp:3000:8080", + ]); + let (_temporary, options) = parse_run(&replaced); + let options = options.unwrap(); + assert_eq!(options.network.mode, "allow-all"); + assert_eq!(options.network.host_loopback, "allow"); +} + +#[test] +fn runs_refuse_what_their_boot_or_restore_does_not_take() { + const KERNEL: [&str; 4] = [ + "--kernel", + "{dir}/vmlinux", + "--initrd", + "{dir}/initramfs.cpio.gz", + ]; + fn boot(extra: &[&'static str]) -> Vec<&'static str> { + let mut arguments = vec!["--memory", "128M"]; + arguments.extend(KERNEL); + arguments.extend(extra); + run_with(&arguments) + } + fn restore(extra: &[&'static str]) -> Vec<&'static str> { + let mut arguments = vec!["--restore-snapshot", "{dir}/snapshot"]; + arguments.extend(extra); + run_with(&arguments) + } + let kernel = KERNEL; + let cases: Vec<(Vec<&str>, &str)> = vec![ + ( + restore(&["--memory", "128M"]), + "a restore takes no --memory", + ), + (restore(&kernel), "a restore takes no --kernel"), + ( + restore(&["--restore-processors", "8"]), + "--restore-processors cannot exceed --processors", + ), + ( + restore(&["--restore-memory", "1G"]), + "--restore-memory must be given in MiB", + ), + ( + restore(&["--net", "10.0.0.2/24", "--network-profile", "portable"]), + "restore takes microVM network addressing from saved state", + ), + ( + restore(&["--network-profile", "open"]), + "--network-profile must be portable, not open", + ), + ( + boot(&["--network-profile", "portable"]), + "--network-profile portable requires --net or --restore-snapshot", + ), + ( + boot(&["--restore-network-policy"]), + "--restore-network-policy requires --restore-snapshot", + ), + ( + restore(&[ + "--network-profile", + "portable", + "--network-ingress", + "allow", + ]), + "microVM snapshots do not support --network-ingress allow, whose published guest \ + listeners are live host attachments, except at a restore with \ + --restore-network-policy", + ), + ( + restore(&[ + "--network-profile", + "portable", + "--host-loopback", + "allow", + "--host-loopback-forward", + "tcp:3000:8080", + ]), + "microVM snapshots do not support --host-loopback allow, whose published guest \ + listeners are live host attachments, except at a restore with \ + --restore-network-policy", + ), + ( + boot(&["--restore-processors", "2"]), + "--restore-processors requires --restore-snapshot", + ), + ( + boot(&["--memory-capacity", "2"]), + "--memory-capacity must be given in MiB", + ), + ( + boot(&["--cpu-profile", "host", "--cpu-profile", "auto"]), + "--cpu-profile must be given at most once", + ), + ( + boot(&["--microvm-workload-identity", "1000:1000"]), + "a microVM run takes no --microvm-workload-identity", + ), + ( + boot(&["--virtio-console", "none"]), + "a microVM run takes no --virtio-console", + ), + ( + boot(&["--mount", "/data,{dir}/share,ro", "--mount-deny", "missing"]), + "invalid --mount-deny missing", + ), + ( + boot(&["--mount-allow", "hidden"]), + "invalid --mount-allow hidden", + ), + ]; + for (arguments, message) in cases { + let (_temporary, options) = parse_run(&arguments); + assert_eq!(options.err().as_deref(), Some(message), "{arguments:?}"); + } + let mut missing = RUN.to_vec(); + missing.truncate(3); + missing.extend(["--hypervisor", "kvm", "--memory", "128M"]); + let (_temporary, options) = parse_run(&missing); + assert_eq!( + options.err().as_deref(), + Some("--processors must be given exactly once") + ); +} + +#[test] +fn launches_with_a_lifecycle_take_no_options_of_a_run() { + for option in ["--processors", "--cpu-profile", "--restore-snapshot"] { + let arguments = [ + "--single-process", + "--microvm-lifecycle", + "managed", + option, + "1", + ]; + let (_temporary, options) = parse_run(&arguments); + assert_eq!( + options.err(), + Some(format!("unsupported argument {option}")), + "{option}" + ); + } +} + +/// The command line of a template's capture, with `{dir}` in place of the directory of +/// [`parse_capture`]. +const CAPTURE: &[&str] = &[ + "--machine", + "microvm", + "--microvm-sandbox-block", + "distro:file:{dir}/placeholder,ro", + "--microvm-sandbox-block", + "scratch:file:{dir}/transaction/scratch.raw", + "--processors", + "2", + "--memory", + "512M", + "--memory-capacity", + "2048M", + "--snapshot-destination", + "{dir}/transaction/snapshot", + "--snapshot-tier", + "platform", + "--snapshot-block-identity", + "generation", + "--snapshot-generation-id", + "0123456789abcdef0123456789ABCDEF", + "--single-process", + "--hypervisor", + "kvm", + "--cpu-profile", + "auto", + "--kernel", + "{dir}/vmlinux", + "--initrd", + "{dir}/initramfs.cpio.gz", + "--cmdline", + "nvx_sandbox=1", + "--virtio-console", + "none", + "--microvm-control-console", + "listen={dir}/transaction/control.sock", + "--microvm-control-auth-stdin", + "--microvm-report", + "{dir}/transaction/outcome.json", +]; + +/// Returns a directory with a kernel, an initramfs, a placeholder, and a transaction with a +/// scratch disk, the directory and the transaction private to the current user, as the +/// directory of a control console's socket must be, and the parse of the command line that +/// `arguments` gives with the path of that directory in place of `{dir}`. +fn parse_capture(arguments: &[&str]) -> (tempfile::TempDir, Result) { + parse_capture_in(arguments, |_| {}) +} + +/// Returns the directory of [`parse_capture`], and the parse of `arguments` there once +/// `prepare` has changed the directory. +fn parse_capture_in( + arguments: &[&str], + prepare: impl FnOnce(&Path), +) -> (tempfile::TempDir, Result) { + let temporary = tempfile::tempdir().unwrap(); + let root = temporary.path(); + fs::write(root.join("vmlinux"), b"kernel").unwrap(); + fs::write(root.join("initramfs.cpio.gz"), b"initrd").unwrap(); + fs::write(root.join("placeholder"), [0; 512]).unwrap(); + fs::create_dir(root.join("transaction")).unwrap(); + fs::write(root.join("transaction").join("scratch.raw"), [0; 512]).unwrap(); + #[cfg(unix)] + for directory in [root.to_owned(), root.join("transaction")] { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap(); + } + prepare(root); + let directory = root.to_str().unwrap(); + let arguments: Vec = arguments + .iter() + .map(|argument| argument.replace("{dir}", directory)) + .collect(); + let options = parse("openvmm", &arguments); + (temporary, options) +} + +/// Returns the command line of [`CAPTURE`] with `value` in place of the value of `option`. +fn capture_with(option: &str, value: &'static str) -> Vec<&'static str> { + let mut arguments = CAPTURE.to_vec(); + let at = arguments.iter().position(|given| *given == option).unwrap(); + arguments[at + 1] = value; + arguments +} + +#[test] +fn captures_boot_their_template_cold_on_their_block_devices() { + let (temporary, options) = parse_capture(CAPTURE); + let options = options.unwrap(); + let root = temporary.path(); + assert_eq!(options.lifecycle, Lifecycle::Capture); + assert!(options.sandbox); + assert_eq!(options.restore, None); + let blocks: Vec<_> = options + .blocks + .iter() + .map(|block| (block.role.as_str(), block.path.clone(), block.read_only)) + .collect(); + assert_eq!( + blocks, + [ + ("distro", root.join("placeholder"), true), + ( + "scratch", + root.join("transaction").join("scratch.raw"), + false + ), + ] + ); + let capture = options.capture.as_ref().unwrap(); + assert_eq!( + capture.destination, + root.join("transaction").join("snapshot") + ); + assert_eq!(capture.memory, 512 * MIB); + assert_eq!(capture.scenario, root.join(CAPTURE_SCENARIO_NAME)); + assert_eq!( + options.endpoint, + format!("{}/transaction/control.sock", root.to_str().unwrap()) + ); + assert_eq!( + options.blocks_dump, + root.join("fake-openvmm-transaction-blocks.json") + ); + assert!(options.workload.is_empty()); + assert!(options.children.is_empty()); +} + +#[test] +fn captures_may_limit_the_processors_online_at_boot() { + // The capture of `CAPTURE` has 2 processors. + for command_line in ["nvx_sandbox=1 maxcpus=1", "nvx_sandbox=1 maxcpus=2"] { + let (_temporary, options) = parse_capture(&capture_with("--cmdline", command_line)); + assert_eq!(options.err(), None, "{command_line}"); + } +} + +#[cfg(unix)] +#[test] +fn captures_listen_in_the_directory_of_their_snapshot_destination() { + let (temporary, options) = parse_capture(&capture_with( + "--microvm-control-console", + "listen={dir}/control.sock", + )); + let namespace = fs::canonicalize(temporary.path().join("transaction")).unwrap(); + assert_eq!( + options.err(), + Some(format!( + "microVM console socket must be inside the snapshot parent namespace {}", + namespace.display() + )) + ); +} + +#[cfg(unix)] +#[test] +fn control_consoles_listen_in_a_private_directory_of_their_user() { + use std::os::unix::fs::{PermissionsExt, symlink}; + + let refusal = "microVM control endpoint parent must be a non-symlink directory owned by \ + OpenVMM with mode 0700"; + // OpenVMM takes exactly the mode 0700. + for mode in [0o750, 0o701, 0o1700] { + let (_temporary, options) = parse_capture_in(CAPTURE, |root| { + let transaction = root.join("transaction"); + fs::set_permissions(transaction, fs::Permissions::from_mode(mode)).unwrap(); + }); + assert_eq!(options.err().as_deref(), Some(refusal), "{mode:o}"); + } + // It follows no link to the socket's directory, even to a private one. + let (_temporary, options) = parse_capture_in( + &capture_with( + "--microvm-control-console", + "listen={dir}/link/control.sock", + ), + |root| symlink(root.join("transaction"), root.join("link")).unwrap(), + ); + assert_eq!(options.err().as_deref(), Some(refusal)); + let (temporary, options) = parse_capture(&capture_with( + "--microvm-control-console", + "listen={dir}/missing/control.sock", + )); + let missing = format!( + "failed to inspect microVM control endpoint parent {}: ", + temporary.path().join("missing").display() + ); + let error = options.err().unwrap(); + assert!(error.starts_with(&missing), "{error}"); +} + +#[cfg(unix)] +#[test] +fn a_restore_listens_in_the_directory_of_the_snapshot_that_it_restores() { + use std::os::unix::fs::PermissionsExt; + + let temporary = tempfile::tempdir().unwrap(); + let (clone, generation) = ( + temporary.path().join("clone"), + temporary.path().join("generation"), + ); + for directory in [&clone, &generation] { + fs::create_dir(directory).unwrap(); + fs::set_permissions(directory, fs::Permissions::from_mode(0o700)).unwrap(); + } + let endpoint = clone.join("control.sock"); + let endpoint = endpoint.to_str().unwrap(); + assert_eq!( + check_control_console(endpoint, Some(&clone.join("snapshot"))), + Ok(()) + ); + // A VM that restores a snapshot elsewhere cannot listen in its own directory. + assert_eq!( + check_control_console(endpoint, Some(&generation.join("snapshot"))), + Err(format!( + "microVM console socket must be inside the snapshot parent namespace {}", + fs::canonicalize(&generation).unwrap().display() + )) + ); + // Without a snapshot, the socket's directory alone counts. + assert_eq!(check_control_console(endpoint, None), Ok(())); +} + +#[test] +fn captures_refuse_what_a_template_does_not_take() { + let mut lifecycle = CAPTURE.to_vec(); + lifecycle.extend(["--microvm-lifecycle", "managed"]); + let mut runtime = CAPTURE.to_vec(); + runtime.extend([ + "--microvm-sandbox-block", + "runtime:file:{dir}/placeholder,ro", + ]); + let mut aggregate = CAPTURE.to_vec(); + aggregate.extend(["--mount-aggregate", "/run/nvx/shares"]); + let mut identity = CAPTURE.to_vec(); + identity.extend(["--microvm-workload-identity", "1000:1000"]); + let mut unbounded = CAPTURE.to_vec(); + let at = unbounded + .iter() + .position(|given| *given == "--memory-capacity") + .unwrap(); + unbounded.drain(at..at + 2); + let mut without_blocks = CAPTURE.to_vec(); + without_blocks.drain(2..6); + let invalid_generation = "invalid --snapshot-generation-id"; + let capacity = "--memory-capacity must be a multiple of 128 MiB no smaller than --memory"; + let cases: Vec<(Vec<&str>, String)> = vec![ + ( + lifecycle, + "a capture takes no --microvm-lifecycle".to_owned(), + ), + ( + runtime, + "a capture takes a distro layer and a scratch disk".to_owned(), + ), + (aggregate, "a capture takes no --mount-aggregate".to_owned()), + ( + identity, + "a capture takes no --microvm-workload-identity".to_owned(), + ), + ( + unbounded, + "--memory-capacity must be given exactly once".to_owned(), + ), + ( + without_blocks, + "a capture takes sandbox block devices".to_owned(), + ), + ( + capture_with("--memory-capacity", "2000M"), + capacity.to_owned(), + ), + ( + capture_with("--memory-capacity", "256M"), + capacity.to_owned(), + ), + ( + capture_with("--snapshot-tier", "process"), + "--snapshot-tier must be platform, not process".to_owned(), + ), + ( + capture_with("--snapshot-block-identity", "path"), + "--snapshot-block-identity must be generation, not path".to_owned(), + ), + ( + capture_with( + "--snapshot-generation-id", + "00000000000000000000000000000000", + ), + format!("{invalid_generation} 00000000000000000000000000000000"), + ), + ( + capture_with( + "--snapshot-generation-id", + "0123456789abcdef0123456789abcde", + ), + format!("{invalid_generation} 0123456789abcdef0123456789abcde"), + ), + ( + capture_with( + "--snapshot-generation-id", + "0123456789abcdef0123456789abcdeg", + ), + format!("{invalid_generation} 0123456789abcdef0123456789abcdeg"), + ), + ( + capture_with("--cmdline", "nvx_sandbox=1 nvx_hostname=tenant"), + CAPTURE_COMMAND_LINE.to_owned(), + ), + // OpenVMM records a limit of the processors online at boot in its canonical form + // alone, of a count that a microVM supports, and at most its processors. + ( + capture_with("--cmdline", "nvx_sandbox=1 maxcpus=01"), + CAPTURE_COMMAND_LINE.to_owned(), + ), + ( + capture_with("--cmdline", "nvx_sandbox=1 maxcpus=3"), + CAPTURE_COMMAND_LINE.to_owned(), + ), + ( + capture_with("--cmdline", "nvx_sandbox=1 maxcpus=4"), + CAPTURE_COMMAND_LINE.to_owned(), + ), + ( + capture_with("--cmdline", "nvx_sandbox=1 maxcpus=1 maxcpus=1"), + CAPTURE_COMMAND_LINE.to_owned(), + ), + ( + capture_with("--snapshot-destination", "{dir}/transaction"), + "the snapshot destination {dir}/transaction exists".to_owned(), + ), + ( + capture_with("--snapshot-destination", "{dir}/missing/snapshot"), + "the directory of the snapshot destination {dir}/missing/snapshot does not exist" + .to_owned(), + ), + ( + capture_with("--virtio-console", "stdio"), + "--virtio-console must be none, not stdio".to_owned(), + ), + ( + capture_with("--microvm-control-console", "listen="), + "--microvm-control-console must name its endpoint after listen=".to_owned(), + ), + ]; + for (arguments, message) in cases { + let (temporary, options) = parse_capture(&arguments); + let message = message.replace("{dir}", temporary.path().to_str().unwrap()); + assert_eq!(options.err(), Some(message), "{arguments:?}"); + } +} + +#[test] +fn capture_scenarios_take_defaults_and_refuse_unknown_fields() { + let scenario: Scenario = serde_json::from_str(r#"{"manifest": "manifest.bin"}"#).unwrap(); + assert_eq!(scenario.manifest, Path::new("manifest.bin")); + assert_eq!(scenario.state_len, 0); + assert_eq!(scenario.outcome, CaptureOutcome::Publish); + assert_eq!(scenario.status, 1); + assert_eq!(scenario.active, None); + assert_eq!(scenario.delay_ms, 0); + assert!(!scenario.keep_memory); + let scenario: Scenario = serde_json::from_str( + r#"{"manifest": "m", "stateLen": 512, "outcome": "publish-then-hang", "status": 3, + "active": "a", "delayMs": 5, "keepMemory": true}"#, + ) + .unwrap(); + assert_eq!( + ( + scenario.state_len, + scenario.outcome, + scenario.status, + scenario.delay_ms, + scenario.keep_memory + ), + (512, CaptureOutcome::PublishThenHang, 3, 5, true) + ); + assert_eq!(scenario.active.as_deref(), Some(Path::new("a"))); + for refused in [ + r#"{}"#, + r#"{"manifest": "m", "outcome": "succeed"}"#, + r#"{"manifest": "m", "memory": 1}"#, + ] { + assert!( + serde_json::from_str::(refused).is_err(), + "{refused}" + ); + } +} diff --git a/nvx-rs/src/uuid.rs b/nvx-rs/src/uuid.rs index 993aeaeb1..643e353e0 100644 --- a/nvx-rs/src/uuid.rs +++ b/nvx-rs/src/uuid.rs @@ -135,98 +135,4 @@ impl fmt::Display for ParseUuidError { impl std::error::Error for ParseUuidError {} #[cfg(test)] -mod tests { - use super::*; - - /// The EFI system partition type GUID, `c12a7328-f81f-11d2-ba4b-00a0c93ec93b`, as GPT stores - /// it. - const ESP_LE: [u8; 16] = [ - 0x28, 0x73, 0x2A, 0xC1, 0x1F, 0xF8, 0xD2, 0x11, 0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, - 0x3B, - ]; - - /// The same GUID's bytes, in the order of its text. - const ESP: [u8; 16] = [ - 0xC1, 0x2A, 0x73, 0x28, 0xF8, 0x1F, 0x11, 0xD2, 0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, - 0x3B, - ]; - - #[test] - fn uuids_display_and_parse_their_canonical_text() { - let esp = Uuid::from_bytes(ESP); - assert_eq!(esp.as_bytes(), &ESP); - assert_eq!(esp.to_string(), "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"); - assert_eq!( - format!("{esp:?}"), - "Uuid(c12a7328-f81f-11d2-ba4b-00a0c93ec93b)" - ); - assert_eq!( - Uuid::parse("c12a7328-f81f-11d2-ba4b-00a0c93ec93b"), - Some(esp) - ); - assert_eq!( - Uuid::parse(b"c12a7328-f81f-11d2-ba4b-00a0c93ec93b"), - Some(esp) - ); - assert_eq!("c12a7328-f81f-11d2-ba4b-00a0c93ec93b".parse(), Ok(esp)); - let text = "0fc63daf-8483-4772-8e79-3d69d8477de4"; - assert_eq!(Uuid::parse(text).unwrap().to_string(), text); - } - - #[test] - fn only_the_canonical_text_parses() { - for text in [ - "", - "C12A7328-F81F-11D2-BA4B-00A0C93EC93B", - "c12a7328-f81f-11d2-ba4b-00a0c93ec93B", - "c12a7328f81f11d2ba4b00a0c93ec93b", - "{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}", - "urn:uuid:c12a7328-f81f-11d2-ba4b-00a0c93ec93b", - "c12a7328-f81f-11d2-ba4b-00a0c93ec93", - "c12a7328-f81f-11d2-ba4b-00a0c93ec93bb", - "c12a7328-f81f-11d2-ba4b-00a0c93ec93g", - "c12a7328_f81f-11d2-ba4b-00a0c93ec93b", - "c12a7328-f81f-11d2-ba4b00-a0c93ec93b", - "+12a7328-f81f-11d2-ba4b-00a0c93ec93b", - " c12a7328-f81f-11d2-ba4b-00a0c93ec93", - "c12a7328-f81f-11d2-ba4b-00a0c93ec9\u{e9}", - ] { - assert_eq!(Uuid::parse(text), None, "{text:?}"); - assert_eq!(text.parse::(), Err(ParseUuidError(())), "{text:?}"); - } - assert_eq!( - ParseUuidError(()).to_string(), - "not a UUID in its canonical text: 32 lowercase hexadecimal digits in groups of 8, 4, \ - 4, 4, and 12, joined by hyphens" - ); - } - - #[test] - fn the_efi_layout_reverses_the_first_three_groups() { - let esp = Uuid::from_bytes_le(ESP_LE); - assert_eq!(esp, Uuid::from_bytes(ESP)); - assert_eq!(esp.to_bytes_le(), ESP_LE); - assert_eq!(esp.to_string(), "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"); - let bytes: [u8; 16] = std::array::from_fn(|index| index as u8); - assert_eq!( - Uuid::from_bytes_le(bytes).as_bytes(), - &[3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15] - ); - assert_eq!(Uuid::from_bytes_le(bytes).to_bytes_le(), bytes); - } - - #[test] - fn the_nil_uuid_has_only_zero_bits() { - assert_eq!( - Uuid::NIL.to_string(), - "00000000-0000-0000-0000-000000000000" - ); - assert_eq!( - Uuid::parse("00000000-0000-0000-0000-000000000000"), - Some(Uuid::NIL) - ); - assert!(Uuid::NIL.is_nil()); - assert!(Uuid::from_bytes_le([0; 16]).is_nil()); - assert!(!Uuid::from_bytes(ESP).is_nil()); - } -} +mod tests; diff --git a/nvx-rs/src/uuid/tests.rs b/nvx-rs/src/uuid/tests.rs new file mode 100644 index 000000000..f36188cc0 --- /dev/null +++ b/nvx-rs/src/uuid/tests.rs @@ -0,0 +1,91 @@ +use super::*; + +/// The EFI system partition type GUID, `c12a7328-f81f-11d2-ba4b-00a0c93ec93b`, as GPT stores +/// it. +const ESP_LE: [u8; 16] = [ + 0x28, 0x73, 0x2A, 0xC1, 0x1F, 0xF8, 0xD2, 0x11, 0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B, +]; + +/// The same GUID's bytes, in the order of its text. +const ESP: [u8; 16] = [ + 0xC1, 0x2A, 0x73, 0x28, 0xF8, 0x1F, 0x11, 0xD2, 0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B, +]; + +#[test] +fn uuids_display_and_parse_their_canonical_text() { + let esp = Uuid::from_bytes(ESP); + assert_eq!(esp.as_bytes(), &ESP); + assert_eq!(esp.to_string(), "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"); + assert_eq!( + format!("{esp:?}"), + "Uuid(c12a7328-f81f-11d2-ba4b-00a0c93ec93b)" + ); + assert_eq!( + Uuid::parse("c12a7328-f81f-11d2-ba4b-00a0c93ec93b"), + Some(esp) + ); + assert_eq!( + Uuid::parse(b"c12a7328-f81f-11d2-ba4b-00a0c93ec93b"), + Some(esp) + ); + assert_eq!("c12a7328-f81f-11d2-ba4b-00a0c93ec93b".parse(), Ok(esp)); + let text = "0fc63daf-8483-4772-8e79-3d69d8477de4"; + assert_eq!(Uuid::parse(text).unwrap().to_string(), text); +} + +#[test] +fn only_the_canonical_text_parses() { + for text in [ + "", + "C12A7328-F81F-11D2-BA4B-00A0C93EC93B", + "c12a7328-f81f-11d2-ba4b-00a0c93ec93B", + "c12a7328f81f11d2ba4b00a0c93ec93b", + "{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}", + "urn:uuid:c12a7328-f81f-11d2-ba4b-00a0c93ec93b", + "c12a7328-f81f-11d2-ba4b-00a0c93ec93", + "c12a7328-f81f-11d2-ba4b-00a0c93ec93bb", + "c12a7328-f81f-11d2-ba4b-00a0c93ec93g", + "c12a7328_f81f-11d2-ba4b-00a0c93ec93b", + "c12a7328-f81f-11d2-ba4b00-a0c93ec93b", + "+12a7328-f81f-11d2-ba4b-00a0c93ec93b", + " c12a7328-f81f-11d2-ba4b-00a0c93ec93", + "c12a7328-f81f-11d2-ba4b-00a0c93ec9\u{e9}", + ] { + assert_eq!(Uuid::parse(text), None, "{text:?}"); + assert_eq!(text.parse::(), Err(ParseUuidError(())), "{text:?}"); + } + assert_eq!( + ParseUuidError(()).to_string(), + "not a UUID in its canonical text: 32 lowercase hexadecimal digits in groups of 8, 4, \ + 4, 4, and 12, joined by hyphens" + ); +} + +#[test] +fn the_efi_layout_reverses_the_first_three_groups() { + let esp = Uuid::from_bytes_le(ESP_LE); + assert_eq!(esp, Uuid::from_bytes(ESP)); + assert_eq!(esp.to_bytes_le(), ESP_LE); + assert_eq!(esp.to_string(), "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"); + let bytes: [u8; 16] = std::array::from_fn(|index| index as u8); + assert_eq!( + Uuid::from_bytes_le(bytes).as_bytes(), + &[3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15] + ); + assert_eq!(Uuid::from_bytes_le(bytes).to_bytes_le(), bytes); +} + +#[test] +fn the_nil_uuid_has_only_zero_bits() { + assert_eq!( + Uuid::NIL.to_string(), + "00000000-0000-0000-0000-000000000000" + ); + assert_eq!( + Uuid::parse("00000000-0000-0000-0000-000000000000"), + Some(Uuid::NIL) + ); + assert!(Uuid::NIL.is_nil()); + assert!(Uuid::from_bytes_le([0; 16]).is_nil()); + assert!(!Uuid::from_bytes(ESP).is_nil()); +} diff --git a/scripts/test-layout-allowlist.json b/scripts/test-layout-allowlist.json index d9c6d2e50..da658eee6 100644 --- a/scripts/test-layout-allowlist.json +++ b/scripts/test-layout-allowlist.json @@ -2,18 +2,6 @@ "schema": "nvx-test-layout-allowlist", "schema_version": 1, "baseline": { - "nvx-rs/src/contract.rs": { - "hooks": 1, - "tests": 2 - }, - "nvx-rs/src/error.rs": { - "hooks": 1, - "tests": 5 - }, - "nvx-rs/src/gpt/crc.rs": { - "hooks": 1, - "tests": 2 - }, "nvx-rs/src/guest/cgroup.rs": { "hooks": 5, "tests": 17 @@ -518,42 +506,6 @@ "hooks": 1, "tests": 6 }, - "nvx-rs/src/hypervisor.rs": { - "hooks": 1, - "tests": 2 - }, - "nvx-rs/src/net/cidr.rs": { - "hooks": 1, - "tests": 7 - }, - "nvx-rs/src/net/mod.rs": { - "hooks": 1, - "tests": 3 - }, - "nvx-rs/src/protocol/cmdline.rs": { - "hooks": 1, - "tests": 0 - }, - "nvx-rs/src/protocol/nvxs/record.rs": { - "hooks": 1, - "tests": 0 - }, - "nvx-rs/src/protocol/share.rs": { - "hooks": 1, - "tests": 2 - }, - "nvx-rs/src/protocol/status.rs": { - "hooks": 1, - "tests": 2 - }, - "nvx-rs/src/testing/fake_openvmm.rs": { - "hooks": 1, - "tests": 13 - }, - "nvx-rs/src/uuid.rs": { - "hooks": 1, - "tests": 4 - }, "tests/runtime-adapter/src/frame.rs": { "hooks": 1, "tests": 8