diff --git a/apps/gpservice/src/hip_preview.rs b/apps/gpservice/src/hip_preview.rs index 3f98408..85f9960 100644 --- a/apps/gpservice/src/hip_preview.rs +++ b/apps/gpservice/src/hip_preview.rs @@ -85,7 +85,7 @@ impl HipPreviews { }) .await; let result = match generated { - Ok(Ok(xml)) => preview_result(®istry, session_id, xml), + Ok(Ok(report)) => preview_result(®istry, session_id, report), Ok(Err(error)) => { log::warn!("HIP preview failed: {error:#}"); ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed") @@ -132,17 +132,20 @@ impl HipPreviews { } } -fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult { - let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| { - registry - .hip_preview_chunk(session_id, preview_id, 0) - .map(|(xml, complete)| ServiceResult::HipPreviewChunk { - preview_id: preview_id.to_string(), - offset: 0, - xml, - complete, - }) - }); +fn preview_result(registry: &SessionRegistry, session_id: Uuid, report: gpapi::hip::HipReport) -> ServiceResult { + let result = registry + .store_hip_preview(session_id, report.xml) + .and_then(|preview_id| { + registry + .hip_preview_chunk(session_id, preview_id, 0) + .map(|(xml, complete)| ServiceResult::HipPreviewChunk { + preview_id: preview_id.to_string(), + offset: 0, + xml, + complete, + windows_updates: report.windows_updates, + }) + }); result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable")) } @@ -152,7 +155,7 @@ fn generate( desktop_uid: Option, identity: HostIdentity, cancellation: CancellationToken, -) -> anyhow::Result { +) -> anyhow::Result { ensure!(request.client_version.len() <= 64, "Invalid HIP client version"); ensure!( request.host_id.as_ref().is_none_or(|id| id.len() <= 256), @@ -188,7 +191,15 @@ fn generate( }; let xml = match &request.source { HipSource::Disabled => bail!("HIP is disabled"), - HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?, + HipSource::Generated => { + return gphip::generate_report_details( + &gphip::ReportInput { + profile, + context: gphip::ReportContext::Preview, + }, + &check, + ); + } HipSource::Edited { .. } => { let xml = edited_report.context("Edited HIP report is unavailable")?; crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)? @@ -204,7 +215,10 @@ fn generate( } }; check()?; - Ok(xml) + Ok(gpapi::hip::HipReport { + xml, + windows_updates: None, + }) } #[cfg(test)] diff --git a/apps/gpservice/src/main.rs b/apps/gpservice/src/main.rs index fcb9bbb..afcdd59 100644 --- a/apps/gpservice/src/main.rs +++ b/apps/gpservice/src/main.rs @@ -22,6 +22,8 @@ mod runtime_user; mod session_registry; mod vpn_script; mod vpn_task; +#[cfg(windows)] +mod windows_patches; mod ws_connection; mod ws_server; diff --git a/apps/gpservice/src/request_dispatcher.rs b/apps/gpservice/src/request_dispatcher.rs index 8f80dcc..5adaafb 100644 --- a/apps/gpservice/src/request_dispatcher.rs +++ b/apps/gpservice/src/request_dispatcher.rs @@ -70,6 +70,10 @@ pub struct RequestDispatcher { } impl RequestDispatcher { + #[cfg(windows)] + pub(crate) fn patch_checks(&self) -> Arc { + self.lifecycle.patch_checks.clone() + } pub fn subscribe_tunnel(&self) -> tokio::sync::watch::Receiver { self.lifecycle.subscribe_tunnel() } @@ -262,7 +266,9 @@ impl RequestDispatcher { | WsRequest::GetHipApprovalStatus { .. } | WsRequest::ReadHipPreviewChunk(_) | WsRequest::GetLastSubmittedHipReport - | WsRequest::SetTunnelStatisticsEnabled { .. } => { + | WsRequest::SetTunnelStatisticsEnabled { .. } + | WsRequest::SetWindowsPatchInterest { .. } + | WsRequest::RefreshWindowsPatches { .. } => { unreachable!("session-bound request was already dispatched") } } diff --git a/apps/gpservice/src/vpn_task.rs b/apps/gpservice/src/vpn_task.rs index 6007999..8709b14 100644 --- a/apps/gpservice/src/vpn_task.rs +++ b/apps/gpservice/src/vpn_task.rs @@ -31,6 +31,8 @@ mod script_tun; #[derive(Clone)] pub(crate) struct LifecycleHandle { + #[cfg(windows)] + pub(crate) patch_checks: Arc, events: mpsc::Sender, admissions: Arc>, tunnel: watch::Sender, @@ -462,6 +464,8 @@ impl VpnTask { ) -> (Self, LifecycleHandle) { let (events_tx, events) = mpsc::channel(4); let lifecycle = LifecycleHandle { + #[cfg(windows)] + patch_checks: crate::windows_patches::PatchChecks::new(), events: events_tx, admissions: Arc::new(Mutex::new(Admissions::default())), tunnel: watch::channel(TunnelBinding::default()).0, diff --git a/apps/gpservice/src/vpn_task/runtime.rs b/apps/gpservice/src/vpn_task/runtime.rs index cfa29b5..f9f13ae 100644 --- a/apps/gpservice/src/vpn_task/runtime.rs +++ b/apps/gpservice/src/vpn_task/runtime.rs @@ -50,6 +50,23 @@ pub(super) fn spawn( ) -> JoinHandle<()> { tokio::spawn(async move { let attempt = input.attempt; + #[cfg(windows)] + let _patch_interest = { + let args = input.connection.request.args(); + let profile = &input.connection.resources.profile; + (matches!(args.hip_source(), gpapi::hip::HipSource::Generated) + && profile.is_native() + && profile.client_os() == gpapi::os_profile::ClientOs::Windows + && (input.connection.request.plan().policy().collect_hip_data() + || input + .connection + .request + .plan() + .members() + .iter() + .any(|member| member.authentication.mode() == SessionMode::Tunnel))) + .then(|| input.lifecycle.patch_checks.consumer()) + }; let mut failure = None; let mut approval = None; if !cancellation.is_cancelled() { diff --git a/apps/gpservice/src/windows_patches.rs b/apps/gpservice/src/windows_patches.rs new file mode 100644 index 0000000..d53ed19 --- /dev/null +++ b/apps/gpservice/src/windows_patches.rs @@ -0,0 +1,159 @@ +//! One service-owned local patch search, independent of report generation. +use gpapi::{ + collection::{CollectionBudget, CollectionControl}, + process::collection::CollectorCommands, +}; +use std::{ + collections::HashSet, + sync::{Arc, Mutex}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use tokio::sync::{mpsc, oneshot}; +use tokio_util::sync::CancellationToken; +use uuid::Uuid; + +const INTERVAL: Duration = Duration::from_secs(15 * 60); +const SEARCH_TIMEOUT: Duration = Duration::from_secs(60); + +enum Command { + Interest(Uuid, bool), + CheckIfDue, + Refresh(Option, oneshot::Sender), +} + +pub(crate) struct PatchChecks { + tx: mpsc::UnboundedSender, + rx: Mutex>>, +} + +pub(crate) struct Consumer { + checks: Arc, + id: Uuid, +} +impl Drop for Consumer { + fn drop(&mut self) { + self.checks.set_interest(self.id, false); + } +} + +impl PatchChecks { + pub(crate) fn new() -> Arc { + let (tx, rx) = mpsc::unbounded_channel(); + Arc::new(Self { + tx, + rx: Mutex::new(Some(rx)), + }) + } + pub(crate) fn set_interest(&self, id: Uuid, enabled: bool) { + let _ = self.tx.send(Command::Interest(id, enabled)); + } + pub(crate) fn check_if_due(&self) { + let _ = self.tx.send(Command::CheckIfDue); + } + pub(crate) fn consumer(self: &Arc) -> Consumer { + let id = Uuid::new_v4(); + self.set_interest(id, true); + Consumer { + checks: self.clone(), + id, + } + } + pub(crate) async fn refresh(&self, after: Option) -> bool { + let (tx, rx) = oneshot::channel(); + if self.tx.send(Command::Refresh(after, tx)).is_err() { + return false; + } + rx.await.unwrap_or(false) + } + pub(crate) async fn run(&self, stop: CancellationToken) { + let Some(mut commands) = self.rx.lock().unwrap().take() else { + return; + }; + let mut consumers = HashSet::new(); + let mut waiters = Vec::>::new(); + let mut worker = None; + // Reading status never searches Windows Update. Missing/unreadable data is due immediately. + let status = tokio::task::spawn_blocking({ + let stop = stop.clone(); + move || helper("--patch-status", None, stop) + }) + .await; + let mut next = match status { + Ok(Ok(Some(checked))) => checked.saturating_add(INTERVAL.as_secs()), + _ => 0, + }; + loop { + tokio::select! { + _ = stop.cancelled() => break, + command = commands.recv() => { + match command { + Some(Command::Interest(id, enabled)) => { + if enabled { consumers.insert(id); } else { consumers.remove(&id); } + } + Some(Command::CheckIfDue) => { + if worker.is_none() && now() >= next { worker = Some(start(None, stop.clone())); } + } + Some(Command::Refresh(after, reply)) => { + waiters.push(reply); + if worker.is_none() { worker = Some(start(after, stop.clone())); } + } + None => break, + } + } + result = async { match &mut worker { Some(task) => task.await, None => std::future::pending().await } } => { + worker = None; + let success = matches!(&result, Ok(Ok(Some(_)))); + if !success { log::warn!("Local Windows patch check failed: {result:?}"); } + for reply in waiters.drain(..) { let _ = reply.send(success); } + next = match result { + Ok(Ok(Some(checked))) => checked.saturating_add(INTERVAL.as_secs()), + _ => now().saturating_add(INTERVAL.as_secs()), + }; + } + _ = tokio::time::sleep(Duration::from_secs(next.saturating_sub(now()).min(30))), + if worker.is_none() && !consumers.is_empty() => { + if now() >= next { worker = Some(start(None, stop.clone())); } + } + } + } + if let Some(task) = worker { + let _ = task.await; + } + for reply in waiters { + let _ = reply.send(false); + } + } +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} +fn start(after: Option, stop: CancellationToken) -> tokio::task::JoinHandle>> { + tokio::task::spawn_blocking(move || helper("--refresh-patches", after, stop)) +} +fn helper(command: &str, after: Option, stop: CancellationToken) -> anyhow::Result> { + let budget = CollectionBudget::new(SEARCH_TIMEOUT); + let check = || { + if stop.is_cancelled() { + return Err(std::io::Error::new( + std::io::ErrorKind::Interrupted, + "Patch check cancelled", + )); + } + budget.check() + }; + let path = std::env::current_exe()?.with_file_name("gp-posture.exe"); + let after = after.map(|after| after.to_string()); + let mut args = vec![command]; + if let Some(after) = &after { + args.push(after); + } + let output = CollectorCommands::new(&check) + .run_executable(&path, &args)? + .ok_or_else(|| anyhow::anyhow!("Windows posture helper is unavailable"))?; + anyhow::ensure!(output.status.success(), "Windows posture helper failed"); + Ok(serde_json::from_slice(&output.stdout)?) +} diff --git a/apps/gpservice/src/ws_connection.rs b/apps/gpservice/src/ws_connection.rs index 34f81b3..c31396b 100644 --- a/apps/gpservice/src/ws_connection.rs +++ b/apps/gpservice/src/ws_connection.rs @@ -410,6 +410,48 @@ async fn handle_client_message( return Ok(()); } + if let WsRequest::SetWindowsPatchInterest { enabled } = &request { + #[cfg(windows)] + ctx.patch_checks.set_interest(control.connection_id(), *enabled); + #[cfg(not(windows))] + let _ = enabled; + control + .send(ConnectionCommand::Reply { + id, + result: ServiceResult::Accepted, + }) + .map_err(|_| ())?; + return Ok(()); + } + if let WsRequest::RefreshWindowsPatches { after } = &request { + #[cfg(windows)] + { + let checks = ctx.patch_checks.clone(); + let control = control.clone(); + let after = Some(after.unwrap_or(0)); + tokio::spawn(async move { + let success = checks.refresh(after).await; + let result = if success { + ServiceResult::Accepted + } else { + ServiceResult::rejected(ServiceErrorCode::Internal, "Couldn’t check local updates.") + }; + let _ = control.send(ConnectionCommand::Reply { id, result }); + }); + } + #[cfg(not(windows))] + { + let _ = after; + control + .send(ConnectionCommand::Reply { + id, + result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Windows patch checks are unavailable"), + }) + .map_err(|_| ())?; + } + return Ok(()); + } + if let WsRequest::StoreEditedHipReportChunk(report) = request { let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok()); let result = if report.upload_id.is_some() && upload_id.is_none() { @@ -451,6 +493,7 @@ async fn handle_client_message( offset: chunk.offset, xml, complete, + windows_updates: None, }) }) .unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable")); @@ -467,6 +510,7 @@ async fn handle_client_message( offset: 0, xml, complete, + windows_updates: None, }, Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"), }, @@ -501,6 +545,10 @@ async fn handle_client_message( } if let WsRequest::PreviewHipReport(preview) = request { + #[cfg(windows)] + if preview.client_os == gpapi::os_profile::ClientOs::Windows && matches!(preview.source, HipSource::Generated) { + ctx.patch_checks.check_if_due(); + } let edited_report = if let HipSource::Edited { report_id } = &preview.source { let report_id = match Uuid::parse_str(report_id) { Ok(id) => id, diff --git a/apps/gpservice/src/ws_server.rs b/apps/gpservice/src/ws_server.rs index 167c8a1..713da08 100644 --- a/apps/gpservice/src/ws_server.rs +++ b/apps/gpservice/src/ws_server.rs @@ -63,6 +63,8 @@ pub(crate) struct WsServerContext { state: Mutex, handshake_slots: Arc, pub(crate) hip_previews: crate::hip_preview::HipPreviews, + #[cfg(windows)] + pub(crate) patch_checks: Arc, } impl WsServerContext { @@ -75,6 +77,8 @@ impl WsServerContext { Self { product_version, registry, + #[cfg(windows)] + patch_checks: dispatcher.patch_checks(), dispatcher, state: Mutex::new(ServiceState { revision: 0, @@ -183,6 +187,8 @@ impl WsServerContext { pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) { self.registry.disconnect_if_current(session_id, generation); + #[cfg(windows)] + self.patch_checks.set_interest(connection_id, false); let mut state = self.state.lock().await; state.connections.remove(&connection_id); state.refresh_demand(); @@ -364,6 +370,12 @@ impl WsServer { }; let _ = ready_tx.send(()); + #[cfg(windows)] + let patch_task = { + let checks = self.ctx.patch_checks.clone(); + let stop = self.cancel_token.clone(); + tokio::spawn(async move { checks.run(stop).await }) + }; tokio::select! { _ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => { info!("VPN state watch task completed"); @@ -378,6 +390,9 @@ impl WsServer { info!("WS server cancelled"); } } + self.cancel_token.cancel(); + #[cfg(windows)] + let _ = patch_task.await; self.ctx.hip_previews.shutdown().await; let _ = shutdown_tx.send(()).await; } diff --git a/crates/gpapi/src/hip.rs b/crates/gpapi/src/hip.rs index 58e00d4..6c3829f 100644 --- a/crates/gpapi/src/hip.rs +++ b/crates/gpapi/src/hip.rs @@ -45,3 +45,18 @@ mod tests { assert_eq!(serde_json::from_value::(json).unwrap(), source); } } + +/// Collection metadata for the exact XML returned by a generated preview. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct HipReport { + pub xml: String, + pub windows_updates: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct WindowsUpdateStatus { + /// Present only when this report includes a completed local patch observation. + pub checked_at: Option, +} diff --git a/crates/gpapi/src/service/request.rs b/crates/gpapi/src/service/request.rs index 8f78f2b..236632b 100644 --- a/crates/gpapi/src/service/request.rs +++ b/crates/gpapi/src/service/request.rs @@ -424,6 +424,8 @@ pub struct UpdateLogLevelRequest(pub String); #[derive(Debug, Deserialize, Serialize)] pub enum WsRequest { SetTunnelStatisticsEnabled { enabled: bool }, + SetWindowsPatchInterest { enabled: bool }, + RefreshWindowsPatches { after: Option }, Connect(Box), Disconnect(DisconnectRequest), StopNonTunnelAttachment { connection_id: uuid::Uuid }, diff --git a/crates/gpapi/src/service/transport/message.rs b/crates/gpapi/src/service/transport/message.rs index 805e5e7..441546f 100644 --- a/crates/gpapi/src/service/transport/message.rs +++ b/crates/gpapi/src/service/transport/message.rs @@ -55,6 +55,8 @@ pub enum ServiceResult { offset: usize, xml: String, complete: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + windows_updates: Option, }, HipApprovalStatus(HipApprovalStatus), NoSubmittedHipReport, diff --git a/crates/gphip/src/lib.rs b/crates/gphip/src/lib.rs index 2cac6f4..6fbfdc1 100644 --- a/crates/gphip/src/lib.rs +++ b/crates/gphip/src/lib.rs @@ -275,10 +275,18 @@ pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result { } pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result { + Ok(generate_report_details(input, control)?.xml) +} + +pub fn generate_report_details( + input: &ReportInput, + control: &dyn CollectionControl, +) -> anyhow::Result { control.check()?; let cookie_params = cookie_params(input); let (generate_time, day, month, year) = get_current_time_components(); let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect(control)?; + let windows_updates = host_info.windows_updates.clone(); let template = HipReportTemplate { client_version: input.profile.client_version(), generate_time, @@ -289,9 +297,9 @@ pub fn generate_report_with_control(input: &ReportInput, control: &dyn Collectio host_info, md5: input.context.md5(), }; - let report = format_xml(&template.render()?)?; + let xml = format_xml(&template.render()?)?; control.check()?; - Ok(report) + Ok(gpapi::hip::HipReport { xml, windows_updates }) } fn cookie_params(input: &ReportInput) -> HashMap { @@ -373,6 +381,7 @@ struct HostInfo { sentinel: Option, ufw: Option, windows_categories: Option, + windows_updates: Option, } impl HostInfo { @@ -497,6 +506,7 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { sentinel: None, ufw: None, windows_categories: None, + windows_updates: None, }) } @@ -558,7 +568,11 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { let commands = CollectorCommands::new(control); #[cfg(windows)] if self.profile.client_os() == ClientOs::Windows && self.profile.is_native() { - info.windows_categories = Some(windows::collect(&commands, control)?.render()?); + let report = windows::collect(&commands, control)?; + info.windows_updates = Some(gpapi::hip::WindowsUpdateStatus { + checked_at: report.patches_checked_at, + }); + info.windows_categories = Some(report.render()?); } if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() { diff --git a/crates/gphip/src/windows_report.rs b/crates/gphip/src/windows_report.rs index ee71d85..5d20347 100644 --- a/crates/gphip/src/windows_report.rs +++ b/crates/gphip/src/windows_report.rs @@ -11,6 +11,7 @@ pub(super) struct WindowsReport { pub firewall: Vec, pub patch_management: Vec, pub missing_patches: Option>, + pub patches_checked_at: Option, pub unavailable: Vec, }