Skip to main content

petri/
requirements.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Test requirements framework for runtime test filtering.
5
6use petri_artifacts_common::capabilities;
7use std::collections::BTreeSet;
8
9/// Execution environments where tests can run.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum ExecutionEnvironment {
12    /// Bare metal execution (not nested virtualization).
13    Baremetal,
14    /// Nested virtualization environment.
15    Nested,
16}
17
18/// CPU vendors.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Vendor {
21    /// AMD processors.
22    Amd,
23    /// Intel processors.
24    Intel,
25    /// ARM processors.
26    Arm,
27}
28
29impl Vendor {
30    /// Detect the vendor of the host CPU the test is running on.
31    pub fn host() -> Self {
32        cfg_select! {
33            // xtask-fmt allow-target-arch cpu-intrinsic
34            target_arch = "x86_64" => {
35                let result = safe_intrinsics::cpuid(
36                    x86defs::cpuid::CpuidFunction::VendorAndMaxFunction.0,
37                    0,
38                );
39                let vendor =
40                    x86defs::cpuid::Vendor::from_ebx_ecx_edx(result.ebx, result.ecx, result.edx);
41                if vendor.is_amd_compatible() {
42                    Vendor::Amd
43                } else {
44                    assert!(vendor.is_intel_compatible());
45                    Vendor::Intel
46                }
47            }
48            _ => Vendor::Arm,
49        }
50    }
51}
52
53/// Types of isolation supported.
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub enum IsolationType {
56    /// Virtualization-based Security (VBS)
57    Vbs,
58    /// Secure Nested Paging (SNP)
59    Snp,
60    /// Trusted Domain Extensions (TDX)
61    Tdx,
62}
63
64/// VMM implementation types.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum VmmType {
67    /// OpenVMM.
68    OpenVmm,
69    /// Microsoft Hyper-V.
70    HyperV,
71    /// QEMU.
72    Qemu,
73}
74
75/// Hypervisor backends that OpenVMM can use.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum OpenVmmHypervisor {
78    /// Linux Microsoft Hypervisor backend.
79    Mshv,
80    /// Linux KVM backend.
81    Kvm,
82    /// Windows Hypervisor Platform backend.
83    Whp,
84    /// macOS Hypervisor Framework backend.
85    Hvf,
86}
87
88/// Information about the VM host. On Windows, petri reads it with the
89/// `Get-VMHost` PowerShell cmdlet. On Linux, petri probes MSHV for SNP support.
90#[derive(Debug, Clone)]
91pub struct VmHostInfo {
92    /// VBS support status
93    pub vbs_supported: bool,
94    /// SNP support status
95    pub snp_status: bool,
96    /// TDX support status
97    pub tdx_status: bool,
98}
99
100/// Platform-specific host context extending the base HostContext
101#[derive(Debug, Clone)]
102pub struct HostContext {
103    /// VM host information, if petri can get it on this host
104    pub vm_host_info: Option<VmHostInfo>,
105    /// CPU vendor
106    pub vendor: Vendor,
107    /// Execution environment
108    pub execution_environment: ExecutionEnvironment,
109    /// Hypervisor backend that OpenVMM will select on this host.
110    pub openvmm_hypervisor: Option<OpenVmmHypervisor>,
111    /// Whether the selected OpenVMM backend supports nested partition reset.
112    pub nested_reset_supported: bool,
113}
114
115impl HostContext {
116    /// Create a new host context by querying host information
117    pub async fn new() -> Self {
118        let is_nested = cfg_select! {
119            // xtask-fmt allow-target-arch cpu-intrinsic
120            target_arch = "x86_64" => {{
121                let result = safe_intrinsics::cpuid(
122                    hvdef::HV_CPUID_FUNCTION_MS_HV_ENLIGHTENMENT_INFORMATION,
123                    0,
124                );
125                hvdef::HvEnlightenmentInformation::from(
126                    result.eax as u128
127                        | (result.ebx as u128) << 32
128                        | (result.ecx as u128) << 64
129                        | (result.edx as u128) << 96,
130                )
131                .nested()
132            }}
133            _ => false,
134        };
135
136        let vendor = Vendor::host();
137
138        let openvmm_hypervisor = cfg_select! {
139            target_os = "linux" => {
140                if fs_err::File::open("/dev/mshv").is_ok() {
141                    Some(OpenVmmHypervisor::Mshv)
142                } else if fs_err::File::options()
143                    .read(true)
144                    .write(true)
145                    .open("/dev/kvm")
146                    .is_ok()
147                {
148                    Some(OpenVmmHypervisor::Kvm)
149                } else {
150                    None
151                }
152            }
153            windows => Some(OpenVmmHypervisor::Whp),
154            target_os = "macos" => Some(OpenVmmHypervisor::Hvf),
155            _ => None,
156        };
157
158        let nested_reset_supported = match openvmm_hypervisor {
159            Some(OpenVmmHypervisor::Kvm) => openvmm_hypervisors::kvm_nested_state_available(),
160            Some(OpenVmmHypervisor::Mshv) => openvmm_hypervisors::mshv_partition_scrub_available(),
161            Some(OpenVmmHypervisor::Whp) => openvmm_hypervisors::whp_nested_reset_available(),
162            _ => false,
163        };
164
165        let vm_host_info = cfg_select! {
166            windows => crate::vm::hyperv::powershell::run_get_vm_host()
167                .await
168                .ok()
169                .map(|info| VmHostInfo {
170                    vbs_supported: info.guest_isolation_types.contains(
171                        &crate::vm::hyperv::powershell::HyperVGuestStateIsolationType::Vbs,
172                    ),
173                    snp_status: info.snp_status,
174                    tdx_status: info.tdx_status,
175                }),
176            _ => {
177                // MSHV has no SNP capability query, so probe by creating a
178                // temporary SNP partition. Only AMD hosts can support SNP.
179                (vendor == Vendor::Amd && openvmm_hypervisor == Some(OpenVmmHypervisor::Mshv)).then(
180                    || VmHostInfo {
181                        vbs_supported: false,
182                        snp_status: openvmm_hypervisors::mshv_snp_available(),
183                        tdx_status: false,
184                    },
185                )
186            }
187        };
188
189        Self {
190            vm_host_info,
191            vendor,
192            execution_environment: if is_nested {
193                ExecutionEnvironment::Nested
194            } else {
195                ExecutionEnvironment::Baremetal
196            },
197            openvmm_hypervisor,
198            nested_reset_supported,
199        }
200    }
201}
202
203/// A single requirement for a test to run.
204pub enum TestRequirement {
205    /// Execution environment requirement.
206    ExecutionEnvironment(ExecutionEnvironment),
207    /// Vendor requirement.
208    Vendor(Vendor),
209    /// Hypervisor backend that OpenVMM must select on the host.
210    OpenVmmHypervisor(OpenVmmHypervisor),
211    /// A host capability probe evaluated only during runtime host filtering.
212    ///
213    /// Combine this with a backend requirement using [`Self::and`] to avoid
214    /// probing backends that are not available on the host.
215    ///
216    /// The probe runs synchronously before test execution, including when
217    /// listing tests for nextest. Artifact enumeration does not evaluate it.
218    /// Callers should cache expensive probes and report probe errors from the
219    /// test body rather than treating errors as unsupported capabilities.
220    HostCapability(fn() -> bool),
221    /// Isolation requirement.
222    Isolation(IsolationType),
223    /// Requires a named capability advertised by the execution environment or
224    /// detected by petri.
225    ///
226    /// Capabilities are how a test says "I need a specific resource to be
227    /// provisioned for me" without naming who provides it or how. The
228    /// execution environment can advertise capabilities via the
229    /// comma-separated `PETRI_CAPABILITIES` environment variable, and petri can
230    /// add capabilities that it detects itself. A test requiring a capability
231    /// that is not available is skipped, so such tests automatically
232    /// self-exclude on any host that cannot satisfy them.
233    RequiresCapability {
234        /// Capability name.
235        name: &'static str,
236        /// VMM used by the test, which may affect capability availability.
237        vmm: VmmType,
238    },
239    /// Logical AND of two requirements.
240    And(Box<TestRequirement>, Box<TestRequirement>),
241    /// Logical OR of two requirements.
242    Or(Box<TestRequirement>, Box<TestRequirement>),
243    /// Logical NOT of a requirement.
244    Not(Box<TestRequirement>),
245    /// Requirement satisfied by any host context.
246    Any,
247}
248
249impl TestRequirement {
250    /// Combine this requirement with another requirement using logical AND.
251    pub fn and(self, other: TestRequirement) -> TestRequirement {
252        TestRequirement::And(Box::new(self), Box::new(other))
253    }
254
255    /// Combine this requirement with another requirement using logical OR.
256    pub fn or(self, other: TestRequirement) -> TestRequirement {
257        TestRequirement::Or(Box::new(self), Box::new(other))
258    }
259
260    /// Negate this requirement.
261    #[expect(clippy::should_implement_trait)]
262    pub fn not(self) -> TestRequirement {
263        TestRequirement::Not(Box::new(self))
264    }
265
266    /// Evaluate if this requirement is satisfied with the given host context
267    pub fn is_satisfied(&self, context: &HostContext) -> bool {
268        match self {
269            TestRequirement::ExecutionEnvironment(env) => context.execution_environment == *env,
270            TestRequirement::Vendor(vendor) => context.vendor == *vendor,
271            TestRequirement::OpenVmmHypervisor(hypervisor) => {
272                context.openvmm_hypervisor == Some(*hypervisor)
273            }
274            TestRequirement::HostCapability(probe) => probe(),
275            TestRequirement::Isolation(isolation_type) => {
276                if let Some(vm_host_info) = &context.vm_host_info {
277                    match isolation_type {
278                        IsolationType::Vbs => vm_host_info.vbs_supported,
279                        IsolationType::Snp => vm_host_info.snp_status,
280                        IsolationType::Tdx => vm_host_info.tdx_status,
281                    }
282                } else {
283                    false
284                }
285            }
286            TestRequirement::RequiresCapability { name, vmm } => {
287                available_capabilities(context, *vmm).contains(name)
288            }
289            TestRequirement::And(req1, req2) => {
290                req1.is_satisfied(context) && req2.is_satisfied(context)
291            }
292            TestRequirement::Or(req1, req2) => {
293                req1.is_satisfied(context) || req2.is_satisfied(context)
294            }
295            TestRequirement::Not(req) => !req.is_satisfied(context),
296            TestRequirement::Any => true,
297        }
298    }
299}
300
301/// Returns the canonical runtime name for a known capability.
302pub fn known_capability(name: &str) -> Option<&'static str> {
303    capabilities::known(name)
304}
305
306/// Returns whether `name` is a known capability.
307pub fn is_known_capability(name: &str) -> bool {
308    known_capability(name).is_some()
309}
310
311fn available_capabilities(context: &HostContext, vmm: VmmType) -> BTreeSet<&'static str> {
312    let mut capabilities = BTreeSet::new();
313
314    // Software VPCI devices are supported by Hyper-V and by the OpenVMM
315    // backends that implement virtual device creation.
316    if matches!(
317        (vmm, context.openvmm_hypervisor),
318        (VmmType::HyperV, _)
319            | (
320                VmmType::OpenVmm,
321                Some(OpenVmmHypervisor::Whp | OpenVmmHypervisor::Mshv)
322            )
323    ) {
324        capabilities.insert(capabilities::VPCI);
325    }
326
327    // virt_mshv cannot currently reset partitions running Windows.
328    // This is due to two issues:
329    // * A hypervisor issue that prevents locked hv#1 MSRs from being set by the host VMM.
330    // * Missing support for the HvScrubPartition hypercall.
331    // Once either of these are fixed, we can remove this check and feature.
332    if !matches!(
333        (vmm, context.openvmm_hypervisor),
334        (VmmType::OpenVmm, Some(OpenVmmHypervisor::Mshv))
335    ) {
336        capabilities.insert(capabilities::WINDOWS_PARTITION_RESET);
337    }
338
339    // Nested virtualization is supported by the x86 OpenVMM backends and QEMU.
340    if matches!(
341        (vmm, context.openvmm_hypervisor),
342        (
343            VmmType::OpenVmm,
344            Some(OpenVmmHypervisor::Kvm | OpenVmmHypervisor::Whp | OpenVmmHypervisor::Mshv)
345        ) | (VmmType::Qemu, _)
346    ) {
347        capabilities.insert(capabilities::NESTED_VIRT);
348    }
349
350    // virt_mshv does not support another level of nested virtualization, so
351    // an mshv root partition can only be booted on the other x86 backends.
352    if matches!(
353        (vmm, context.openvmm_hypervisor),
354        (
355            VmmType::OpenVmm,
356            Some(OpenVmmHypervisor::Kvm | OpenVmmHypervisor::Whp)
357        )
358    ) {
359        capabilities.insert(capabilities::NESTED_MSHV);
360    }
361
362    if vmm == VmmType::OpenVmm && context.nested_reset_supported {
363        capabilities.insert(capabilities::NESTED_RESET);
364    }
365
366    match std::env::var("PETRI_CAPABILITIES") {
367        Ok(env_capabilities) => {
368            for capability in env_capabilities.split(',').map(str::trim) {
369                if capability.is_empty() {
370                    continue;
371                }
372                let capability = known_capability(capability)
373                    .unwrap_or_else(|| panic!("unknown PETRI_CAPABILITIES entry: {capability}"));
374                capabilities.insert(capability);
375            }
376        }
377        Err(std::env::VarError::NotPresent) => {}
378        Err(std::env::VarError::NotUnicode(_)) => {
379            panic!("PETRI_CAPABILITIES is not valid UTF-8")
380        }
381    }
382
383    capabilities
384}
385
386/// Container for test requirements that can be evaluated
387pub struct TestCaseRequirements {
388    requirements: TestRequirement,
389}
390
391impl TestCaseRequirements {
392    /// Create a new TestCaseRequirements from a TestRequirement
393    pub fn new(requirements: TestRequirement) -> Self {
394        Self { requirements }
395    }
396}
397
398/// Evaluates if a test case can be run in the current execution environment with context.
399pub fn can_run_test_with_context(
400    config: Option<&TestCaseRequirements>,
401    context: &HostContext,
402) -> bool {
403    if let Some(config) = config {
404        config.requirements.is_satisfied(context)
405    } else {
406        true
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413
414    fn host_context(openvmm_hypervisor: OpenVmmHypervisor) -> HostContext {
415        HostContext {
416            vm_host_info: None,
417            vendor: Vendor::Intel,
418            execution_environment: ExecutionEnvironment::Baremetal,
419            openvmm_hypervisor: Some(openvmm_hypervisor),
420            nested_reset_supported: false,
421        }
422    }
423
424    #[test]
425    fn capabilities_are_evaluated_for_the_selected_vmm() {
426        let requirement = |vmm| TestRequirement::RequiresCapability {
427            name: capabilities::WINDOWS_PARTITION_RESET,
428            vmm,
429        };
430        let mshv = host_context(OpenVmmHypervisor::Mshv);
431
432        assert!(!requirement(VmmType::OpenVmm).is_satisfied(&mshv));
433        assert!(requirement(VmmType::HyperV).is_satisfied(&mshv));
434        assert!(requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Kvm)));
435    }
436
437    #[test]
438    fn nested_virt_capability_matches_the_selected_backend() {
439        let requirement = TestRequirement::RequiresCapability {
440            name: capabilities::NESTED_VIRT,
441            vmm: VmmType::OpenVmm,
442        };
443
444        assert!(requirement.is_satisfied(&host_context(OpenVmmHypervisor::Mshv)));
445        assert!(!requirement.is_satisfied(&host_context(OpenVmmHypervisor::Hvf)));
446    }
447
448    #[test]
449    fn nested_mshv_capability_excludes_the_mshv_backend() {
450        let requirement = |vmm| TestRequirement::RequiresCapability {
451            name: capabilities::NESTED_MSHV,
452            vmm,
453        };
454
455        assert!(requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Kvm)));
456        assert!(requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Whp)));
457        assert!(
458            !requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Mshv))
459        );
460        assert!(!requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Hvf)));
461        assert!(!requirement(VmmType::Qemu).is_satisfied(&host_context(OpenVmmHypervisor::Kvm)));
462    }
463
464    #[test]
465    fn openvmm_hypervisor_requirement_matches_the_selected_backend() {
466        let requirement = TestRequirement::OpenVmmHypervisor(OpenVmmHypervisor::Mshv);
467        assert!(requirement.is_satisfied(&host_context(OpenVmmHypervisor::Mshv)));
468        assert!(!requirement.is_satisfied(&host_context(OpenVmmHypervisor::Kvm)));
469        assert!(!requirement.is_satisfied(&host_context(OpenVmmHypervisor::Whp)));
470        let mut without_hypervisor = host_context(OpenVmmHypervisor::Mshv);
471        without_hypervisor.openvmm_hypervisor = None;
472        assert!(!requirement.is_satisfied(&without_hypervisor));
473    }
474
475    #[test]
476    fn capability_probes_are_short_circuited_by_backend_requirements() {
477        let requirement = TestRequirement::OpenVmmHypervisor(OpenVmmHypervisor::Kvm).and(
478            TestRequirement::HostCapability(|| panic!("unavailable backend must not be probed")),
479        );
480        assert!(!requirement.is_satisfied(&host_context(OpenVmmHypervisor::Mshv)));
481        assert!(
482            !TestRequirement::HostCapability(|| false)
483                .is_satisfied(&host_context(OpenVmmHypervisor::Kvm))
484        );
485        assert!(
486            TestRequirement::HostCapability(|| true)
487                .is_satisfied(&host_context(OpenVmmHypervisor::Kvm))
488        );
489    }
490}