Add reviewed Windows scope completion and idle certificate renewal; deploy completion API
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-16 10:25:25 +01:00
parent ebcad08731
commit bb4ffe518d
43 changed files with 5146 additions and 50 deletions
+217 -15
View File
@@ -49,6 +49,42 @@ struct Config {
)]
windows_execution_profile: Option<rmm_domain::jobs::WindowsExecutionProfile>,
}
/// Local TLS maintenance evidence only. It never restores readiness; after
/// renewal both roles must pass their ordinary fresh signed synchronization.
#[derive(serde::Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct RotationIdleAdmission {
schema_version: u32,
agent_id: String,
binding_sha256: String,
boot_id: String,
journal_file_id: [u32; 3],
ledger_file_id: [u32; 3],
history_sha256: String,
helper_pin_sha256: Option<String>,
helper_anchor_sha256: Option<String>,
intent_file_id: Option<[u32; 3]>,
}
fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
};
native::private_path(path, false)?;
let file = fs::File::open(path)?;
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: live file handle and correctly sized writable native structure.
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0
&& info.nNumberOfLinks == 1,
"ROTATION_FILE_IDENTITY"
);
Ok([
info.dwVolumeSerialNumber,
info.nFileIndexHigh,
info.nFileIndexLow,
])
}
impl Config {
fn profile_enabled(&self, profile: rmm_domain::jobs::WindowsExecutionProfile) -> bool {
self.enable_jobs
@@ -536,6 +572,137 @@ struct Agent {
deferred_permit: Option<(u64, ExecutionPermit)>,
}
impl Agent {
fn rotation_without_effects(&self) -> Result<()> {
ensure!(
self.running.is_none() && self.deferred_permit.is_none() && !self.prepared,
"ROTATION_BUSY"
);
let idle: bool = self.journal.connection().query_row("SELECT NOT EXISTS(SELECT 1 FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired'))", [], |r| r.get(0))?;
ensure!(idle, "ROTATION_EFFECT_UNRESOLVED");
if let Some(ledger) = &self.ledger {
let resolved: bool = ledger.query_row("SELECT NOT EXISTS(SELECT 1 FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.result IS NULL OR e.start IS NULL OR e.outcome IS NULL)", [], |r| r.get(0))?;
ensure!(resolved, "ROTATION_CONSUMPTION_UNRESOLVED");
}
#[cfg(feature = "system-helper")]
{
ensure!(
self.helper_control.is_none()
&& self.helper_probe.is_none()
&& !self.helper_apply_unconfirmed,
"ROTATION_HELPER_CONTROL_PENDING"
);
if Path::new(rmm_agent_windows::helper_runtime::intent::DB).try_exists()? {
let intents = rmm_agent_windows::helper_runtime::intent::Store::open(false)?;
ensure!(
intents.pending()?.is_empty(),
"ROTATION_SYSTEM_DELEGATION_PENDING"
);
}
}
Ok(())
}
fn rotation_admission(
&self,
generation: Option<u64>,
retained: Option<&[u8]>,
) -> Result<Vec<u8>> {
self.rotation_without_effects()?;
let old: Option<RotationIdleAdmission> =
retained.map(serde_json::from_slice).transpose()?;
if let Some(generation) = generation {
#[cfg(feature = "system-helper")]
let helper_present = self.helper.is_some();
#[cfg(not(feature = "system-helper"))]
let helper_present = false;
ensure!(
self.ready_identity(generation, helper_present),
"ROTATION_SIGNED_IDLE_REQUIRED"
);
} else {
ensure!(
self.fence.generation.load(Ordering::SeqCst) == 0 && old.is_some(),
"ROTATION_PENDING_IDLE_ADMISSION_REQUIRED"
);
}
#[cfg(feature = "system-helper")]
let (helper_pin_sha256, helper_anchor_sha256, intent_file_id) = {
use rmm_agent_windows::helper_runtime::{Client, intent};
let helper = Client::discover(
&self.identity.agent_id,
&self.identity.asset_id,
self.binding.as_ref(),
self.helper_lane.clone(),
)?;
let pin = helper.as_ref().map(|h| {
format!(
"{:x}",
Sha256::digest(
format!("{}:{}", h.pin_hash(), h.helper_binary_hash()).as_bytes()
)
)
});
let anchor = if helper.is_some() {
if generation.is_some() {
Some(format!(
"{:x}",
Sha256::digest(serde_json::to_vec(
self.helper_anchor
.as_ref()
.context("ROTATION_HELPER_ANCHOR_REQUIRED")?
)?)
))
} else {
let saved = old
.as_ref()
.and_then(|a| a.helper_anchor_sha256.clone())
.context("ROTATION_RETAINED_HELPER_ANCHOR_REQUIRED")?;
ensure!(
saved.len() == 64 && saved.bytes().all(|b| b.is_ascii_hexdigit()),
"ROTATION_RETAINED_HELPER_ANCHOR_INVALID"
);
Some(saved)
}
} else {
None
};
let file = Path::new(intent::DB)
.try_exists()?
.then(|| rotation_file_id(Path::new(intent::DB)))
.transpose()?;
(pin, anchor, file)
};
#[cfg(not(feature = "system-helper"))]
let (helper_pin_sha256, helper_anchor_sha256, intent_file_id) = (None, None, None);
let admission = RotationIdleAdmission {
schema_version: 1,
agent_id: self.identity.agent_id.clone(),
binding_sha256: format!(
"{:x}",
Sha256::digest(serde_json::to_vec(
self.binding.as_ref().context("ROTATION_BINDING_REQUIRED")?
)?)
),
boot_id: self.boot.clone(),
journal_file_id: rotation_file_id(
&self.config.state_directory.join("telemetry.sqlite"),
)?,
ledger_file_id: rotation_file_id(
&self.config.state_directory.join("consumption.sqlite"),
)?,
history_sha256: rmm_agent_windows::certificate_rotation::idle_history_sha256(
self.journal.connection(),
self.ledger.as_ref().context("ROTATION_LEDGER_REQUIRED")?,
)?,
helper_pin_sha256,
helper_anchor_sha256,
intent_file_id,
};
ensure!(
old.as_ref().is_none_or(|saved| saved == &admission),
"ROTATION_IDLE_STATE_CHANGED"
);
Ok(serde_json::to_vec(&admission)?)
}
#[cfg(feature = "system-helper")]
fn start_time_refresh(
&mut self,
@@ -958,6 +1125,12 @@ impl Agent {
caps.push(rmm_agent_windows::actions::REMOTE_SIGNED_PROFILE_CAPABILITY.into());
}
}
#[cfg(feature = "system-helper")]
if !self.config.windows_echo_probe_only
&& let Some(helper) = &self.helper
{
caps.extend(helper.qualified_capabilities());
}
}
caps
}
@@ -1679,11 +1852,16 @@ impl Agent {
// Server commit may have fenced Hello even if its HTTP response was
// lost. Recover the durable original CSR before requiring any channel.
if self.certificates.has_pending(self.journal.connection())? {
ensure!(
!self.config.enable_jobs,
"ROTATION_PENDING_REQUIRES_PASSIVE_RECOVERY"
);
self.renew_certificate().await?;
let admission = if self.config.enable_jobs {
let retained = self
.certificates
.pending_idle_admission(self.journal.connection())?
.context("ROTATION_PENDING_REQUIRES_PASSIVE_RECOVERY")?;
Some(self.rotation_admission(None, Some(&retained))?)
} else {
None
};
self.renew_certificate(admission.as_deref()).await?;
}
self.boot = native::boot_id().await?;
let advertised = self.capabilities();
@@ -1747,6 +1925,7 @@ impl Agent {
let mut inventory = Instant::now();
let mut update_at = Instant::now();
let mut rotation_at = Instant::now();
let mut rotation_after = Duration::from_secs(30);
let mut heartbeat = Instant::now() - Duration::from_secs(60);
let mut heartbeat_after = Duration::from_secs(30);
let mut tick = tokio::time::interval(Duration::from_secs(1));
@@ -1834,19 +2013,32 @@ impl Agent {
if stop.load(Ordering::SeqCst) {
continue;
}
// This slice renews only passive clients. Job admission and helper
// lifecycle are not extended by certificate maintenance.
if !self.config.enable_jobs && rotation_at.elapsed() >= Duration::from_secs(30) {
// Certificate maintenance cannot interrupt accepted, ambiguous or
// live work. Active rotation also retains its exact signed-idle
// context for a closed, effect-free retry after response loss.
if rotation_at.elapsed() >= rotation_after {
rotation_at = Instant::now();
rotation_after = Duration::from_secs(30);
let now = Utc::now().timestamp();
if self
.certificates
.due(self.journal.connection(), &self.key_files, now)?
{
self.renew_certificate().await?;
// The server fences the previous connection generation.
// A new Hello/Sync uses the newly selected pair.
return Ok(());
let admission = if self.config.enable_jobs {
self.rotation_admission(Some(generation), None).map(Some)
} else {
self.rotation_without_effects().map(|()| None)
};
if let Ok(admission) = admission {
self.renew_certificate(admission.as_deref()).await?;
// No offers are processed during renewal. The server
// fences this channel; fresh Hello/Sync must qualify
// both roles again before any subsequent job starts.
return Ok(());
}
// Avoid phase-locking a due renewal to the 30s helper
// probe cadence. Busy work keeps its guard and continues.
rotation_after = Duration::from_secs(1);
}
}
if heartbeat.elapsed() >= heartbeat_after {
@@ -1901,13 +2093,23 @@ impl Agent {
}
Ok(())
}
async fn renew_certificate(&mut self) -> Result<()> {
ensure!(!self.config.enable_jobs, "PASSIVE_RENEWAL_ONLY");
async fn renew_certificate(&mut self, admission: Option<&[u8]>) -> Result<()> {
self.rotation_without_effects()?;
ensure!(
!self.config.enable_jobs || admission.is_some(),
"ROTATION_ACTIVE_IDLE_REQUIRED"
);
self.close_gate();
let request = self.certificates.prepare(
#[cfg(feature = "system-helper")]
self.stop_time_refresh().await;
if self.config.enable_jobs {
self.rotation_admission(None, admission)?;
}
let request = self.certificates.prepare_with_idle_admission(
self.journal.connection_mut(),
&self.key_files,
Utc::now().timestamp(),
admission,
)?;
let client = crate::https_channel::mtls_client(
self.config.connect_address,