Files
rust-discovery/crates/domain/src/windows_execution.rs
T
2026-11-14 12:04:36 +01:00

387 lines
16 KiB
Rust

//! Windows MSI fixture contract. No legacy Linux codec is changed.
//! Fixed1.0 first installation/noop and separate1.0→1.1 major-upgrade/noop
//! recipes only. No implicit REINSTALL, repair, downgrade or fresh1.1 mode.
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;
pub const MSI_PACKAGE_ID: &str = "rmm-windows-msi-fixture";
pub const MSI_CAPABILITY: &str = "package.msi.fixture/1";
pub const MSI_RECIPE_ID: &str = "rmm-windows-msi-fixture-install-1.0";
pub const MSI_PRODUCT_CODE: &str = "{3F070B4B-9C08-4D65-BD41-13D81B884AEC}";
pub const MSI_UPGRADE_CODE: &str = "{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}";
pub const MSI_VERSION: &str = "1.0.0";
pub const MSI_PAYLOAD: &str = r"C:\Program Files\RustDiscoveryFixtures\msi-payload.txt";
pub const MSI_UPGRADE_RECIPE_ID: &str = "rmm-windows-msi-fixture-upgrade-1.1";
pub const MSI_UPGRADE_PRODUCT_CODE: &str = "{D42BD387-079B-4BBF-A134-0DA7B7A97011}";
pub const MSI_UPGRADE_VERSION: &str = "1.1.0";
pub const MSI_PAYLOAD_BYTES: u64 = 33;
pub const MSI_PAYLOAD_10_SHA256: &str =
"0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0";
pub const MSI_PAYLOAD_11_SHA256: &str =
"ba0c83deff9eed014009bcd45369b2a356ae909ebf0c1434dc836b0e6d759c49";
pub const MSI_OLD_PRODUCTS: &str = "RMM_OLD_PRODUCTS";
pub const MSI_ALL_PRODUCTS: &str = "RMM_ALL_PRODUCTS";
pub const MSI_UPGRADE_CONDITION: &str = "Installed OR (RMM_OLD_PRODUCTS = \"{3F070B4B-9C08-4D65-BD41-13D81B884AEC}\" AND RMM_ALL_PRODUCTS = \"{3F070B4B-9C08-4D65-BD41-13D81B884AEC}\")";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Architecture {
X64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InstallContext {
Machine,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MsiCommandProfile {
FixtureQuietNoRebootV1,
}
impl<'de> Deserialize<'de> for Architecture {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
if value == "x64" {
Ok(Self::X64)
} else {
Err(serde::de::Error::unknown_variant(&value, &["x64"]))
}
}
}
impl<'de> Deserialize<'de> for InstallContext {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
if value == "machine" {
Ok(Self::Machine)
} else {
Err(serde::de::Error::unknown_variant(&value, &["machine"]))
}
}
}
impl<'de> Deserialize<'de> for MsiCommandProfile {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
if value == "fixture_quiet_no_reboot_v1" {
Ok(Self::FixtureQuietNoRebootV1)
} else {
Err(serde::de::Error::unknown_variant(
&value,
&["fixture_quiet_no_reboot_v1"],
))
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MsiArtifact {
pub artifact_id: Uuid,
pub sha256: String,
pub bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MsiPostcondition {
pub product_code: String,
pub product_version: String,
pub payload_path: String,
pub payload_sha256: String,
pub payload_bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WindowsMsiRecipe {
pub schema_version: u32,
pub recipe_id: String,
pub recipe_version: String,
pub platform: String,
pub upgrade_code: String,
pub architecture: Architecture,
pub context: InstallContext,
pub command_profile: MsiCommandProfile,
pub artifact: MsiArtifact,
pub postcondition: MsiPostcondition,
pub no_reboot: bool,
// Appended opt-in metadata: old1.0 recipes retain exactly their old bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub package_code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub predecessor: Option<MsiPostcondition>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ResolvedWindowsMsi {
pub recipe: WindowsMsiRecipe,
/// SHA256 of exactly serde_json::to_vec(recipe), not a self-reference.
pub recipe_sha256: String,
}
pub fn digest(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
pub fn valid_package_code(value: &str) -> bool {
Uuid::parse_str(value).is_ok_and(|id| {
!id.is_nil()
&& value == format!("{{{}}}", id.to_string().to_uppercase())
&& ![MSI_PRODUCT_CODE, MSI_UPGRADE_PRODUCT_CODE, MSI_UPGRADE_CODE].contains(&value)
})
}
impl WindowsMsiRecipe {
pub fn validate(&self) -> bool {
self.schema_version == 1
&& self.recipe_version == "1"
&& self.platform == "windows"
&& self.upgrade_code == MSI_UPGRADE_CODE
&& self.no_reboot
&& !self.artifact.artifact_id.is_nil()
&& digest(&self.artifact.sha256)
&& (1..=262144).contains(&self.artifact.bytes)
&& self.postcondition.payload_path == MSI_PAYLOAD
&& digest(&self.postcondition.payload_sha256)
&& (1..=65536).contains(&self.postcondition.payload_bytes)
&& match self.recipe_id.as_str() {
MSI_RECIPE_ID => {
self.postcondition.product_code == MSI_PRODUCT_CODE
&& self.postcondition.product_version == MSI_VERSION
&& self.package_code.is_none()
&& self.predecessor.is_none()
}
MSI_UPGRADE_RECIPE_ID => {
self.postcondition.product_code == MSI_UPGRADE_PRODUCT_CODE
&& self.postcondition.product_version == MSI_UPGRADE_VERSION
&& self.postcondition.payload_sha256 == MSI_PAYLOAD_11_SHA256
&& self.postcondition.payload_bytes == MSI_PAYLOAD_BYTES
&& self.package_code.as_deref().is_some_and(valid_package_code)
&& self.predecessor.as_ref().is_some_and(|old| {
old.product_code == MSI_PRODUCT_CODE
&& old.product_version == MSI_VERSION
&& old.payload_path == MSI_PAYLOAD
&& old.payload_sha256 == MSI_PAYLOAD_10_SHA256
&& old.payload_bytes == MSI_PAYLOAD_BYTES
})
}
_ => false,
}
}
pub fn sha256(&self) -> Result<String, serde_json::Error> {
Ok(format!("{:x}", Sha256::digest(serde_json::to_vec(self)?)))
}
}
impl ResolvedWindowsMsi {
pub fn validate(&self) -> bool {
self.recipe.validate()
&& digest(&self.recipe_sha256)
&& self
.recipe
.sha256()
.is_ok_and(|sha| sha == self.recipe_sha256)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn recipe() -> WindowsMsiRecipe {
WindowsMsiRecipe {
schema_version: 1,
recipe_id: MSI_RECIPE_ID.into(),
recipe_version: "1".into(),
platform: "windows".into(),
upgrade_code: MSI_UPGRADE_CODE.into(),
architecture: Architecture::X64,
context: InstallContext::Machine,
command_profile: MsiCommandProfile::FixtureQuietNoRebootV1,
artifact: MsiArtifact {
artifact_id: Uuid::new_v4(),
sha256: "ab".repeat(32),
bytes: 1234,
},
postcondition: MsiPostcondition {
product_code: MSI_PRODUCT_CODE.into(),
product_version: MSI_VERSION.into(),
payload_path: MSI_PAYLOAD.into(),
payload_sha256: "cd".repeat(32),
payload_bytes: 20,
},
no_reboot: true,
package_code: None,
predecessor: None,
}
}
#[test]
fn ensure_msi_action_is_strict_opt_in_and_system_windows_only_without_linux_byte_changes() {
use crate::jobs::{Action, encode};
let old=br#"{"action":"ensure_package","provider":"apt","package":"rmm-test","version":"1.0","architecture":"amd64","recipe_version":"1","installation_context":"system"}"#;
let legacy: Action = serde_json::from_slice(old).unwrap();
assert!(legacy.validate_plan_shape());
assert!(legacy.windows_msi().is_none());
assert_eq!(encode(&legacy).unwrap(), old);
let recipe = recipe();
let m = ResolvedWindowsMsi {
recipe_sha256: recipe.sha256().unwrap(),
recipe,
};
let action = Action::EnsurePackage {
provider: "msi".into(),
package: MSI_PACKAGE_ID.into(),
version: MSI_VERSION.into(),
architecture: "x64".into(),
recipe_version: "1".into(),
installation_context: "machine".into(),
recipe_id: Some(MSI_RECIPE_ID.into()),
apt_manifest: None,
windows_msi_manifest: Some(Box::new(m)),
};
assert!(action.validate());
assert!(action.valid_helper_denial_shape("system"));
assert!(!action.valid_helper_denial_shape("root"));
let caps: Vec<String> = [
"ensure_package",
"windows.base/1",
"rmm.sync.v1",
"helper.system.v1",
"system:ensure_package",
MSI_CAPABILITY,
]
.into_iter()
.map(str::to_owned)
.collect();
assert!(action.available_for("system", &caps));
for identity in ["root", "agent_service"] {
assert!(!action.available_for(identity, &caps));
}
for i in 0..caps.len() {
let mut short = caps.clone();
short.remove(i);
assert!(!action.available_for("system", &short));
}
let mut mixed = caps;
mixed.push("linux.base/1".into());
assert!(!action.available_for("system", &mixed));
for (key, value) in [
("provider", serde_json::json!("apt")),
("architecture", serde_json::json!("amd64")),
("installation_context", serde_json::json!("system")),
("version", serde_json::json!("1.1.0")),
] {
let mut bad = serde_json::to_value(&action).unwrap();
bad[key] = value;
assert!(!serde_json::from_value::<Action>(bad).unwrap().validate());
}
for value in [
serde_json::Value::Null,
serde_json::json!(false),
serde_json::json!(1),
serde_json::json!([]),
serde_json::json!({}),
] {
let mut bad = serde_json::to_value(&action).unwrap();
bad["windows_msi_manifest"] = value;
assert!(serde_json::from_value::<Action>(bad).is_err());
}
for (key, value) in [
("architecture", "x64"),
("context", "machine"),
("command_profile", "fixture_quiet_no_reboot_v1"),
] {
let mut bad = serde_json::to_value(&action).unwrap();
bad["windows_msi_manifest"]["recipe"][key] = serde_json::json!({value:null});
assert!(serde_json::from_value::<Action>(bad).is_err());
}
for (runtime, bytes) in [(9, 4096), (121, 4096), (10, 1023), (10, 65537)] {
assert!(!action.valid_job_limits(runtime, bytes));
}
let schema = schemars::schema_for!(Action).to_value();
let pkg = schema["oneOf"]
.as_array()
.unwrap()
.iter()
.find(|v| v["properties"].get("windows_msi_manifest").is_some())
.unwrap();
assert_eq!(
pkg["properties"]["windows_msi_manifest"],
serde_json::json!({"$ref":"#/$defs/ResolvedWindowsMsi"})
);
assert!(
!pkg["required"]
.as_array()
.unwrap()
.contains(&serde_json::json!("windows_msi_manifest"))
);
}
#[test]
fn major_upgrade_requires_explicit_exact_predecessor_new_package_and_same_family() {
let old = recipe();
let old_bytes = serde_json::to_vec(&old).unwrap();
assert!(
!String::from_utf8(old_bytes.clone())
.unwrap()
.contains("predecessor")
);
assert_eq!(
serde_json::to_vec(&serde_json::from_slice::<WindowsMsiRecipe>(&old_bytes).unwrap())
.unwrap(),
old_bytes
);
let mut r = old.clone();
r.recipe_id = MSI_UPGRADE_RECIPE_ID.into();
r.package_code = Some("{8475C4D1-6EE2-4C3A-B41D-D834A20F4135}".into());
r.postcondition.product_code = MSI_UPGRADE_PRODUCT_CODE.into();
r.postcondition.product_version = MSI_UPGRADE_VERSION.into();
r.postcondition.payload_sha256 = MSI_PAYLOAD_11_SHA256.into();
r.postcondition.payload_bytes = MSI_PAYLOAD_BYTES;
r.predecessor = Some(MsiPostcondition {
product_code: MSI_PRODUCT_CODE.into(),
product_version: MSI_VERSION.into(),
payload_path: MSI_PAYLOAD.into(),
payload_sha256: MSI_PAYLOAD_10_SHA256.into(),
payload_bytes: MSI_PAYLOAD_BYTES,
});
assert!(r.validate());
assert_ne!(r.sha256().unwrap(), old.sha256().unwrap());
for case in 0..8 {
let mut bad = r.clone();
match case {
0 => bad.predecessor = None,
1 => bad.package_code = None,
2 => bad.package_code = Some(MSI_PRODUCT_CODE.into()),
3 => bad.upgrade_code = Uuid::new_v4().to_string(),
4 => {
bad.predecessor.as_mut().unwrap().product_code = MSI_UPGRADE_PRODUCT_CODE.into()
}
5 => bad.predecessor.as_mut().unwrap().payload_sha256 = "aa".repeat(32),
6 => bad.postcondition.product_version = "1.2.0".into(),
_ => bad.postcondition.payload_sha256 = MSI_PAYLOAD_10_SHA256.into(),
};
assert!(!bad.validate());
}
}
#[test]
fn immutable_fixture_recipe_rejects_reboot_url_transform_and_implicit_upgrade() {
let recipe = recipe();
let bound = ResolvedWindowsMsi {
recipe_sha256: recipe.sha256().unwrap(),
recipe: recipe.clone(),
};
assert!(bound.validate());
let mut changed = bound.clone();
changed.recipe.artifact.bytes += 1;
assert!(!changed.validate());
for case in 0..6 {
let mut r = recipe.clone();
match case {
0 => r.no_reboot = false,
1 => r.postcondition.product_code = Uuid::new_v4().to_string(),
2 => r.postcondition.product_version = "1.1.0".into(),
3 => r.postcondition.payload_path = r"\\server\share\payload".into(),
4 => r.artifact.bytes = 262145,
_ => r.platform = "linux".into(),
};
assert!(!r.validate());
}
let mut value = serde_json::to_value(recipe).unwrap();
value["transforms"] = serde_json::json!(["unapproved.mst"]);
assert!(serde_json::from_value::<WindowsMsiRecipe>(value).is_err());
}
}