diff --git a/Rust_RMM_Implementierungsspezifikation.md b/Rust_RMM_Implementierungsspezifikation.md index 77a1b72..66bd225 100644 --- a/Rust_RMM_Implementierungsspezifikation.md +++ b/Rust_RMM_Implementierungsspezifikation.md @@ -1,6 +1,6 @@ # Rust RMM: Architektur und Implementierungsspezifikation -Version 1.18 · 2026-11-14 · Sprache: Deutsch +Version 1.19 · 2026-11-14 · Sprache: Deutsch **Zweck:** Vollständige, eigenständig nutzbare Grundlage für die Implementierung einer mandantenfähigen Plattform zur Inventarisierung, Überwachung und Fernadministration von Kundengeräten durch eine Coding-KI und ein Entwicklungsteam. @@ -15,6 +15,12 @@ Version 1.18 · 2026-11-14 · Sprache: Deutsch lokaler Helperpolicy präzisiert. Keine Vererbung von Linux-Rootrechten, keine Windowsfähigkeit aus einer bloßen Quellen-/Build-/Linux-Unitqualifikation. +1.18 → 1.19 (2026-11-14): Nächster Windows-M4-Schnitt als ausdrücklicher +Opt-in für zwei eigene feste MSI-Rezepte (1.0 und1.0→1.1) präzisiert: +unveränderlicher Tenantkatalog, exakte automatische Job-/Artefaktbindung, +getrennte SYSTEM-Paketerlaubnis und unabhängige Nachbedingungen. Kein freier +Installer, kein automatisches Update/Repair, keine implizite EXE-/Rebootfreigabe. + 1.17 → 1.18 (2026-11-14): Ausdrückliche Userfreigabe für die feste, vor der WebUI-Genehmigung sichtbare RemoteSigned-Option je Windows-PowerShell5.1- Jobprozess, gezieltes Starten des bestehenden W32Time ohne Konfigurationsänderung @@ -141,6 +147,50 @@ keinen Rebootjob-Abnahmenachweis. Dokumentierte Freigaben sind keine bereits ausgeführten Schritte. Neue Capabilities werden erst nach ihrer getrennten nativen Qualifikation eröffnet. +**Technische Präzisierung Version1.19 — enger Windows-M4-MSI-Schnitt:** +Nach dem getrennten SCM-Vertrag wird `ensure_package` ausschließlich für die +eigenen festen Machine-/x64-MSI-Rezepte1.0 und1.0→1.1 erweitert. Keine freie +SYSTEM-Shell, URL, Transformdatei, Propertyliste oder Ableitung von Linux-Root. +Ein optionales, bei Vorhandensein streng typisiertes `windows_msi_manifest` +bindet das vollständige kanonische Rezept samt Hash in der Action; fehlend bleibt +bei alten Linuxjobs ausgelassen. APT- und Windowsmanifest schließen einander aus. +Äußere Paket-/Versions-/Kontextfelder, Plattform und SYSTEM-Identität müssen +exakt zum Rezept passen. Sämtliche historischen Linux-Codecbytes bleiben erhalten. + +Der Windowskatalog ist eigenständig, unveränderlich und mandantengetrennt; seine +Artefaktreferenz benötigt denselben Tenant. Pro konkretem Job/Versuch entsteht +automatisch genau die eine Referenz aus dem genehmigten Rezept: Artefakt-ID, +SHA256 und Länge. Freie zusätzliche Artefakt-IDs sind im MSI-Pfad verweigert. +Fehlende, zusätzliche oder doppelte Referenzen verweigern Revalidation, +Startgrant und Download. Der bestehende geräte-mTLS-/Job-/Versuch-gebundene +Artefaktendpoint bleibt maßgeblich; Bootstrap-SFTP ist keine Paketabnahme. + +Zentrale und lokale SYSTEM-Policy erweitern ihre bisherige SCM-Erlaubnis nur +ausdrücklich versioniert um exakte MSI-Rezepthashes und eigene Paketrechte/ +Capabilities. Alte SCM-only-Profile erteilen keine Paketerlaubnis. Vor WebUI- +Genehmigung stehen SYSTEM/Machine/x64, Rezept-/Artefakthashes, Produkt-/Upgrade- +und beim1.1-Rezept PackageCode, feste Version/Nutzdatei, Vorgänger, feste Argumente und +No-Reboot-Vertrag sichtbar aus den unveränderlichen Planbytes fest. Clock, +signierter unabhängiger Helpersync, Plan/Grant und dauerhafter Einmalverbrauch +bleiben vor Installerwirkung zwingend. Der Helper kopiert ausschließlich gegen +das signierte Rezept geprüfte Bytes in seinen geschützten Cache; keine vom +Netzwerkagenten frei gewählten Pfade/Programme oder allgemeinen Schreiboperationen. + +Der getrennte Nichtdispatch-/Abandon-/RawMirror-Vertrag gilt additiv auch für +diese konkrete typisierte Action, ohne Cache-/Provider-/Installerwirkung durch +Abandon. Nach möglicher Übergabe gibt es keinen Execute-Retry. MSI0/3010 ist +nur mit unabhängiger innerhalb des ursprünglichen Budgets beobachteter +Nachbedingung erfolgreich;3010 meldet Neustartbedarf ohne Neustartstart. +1641 bleibt Unknown,1618 bekannter Konflikt ohne Retry. Unklarer Timeout/Abbruch +bleibt Unknown; kein globales Beenden von Windows Installer. Auch Noop benötigt +gültige Clock/Fence, Abbruchprüfung und rechtzeitigen unabhängigen Beleg. +Upgrade1.1 setzt genau den bekannten1.0-Vorgänger voraus; danach1.1 installiert, +1.0 entfernt und Nutzdatei exakt. Derselbe1.1-Rezept-/PackageCode erlaubt einen +separat genehmigten echten Noop, kein implizites Repair/Downgrade/Fresh1.1. +Quellen, Builds und Units eröffnen keine Capability oder Policy. Native +Installation/Upgrade/Noop erfolgen jeweils ausschließlich nach tatsächlicher +WebUI-Genehmigung auf der Windows-VM; Linux-first-Vertragsnachweise zuerst. + **Technische Präzisierung Version 1.17 — Nichtstart vor SYSTEM-Delegation:** Vor jeder Socketübergabe bindet ein dauerhafter Intent die unveränderten Originalrequest-/Job-/Grant-/Signaturbytes, Plan/Autorisierung, Gerät und diff --git a/crates/agent-core/src/auth.rs b/crates/agent-core/src/auth.rs index 974136c..581734f 100644 --- a/crates/agent-core/src/auth.rs +++ b/crates/agent-core/src/auth.rs @@ -72,8 +72,7 @@ impl Binding { ensure!(permit_window(&job, &permit), "PERMIT_TIME"); ensure!( job.execution_identity == identity.as_str() - && matches!(&job.action, rmm_domain::jobs::Action::SetServiceState { state, .. } - if matches!(state.as_str(), "running" | "stopped")), + && job.action.valid_helper_denial_shape(identity.as_str()), "DENIAL_HELPER_SCOPE" ); Ok(VerifiedHistoricalDenial { diff --git a/crates/agent-core/tests/contracts.rs b/crates/agent-core/tests/contracts.rs index 4ccb931..145bbf3 100644 --- a/crates/agent-core/tests/contracts.rs +++ b/crates/agent-core/tests/contracts.rs @@ -480,3 +480,96 @@ fn completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evid .is_err() ); } + +#[test] +fn historical_msi_nonstart_keeps_full_signature_binding_and_never_becomes_root_authority() { + use rmm_agent_core::auth::HelperIdentity; + use rmm_domain::windows_execution::*; + let (binding, mut request, mut permit, now) = fixture(); + let mut job: JobPayload = serde_json::from_slice(&request.job_bytes).unwrap(); + let recipe = 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::from_u128(19), + sha256: "ab".repeat(32), + bytes: 32, + }, + postcondition: 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, + }, + no_reboot: true, + package_code: None, + predecessor: None, + }; + let manifest = ResolvedWindowsMsi { + recipe_sha256: recipe.sha256().unwrap(), + recipe, + }; + job.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(manifest)), + }; + job.execution_identity = "system".into(); + request.job_bytes = encode(&job).unwrap(); + permit.action = "ensure_package".into(); + permit.execution_identity = "system".into(); + permit.job_payload_hash = hash(&request.job_bytes); + request.permit_bytes = encode(&permit).unwrap(); + request.signature = SigningKey::from_bytes(&[9; 32]) + .sign(&request.permit_bytes) + .to_bytes() + .to_vec(); + binding + .verify_historical_for_denial_with( + &request, + HelperIdentity::System, + &rmm_agent_core::crypto::DalekVerifier, + ) + .unwrap(); + assert!( + binding + .verify_historical_for_denial_with( + &request, + HelperIdentity::Root, + &rmm_agent_core::crypto::DalekVerifier + ) + .is_err() + ); + assert!(binding.verify(&request, now + Duration::hours(1)).is_err()); // historical denial is never live authorization + if let Action::EnsurePackage { + windows_msi_manifest: Some(m), + .. + } = &mut job.action + { + m.recipe.artifact.bytes += 1; + m.recipe_sha256 = m.recipe.sha256().unwrap(); + } + request.job_bytes = encode(&job).unwrap(); + assert!( + binding + .verify_historical_for_denial_with( + &request, + HelperIdentity::System, + &rmm_agent_core::crypto::DalekVerifier + ) + .is_err() + ); +} diff --git a/crates/domain/src/jobs.rs b/crates/domain/src/jobs.rs index 5399dc6..ac54f63 100644 --- a/crates/domain/src/jobs.rs +++ b/crates/domain/src/jobs.rs @@ -48,6 +48,17 @@ where } } +/// Missing preserves Linux codecs; explicit null/nonobject is never a manifest. +pub fn deserialize_windows_msi_manifest<'de, D>( + deserializer: D, +) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, +{ + crate::windows_execution::ResolvedWindowsMsi::deserialize(deserializer) + .map(|m| Some(Box::new(m))) +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)] #[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] pub enum Action { @@ -88,6 +99,13 @@ pub enum Action { recipe_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] apt_manifest: Option, + #[serde( + default, + deserialize_with = "deserialize_windows_msi_manifest", + skip_serializing_if = "Option::is_none" + )] + #[schemars(with = "crate::windows_execution::ResolvedWindowsMsi")] + windows_msi_manifest: Option>, }, ApplyUpdates { provider: String, @@ -185,6 +203,28 @@ impl Action { installation_context, recipe_id, apt_manifest, + windows_msi_manifest: Some(m), + } => { + m.validate() + && provider == "msi" + && package == crate::windows_execution::MSI_PACKAGE_ID + && version == &m.recipe.postcondition.product_version + && architecture == "x64" + && installation_context == "machine" + && recipe_version == &m.recipe.recipe_version + && recipe_id.as_ref() == Some(&m.recipe.recipe_id) + && apt_manifest.is_none() + } + Self::EnsurePackage { + provider, + package, + version, + architecture, + recipe_version, + installation_context, + recipe_id, + apt_manifest, + windows_msi_manifest: None, } => { provider == "apt" && unit(package) @@ -243,6 +283,20 @@ impl Action { } } } + pub fn windows_msi(&self) -> Option<&crate::windows_execution::ResolvedWindowsMsi> { + match self { + Self::EnsurePackage { + windows_msi_manifest: Some(m), + .. + } => Some(m.as_ref()), + _ => None, + } + } + pub fn valid_helper_denial_shape(&self, identity: &str) -> bool { + (matches!(self,Self::SetServiceState{state,..} if matches!(state.as_str(),"running"|"stopped")) + && self.validate()) + || (identity == "system" && self.windows_msi().is_some() && self.validate()) + } pub fn is_windows_event_log_fixture(&self) -> bool { matches!(self, Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE) } @@ -250,6 +304,9 @@ impl Action { /// its inner Event Log calls retain their own cooperative <=5s deadline. pub fn valid_job_limits(&self, runtime_seconds: u32, output_bytes: u32) -> bool { (1..=3600).contains(&runtime_seconds) + && (self.windows_msi().is_none() + || ((10..=120).contains(&runtime_seconds) + && (1024..=65536).contains(&output_bytes))) && (1..=262144).contains(&output_bytes) && (!self.is_windows_event_log_fixture() || ((10..=120).contains(&runtime_seconds) @@ -268,7 +325,7 @@ impl Action { } /// Shared plan/revalidation/start gate. Passive Windows never implies job support. pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool { - if identity == "system" && !matches!(self, Self::SetServiceState { .. }) { + if identity == "system" && !self.valid_helper_denial_shape(identity) { return false; } let has = |cap: &str| capabilities.iter().any(|c| c == cap); @@ -304,6 +361,17 @@ impl Action { && !(has("linux.base/1") && has("windows.base/1")) && (scope != "windows.base" || has("rmm.sync.v1")) } + Self::EnsurePackage { .. } if self.windows_msi().is_some() || has("windows.base/1") => { + self.windows_msi().is_some() + && self.validate() + && identity == "system" + && has("windows.base/1") + && !has("linux.base/1") + && has("rmm.sync.v1") + && has("helper.system.v1") + && has("system:ensure_package") + && has(crate::windows_execution::MSI_CAPABILITY) + } Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE || has("windows.base/1") => { @@ -349,6 +417,7 @@ impl Action { installation_context, recipe_id: None, apt_manifest: None, + windows_msi_manifest: None, } => { provider == "apt" && !package.is_empty() diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs index 5f394f7..78a3fd1 100644 --- a/crates/domain/src/lib.rs +++ b/crates/domain/src/lib.rs @@ -4,6 +4,7 @@ pub mod checkpoint_repair; pub mod inventory_document; pub mod jobs; pub mod reconciliation; +pub mod windows_execution; pub const TENANT_A: &str = "11111111-1111-4111-8111-111111111111"; pub const TENANT_B: &str = "22222222-2222-4222-8222-222222222222"; diff --git a/crates/domain/src/windows_execution.rs b/crates/domain/src/windows_execution.rs index 7ad51f9..bb89a1b 100644 --- a/crates/domain/src/windows_execution.rs +++ b/crates/domain/src/windows_execution.rs @@ -1,10 +1,12 @@ -//! Unexported Windows MSI fixture contract. No legacy Linux codec is changed. +//! 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}"; @@ -21,29 +23,62 @@ pub const MSI_PAYLOAD_11_SHA256: &str = 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, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)] #[serde(rename_all = "snake_case")] pub enum Architecture { X64, } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)] #[serde(rename_all = "snake_case")] pub enum InstallContext { Machine, } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)] #[serde(rename_all = "snake_case")] pub enum MsiCommandProfile { FixtureQuietNoRebootV1, } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +impl<'de> Deserialize<'de> for Architecture { + fn deserialize>(deserializer: D) -> Result { + 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>(deserializer: D) -> Result { + 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>(deserializer: D) -> Result { + 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)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(deny_unknown_fields)] pub struct MsiPostcondition { pub product_code: String, @@ -52,7 +87,7 @@ pub struct MsiPostcondition { pub payload_sha256: String, pub payload_bytes: u64, } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(deny_unknown_fields)] pub struct WindowsMsiRecipe { pub schema_version: u32, @@ -72,7 +107,7 @@ pub struct WindowsMsiRecipe { #[serde(default, skip_serializing_if = "Option::is_none")] pub predecessor: Option, } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(deny_unknown_fields)] pub struct ResolvedWindowsMsi { pub recipe: WindowsMsiRecipe, @@ -174,6 +209,107 @@ mod tests { } } #[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 = [ + "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::(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::(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::(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(); diff --git a/crates/server/src/agent_artifacts.rs b/crates/server/src/agent_artifacts.rs index 455f95d..22529fc 100644 --- a/crates/server/src/agent_artifacts.rs +++ b/crates/server/src/agent_artifacts.rs @@ -36,13 +36,20 @@ pub async fn download( return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")); } let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?; - let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying','awaiting_reboot') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL").bind(a).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?; + let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying','awaiting_reboot') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL").bind(a).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?; let job: JobPayload = serde_json::from_slice(&row.get::, _>("payload"))?; let plan_bytes: Vec = row.get("plan_payload"); if rmm_domain::jobs::hash(&plan_bytes) != row.get::("plan_hash") { return Err(Error(StatusCode::CONFLICT, "PLAN_HASH_MISMATCH")); } let plan: PlanPayload = serde_json::from_slice(&plan_bytes)?; + if job.action.windows_msi().is_some() { + crate::windows_msi_catalog::validate_job_binding(&plan, &job)?; + crate::catalog::check(&mut tx, &job.action).await?; + crate::root_policy::authorize(&mut tx, &plan.principal, &job).await?; + crate::root_policy::authorize(&mut tx, &row.get::("approver"), &job).await?; + } + if job.asset_id != row.get::("asset_id") || job.enrollment_generation != row.get::("enrollment_generation") as u64 || job.assignment_version != row.get::("assignment_version") as u64 diff --git a/crates/server/src/catalog.rs b/crates/server/src/catalog.rs index 3716eb1..413f513 100644 --- a/crates/server/src/catalog.rs +++ b/crates/server/src/catalog.rs @@ -24,6 +24,10 @@ pub struct AptRecipe { } pub fn routes(r: Router) -> Router { r.route( + "/api/v1/tenants/{tenant}/windows-msi-recipes", + get(crate::windows_msi_catalog::list).post(crate::windows_msi_catalog::import), + ) + .route( "/api/v1/tenants/{tenant}/package-recipes", get(list).post(import), ) @@ -43,6 +47,15 @@ pub async fn references( tx: &mut Transaction<'_, Postgres>, action: &rmm_domain::jobs::Action, ) -> Result, Error> { + if let Some(manifest) = action.windows_msi() { + if !action.validate() { + return Err(Error( + StatusCode::BAD_REQUEST, + "INVALID_WINDOWS_MSI_MANIFEST", + )); + } + return crate::windows_msi_catalog::references(tx, manifest).await; + } let manifest = match action { rmm_domain::jobs::Action::EnsurePackage { apt_manifest: Some(m), @@ -138,7 +151,7 @@ pub async fn references( references.dedup(); Ok(references) } -async fn context<'a>( +pub(crate) async fn context<'a>( s: &'a crate::State, h: &HeaderMap, t: Uuid, @@ -182,6 +195,7 @@ pub async fn import( installation_context: recipe.installation_context.clone(), recipe_id: None, apt_manifest: None, + windows_msi_manifest: None, }; if recipe.schema_version != 1 || recipe.reboot_policy != "never" diff --git a/crates/server/src/job_gateway.rs b/crates/server/src/job_gateway.rs index e486aca..4aa690a 100644 --- a/crates/server/src/job_gateway.rs +++ b/crates/server/src/job_gateway.rs @@ -491,6 +491,9 @@ pub async fn permit( let payload: JobPayload = serde_json::from_slice(&row.get::, _>("payload"))?; let plan: PlanPayload = serde_json::from_slice(&row.get::, _>("plan_payload"))?; let capabilities: Vec = serde_json::from_value(row.get("capabilities"))?; + if crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err() { + return Ok(denied("WINDOWS_MSI_BINDING_MISMATCH")); + } if row.get::("bound_asset") != payload.asset_id || !payload .action @@ -736,6 +739,20 @@ pub async fn next( }; let payload: JobPayload = serde_json::from_slice(&row.get::, _>("payload"))?; let caps: Vec = serde_json::from_value(row.get("capabilities"))?; + if payload.action.windows_msi().is_some() { + let raw: Vec = row.get("plan_payload"); + let plan: PlanPayload = serde_json::from_slice(&raw)?; + if hash(&raw) != row.get::("plan_hash") + || crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err() + || crate::catalog::check(&mut tx, &payload.action) + .await + .is_err() + { + tx.commit().await?; + return Ok(None); + } + } + if !payload .action .available_for(&payload.execution_identity, &caps) diff --git a/crates/server/src/jobs.rs b/crates/server/src/jobs.rs index cae4ce2..5eeeb6c 100644 --- a/crates/server/src/jobs.rs +++ b/crates/server/src/jobs.rs @@ -181,6 +181,12 @@ struct WebParameters { recipe_version: Option, recipe_id: Option, apt_manifest: Option, + #[serde( + default, + deserialize_with = "rmm_domain::jobs::deserialize_windows_msi_manifest" + )] + #[schemars(with = "rmm_domain::windows_execution::ResolvedWindowsMsi")] + windows_msi_manifest: Option>, installation_context: Option, packages: Option>, reboot_policy: Option, @@ -205,6 +211,9 @@ impl PlanRequest { return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")); } let p = w.parameters; + if p.windows_msi_manifest.is_some() && w.action != "ensure_package" { + return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")); + } let required = |value: Option| value.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")); let action = match w.action.as_str() { @@ -251,6 +260,7 @@ impl PlanRequest { installation_context: required(p.installation_context)?, recipe_id: p.recipe_id, apt_manifest: p.apt_manifest, + windows_msi_manifest: p.windows_msi_manifest, }, "apply_updates" => Action::ApplyUpdates { provider: required(p.provider)?, @@ -435,6 +445,14 @@ pub async fn plan( { return Err(Error(StatusCode::FORBIDDEN, "ROOT_IDENTITY_REQUIRED")); } + if input.action.windows_msi().is_some() + && (input.execution_identity != "system" || !input.artifact_ids.is_empty()) + { + return Err(Error( + StatusCode::BAD_REQUEST, + "WINDOWS_MSI_EXACT_ARTIFACT_REQUIRED", + )); + } // Conservative policy: reboot is always serial, no provider-triggered reboot. if matches!(input.action, Action::Reboot { .. }) && input.rollout.max_parallel != 1 { return Err(fail("POLICY_DENIED")); @@ -458,7 +476,11 @@ pub async fn plan( crate::permissions::require_principal(&mut tx, p, "logs:read").await?; } let recipe_references = crate::catalog::references(&mut tx, &input.action).await?; - let artifacts = crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?; + let artifacts = if input.action.windows_msi().is_some() { + crate::windows_msi_catalog::automatic_artifacts(&mut tx, tenant, &input.action).await? + } else { + crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await? + }; let mut jobs = Vec::new(); for asset in ids { let rows=sqlx::query("SELECT agent_id,enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE asset_id=$1 AND revoked_at IS NULL ORDER BY agent_id FOR SHARE").bind(asset).fetch_all(&mut *tx).await?; @@ -531,6 +553,7 @@ pub async fn plan( recipe_references, artifact_references, }; + crate::windows_msi_catalog::validate_plan_bindings(&payload)?; let bytes = encode(&payload)?; let plan_hash = hash(&bytes); sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(payload.plan_id).bind(&p.name).bind(&bytes).bind(&plan_hash).bind(input.schedule.start_before).execute(&mut *tx).await?; @@ -565,6 +588,7 @@ async fn load_plan( Ok((serde_json::from_slice(&bytes)?, h, bytes)) } async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> { + crate::windows_msi_catalog::validate_plan_bindings(plan)?; policy(tx).await?; let current_artifacts = crate::catalog::resolve_artifacts( tx, @@ -1511,6 +1535,188 @@ mod windows_contract_tests { "FORBIDDEN" ); tx.rollback().await.unwrap(); + // MSI metadata only: real migration/RLS/FKs and pending-only planning. + // This ignored test runs alone in the dedicated isolated PostgreSQL process. + // Opaque bytes deliberately are NOT an authored/installed MSI fixture. + use crate::artifact_store::ArtifactStore; + use std::os::unix::fs::PermissionsExt; + let key_path = temp.join("key.pem"); + let policy_path = temp.join("system-msi.json"); + let settings = [ + ("RMM_PROFILE", "development".to_string()), + ("RMM_JOB_KEY_FILE", key_path.display().to_string()), + ("RMM_DEV_SYSTEM_ENABLED", "true".to_string()), + ( + "RMM_DEV_SYSTEM_POLICY_FILE", + policy_path.display().to_string(), + ), + ]; + let previous = settings + .iter() + .map(|(key, _)| (*key, std::env::var_os(key))) + .collect::>(); + for (key, value) in &settings { + unsafe { + std::env::set_var(key, value); + } + } + let artifact_id = Uuid::new_v4(); + let opaque = b"metadata-contract-not-an-executable-msi"; + let artifact_sha = crate::catalog::store() + .unwrap() + .put(tenant, opaque) + .unwrap(); + let manifest = crate::windows_msi_catalog::test_manifest( + artifact_id, + &artifact_sha, + opaque.len() as u64, + ); + let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant) + .await + .unwrap(); + sqlx::query("INSERT INTO artifacts(tenant_id,artifact_id,sha256,size_bytes,media_type) VALUES($1,$2,$3,$4,'application/octet-stream')") + .bind(tenant).bind(artifact_id).bind(&artifact_sha).bind(opaque.len() as i64).execute(&mut *tx).await.unwrap(); + let catalog_id = crate::windows_msi_catalog::store_recipe(&mut tx, tenant, &manifest) + .await + .unwrap(); + tx.commit().await.unwrap(); + let other = Uuid::new_v4(); + sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'other MSI tenant')") + .bind(other) + .execute(&admin) + .await + .unwrap(); + let mut foreign = rmm_persistence::tenant_tx(&state.pool, other) + .await + .unwrap(); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM windows_msi_recipes") + .fetch_one(&mut *foreign) + .await + .unwrap(); + assert_eq!(count, 0); + assert!( + crate::windows_msi_catalog::references(&mut foreign, &manifest) + .await + .is_err() + ); + foreign.rollback().await.unwrap(); + let row=sqlx::query("INSERT INTO windows_msi_recipes(tenant_id,catalog_id,recipe_id,recipe_version,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes,payload) VALUES($1,$2,$3,'1',$4,$5,$6,$7,$8)") + .bind(other).bind(Uuid::new_v4()).bind(&manifest.recipe.recipe_id).bind(&manifest.recipe_sha256) + .bind(artifact_id).bind(&artifact_sha).bind(opaque.len() as i64).bind(encode(&manifest.recipe).unwrap()).execute(&admin).await; + assert!(row.is_err()); // database-level composite tenant/artifact FK + assert!( + sqlx::query("UPDATE windows_msi_recipes SET recipe_sha256=$2 WHERE catalog_id=$1") + .bind(catalog_id) + .bind("cd".repeat(32)) + .execute(&admin) + .await + .is_err() + ); + assert!( + sqlx::query("DELETE FROM windows_msi_recipes WHERE catalog_id=$1") + .bind(catalog_id) + .execute(&admin) + .await + .is_err() + ); + sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'system:execute') WHERE tenant_id=$1 AND principal=$2").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap(); + let caps = json!([ + "windows.base/1", + "rmm.sync.v1", + "helper.system.v1", + "ensure_package", + "system:ensure_package", + rmm_domain::windows_execution::MSI_CAPABILITY, + format!("helper.policy.sha256:{}", "ab".repeat(32)), + format!("helper.binary.sha256:{}", "cd".repeat(32)) + ]); + sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1") + .bind(agents[1]) + .bind(&caps) + .execute(&admin) + .await + .unwrap(); + let system = json!({"schema_version":2,"profile":"development","expires_at":Utc::now()+Duration::minutes(10),"scopes":[{ + "tenant_id":tenant,"asset_id":assets[1],"agent_id":agents[1],"enrollment_generation":1,"assignment_version":1, + "principals":[principal.name],"helper_policy_sha256":"ab".repeat(32),"helper_binary_sha256":"cd".repeat(32), + "acceptance_evidence_id":Uuid::new_v4(),"allowed_services":[],"max_runtime_seconds":120,"allowed_msi_recipe_sha256":[manifest.recipe_sha256]}]}); + std::fs::write(&policy_path, encode(&system).unwrap()).unwrap(); + std::fs::set_permissions(&policy_path, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut package = input(); + package.targets.asset_ids = vec![assets[1]]; + package.script_variants.clear(); + package.execution_identity = "system".into(); + package.action = crate::windows_msi_catalog::test_action(manifest.clone()); + package.max_runtime_seconds = 30; + package.max_output_bytes = 4096; + let mut extra = package.clone(); + extra.artifact_ids = vec![artifact_id]; + assert_eq!( + plan(&state, &principal, tenant, extra).await.unwrap_err().1, + "WINDOWS_MSI_EXACT_ARTIFACT_REQUIRED" + ); + let view = plan(&state, &principal, tenant, package).await.unwrap(); + let package_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap(); + let raw: Vec = + sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1") + .bind(package_id) + .fetch_one(&admin) + .await + .unwrap(); + let fixed: PlanPayload = serde_json::from_slice(&raw).unwrap(); + assert_eq!(fixed.artifact_references.len(), 1); + assert_eq!( + fixed.artifact_references[0].artifact.artifact_id, + artifact_id + ); + let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant) + .await + .unwrap(); + recheck(&mut tx, &fixed).await.unwrap(); + tx.rollback().await.unwrap(); + for case in 0..4 { + let mut bad = fixed.clone(); + match case { + 0 => bad.artifact_references.clear(), + 1 => bad + .artifact_references + .push(bad.artifact_references[0].clone()), + 2 => bad.artifact_references[0].artifact.size_bytes += 1, + _ => bad.artifact_references[0].artifact.artifact_id = Uuid::new_v4(), + }; + let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant) + .await + .unwrap(); + assert!(recheck(&mut tx, &bad).await.is_err()); + tx.rollback().await.unwrap(); + } + let pending = submit( + &state, + &principal, + tenant, + package_id, + Submit { + idempotency_key: "fixed-msi-metadata".into(), + }, + ) + .await + .unwrap(); + assert_eq!(pending["approval_state"], "pending_approval"); + assert_eq!(pending["job_count"], 0); + sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'system:execute') WHERE tenant_id=$1 AND principal=$2").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap(); + let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant) + .await + .unwrap(); + assert_eq!(recheck(&mut tx, &fixed).await.unwrap_err().1, "FORBIDDEN"); + tx.rollback().await.unwrap(); + for (key, value) in previous { + unsafe { + match value { + Some(value) => std::env::set_var(key, value), + None => std::env::remove_var(key), + } + } + } let counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM jobs WHERE tenant_id=$1),(SELECT count(*) FROM outbox WHERE tenant_id=$1),(SELECT count(*) FROM execution_permits WHERE tenant_id=$1)").bind(tenant).fetch_one(&admin).await.unwrap(); assert_eq!(counts, (0, 0, 0)); let after: Vec = diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index 5e47fc8..042ce15 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -21,6 +21,7 @@ mod root_policy; mod scheduler; mod synchronization; mod tls; +mod windows_msi_catalog; mod windows_policy; use anyhow::{Context, Result, ensure}; diff --git a/crates/server/src/windows_msi_catalog.rs b/crates/server/src/windows_msi_catalog.rs new file mode 100644 index 0000000..d273c89 --- /dev/null +++ b/crates/server/src/windows_msi_catalog.rs @@ -0,0 +1,380 @@ +//! Immutable tenant MSI recipe/one-artifact binding. Catalog import is metadata, +//! never job approval, helper provisioning, an installer, or a capability grant. +use crate::{jobs::Error, pagination}; +use axum::{ + Json, + extract::{Path, Query, State}, + http::{HeaderMap, StatusCode}, +}; +use rmm_domain::{ + jobs::{Action, ArtifactReference, JobPayload, PlanPayload, RecipeReference, encode, hash}, + windows_execution::{MSI_PACKAGE_ID, ResolvedWindowsMsi, WindowsMsiRecipe}, +}; +use serde_json::{Value, json}; +use sqlx::{Postgres, Row, Transaction}; +use uuid::Uuid; +fn conflict() -> Error { + Error(StatusCode::CONFLICT, "WINDOWS_MSI_BINDING_MISMATCH") +} +fn reference(m: &ResolvedWindowsMsi) -> RecipeReference { + RecipeReference { + package: MSI_PACKAGE_ID.into(), + version: m.recipe.postcondition.product_version.clone(), + architecture: "x64".into(), + recipe_version: m.recipe.recipe_version.clone(), + sha256: m.recipe_sha256.clone(), + } +} +fn artifact(m: &ResolvedWindowsMsi) -> ArtifactReference { + ArtifactReference { + artifact_id: m.recipe.artifact.artifact_id, + sha256: m.recipe.artifact.sha256.clone(), + size_bytes: m.recipe.artifact.bytes, + } +} +async fn checked( + tx: &mut Transaction<'_, Postgres>, + m: &ResolvedWindowsMsi, +) -> Result<(Uuid, ArtifactReference), Error> { + if !m.validate() { + return Err(Error( + StatusCode::BAD_REQUEST, + "INVALID_WINDOWS_MSI_MANIFEST", + )); + } + // Catalog rows cannot be updated/deleted. Avoid a row lock here: PostgreSQL + // requires UPDATE privilege for FOR SHARE, which this immutable reader lacks. + let row=sqlx::query("SELECT tenant_id,payload,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes FROM windows_msi_recipes WHERE recipe_id=$1 AND recipe_version=$2") + .bind(&m.recipe.recipe_id).bind(&m.recipe.recipe_version).fetch_optional(&mut **tx).await? + .ok_or(Error(StatusCode::CONFLICT,"WINDOWS_MSI_RECIPE_NOT_CONFIGURED"))?; + let bytes: Vec = row.get("payload"); + let a = artifact(m); + if encode(&m.recipe)? != bytes + || hash(&bytes) != m.recipe_sha256 + || row.get::("recipe_sha256") != m.recipe_sha256 + || row.get::("artifact_id") != a.artifact_id + || row.get::("artifact_sha256") != a.sha256 + || row.get::("artifact_bytes") as u64 != a.size_bytes + { + return Err(conflict()); + } + let tenant: Uuid = row.get("tenant_id"); + let actual = crate::catalog::resolve_artifacts(tx, tenant, &[a.artifact_id]).await?; + if actual != [a.clone()] { + return Err(conflict()); + } + Ok((tenant, a)) +} +pub async fn references( + tx: &mut Transaction<'_, Postgres>, + m: &ResolvedWindowsMsi, +) -> Result, Error> { + checked(tx, m).await?; + Ok(vec![reference(m)]) +} +pub async fn automatic_artifacts( + tx: &mut Transaction<'_, Postgres>, + tenant: Uuid, + action: &Action, +) -> Result, Error> { + let m = action.windows_msi().ok_or_else(conflict)?; + if !action.validate() { + return Err(conflict()); + } + let (actual, a) = checked(tx, m).await?; + if actual != tenant { + return Err(conflict()); + } + Ok(vec![a]) +} +/// Set equality/count checks are deliberate. contains()/dedup() would accept +/// missing, additional, or duplicate per-attempt Windows artifact authorizations. +pub fn validate_plan_bindings(plan: &PlanPayload) -> Result<(), Error> { + let mut has_msi = false; + let mut recipes = Vec::new(); + for job in &plan.jobs { + let Some(m) = job.payload.action.windows_msi() else { + continue; + }; + has_msi = true; + recipes.push(reference(m)); + if !job.payload.action.validate() + || job.payload.execution_identity != "system" + || !job.payload.action.valid_job_limits( + job.payload.max_runtime_seconds, + job.payload.max_output_bytes, + ) + || plan.tenant_id != job.payload.tenant_id + || plan + .jobs + .iter() + .filter(|other| { + other.payload.job_id == job.payload.job_id + && other.payload.attempt_id == job.payload.attempt_id + }) + .count() + != 1 + { + return Err(conflict()); + } + let refs = plan + .artifact_references + .iter() + .filter(|r| r.job_id == job.payload.job_id && r.attempt_id == job.payload.attempt_id) + .collect::>(); + if refs.len() != 1 + || refs[0].artifact != artifact(m) + || plan + .recipe_references + .iter() + .filter(|r| **r == reference(m)) + .count() + != 1 + { + return Err(conflict()); + } + } + if has_msi { + recipes.sort(); + recipes.dedup(); + // A package plan resolves one common MSI action for all its targets. + // Never accept extra recipe authority or a mixed-action plan at a later + // delivery/permit/download boundary merely because contains() succeeds. + if recipes != plan.recipe_references + || plan + .jobs + .iter() + .any(|j| j.payload.action.windows_msi().is_none()) + || plan.artifact_references.iter().any(|r| { + !plan + .jobs + .iter() + .any(|j| j.payload.job_id == r.job_id && j.payload.attempt_id == r.attempt_id) + }) + { + return Err(conflict()); + } + } + Ok(()) +} +pub fn validate_job_binding(plan: &PlanPayload, job: &JobPayload) -> Result<(), Error> { + if job.action.windows_msi().is_none() { + return Ok(()); + } + validate_plan_bindings(plan)?; + let bytes = encode(job)?; + let matches = plan + .jobs + .iter() + .filter(|j| j.payload.job_id == job.job_id && j.payload.attempt_id == job.attempt_id) + .collect::>(); + if matches.len() != 1 + || matches[0].job_payload_hash != hash(&bytes) + || encode(&matches[0].payload)? != bytes + { + return Err(conflict()); + } + Ok(()) +} +pub(crate) async fn store_recipe( + tx: &mut Transaction<'_, Postgres>, + t: Uuid, + m: &ResolvedWindowsMsi, +) -> Result { + if !m.validate() { + return Err(Error( + StatusCode::BAD_REQUEST, + "INVALID_WINDOWS_MSI_MANIFEST", + )); + } + let actual = crate::catalog::resolve_artifacts(tx, t, &[m.recipe.artifact.artifact_id]).await?; + if actual != [artifact(m)] { + return Err(conflict()); + } + let bytes = encode(&m.recipe)?; + if bytes.len() > 65536 { + return Err(Error(StatusCode::PAYLOAD_TOO_LARGE, "QUOTA_EXCEEDED")); + } + let id = Uuid::new_v4(); + sqlx::query("INSERT INTO windows_msi_recipes(tenant_id,catalog_id,recipe_id,recipe_version,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes,payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)") + .bind(t).bind(id).bind(&m.recipe.recipe_id).bind(&m.recipe.recipe_version).bind(&m.recipe_sha256) + .bind(m.recipe.artifact.artifact_id).bind(&m.recipe.artifact.sha256).bind(m.recipe.artifact.bytes as i64).bind(bytes).execute(&mut **tx).await?; + Ok(id) +} +pub async fn import( + State(s): State, + h: HeaderMap, + Path(t): Path, + Json(m): Json, +) -> Result, Error> { + let (p, mut tx) = crate::catalog::context(&s, &h, t, true).await?; + let id = store_recipe(&mut tx, t, &m).await?; + sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'windows_msi_recipe_imported',$4,now())") + .bind(t) + .bind(Uuid::new_v4()) + .bind(p.name) + .bind( + json!({"catalog_id":id,"recipe_id":m.recipe.recipe_id,"recipe_sha256":m.recipe_sha256, + "artifact_id":m.recipe.artifact.artifact_id,"testsimulation":p.testsimulation}), + ) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(Json( + json!({"catalog_id":id,"recipe_id":m.recipe.recipe_id,"sha256":m.recipe_sha256,"manifest":m}), + )) +} +pub async fn list( + State(s): State, + h: HeaderMap, + Path(t): Path, + Query(query): Query, +) -> Result, Error> { + let (p, mut tx) = crate::catalog::context(&s, &h, t, false).await?; + let mut page = pagination::Cursor::parse(&s, &p, "catalog:windows-msi:catalog_id:asc", query) + .map_err(|status| Error(status, "VALIDATION_ERROR"))?; + let rows=sqlx::query("SELECT catalog_id,payload,recipe_sha256 FROM windows_msi_recipes WHERE catalog_id>$1 AND created_at<=$2 ORDER BY catalog_id LIMIT $3") + .bind(page.last).bind(page.as_of).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?; + let truncated = rows.len() > usize::from(page.limit); + let next = if truncated { + Some( + page.next(&s, rows[usize::from(page.limit) - 1].get("catalog_id")) + .map_err(|status| Error(status, "VALIDATION_ERROR"))?, + ) + } else { + None + }; + let mut items = Vec::new(); + for row in rows.iter().take(usize::from(page.limit)) { + let bytes: Vec = row.get("payload"); + let m = ResolvedWindowsMsi { + recipe: serde_json::from_slice::(&bytes)?, + recipe_sha256: row.get("recipe_sha256"), + }; + if !m.validate() || encode(&m.recipe)? != bytes { + return Err(conflict()); + } + items.push(json!({"catalog_id":row.get::("catalog_id"),"recipe_id":m.recipe.recipe_id,"sha256":m.recipe_sha256,"manifest":m})); + } + tx.commit().await?; + Ok(Json( + json!({"items":items,"next_cursor":next,"completeness":if truncated{"partial"}else{"complete"},"truncated":truncated,"as_of":page.as_of}), + )) +} + +#[cfg(test)] +pub(crate) fn test_manifest(id: Uuid, sha: &str, bytes: u64) -> ResolvedWindowsMsi { + use rmm_domain::windows_execution::*; + let recipe = 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: id, + sha256: sha.into(), + bytes, + }, + postcondition: 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, + }, + no_reboot: true, + package_code: None, + predecessor: None, + }; + ResolvedWindowsMsi { + recipe_sha256: recipe.sha256().unwrap(), + recipe, + } +} +#[cfg(test)] +pub(crate) fn test_action(m: ResolvedWindowsMsi) -> Action { + Action::EnsurePackage { + provider: "msi".into(), + package: MSI_PACKAGE_ID.into(), + version: m.recipe.postcondition.product_version.clone(), + architecture: "x64".into(), + recipe_version: m.recipe.recipe_version.clone(), + installation_context: "machine".into(), + recipe_id: Some(m.recipe.recipe_id.clone()), + apt_manifest: None, + windows_msi_manifest: Some(Box::new(m)), + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exact_per_attempt_artifact_set_never_deduplicates_missing_extra_or_foreign_authority() { + use rmm_domain::jobs::{JobArtifactReference, PlannedJob}; + let id = Uuid::new_v4(); + let now = chrono::Utc::now(); + let m = test_manifest(Uuid::new_v4(), &"ab".repeat(32), 32); + let job = JobPayload { + schema_version: 1, + tenant_id: id, + asset_id: id, + agent_id: id, + enrollment_generation: 1, + assignment_version: 1, + job_id: Uuid::new_v4(), + attempt_id: Uuid::new_v4(), + action: test_action(m.clone()), + execution_identity: "system".into(), + not_before: now, + start_before: now + chrono::Duration::minutes(1), + max_runtime_seconds: 30, + max_output_bytes: 4096, + }; + let plan = PlanPayload { + schema_version: 1, + plan_id: Uuid::new_v4(), + tenant_id: id, + principal: "test".into(), + reason: "metadata only".into(), + jobs: vec![PlannedJob { + job_payload_hash: hash(&encode(&job).unwrap()), + payload: job.clone(), + script_sha256: None, + }], + max_parallel: 1, + halt_after_failures: 1, + recipe_references: vec![reference(&m)], + artifact_references: vec![JobArtifactReference { + job_id: job.job_id, + attempt_id: job.attempt_id, + artifact: artifact(&m), + }], + }; + validate_job_binding(&plan, &job).unwrap(); + for case in 0..9 { + let mut bad = plan.clone(); + match case { + 0 => bad.artifact_references.clear(), + 1 => bad + .artifact_references + .push(bad.artifact_references[0].clone()), + 2 => bad.artifact_references[0].artifact.artifact_id = Uuid::new_v4(), + 3 => bad.artifact_references[0].artifact.size_bytes += 1, + 4 => bad.artifact_references[0].attempt_id = Uuid::new_v4(), + 5 => bad.jobs[0].payload.max_output_bytes += 1, + 6 => bad.recipe_references.clear(), + 7 => bad.recipe_references.push(bad.recipe_references[0].clone()), + _ => { + let mut extra = bad.recipe_references[0].clone(); + extra.sha256 = "ef".repeat(32); + bad.recipe_references.push(extra); + } + } + assert!(validate_job_binding(&bad, &job).is_err()); + } + } +} diff --git a/crates/server/src/windows_policy.rs b/crates/server/src/windows_policy.rs index dcf8e6d..4bfbeec 100644 --- a/crates/server/src/windows_policy.rs +++ b/crates/server/src/windows_policy.rs @@ -37,8 +37,16 @@ struct SystemScope { // Administrative evidence pin, never an approval or authorization ID. acceptance_evidence_id: Uuid, allowed_services: Vec, + #[serde(default, deserialize_with = "strict_optional_hashes")] + allowed_msi_recipe_sha256: Option>, max_runtime_seconds: u32, } +fn strict_optional_hashes<'de, D>(deserializer: D) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, +{ + Vec::::deserialize(deserializer).map(Some) +} fn digest(value: &str) -> bool { value.len() == 64 && value @@ -86,9 +94,27 @@ impl SystemScope { .collect::>() .len() == self.allowed_services.len() + && self + .allowed_msi_recipe_sha256 + .as_ref() + .is_none_or(|hashes| { + hashes.len() <= 2 + && hashes.iter().all(|h| digest(h)) + && hashes + .iter() + .collect::>() + .len() + == hashes.len() + }) && (1..=120).contains(&self.max_runtime_seconds) } - fn permits(&self, principal: &str, job: &JobPayload, capabilities: &[String]) -> bool { + fn permits( + &self, + principal: &str, + job: &JobPayload, + capabilities: &[String], + allow_msi: bool, + ) -> bool { let has = |cap: &str| capabilities.iter().any(|c| c == cap); self.valid() && job.execution_identity == "system" @@ -110,17 +136,40 @@ impl SystemScope { "helper.binary.sha256:{}", self.helper_binary_sha256 )) - && has("system:set_service_state") - && has("set_service_state") && (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds) && (1..=65536).contains(&job.max_output_bytes) - && matches!(&job.action,Action::SetServiceState{unit,state} - if self.allowed_services.contains(unit) && matches!(state.as_str(),"running"|"stopped")) + && match &job.action { + Action::SetServiceState { unit, state } => { + self.allowed_services.contains(unit) + && matches!(state.as_str(), "running" | "stopped") + && has("system:set_service_state") + && has("set_service_state") + } + _ if allow_msi => job.action.windows_msi().is_some_and(|m| { + job.action.validate() + && job + .action + .valid_job_limits(job.max_runtime_seconds, job.max_output_bytes) + && self + .allowed_msi_recipe_sha256 + .as_ref() + .is_some_and(|hashes| hashes.contains(&m.recipe_sha256)) + && has("ensure_package") + && has("system:ensure_package") + && has(rmm_domain::windows_execution::MSI_CAPABILITY) + }), + _ => false, + } } } impl SystemPolicy { fn valid(&self, now: DateTime) -> bool { - self.schema_version == 1 + matches!(self.schema_version, 1 | 2) + && (self.schema_version == 2 + || self + .scopes + .iter() + .all(|scope| scope.allowed_msi_recipe_sha256.is_none())) && self.profile == "development" && self.expires_at > now && !self.scopes.is_empty() @@ -138,7 +187,7 @@ impl SystemPolicy { && self .scopes .iter() - .any(|scope| scope.permits(principal, job, capabilities)) + .any(|scope| scope.permits(principal, job, capabilities, self.schema_version == 2)) } } fn disabled() -> Error { @@ -410,6 +459,29 @@ mod tests { assert!(serde_json::from_value::(invalid).is_err()); } #[test] + fn only_explicit_v2_hash_scope_and_package_caps_allow_fixed_msi() { + let (mut policy, mut job, mut caps) = fixture(); + let m = crate::windows_msi_catalog::test_manifest(Uuid::new_v4(), &"ab".repeat(32), 32); + job.action = crate::windows_msi_catalog::test_action(m.clone()); + caps.extend([ + "ensure_package".into(), + "system:ensure_package".into(), + rmm_domain::windows_execution::MSI_CAPABILITY.into(), + ]); + assert!(!policy.permits("selected", &job, &caps, Utc::now())); + policy.scopes[0].allowed_msi_recipe_sha256 = Some(vec![m.recipe_sha256.clone()]); + assert!(!policy.permits("selected", &job, &caps, Utc::now())); // v1 remains SCM-only + policy.schema_version = 2; + assert!(policy.permits("selected", &job, &caps, Utc::now())); + for index in caps.len() - 3..caps.len() { + let mut short = caps.clone(); + short.remove(index); + assert!(!policy.permits("selected", &job, &short, Utc::now())); + } + policy.scopes[0].allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]); + assert!(!policy.permits("selected", &job, &caps, Utc::now())); + } + #[test] fn policy_file_refuses_symlinks_public_mode_wrong_owner_and_writable_parent() { use std::os::unix::fs::symlink; let directory = std::env::temp_dir().join(format!("rmm-windows-policy-{}", Uuid::new_v4())); diff --git a/docs/development.md b/docs/development.md index 4af9fae..362a4d6 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,6 +1,6 @@ # Linux-first-Entwicklung und reale VM-Abnahme -Stand: 2026-11-14 · Spezifikation 1.18. Das begrenzte Linux-MVP ist inzwischen +Stand: 2026-11-14 · Spezifikation 1.19. Das begrenzte Linux-MVP ist inzwischen dokumentiert abgenommen; aktuelle Nachweise stehen in [handover.md](handover.md). Die getrennte Windows-SYSTEM-Grenze ist in Spezifikation0.1 und [windows-system-policy.md](windows-system-policy.md) präzisiert; Quellen-/Build- diff --git a/docs/project-decisions.md b/docs/project-decisions.md index a84d90e..ea389df 100644 --- a/docs/project-decisions.md +++ b/docs/project-decisions.md @@ -1,6 +1,27 @@ # Verbindliche Projektentscheidungen -Stand: **2026-11-14**, Spezifikation **1.18** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. +Stand: **2026-11-14**, Spezifikation **1.19** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung. + +## Enger Windows-M4-MSI-Schnitt (Version1.19) + +Die beauftragte Windows-MVP-Fortsetzung erhält als nächsten getrennten Schnitt +zwei feste eigene MSI-Rezepte1.0 und1.0→1.1. Dies ist eine explizite technische +Präzisierung innerhalb des bereits beauftragten M4-Umfangs, keine neue pauschale +Userfreigabe für Paketwirkungen. Kapitel0 bindet vollständiges optionales +Windowsmanifest, unveränderlichen Tenantkatalog, exakte automatisch abgeleitete +Job-/Versuch-/Artefaktreferenz, neue getrennte SYSTEM-Paketerlaubnis und sichtbare +Planbytes. Alte SCM-only-Policies erteilen keine Paketrechte. Native +Installation/Upgrade/Noop bleiben jeweils eigene WebUI-genehmigte Jobs. + +APT-/Windowsmanifest schließen sich aus; alte Linuxbytes und freie Linux- +Artefaktpfade behalten ihre bisherigen Verträge. Kein freier Installer oder +Rezeptargumentvektor, kein Repair/Downgrade/Fresh1.1, keine EXE-/Skript-/Reboot- +Erlaubnis in diesem Schnitt. Cache-/Provider-/Installerwirkung bleibt bei +Abandon ausgeschlossen. Noop und tatsächliche Nachbedingungen müssen innerhalb +des ursprünglichen Budgets unter gültigem Clock-/Fence-/Abbruchkontext liegen. +Ein später belegter Zustand heilt keinen Timeout. Die ursprünglichen MSI- +Artefakt- und Nativeberichte bleiben unverändert. Quelle/Build/Unitnachweis +öffnet keine Capability und ist keine tatsächliche Paketabnahme. ## Begrenzte Windowsfreigaben des Users (Version1.18) diff --git a/docs/windows-msi-integration.md b/docs/windows-msi-integration.md new file mode 100644 index 0000000..0d97250 --- /dev/null +++ b/docs/windows-msi-integration.md @@ -0,0 +1,54 @@ +# Windows-M4: Domain und Backend + +Stand2026-11-14, Spezifikation1.19. Implementierter und unabhängig geprüfter +Quellenschnitt im Branch `codex/windows-msi-integration`; **kein Clouddeployment +und keine native Paketabnahme**. Die folgenden Teile ergänzen die getrennten +[MSI-Providerquellen](windows-msi11-source.md). + +`ensure_package` erhält das optionale, bei Vorhandensein strikt objektförmige +`windows_msi_manifest`. Intern Box, auf dem Draht unverändertes flaches +Rezeptobjekt; fehlend ausgelassen. Explizites Null, unbekannte Felder und +Objektformen der String-Enums werden verweigert. APT und MSI schließen sich aus. +Nur `msi`/`rmm-windows-msi-fixture`/`x64`/`machine`/SYSTEM mit exakt gebundener +Rezept-ID/-Version und gewünschter Produktversion. Alte Linux-Goldenbytes bleiben +erhalten. MSI-Jobrahmen10–120Sekunden und1024–65536Ausgabebytes. + +Eigener unveränderlicher Windows-MSI-Katalog mit Migration0014, FORCE-Tenant-RLS, +zusammengesetztem Tenant-/Artifact-ID-/SHA-/Längen-FK und bestehenden interaktiven +Katalogrechten. Import/List sind vom APT-Katalog getrennt. Pro MSI-Job/Versuch +wird genau eine Artefaktreferenz automatisch aus dem Rezept abgeleitet; freie +`artifact_ids` sind hier verboten. Fehlende, zusätzliche oder doppelte Artefakte +und abweichende gesamte Rezeptmengen werden bei Planung, Revalidation, +Zustellung, Permit und Geräte-mTLS-Download verweigert. Linux-Artefaktpfade +behalten ihre bisherigen Verträge. + +SYSTEM-Policyversion2 verlangt die eigene explizite Allowlist von höchstens +zwei vollständigen MSI-Rezepthashes, bestehende Geräte-/Principal-/Helperpins, +`system:execute` und getrennte Paketcaps. Schema1 bleibt SCM-only und verweigert +MSI. Die historische Core-Nichtstartprüfung kennt nur den zusätzlichen exakt +validierten MSI-Actiontyp; keine Missing-Row-/Signatur-/Lineageausnahme, +Installer- oder Cachewirkung durch Abandon. + +Tatsächlich lokal bestanden:118betroffene Domain-/Core-/Servertests, danach +gezielter Test der verschärften vollständigen Rezeptmenge; isolierter realer +PostgreSQL-Fall mit Migration/RLS/Tenant-FK/Immutabilität/Planreferenzmutationen +und `pending_approval` mit0Jobs/Outbox/Permits. Fehlendes `system:execute` +verweigert. Fünf bestehende Serverfälle bleiben ausdrücklich ignoriert. +Linux-Clippy einschließlich Agent/privilegiertem Helper und WindowsGNU- +System-helper-Alltargets sowie Format-/Diffprüfung bestanden. + +Der erste PG-Lauf belegte einen unnötigen `FOR SHARE`-Lock, der zusätzliche +UPDATE-Rechte erfordert hätte. Ausschließlich der Lock wurde entfernt; +Unveränderlichkeit/SELECT-/INSERT-Rechte bleiben erhalten. Fehlversuchslog +privat unverändert. Der erfolgreiche PG-Fall nutzte ausdrücklich opake +Metadaten-Testbytes, kein tatsächlich geprüftes oder installiertes MSI. +Lokaler Beleg `devstate/windows-msi-integration/local-qualification.json`, +SHA256 `b7bced0a341ffb88af8b584cbe8355ff1021add541004347f609f6136a684b74`, +bindet13Quelldateien. Unabhängiger Quellenreview ohne weiteren konkreten Blocker. + +Weiter offen: Linux-first-Nativevertragsnachweise, getrennte WebUI-Erweiterung, +Windowsdownload und geschützter SYSTEM-Cache, Helper-/Runtimeverdrahtung und +jeweils echte WebUI-genehmigte Installation/Upgrade/Noops. Keine Capability, +Helperpolicy oder Clock-/Jobkonfiguration auf der VM wurde geöffnet. Die +bisherige UI verweigert SYSTEM-Nicht-SCM-Pläne weiterhin bis zum separaten +Schnitt. Quellen/Units sind keine Paketfreigabe. diff --git a/migrations/0014_windows_msi_catalog.sql b/migrations/0014_windows_msi_catalog.sql new file mode 100644 index 0000000..910ffe3 --- /dev/null +++ b/migrations/0014_windows_msi_catalog.sql @@ -0,0 +1,27 @@ +-- Additive immutable tenant catalog; existing APT recipes/artifact semantics stay. +ALTER TABLE artifacts ADD CONSTRAINT artifacts_tenant_identity_digest + UNIQUE (tenant_id,artifact_id,sha256,size_bytes); +CREATE TABLE windows_msi_recipes ( + tenant_id uuid NOT NULL REFERENCES tenants, + catalog_id uuid NOT NULL, + recipe_id text NOT NULL CHECK(recipe_id IN ('rmm-windows-msi-fixture-install-1.0','rmm-windows-msi-fixture-upgrade-1.1')), + recipe_version text NOT NULL CHECK(recipe_version='1'), + recipe_sha256 text NOT NULL CHECK(recipe_sha256 ~ '^[0-9a-f]{64}$'), + artifact_id uuid NOT NULL, + artifact_sha256 text NOT NULL CHECK(artifact_sha256 ~ '^[0-9a-f]{64}$'), + artifact_bytes bigint NOT NULL CHECK(artifact_bytes BETWEEN 1 AND 262144), + payload bytea NOT NULL CHECK(octet_length(payload) BETWEEN 1 AND 65536), + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY(tenant_id,catalog_id), + UNIQUE(tenant_id,recipe_id,recipe_version), UNIQUE(tenant_id,recipe_sha256), + FOREIGN KEY(tenant_id,artifact_id,artifact_sha256,artifact_bytes) + REFERENCES artifacts(tenant_id,artifact_id,sha256,size_bytes) +); +ALTER TABLE windows_msi_recipes ENABLE ROW LEVEL SECURITY; +ALTER TABLE windows_msi_recipes FORCE ROW LEVEL SECURITY; +CREATE POLICY tenant_scope ON windows_msi_recipes + USING (tenant_id::text=current_setting('app.tenant_id',true)) + WITH CHECK (tenant_id::text=current_setting('app.tenant_id',true)); +GRANT SELECT, INSERT ON windows_msi_recipes TO rmm_app; +CREATE TRIGGER immutable_content BEFORE UPDATE OR DELETE ON windows_msi_recipes + FOR EACH ROW EXECUTE FUNCTION immutable_plan();