File size: 2,913 Bytes
955a66f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from __future__ import annotations

from typing import Any

import pandas as pd

from src.domain import MAX_BYTES, MAX_EVENTS, REQUIRED_EVENT_FIELDS
from src.parsers import parse_timestamp
from src.schemas import ValidationReport


def _as_rows(frame: pd.DataFrame | list[dict[str, Any]] | None) -> list[dict[str, Any]]:
    if frame is None:
        return []
    if isinstance(frame, pd.DataFrame):
        if frame.empty:
            return []
        rows: list[dict[str, Any]] = []
        for raw in frame.to_dict(orient="records"):
            rows.append(
                {
                    key: value
                    for key, value in raw.items()
                    if value is not None and not (isinstance(value, float) and pd.isna(value))
                }
            )
        return rows
    return [dict(item) for item in frame if isinstance(item, dict)]


def validate_payload_size(text: str) -> ValidationReport:
    report = ValidationReport(ok=True)
    if len((text or "").encode("utf-8")) > MAX_BYTES:
        report.add("size", f"Upload exceeds {MAX_BYTES} bytes.")
    return report


def validate_events(rows: pd.DataFrame | list[dict[str, Any]] | None) -> ValidationReport:
    report = ValidationReport(ok=True)
    raw_rows = _as_rows(rows)
    report.n_raw = len(raw_rows)
    if not raw_rows:
        report.add("empty", "No CloudTrail events provided.", severity="warning")
        return report
    if len(raw_rows) > MAX_EVENTS:
        report.add("count", f"This run accepts at most {MAX_EVENTS} CloudTrail events.")
        return report
    seen: set[str] = set()
    valid = 0
    dropped = 0
    for index, row in enumerate(raw_rows):
        locator = f"event row {index}"
        timestamp = parse_timestamp(
            row.get("timestamp") or row.get("eventTime") or row.get("time") or row.get("created_at")
        )
        event_name = str(row.get("event_name") or row.get("eventName") or "").strip()
        missing = []
        if timestamp is None:
            missing.append("timestamp")
        if not event_name:
            missing.append("event_name")
        if missing:
            dropped += 1
            report.add(
                "incomplete",
                f"Dropped incomplete row ({', '.join(missing)}).",
                locator=locator,
                severity="warning",
            )
            continue
        event_id = str(row.get("event_id") or row.get("eventID") or "").strip()
        if event_id:
            if event_id in seen:
                report.add("duplicate", f"Duplicate event_id `{event_id}`.", locator=locator)
            seen.add(event_id)
        valid += 1
    report.n_valid = valid
    report.n_dropped = dropped
    if valid == 0:
        report.add("empty", "No valid CloudTrail events remained after schema checks.", severity="warning")
    unused = REQUIRED_EVENT_FIELDS
    _ = unused
    return report