Skip to main content

cmtraceopen_parser/dsregcmd/
rules.rs

1use crate::dsregcmd::models::{
2    DsregcmdAnalysisResult, DsregcmdDiagnosticInsight, DsregcmdFacts, DsregcmdJoinType,
3};
4use crate::intune::models::IntuneDiagnosticSeverity;
5
6use super::derive::{
7    aggregated_error_text, contains_text, derive_facts, equals_text, has_code, is_failure,
8    is_failure_text, is_missing, issue, push_test_failure, render_bool, render_optional,
9    render_phase_code_evidence,
10};
11
12// Re-export public items that external callers depend on.
13pub use super::extended::{
14    apply_enrollment_cross_reference, build_active_diagnostics_rules, build_event_log_diagnostics,
15    build_extended_diagnostics,
16};
17
18pub fn analyze_facts(facts: DsregcmdFacts, raw_input: &str) -> DsregcmdAnalysisResult {
19    let derived = derive_facts(&facts, raw_input);
20    let diagnostics = build_diagnostics(&facts, &derived);
21
22    DsregcmdAnalysisResult {
23        facts,
24        derived,
25        diagnostics,
26        policy_evidence: Default::default(),
27        os_version: None,
28        proxy_evidence: None,
29        enrollment_evidence: None,
30        active_evidence: None,
31        scheduled_task_evidence: None,
32        event_log_analysis: None,
33    }
34}
35
36fn build_diagnostics(
37    facts: &DsregcmdFacts,
38    derived: &super::models::DsregcmdDerived,
39) -> Vec<DsregcmdDiagnosticInsight> {
40    let mut diagnostics = Vec::new();
41    let aggregated_errors = aggregated_error_text(facts);
42
43    if facts.join_state.azure_ad_joined == Some(false) {
44        diagnostics.push(issue(
45            "not-aadj",
46            IntuneDiagnosticSeverity::Error,
47            "authentication",
48            "Device is not Entra ID joined",
49            "AzureAdJoined is NO, so this device is not currently joined to Entra ID.",
50            vec![render_bool("AzureAdJoined", facts.join_state.azure_ad_joined)],
51            vec![
52                "Confirm whether the device should be Entra ID joined or hybrid joined.".to_string(),
53                "Review the registration section for client or server error codes.".to_string(),
54            ],
55            vec![
56                "Retry the join or registration workflow from the intended user context.".to_string(),
57                "Check tenant targeting, licensing, and connectivity to Entra device registration endpoints.".to_string(),
58            ],
59        ));
60    }
61
62    if is_missing(&facts.tenant_details.tenant_id) {
63        diagnostics.push(issue(
64            "missing-tenant",
65            IntuneDiagnosticSeverity::Error,
66            "configuration",
67            "Tenant identifier is missing",
68            "The dsregcmd output did not include TenantId, which usually indicates registration never completed or the device is not properly scoped to a tenant.",
69            vec![render_optional("TenantId", &facts.tenant_details.tenant_id)],
70            vec![
71                "Verify the device is targeting the expected Entra tenant.".to_string(),
72                "Check registration errors and the join server endpoints in the dsregcmd output.".to_string(),
73            ],
74            vec![
75                "Re-run device registration after confirming tenant discovery and network access.".to_string(),
76            ],
77        ));
78    }
79
80    if is_missing(&facts.device_details.device_id) {
81        diagnostics.push(issue(
82            "missing-deviceid",
83            IntuneDiagnosticSeverity::Error,
84            "configuration",
85            "Device identifier is missing",
86            "The dsregcmd output did not include DeviceId, so the device is not presenting a stable Entra device identity.",
87            vec![render_optional("DeviceId", &facts.device_details.device_id)],
88            vec![
89                "Check whether the device certificate and join state are populated.".to_string(),
90                "Review previous registration attempts and pre-join test results.".to_string(),
91            ],
92            vec![
93                "Complete or repair device registration before troubleshooting downstream MDM or PRT issues.".to_string(),
94            ],
95        ));
96    }
97
98    if contains_text(&facts.registration.client_error_code, "0x801c03f2")
99        || contains_text(&facts.registration.server_error_code, "directoryerror")
100        || aggregated_errors.contains("directory sync pending")
101    {
102        diagnostics.push(issue(
103            "entra-sync-pending",
104            IntuneDiagnosticSeverity::Error,
105            "sync",
106            "Directory synchronization appears to be pending",
107            "The registration errors match the common hybrid join state where the device object has not fully synchronized to Entra ID yet.",
108            vec![
109                render_optional("Client ErrorCode", &facts.registration.client_error_code),
110                render_optional("Server ErrorCode", &facts.registration.server_error_code),
111            ],
112            vec![
113                "Confirm the corresponding on-premises device object has synchronized to Entra ID.".to_string(),
114                "Check Azure AD Connect or Cloud Sync health and object writeback timing.".to_string(),
115            ],
116            vec![
117                "Wait for directory synchronization to complete, then retry registration.".to_string(),
118            ],
119        ));
120    }
121
122    if aggregated_errors.contains("aadsts50155") {
123        diagnostics.push(issue(
124            "aadsts50155",
125            IntuneDiagnosticSeverity::Error,
126            "authentication",
127            "Device authentication failed with AADSTS50155",
128            "The tenant rejected the authentication request because device authentication requirements were not satisfied.",
129            vec![
130                render_optional("Server Message", &facts.registration.server_message),
131                render_optional(
132                    "Server Error Description",
133                    &facts.registration.server_error_description,
134                ),
135            ],
136            vec![
137                "Confirm the device object exists and is enabled in Entra ID.".to_string(),
138                "Validate certificate trust and device authentication state.".to_string(),
139            ],
140            vec![
141                "Repair the device registration or remove stale device objects before retrying sign-in.".to_string(),
142            ],
143        ));
144    }
145
146    if aggregated_errors.contains("aadsts50034") {
147        diagnostics.push(issue(
148            "aadsts50034",
149            IntuneDiagnosticSeverity::Error,
150            "user",
151            "User account was not found in the tenant",
152            "The dsregcmd error fields contain AADSTS50034, which points to an unknown or mismatched user account during sign-in or registration.",
153            vec![render_optional("Server Message", &facts.registration.server_message)],
154            vec![
155                "Check the user identity shown in the diagnostics block.".to_string(),
156                "Confirm the user belongs to the expected tenant and is synchronized.".to_string(),
157            ],
158            vec![
159                "Retry the sign-in flow with the correct tenant-aligned user account.".to_string(),
160            ],
161        ));
162    }
163
164    push_test_failure(
165        &mut diagnostics,
166        "drs-discovery-failed",
167        "discovery",
168        "DRS discovery test failed",
169        &facts.pre_join_tests.drs_discovery_test,
170        vec![
171            "Validate DNS resolution and reachability for the join service URLs.".to_string(),
172            "Check whether the tenant discovery endpoints are correct for this tenant.".to_string(),
173        ],
174        vec!["Resolve discovery failures before retrying registration.".to_string()],
175    );
176    push_test_failure(
177        &mut diagnostics,
178        "drs-connectivity-failed",
179        "connectivity",
180        "DRS connectivity test failed",
181        &facts.pre_join_tests.drs_connectivity_test,
182        vec![
183            "Verify outbound HTTPS connectivity to the DRS endpoint.".to_string(),
184            "Check proxy, TLS inspection, and firewall behavior.".to_string(),
185        ],
186        vec!["Restore connectivity to the DRS service and re-run dsregcmd.".to_string()],
187    );
188    push_test_failure(
189        &mut diagnostics,
190        "ad-connectivity-failed",
191        "connectivity",
192        "Active Directory connectivity test failed",
193        &facts.pre_join_tests.ad_connectivity_test,
194        vec![
195            "Confirm the device can reach a domain controller.".to_string(),
196            "Review VPN, line-of-sight, and DNS configuration for domain connectivity.".to_string(),
197        ],
198        vec!["Restore AD connectivity before retrying hybrid join.".to_string()],
199    );
200    push_test_failure(
201        &mut diagnostics,
202        "ad-config-failed",
203        "configuration",
204        "Active Directory configuration test failed",
205        &facts.pre_join_tests.ad_configuration_test,
206        vec![
207            "Review SCP configuration and tenant targeting in on-premises Active Directory."
208                .to_string(),
209            "Confirm the domain is configured for hybrid join.".to_string(),
210        ],
211        vec!["Correct the AD hybrid join configuration and retry registration.".to_string()],
212    );
213
214    if has_code(facts, "0xcaa90017") {
215        diagnostics.push(issue(
216            "adal-protocol-not-supported",
217            IntuneDiagnosticSeverity::Error,
218            "authentication",
219            "Federation service does not support the required WS-Trust protocol",
220            "The failure pattern matches ERROR_ADAL_PROTOCOL_NOT_SUPPORTED (0xcaa90017), which means the federated identity provider is not exposing the WS-Trust protocol flow that hybrid join expects.",
221            vec![render_phase_code_evidence(facts, "0xcaa90017")],
222            vec![
223                "Review federation settings and confirm the on-premises identity provider supports WS-Trust for device registration flows.".to_string(),
224                "Check whether the endpoint returned by federation metadata matches the protocol expected by Windows.".to_string(),
225            ],
226            vec!["Enable or repair the required WS-Trust support in the identity provider.".to_string()],
227        ));
228    }
229
230    if has_code(facts, "0xcaa9002c") {
231        diagnostics.push(issue(
232            "adal-parse-xml-failed",
233            IntuneDiagnosticSeverity::Error,
234            "configuration",
235            "Federation metadata XML could not be parsed",
236            "The failure pattern matches ERROR_ADAL_FAILED_TO_PARSE_XML (0xcaa9002c), which usually means the MEX or WS-Trust endpoint returned malformed or unexpected XML.",
237            vec![render_phase_code_evidence(facts, "0xcaa9002c")],
238            vec![
239                "Inspect the MEX endpoint response for valid XML and correct WS-Trust metadata.".to_string(),
240                "Check whether a proxy is replacing the expected federation XML with an HTML or otherwise modified response.".to_string(),
241            ],
242            vec!["Repair the federation metadata response so it returns valid XML.".to_string()],
243        ));
244    }
245
246    if has_code(facts, "0xcaa90023") {
247        diagnostics.push(issue(
248            "adal-password-endpoint-missing",
249            IntuneDiagnosticSeverity::Error,
250            "configuration",
251            "Federation metadata is missing the username or password endpoint",
252            "The failure pattern matches ERROR_ADAL_COULDNOT_DISCOVER_USERNAME_PASSWORD_ENDPOINT (0xcaa90023), which means the MEX response does not advertise the WS-Trust endpoint Windows expects to use.",
253            vec![render_phase_code_evidence(facts, "0xcaa90023")],
254            vec![
255                "Review the MEX response for the required WS-Trust username/password endpoints.".to_string(),
256                "Confirm the identity provider publishes the correct endpoints for federated hybrid join.".to_string(),
257            ],
258            vec!["Fix the federation metadata so the required endpoints are advertised.".to_string()],
259        ));
260    }
261
262    if has_code(facts, "0xcaa82ee2") {
263        diagnostics.push(issue(
264            "adal-timeout",
265            IntuneDiagnosticSeverity::Error,
266            "network",
267            "Federated authentication timed out",
268            "The failure pattern matches ERROR_ADAL_INTERNET_TIMEOUT (0xcaa82ee2), which means the device could not complete communication with Microsoft Entra or the federation endpoint in time.",
269            vec![render_phase_code_evidence(facts, "0xcaa82ee2")],
270            vec![
271                "Verify connectivity to https://login.microsoftonline.com and the federated identity provider from the effective system or user context.".to_string(),
272                "Check proxy behavior, network stability, and endpoint reachability.".to_string(),
273            ],
274            vec!["Resolve the network timeout path before retrying authentication.".to_string()],
275        ));
276    }
277
278    if has_code(facts, "0xcaa82efe") {
279        diagnostics.push(issue(
280            "adal-connection-aborted",
281            IntuneDiagnosticSeverity::Error,
282            "network",
283            "Federated authentication connection was aborted",
284            "The failure pattern matches ERROR_ADAL_INTERNET_CONNECTION_ABORTED (0xcaa82efe), which means the connection to the authorization endpoint terminated unexpectedly.",
285            vec![render_phase_code_evidence(facts, "0xcaa82efe")],
286            vec![
287                "Check for unstable network links or intermediary devices terminating the connection.".to_string(),
288                "Retry from a more stable network path and compare results.".to_string(),
289            ],
290            vec!["Stabilize the network path or endpoint availability before retrying.".to_string()],
291        ));
292    }
293
294    if has_code(facts, "0xcaa82f8f") {
295        diagnostics.push(issue(
296            "adal-secure-failure",
297            IntuneDiagnosticSeverity::Error,
298            "network",
299            "TLS validation failed during federated authentication",
300            "The failure pattern matches ERROR_ADAL_INTERNET_SECURE_FAILURE (0xcaa82f8f), which usually means certificate validation or time skew blocked the secure connection.",
301            vec![render_phase_code_evidence(facts, "0xcaa82f8f")],
302            vec![
303                "Check device time skew and certificate trust for the federated endpoint.".to_string(),
304                "Review whether TLS inspection or certificate replacement is breaking trust.".to_string(),
305            ],
306            vec!["Fix certificate trust or time skew before retrying federated authentication.".to_string()],
307        ));
308    }
309
310    if has_code(facts, "0xcaa82efd") {
311        diagnostics.push(issue(
312            "adal-cannot-connect",
313            IntuneDiagnosticSeverity::Error,
314            "network",
315            "The device could not connect to the federated or Microsoft Entra endpoint",
316            "The failure pattern matches ERROR_ADAL_INTERNET_CANNOT_CONNECT (0xcaa82efd), which means the connection to the authentication endpoint could not be established.",
317            vec![render_phase_code_evidence(facts, "0xcaa82efd")],
318            vec![
319                "Check endpoint URI reachability and whether outbound proxy rules allow the traffic.".to_string(),
320                "Validate DNS resolution and HTTPS connectivity for the authentication endpoint.".to_string(),
321            ],
322            vec!["Restore connectivity to the authentication endpoint and retry.".to_string()],
323        ));
324    }
325
326    if has_code(facts, "0xcaa20003") {
327        diagnostics.push(issue(
328            "adal-invalid-grant",
329            IntuneDiagnosticSeverity::Error,
330            "authentication",
331            "Microsoft Entra rejected the federated assertion as an invalid grant",
332            "The failure pattern matches ERROR_ADAL_SERVER_ERROR_INVALID_GRANT (0xcaa20003), which means Microsoft Entra rejected the SAML assertion supplied by the federated identity provider.",
333            vec![render_phase_code_evidence(facts, "0xcaa20003")],
334            vec![
335                "Review federation logs and server error details for why the assertion was rejected.".to_string(),
336                "Check claim issuance rules and token content from the identity provider.".to_string(),
337            ],
338            vec!["Repair the federation assertion flow before retrying sign-in.".to_string()],
339        ));
340    }
341
342    if has_code(facts, "0xcaa90014") {
343        diagnostics.push(issue(
344            "adal-wstrust-request-failed",
345            IntuneDiagnosticSeverity::Error,
346            "authentication",
347            "The WS-Trust request failed with a server-side fault",
348            "The failure pattern matches ERROR_ADAL_WSTRUST_REQUEST_SECURITYTOKEN_FAILED (0xcaa90014), which means the federation service returned a WS-Trust fault instead of the expected assertion.",
349            vec![render_phase_code_evidence(facts, "0xcaa90014")],
350            vec![
351                "Review federation server logs for the specific WS-Trust fault returned to the device.".to_string(),
352                "Check whether metadata, claim rules, or certificate trust issues are causing the failure.".to_string(),
353            ],
354            vec!["Repair the WS-Trust issuance path before retrying authentication.".to_string()],
355        ));
356    }
357
358    if has_code(facts, "0xcaa90006") {
359        diagnostics.push(issue(
360            "adal-token-request-failed",
361            IntuneDiagnosticSeverity::Error,
362            "authentication",
363            "The federated token request failed before an access token was returned",
364            "The failure pattern matches ERROR_ADAL_WSTRUST_TOKEN_REQUEST_FAIL (0xcaa90006), which means the device could not complete token acquisition against the WS-Trust endpoint.",
365            vec![render_phase_code_evidence(facts, "0xcaa90006")],
366            vec![
367                "Check the underlying federation endpoint error and whether the request reached the token service.".to_string(),
368                "Review WS-Trust endpoint health and metadata correctness.".to_string(),
369            ],
370            vec!["Resolve the WS-Trust token issuance failure and retry.".to_string()],
371        ));
372    }
373
374    if has_code(facts, "0xcaa1002d") {
375        diagnostics.push(issue(
376            "adal-operation-pending",
377            IntuneDiagnosticSeverity::Warning,
378            "authentication",
379            "The federated authentication operation is still reported as pending",
380            "The failure pattern matches ERROR_ADAL_OPERATION_PENDING (0xcaa1002d), which is a broad ADAL failure that usually needs the underlying suberror or server code to narrow down the root cause.",
381            vec![render_phase_code_evidence(facts, "0xcaa1002d")],
382            vec![
383                "Check any accompanying federation server or suberror details in the capture.".to_string(),
384                "Look for a more specific network, WS-Trust, or server-side error in the surrounding fields.".to_string(),
385            ],
386            Vec::new(),
387        ));
388    }
389
390    if contains_text(&facts.registration.client_error_code, "0x801c001d")
391        || contains_text(&facts.pre_join_tests.ad_configuration_test, "0x801c001d")
392    {
393        diagnostics.push(issue(
394            "scp-read-failed",
395            IntuneDiagnosticSeverity::Error,
396            "configuration",
397            "Service Connection Point lookup failed",
398            "The failure pattern matches DSREG_AUTOJOIN_ADCONFIG_READ_FAILED (0x801c001d), which usually means the device could not read or validate the Service Connection Point for hybrid join.",
399            vec![
400                render_optional("AD Configuration Test", &facts.pre_join_tests.ad_configuration_test),
401                render_optional("Client ErrorCode", &facts.registration.client_error_code),
402            ],
403            vec![
404                "Verify the SCP exists in the correct forest and points to the expected verified tenant domain.".to_string(),
405                "Check whether the device can read the SCP from a reachable domain controller.".to_string(),
406            ],
407            vec![
408                "Correct the hybrid join SCP configuration before retrying registration.".to_string(),
409            ],
410        ));
411    }
412
413    if contains_text(&facts.registration.client_error_code, "0x801c0021")
414        || contains_text(&facts.pre_join_tests.drs_discovery_test, "0x801c0021")
415    {
416        diagnostics.push(issue(
417            "drs-discovery-code",
418            IntuneDiagnosticSeverity::Error,
419            "discovery",
420            "DRS discovery metadata retrieval failed",
421            "The failure pattern matches DSREG_AUTOJOIN_DISC_FAILED (0x801c0021), which points to tenant discovery metadata retrieval failing before registration can proceed.",
422            vec![
423                render_optional("DRS Discovery Test", &facts.pre_join_tests.drs_discovery_test),
424                render_optional("Client ErrorCode", &facts.registration.client_error_code),
425            ],
426            vec![
427                "Verify access to https://enterpriseregistration.windows.net from the effective system context.".to_string(),
428                "Check proxy, DNS, and TLS inspection behavior around discovery endpoints.".to_string(),
429            ],
430            vec!["Restore discovery endpoint access and retry hybrid join.".to_string()],
431        ));
432    }
433
434    if contains_text(&facts.registration.client_error_code, "0x801c001f")
435        || contains_text(&facts.pre_join_tests.drs_discovery_test, "0x801c001f")
436    {
437        diagnostics.push(issue(
438            "drs-discovery-timeout",
439            IntuneDiagnosticSeverity::Error,
440            "network",
441            "DRS discovery timed out",
442            "The failure pattern matches DSREG_AUTOJOIN_DISC_WAIT_TIMEOUT (0x801c001f), which usually indicates the discovery endpoint could not be reached reliably from the current system context.",
443            vec![
444                render_optional("DRS Discovery Test", &facts.pre_join_tests.drs_discovery_test),
445                render_optional("Client ErrorCode", &facts.registration.client_error_code),
446            ],
447            vec![
448                "Confirm outbound HTTPS connectivity to https://enterpriseregistration.windows.net.".to_string(),
449                "Check WinHTTP proxy configuration and whether the computer account can authenticate through the proxy.".to_string(),
450            ],
451            vec!["Resolve the discovery timeout path before retrying join.".to_string()],
452        ));
453    }
454
455    if contains_text(&facts.registration.client_error_code, "0x801c003d") {
456        diagnostics.push(issue(
457            "user-realm-discovery-failed",
458            IntuneDiagnosticSeverity::Error,
459            "authentication",
460            "User realm discovery failed",
461            "The failure pattern matches DSREG_AUTOJOIN_USERREALM_DISCOVERY_FAILED (0x801c003d), which means the device could not determine whether the user domain is managed or federated.",
462            vec![render_optional("Client ErrorCode", &facts.registration.client_error_code)],
463            vec![
464                "Verify the user realm lookup can reach https://login.microsoftonline.com from the system context.".to_string(),
465                "Check whether proxy requirements or tenant domain configuration are interfering with realm discovery.".to_string(),
466            ],
467            vec!["Restore user realm discovery before retrying hybrid join.".to_string()],
468        ));
469    }
470
471    if contains_text(&facts.registration.client_error_code, "0x8007000d")
472        || contains_text(&facts.diagnostics.http_error, "0x8007000d")
473    {
474        diagnostics.push(issue(
475            "invalid-discovery-response",
476            IntuneDiagnosticSeverity::Error,
477            "network",
478            "Discovery response could not be parsed",
479            "The failure pattern matches E_INVALIDDATA (0x8007000d), which often happens when a proxy or intermediary returns HTML or a modified response instead of the expected discovery JSON.",
480            vec![
481                render_optional("Client ErrorCode", &facts.registration.client_error_code),
482                render_optional("HTTP Error", &facts.diagnostics.http_error),
483                render_optional("Endpoint URI", &facts.diagnostics.endpoint_uri),
484            ],
485            vec![
486                "Check whether an outbound proxy is intercepting or rewriting the discovery response.".to_string(),
487                "Compare the endpoint behavior from the system context against a healthy device.".to_string(),
488            ],
489            vec!["Fix the proxy or response path so discovery returns the expected JSON.".to_string()],
490        ));
491    }
492
493    if contains_text(&facts.registration.client_error_code, "0x801c0002") {
494        diagnostics.push(issue(
495            "join-device-authentication-error",
496            IntuneDiagnosticSeverity::Error,
497            "authentication",
498            "Join failed because device authentication was rejected",
499            "The failure pattern matches DSREG_E_DEVICE_AUTHENTICATION_ERROR (0x801c0002), which means the DRS service rejected device authentication during join.",
500            vec![
501                render_optional("Client ErrorCode", &facts.registration.client_error_code),
502                render_optional("Server ErrorCode", &facts.registration.server_error_code),
503                render_optional("Server Message", &facts.registration.server_message),
504            ],
505            vec![
506                "Validate the device certificate, device object state, and sync status in Entra ID.".to_string(),
507                "Check whether the server error indicates an authentication mismatch or stale registration state.".to_string(),
508            ],
509            vec!["Repair device registration state before retrying join.".to_string()],
510        ));
511    }
512
513    if contains_text(&facts.registration.client_error_code, "0x801c0006") {
514        diagnostics.push(issue(
515            "join-internal-service-error",
516            IntuneDiagnosticSeverity::Error,
517            "join",
518            "Join failed because the registration service returned an internal error",
519            "The failure pattern matches DSREG_E_DEVICE_INTERNALSERVICE_ERROR (0x801c0006), which means the DRS service returned an internal failure during join processing.",
520            vec![
521                render_optional("Client ErrorCode", &facts.registration.client_error_code),
522                render_optional("Server ErrorCode", &facts.registration.server_error_code),
523                render_optional("Server Message", &facts.registration.server_message),
524            ],
525            vec![
526                "Check whether the failure is transient or whether server-side throttling or directory errors are also present.".to_string(),
527                "Compare with another registration attempt after a short wait.".to_string(),
528            ],
529            vec!["Retry the join after confirming the service-side condition has cleared.".to_string()],
530        ));
531    }
532
533    if facts.sso_state.azure_ad_prt == Some(false) {
534        diagnostics.push(issue(
535            "no-azure-prt",
536            IntuneDiagnosticSeverity::Error,
537            "authentication",
538            "No Azure AD PRT is present",
539            "AzureAdPrt is NO, so the current sign-in context does not have a Primary Refresh Token available.",
540            vec![render_bool("AzureAdPrt", facts.sso_state.azure_ad_prt)],
541            vec![
542                "Check the diagnostics block for the last PRT acquisition attempt.".to_string(),
543                "Review WAM, credentials, and device authentication health.".to_string(),
544            ],
545            vec![
546                "Have the user sign out and back in after correcting registration or credential issues.".to_string(),
547            ],
548        ));
549    }
550
551    if contains_text(&facts.diagnostics.attempt_status, "0xc000006d") {
552        diagnostics.push(issue(
553            "invalid-credentials",
554            IntuneDiagnosticSeverity::Error,
555            "credentials",
556            "PRT acquisition failed because credentials were rejected",
557            "Attempt Status contains 0xc000006d, which maps to invalid credentials during the sign-in flow.",
558            vec![render_optional("Attempt Status", &facts.diagnostics.attempt_status)],
559            vec![
560                "Check whether the user recently changed their password or entered the wrong credentials.".to_string(),
561                "Review the credential type and user identity fields in the diagnostics section.".to_string(),
562            ],
563            vec![
564                "Retry authentication with the correct credentials or refreshed password.".to_string(),
565            ],
566        ));
567    }
568
569    if contains_text(&facts.diagnostics.attempt_status, "0xc000006a") {
570        diagnostics.push(issue(
571            "wrong-password",
572            IntuneDiagnosticSeverity::Error,
573            "credentials",
574            "PRT acquisition failed because the password was rejected",
575            "Attempt Status contains 0xc000006a, which maps to STATUS_WRONG_PASSWORD during PRT acquisition.",
576            vec![
577                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
578                render_optional("User Identity", &facts.diagnostics.user_identity),
579            ],
580            vec![
581                "Check whether the user recently changed their password and Entra password sync has not completed yet.".to_string(),
582                "Confirm the user is signing in with the intended UPN and password.".to_string(),
583            ],
584            vec!["Retry sign-in after password sync finishes or after correcting credentials.".to_string()],
585        ));
586    }
587
588    if contains_text(&facts.diagnostics.attempt_status, "0xc00000d0") {
589        diagnostics.push(issue(
590            "request-not-accepted",
591            IntuneDiagnosticSeverity::Error,
592            "authentication",
593            "PRT request was not accepted by the authentication endpoint",
594            "Attempt Status contains 0xc00000d0, which lines up with an HTTP 400-style rejection from the Microsoft Entra or WS-Trust endpoint.",
595            vec![
596                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
597                render_optional("HTTP Status", &facts.diagnostics.http_status.as_ref().map(|value| value.to_string())),
598                render_optional("Endpoint URI", &facts.diagnostics.endpoint_uri),
599            ],
600            vec![
601                "Review server error details and endpoint URI for the rejected request.".to_string(),
602                "Check for federation or proxy behavior that alters the request flow.".to_string(),
603            ],
604            vec!["Resolve the endpoint rejection cause before retrying PRT acquisition.".to_string()],
605        ));
606    }
607
608    if contains_text(&facts.diagnostics.attempt_status, "0xc000023c")
609        || contains_text(&facts.diagnostics.attempt_status, "0xc00000be")
610        || contains_text(&facts.diagnostics.attempt_status, "0xc00000c4")
611    {
612        diagnostics.push(issue(
613            "prt-network-path-error",
614            IntuneDiagnosticSeverity::Error,
615            "network",
616            "PRT acquisition failed because the network path was unavailable",
617            "Attempt Status matches a documented network-path failure during PRT acquisition, which usually means the required Microsoft Entra or federation endpoint was unreachable or the connection failed mid-flight.",
618            vec![
619                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
620                render_optional("Endpoint URI", &facts.diagnostics.endpoint_uri),
621                render_optional("HTTP Error", &facts.diagnostics.http_error),
622            ],
623            vec![
624                "Check network reachability to the endpoint URI from the current device context.".to_string(),
625                "Review proxy requirements and intermittent network stability issues.".to_string(),
626            ],
627            vec!["Restore the endpoint network path and retry token acquisition.".to_string()],
628        ));
629    }
630
631    if contains_text(&facts.diagnostics.attempt_status, "0xc000005f") {
632        diagnostics.push(issue(
633            "prt-user-realm-not-found",
634            IntuneDiagnosticSeverity::Error,
635            "user",
636            "PRT acquisition could not resolve the user realm",
637            "Attempt Status contains 0xc000005f, which usually means Microsoft Entra could not find the user's domain during realm discovery.",
638            vec![
639                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
640                render_optional("User Identity", &facts.diagnostics.user_identity),
641            ],
642            vec![
643                "Check whether the user's UPN suffix is a verified custom domain in the target tenant.".to_string(),
644                "If the on-premises domain is nonroutable, review Alternate Login ID configuration.".to_string(),
645            ],
646            vec!["Correct the user realm or UPN configuration before retrying sign-in.".to_string()],
647        ));
648    }
649
650    if contains_text(&facts.diagnostics.attempt_status, "0xc004844c") {
651        diagnostics.push(issue(
652            "malformed-upn",
653            IntuneDiagnosticSeverity::Error,
654            "user",
655            "The user principal name format is invalid for PRT acquisition",
656            "Attempt Status contains 0xc004844c, which indicates the user's UPN is not in the expected internet-style format.",
657            vec![
658                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
659                render_optional("User Identity", &facts.diagnostics.user_identity),
660            ],
661            vec![
662                "Validate the returned UPN format for the signed-in user.".to_string(),
663                "For hybrid join, compare with whoami /upn on the device and confirm the domain controller returns the expected value.".to_string(),
664            ],
665            vec!["Correct the user's UPN formatting or Alternate Login ID configuration.".to_string()],
666        ));
667    }
668
669    if contains_text(&facts.diagnostics.attempt_status, "0xc0048442") {
670        diagnostics.push(issue(
671            "missing-user-sid-in-token",
672            IntuneDiagnosticSeverity::Error,
673            "authentication",
674            "The returned identity token did not include a user SID",
675            "Attempt Status contains 0xc0048442, which means the token returned by Microsoft Entra did not contain the expected user SID claim.",
676            vec![
677                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
678                render_optional("Endpoint URI", &facts.diagnostics.endpoint_uri),
679            ],
680            vec![
681                "Check whether a network proxy is rewriting or interfering with the token response.".to_string(),
682                "Compare the behavior from another network path without TLS or proxy interception.".to_string(),
683            ],
684            vec!["Fix the token response path before retrying sign-in.".to_string()],
685        ));
686    }
687
688    if contains_text(&facts.diagnostics.attempt_status, "0xc00484c1") {
689        diagnostics.push(issue(
690            "wstrust-empty-saml",
691            IntuneDiagnosticSeverity::Error,
692            "authentication",
693            "The WS-Trust endpoint returned an unusable SAML response",
694            "Attempt Status contains 0xc00484c1, which indicates the WS-Trust response did not contain the expected SAML tokens for federated authentication.",
695            vec![
696                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
697                render_optional("Endpoint URI", &facts.diagnostics.endpoint_uri),
698            ],
699            vec![
700                "Review the WS-Trust endpoint response and whether a proxy is modifying it.".to_string(),
701                "Check federation logs for server-side faults during token issuance.".to_string(),
702            ],
703            vec!["Repair the WS-Trust response path before retrying authentication.".to_string()],
704        ));
705    }
706
707    if contains_text(&facts.diagnostics.attempt_status, "0xc004848b")
708        || contains_text(&facts.diagnostics.attempt_status, "0xc004848c")
709    {
710        diagnostics.push(issue(
711            "mex-endpoint-misconfigured",
712            IntuneDiagnosticSeverity::Error,
713            "configuration",
714            "The federation MEX metadata is missing required endpoints",
715            "Attempt Status matches the documented MEX endpoint misconfiguration where password or certificate URLs are missing from the federation metadata response.",
716            vec![
717                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
718                render_optional("Endpoint URI", &facts.diagnostics.endpoint_uri),
719            ],
720            vec![
721                "Review the federation MEX response for missing WS-Trust password or certificate endpoints.".to_string(),
722                "Check whether a proxy is modifying the federation metadata response.".to_string(),
723            ],
724            vec!["Fix the MEX configuration to advertise the required endpoints.".to_string()],
725        ));
726    }
727
728    if contains_text(&facts.diagnostics.attempt_status, "0xc00cee4f") {
729        diagnostics.push(issue(
730            "federation-xml-dtd-prohibited",
731            IntuneDiagnosticSeverity::Error,
732            "configuration",
733            "The federation XML response included a prohibited DTD",
734            "Attempt Status contains 0xc00cee4f, which means the WS-Trust XML response included a DTD that the parser rejects.",
735            vec![
736                render_optional("Attempt Status", &facts.diagnostics.attempt_status),
737                render_optional("Endpoint URI", &facts.diagnostics.endpoint_uri),
738            ],
739            vec![
740                "Inspect the federation XML response for a DTD or other invalid additions.".to_string(),
741                "Check whether the identity provider or proxy is modifying the XML document.".to_string(),
742            ],
743            vec!["Remove the DTD from the federation XML response and retry authentication.".to_string()],
744        ));
745    }
746
747    if contains_text(&facts.registration.server_error_description, "aadsts50126") {
748        diagnostics.push(issue(
749            "aadsts50126-detailed",
750            IntuneDiagnosticSeverity::Error,
751            "credentials",
752            "Server error description reports AADSTS50126",
753            "The detailed server error description indicates invalid username or password during authentication.",
754            vec![render_optional(
755                "Server Error Description",
756                &facts.registration.server_error_description,
757            )],
758            vec![
759                "Compare the user identity in dsregcmd with the expected sign-in account.".to_string(),
760                "Review conditional access or federation prompts that may have redirected the flow.".to_string(),
761            ],
762            vec![
763                "Retry sign-in with valid credentials after confirming the correct account.".to_string(),
764            ],
765        ));
766    }
767
768    if has_code(facts, "0x80090016") {
769        diagnostics.push(issue(
770            "tpm-bad-keyset",
771            IntuneDiagnosticSeverity::Error,
772            "configuration",
773            "TPM key material is missing or invalid",
774            "The failure pattern matches NTE_BAD_KEYSET (0x80090016), which usually means the TPM-backed keyset no longer exists or the device image was prepared from a bad joined-state source.",
775            vec![render_phase_code_evidence(facts, "0x80090016")],
776            vec![
777                "Check whether the TPM was cleared or whether the device image came from a machine that was already registered or joined.".to_string(),
778                "Compare with device registration history and account recovery behavior on the machine.".to_string(),
779            ],
780            vec!["Repair or re-register the device after correcting the TPM keyset issue.".to_string()],
781        ));
782    }
783
784    if has_code(facts, "0x80290407") {
785        diagnostics.push(issue(
786            "tpm-internal-error",
787            IntuneDiagnosticSeverity::Error,
788            "configuration",
789            "The TPM reported an internal failure during join",
790            "The failure pattern matches TPM_E_PCP_INTERNAL_ERROR (0x80290407), which indicates a TPM failure that can block TPM-backed device registration.",
791            vec![render_phase_code_evidence(facts, "0x80290407")],
792            vec![
793                "Check TPM health and whether Windows can use the TPM normally on this device.".to_string(),
794                "Compare with a retry that uses a non-TPM path if the platform and Windows version support it.".to_string(),
795            ],
796            vec!["Resolve or bypass the unhealthy TPM path before retrying join.".to_string()],
797        ));
798    }
799
800    if has_code(facts, "0x80280036") {
801        diagnostics.push(issue(
802            "tpm-not-fips",
803            IntuneDiagnosticSeverity::Error,
804            "configuration",
805            "The TPM is in an unsupported FIPS mode for this flow",
806            "The failure pattern matches TPM_E_NOTFIPS (0x80280036), which means the TPM state is not supported for this registration flow.",
807            vec![render_phase_code_evidence(facts, "0x80280036")],
808            vec![
809                "Review the TPM configuration and whether the device is enforcing a TPM mode unsupported for this join path.".to_string(),
810                "Check whether the Windows version can fall back to a non-TPM registration path.".to_string(),
811            ],
812            vec!["Correct the TPM mode or use a supported fallback path before retrying.".to_string()],
813        ));
814    }
815
816    if has_code(facts, "0x80090031") {
817        diagnostics.push(issue(
818            "tpm-locked-out",
819            IntuneDiagnosticSeverity::Warning,
820            "configuration",
821            "The TPM appears to be locked out temporarily",
822            "The failure pattern matches NTE_AUTHENTICATION_IGNORED (0x80090031), which is commonly a transient TPM lockout or anti-hammering condition.",
823            vec![render_phase_code_evidence(facts, "0x80090031")],
824            vec![
825                "Wait for the TPM lockout cool-down period to expire before retrying.".to_string(),
826                "Check whether repeated recent authentication failures triggered TPM anti-hammering.".to_string(),
827            ],
828            Vec::new(),
829        ));
830    }
831
832    if aggregated_errors.contains("aadsts90002")
833        || aggregated_errors.contains("tenant uuid not found")
834    {
835        diagnostics.push(issue(
836            "tenant-uuid-not-found",
837            IntuneDiagnosticSeverity::Error,
838            "dynamic",
839            "Tenant identifier could not be resolved",
840            "The aggregated dsregcmd error fields contain an AADSTS90002-style tenant lookup failure.",
841            vec![
842                render_optional("TenantId", &facts.tenant_details.tenant_id),
843                render_optional("Server Message", &facts.registration.server_message),
844            ],
845            vec![
846                "Verify the tenant ID and tenant discovery URLs in the capture.".to_string(),
847                "Confirm the user and device are targeting the correct cloud tenant.".to_string(),
848            ],
849            vec!["Correct the tenant targeting information and retry registration.".to_string()],
850        ));
851    }
852
853    if aggregated_errors.contains("1312") || aggregated_errors.contains("1317") {
854        diagnostics.push(issue(
855            "ad-replication-issue",
856            IntuneDiagnosticSeverity::Error,
857            "dynamic",
858            "Directory replication or lookup issue detected",
859            "The aggregated registration errors contain 1312 or 1317, which commonly show up during AD replication or object lookup problems.",
860            vec![
861                render_optional("Client ErrorCode", &facts.registration.client_error_code),
862                render_optional("Server ErrorCode", &facts.registration.server_error_code),
863            ],
864            vec![
865                "Check the health of the on-premises AD object and replication status.".to_string(),
866                "Verify the computer account exists and is consistent across domain controllers.".to_string(),
867            ],
868            vec!["Resolve the directory replication issue, then retry hybrid join.".to_string()],
869        ));
870    }
871
872    if let Some(device_auth_status) = facts.device_details.device_auth_status.as_deref() {
873        if !device_auth_status.eq_ignore_ascii_case("SUCCESS") {
874            diagnostics.push(issue(
875                "device-auth-failed",
876                IntuneDiagnosticSeverity::Error,
877                "authentication",
878                "Device authentication status is not SUCCESS",
879                "DeviceAuthStatus reports a failing or incomplete state, so the device is not currently authenticating cleanly with Entra ID.",
880                vec![render_optional(
881                    "DeviceAuthStatus",
882                    &facts.device_details.device_auth_status,
883                )],
884                vec![
885                    "Compare device authentication status with certificate, TPM, and join state details.".to_string(),
886                    "Look for upstream registration or certificate errors in the capture.".to_string(),
887                ],
888                vec!["Repair device registration and certificate trust before retrying authentication.".to_string()],
889            ));
890        }
891    }
892
893    if derived.missing_mdm == Some(true) {
894        diagnostics.push(issue(
895            "no-mdm",
896            IntuneDiagnosticSeverity::Info,
897            "configuration",
898            "MDM enrollment URL is not present",
899            "MdmComplianceUrl is present but MdmUrl is not. That usually means the capture is incomplete or the tenant advertises only part of the management metadata, not that the device is definitively broken.",
900            vec![
901                render_optional("MdmUrl", &facts.management_details.mdm_url),
902                render_optional(
903                    "MdmComplianceUrl",
904                    &facts.management_details.mdm_compliance_url,
905                ),
906            ],
907            vec![
908                "Confirm whether this tenant and user are actually in scope for automatic MDM enrollment.".to_string(),
909                "Compare with a healthy capture from the same org before treating missing MDM metadata as a failure.".to_string(),
910            ],
911            Vec::new(),
912        ));
913    }
914
915    if derived.missing_compliance_url == Some(true) {
916        diagnostics.push(issue(
917            "no-compliance",
918            IntuneDiagnosticSeverity::Info,
919            "configuration",
920            "Compliance URL is not present",
921            "MdmUrl is present but MdmComplianceUrl is not. dsregcmd management fields are tenant- and scope-dependent, so this is context rather than proof of an enrollment problem.",
922            vec![render_optional(
923                "MdmComplianceUrl",
924                &facts.management_details.mdm_compliance_url,
925            )],
926            vec![
927                "Confirm whether compliance reporting is expected for this org and user scope.".to_string(),
928                "Compare with another healthy capture from the same tenant before escalating.".to_string(),
929            ],
930            Vec::new(),
931        ));
932    }
933
934    if facts.user_state.wam_default_set == Some(false) {
935        diagnostics.push(issue(
936            "wam-not-default",
937            IntuneDiagnosticSeverity::Warning,
938            "configuration",
939            "Web Account Manager default account is not set",
940            "WamDefaultSet is NO, which often lines up with user sign-in or token acquisition issues.",
941            vec![render_bool("WamDefaultSet", facts.user_state.wam_default_set)],
942            vec![
943                "Check the signed-in account and WAM authority values.".to_string(),
944                "Review whether the user is fully signed in to Windows with a work account.".to_string(),
945            ],
946            vec!["Refresh the account session or sign in again to restore WAM defaults.".to_string()],
947        ));
948    }
949
950    if contains_text(&facts.registration.server_message, "aadsts50126") {
951        diagnostics.push(issue(
952            "aadsts50126",
953            IntuneDiagnosticSeverity::Warning,
954            "credentials",
955            "Server message reports AADSTS50126",
956            "The high-level server message indicates invalid credentials or an authentication mismatch.",
957            vec![render_optional("Server Message", &facts.registration.server_message)],
958            vec![
959                "Compare the user identity, credential type, and endpoint URI in the diagnostics block.".to_string(),
960            ],
961            vec!["Retry sign-in with the correct account and credentials.".to_string()],
962        ));
963    }
964
965    let has_specific_network_issue = diagnostics.iter().any(|item| {
966        matches!(
967            item.id.as_str(),
968            "drs-discovery-timeout"
969                | "invalid-discovery-response"
970                | "prt-network-path-error"
971                | "adal-timeout"
972                | "adal-connection-aborted"
973                | "adal-secure-failure"
974                | "adal-cannot-connect"
975        )
976    });
977
978    if let Some(network_error_code) = derived.network_error_code.as_deref() {
979        if !has_specific_network_issue {
980            diagnostics.push(issue(
981                "network-issue",
982                IntuneDiagnosticSeverity::Warning,
983                "network",
984                "Network connectivity marker detected",
985                &format!(
986                    "The capture contains {}, which points to a network, DNS, proxy, or transport-layer problem during registration or token acquisition.",
987                    network_error_code
988                ),
989                vec![
990                    format!("NetworkErrorCode: {}", network_error_code),
991                    render_optional("HTTP Error", &facts.diagnostics.http_error),
992                    render_optional("Endpoint URI", &facts.diagnostics.endpoint_uri),
993                ],
994                vec![
995                    "Test name resolution and HTTPS connectivity to the endpoint URI.".to_string(),
996                    "Check WinHTTP proxy configuration and outbound firewall policy.".to_string(),
997                ],
998                vec!["Resolve the network path issue and re-run dsregcmd /status.".to_string()],
999            ));
1000        }
1001    }
1002
1003    if derived.stale_prt == Some(true) {
1004        let age_text = derived
1005            .prt_age_hours
1006            .map(|hours| format!("{hours:.1} hours"))
1007            .unwrap_or_else(|| "more than 4 hours".to_string());
1008        diagnostics.push(issue(
1009            "stale-prt",
1010            IntuneDiagnosticSeverity::Warning,
1011            "dynamic",
1012            "Azure AD PRT appears stale",
1013            &format!(
1014                "AzureAdPrtUpdateTime is older than the 4-hour threshold ({age_text})."
1015            ),
1016            vec![
1017                render_optional(
1018                    "AzureAdPrtUpdateTime",
1019                    &facts.sso_state.azure_ad_prt_update_time,
1020                ),
1021                render_optional("Client Time", &facts.diagnostics.client_time),
1022            ],
1023            vec![
1024                "Check whether token renewal is being blocked by sign-in, network, or device auth issues.".to_string(),
1025                "Review the last PRT acquisition attempt and any AADSTS codes.".to_string(),
1026            ],
1027            vec!["Refresh the user sign-in session after fixing the root cause.".to_string()],
1028        ));
1029    }
1030
1031    if facts.device_details.tpm_protected == Some(false) {
1032        let has_specific_tpm_issue = diagnostics.iter().any(|item| {
1033            matches!(
1034                item.id.as_str(),
1035                "tpm-bad-keyset" | "tpm-internal-error" | "tpm-not-fips" | "tpm-locked-out"
1036            )
1037        });
1038        if !has_specific_tpm_issue {
1039            diagnostics.push(issue(
1040                "no-tpm-protection",
1041                IntuneDiagnosticSeverity::Warning,
1042                "configuration",
1043                "Device keys are not TPM protected",
1044                "TpmProtected is NO, so the device registration keys are not currently backed by TPM protection.",
1045                vec![render_bool("TpmProtected", facts.device_details.tpm_protected)],
1046                vec![
1047                    "Confirm whether the device has a healthy TPM and that it is available to Windows.".to_string(),
1048                    "Compare the key provider and key container details with a healthy device.".to_string(),
1049                ],
1050                vec!["Resolve TPM availability issues or re-register the device using hardware-backed keys.".to_string()],
1051            ));
1052        }
1053    }
1054
1055    if let Some(logon_cert_template_ready) = facts.registration.logon_cert_template_ready.as_deref()
1056    {
1057        if !logon_cert_template_ready.contains("StateReady")
1058            && equals_text(&facts.registration.cert_enrollment, "enrollment authority")
1059        {
1060            diagnostics.push(issue(
1061                "logon-cert-not-ready",
1062                IntuneDiagnosticSeverity::Info,
1063                "configuration",
1064                "Logon certificate template is not ready",
1065                "LogonCertTemplateReady is present but does not report StateReady. This is supporting context for Windows Hello certificate-trust readiness, not a standalone device health failure.",
1066                vec![render_optional(
1067                    "LogonCertTemplateReady",
1068                    &facts.registration.logon_cert_template_ready,
1069                )],
1070                vec![
1071                    "Review certificate enrollment prerequisites and issuance policy.".to_string(),
1072                    "Check whether the device can reach the issuing CA or enrollment service when certificate-trust WHfB is expected."
1073                        .to_string(),
1074                ],
1075                Vec::new(),
1076            ));
1077        }
1078    }
1079
1080    if derived.certificate_expiring_soon == Some(true) {
1081        let certificate_summary = match derived.certificate_days_remaining {
1082            Some(days_remaining) if days_remaining < 0 => {
1083                format!(
1084                    "The device certificate already expired {} days ago.",
1085                    days_remaining.abs()
1086                )
1087            }
1088            Some(days_remaining) => {
1089                format!("The device certificate expires in {} days.", days_remaining)
1090            }
1091            None => "The device certificate validity window is near expiry.".to_string(),
1092        };
1093        diagnostics.push(issue(
1094            "cert-expiring-soon",
1095            IntuneDiagnosticSeverity::Warning,
1096            "configuration",
1097            "Device certificate validity is near expiry",
1098            &certificate_summary,
1099            vec![render_optional(
1100                "DeviceCertificateValidity",
1101                &facts.device_details.device_certificate_validity,
1102            )],
1103            vec![
1104                "Check whether automatic device certificate renewal is functioning.".to_string(),
1105                "Review device auth state and certificate enrollment prerequisites.".to_string(),
1106            ],
1107            vec![
1108                "Renew or repair the device certificate before authentication starts failing."
1109                    .to_string(),
1110            ],
1111        ));
1112    }
1113
1114    if derived.remote_session_system == Some(true) {
1115        diagnostics.push(issue(
1116            "remote-session-system",
1117            IntuneDiagnosticSeverity::Warning,
1118            "configuration",
1119            "Capture was taken as SYSTEM in a remote session",
1120            "The diagnostics block shows User Context as SYSTEM while SessionIsNotRemote is NO, which can produce misleading token and user-state output.",
1121            vec![
1122                render_optional("User Context", &facts.diagnostics.user_context),
1123                render_bool("SessionIsNotRemote", facts.user_state.session_is_not_remote),
1124            ],
1125            vec![
1126                "Compare with a capture taken interactively as the affected user.".to_string(),
1127                "Be cautious when interpreting PRT and WAM fields from SYSTEM remote sessions.".to_string(),
1128            ],
1129            vec!["Re-run dsregcmd /status in the intended interactive user session when possible.".to_string()],
1130        ));
1131    }
1132
1133    if facts.join_state.workplace_joined == Some(true) {
1134        diagnostics.push(issue(
1135            "workplace-joined-present",
1136            IntuneDiagnosticSeverity::Info,
1137            "configuration",
1138            "Workplace join is present",
1139            "WorkplaceJoined is YES.",
1140            vec![render_bool("WorkplaceJoined", facts.join_state.workplace_joined)],
1141            vec![
1142                "Workplace join is scenario-specific and is not required for most standard Entra joined device flows.".to_string(),
1143                "Confirm that this registration is expected before treating it as important during triage.".to_string(),
1144            ],
1145            Vec::new(),
1146        ));
1147    }
1148
1149    if facts.join_state.domain_joined == Some(true) {
1150        diagnostics.push(issue(
1151            "onprem-domain-joined",
1152            IntuneDiagnosticSeverity::Info,
1153            "configuration",
1154            "Device is joined to on-premises Active Directory",
1155            "DomainJoined is YES.",
1156            vec![render_bool("DomainJoined", facts.join_state.domain_joined)],
1157            vec!["Use this together with AzureAdJoined to understand whether the device is hybrid joined.".to_string()],
1158            Vec::new(),
1159        ));
1160    }
1161
1162    match derived.join_type {
1163        DsregcmdJoinType::EntraIdJoined => diagnostics.push(issue(
1164            "join-type-entraid",
1165            IntuneDiagnosticSeverity::Info,
1166            "configuration",
1167            "Join type is Entra ID Joined",
1168            "AzureAdJoined is YES and DomainJoined is NO.",
1169            vec![format!("JoinType: {}", derived.join_type_label)],
1170            vec!["This is the expected join state for cloud-only Entra ID joined devices.".to_string()],
1171            Vec::new(),
1172        )),
1173        DsregcmdJoinType::HybridEntraIdJoined => diagnostics.push(issue(
1174            "join-type-hybrid",
1175            IntuneDiagnosticSeverity::Info,
1176            "configuration",
1177            "Join type is Hybrid Entra ID Joined",
1178            "AzureAdJoined is YES and DomainJoined is YES.",
1179            vec![format!("JoinType: {}", derived.join_type_label)],
1180            vec!["Hybrid join scenarios depend on both AD connectivity and Entra registration health.".to_string()],
1181            Vec::new(),
1182        )),
1183        _ => {}
1184    }
1185
1186    if facts.user_state.ngc_set == Some(false)
1187        && equals_text(&facts.registration.pre_req_result, "WillProvision")
1188    {
1189        diagnostics.push(issue(
1190            "ngc-will-provision",
1191            IntuneDiagnosticSeverity::Info,
1192            "configuration",
1193            "Windows Hello for Business is expected to provision",
1194            "NgcSet is NO but PreReqResult is WillProvision, which means prerequisites are satisfied and provisioning is expected later.",
1195            vec![
1196                render_bool("NgcSet", facts.user_state.ngc_set),
1197                render_optional("PreReqResult", &facts.registration.pre_req_result),
1198            ],
1199            vec!["Monitor the next sign-in or policy refresh to confirm WHfB provisioning completes.".to_string()],
1200            Vec::new(),
1201        ));
1202    }
1203
1204    if is_failure_text(&facts.post_join_diagnostics.key_sign_test) {
1205        diagnostics.push(issue(
1206            "ngc-key-sign-failed",
1207            IntuneDiagnosticSeverity::Warning,
1208            "configuration",
1209            "Windows Hello key health check failed",
1210            "KeySignTest did not pass, which means the device could not validate the current Windows Hello key material during post-join diagnostics.",
1211            vec![render_optional(
1212                "KeySignTest",
1213                &facts.post_join_diagnostics.key_sign_test,
1214            )],
1215            vec![
1216                "Re-run dsregcmd /status from an elevated prompt because KeySignTest requires elevation to be reliable.".to_string(),
1217                "Check whether the device is entering a recovery or re-registration flow for Windows Hello for Business.".to_string(),
1218            ],
1219            vec![
1220                "Repair or recover the Windows Hello key state before expecting WHfB sign-in to behave normally.".to_string(),
1221            ],
1222        ));
1223    }
1224
1225    if facts.post_join_diagnostics.aad_recovery_enabled == Some(true) {
1226        diagnostics.push(issue(
1227            "ngc-recovery-enabled",
1228            IntuneDiagnosticSeverity::Warning,
1229            "configuration",
1230            "Windows Hello key recovery is enabled",
1231            "AadRecoveryEnabled is YES, which means the current device key state is marked for recovery and the next sign-in may trigger device recovery or re-registration behavior.",
1232            vec![render_bool(
1233                "AadRecoveryEnabled",
1234                facts.post_join_diagnostics.aad_recovery_enabled,
1235            )],
1236            vec![
1237                "Confirm whether recent WHfB sign-in, PIN reset, or recovery prompts were observed on the device.".to_string(),
1238                "Review adjacent device registration or Hello for Business logs for the recovery trigger.".to_string(),
1239            ],
1240            vec![
1241                "Allow the device recovery flow to complete and then capture dsregcmd again to confirm the key state stabilizes.".to_string(),
1242            ],
1243        ));
1244    }
1245
1246    if derived.join_type == DsregcmdJoinType::HybridEntraIdJoined
1247        && contains_text(&facts.pre_join_tests.fallback_to_sync_join, "enabled")
1248    {
1249        diagnostics.push(issue(
1250            "hybrid-fallback-enabled",
1251            IntuneDiagnosticSeverity::Info,
1252            "configuration",
1253            "Hybrid join fallback to sync-join is enabled",
1254            "Fallback to Sync-Join reports ENABLED while the device is hybrid joined.",
1255            vec![render_optional(
1256                "Fallback to Sync-Join",
1257                &facts.pre_join_tests.fallback_to_sync_join,
1258            )],
1259            vec![
1260                "This is informational context for hybrid join timing and registration behavior."
1261                    .to_string(),
1262            ],
1263            Vec::new(),
1264        ));
1265    }
1266
1267    // ── DSRegTool integration — Phase 1 quick-win rules ──────────────────────
1268
1269    // Built-in Administrator account detection
1270    {
1271        let is_builtin_admin = contains_text(&facts.diagnostics.user_identity, "administrator")
1272            || facts
1273                .diagnostics
1274                .user_identity
1275                .as_deref()
1276                .map(|id| id.trim().ends_with("-500"))
1277                .unwrap_or(false);
1278        if is_builtin_admin
1279            && matches!(
1280                derived.join_type,
1281                DsregcmdJoinType::NotJoined | DsregcmdJoinType::Unknown
1282            )
1283        {
1284            diagnostics.push(issue(
1285                "builtin-admin-cannot-join",
1286                IntuneDiagnosticSeverity::Error,
1287                "user",
1288                "Built-in Administrator account cannot perform Azure AD Join",
1289                "The user identity appears to be the built-in Administrator account (or SID ending in -500), which cannot perform Azure AD Join.",
1290                vec![render_optional("User Identity", &facts.diagnostics.user_identity)],
1291                vec![
1292                    "Sign in with a standard user or non-built-in admin account.".to_string(),
1293                ],
1294                vec![
1295                    "Create or use a non-built-in administrator account.".to_string(),
1296                ],
1297            ));
1298        }
1299    }
1300
1301    // Device sync status inference — sync pending
1302    if facts.join_state.domain_joined == Some(true)
1303        && facts.join_state.azure_ad_joined == Some(false)
1304        && facts.pre_join_tests.ad_connectivity_test.is_some()
1305        && facts.pre_join_tests.ad_configuration_test.is_some()
1306        && !is_failure(&facts.pre_join_tests.ad_connectivity_test)
1307        && !is_failure(&facts.pre_join_tests.ad_configuration_test)
1308        && !diagnostics
1309            .iter()
1310            .any(|item| item.id == "entra-sync-pending")
1311    {
1312        diagnostics.push(issue(
1313            "entra-sync-pending-inference",
1314            IntuneDiagnosticSeverity::Warning,
1315            "sync",
1316            "Domain-joined device not yet synced to Entra ID",
1317            "The device is domain-joined but not Azure AD joined, and pre-join AD tests are not failing. This commonly indicates the device object has not yet been synchronized to Entra ID via Azure AD Connect or Cloud Sync.",
1318            vec![
1319                render_bool("DomainJoined", facts.join_state.domain_joined),
1320                render_bool("AzureAdJoined", facts.join_state.azure_ad_joined),
1321            ],
1322            vec![
1323                "Check Azure AD Connect or Cloud Sync health and verify the device object exists on-premises.".to_string(),
1324                "Confirm the OU containing the computer object is in scope for directory synchronization.".to_string(),
1325            ],
1326            vec![
1327                "Wait for the next sync cycle or force a delta sync, then retry registration.".to_string(),
1328            ],
1329        ));
1330    }
1331
1332    // Device sync status inference — fallback to sync-join active (non-hybrid)
1333    if derived.join_type != DsregcmdJoinType::HybridEntraIdJoined
1334        && (contains_text(&facts.pre_join_tests.fallback_to_sync_join, "enabled")
1335            || contains_text(&facts.pre_join_tests.fallback_to_sync_join, "yes"))
1336    {
1337        diagnostics.push(issue(
1338            "fallback-sync-join-active",
1339            IntuneDiagnosticSeverity::Info,
1340            "sync",
1341            "Sync-join fallback is active on a device not yet hybrid-joined",
1342            "Fallback to Sync-Join is active on a device that is not hybrid-joined, which means the device will rely on directory synchronization to complete its join rather than the immediate online path.",
1343            vec![render_optional(
1344                "Fallback to Sync-Join",
1345                &facts.pre_join_tests.fallback_to_sync_join,
1346            )],
1347            vec![
1348                "Monitor Azure AD Connect sync cycles for the device object to appear in Entra ID.".to_string(),
1349            ],
1350            Vec::new(),
1351        ));
1352    }
1353
1354    // Enhanced SCP heuristic — SCP verification needed
1355    {
1356        let has_drs_discovery_failure = is_failure(&facts.pre_join_tests.drs_discovery_test);
1357        let is_domain_joined_not_hybrid = facts.join_state.domain_joined == Some(true)
1358            && matches!(
1359                derived.join_type,
1360                DsregcmdJoinType::HybridEntraIdJoined | DsregcmdJoinType::NotJoined
1361            );
1362        if has_drs_discovery_failure && is_domain_joined_not_hybrid {
1363            diagnostics.push(issue(
1364                "scp-verify-needed",
1365                IntuneDiagnosticSeverity::Warning,
1366                "discovery",
1367                "DRS discovery failed — verify Service Connection Point (SCP) configuration",
1368                "DRS discovery failed on a domain-joined device. In hybrid join scenarios, this commonly points to a missing, misconfigured, or unreachable Service Connection Point (SCP) in Active Directory.",
1369                vec![
1370                    render_optional("DRS Discovery Test", &facts.pre_join_tests.drs_discovery_test),
1371                    render_bool("DomainJoined", facts.join_state.domain_joined),
1372                ],
1373                vec![
1374                    "Verify the SCP exists in Active Directory under CN=62a0ff2e-97b9-4513-943f-0d221bd30080,CN=Device Registration Configuration,CN=Services,CN=Configuration,DC=...".to_string(),
1375                    "Confirm the SCP points to the correct verified tenant domain.".to_string(),
1376                ],
1377                vec![
1378                    "Create or correct the SCP using Azure AD Connect or manually in Active Directory.".to_string(),
1379                ],
1380            ));
1381        }
1382    }
1383
1384    // Enhanced SCP heuristic — SCP tenant mismatch hint
1385    if is_failure(&facts.pre_join_tests.drs_discovery_test)
1386        && is_failure(&facts.pre_join_tests.ad_configuration_test)
1387        && facts.tenant_details.tenant_id.is_some()
1388    {
1389        diagnostics.push(issue(
1390            "scp-tenant-mismatch-hint",
1391            IntuneDiagnosticSeverity::Warning,
1392            "configuration",
1393            "Check SCP tenant alignment after migration or reconfiguration",
1394            "Both DRS discovery and AD configuration tests failed while tenant details are present. This pattern can occur when the SCP points to a different tenant than expected, such as after a tenant migration or domain reconfiguration.",
1395            vec![
1396                render_optional("DRS Discovery Test", &facts.pre_join_tests.drs_discovery_test),
1397                render_optional("AD Configuration Test", &facts.pre_join_tests.ad_configuration_test),
1398                render_optional("TenantId", &facts.tenant_details.tenant_id),
1399            ],
1400            vec![
1401                "Compare the tenant ID in the SCP with the expected target tenant.".to_string(),
1402                "Check if the organization recently migrated tenants or reconfigured hybrid join.".to_string(),
1403            ],
1404            vec![
1405                "Update the SCP to point to the correct tenant domain and re-run Azure AD Connect.".to_string(),
1406            ],
1407        ));
1408    }
1409
1410    diagnostics
1411}
1412
1413#[cfg(test)]
1414mod tests {
1415    use super::analyze_facts;
1416    use crate::dsregcmd::models::{
1417        DsregcmdCaptureConfidence, DsregcmdDiagnosticPhase, DsregcmdJoinType,
1418    };
1419    use crate::dsregcmd::parser::parse_dsregcmd;
1420    use crate::intune::models::IntuneDiagnosticSeverity;
1421    use chrono::Utc;
1422
1423    const HYBRID_SAMPLE: &str = r#"
1424 AzureAdJoined : YES
1425 DomainJoined : YES
1426 WorkplaceJoined : NO
1427 EnterpriseJoined : YES
1428 NgcSet : NO
1429 TenantId : 11111111-2222-3333-4444-555555555555
1430 TenantName : Contoso
1431 DeviceId : abcdefab-1111-2222-3333-abcdefabcdef
1432 DeviceAuthStatus : FAILED. Device is either disabled or deleted
1433 MdmUrl : https://enrollment.manage.microsoft.com/enrollmentserver/discovery.svc
1434 MdmComplianceUrl : https://portal.manage.microsoft.com/Compliance
1435 AzureAdPrt : YES
1436 AzureAdPrtUpdateTime : 2025-03-10 05:00:00.000 UTC
1437 TpmProtected : NO
1438 DeviceCertificateValidity : [ 2025-03-01 00:00:00.000 UTC -- 2025-03-20 00:00:00.000 UTC ]
1439 Previous Prt Attempt : 2025-03-10 08:30:00.000 UTC
1440 Attempt Status : 0xc000006d
1441 User Context : SYSTEM
1442 SessionIsNotRemote : NO
1443 Client Time : 2025-03-10 10:30:00.000 UTC
1444 DRS Discovery Test : FAIL [0x801c0021]
1445 AD Connectivity Test : FAIL [0x54b]
1446 Fallback to Sync-Join : ENABLED
1447 Server Message : AADSTS50126 Invalid username or password ERROR_WINHTTP_TIMEOUT
1448 Server Error Description : AADSTS50126: Invalid username or password.
1449 CertEnrollment : enrollment authority
1450 LogonCertTemplateReady : Pending
1451 PreReqResult : WillProvision
1452 KeySignTest : FAILED
1453 AadRecoveryEnabled : YES
1454"#;
1455
1456    const NOT_JOINED_SAMPLE: &str = r#"
1457 AzureAdJoined : NO
1458 DomainJoined : NO
1459 WorkplaceJoined : NO
1460 TenantId : -
1461 DeviceId : -
1462 MdmUrl : -
1463 MdmComplianceUrl : -
1464 AzureAdPrt : NO
1465"#;
1466
1467    const PHASE_AWARE_SAMPLE: &str = r#"
1468 AzureAdJoined : NO
1469 DomainJoined : YES
1470 WorkplaceJoined : NO
1471 TenantId : 11111111-2222-3333-4444-555555555555
1472 DeviceId : abcdefab-1111-2222-3333-abcdefabcdef
1473 DRS Discovery Test : FAIL [0x801c0021/0x80072ee2]
1474 AD Configuration Test : FAIL [0x801c001d]
1475 Client ErrorCode : 0x801c001d
1476 Error Phase : discover
1477 Attempt Status : 0xc004844c
1478 User Identity : user@contoso.local
1479 Endpoint URI : https://login.microsoftonline.com/11111111-2222-3333-4444-555555555555/oauth2/token/
1480 HTTP Error : 0x8007000d
1481 HTTP status : 400
1482 AzureAdPrt : NO
1483"#;
1484
1485    const ADAL_AND_TPM_SAMPLE: &str = r#"
1486 AzureAdJoined : NO
1487 DomainJoined : YES
1488 WorkplaceJoined : NO
1489 TenantId : 11111111-2222-3333-4444-555555555555
1490 DeviceId : abcdefab-1111-2222-3333-abcdefabcdef
1491 Token Acquisition Test : FAIL [0xcaa90017]
1492 Client ErrorCode : 0xcaa9002c
1493 Attempt Status : 0xcaa90023
1494 HTTP Error : 0xcaa82f8f
1495 Server ErrorDescription : 0xcaa20003
1496 Server Message : 0xcaa90014 0xcaa90006 0xcaa1002d
1497 Endpoint URI : https://fs.contoso.com/adfs/services/trust/mex
1498 AzureAdPrt : NO
1499 DeviceAuthStatus : FAILED
1500 TpmProtected : NO
1501 Server ErrorCode : 0x80090016 0x80290407 0x80280036 0x80090031
1502"#;
1503
1504    #[test]
1505    fn derives_join_type_and_high_value_flags() {
1506        let facts = parse_dsregcmd(HYBRID_SAMPLE).expect("parse hybrid sample");
1507        let analysis = analyze_facts(facts, HYBRID_SAMPLE);
1508
1509        assert_eq!(
1510            analysis.derived.join_type,
1511            DsregcmdJoinType::HybridEntraIdJoined
1512        );
1513        assert_eq!(analysis.derived.azure_ad_prt_present, Some(true));
1514        assert_eq!(analysis.derived.stale_prt, Some(true));
1515        assert_eq!(analysis.derived.tpm_protected, Some(false));
1516        assert_eq!(analysis.derived.certificate_expiring_soon, Some(true));
1517        assert_eq!(
1518            analysis.derived.network_error_code.as_deref(),
1519            Some("ERROR_WINHTTP_TIMEOUT")
1520        );
1521        assert_eq!(analysis.derived.remote_session_system, Some(true));
1522        assert_eq!(
1523            analysis.derived.dominant_phase,
1524            DsregcmdDiagnosticPhase::PostJoin
1525        );
1526        assert_eq!(
1527            analysis.derived.capture_confidence,
1528            DsregcmdCaptureConfidence::Low
1529        );
1530    }
1531
1532    #[test]
1533    fn emits_expected_error_warning_and_info_rules() {
1534        let facts = parse_dsregcmd(HYBRID_SAMPLE).expect("parse hybrid sample");
1535        let analysis = analyze_facts(facts, HYBRID_SAMPLE);
1536        let ids: Vec<&str> = analysis
1537            .diagnostics
1538            .iter()
1539            .map(|item| item.id.as_str())
1540            .collect();
1541
1542        for expected in [
1543            "device-auth-failed",
1544            "drs-discovery-failed",
1545            "ad-connectivity-failed",
1546            "invalid-credentials",
1547            "aadsts50126-detailed",
1548            "aadsts50126",
1549            "network-issue",
1550            "stale-prt",
1551            "no-tpm-protection",
1552            "logon-cert-not-ready",
1553            "cert-expiring-soon",
1554            "remote-session-system",
1555            "join-type-hybrid",
1556            "hybrid-fallback-enabled",
1557            "ngc-will-provision",
1558        ] {
1559            assert!(ids.contains(&expected), "missing diagnostic: {expected}");
1560        }
1561
1562        let remote_rule = analysis
1563            .diagnostics
1564            .iter()
1565            .find(|item| item.id == "remote-session-system")
1566            .expect("remote session rule present");
1567        assert_eq!(remote_rule.severity, IntuneDiagnosticSeverity::Warning);
1568    }
1569
1570    #[test]
1571    fn emits_core_not_joined_rules() {
1572        let facts = parse_dsregcmd(NOT_JOINED_SAMPLE).expect("parse not joined sample");
1573        let analysis = analyze_facts(facts, NOT_JOINED_SAMPLE);
1574        let ids: Vec<&str> = analysis
1575            .diagnostics
1576            .iter()
1577            .map(|item| item.id.as_str())
1578            .collect();
1579
1580        assert_eq!(analysis.derived.join_type, DsregcmdJoinType::NotJoined);
1581        for expected in [
1582            "not-aadj",
1583            "missing-tenant",
1584            "missing-deviceid",
1585            "no-azure-prt",
1586        ] {
1587            assert!(ids.contains(&expected), "missing diagnostic: {expected}");
1588        }
1589    }
1590
1591    #[test]
1592    fn missing_mdm_urls_do_not_create_warnings_by_default() {
1593        let facts = parse_dsregcmd(NOT_JOINED_SAMPLE).expect("parse not joined sample");
1594        let analysis = analyze_facts(facts, NOT_JOINED_SAMPLE);
1595
1596        assert_eq!(analysis.derived.mdm_enrolled, None);
1597        assert_eq!(analysis.derived.missing_mdm, None);
1598        assert_eq!(analysis.derived.missing_compliance_url, None);
1599        assert!(!analysis
1600            .diagnostics
1601            .iter()
1602            .any(|item| item.id == "no-mdm" || item.id == "no-compliance"));
1603    }
1604
1605    #[test]
1606    fn ngc_prereq_fields_stay_lightweight_when_context_is_healthy() {
1607        let sample = r#"
1608 AzureAdJoined : YES
1609 DomainJoined : YES
1610 WorkplaceJoined : NO
1611 TenantId : 11111111-2222-3333-4444-555555555555
1612 DeviceId : abcdefab-1111-2222-3333-abcdefabcdef
1613 AzureAdPrt : YES
1614 AzureAdPrtUpdateTime : 2025-03-10 09:00:00.000 UTC
1615 Client Time : 2025-03-10 10:00:00.000 UTC
1616 NgcSet : NO
1617 IsDeviceJoined : YES
1618 IsUserAzureAD : YES
1619 PolicyEnabled : YES
1620 PostLogonEnabled : YES
1621 DeviceEligible : YES
1622 SessionIsNotRemote : YES
1623 CertEnrollment : none
1624 PreReqResult : WillProvision
1625 KeySignTest : PASSED
1626 AadRecoveryEnabled : NO
1627"#;
1628
1629        let facts = parse_dsregcmd(sample).expect("parse ngc sample");
1630        let analysis = analyze_facts(facts, sample);
1631
1632        assert!(analysis
1633            .diagnostics
1634            .iter()
1635            .any(|item| item.id == "ngc-will-provision"));
1636        assert!(!analysis.diagnostics.iter().any(|item| {
1637            item.id == "ngc-not-set"
1638                || item.id == "logon-cert-not-ready"
1639                || item.id == "ngc-key-sign-failed"
1640                || item.id == "ngc-recovery-enabled"
1641        }));
1642    }
1643
1644    #[test]
1645    fn emits_ngc_post_join_health_diagnostics_when_present() {
1646        let sample = r#"
1647 AzureAdJoined : YES
1648 DomainJoined : NO
1649 WorkplaceJoined : NO
1650 NgcSet : YES
1651 KeySignTest : FAILED
1652 AadRecoveryEnabled : YES
1653 AzureAdPrt : YES
1654"#;
1655
1656        let facts = parse_dsregcmd(sample).expect("parse ngc post join sample");
1657        let analysis = analyze_facts(facts, sample);
1658        let ids: Vec<&str> = analysis
1659            .diagnostics
1660            .iter()
1661            .map(|item| item.id.as_str())
1662            .collect();
1663
1664        assert!(ids.contains(&"ngc-key-sign-failed"));
1665        assert!(ids.contains(&"ngc-recovery-enabled"));
1666    }
1667
1668    #[test]
1669    fn emits_phase_aware_discovery_and_prt_code_diagnostics() {
1670        let facts = parse_dsregcmd(PHASE_AWARE_SAMPLE).expect("parse phase aware sample");
1671        let analysis = analyze_facts(facts, PHASE_AWARE_SAMPLE);
1672        let ids: Vec<&str> = analysis
1673            .diagnostics
1674            .iter()
1675            .map(|item| item.id.as_str())
1676            .collect();
1677
1678        for expected in [
1679            "scp-read-failed",
1680            "drs-discovery-code",
1681            "invalid-discovery-response",
1682            "malformed-upn",
1683            "no-azure-prt",
1684        ] {
1685            assert!(ids.contains(&expected), "missing diagnostic: {expected}");
1686        }
1687
1688        assert_eq!(
1689            analysis.derived.dominant_phase,
1690            DsregcmdDiagnosticPhase::Discover
1691        );
1692    }
1693
1694    #[test]
1695    fn emits_remaining_adal_and_tpm_mappings() {
1696        let facts = parse_dsregcmd(ADAL_AND_TPM_SAMPLE).expect("parse adal and tpm sample");
1697        let analysis = analyze_facts(facts, ADAL_AND_TPM_SAMPLE);
1698        let ids: Vec<&str> = analysis
1699            .diagnostics
1700            .iter()
1701            .map(|item| item.id.as_str())
1702            .collect();
1703
1704        for expected in [
1705            "adal-protocol-not-supported",
1706            "adal-parse-xml-failed",
1707            "adal-password-endpoint-missing",
1708            "adal-secure-failure",
1709            "adal-invalid-grant",
1710            "adal-wstrust-request-failed",
1711            "adal-token-request-failed",
1712            "adal-operation-pending",
1713            "tpm-bad-keyset",
1714            "tpm-internal-error",
1715            "tpm-not-fips",
1716            "tpm-locked-out",
1717        ] {
1718            assert!(ids.contains(&expected), "missing diagnostic: {expected}");
1719        }
1720    }
1721
1722    #[test]
1723    fn derives_high_capture_confidence_for_recent_interactive_capture() {
1724        let now = Utc::now().format("%Y-%m-%d %H:%M:%S%.3f UTC").to_string();
1725        let sample = format!(
1726            "\n AzureAdJoined : YES\n DomainJoined : YES\n AzureAdPrt : YES\n AzureAdPrtUpdateTime : {now}\n Client Time : {now}\n User Context : UN-ELEVATED User\n SessionIsNotRemote : YES\n"
1727        );
1728
1729        let facts = parse_dsregcmd(&sample).expect("parse high confidence sample");
1730        let analysis = analyze_facts(facts, &sample);
1731
1732        assert_eq!(
1733            analysis.derived.capture_confidence,
1734            DsregcmdCaptureConfidence::High
1735        );
1736    }
1737
1738    #[test]
1739    fn derives_low_capture_confidence_for_remote_system_capture() {
1740        let sample = r#"
1741 AzureAdJoined : YES
1742 DomainJoined : YES
1743 AzureAdPrt : YES
1744 AzureAdPrtUpdateTime : 2025-03-10 05:00:00.000 UTC
1745 Client Time : 2025-03-10 10:30:00.000 UTC
1746 User Context : SYSTEM
1747 SessionIsNotRemote : NO
1748"#;
1749
1750        let facts = parse_dsregcmd(sample).expect("parse low confidence sample");
1751        let analysis = analyze_facts(facts, sample);
1752
1753        assert_eq!(
1754            analysis.derived.capture_confidence,
1755            DsregcmdCaptureConfidence::Low
1756        );
1757    }
1758
1759    #[test]
1760    fn emits_builtin_admin_cannot_join_for_administrator_identity() {
1761        let sample = r#"
1762 AzureAdJoined : NO
1763 DomainJoined : NO
1764 WorkplaceJoined : NO
1765 AzureAdPrt : NO
1766 User Identity : Administrator
1767"#;
1768        let facts = parse_dsregcmd(sample).expect("parse admin sample");
1769        let analysis = analyze_facts(facts, sample);
1770        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1771
1772        assert!(
1773            ids.contains(&"builtin-admin-cannot-join"),
1774            "missing builtin-admin-cannot-join"
1775        );
1776        let rule = analysis
1777            .diagnostics
1778            .iter()
1779            .find(|i| i.id == "builtin-admin-cannot-join")
1780            .unwrap();
1781        assert_eq!(rule.severity, IntuneDiagnosticSeverity::Error);
1782    }
1783
1784    #[test]
1785    fn emits_builtin_admin_for_sid_ending_in_500() {
1786        let sample = r#"
1787 AzureAdJoined : NO
1788 DomainJoined : NO
1789 WorkplaceJoined : NO
1790 AzureAdPrt : NO
1791 User Identity : S-1-5-21-3623811015-3361044348-30300820-500
1792"#;
1793        let facts = parse_dsregcmd(sample).expect("parse sid admin sample");
1794        let analysis = analyze_facts(facts, sample);
1795        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1796
1797        assert!(
1798            ids.contains(&"builtin-admin-cannot-join"),
1799            "missing builtin-admin-cannot-join for SID -500"
1800        );
1801    }
1802
1803    #[test]
1804    fn does_not_emit_builtin_admin_when_already_joined() {
1805        let sample = r#"
1806 AzureAdJoined : YES
1807 DomainJoined : NO
1808 WorkplaceJoined : NO
1809 AzureAdPrt : YES
1810 User Identity : Administrator
1811"#;
1812        let facts = parse_dsregcmd(sample).expect("parse joined admin sample");
1813        let analysis = analyze_facts(facts, sample);
1814        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1815
1816        assert!(
1817            !ids.contains(&"builtin-admin-cannot-join"),
1818            "should not fire when already joined"
1819        );
1820    }
1821
1822    #[test]
1823    fn emits_entra_sync_pending_inference_for_domain_joined_not_aad() {
1824        let sample = r#"
1825 AzureAdJoined : NO
1826 DomainJoined : YES
1827 WorkplaceJoined : NO
1828 AzureAdPrt : NO
1829 AD Connectivity Test : PASSED
1830 AD Configuration Test : PASSED
1831"#;
1832        let facts = parse_dsregcmd(sample).expect("parse sync pending sample");
1833        let analysis = analyze_facts(facts, sample);
1834        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1835
1836        assert!(
1837            ids.contains(&"entra-sync-pending-inference"),
1838            "missing entra-sync-pending-inference"
1839        );
1840        let rule = analysis
1841            .diagnostics
1842            .iter()
1843            .find(|i| i.id == "entra-sync-pending-inference")
1844            .unwrap();
1845        assert_eq!(rule.severity, IntuneDiagnosticSeverity::Warning);
1846    }
1847
1848    #[test]
1849    fn does_not_emit_sync_pending_inference_when_ad_tests_fail() {
1850        let sample = r#"
1851 AzureAdJoined : NO
1852 DomainJoined : YES
1853 WorkplaceJoined : NO
1854 AzureAdPrt : NO
1855 AD Connectivity Test : FAIL [0x54b]
1856 AD Configuration Test : PASSED
1857"#;
1858        let facts = parse_dsregcmd(sample).expect("parse ad fail sample");
1859        let analysis = analyze_facts(facts, sample);
1860        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1861
1862        assert!(
1863            !ids.contains(&"entra-sync-pending-inference"),
1864            "should not fire when AD tests fail"
1865        );
1866    }
1867
1868    #[test]
1869    fn emits_fallback_sync_join_active_for_not_joined_device() {
1870        let sample = r#"
1871 AzureAdJoined : NO
1872 DomainJoined : YES
1873 WorkplaceJoined : NO
1874 AzureAdPrt : NO
1875 Fallback to Sync-Join : ENABLED
1876"#;
1877        let facts = parse_dsregcmd(sample).expect("parse fallback sync sample");
1878        let analysis = analyze_facts(facts, sample);
1879        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1880
1881        assert!(
1882            ids.contains(&"fallback-sync-join-active"),
1883            "missing fallback-sync-join-active"
1884        );
1885        let rule = analysis
1886            .diagnostics
1887            .iter()
1888            .find(|i| i.id == "fallback-sync-join-active")
1889            .unwrap();
1890        assert_eq!(rule.severity, IntuneDiagnosticSeverity::Info);
1891    }
1892
1893    #[test]
1894    fn emits_scp_verify_needed_for_drs_failure_on_domain_joined() {
1895        let sample = r#"
1896 AzureAdJoined : NO
1897 DomainJoined : YES
1898 WorkplaceJoined : NO
1899 AzureAdPrt : NO
1900 DRS Discovery Test : FAIL [0x801c0021]
1901"#;
1902        let facts = parse_dsregcmd(sample).expect("parse scp verify sample");
1903        let analysis = analyze_facts(facts, sample);
1904        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1905
1906        assert!(
1907            ids.contains(&"scp-verify-needed"),
1908            "missing scp-verify-needed"
1909        );
1910        let rule = analysis
1911            .diagnostics
1912            .iter()
1913            .find(|i| i.id == "scp-verify-needed")
1914            .unwrap();
1915        assert_eq!(rule.severity, IntuneDiagnosticSeverity::Warning);
1916    }
1917
1918    #[test]
1919    fn does_not_emit_scp_verify_when_not_domain_joined() {
1920        let sample = r#"
1921 AzureAdJoined : NO
1922 DomainJoined : NO
1923 WorkplaceJoined : NO
1924 AzureAdPrt : NO
1925 DRS Discovery Test : FAIL [0x801c0021]
1926"#;
1927        let facts = parse_dsregcmd(sample).expect("parse scp non-domain sample");
1928        let analysis = analyze_facts(facts, sample);
1929        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1930
1931        assert!(
1932            !ids.contains(&"scp-verify-needed"),
1933            "should not fire when not domain-joined"
1934        );
1935    }
1936
1937    #[test]
1938    fn emits_scp_tenant_mismatch_hint_when_both_tests_fail() {
1939        let sample = r#"
1940 AzureAdJoined : NO
1941 DomainJoined : YES
1942 WorkplaceJoined : NO
1943 TenantId : 11111111-2222-3333-4444-555555555555
1944 AzureAdPrt : NO
1945 DRS Discovery Test : FAIL [0x801c0021]
1946 AD Configuration Test : FAIL [0x801c001d]
1947"#;
1948        let facts = parse_dsregcmd(sample).expect("parse tenant mismatch sample");
1949        let analysis = analyze_facts(facts, sample);
1950        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1951
1952        assert!(
1953            ids.contains(&"scp-tenant-mismatch-hint"),
1954            "missing scp-tenant-mismatch-hint"
1955        );
1956        let rule = analysis
1957            .diagnostics
1958            .iter()
1959            .find(|i| i.id == "scp-tenant-mismatch-hint")
1960            .unwrap();
1961        assert_eq!(rule.severity, IntuneDiagnosticSeverity::Warning);
1962    }
1963
1964    #[test]
1965    fn does_not_emit_scp_tenant_mismatch_without_tenant_id() {
1966        let sample = r#"
1967 AzureAdJoined : NO
1968 DomainJoined : YES
1969 WorkplaceJoined : NO
1970 AzureAdPrt : NO
1971 DRS Discovery Test : FAIL [0x801c0021]
1972 AD Configuration Test : FAIL [0x801c001d]
1973"#;
1974        let facts = parse_dsregcmd(sample).expect("parse no tenant sample");
1975        let analysis = analyze_facts(facts, sample);
1976        let ids: Vec<&str> = analysis.diagnostics.iter().map(|i| i.id.as_str()).collect();
1977
1978        assert!(
1979            !ids.contains(&"scp-tenant-mismatch-hint"),
1980            "should not fire without tenant ID"
1981        );
1982    }
1983
1984    #[test]
1985    fn mdm_confirmed_via_registry_diagnostic_fires_when_cross_referenced() {
1986        use super::{apply_enrollment_cross_reference, build_extended_diagnostics};
1987        use crate::dsregcmd::models::{
1988            DsregcmdEnrollmentEntry, DsregcmdEnrollmentEvidence, DsregcmdScheduledTaskEvidence,
1989        };
1990
1991        let facts = parse_dsregcmd(NOT_JOINED_SAMPLE).expect("parse sample");
1992        let mut result = analyze_facts(facts, NOT_JOINED_SAMPLE);
1993
1994        result.enrollment_evidence = Some(DsregcmdEnrollmentEvidence {
1995            enrollment_count: 1,
1996            enrollments: vec![DsregcmdEnrollmentEntry {
1997                guid: Some("{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}".to_string()),
1998                upn: Some("user@contoso.com".to_string()),
1999                provider_id: Some("MS DM Server".to_string()),
2000                enrollment_state: Some(1),
2001            }],
2002        });
2003        result.scheduled_task_evidence = Some(DsregcmdScheduledTaskEvidence {
2004            enterprise_mgmt_guids: vec!["{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}".to_string()],
2005        });
2006
2007        assert_eq!(result.derived.mdm_enrolled, None);
2008        apply_enrollment_cross_reference(&mut result);
2009        assert_eq!(result.derived.mdm_enrolled, Some(true));
2010
2011        let extended = build_extended_diagnostics(&result);
2012        assert!(
2013            extended
2014                .iter()
2015                .any(|d| d.id == "mdm-confirmed-via-registry"),
2016            "should fire mdm-confirmed-via-registry diagnostic"
2017        );
2018    }
2019
2020    #[test]
2021    fn mdm_not_confirmed_without_matching_scheduled_task() {
2022        use super::apply_enrollment_cross_reference;
2023        use crate::dsregcmd::models::{
2024            DsregcmdEnrollmentEntry, DsregcmdEnrollmentEvidence, DsregcmdScheduledTaskEvidence,
2025        };
2026
2027        let facts = parse_dsregcmd(NOT_JOINED_SAMPLE).expect("parse sample");
2028        let mut result = analyze_facts(facts, NOT_JOINED_SAMPLE);
2029
2030        // Enrollment state=1 but GUID doesn't match any scheduled task
2031        result.enrollment_evidence = Some(DsregcmdEnrollmentEvidence {
2032            enrollment_count: 1,
2033            enrollments: vec![DsregcmdEnrollmentEntry {
2034                guid: Some("{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}".to_string()),
2035                upn: Some("user@contoso.com".to_string()),
2036                provider_id: Some("MS DM Server".to_string()),
2037                enrollment_state: Some(1),
2038            }],
2039        });
2040        result.scheduled_task_evidence = Some(DsregcmdScheduledTaskEvidence {
2041            enterprise_mgmt_guids: vec!["{99999999-8888-7777-6666-555555555555}".to_string()],
2042        });
2043
2044        // Cross-reference should NOT upgrade because GUIDs don't match
2045        apply_enrollment_cross_reference(&mut result);
2046        assert_eq!(
2047            result.derived.mdm_enrolled, None,
2048            "should stay None when GUIDs don't match"
2049        );
2050    }
2051
2052    /// Regression: on a joined device with enrollment_count == 0 but cross-reference
2053    /// confirming MDM, the "enrollment-missing-on-joined" warning must NOT fire.
2054    const JOINED_NO_MDM_URLS_SAMPLE: &str = r#"
2055 AzureAdJoined : YES
2056 DomainJoined : NO
2057 WorkplaceJoined : NO
2058 TenantId : 11111111-2222-3333-4444-555555555555
2059 DeviceId : abcdefab-1111-2222-3333-abcdefabcdef
2060 AzureAdPrt : YES
2061 AzureAdPrtUpdateTime : 2025-03-10 05:00:00.000 UTC
2062"#;
2063
2064    #[test]
2065    fn enrollment_missing_warning_suppressed_when_cross_reference_confirms_mdm() {
2066        use super::{apply_enrollment_cross_reference, build_extended_diagnostics};
2067        use crate::dsregcmd::models::{
2068            DsregcmdEnrollmentEntry, DsregcmdEnrollmentEvidence, DsregcmdScheduledTaskEvidence,
2069        };
2070
2071        let facts = parse_dsregcmd(JOINED_NO_MDM_URLS_SAMPLE).expect("parse sample");
2072        let mut result = analyze_facts(facts, JOINED_NO_MDM_URLS_SAMPLE);
2073
2074        // enrollment_count is 0 in registry evidence, but scheduled tasks have matching GUIDs
2075        result.enrollment_evidence = Some(DsregcmdEnrollmentEvidence {
2076            enrollment_count: 0,
2077            enrollments: vec![DsregcmdEnrollmentEntry {
2078                guid: Some("{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}".to_string()),
2079                upn: Some("user@contoso.com".to_string()),
2080                provider_id: Some("MS DM Server".to_string()),
2081                enrollment_state: Some(1),
2082            }],
2083        });
2084        result.scheduled_task_evidence = Some(DsregcmdScheduledTaskEvidence {
2085            enterprise_mgmt_guids: vec!["{AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE}".to_string()],
2086        });
2087
2088        apply_enrollment_cross_reference(&mut result);
2089        assert_eq!(result.derived.mdm_enrolled, Some(true));
2090
2091        let extended = build_extended_diagnostics(&result);
2092
2093        // The cross-reference info diagnostic SHOULD fire
2094        assert!(
2095            extended
2096                .iter()
2097                .any(|d| d.id == "mdm-confirmed-via-registry"),
2098            "should fire mdm-confirmed-via-registry diagnostic"
2099        );
2100
2101        // The enrollment-missing warning should NOT fire — MDM was confirmed
2102        assert!(
2103            !extended
2104                .iter()
2105                .any(|d| d.id == "enrollment-missing-on-joined"),
2106            "enrollment-missing-on-joined should be suppressed when cross-reference confirms MDM"
2107        );
2108    }
2109}