Implement bounded Windows MSI delegation with deny-only cancellation and retained installer ownership
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-14 13:53:05 +01:00
parent 66c1855056
commit 66e77ad83e
9 changed files with 996 additions and 16 deletions
+1 -1
View File
@@ -39,4 +39,4 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
cc = "=1.11.1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
+170 -5
View File
@@ -16,16 +16,67 @@ pub const ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents";
pub const DB: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite";
const ACTOR_RW: u32 = 0x0012_019f;
const SCHEMA:&str="CREATE TABLE IF NOT EXISTS system_intent_meta(id INTEGER PRIMARY KEY CHECK(id=1),file_identity BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1)),UNIQUE(job,attempt));
CREATE TABLE IF NOT EXISTS system_intent_mirrors(id TEXT PRIMARY KEY,outcome_sha256 TEXT NOT NULL,mirror_observed_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS system_intent_denial_resumes(id TEXT NOT NULL,agent_instance TEXT NOT NULL,observed_at TEXT NOT NULL,PRIMARY KEY(id,agent_instance));
CREATE TRIGGER IF NOT EXISTS system_intents_no_delete BEFORE DELETE ON system_intents BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR NOT ((NEW.phase=OLD.phase AND NEW.cancel_requested=1 AND OLD.cancel_requested IN (0,1)) OR (OLD.phase='prepared' AND NEW.phase IN ('known_no_dispatch','may_have_dispatched') AND NEW.cancel_requested=OLD.cancel_requested)) BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_delete BEFORE DELETE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_update BEFORE UPDATE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_delete BEFORE DELETE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_update BEFORE UPDATE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;";
const LEGACY_INTENTS_TABLE: &str = "CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));";
const LEGACY_MONOTONIC: &str = "CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;";
const CLAIM_RESUME: &str = "INSERT OR IGNORE INTO system_intent_denial_resumes(id,agent_instance,observed_at) VALUES(?1,?2,?3)";
fn initialize_schema(db: &mut Connection) -> Result<()> {
let exists: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='system_intents')",
[],
|r| r.get(0),
)?;
if exists {
let columns = db
.prepare("PRAGMA table_info(system_intents)")?
.query_map([], |r| r.get::<_, String>(1))?
.collect::<rusqlite::Result<Vec<_>>>()?;
if !columns.iter().any(|name| name == "cancel_requested") {
ensure!(
columns
== [
"id", "job", "attempt", "grant_id", "body", "digest", "phase"
],
"SYSTEM_INTENT_LEGACY_SCHEMA"
);
let old:String=db.query_row("SELECT sql FROM sqlite_master WHERE type='trigger' AND name='system_intents_monotonic'",[],|r|r.get(0))?;
let normalize = |s: &str| {
s.replace("IF NOT EXISTS ", "")
.trim_end_matches(';')
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
};
ensure!(
normalize(&old) == normalize(LEGACY_MONOTONIC),
"SYSTEM_INTENT_LEGACY_TRIGGER"
);
let table: String = db.query_row(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='system_intents'",
[],
|r| r.get(0),
)?;
ensure!(
normalize(&table) == normalize(LEGACY_INTENTS_TABLE),
"SYSTEM_INTENT_LEGACY_SCHEMA"
);
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
tx.execute_batch("ALTER TABLE system_intents ADD COLUMN cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1));DROP TRIGGER system_intents_monotonic;")?;
tx.execute_batch(SCHEMA)?;
tx.commit()?;
}
}
db.execute_batch(SCHEMA)?;
Ok(())
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Intent {
@@ -148,14 +199,14 @@ impl Store {
} else {
OpenFlags::SQLITE_OPEN_READ_ONLY
};
let db = Connection::open_with_flags(DB, flags)?;
let mut db = Connection::open_with_flags(DB, flags)?;
db.busy_timeout(Duration::from_millis(250))?;
if write {
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
let mode: String = db.query_row("PRAGMA journal_mode=PERSIST", [], |r| r.get(0))?;
ensure!(mode == "persist", "SYSTEM_INTENT_JOURNAL_MODE");
db.execute_batch("PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;PRAGMA journal_size_limit=1048576;")?;
db.execute_batch(SCHEMA)?;
initialize_schema(&mut db)?;
db.execute(
"INSERT OR IGNORE INTO system_intent_meta VALUES(1,?1)",
[serde_json::to_vec(&identity)?],
@@ -241,10 +292,60 @@ impl Store {
}
pub fn cancel_before_dispatch(&mut self, id: Uuid) -> Result<Phase> {
self.check()?;
self.db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[id.to_string()],
)?;
let (_, phase) = advance(&mut self.db, id, Phase::KnownNoDispatch)?;
self.check()?;
Ok(phase)
}
/// Denial only. Original phase/request/anchor never changes, even after IPC.
pub fn deny(&mut self, original: &Request, boot: Uuid) -> Result<()> {
self.check()?;
let permit: ExecutionPermitPayload = serde_json::from_slice(&original.permit_bytes)?;
let intent = self.by_grant(permit.grant_id)?;
ensure!(
serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
&& intent.original_boot_id == boot,
"SYSTEM_CANCEL_ORIGINAL_BINDING"
);
self.db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[intent.id.to_string()],
)?;
self.check()
}
/// Open a new ordinary RO connection for each observation. No long-lived
/// SQLite read transaction or immutable-mode shortcut may hide actor denial.
pub fn require_not_denied(
original: &Request,
boot: Uuid,
generation: u64,
policy: &str,
binary: &str,
) -> Result<()> {
let mut store = Self::open(false)?;
let permit: ExecutionPermitPayload = serde_json::from_slice(&original.permit_bytes)?;
let intent = store.by_grant(permit.grant_id)?;
let (_, phase) = store.load(intent.id)?;
ensure!(
serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
&& intent.original_boot_id == boot
&& intent.connection_generation == generation
&& phase == Phase::MayHaveDispatched
&& intent.policy_sha256 == policy
&& intent.helper_binary_sha256 == binary,
"SYSTEM_CANCEL_ORIGINAL_BINDING"
);
let denied: i64 = store.db.query_row(
"SELECT cancel_requested FROM system_intents WHERE id=?1",
[intent.id.to_string()],
|r| r.get(0),
)?;
ensure!(denied == 0, "SYSTEM_MSI_CANCELLED_OR_FENCED");
store.check()
}
pub fn pending(&self) -> Result<Vec<Intent>> {
let mut rows=self.db.prepare("SELECT i.id FROM system_intents i WHERE NOT EXISTS(SELECT 1 FROM system_intent_mirrors m WHERE m.id=i.id) ORDER BY i.rowid LIMIT 2")?;
let ids = rows
@@ -356,7 +457,7 @@ mod tests {
let dispatched = Uuid::new_v4();
for id in [cancelled, dispatched] {
db.execute(
"INSERT INTO system_intents VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
"INSERT INTO system_intents(id,job,attempt,grant_id,body,digest,phase) VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
[id.to_string()],
)
.unwrap();
@@ -377,6 +478,29 @@ mod tests {
advance(&mut db, dispatched, Phase::KnownNoDispatch).unwrap(),
(0, Phase::MayHaveDispatched)
);
for _ in 0..2 {
db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[dispatched.to_string()],
)
.unwrap();
}
assert_eq!(
db.query_row(
"SELECT phase,cancel_requested FROM system_intents WHERE id=?1",
[dispatched.to_string()],
|r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?))
)
.unwrap(),
("may_have_dispatched".into(), 1)
);
assert!(
db.execute(
"UPDATE system_intents SET cancel_requested=0 WHERE id=?1",
[dispatched.to_string()]
)
.is_err()
);
assert!(
db.execute(
"UPDATE system_intents SET phase='prepared' WHERE id=?1",
@@ -411,4 +535,45 @@ mod tests {
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 1);
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 0);
}
#[test]
fn additive_denial_column_preserves_original_legacy_intents_and_rejects_unknown_trigger() {
let mut db = Connection::open_in_memory().unwrap();
db.execute_batch(LEGACY_INTENTS_TABLE).unwrap();
db.execute_batch(LEGACY_MONOTONIC).unwrap();
db.execute("INSERT INTO system_intents VALUES('id','job','attempt','grant',x'0102','original','may_have_dispatched')",[]).unwrap();
initialize_schema(&mut db).unwrap();
initialize_schema(&mut db).unwrap();
assert_eq!(
db.query_row(
"SELECT body,digest,phase,cancel_requested FROM system_intents",
[],
|r| Ok((
r.get::<_, Vec<u8>>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, i64>(3)?
))
)
.unwrap(),
(
vec![1, 2],
"original".into(),
"may_have_dispatched".into(),
0
)
);
db.execute("UPDATE system_intents SET cancel_requested=1", [])
.unwrap();
assert!(
db.execute("UPDATE system_intents SET body=x'03'", [])
.is_err()
);
assert!(
db.execute("UPDATE system_intents SET cancel_requested=0", [])
.is_err()
);
let mut foreign = Connection::open_in_memory().unwrap();
foreign.execute_batch("CREATE TABLE system_intents(id,job,attempt,grant_id,body,digest,phase);CREATE TRIGGER system_intents_monotonic BEFORE UPDATE ON system_intents BEGIN SELECT 1;END;").unwrap();
assert!(initialize_schema(&mut foreign).is_err());
}
}
+130 -1
View File
@@ -470,6 +470,13 @@ fn verified_mirror_row(
Ok(outcome)
}
fn system_shape(job: &JobPayload) -> bool {
if job.action.windows_msi().is_some() {
return job.execution_identity == "system"
&& job.action.validate()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes);
}
job.execution_identity == "system"
&& (1..=120).contains(&job.max_runtime_seconds)
&& (1..=65536).contains(&job.max_output_bytes)
@@ -487,7 +494,7 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
matches!(
outcome.state.as_str(),
"succeeded" | "failed" | "cancelled" | "expired" | "unknown"
) && !outcome.reboot_required
) && (job.action.windows_msi().is_some() || !outcome.reboot_required)
&& outcome
.stdout
.len()
@@ -496,6 +503,47 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
"SYSTEM_EXECUTE_OUTCOME_SCOPE"
);
if outcome.state == "succeeded" {
if let Some(m) = job.action.windows_msi() {
let e = &outcome.evidence;
let after: crate::package::Snapshot = serde_json::from_value(e["after"].clone())?;
let noop = e["already_desired"] == true;
ensure!(
job.action.validate()
&& e["provider"] == "windows.msi.fixture/1"
&& e["recipe_sha256"] == m.recipe_sha256
&& e["artifact_sha256"] == m.recipe.artifact.sha256
&& e["postconditions_passed"] == true
&& e["state"] == "succeeded"
&& e["exit_code"] == serde_json::to_value(outcome.exit_code)?
&& e["already_desired"].is_boolean()
&& !outcome.output_truncated
&& e["reboot_initiated"] == false
&& e["automatic_retry"] == false
&& after.desired(m),
"SYSTEM_MSI_POSTCONDITION_BINDING"
);
if noop {
let before: crate::package::Snapshot = serde_json::from_value(e["before"].clone())?;
ensure!(
outcome.exit_code.is_none()
&& !outcome.reboot_required
&& e["installer_process_started"] == false
&& e["transaction_started"] == false
&& e["installer_reboot_required"].is_null()
&& before.desired(m),
"SYSTEM_MSI_NOOP_BINDING"
);
} else {
ensure!(
matches!(outcome.exit_code, Some(0 | 3010))
&& e["installer_process_started"] == true
&& outcome.reboot_required == (outcome.exit_code == Some(3010))
&& e["installer_reboot_required"] == outcome.reboot_required,
"SYSTEM_MSI_EXIT_BINDING"
);
}
return Ok(());
}
let Action::SetServiceState { unit, state } = &job.action else {
anyhow::bail!("SYSTEM_TYPED_SERVICE_REQUIRED");
};
@@ -537,6 +585,43 @@ pub fn map_snapshot(s: &Snapshot) -> HelperSnapshot {
.collect(),
}
}
#[cfg(test)]
pub(crate) fn msi_test_job() -> JobPayload {
use rmm_domain::windows_execution::*;
let recipe:WindowsMsiRecipe=serde_json::from_value(json!({"schema_version":1,"recipe_id":MSI_RECIPE_ID,"recipe_version":"1","platform":"windows","upgrade_code":MSI_UPGRADE_CODE,"architecture":"x64","context":"machine","command_profile":"fixture_quiet_no_reboot_v1","artifact":{"artifact_id":uuid::Uuid::from_u128(10),"sha256":"ab".repeat(32),"bytes":32768},"postcondition":{"product_code":MSI_PRODUCT_CODE,"product_version":MSI_VERSION,"payload_path":MSI_PAYLOAD,"payload_sha256":MSI_PAYLOAD_10_SHA256,"payload_bytes":33},"no_reboot":true})).unwrap();
let manifest = ResolvedWindowsMsi {
recipe_sha256: recipe.sha256().unwrap(),
recipe,
};
let now = chrono::Utc::now();
let id = uuid::Uuid::from_u128(1);
JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
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)),
},
execution_identity: "system".into(),
not_before: now,
start_before: now + chrono::Duration::minutes(2),
max_runtime_seconds: 30,
max_output_bytes: 4096,
}
}
fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
native::private_path(state, true)?;
let path = state.join(PROBE_FILE);
@@ -574,6 +659,50 @@ fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
mod tests {
use super::*;
#[test]
fn msi_scope_requires_bound_independent_postconditions_and_exact_noop_or_installer_exit() {
let job = msi_test_job();
assert!(system_shape(&job));
let m = job.action.windows_msi().unwrap();
let p = &m.recipe.postcondition;
let snapshot = crate::package::Snapshot {
product_code: p.product_code.clone(),
related_products: vec![p.product_code.clone()],
product_state: Some("5".into()),
product_version: Some(p.product_version.clone()),
payload_sha256: Some(p.payload_sha256.clone()),
payload_bytes: Some(p.payload_bytes),
..Default::default()
};
let mut out = Outcome {
state: "succeeded".into(),
exit_code: Some(3010),
reboot_required: true,
evidence: json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":true,"reboot_initiated":false,"automatic_retry":false,"already_desired":false,"state":"succeeded","exit_code":3010,"installer_process_started":true,"installer_reboot_required":true,"after":snapshot,"before":snapshot}),
..Outcome::unknown("")
};
assert!(checked_outcome(&job, &out).is_ok());
out.reboot_required = false;
assert!(checked_outcome(&job, &out).is_err());
out.reboot_required = true;
out.evidence["after"]["payload_sha256"] = "cd".repeat(32).into();
assert!(checked_outcome(&job, &out).is_err());
out.evidence["after"] = serde_json::to_value(&snapshot).unwrap();
out.evidence["already_desired"] = true.into();
out.evidence["exit_code"] = serde_json::Value::Null;
out.exit_code = None;
out.reboot_required = false;
out.evidence["installer_reboot_required"] = serde_json::Value::Null;
out.evidence["installer_process_started"] = false.into();
out.evidence["transaction_started"] = false.into();
assert!(checked_outcome(&job, &out).is_ok());
out.exit_code = Some(0);
assert!(checked_outcome(&job, &out).is_err());
out.state = "unknown".into();
out.reboot_required = true;
out.exit_code = Some(1641);
assert!(checked_outcome(&job, &out).is_ok());
}
#[test]
fn system_route_binds_original_request_shape_budget_and_reply_scope() {
let id = uuid::Uuid::new_v4();
let now = chrono::Utc::now();
+312 -2
View File
@@ -69,11 +69,49 @@ pub struct Settings {
pub max_runtime_seconds: u32,
pub enable_effects: bool,
pub allow_reboot: bool,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "strict_recipe_hashes"
)]
pub allowed_msi_recipe_sha256: Option<Vec<String>>,
}
fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
d: D,
) -> std::result::Result<Option<Vec<String>>, D::Error> {
Vec::<String>::deserialize(d).map(Some)
}
impl Settings {
fn permits_msi(&self, job: &JobPayload) -> bool {
self.schema_version == 2
&& job.execution_identity == "system"
&& job.action.validate()
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& job.max_runtime_seconds <= self.max_runtime_seconds
&& job.action.windows_msi().is_some_and(|m| {
self.allowed_msi_recipe_sha256
.as_ref()
.is_some_and(|h| h.contains(&m.recipe_sha256))
})
}
pub fn validate(&self) -> Result<()> {
ensure!(
self.schema_version == 1
matches!(self.schema_version, 1 | 2)
&& (self.schema_version == 2 || self.allowed_msi_recipe_sha256.is_none())
&& self
.allowed_msi_recipe_sha256
.as_ref()
.is_none_or(|hashes| {
hashes.len() <= 2
&& hashes.iter().all(|h| ipc::digest(h))
&& hashes
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len()
== hashes.len()
})
&& !self.allow_reboot
&& (1..=120).contains(&self.max_runtime_seconds)
&& self.allowed_services.len() <= 16,
@@ -763,6 +801,11 @@ fn verified_window(
Ok((job, permit, now))
}
struct UnsettledMsi {
grant: Uuid,
request_sha256: String,
installer: Box<crate::package::Installer>,
}
pub struct SystemHelper {
settings: Settings,
pin: Pin,
@@ -773,6 +816,7 @@ pub struct SystemHelper {
boot: WindowsBoot,
sync: Option<HelperSync<DalekVerifier>>,
last_diagnostic: Option<Instant>,
unsettled_msi: Option<UnsettledMsi>,
}
impl SystemHelper {
pub fn open() -> Result<Self> {
@@ -796,6 +840,7 @@ impl SystemHelper {
boot,
sync,
last_diagnostic: None,
unsettled_msi: None,
})
}
pub fn pin(&self) -> &Pin {
@@ -972,7 +1017,8 @@ impl SystemHelper {
ensure!(
job.execution_identity == "system"
&& job.max_runtime_seconds <= self.settings.max_runtime_seconds
&& matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit)),
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|| self.settings.permits_msi(&job)),
"SYSTEM_ABANDON_POLICY_DENIED"
);
self.sync()?;
@@ -1063,6 +1109,9 @@ impl SystemHelper {
),
"SYSTEM_SIGNED_SYNC_REQUIRED"
);
if job.action.windows_msi().is_some() {
return self.execute_msi(generation, request, &job, &permit, peer);
}
let mut provider = PreparedService::prepare(&self.settings, &job)?;
self.recheck()?;
peer.check()?;
@@ -1101,6 +1150,211 @@ impl SystemHelper {
ledger::finish(&self.db, &permit, &outcome)?;
Ok(outcome)
}
fn execute_msi(
&mut self,
generation: u64,
request: &Request,
job: &JobPayload,
permit: &ExecutionPermitPayload,
peer: &mut ipc::PeerProof,
) -> Result<Outcome> {
use crate::package::{Prepared, Run};
self.observe_unsettled_msi()?;
ensure!(
self.unsettled_msi.is_none(),
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
);
let began = Instant::now();
let original_request_sha256 = hash(&serde_json::to_vec(request)?);
let timeout = Duration::from_secs(job.max_runtime_seconds.into());
let m = job
.action
.windows_msi()
.context("SYSTEM_MSI_MANIFEST_REQUIRED")?;
ensure!(
self.settings.permits_msi(job),
"SYSTEM_MSI_RECIPE_NOT_ALLOWED"
);
// No implicit bootstrap: reject absent/unprotected cache before consume.
let _cache = PinnedFile::open(Path::new(crate::msi_cache::CACHE), true, &[], &[], false)
.context("MSI_CACHE_NOT_CONFIGURED")?;
self.recheck()?;
peer.check()?;
ensure!(
self.sync.as_ref().unwrap().can_start(
&self.db,
&self.guard,
generation,
&self.clock,
&self.boot
),
"SYSTEM_SIGNED_SYNC_REQUIRED"
);
let (_, fresh, recorded_at) =
verified_window(&self.settings.binding, request, &self.clock)?;
ensure!(
&fresh == permit && !STOP.load(Ordering::SeqCst),
"SYSTEM_MSI_START_FENCED"
);
ledger::begin_execution(
&mut self.db,
permit,
request,
self.boot.current_boot()?,
recorded_at,
)?;
self.sync.as_mut().unwrap().close();
let result = (|| -> Result<Outcome> {
ensure!(
began.elapsed() < timeout,
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
crate::helper_runtime::intent::Store::require_not_denied(
request,
self.boot.current_boot()?,
generation,
&self.pin.policy_sha256,
&self.pin.helper.binary_sha256,
)?;
let _copied_archive = crate::msi_cache::import(m, permit.grant_id)?;
ensure!(
began.elapsed() < timeout,
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
let provider = Prepared::prepare(m, &m.recipe_sha256, began, timeout)?;
let run = provider.start(began, timeout, &STOP, || {
self.recheck()?;
peer.check()?;
ensure!(
!STOP.load(Ordering::SeqCst),
"SYSTEM_MSI_CANCELLED_BEFORE_START"
);
verified_window(&self.settings.binding, request, &self.clock)?;
crate::helper_runtime::intent::Store::require_not_denied(
request,
self.boot.current_boot()?,
generation,
&self.pin.policy_sha256,
&self.pin.helper.binary_sha256,
)?;
Ok(())
})?;
let observation = match run {
Run::Noop(value) => *value, // Noop variant can itself be Unknown.
Run::Installer(mut child) => loop {
// Continue observing this original transaction after start.
// A lost clock/peer/agent-denial observation cannot free the
// lane or retroactively produce success; never kill/retry.
let fenced = STOP.load(Ordering::SeqCst)
|| self.clock.now().is_err()
|| peer.check().is_err()
|| self
.boot
.current_boot()
.and_then(|boot| {
crate::helper_runtime::intent::Store::require_not_denied(
request,
boot,
generation,
&self.pin.policy_sha256,
&self.pin.helper.binary_sha256,
)
})
.is_err();
let cancelled = AtomicBool::new(fenced);
match child.poll(&cancelled) {
Ok(Some(mut value)) => {
if fenced {
value.state = "unknown";
value.code = "MSI_RUNNING_OBSERVATION_FENCED";
value.postconditions_passed = false;
}
if value.state == "unknown" {
self.unsettled_msi = Some(UnsettledMsi {
grant: permit.grant_id,
request_sha256: original_request_sha256.clone(),
installer: child,
});
}
break value;
}
Ok(None) => std::thread::sleep(Duration::from_millis(50)),
Err(error) => {
let outcome = Outcome {
evidence: serde_json::json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":false,"installer_process_started":true,"process_id":child.process_id(),"automatic_retry":false,"observer_error":safe_error(&error)}),
..Outcome::unknown("MSI_OBSERVER_FAILED_EFFECT_UNRESOLVED")
};
self.unsettled_msi = Some(UnsettledMsi {
grant: permit.grant_id,
request_sha256: original_request_sha256.clone(),
installer: child,
});
return Ok(outcome);
}
}
},
};
let mut evidence = serde_json::to_value(&observation)?;
evidence["provider"] = "windows.msi.fixture/1".into();
let mut outcome = Outcome {
state: observation.state.into(),
stdout: vec![],
stderr: vec![],
exit_code: observation.exit_code.map(|v| v as i32),
output_truncated: false,
reboot_required: observation.installer_reboot_required.unwrap_or(false),
error_code: if observation.state == "succeeded" {
String::new()
} else {
observation.code.into()
},
evidence,
};
if outcome.state == "succeeded" {
let fresh = self.clock.now().is_ok() && peer.check().is_ok();
if !fresh || began.elapsed() >= timeout {
outcome.state = "unknown".into();
outcome.error_code = "MSI_FINAL_OBSERVATION_FENCED".into();
outcome.evidence["postconditions_passed"] = false.into();
}
}
Ok(outcome)
})();
let outcome = result.unwrap_or_else(|error| {
let code = safe_error(&error);
Outcome {state:if began.elapsed() >= timeout {"unknown"} else {"failed"}.into(),
evidence:serde_json::json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":false,"installer_process_started":false,"transaction_started":false,"automatic_retry":false}), ..Outcome::unknown(&code)}
});
ledger::persist_outcome(&self.db, permit, &outcome)?;
self.guard.check(&self.db)?;
ledger::finish(&self.db, permit, &outcome)?;
Ok(outcome)
}
fn observe_unsettled_msi(&mut self) -> Result<()> {
let Some(slot) = self.unsettled_msi.as_mut() else {
return Ok(());
};
self.guard.check(&self.db)?;
let (start, outcome): (Vec<u8>, Vec<u8>) = self.db.query_row(
"SELECT start,outcome FROM execution_evidence WHERE grant_id=?1",
[slot.grant.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
let start: serde_json::Value = serde_json::from_slice(&start)?;
let original: Request = serde_json::from_value(start["request"].clone())?;
let saved: Outcome = serde_json::from_slice(&outcome)?;
ensure!(
hash(&serde_json::to_vec(&original)?) == slot.request_sha256
&& saved.state == "unknown",
"SYSTEM_MSI_UNSETTLED_ORIGINAL_BINDING"
);
if slot.installer.process_exited()? {
self.unsettled_msi = None;
}
// No ledger/outcome update here. An observed late exit never revises
// the original deadline outcome or grants permission for another job.
Ok(())
}
}
pub fn safe_error(error: &anyhow::Error) -> String {
if error.chain().any(|cause| {
@@ -1176,6 +1430,12 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
let server = ipc::Server::bind(helper.pin().clone())?;
scm_status(SERVICE_RUNNING, 0);
while !STOP.load(Ordering::SeqCst) {
// A failed observation keeps the owned slot and its handles locked.
if helper.observe_unsettled_msi().is_err()
&& let Some(sync) = &mut helper.sync
{
sync.close();
}
match server.receive() {
Ok(Some(mut incoming)) => {
let reply = helper.handle(&incoming.call, &mut incoming.peer);
@@ -1230,6 +1490,56 @@ pub fn dispatch() -> Result<()> {
mod tests {
use super::*;
#[test]
fn old_settings_omit_new_scope_and_only_v2_exact_recipe_hash_and_budget_allow_msi() {
let job = crate::helper_runtime::msi_test_job();
let m = job.action.windows_msi().unwrap();
let peer = PeerPin {
service_name: "synthetic".into(),
service_sid: "synthetic".into(),
user_sid: "synthetic".into(),
binary: PathBuf::from("synthetic"),
binary_sha256: "ab".repeat(32),
};
let mut settings = Settings {
schema_version: 1,
binding: Binding {
tenant_id: job.tenant_id,
asset_id: job.asset_id,
agent_id: job.agent_id,
enrollment_generation: 1,
assignment_version: 1,
public_key_hex: "ab".repeat(32),
},
agent: peer.clone(),
helper: peer,
allowed_services: vec![],
max_runtime_seconds: 30,
enable_effects: false,
allow_reboot: false,
allowed_msi_recipe_sha256: None,
};
let legacy = serde_json::to_value(&settings).unwrap();
assert!(legacy.get("allowed_msi_recipe_sha256").is_none());
let mut null = legacy.clone();
null["allowed_msi_recipe_sha256"] = serde_json::Value::Null;
assert!(serde_json::from_value::<Settings>(null).is_err());
assert!(!settings.permits_msi(&job));
settings.allowed_msi_recipe_sha256 = Some(vec![m.recipe_sha256.clone()]);
assert!(!settings.permits_msi(&job));
assert_eq!(
settings.validate().unwrap_err().to_string(),
"SYSTEM_POLICY_PROFILE"
);
settings.schema_version = 2;
assert!(settings.permits_msi(&job));
assert!(!settings.enable_effects);
settings.max_runtime_seconds = 29;
assert!(!settings.permits_msi(&job));
settings.max_runtime_seconds = 30;
settings.allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]);
assert!(!settings.permits_msi(&job));
}
#[test]
fn service_adapter_exposes_only_implemented_states() {
assert_eq!(desired_state("running").unwrap(), SERVICE_RUNNING);
assert_eq!(desired_state("stopped").unwrap(), SERVICE_STOPPED);
+3
View File
@@ -18,6 +18,9 @@ pub mod inventory;
#[cfg(windows)]
pub mod job_binding;
pub mod journal;
pub mod package;
#[cfg(all(windows, feature = "system-helper"))]
pub mod msi_cache;
#[cfg(windows)]
pub mod native;
#[cfg(windows)]
+178
View File
@@ -0,0 +1,178 @@
//! Fixed public-byte staging and independent SYSTEM cache import. No IPC path,
//! URL or byte-array authority. Directories must be provisioned separately;
//! this module never installs/repairs an ACL, directory, policy or service.
use crate::helper_ipc::{self as ipc, PinnedFile};
use anyhow::{Context, Result, ensure};
use rmm_domain::windows_execution::ResolvedWindowsMsi;
use sha2::{Digest, Sha256};
use std::{
fs::{File, OpenOptions},
io::{Read, Write},
mem::zeroed,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
ptr,
};
use uuid::Uuid;
use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*};
pub const AGENT_STATE: &str = r"C:\ProgramData\RustDiscovery\state";
pub const STAGE: &str = r"C:\ProgramData\RustDiscovery\state\msi-stage";
pub const CACHE: &str = r"C:\ProgramData\RustDiscoverySystem\cache";
fn name(m: &ResolvedWindowsMsi) -> Result<String> {
ensure!(m.validate(), "MSI_CACHE_MANIFEST");
Ok(format!("{}.msi", m.recipe.artifact.sha256))
}
fn regular(file: &File, directory: bool) -> Result<()> {
let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut i) } != 0
&& i.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (i.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory
&& (directory || i.nNumberOfLinks == 1),
"MSI_CACHE_NONREGULAR"
);
Ok(())
}
/// Keep every actual parent open without DELETE sharing throughout the copy.
/// Source data/ACL is untrusted; only the original signed digest authorizes bytes.
fn parents(path: &Path) -> Result<Vec<File>> {
let mut held = Vec::new();
for p in path.ancestors().skip(1) {
let raw = unsafe {
CreateFileW(
ipc::wide(p).as_ptr(),
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
ptr::null_mut(),
)
};
ensure!(
raw != INVALID_HANDLE_VALUE,
"MSI_CACHE_PARENT_NOT_CONFIGURED"
);
let file = unsafe { File::from_raw_handle(raw) };
regular(&file, true)?;
held.push(file);
}
Ok(held)
}
fn checked_bytes(path: &Path, m: &ResolvedWindowsMsi) -> Result<Vec<u8>> {
let _parents = parents(path)?;
let mut file = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
.context("MSI_STAGE_NOT_CONFIGURED")?;
regular(&file, false)?;
let id = ipc::file_identity(&file)?;
ensure!(
file.metadata()?.len() == m.recipe.artifact.bytes && m.recipe.artifact.bytes <= 262144,
"MSI_CACHE_LENGTH"
);
let mut bytes = Vec::new();
(&mut file).take(262145).read_to_end(&mut bytes)?;
ensure!(
bytes.len() as u64 == m.recipe.artifact.bytes
&& format!("{:x}", Sha256::digest(&bytes)) == m.recipe.artifact.sha256,
"MSI_CACHE_DIGEST"
);
let again = OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
regular(&again, false)?;
ensure!(ipc::file_identity(&again)? == id, "MSI_CACHE_FILE_REPLACED");
Ok(bytes)
}
pub fn stage_configured() -> bool {
crate::native::private_path(Path::new(STAGE), true).is_ok()
}
/// Called by LocalService only for the already approved original job/attempt.
pub fn stage(m: &ResolvedWindowsMsi, bytes: &[u8]) -> Result<()> {
crate::native::require_local_service()?;
let path = Path::new(STAGE).join(name(m)?);
let _parents = parents(&path)?;
crate::native::private_path(Path::new(STAGE), true)?;
ensure!(
bytes.len() as u64 == m.recipe.artifact.bytes
&& format!("{:x}", Sha256::digest(bytes)) == m.recipe.artifact.sha256,
"MSI_DOWNLOAD_DIGEST"
);
if path.try_exists()? {
ensure!(checked_bytes(&path, m)? == bytes, "MSI_STAGE_CONFLICT");
return Ok(());
}
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&path)?;
regular(&file, false)?;
let id = ipc::file_identity(&file)?;
file.write_all(bytes)?;
file.sync_all()?;
ensure!(ipc::file_identity(&file)? == id, "MSI_STAGE_FILE_CHANGED");
drop(file);
crate::native::private_path(&path, false)?;
ensure!(checked_bytes(&path, m)? == bytes, "MSI_STAGE_CONFLICT");
Ok(())
}
/// Called ONLY after full independent helper authorization and durable consume.
/// Publish to the fixed SYS/Admin cache without replacing any existing entry.
/// Returned guards pin the copied archive until the provider holds its own.
pub fn import(m: &ResolvedWindowsMsi, grant: Uuid) -> Result<Vec<PinnedFile>> {
let file_name = name(m)?;
ensure!(!grant.is_nil(), "MSI_CACHE_GRANT");
let destination = Path::new(CACHE).join(file_name);
let _parents = parents(&destination)?;
let root = PinnedFile::open(Path::new(CACHE), true, &[], &[], false)
.context("MSI_CACHE_NOT_CONFIGURED")?;
if destination.try_exists()? {
let archive = PinnedFile::open(&destination, false, &[], &[], false)?;
checked_bytes(&destination, m)?;
return Ok(vec![root, archive]);
}
let source: PathBuf = Path::new(STAGE).join(name(m)?);
let bytes = checked_bytes(&source, m)?; // Never trust actor ownership/data.
let pending = Path::new(CACHE).join(format!("{}.{}.pending", m.recipe.artifact.sha256, grant));
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(&pending)?;
regular(&file, false)?;
file.write_all(&bytes)?;
file.sync_all()?;
drop(file);
// Cache directory was already independently validated SYS/Admin-only. New
// SYSTEM-created files inherit that boundary; no ACL repair is performed.
let copied = PinnedFile::open(&pending, false, &[], &[], false)?;
checked_bytes(&pending, m)?;
drop(copied);
ensure!(
unsafe {
MoveFileExW(
ipc::wide(&pending).as_ptr(),
ipc::wide(&destination).as_ptr(),
0,
)
} != 0,
"MSI_CACHE_CREATE_ONLY_PUBLICATION"
);
let archive = PinnedFile::open(&destination, false, &[], &[], false)?;
checked_bytes(&destination, m)?;
Ok(vec![root, archive])
}
+28 -5
View File
@@ -17,9 +17,10 @@
use anyhow::{Result, ensure};
#[cfg(any(windows, test))]
use rmm_domain::windows_execution::{ResolvedWindowsMsi, valid_package_code};
use serde::Serialize;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Snapshot {
pub product_code: String,
pub package_code: Option<String>,
@@ -34,7 +35,7 @@ pub struct Snapshot {
}
impl Snapshot {
#[cfg(any(windows, test))]
fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
pub(crate) fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
let p = &r.recipe.postcondition;
self.product_code == p.product_code
&& self.related_products == [p.product_code.clone()]
@@ -854,8 +855,17 @@ mod windows {
system_root: PathBuf,
}
impl Prepared {
pub fn prepare(r: &ResolvedWindowsMsi, allowed_recipe_sha256: &str) -> Result<Self> {
pub fn prepare(
r: &ResolvedWindowsMsi,
allowed_recipe_sha256: &str,
began: Instant,
timeout: Duration,
) -> Result<Self> {
validate(r, allowed_recipe_sha256)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
let mut roots = Vec::new();
for path in [CACHE, FIXTURES] {
let file = OpenOptions::new()
@@ -872,9 +882,17 @@ mod windows {
false,
)?;
inspect_archive(&mut archive, r)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
let system_root = system_root()?;
let msiexec = Held::open(&system_root.join("System32").join("msiexec.exe"), true)?;
let before = snapshot_for(r)?;
ensure!(
within_budget(began, timeout),
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
);
ensure!(
before.baseline_allowed(r),
"MSI_EXISTING_PRODUCT_OR_PAYLOAD_CONFLICT"
@@ -911,6 +929,7 @@ mod windows {
/// config, privilege, policy, clock, reboot or foreign process occurs.
pub fn start(
mut self,
began: Instant,
timeout: Duration,
cancelled: &AtomicBool,
check_effect_fence: impl FnOnce() -> Result<()>,
@@ -923,7 +942,6 @@ mod windows {
);
// One original budget includes all synchronous verification and
// the eventual installer. A late Noop is not retroactive success.
let began = Instant::now();
let archive = inspect_archive(&mut self.archive, &self.recipe);
if !within_budget(began, timeout) {
return Ok(self.verification_timeout(None));
@@ -1010,6 +1028,11 @@ mod windows {
timeout: Duration,
}
impl Installer {
/// Observe only this retained process handle. Never adopt a PID, kill,
/// restart, or revise an already persisted timeout outcome.
pub fn process_exited(&mut self) -> Result<bool> {
Ok(self.child.try_wait()?.is_some())
}
pub fn process_id(&self) -> u32 {
self.child.id()
}
+85 -2
View File
@@ -367,6 +367,25 @@ struct Agent {
impl Agent {
fn close_gate(&mut self) {
self.fence.close();
#[cfg(feature = "system-helper")]
if let Some(running) = &self.running
&& running.grant.execution_identity == "system"
{
running.cancel.store(true, Ordering::SeqCst);
let denied = (|| -> Result<()> {
let mut store = rmm_agent_windows::helper_runtime::intent::Store::open(true)?;
let intent = store.by_grant(running.grant.grant_id)?;
ensure!(
intent.permit()? == running.grant,
"SYSTEM_CANCEL_GRANT_BINDING"
);
store.deny(&intent.request, Uuid::parse_str(&self.boot)?)
})();
if denied.is_err() {
self.helper_refused = true;
eprintln!("SYSTEM_CANCEL_PERSISTENCE_FAILED");
}
}
if let Some(sync) = &mut self.sync {
sync.close();
}
@@ -566,7 +585,11 @@ impl Agent {
}
#[cfg(feature = "system-helper")]
{
Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file()
(job.action.windows_msi().is_none()
|| (self.config.state_directory
== Path::new(rmm_agent_windows::msi_cache::AGENT_STATE)
&& rmm_agent_windows::msi_cache::stage_configured()))
&& Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file()
&& self
.helper
.as_ref()
@@ -983,9 +1006,69 @@ impl Agent {
let completed = self.completed_tx.clone();
let work_offer = offer.clone();
let work_grant = grant.clone();
let msi = job.action.windows_msi().cloned();
let address = self.config.connect_address;
let ca = self.ca.clone();
let state = self.config.state_directory.clone();
let request_for_stage = request.clone();
let binding_for_stage = binding.clone();
let worker = tokio::spawn(async move {
let staged = if let Some(m) = msi {
let result = async {
ensure!(
!worker_cancel.load(Ordering::SeqCst)
&& fence.allows_identity(generation, true, &clock),
"MSI_DOWNLOAD_FENCED"
);
verified_window(&binding_for_stage, &request_for_stage, &clock)?;
let cert = protected_read(&state.join("device.pem"), 32768)?;
let key = protected_read(&state.join("device.key"), 16384)?;
let tls = crate::https_channel::mtls_client(address, &ca, &cert, &key)?;
let response = tls
.get(format!(
"https://{}:{}/agent/v1/artifacts/{}?job_id={}&attempt_id={}",
crate::https_channel::server_name()?,
address.port(),
m.recipe.artifact.artifact_id,
work_grant.job_id,
work_grant.attempt_id
))
.send()
.await?;
ensure!(
response
.headers()
.get("x-artifact-sha256")
.and_then(|v| v.to_str().ok())
== Some(m.recipe.artifact.sha256.as_str()),
"MSI_DOWNLOAD_METADATA"
);
let bytes = crate::https_channel::bounded_body(
response,
m.recipe.artifact.bytes as usize,
"application/octet-stream",
)
.await?;
ensure!(
!worker_cancel.load(Ordering::SeqCst)
&& fence.allows_identity(generation, true, &clock),
"MSI_DOWNLOAD_FENCED"
);
verified_window(&binding_for_stage, &request_for_stage, &clock)?;
tokio::task::spawn_blocking(move || {
rmm_agent_windows::msi_cache::stage(&m, &bytes)
})
.await??;
Ok::<_, anyhow::Error>(())
}
.await;
result.is_ok()
} else {
true
};
let _result = helper
.delegate(intent, move || {
ensure!(staged, "MSI_DOWNLOAD_NOT_READY");
ensure!(
!worker_cancel.load(Ordering::SeqCst),
"CANCELLED_BEFORE_DISPATCH"
@@ -1298,7 +1381,7 @@ impl Agent {
#[cfg(feature="system-helper")]
if Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file() {
let mut store=rmm_agent_windows::helper_runtime::intent::Store::open(true)?;
if let Some(intent)=store.pending()?.first() && intent.permit()?.job_id.to_string()==cancel.job_id && intent.permit()?.attempt_id.to_string()==cancel.attempt_id {store.cancel_before_dispatch(intent.id)?;}
if let Some(intent)=store.pending()?.first() && intent.permit()?.job_id.to_string()==cancel.job_id && intent.permit()?.attempt_id.to_string()==cancel.attempt_id {store.deny(&intent.request,Uuid::parse_str(&self.boot)?)?;store.cancel_before_dispatch(intent.id)?;}
}
if state=="accepted" {self.record(generation,&JobOffer::decode(bytes.as_slice())?,&grant,jobs::no_start("cancelled","CANCELLED_BEFORE_START"))?;needs_sync=true;}
}
+89
View File
@@ -0,0 +1,89 @@
# Windows MSI runtime: implementierter, noch nicht nativ abgenommener Schnitt
Stand 2026-11-14, isolierter Zweig `codex/windows-msi-runtime`, Basis `66c1855`.
Dies ist ein Quellen-/Lokalnachweis. Es wurde damit kein Windows-Installer,
RMM-Job, Dienstwechsel oder Bootstrap am Ziel ausgeführt. Die nativen
Domain-/Backend-Nachweise des vorhergehenden M4-Schritts ersetzen die folgenden
noch offenen Runtime-Nachweise nicht.
## Implementierte Grenze
Der Network-Agent lädt ausschließlich das im genehmigten Originaljob gebundene
MSI-Artefakt über den bestehenden mTLS-Client und den festen Agent-Endpunkt.
Es gibt keine Installer-URL, Weiterleitung, Bearer-Abkürzung oder abgeschaltete
TLS-Prüfung. Länge und SHA-256 sind auf das Manifest und höchstens 256 KiB
begrenzt. Das Staging liegt unter dem festen Agentzustandsverzeichnis.
Der SYSTEM-Helper nimmt weiterhin nur die originale signierte Request an,
keinen Callerpfad und keine Installerbytes. Settings-Schema 1 bleibt SCM-only;
Schema 2 kann höchstens zwei genaue Recipe-SHA-256 freigeben. Fehlende neue
Settings-Felder werden beim Serialisieren ausgelassen; vorhandenes `null` ist
kein erlaubter Recipe-Allowlistwert. Die lokale Allowlist begrenzt ausschließlich
und ersetzt weder Plan, Startgrant, Clock noch signierten Sync.
Vor einer SYSTEM-Cachekopie persistiert der Helper den atomaren Originalstart
mit Verbrauch. Die Kopie verwendet den manifestabgeleiteten SHA-Pfad, prüft
Nicht-Reparse, Elternhandles, File-ID, Länge, Hash und die SYS/Admin-Cachegrenze.
Neue Cacheeinträge werden ohne Ersetzen bestehender Dateien veröffentlicht.
Cache/Staging müssen vorher eingerichtet sein; der Runtimecode repariert weder
ACLs noch Verzeichnisse. Der Provider hält eigene Archiv-/Prozesshandles.
Ein originales monotones Laufzeitbudget umfasst SYSTEM-Cacheaufbereitung,
MSI-Metadaten, unabhängige Bestandsprüfung, Noopentscheidung und Installerlauf.
Die festen Argumente und MSI-Tabellenprüfungen bleiben erhalten. Erfolg benötigt
unabhängige Product-/Family-/PackageCode-/Payload-Nachbedingungen; `3010` bleibt
als Rebootbedarf sichtbar, `1641` unklar, `1618` ein fehlgeschlagener eigener
Start. Noop hat keinen Installerexitcode. Weder automatischer Reboot noch
allgemeines `msiexec`-Kill oder automatischer Wiederholungsstart sind enthalten.
Die vorhandene Intentzeile besitzt zusätzlich eine dauerhafte, ausschließlich
verweigernde Abbruchmarkierung. Sie ist nur von 0 nach 1 änderbar; Originalbytes,
Grant und `may_have_dispatched` werden dabei nicht zurückgesetzt. Eine eng
geprüfte additive Migration akzeptiert nur die bisherige genaue Tabellen- und
Triggerdefinition. Der Helper liest die vollständige Originalbindung über eine
jeweils frische gewöhnliche Read-only-Verbindung vor Noop/Start und während der
Beobachtung. Fehlende, fehlerhafte oder gesperrte Beobachtung verweigert. Dies ist
keine zusätzliche Ausführungsautorität. Zwischen letzter Prüfung und OS-Start
bleibt das übliche kleine Rennen; es gibt kein behauptetes Rückgängigmachen.
Nach unklarem Timeout oder Beobachtungsfehler hält der Helper den eigenen Child,
Archivhandles und Originalgrant-/Requestbindung in einem ungeklärten Slot.
Weitere MSI-Starts werden bis zur Beobachtung desselben Prozessendes verweigert.
Ein späterer Exit ändert das bereits persistierte `unknown` nicht. Nach einem
Helperabsturz bleibt die ursprüngliche Ledger-Sperre bestehen. Intent, Abandon,
RawMirror und signierter Core-Sync behalten ihre strengen Originalbindungen;
keine Missing-row-Regel wurde gelockert.
## Tatsächlich lokale Prüfung
Der private Fall `qualified-ee6681c7-8d9d-4af9-8947-5325e1ea2e0f` unter
`devstate/windows-msi-runtime/` bindet 82 Compiler-/Manifestquellen vor und nach
allen qualifizierten Prüfungen identisch. Qualification-SHA-256:
`17f3eb2258773a22be26afd9681d271f69136cfb52dbda31aac2a0ef577b3816`.
- Linux-Container: 10 Bibliothekstests ausgeführt, 10 bestanden, 0 ignoriert.
- Windows-GNU: Default- und SYSTEM-Feature-Alltargets-Clippy mit `-D warnings`
bestanden.
- Windows-GNU: Lib-/Agent-Bin-Unittests gelinkt, nicht ausgeführt.
- Windows-GNU: beide Releasebinaries gelinkt; AMD64-PE geprüft. Originale und
mit `--strip-all` bearbeitete Auslieferungsdateien sind getrennt erhalten.
- `git diff --check` bestanden. Keine Domain-/Core-/Server-/Web- oder
Root-Cargo-/Lockänderung.
Release-Auslieferung Agent:
`7d9b1221ccb3587437d0866296472330947a16445c4e40069981fc4197242d83`.
Release-Auslieferung Helper:
`96589d53d366a0ccbd60c301fd3d1f03cd4d9f93d85bdcb3ce9b7f4647afc273`.
Die Zwischenbelege vor der ergänzten laufenden Abbruchbeobachtung bleiben
historisch erhalten und sind nicht die finale Qualification.
## Noch offen
Die Windows-Unitbinaries, Cache-/Staging-ACLs und gehaltenen Handles, tatsächliche
PERSIST-Migration mit konkurrierender Deny-Lesung, Installer 1.0, MajorUpgrade
1.1, beide Noops und die Abbruch-/Unklarheitsfälle müssen auf der Windows-VM
nachgewiesen werden. Installerjobs benötigen jeweils die reale WebUI-Grenze.
Capabilityliste bleibt passiv, Clock-Gate unqualifiziert, Job-/Effektdefaults
bleiben geschlossen. Diese Implementierung behauptet weder native MSI-Abnahme
noch Windows-MVP-Abschluss. EXE, WinGet, allgemeine Installerargumente oder eine
neue Rebootstrecke gehören nicht zu diesem Schnitt.