Skip to main content

cmtraceopen_parser/intune/
ime_parser.rs

1use chrono::{FixedOffset, Local, LocalResult, TimeZone, Utc};
2use regex::Regex;
3
4use crate::models::log_entry::{LogEntry, LogFormat, Severity};
5use crate::parser::ccm::{build_timestamp, format_thread_display, severity_from_type_field};
6use crate::parser::severity::detect_severity_from_text;
7use std::sync::OnceLock;
8
9/// A parsed IME log line with extracted timestamp and message.
10#[derive(Debug, Clone)]
11pub struct ImeLine {
12    pub line_number: u32,
13    pub timestamp: Option<String>,
14    pub timestamp_utc: Option<String>,
15    pub message: String,
16    pub component: Option<String>,
17}
18
19fn ime_record_re() -> &'static Regex {
20    static CELL: OnceLock<Regex> = OnceLock::new();
21    CELL.get_or_init(|| {
22        Regex::new(r#"<!\[LOG\[(?P<msg>[\s\S]*?)\]LOG\]!><(?P<attrs>[^>]*)>"#)
23            .expect("IME record regex must compile")
24    })
25}
26
27/// Regex for simple timestamped log lines (fallback format):
28/// YYYY-MM-DD HH:MM:SS.fff message
29fn simple_ts_re() -> &'static Regex {
30    static CELL: OnceLock<Regex> = OnceLock::new();
31    CELL.get_or_init(|| {
32        Regex::new(r#"^(?P<ts>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}[\.\d]*)\s+(?P<msg>.+)$"#)
33            .expect("IME fallback timestamp regex must compile")
34    })
35}
36
37#[derive(Debug, Clone)]
38struct ParsedImeRecord {
39    line: ImeLine,
40    timestamp_millis: Option<i64>,
41    timestamp_display: Option<String>,
42    severity: Severity,
43    thread: Option<u32>,
44    thread_display: Option<String>,
45    source_file: Option<String>,
46    timezone_offset: Option<i32>,
47    format: LogFormat,
48}
49
50#[derive(Debug, Default, Clone, Copy)]
51struct ParsedImeAttrs<'a> {
52    component: Option<&'a str>,
53    source_file: Option<&'a str>,
54    thread: Option<u32>,
55    type_value: Option<u32>,
56    date: Option<&'a str>,
57    time: Option<&'a str>,
58}
59
60/// Parse IME log content into structured logical records.
61pub fn parse_ime_content(content: &str) -> Vec<ImeLine> {
62    let parsed = parse_ime_records(content);
63    parsed.entries.into_iter().map(|entry| entry.line).collect()
64}
65
66/// Parse IME log content into shared log entries while preserving logical records.
67pub fn parse_ime_entries(content: &str, file_path: &str) -> (Vec<LogEntry>, u32) {
68    let parsed = parse_ime_records(content);
69    let entries = parsed
70        .entries
71        .into_iter()
72        .enumerate()
73        .map(|(id, entry)| LogEntry {
74            id: id as u64,
75            line_number: entry.line.line_number,
76            message: entry.line.message,
77            component: entry.line.component,
78            timestamp: entry.timestamp_millis,
79            timestamp_display: entry.timestamp_display,
80            severity: entry.severity,
81            thread: entry.thread,
82            thread_display: entry.thread_display,
83            source_file: entry.source_file,
84            format: entry.format,
85            file_path: file_path.to_string(),
86            timezone_offset: entry.timezone_offset,
87            error_code_spans: Vec::new(),
88            ip_address: None,
89            host_name: None,
90            mac_address: None,
91            result_code: None,
92            gle_code: None,
93            setup_phase: None,
94            operation_name: None,
95            http_method: None,
96            uri_stem: None,
97            uri_query: None,
98            status_code: None,
99            sub_status: None,
100            time_taken_ms: None,
101            client_ip: None,
102            server_ip: None,
103            user_agent: None,
104            server_port: None,
105            username: None,
106            win32_status: None,
107            query_name: None,
108            query_type: None,
109            response_code: None,
110            dns_direction: None,
111            dns_protocol: None,
112            source_ip: None,
113            dns_flags: None,
114            dns_event_id: None,
115            zone_name: None,
116            entry_kind: None,
117            whatif: None,
118            section_name: None,
119            section_color: None,
120            iteration: None,
121            tags: None,
122        })
123        .collect();
124
125    // Post-process: extract [Subsystem] prefix from message into source_file
126    // when the CCM file="" attribute is empty (common in IME logs).
127    let entries = enrich_subsystem_source(entries);
128
129    (entries, parsed.parse_errors)
130}
131
132/// Extract `[SubSystem]` prefix from IME log messages and populate `source_file`
133/// when it is empty. This surfaces the sub-component in the "Source" column.
134///
135/// Examples:
136/// - `[Win32App] Starting app check in` → source_file = "Win32App"
137/// - `[Win32App][Win32AppDownloadExecutor] Execution completed` → source_file = "Win32App"
138/// - `[PowerShell] Script parameters tamper validation` → source_file = "PowerShell"
139fn enrich_subsystem_source(mut entries: Vec<LogEntry>) -> Vec<LogEntry> {
140    for entry in &mut entries {
141        if entry.source_file.is_some() {
142            continue;
143        }
144        if let Some(subsystem) = extract_subsystem_prefix(&entry.message) {
145            entry.source_file = Some(subsystem);
146        }
147    }
148    entries
149}
150
151/// Extract the first `[Name]` prefix from a message string.
152/// Returns the name without brackets, or None if no prefix found.
153fn extract_subsystem_prefix(message: &str) -> Option<String> {
154    let msg = message.trim_start();
155    if !msg.starts_with('[') {
156        return None;
157    }
158    let end = msg.find(']')?;
159    let name = &msg[1..end];
160    // Skip if it looks like a GUID or timestamp rather than a subsystem name
161    if name.contains('-') && name.len() > 20 {
162        return None;
163    }
164    if name.is_empty() {
165        return None;
166    }
167    Some(name.to_string())
168}
169
170struct ParsedImeChunk {
171    entries: Vec<ParsedImeRecord>,
172    parse_errors: u32,
173}
174
175fn parse_ime_records(content: &str) -> ParsedImeChunk {
176    let line_starts = build_line_starts(content);
177    let mut entries = Vec::with_capacity(line_starts.len());
178    let mut parse_errors = 0u32;
179    let mut cursor = 0usize;
180    let mut matched_any = false;
181
182    for caps in ime_record_re().captures_iter(content) {
183        let Some(full_match) = caps.get(0) else {
184            continue;
185        };
186
187        push_unmatched_segment(
188            &content[cursor..full_match.start()],
189            cursor,
190            &line_starts,
191            &mut entries,
192            &mut parse_errors,
193        );
194
195        if let Some(record) = parse_record(&caps, full_match.start(), &line_starts) {
196            entries.push(record);
197        } else {
198            push_unmatched_segment(
199                full_match.as_str(),
200                full_match.start(),
201                &line_starts,
202                &mut entries,
203                &mut parse_errors,
204            );
205        }
206
207        cursor = full_match.end();
208        matched_any = true;
209    }
210
211    push_unmatched_segment(
212        &content[cursor..],
213        cursor,
214        &line_starts,
215        &mut entries,
216        &mut parse_errors,
217    );
218
219    if matched_any {
220        ParsedImeChunk {
221            entries,
222            parse_errors,
223        }
224    } else {
225        parse_fallback_lines(content)
226    }
227}
228
229fn parse_record(
230    caps: &regex::Captures<'_>,
231    offset: usize,
232    line_starts: &[usize],
233) -> Option<ParsedImeRecord> {
234    let message = caps.name("msg")?.as_str().to_string();
235    let attrs = parse_attributes(caps.name("attrs")?.as_str());
236    let component = attrs
237        .component
238        .filter(|value| !value.is_empty())
239        .map(ToOwned::to_owned);
240    let source_file = attrs
241        .source_file
242        .filter(|value| !value.is_empty())
243        .map(ToOwned::to_owned);
244    let thread = attrs.thread;
245    let thread_display = thread.map(format_thread_display);
246    let severity = severity_from_type_field(attrs.type_value, &message);
247    let (timestamp_millis, timestamp_display, timezone_offset, line_timestamp, line_timestamp_utc) =
248        parse_timestamp_fields(attrs.date, attrs.time);
249
250    Some(ParsedImeRecord {
251        line: ImeLine {
252            line_number: line_number_for_offset(line_starts, offset),
253            timestamp: line_timestamp,
254            timestamp_utc: line_timestamp_utc,
255            message,
256            component,
257        },
258        timestamp_millis,
259        timestamp_display,
260        severity,
261        thread,
262        thread_display,
263        source_file,
264        timezone_offset,
265        format: LogFormat::Ccm,
266    })
267}
268
269fn parse_attributes(attrs: &str) -> ParsedImeAttrs<'_> {
270    let bytes = attrs.as_bytes();
271    let mut index = 0usize;
272    let mut parsed = ParsedImeAttrs::default();
273
274    while index < bytes.len() {
275        while index < bytes.len() && bytes[index].is_ascii_whitespace() {
276            index += 1;
277        }
278
279        let key_start = index;
280        while index < bytes.len() && (bytes[index].is_ascii_alphanumeric() || bytes[index] == b'_')
281        {
282            index += 1;
283        }
284
285        if key_start == index {
286            index += 1;
287            continue;
288        }
289
290        if index + 1 >= bytes.len() || bytes[index] != b'=' || bytes[index + 1] != b'"' {
291            while index < bytes.len() && !bytes[index].is_ascii_whitespace() {
292                index += 1;
293            }
294            continue;
295        }
296
297        let key = &attrs[key_start..index];
298        index += 2;
299
300        let value_start = index;
301        while index < bytes.len() && bytes[index] != b'"' {
302            index += 1;
303        }
304
305        if index >= bytes.len() {
306            break;
307        }
308
309        let value = &attrs[value_start..index];
310        match_attribute(&mut parsed, key, value);
311        index += 1;
312    }
313
314    parsed
315}
316
317// The tuple return avoids an extra struct for internal parsing.
318#[allow(clippy::type_complexity)]
319fn parse_timestamp_fields(
320    date: Option<&str>,
321    time: Option<&str>,
322) -> (
323    Option<i64>,
324    Option<String>,
325    Option<i32>,
326    Option<String>,
327    Option<String>,
328) {
329    let Some(date) = date else {
330        return (None, None, None, None, None);
331    };
332    let Some(time) = time else {
333        return (None, None, None, None, None);
334    };
335
336    let Some((month, day, year)) = parse_date(date) else {
337        return (None, None, None, None, None);
338    };
339    let Some((hour, minute, second, millis, timezone_offset)) = parse_time(time) else {
340        return (None, None, None, None, None);
341    };
342
343    // When no timezone offset is embedded in the log (the norm for IME logs),
344    // fall back to the machine's current local UTC offset so the display column
345    // shows the correct local time rather than treating local time as UTC.
346    let effective_tz = timezone_offset.or_else(|| {
347        let offset_secs = chrono::Local::now().offset().local_minus_utc();
348        offset_secs.checked_div(60)
349    });
350
351    let (timestamp_millis, timestamp_display) =
352        build_timestamp(month, day, year, hour, minute, second, millis, effective_tz);
353    let line_timestamp = timestamp_display.clone();
354    let line_timestamp_utc = build_utc_timestamp(
355        month,
356        day,
357        year,
358        hour,
359        minute,
360        second,
361        millis,
362        timezone_offset,
363    );
364
365    (
366        timestamp_millis,
367        timestamp_display,
368        timezone_offset,
369        line_timestamp,
370        line_timestamp_utc,
371    )
372}
373
374// Timestamp construction keeps calendar fields explicit.
375#[allow(clippy::too_many_arguments)]
376fn build_utc_timestamp(
377    month: u32,
378    day: u32,
379    year: i32,
380    hour: u32,
381    minute: u32,
382    second: u32,
383    millis: u32,
384    timezone_offset: Option<i32>,
385) -> Option<String> {
386    let naive = chrono::NaiveDate::from_ymd_opt(year, month, day)?
387        .and_hms_milli_opt(hour, minute, second, millis)?;
388
389    let utc_value = if let Some(offset_minutes) = timezone_offset {
390        offset_minutes
391            .checked_mul(60)
392            .and_then(FixedOffset::east_opt)
393            .and_then(|offset| offset.from_local_datetime(&naive).single())
394            .map(|dt| dt.with_timezone(&Utc))
395            .unwrap_or_else(|| naive.and_utc())
396    } else {
397        match Local.from_local_datetime(&naive) {
398            LocalResult::Single(local_value) => local_value.with_timezone(&Utc),
399            LocalResult::Ambiguous(local_value, _) => local_value.with_timezone(&Utc),
400            LocalResult::None => naive.and_utc(),
401        }
402    };
403
404    Some(utc_value.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
405}
406
407fn parse_fallback_timestamp_utc(value: &str) -> Option<String> {
408    let naive = chrono::NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S%.f").ok()?;
409    let local_value = match Local.from_local_datetime(&naive) {
410        LocalResult::Single(local_value) => local_value,
411        LocalResult::Ambiguous(local_value, _) => local_value,
412        LocalResult::None => return None,
413    };
414
415    Some(
416        local_value
417            .with_timezone(&Utc)
418            .to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
419    )
420}
421
422fn parse_date(date: &str) -> Option<(u32, u32, i32)> {
423    let (month, remainder) = date.split_once('-')?;
424    let (day, year) = remainder.split_once('-')?;
425    Some((
426        parse_ascii_u32(month)?,
427        parse_ascii_u32(day)?,
428        parse_ascii_i32(year)?,
429    ))
430}
431
432fn parse_time(time: &str) -> Option<(u32, u32, u32, u32, Option<i32>)> {
433    let timezone_start = find_timezone_start(time);
434    let (time_value, timezone_value) = match timezone_start {
435        Some(index) => (&time[..index], Some(&time[index..])),
436        None => (time, None),
437    };
438    let (hour, remainder) = time_value.split_once(':')?;
439    let (minute, second_and_fraction) = remainder.split_once(':')?;
440    let (second, fraction) = second_and_fraction
441        .split_once('.')
442        .map_or((second_and_fraction, ""), |(seconds, fraction)| {
443            (seconds, fraction)
444        });
445    let millis = if fraction.is_empty() {
446        0
447    } else {
448        truncate_fraction_to_millis(fraction)?
449    };
450
451    Some((
452        parse_ascii_u32(hour)?,
453        parse_ascii_u32(minute)?,
454        parse_ascii_u32(second)?,
455        millis,
456        timezone_value.and_then(parse_timezone_offset),
457    ))
458}
459
460fn parse_timezone_offset(value: &str) -> Option<i32> {
461    if value.eq_ignore_ascii_case("z") {
462        return Some(0);
463    }
464
465    if value.contains(':') {
466        let sign = if value.starts_with('-') { -1 } else { 1 };
467        let trimmed = value.trim_start_matches(['+', '-']);
468        let (hours, minutes) = trimmed.split_once(':')?;
469        let hours = parse_ascii_i32(hours)?;
470        let minutes = parse_ascii_i32(minutes)?;
471        return Some(sign * ((hours * 60) + minutes));
472    }
473
474    parse_ascii_i32(value)
475}
476
477fn match_attribute<'a>(parsed: &mut ParsedImeAttrs<'a>, key: &str, value: &'a str) {
478    if key.eq_ignore_ascii_case("component") {
479        parsed.component = Some(value);
480    } else if key.eq_ignore_ascii_case("file") {
481        parsed.source_file = Some(value);
482    } else if key.eq_ignore_ascii_case("thread") {
483        parsed.thread = parse_ascii_u32(value);
484    } else if key.eq_ignore_ascii_case("type") {
485        parsed.type_value = parse_ascii_u32(value);
486    } else if key.eq_ignore_ascii_case("date") {
487        parsed.date = Some(value);
488    } else if key.eq_ignore_ascii_case("time") {
489        parsed.time = Some(value);
490    }
491}
492
493fn find_timezone_start(time: &str) -> Option<usize> {
494    let bytes = time.as_bytes();
495    for (index, value) in bytes.iter().enumerate().skip(1) {
496        if matches!(*value, b'+' | b'-') {
497            return Some(index);
498        }
499    }
500
501    None
502}
503
504fn truncate_fraction_to_millis(value: &str) -> Option<u32> {
505    let mut millis = 0u32;
506    let mut digits = 0u8;
507
508    for byte in value.bytes() {
509        if !byte.is_ascii_digit() {
510            return None;
511        }
512
513        if digits < 3 {
514            millis = (millis * 10) + u32::from(byte - b'0');
515            digits += 1;
516        }
517    }
518
519    while digits < 3 {
520        millis *= 10;
521        digits += 1;
522    }
523
524    Some(millis)
525}
526
527fn parse_ascii_u32(value: &str) -> Option<u32> {
528    if value.is_empty() {
529        return None;
530    }
531
532    let mut parsed = 0u32;
533    for byte in value.bytes() {
534        if !byte.is_ascii_digit() {
535            return None;
536        }
537
538        parsed = parsed
539            .checked_mul(10)?
540            .checked_add(u32::from(byte - b'0'))?;
541    }
542
543    Some(parsed)
544}
545
546fn parse_ascii_i32(value: &str) -> Option<i32> {
547    let bytes = value.as_bytes();
548    if bytes.is_empty() {
549        return None;
550    }
551
552    let (sign, digits) = match bytes[0] {
553        b'+' => (1i32, &value[1..]),
554        b'-' => (-1i32, &value[1..]),
555        _ => (1i32, value),
556    };
557
558    let parsed = parse_ascii_u32(digits)? as i32;
559    parsed.checked_mul(sign)
560}
561
562fn build_line_starts(content: &str) -> Vec<usize> {
563    let mut starts = vec![0];
564    for (index, byte) in content.bytes().enumerate() {
565        if byte == b'\n' {
566            starts.push(index + 1);
567        }
568    }
569    starts
570}
571
572fn line_number_for_offset(line_starts: &[usize], offset: usize) -> u32 {
573    match line_starts.binary_search(&offset) {
574        Ok(index) => (index + 1) as u32,
575        Err(index) => index as u32,
576    }
577}
578
579fn push_unmatched_segment(
580    segment: &str,
581    base_offset: usize,
582    line_starts: &[usize],
583    entries: &mut Vec<ParsedImeRecord>,
584    parse_errors: &mut u32,
585) {
586    let mut local_offset = 0usize;
587
588    for piece in segment.split_inclusive('\n') {
589        let line = piece.trim_end_matches(['\r', '\n']);
590        let trimmed = line.trim();
591        if !trimmed.is_empty() {
592            entries.push(ParsedImeRecord {
593                line: ImeLine {
594                    line_number: line_number_for_offset(line_starts, base_offset + local_offset),
595                    timestamp: None,
596                    timestamp_utc: None,
597                    message: trimmed.to_string(),
598                    component: None,
599                },
600                timestamp_millis: None,
601                timestamp_display: None,
602                severity: detect_severity_from_text(trimmed),
603                thread: None,
604                thread_display: None,
605                source_file: None,
606                timezone_offset: None,
607                format: LogFormat::Plain,
608            });
609            *parse_errors += 1;
610        }
611        local_offset += piece.len();
612    }
613}
614
615fn parse_fallback_lines(content: &str) -> ParsedImeChunk {
616    let mut entries = Vec::new();
617
618    for (index, line) in content.lines().enumerate() {
619        let trimmed = line.trim();
620        if trimmed.is_empty() {
621            continue;
622        }
623
624        if let Some(caps) = simple_ts_re().captures(trimmed) {
625            let timestamp = caps.name("ts").map(|value| value.as_str().to_string());
626            let timestamp_utc = timestamp.as_deref().and_then(parse_fallback_timestamp_utc);
627            let message = caps
628                .name("msg")
629                .map(|value| value.as_str().to_string())
630                .unwrap_or_default();
631            entries.push(ParsedImeRecord {
632                line: ImeLine {
633                    line_number: (index + 1) as u32,
634                    timestamp: timestamp.clone(),
635                    timestamp_utc,
636                    message: message.clone(),
637                    component: None,
638                },
639                timestamp_millis: None,
640                timestamp_display: timestamp,
641                severity: detect_severity_from_text(&message),
642                thread: None,
643                thread_display: None,
644                source_file: None,
645                timezone_offset: None,
646                format: LogFormat::Plain,
647            });
648        } else {
649            entries.push(ParsedImeRecord {
650                line: ImeLine {
651                    line_number: (index + 1) as u32,
652                    timestamp: None,
653                    timestamp_utc: None,
654                    message: trimmed.to_string(),
655                    component: None,
656                },
657                timestamp_millis: None,
658                timestamp_display: None,
659                severity: detect_severity_from_text(trimmed),
660                thread: None,
661                thread_display: None,
662                source_file: None,
663                timezone_offset: None,
664                format: LogFormat::Plain,
665            });
666        }
667    }
668
669    ParsedImeChunk {
670        parse_errors: 0,
671        entries,
672    }
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678
679    #[test]
680    fn test_parse_ime_content_preserves_logical_record_start_lines() {
681        let content = concat!(
682            "<![LOG[First record]LOG]!><time=\"11:16:37.3093207\" date=\"3-12-2026\" component=\"HealthScripts\" context=\"\" type=\"1\" thread=\"50\" file=\"\">\n",
683            "<![LOG[Second line one\n",
684            "Second line two]LOG]!><time=\"11:16:42.3322734\" date=\"3-12-2026\" component=\"HealthScripts\" context=\"\" type=\"3\" thread=\"50\" file=\"\">\n",
685            "<![LOG[Third record]LOG]!><time=\"11:16:43.0000000\" date=\"3-12-2026\" component=\"HealthScripts\" context=\"\" type=\"1\" thread=\"50\" file=\"\">"
686        );
687
688        let lines = parse_ime_content(content);
689        let expected_utc = parse_fallback_timestamp_utc("2026-03-12 11:16:37.309");
690
691        assert_eq!(lines.len(), 3);
692        assert_eq!(lines[0].line_number, 1);
693        assert_eq!(lines[1].line_number, 2);
694        assert_eq!(lines[2].line_number, 4);
695        assert_eq!(lines[1].message, "Second line one\nSecond line two");
696        assert_eq!(lines[0].timestamp_utc, expected_utc);
697    }
698
699    #[test]
700    fn test_parse_ime_entries_preserves_truncated_tail_as_plain_text() {
701        let content = concat!(
702            "<![LOG[Client Health evaluation starts.]LOG]!><time=\"23:00:10.6893636\" date=\"11-12-2025\" component=\"ClientHealth\" context=\"\" type=\"1\" thread=\"1\" file=\"\">\n",
703            "\n",
704            "<![LOG[OnStart, public cloud env.]LOG]!><time=\"23:00:11.4573058\" date=\"11-12-2025\" component=\"ClientHealth\" context=\"\" type=\"1\" thread=\"1\" file=\"\">\n",
705            "<![LOG[Set MdmDeviceCertificate : 3788C1E384FDCB3F173A3222CB4191883A94224E]LOG]!><time=\"23:00"
706        );
707
708        let (entries, parse_errors) = parse_ime_entries(content, "ClientHealth.log");
709
710        assert_eq!(parse_errors, 1);
711        assert_eq!(entries.len(), 3);
712        assert_eq!(entries[0].line_number, 1);
713        assert_eq!(entries[1].line_number, 3);
714        assert_eq!(entries[2].line_number, 4);
715        assert_eq!(entries[2].format, LogFormat::Plain);
716        assert!(entries[2].message.contains("Set MdmDeviceCertificate"));
717    }
718
719    #[test]
720    fn test_parse_ime_entries_parses_attributes_without_regex_map_overhead() {
721        let content = "<![LOG[Case-insensitive attribute parse]LOG]!><THREAD=\"50\" TYPE=\"3\" context=\"\" COMPONENT=\"HealthScripts\" DATE=\"3-12-2026\" TIME=\"11:16:42.3322734\" FILE=\"script.ps1\">";
722
723        let (entries, parse_errors) = parse_ime_entries(content, "HealthScripts.log");
724
725        assert_eq!(parse_errors, 0);
726        assert_eq!(entries.len(), 1);
727        assert_eq!(entries[0].component.as_deref(), Some("HealthScripts"));
728        assert_eq!(entries[0].thread, Some(50));
729        assert_eq!(entries[0].source_file.as_deref(), Some("script.ps1"));
730        assert_eq!(entries[0].severity, Severity::Error);
731        assert_eq!(
732            entries[0].timestamp_display.as_deref(),
733            Some("03-12-2026 11:16:42.332")
734        );
735    }
736
737    #[test]
738    fn test_parse_ime_content_normalizes_timezone_offset_to_utc() {
739        let content = "<![LOG[Timezone aware]LOG]!><time=\"08:06:34.590-060\" date=\"09-02-2016\" component=\"ContentTransferManager\" context=\"\" type=\"1\" thread=\"3692\" file=\"datatransfer.cpp\">";
740
741        let lines = parse_ime_content(content);
742
743        assert_eq!(lines.len(), 1);
744        assert_eq!(
745            lines[0].timestamp_utc.as_deref(),
746            Some("2016-09-02T09:06:34.590Z")
747        );
748    }
749
750    #[test]
751    fn test_build_utc_timestamp_extreme_offset_falls_back() {
752        // Extreme offset should fall back to UTC-as-local, not return None
753        let result = super::build_utc_timestamp(1, 1, 2024, 10, 0, 0, 0, Some(99999));
754        assert!(
755            result.is_some(),
756            "extreme offset should fall back, not return None"
757        );
758        assert_eq!(result.unwrap(), "2024-01-01T10:00:00.000Z");
759    }
760
761    /// IME logs typically omit the timezone offset from the time field.
762    /// Verify that the local-time fallback is applied so the stored UTC millis
763    /// differ from a naive UTC interpretation by the machine's current offset.
764    #[test]
765    fn test_no_timezone_in_time_field_uses_local_fallback() {
766        // A record whose time= field has no +/- suffix (typical IME format)
767        let content = "<![LOG[EMS Agent Started]LOG]!><time=\"00:22:30.000\" date=\"3-27-2026\" component=\"IntuneManagementExtension\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
768
769        let (entries, _) = parse_ime_entries(content, "IntuneManagementExtension.log");
770        assert_eq!(entries.len(), 1);
771
772        let ts = entries[0].timestamp.expect("timestamp should be set");
773
774        // Compute what the timestamp would be if naive time were treated as UTC (the old bug).
775        let naive_utc = chrono::NaiveDate::from_ymd_opt(2026, 3, 27)
776            .unwrap()
777            .and_hms_milli_opt(0, 22, 30, 0)
778            .unwrap()
779            .and_utc()
780            .timestamp_millis();
781
782        // Compute what the timestamp should be with the local-timezone fallback.
783        let local_offset_mins = chrono::Local::now().offset().local_minus_utc() / 60;
784        let expected = crate::parser::ccm::naive_to_utc_millis(
785            chrono::NaiveDate::from_ymd_opt(2026, 3, 27)
786                .unwrap()
787                .and_hms_milli_opt(0, 22, 30, 0)
788                .unwrap(),
789            Some(local_offset_mins),
790        );
791
792        assert_eq!(ts, expected, "timestamp should use local-timezone fallback");
793
794        // If the machine is not UTC, the stored value must differ from the naive-UTC value.
795        if local_offset_mins != 0 {
796            assert_ne!(
797                ts, naive_utc,
798                "timestamp must not treat naive local time as UTC when offset is non-zero"
799            );
800        }
801    }
802}