Qualify Windows IPC client runtime and prepare bounded native providers
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-14 03:53:48 +01:00
parent 2bf0183e68
commit 9d6a6f0eb6
24 changed files with 3880 additions and 30 deletions
+223
View File
@@ -0,0 +1,223 @@
//! Optional passive helper control client. No SYSTEM action capability is
//! advertised here. Each actual IPC runs on one bounded blocking lane.
use crate::{helper_ipc as ipc, native};
use anyhow::{Context, Result, ensure};
use rmm_agent_core::{auth::Binding, helper_reconcile::Snapshot, reconcile::HelperSnapshot};
use rmm_protocol::{SyncAttempt, SyncResponse};
use serde_json::json;
use std::{
io::{Read, Write},
path::Path,
sync::Arc,
time::Duration,
};
use tokio::sync::Semaphore;
pub const PIN_PATH: &str = r"C:\ProgramData\RustDiscoverySystem\agent-pin.json";
const PUBLIC_ROOT: &str = r"C:\ProgramData\RustDiscoverySystem";
const PROBE_FILE: &str = "helper-probe.json";
#[derive(Clone)]
pub struct Client {
pin: ipc::Pin,
lane: Arc<Semaphore>,
}
impl Client {
/// Missing pin is deliberately passive. A present but invalid pin is refused;
/// no endpoint/key/policy is discovered from the pipe itself.
pub fn discover(
agent_id: &str,
asset_id: &str,
binding: Option<&Binding>,
lane: Arc<Semaphore>,
) -> Result<Option<Self>> {
if !Path::new(PIN_PATH).try_exists()? {
return Ok(None);
}
let readers = [
ipc::service_sid(crate::SERVICE_NAME)?,
ipc::service_sid(ipc::HELPER_SERVICE)?,
];
let _root = ipc::PinnedFile::open(Path::new(PUBLIC_ROOT), true, &readers, &[], false)?;
let mut file = ipc::PinnedFile::open(Path::new(PIN_PATH), false, &readers, &[], false)?;
ensure!(file.file.metadata()?.len() <= 16384, "HELPER_PIN_SIZE");
let mut bytes = Vec::new();
file.file.read_to_end(&mut bytes)?;
let pin: ipc::Pin = serde_json::from_slice(&bytes)?;
pin.validate()?;
ensure!(
pin.binding.agent_id.to_string() == agent_id
&& pin.binding.asset_id.to_string() == asset_id
&& pin.binding.enrollment_generation
== binding.map_or(1, |b| b.enrollment_generation),
"HELPER_ENROLLMENT_PIN_MISMATCH"
);
if let Some(binding) = binding {
ensure!(
ipc::binding_hash(binding)? == ipc::binding_hash(&pin.binding)?,
"HELPER_JOB_BINDING_MISMATCH"
);
}
Ok(Some(Self { pin, lane }))
}
pub async fn refresh(
agent_id: String,
asset_id: String,
binding: Option<Binding>,
lane: Arc<Semaphore>,
state: std::path::PathBuf,
) -> Result<Option<Self>> {
let permit = lane
.clone()
.try_acquire_owned()
.context("HELPER_CONTROL_BUSY")?;
tokio::task::spawn_blocking(move || {
let _permit = permit;
let result=(|| {
let client=Self::discover(&agent_id,&asset_id,binding.as_ref(),lane)?;
if let Some(client)=&client {client.probe_blocking(&state)?;}
Ok(client)
})();
if result.is_err() || matches!(&result,Ok(None)) && state.join(PROBE_FILE).try_exists()? {
write_current_probe(&state,&json!({"schema_version":1,"source":"actual_local_service_runtime","agent_process_id":std::process::id(),"agent_id":agent_id,"asset_id":asset_id,"observed_at":chrono::Utc::now(),"authenticated_pipe_exchange":false,"system_capability_advertised":false,"helper_ready":false,"no_jobs":true,"code":"HELPER_NOT_AVAILABLE"}))?;
}
result
})
.await?
}
fn check_pin(&self) -> Result<()> {
let current = Self::discover(
&self.pin.binding.agent_id.to_string(),
&self.pin.binding.asset_id.to_string(),
Some(&self.pin.binding),
self.lane.clone(),
)?
.context("HELPER_PIN_REMOVED")?;
ensure!(
serde_json::to_vec(&current.pin)? == serde_json::to_vec(&self.pin)?,
"HELPER_PIN_CHANGED"
);
Ok(())
}
pub fn pin_hash(&self) -> &str {
&self.pin.policy_sha256
}
async fn call(&self, operation: ipc::Operation) -> Result<ipc::Reply> {
let permit = self
.lane
.clone()
.try_acquire_owned()
.context("HELPER_CONTROL_BUSY")?;
let client = self.clone();
tokio::task::spawn_blocking(move || {
let _permit = permit;
client.check_pin()?;
let call = ipc::Call::new(&client.pin, operation);
let reply = ipc::exchange(&client.pin, &call, Duration::from_secs(5))?;
client.check_pin()?;
Ok(reply)
})
.await?
}
fn probe_blocking(&self, state: &Path) -> Result<()> {
self.check_pin()?;
let pin = &self.pin;
let call = ipc::Call::new(pin, ipc::Operation::Probe {});
let reply = ipc::exchange(pin, &call, Duration::from_secs(5))?;
let ipc::ReplyBody::Probe {
clock_qualified,
ready,
ledger,
lock,
} = reply.body
else {
anyhow::bail!("HELPER_PROBE_DENIED");
};
let value = json!({"schema_version":1,"source":"actual_local_service_runtime","agent_process_id":std::process::id(),"agent_service":crate::SERVICE_NAME,"agent_id":pin.binding.agent_id,"asset_id":pin.binding.asset_id,"challenge":reply.challenge,"observed_at":chrono::Utc::now(),"helper_service":ipc::HELPER_SERVICE,"verified_helper_user_sid":pin.helper.user_sid,"verified_helper_service_sid":pin.helper.service_sid,"helper_binary_sha256":reply.helper_binary_sha256,"policy_sha256":reply.policy_sha256,"authenticated_pipe_exchange":true,"client_service_pid_verified_by_helper":true,"ledger_file_id":ledger,"executor_lock_file_id":lock,"helper_clock_qualified":clock_qualified,"helper_ready":ready,"system_capability_advertised":false,"no_jobs":true});
self.check_pin()?;
write_current_probe(state, &value)
}
pub async fn snapshot(&self, generation: u64, boot: uuid::Uuid) -> Result<HelperSnapshot> {
let reply = self.call(ipc::Operation::Snapshot { generation }).await?;
let ipc::ReplyBody::Snapshot { snapshot } = reply.body else {
anyhow::bail!("HELPER_SNAPSHOT_DENIED");
};
ensure!(snapshot.boot_id == boot, "HELPER_BOOT_MISMATCH");
Ok(map_snapshot(&snapshot))
}
pub async fn apply(
&self,
response: &SyncResponse,
request_bytes: Vec<u8>,
boot: uuid::Uuid,
) -> Result<HelperSnapshot> {
let reply = self
.call(ipc::Operation::Apply {
response: rmm_agent_core::helper_reconcile::SignedResponse {
decision_bytes: response.decision_bytes.clone(),
signature: response.signature.clone(),
},
request_bytes,
})
.await?;
let ipc::ReplyBody::Applied { snapshot, .. } = reply.body else {
anyhow::bail!("HELPER_APPLY_DENIED");
};
ensure!(snapshot.boot_id == boot, "HELPER_BOOT_MISMATCH");
Ok(map_snapshot(&snapshot))
}
}
fn map_snapshot(s: &Snapshot) -> HelperSnapshot {
HelperSnapshot {
journal_id: s.journal_id,
checkpoint: s.checkpoint,
previous_decision_id: s.previous_decision_id,
attempts: s
.attempts
.iter()
.map(|a| SyncAttempt {
job_id: a.job_id.to_string(),
attempt_id: a.attempt_id.to_string(),
job_payload_hash: a.job_payload_hash.clone(),
grant_id: a.grant_id.to_string(),
consumption: a.consumption.clone(),
state: a.state.clone(),
revision: a.revision,
original_boot_id: a.original_boot_id.to_string(),
outcome_sha256: a.outcome_sha256.clone(),
outcome_bytes: a.outcome_bytes.clone(),
..Default::default()
})
.collect(),
}
}
fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
native::private_path(state, true)?;
let path = state.join(PROBE_FILE);
if path.try_exists()? {
native::private_path(&path, false)?;
}
let bytes = serde_json::to_vec(value)?;
ensure!(bytes.len() <= 8192, "HELPER_PROBE_REPORT_LIMIT");
// One fixed create-only staging file bounds even interrupted-report state.
// A leftover from a killed process is refused; it is never overwritten.
let temporary = state.join(".helper-probe.pending");
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
let written = (|| {
native::private_path(&temporary, false)?;
file.write_all(&bytes)?;
file.sync_all()?;
Ok::<_, anyhow::Error>(())
})();
drop(file);
let result = written.and_then(|()| {
std::fs::rename(&temporary, &path)?;
native::private_path(&path, false)
});
if result.is_err() {
// Only our successfully create_new-opened staging file is eligible.
let _ = std::fs::remove_file(&temporary);
}
result
}