1use std::collections::HashMap;
2
3use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
4
5use super::guid_registry::GuidRegistryEntry;
6
7#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
9#[serde(rename_all = "camelCase")]
10pub struct EvidenceBundleArtifactCounts {
11 pub collected: u64,
12 pub missing: u64,
13 pub failed: u64,
14 pub skipped: u64,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
19#[serde(rename_all = "camelCase")]
20pub struct EvidenceBundleMetadata {
21 pub manifest_path: String,
22 pub notes_path: Option<String>,
23 pub evidence_root: Option<String>,
24 #[serde(default)]
25 pub primary_entry_points: Vec<String>,
26 #[serde(default)]
27 pub available_primary_entry_points: Vec<String>,
28 pub bundle_id: Option<String>,
29 pub bundle_label: Option<String>,
30 pub created_utc: Option<String>,
31 pub case_reference: Option<String>,
32 pub summary: Option<String>,
33 pub collector_profile: Option<String>,
34 pub collector_version: Option<String>,
35 pub collected_utc: Option<String>,
36 pub device_name: Option<String>,
37 pub primary_user: Option<String>,
38 pub platform: Option<String>,
39 pub os_version: Option<String>,
40 pub tenant: Option<String>,
41 pub artifact_counts: Option<EvidenceBundleArtifactCounts>,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46pub enum IntuneDiagnosticSeverity {
47 Info,
48 Warning,
49 Error,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
54pub enum IntuneDiagnosticCategory {
55 Download,
56 Install,
57 Timeout,
58 Script,
59 Policy,
60 State,
61 General,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
66pub enum IntuneRemediationPriority {
67 Monitor,
68 Medium,
69 High,
70 Immediate,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76pub struct IntuneDiagnosticInsight {
77 pub id: String,
78 pub severity: IntuneDiagnosticSeverity,
79 pub category: IntuneDiagnosticCategory,
80 pub remediation_priority: IntuneRemediationPriority,
81 pub title: String,
82 pub summary: String,
83 pub likely_cause: Option<String>,
84 pub evidence: Vec<String>,
85 pub next_checks: Vec<String>,
86 #[serde(default)]
87 pub suggested_fixes: Vec<String>,
88 #[serde(default)]
89 pub focus_areas: Vec<String>,
90 #[serde(default)]
91 pub affected_source_files: Vec<String>,
92 #[serde(default)]
93 pub related_error_codes: Vec<String>,
94}
95
96#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
98pub enum IntuneEventType {
99 Win32App,
100 WinGetApp,
101 PowerShellScript,
102 Remediation,
103 Esp,
104 SyncSession,
105 PolicyEvaluation,
106 ContentDownload,
107 Other,
108}
109
110#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
112pub enum IntuneStatus {
113 Success,
114 Failed,
115 InProgress,
116 Pending,
117 Timeout,
118 Unknown,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124pub struct IntuneEvent {
125 pub id: u64,
127 pub event_type: IntuneEventType,
129 pub name: String,
131 pub guid: Option<String>,
133 pub status: IntuneStatus,
135 pub start_time: Option<String>,
137 pub end_time: Option<String>,
139 pub duration_secs: Option<f64>,
141 pub error_code: Option<String>,
143 pub detail: String,
145 pub source_file: String,
147 pub line_number: u32,
149 pub start_time_epoch: Option<i64>,
151 pub end_time_epoch: Option<i64>,
153 #[serde(skip_serializing_if = "Option::is_none")]
155 pub script_body: Option<String>,
156 #[serde(skip_serializing_if = "Option::is_none")]
158 pub parent_app_guid: Option<String>,
159}
160
161impl IntuneEvent {
162 pub fn status_is_failed(&self) -> bool {
164 matches!(self.status, IntuneStatus::Failed)
165 }
166
167 pub fn start_time_epoch_ms(&self) -> Option<i64> {
169 self.start_time_epoch
170 }
171
172 pub fn anchor_guid(&self) -> Option<&str> {
174 self.guid.as_deref()
175 }
176
177 pub fn display_name(&self) -> Option<&str> {
179 if self.name.is_empty() {
180 None
181 } else {
182 Some(self.name.as_str())
183 }
184 }
185
186 pub fn event_kind_label(&self) -> Option<&str> {
188 Some(match self.event_type {
189 IntuneEventType::Win32App => "App Install",
190 IntuneEventType::WinGetApp => "WinGet Install",
191 IntuneEventType::PowerShellScript => "Script",
192 IntuneEventType::Remediation => "Remediation",
193 IntuneEventType::Esp => "ESP",
194 IntuneEventType::SyncSession => "Sync",
195 IntuneEventType::PolicyEvaluation => "Policy",
196 IntuneEventType::ContentDownload => "Download",
197 IntuneEventType::Other => "Operation",
198 })
199 }
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
204#[serde(rename_all = "camelCase")]
205pub struct AppPolicyMetadata {
206 pub id: String,
207 pub name: String,
208 pub intent: Option<i32>,
209 pub target_type: Option<i32>,
210 pub install_command_line: Option<String>,
211 pub uninstall_command_line: Option<String>,
212 pub detection_rules: Vec<DetectionRuleMetadata>,
213 pub return_codes: Vec<ReturnCodeEntry>,
214 pub requirement_rules: Option<String>,
215 pub install_behavior: Option<i32>,
216}
217
218#[derive(Debug, Clone, Serialize, Deserialize)]
220#[serde(rename_all = "camelCase")]
221pub struct DetectionRuleMetadata {
222 pub detection_type: i32,
224 #[serde(skip_serializing_if = "Option::is_none")]
226 pub script_body: Option<String>,
227 #[serde(skip_serializing_if = "Option::is_none")]
228 pub enforce_signature_check: Option<bool>,
229 #[serde(skip_serializing_if = "Option::is_none")]
230 pub run_as_32_bit: Option<bool>,
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct ReturnCodeEntry {
237 pub return_code: i32,
238 #[serde(rename = "type")]
240 pub code_type: i32,
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize)]
245#[serde(rename_all = "camelCase")]
246pub struct DownloadStat {
247 pub content_id: String,
249 pub name: String,
251 pub size_bytes: u64,
253 pub speed_bps: f64,
255 pub do_percentage: f64,
257 pub duration_secs: f64,
259 pub success: bool,
261 pub timestamp: Option<String>,
263 pub timestamp_epoch: Option<i64>,
265}
266
267#[derive(Debug, Clone, Serialize, Deserialize, Default)]
269#[serde(rename_all = "camelCase")]
270pub struct IntuneTimestampBounds {
271 pub first_timestamp: Option<String>,
272 pub last_timestamp: Option<String>,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize, Default)]
277#[serde(rename_all = "camelCase")]
278pub struct IntuneDiagnosticsFileCoverage {
279 pub file_path: String,
280 pub event_count: u32,
281 pub download_count: u32,
282 pub timestamp_bounds: Option<IntuneTimestampBounds>,
283 #[serde(default)]
284 pub is_rotated_segment: bool,
285 pub rotation_group: Option<String>,
286}
287
288#[derive(Debug, Clone, Serialize, Deserialize, Default)]
290#[serde(rename_all = "camelCase")]
291pub struct IntuneDiagnosticsCoverage {
292 #[serde(default)]
293 pub files: Vec<IntuneDiagnosticsFileCoverage>,
294 pub timestamp_bounds: Option<IntuneTimestampBounds>,
295 #[serde(default)]
296 pub has_rotated_logs: bool,
297 pub dominant_source: Option<IntuneDominantSource>,
298}
299
300#[derive(Debug, Clone, Serialize, Deserialize, Default)]
302#[serde(rename_all = "camelCase")]
303pub struct IntuneDominantSource {
304 pub file_path: String,
305 pub event_count: u32,
306 pub event_share: Option<f64>,
307}
308
309#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
311pub enum IntuneDiagnosticsConfidenceLevel {
312 #[default]
313 Unknown,
314 Low,
315 Medium,
316 High,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize, Default)]
321#[serde(rename_all = "camelCase")]
322pub struct IntuneDiagnosticsConfidence {
323 pub level: IntuneDiagnosticsConfidenceLevel,
324 pub score: Option<f64>,
325 #[serde(default)]
326 pub reasons: Vec<String>,
327}
328
329#[derive(Debug, Clone, Serialize, Deserialize)]
331#[serde(rename_all = "camelCase")]
332pub struct IntuneRepeatedFailureGroup {
333 pub id: String,
334 pub name: String,
335 pub event_type: IntuneEventType,
336 pub error_code: Option<String>,
337 pub occurrences: u32,
338 pub timestamp_bounds: Option<IntuneTimestampBounds>,
339 #[serde(default)]
340 pub source_files: Vec<String>,
341 #[serde(default)]
342 pub sample_event_ids: Vec<u64>,
343}
344
345#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
351pub enum EventLogSeverity {
352 Critical,
353 Error,
354 Warning,
355 Information,
356 Verbose,
357 Unknown,
358}
359
360impl EventLogSeverity {
361 pub fn from_level(level: u8) -> Self {
363 match level {
364 1 => Self::Critical,
365 2 => Self::Error,
366 3 => Self::Warning,
367 4 => Self::Information,
368 5 => Self::Verbose,
369 _ => Self::Unknown,
370 }
371 }
372
373 pub fn is_error_or_warning(&self) -> bool {
374 matches!(self, Self::Critical | Self::Error | Self::Warning)
375 }
376}
377
378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
381pub enum EventLogChannel {
382 DeviceManagementAdmin,
383 DeviceManagementOperational,
384 Autopilot,
385 AadOperational,
386 DeliveryOptimizationOperational,
387 ManagementService,
388 ProvisioningDiagnosticsAdmin,
389 ShellCoreOperational,
390 TimeServiceOperational,
391 UserDeviceRegistrationAdmin,
392 CryptoDpapiOperational,
393 KerberosOperational,
394 SystemLog,
395 Other(String),
396}
397
398impl EventLogChannel {
399 pub fn from_channel_string(raw: &str) -> Self {
401 let lower = raw.to_ascii_lowercase();
402 if lower.contains("devicemanagement")
403 && lower.contains("/admin")
404 && !lower.contains("/operational")
405 {
406 Self::DeviceManagementAdmin
407 } else if lower.contains("devicemanagement") && lower.contains("/operational") {
408 Self::DeviceManagementOperational
409 } else if lower.contains("moderndeployment") && lower.contains("autopilot") {
410 Self::Autopilot
411 } else if lower.contains("-aad/operational") {
412 Self::AadOperational
413 } else if lower.contains("deliveryoptimization") && lower.contains("/operational") {
414 Self::DeliveryOptimizationOperational
415 } else if lower.contains("moderndeployment") && lower.contains("managementservice") {
416 Self::ManagementService
417 } else if lower.contains("provisioning-diagnostics") && lower.contains("/admin") {
418 Self::ProvisioningDiagnosticsAdmin
419 } else if lower.contains("shell-core") && lower.contains("/operational") {
420 Self::ShellCoreOperational
421 } else if lower.contains("time-service") && lower.contains("/operational") {
422 Self::TimeServiceOperational
423 } else if lower.contains("user device registration") && lower.contains("/admin") {
424 Self::UserDeviceRegistrationAdmin
425 } else if lower.contains("crypto-dpapi") && lower.contains("/operational") {
426 Self::CryptoDpapiOperational
427 } else if lower.contains("kerberos") && lower.contains("/operational") {
428 Self::KerberosOperational
429 } else if lower == "system" || lower.contains("system log") {
430 Self::SystemLog
431 } else if raw.is_empty() {
432 Self::Other("Unknown".to_string())
433 } else {
434 Self::Other(raw.to_string())
435 }
436 }
437
438 pub fn display_name(&self) -> &str {
440 match self {
441 Self::DeviceManagementAdmin => "MDM Admin",
442 Self::DeviceManagementOperational => "MDM Operational",
443 Self::Autopilot => "Autopilot",
444 Self::AadOperational => "AAD Operational",
445 Self::DeliveryOptimizationOperational => "DO Operational",
446 Self::ManagementService => "Management Service",
447 Self::ProvisioningDiagnosticsAdmin => "Provisioning Admin",
448 Self::ShellCoreOperational => "Shell Core",
449 Self::TimeServiceOperational => "Time Service",
450 Self::UserDeviceRegistrationAdmin => "User Device Reg",
451 Self::CryptoDpapiOperational => "Crypto DPAPI",
452 Self::KerberosOperational => "Kerberos",
453 Self::SystemLog => "System",
454 Self::Other(name) => name.as_str(),
455 }
456 }
457}
458
459#[derive(Debug, Clone, Serialize, Deserialize)]
461#[serde(rename_all = "camelCase")]
462pub struct EventLogEntry {
463 pub id: u64,
465 pub channel: EventLogChannel,
467 pub channel_display: String,
469 pub provider: String,
471 pub event_id: u32,
473 pub severity: EventLogSeverity,
475 pub timestamp: String,
477 pub computer: Option<String>,
479 pub message: String,
481 pub correlation_activity_id: Option<String>,
483 pub source_file: String,
485}
486
487#[derive(Debug, Clone, Serialize, Deserialize)]
489#[serde(rename_all = "camelCase")]
490pub struct EventLogChannelSummary {
491 pub channel: EventLogChannel,
492 pub channel_display: String,
493 pub entry_count: u32,
494 pub error_count: u32,
495 pub warning_count: u32,
496 pub timestamp_bounds: Option<IntuneTimestampBounds>,
497 pub source_file: String,
498}
499
500#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
503pub enum EventLogCorrelationKind {
504 TimeWindowChannelMatch,
506 ErrorCodeMatch,
508 EnrollmentContextMatch,
510}
511
512#[derive(Debug, Clone, Serialize, Deserialize)]
514#[serde(rename_all = "camelCase")]
515pub struct EventLogCorrelationLink {
516 pub event_log_entry_id: u64,
518 pub linked_intune_event_id: Option<u64>,
520 pub linked_diagnostic_id: Option<String>,
522 pub correlation_kind: EventLogCorrelationKind,
524 pub time_delta_secs: Option<f64>,
526}
527
528#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
530pub enum EventLogAnalysisSource {
531 #[default]
532 Bundle,
533 Live,
534}
535
536#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
538pub enum EventLogLiveQueryStatus {
539 #[default]
540 Success,
541 Empty,
542 Failed,
543}
544
545#[derive(Debug, Clone, Serialize, Deserialize)]
547#[serde(rename_all = "camelCase")]
548pub struct EventLogLiveQueryChannelResult {
549 pub channel: EventLogChannel,
550 pub channel_display: String,
551 pub channel_path: String,
552 pub source_file: String,
553 pub status: EventLogLiveQueryStatus,
554 pub entry_count: u32,
555 pub error_message: Option<String>,
556}
557
558#[derive(Debug, Clone, Serialize, Deserialize, Default)]
560#[serde(rename_all = "camelCase")]
561pub struct EventLogLiveQueryMetadata {
562 pub attempted_channel_count: u32,
563 pub successful_channel_count: u32,
564 pub channels_with_results_count: u32,
565 pub failed_channel_count: u32,
566 pub per_channel_entry_limit: u32,
567 #[serde(default)]
568 pub channels: Vec<EventLogLiveQueryChannelResult>,
569}
570
571#[derive(Debug, Clone, Serialize, Deserialize, Default)]
573#[serde(rename_all = "camelCase")]
574pub struct EventLogAnalysis {
575 pub source_kind: EventLogAnalysisSource,
576 pub entries: Vec<EventLogEntry>,
577 pub channel_summaries: Vec<EventLogChannelSummary>,
578 pub correlation_links: Vec<EventLogCorrelationLink>,
579 pub parsed_file_count: u32,
580 pub total_entry_count: u32,
581 pub error_entry_count: u32,
582 pub warning_entry_count: u32,
583 pub timestamp_bounds: Option<IntuneTimestampBounds>,
584 pub live_query: Option<EventLogLiveQueryMetadata>,
585}
586
587#[derive(Debug, Clone, Deserialize)]
593#[serde(rename_all = "camelCase")]
594pub struct IntuneAnalysisResult {
595 pub events: Vec<IntuneEvent>,
597 pub downloads: Vec<DownloadStat>,
599 pub summary: IntuneSummary,
601 #[serde(default)]
603 pub diagnostics: Vec<IntuneDiagnosticInsight>,
604 pub source_file: String,
606 #[serde(default)]
608 pub source_files: Vec<String>,
609 #[serde(default)]
611 pub diagnostics_coverage: IntuneDiagnosticsCoverage,
612 #[serde(default)]
614 pub diagnostics_confidence: IntuneDiagnosticsConfidence,
615 #[serde(default)]
617 pub repeated_failures: Vec<IntuneRepeatedFailureGroup>,
618 #[serde(default)]
620 pub evidence_bundle: Option<EvidenceBundleMetadata>,
621 #[serde(default)]
623 pub event_log_analysis: Option<EventLogAnalysis>,
624 #[serde(default)]
626 pub guid_registry: HashMap<String, GuidRegistryEntry>,
627 #[serde(default)]
629 pub policy_metadata: HashMap<String, AppPolicyMetadata>,
630}
631
632impl Serialize for IntuneAnalysisResult {
633 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
634 where
635 S: Serializer,
636 {
637 let mut state = serializer.serialize_struct("IntuneAnalysisResult", 13)?;
638 state.serialize_field("events", &self.events)?;
639 state.serialize_field("downloads", &self.downloads)?;
640 state.serialize_field("summary", &self.summary)?;
641 state.serialize_field("diagnostics", &self.diagnostics)?;
642 state.serialize_field("sourceFile", &self.source_file)?;
643 state.serialize_field("sourceFiles", &self.source_files)?;
644 state.serialize_field("diagnosticsCoverage", &self.diagnostics_coverage)?;
645 state.serialize_field("diagnosticsConfidence", &self.diagnostics_confidence)?;
646 state.serialize_field("repeatedFailures", &self.repeated_failures)?;
647 state.serialize_field("evidenceBundle", &self.evidence_bundle)?;
648 state.serialize_field("eventLogAnalysis", &self.event_log_analysis)?;
649 state.serialize_field("guidRegistry", &self.guid_registry)?;
650 state.serialize_field("policyMetadata", &self.policy_metadata)?;
651 state.end()
652 }
653}
654
655#[derive(Debug, Clone, Serialize, Deserialize)]
657#[serde(rename_all = "camelCase")]
658pub struct IntuneSummary {
659 pub total_events: u32,
660 pub win32_apps: u32,
661 pub winget_apps: u32,
662 pub scripts: u32,
663 pub remediations: u32,
664 pub succeeded: u32,
665 pub failed: u32,
666 pub in_progress: u32,
667 pub pending: u32,
668 pub timed_out: u32,
669 pub total_downloads: u32,
670 pub successful_downloads: u32,
671 pub failed_downloads: u32,
672 pub failed_scripts: u32,
673 pub log_time_span: Option<String>,
674}
675
676#[cfg(test)]
677mod tests {
678 use std::collections::HashMap;
679
680 use super::{
681 EvidenceBundleArtifactCounts, EvidenceBundleMetadata, IntuneAnalysisResult,
682 IntuneDiagnosticsConfidence, IntuneDiagnosticsCoverage, IntuneSummary,
683 };
684
685 #[test]
686 fn intune_analysis_result_serializes_evidence_bundle_metadata() {
687 let result = IntuneAnalysisResult {
688 events: Vec::new(),
689 downloads: Vec::new(),
690 summary: IntuneSummary {
691 total_events: 0,
692 win32_apps: 0,
693 winget_apps: 0,
694 scripts: 0,
695 remediations: 0,
696 succeeded: 0,
697 failed: 0,
698 in_progress: 0,
699 pending: 0,
700 timed_out: 0,
701 total_downloads: 0,
702 successful_downloads: 0,
703 failed_downloads: 0,
704 failed_scripts: 0,
705 log_time_span: None,
706 },
707 diagnostics: Vec::new(),
708 source_file: "bundle-root".to_string(),
709 source_files: Vec::new(),
710 diagnostics_coverage: IntuneDiagnosticsCoverage::default(),
711 diagnostics_confidence: IntuneDiagnosticsConfidence::default(),
712 repeated_failures: Vec::new(),
713 event_log_analysis: None,
714 guid_registry: HashMap::new(),
715 policy_metadata: HashMap::new(),
716 evidence_bundle: Some(EvidenceBundleMetadata {
717 manifest_path: "bundle-root/manifest.json".to_string(),
718 notes_path: Some("bundle-root/notes.md".to_string()),
719 evidence_root: Some("bundle-root/evidence".to_string()),
720 primary_entry_points: vec!["bundle-root/evidence/logs".to_string()],
721 available_primary_entry_points: vec!["bundle-root/evidence/logs".to_string()],
722 bundle_id: Some("CMTRACE-123".to_string()),
723 bundle_label: Some("intune-endpoint-evidence".to_string()),
724 created_utc: Some("2026-03-12T16:00:54Z".to_string()),
725 case_reference: Some("case-123".to_string()),
726 summary: Some("Collected bundle".to_string()),
727 collector_profile: Some("intune-windows-endpoint-v1".to_string()),
728 collector_version: Some("1.1.0".to_string()),
729 collected_utc: Some("2026-03-12T16:00:54Z".to_string()),
730 device_name: Some("GELL-VM-5879648".to_string()),
731 primary_user: Some("AzureAD\\AdamGell".to_string()),
732 platform: Some("Windows".to_string()),
733 os_version: Some("Windows 11".to_string()),
734 tenant: Some("CDWWorkspaceLab".to_string()),
735 artifact_counts: Some(EvidenceBundleArtifactCounts {
736 collected: 55,
737 missing: 7,
738 failed: 2,
739 skipped: 0,
740 }),
741 }),
742 };
743
744 let value = serde_json::to_value(&result).expect("serialize result");
745
746 assert_eq!(
747 value["evidenceBundle"]["bundleId"].as_str(),
748 Some("CMTRACE-123")
749 );
750 assert_eq!(
751 value["evidenceBundle"]["artifactCounts"]["collected"].as_u64(),
752 Some(55)
753 );
754 }
755}