Skip to main content

cmtraceopen_parser/dsregcmd/
derive.rs

1use chrono::{DateTime, Local, LocalResult, NaiveDateTime, TimeZone, Utc};
2use regex::Regex;
3
4use crate::dsregcmd::models::{
5    DsregcmdCaptureConfidence, DsregcmdDerived, DsregcmdDiagnosticInsight, DsregcmdDiagnosticPhase,
6    DsregcmdFacts, DsregcmdJoinType,
7};
8use crate::intune::models::IntuneDiagnosticSeverity;
9use std::sync::OnceLock;
10
11pub(super) const NETWORK_ERROR_MARKERS: &[&str] = &[
12    "ERROR_WINHTTP_TIMEOUT",
13    "ERROR_WINHTTP_NAME_NOT_RESOLVED",
14    "ERROR_WINHTTP_CANNOT_CONNECT",
15    "ERROR_WINHTTP_CONNECTION_ERROR",
16];
17
18fn certificate_timestamp_re() -> &'static Regex {
19    static CELL: OnceLock<Regex> = OnceLock::new();
20    CELL.get_or_init(|| {
21    Regex::new(
22        r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)?(?: UTC|Z)?|\d{1,2}/\d{1,2}/\d{4} \d{2}:\d{2}:\d{2}(?:\.\d+)?(?: UTC|Z)?",
23    )
24    .expect("valid certificate timestamp regex")
25})
26}
27
28pub(super) fn derive_facts(facts: &DsregcmdFacts, raw_input: &str) -> DsregcmdDerived {
29    let join_type = derive_join_type(facts);
30    let join_type_label = join_type_label(join_type).to_string();
31    let mdm_enrolled = if facts.management_details.mdm_url.is_some()
32        || facts.management_details.mdm_compliance_url.is_some()
33    {
34        Some(true)
35    } else {
36        None
37    };
38    let missing_mdm = match (
39        facts.management_details.mdm_url.is_some(),
40        facts.management_details.mdm_compliance_url.is_some(),
41    ) {
42        (false, true) => Some(true),
43        (true, _) => Some(false),
44        (false, false) => None,
45    };
46    let compliance_url_present = if facts.management_details.mdm_compliance_url.is_some() {
47        Some(true)
48    } else if facts.management_details.mdm_url.is_some() {
49        Some(false)
50    } else {
51        None
52    };
53    let missing_compliance_url = match (
54        facts.management_details.mdm_url.is_some(),
55        facts.management_details.mdm_compliance_url.is_some(),
56    ) {
57        (true, false) => Some(true),
58        (true, true) => Some(false),
59        (false, _) => None,
60    };
61    let azure_ad_prt_present = facts.sso_state.azure_ad_prt;
62    let prt_reference_time = facts
63        .diagnostics
64        .client_time
65        .as_deref()
66        .and_then(parse_dsregcmd_timestamp)
67        .or_else(|| Some(Utc::now()));
68    let prt_last_update = facts
69        .sso_state
70        .azure_ad_prt_update_time
71        .as_deref()
72        .and_then(parse_dsregcmd_timestamp);
73    let prt_age_hours = match (prt_reference_time, prt_last_update) {
74        (Some(reference_time), Some(last_update)) => {
75            let age_hours = reference_time
76                .signed_duration_since(last_update)
77                .num_minutes() as f64
78                / 60.0;
79            Some(age_hours.max(0.0))
80        }
81        _ => None,
82    };
83    let stale_prt = prt_age_hours.map(|hours| hours > 4.0);
84    let tpm_protected = facts.device_details.tpm_protected;
85    let (certificate_valid_from, certificate_valid_to) = facts
86        .device_details
87        .device_certificate_validity
88        .as_deref()
89        .map(parse_certificate_validity)
90        .unwrap_or((None, None));
91    let certificate_days_remaining = match (prt_reference_time, certificate_valid_to) {
92        (Some(reference_time), Some(valid_to)) => {
93            Some(valid_to.signed_duration_since(reference_time).num_days())
94        }
95        _ => None,
96    };
97    let certificate_expiring_soon = certificate_days_remaining.map(|days| days < 30);
98    let network_error_code = detect_network_error(raw_input);
99    let has_network_error = network_error_code.is_some();
100    let remote_session_system = match (
101        facts.diagnostics.user_context.as_deref(),
102        facts.user_state.session_is_not_remote,
103    ) {
104        (Some(user_context), Some(false)) if user_context.eq_ignore_ascii_case("SYSTEM") => {
105            Some(true)
106        }
107        (Some(_), Some(_)) => Some(false),
108        _ => None,
109    };
110    let dominant_phase = derive_dominant_phase(facts);
111    let phase_summary = phase_summary(dominant_phase).to_string();
112    let (capture_confidence, capture_confidence_reason) =
113        derive_capture_confidence(facts, prt_reference_time, remote_session_system);
114
115    DsregcmdDerived {
116        join_type,
117        join_type_label,
118        dominant_phase,
119        phase_summary,
120        capture_confidence,
121        capture_confidence_reason,
122        mdm_enrolled,
123        missing_mdm,
124        compliance_url_present,
125        missing_compliance_url,
126        azure_ad_prt_present,
127        stale_prt,
128        prt_last_update,
129        prt_reference_time,
130        prt_age_hours,
131        tpm_protected,
132        certificate_valid_from,
133        certificate_valid_to,
134        certificate_expiring_soon,
135        certificate_days_remaining,
136        network_error_code,
137        has_network_error,
138        remote_session_system,
139    }
140}
141
142pub(super) fn derive_join_type(facts: &DsregcmdFacts) -> DsregcmdJoinType {
143    match (
144        facts.join_state.azure_ad_joined,
145        facts.join_state.domain_joined,
146    ) {
147        (Some(true), Some(true)) => DsregcmdJoinType::HybridEntraIdJoined,
148        (Some(true), Some(false)) => DsregcmdJoinType::EntraIdJoined,
149        (Some(false), _) => DsregcmdJoinType::NotJoined,
150        _ => DsregcmdJoinType::Unknown,
151    }
152}
153
154fn join_type_label(join_type: DsregcmdJoinType) -> &'static str {
155    match join_type {
156        DsregcmdJoinType::HybridEntraIdJoined => "Hybrid Entra ID Joined",
157        DsregcmdJoinType::EntraIdJoined => "Entra ID Joined",
158        DsregcmdJoinType::NotJoined => "Not Joined",
159        DsregcmdJoinType::Unknown => "Unknown",
160    }
161}
162
163fn derive_dominant_phase(facts: &DsregcmdFacts) -> DsregcmdDiagnosticPhase {
164    if let Some(phase) = facts
165        .registration
166        .error_phase
167        .as_deref()
168        .and_then(parse_phase)
169    {
170        return phase;
171    }
172
173    if facts.diagnostics.attempt_status.is_some()
174        || facts.diagnostics.previous_prt_attempt.is_some()
175        || facts.sso_state.acquire_prt_diagnostics.is_some()
176    {
177        return DsregcmdDiagnosticPhase::PostJoin;
178    }
179
180    if is_failure(&facts.pre_join_tests.ad_connectivity_test) {
181        return DsregcmdDiagnosticPhase::Precheck;
182    }
183
184    if is_failure(&facts.pre_join_tests.ad_configuration_test)
185        || is_failure(&facts.pre_join_tests.drs_discovery_test)
186        || is_failure(&facts.pre_join_tests.drs_connectivity_test)
187    {
188        return DsregcmdDiagnosticPhase::Discover;
189    }
190
191    if is_failure(&facts.pre_join_tests.token_acquisition_test)
192        || has_any_code(
193            facts,
194            &[
195                "0xcaa90017",
196                "0xcaa9002c",
197                "0xcaa90023",
198                "0xcaa82ee2",
199                "0xcaa82efe",
200                "0xcaa82f8f",
201                "0xcaa82efd",
202                "0xcaa20003",
203                "0xcaa90014",
204                "0xcaa90006",
205                "0xcaa1002d",
206            ],
207        )
208    {
209        return DsregcmdDiagnosticPhase::Auth;
210    }
211
212    if facts.registration.client_error_code.is_some()
213        || facts.registration.server_error_code.is_some()
214        || facts.registration.server_message.is_some()
215    {
216        return DsregcmdDiagnosticPhase::Join;
217    }
218
219    if facts.sso_state.azure_ad_prt == Some(false)
220        || facts.sso_state.azure_ad_prt_update_time.is_some()
221    {
222        return DsregcmdDiagnosticPhase::PostJoin;
223    }
224
225    DsregcmdDiagnosticPhase::Unknown
226}
227
228fn phase_summary(phase: DsregcmdDiagnosticPhase) -> &'static str {
229    match phase {
230        DsregcmdDiagnosticPhase::Precheck => {
231            "Current evidence points to a precheck failure before discovery could complete."
232        }
233        DsregcmdDiagnosticPhase::Discover => {
234            "Current evidence points to a discover-phase failure while locating or reaching registration services."
235        }
236        DsregcmdDiagnosticPhase::Auth => {
237            "Current evidence points to an authentication-phase failure during federation or token acquisition."
238        }
239        DsregcmdDiagnosticPhase::Join => {
240            "Current evidence points to a join-phase failure while registering the device with Entra."
241        }
242        DsregcmdDiagnosticPhase::PostJoin => {
243            "Current evidence points to a post-join token, session, or refresh problem."
244        }
245        DsregcmdDiagnosticPhase::Unknown => {
246            "Current evidence does not isolate a single failure phase from this capture."
247        }
248    }
249}
250
251fn derive_capture_confidence(
252    facts: &DsregcmdFacts,
253    reference_time: Option<DateTime<Utc>>,
254    remote_session_system: Option<bool>,
255) -> (DsregcmdCaptureConfidence, String) {
256    if remote_session_system == Some(true) {
257        return (
258            DsregcmdCaptureConfidence::Low,
259            "Capture was taken as SYSTEM in a remote session, so user-scoped token and session evidence may be distorted.".to_string(),
260        );
261    }
262
263    if let Some(client_time) = facts
264        .diagnostics
265        .client_time
266        .as_deref()
267        .and_then(parse_dsregcmd_timestamp)
268    {
269        let age_minutes = Utc::now()
270            .signed_duration_since(client_time)
271            .num_minutes()
272            .abs();
273        if age_minutes <= 15
274            && facts.user_state.session_is_not_remote == Some(true)
275            && !matches!(facts.diagnostics.user_context.as_deref(), Some(context) if context.eq_ignore_ascii_case("SYSTEM"))
276        {
277            return (
278                DsregcmdCaptureConfidence::High,
279                "Capture looks recent and interactive, so user-scoped evidence should be trustworthy.".to_string(),
280            );
281        }
282
283        if age_minutes <= 24 * 60 {
284            return (
285                DsregcmdCaptureConfidence::Medium,
286                "Capture looks reasonably recent, but it may not exactly match the current device state.".to_string(),
287            );
288        }
289
290        return (
291            DsregcmdCaptureConfidence::Low,
292            "Capture looks old relative to the device clock, so conclusions may no longer match the current state.".to_string(),
293        );
294    }
295
296    if reference_time.is_some() {
297        return (
298            DsregcmdCaptureConfidence::Medium,
299            "Capture included enough timing context to analyze, but it did not provide a clearly recent interactive client timestamp.".to_string(),
300        );
301    }
302
303    (
304        DsregcmdCaptureConfidence::Medium,
305        "Capture confidence is moderate because the source lacked enough timing and session context to judge freshness precisely.".to_string(),
306    )
307}
308
309fn parse_phase(value: &str) -> Option<DsregcmdDiagnosticPhase> {
310    match value.trim().to_ascii_lowercase().as_str() {
311        "pre-check" | "precheck" => Some(DsregcmdDiagnosticPhase::Precheck),
312        "discover" => Some(DsregcmdDiagnosticPhase::Discover),
313        "auth" | "authentication" => Some(DsregcmdDiagnosticPhase::Auth),
314        "join" => Some(DsregcmdDiagnosticPhase::Join),
315        "post_join" | "post-join" | "postjoin" => Some(DsregcmdDiagnosticPhase::PostJoin),
316        _ => None,
317    }
318}
319
320pub(super) fn parse_dsregcmd_timestamp(value: &str) -> Option<DateTime<Utc>> {
321    let trimmed = value.trim();
322    if let Ok(parsed) = DateTime::parse_from_rfc3339(trimmed) {
323        return Some(parsed.with_timezone(&Utc));
324    }
325
326    for format in [
327        "%Y-%m-%d %H:%M:%S%.f UTC",
328        "%Y-%m-%d %H:%M:%S UTC",
329        "%m/%d/%Y %H:%M:%S%.f UTC",
330        "%m/%d/%Y %H:%M:%S UTC",
331    ] {
332        if let Ok(parsed) = NaiveDateTime::parse_from_str(trimmed, format) {
333            return Some(DateTime::<Utc>::from_naive_utc_and_offset(parsed, Utc));
334        }
335    }
336
337    for format in [
338        "%Y-%m-%d %H:%M:%S%.f",
339        "%Y-%m-%d %H:%M:%S",
340        "%m/%d/%Y %H:%M:%S%.f",
341        "%m/%d/%Y %H:%M:%S",
342    ] {
343        if let Ok(parsed) = NaiveDateTime::parse_from_str(trimmed, format) {
344            return match Local.from_local_datetime(&parsed) {
345                LocalResult::Single(local_time) => Some(local_time.with_timezone(&Utc)),
346                LocalResult::Ambiguous(local_time, _) => Some(local_time.with_timezone(&Utc)),
347                LocalResult::None => None,
348            };
349        }
350    }
351
352    None
353}
354
355fn parse_certificate_validity(value: &str) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
356    let timestamps: Vec<DateTime<Utc>> = certificate_timestamp_re()
357        .find_iter(value)
358        .filter_map(|capture| parse_dsregcmd_timestamp(capture.as_str()))
359        .collect();
360
361    match timestamps.as_slice() {
362        [valid_from, valid_to, ..] => (Some(*valid_from), Some(*valid_to)),
363        [valid_to] => (None, Some(*valid_to)),
364        _ => (None, None),
365    }
366}
367
368fn detect_network_error(raw_input: &str) -> Option<String> {
369    let uppercase = raw_input.to_ascii_uppercase();
370    NETWORK_ERROR_MARKERS
371        .iter()
372        .find(|marker| uppercase.contains(**marker))
373        .map(|marker| (*marker).to_string())
374}
375
376// ── Utility helpers shared across rule modules ──────────────────────────────
377
378pub(super) fn aggregated_error_text(facts: &DsregcmdFacts) -> String {
379    [
380        facts.registration.client_error_code.as_deref(),
381        facts.registration.server_error_code.as_deref(),
382        facts.registration.server_message.as_deref(),
383        facts.registration.server_error_description.as_deref(),
384        facts.diagnostics.attempt_status.as_deref(),
385        facts.diagnostics.http_error.as_deref(),
386    ]
387    .into_iter()
388    .flatten()
389    .collect::<Vec<_>>()
390    .join(" ")
391    .to_ascii_lowercase()
392}
393
394pub(super) fn has_code(facts: &DsregcmdFacts, code: &str) -> bool {
395    contains_text(&facts.registration.client_error_code, code)
396        || contains_text(&facts.registration.server_error_code, code)
397        || contains_text(&facts.registration.server_message, code)
398        || contains_text(&facts.registration.server_error_description, code)
399        || contains_text(&facts.diagnostics.attempt_status, code)
400        || contains_text(&facts.diagnostics.http_error, code)
401        || contains_text(&facts.pre_join_tests.token_acquisition_test, code)
402        || contains_text(&facts.pre_join_tests.drs_discovery_test, code)
403        || contains_text(&facts.pre_join_tests.ad_configuration_test, code)
404}
405
406pub(super) fn has_any_code(facts: &DsregcmdFacts, codes: &[&str]) -> bool {
407    codes.iter().any(|code| has_code(facts, code))
408}
409
410pub(super) fn is_failure(field: &Option<String>) -> bool {
411    field
412        .as_deref()
413        .map(|value| value.to_ascii_uppercase().contains("FAIL"))
414        .unwrap_or(false)
415}
416
417pub(super) fn is_failure_text(field: &Option<String>) -> bool {
418    field
419        .as_deref()
420        .map(|value| {
421            let normalized = value.to_ascii_uppercase();
422            normalized.contains("FAIL") || normalized.contains("ERROR")
423        })
424        .unwrap_or(false)
425}
426
427pub(super) fn render_phase_code_evidence(facts: &DsregcmdFacts, code: &str) -> String {
428    let sources = [
429        (
430            "Client ErrorCode",
431            facts.registration.client_error_code.as_deref(),
432        ),
433        (
434            "Attempt Status",
435            facts.diagnostics.attempt_status.as_deref(),
436        ),
437        ("HTTP Error", facts.diagnostics.http_error.as_deref()),
438        (
439            "Token Acquisition Test",
440            facts.pre_join_tests.token_acquisition_test.as_deref(),
441        ),
442    ];
443
444    for (label, value) in sources {
445        if let Some(value) = value {
446            if value
447                .to_ascii_lowercase()
448                .contains(&code.to_ascii_lowercase())
449            {
450                return format!("{label}: {value}");
451            }
452        }
453    }
454
455    format!("Code: {code}")
456}
457
458pub(super) fn push_test_failure(
459    diagnostics: &mut Vec<DsregcmdDiagnosticInsight>,
460    id: &str,
461    category: &str,
462    title: &str,
463    field: &Option<String>,
464    next_checks: Vec<String>,
465    suggested_fixes: Vec<String>,
466) {
467    let Some(value) = field.as_deref() else {
468        return;
469    };
470
471    if !value.to_ascii_uppercase().contains("FAIL") {
472        return;
473    }
474
475    let mut evidence = vec![format!("Result: {value}")];
476    if let Some(detail) = extract_bracket_detail(value) {
477        evidence.push(format!("Detail: {detail}"));
478    }
479
480    diagnostics.push(issue(
481        id,
482        IntuneDiagnosticSeverity::Error,
483        category,
484        title,
485        &format!("{title}."),
486        evidence,
487        next_checks,
488        suggested_fixes,
489    ));
490}
491
492fn extract_bracket_detail(value: &str) -> Option<String> {
493    let start = value.find('[')?;
494    let end = value[start + 1..].find(']')?;
495    let detail = &value[start + 1..start + 1 + end];
496    (!detail.trim().is_empty()).then(|| detail.trim().to_string())
497}
498
499// Diagnostic construction keeps explicit backend contract fields together.
500#[allow(clippy::too_many_arguments)]
501pub(super) fn issue(
502    id: &str,
503    severity: IntuneDiagnosticSeverity,
504    category: &str,
505    title: &str,
506    summary: &str,
507    evidence: Vec<String>,
508    next_checks: Vec<String>,
509    suggested_fixes: Vec<String>,
510) -> DsregcmdDiagnosticInsight {
511    DsregcmdDiagnosticInsight {
512        id: id.to_string(),
513        severity,
514        category: category.to_string(),
515        title: title.to_string(),
516        summary: summary.to_string(),
517        evidence,
518        next_checks,
519        suggested_fixes,
520    }
521}
522
523pub(super) fn render_optional(label: &str, value: &Option<String>) -> String {
524    match value {
525        Some(value) => format!("{label}: {value}"),
526        None => format!("{label}: (missing)"),
527    }
528}
529
530pub(super) fn render_bool(label: &str, value: Option<bool>) -> String {
531    match value {
532        Some(true) => format!("{label}: YES"),
533        Some(false) => format!("{label}: NO"),
534        None => format!("{label}: (unknown)"),
535    }
536}
537
538pub(super) fn contains_text(field: &Option<String>, needle: &str) -> bool {
539    field
540        .as_deref()
541        .map(|value| {
542            value
543                .to_ascii_lowercase()
544                .contains(&needle.to_ascii_lowercase())
545        })
546        .unwrap_or(false)
547}
548
549pub(super) fn equals_text(field: &Option<String>, expected: &str) -> bool {
550    field
551        .as_deref()
552        .map(|value| value.eq_ignore_ascii_case(expected))
553        .unwrap_or(false)
554}
555
556pub(super) fn is_missing(field: &Option<String>) -> bool {
557    field.is_none()
558}