File size: 7,347 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
from __future__ import annotations

from src.domain import AlertClass, ClaimKind, MIN_VALID_EVENTS, StateKnown, Tag, Verdict
from src.i18n import t
from src.schemas import ChangeFinding, Claim, PipelineResult, ValidationReport


def status_label(lang: str, verdict: Verdict, live: bool) -> str:
    suffix = t(lang, "live_note") if live else t(lang, "cached_note")
    return f"{t(lang, f'verdict_{verdict.value}')} · {suffix}"


def decide_verdict(n_valid: int, report: ValidationReport) -> Verdict:
    if not report.ok:
        return Verdict.INVALID
    if n_valid < MIN_VALID_EVENTS:
        return Verdict.INSUFFICIENT
    return Verdict.READY


def reasons(lang: str, result: PipelineResult) -> list[str]:
    kpis = result.kpis
    lines = [
        t(lang, "reason_counts").format(valid=kpis.n_valid, raw=kpis.n_raw, dropped=kpis.n_dropped, changes=kpis.n_changes),
        t(lang, "reason_alerts").format(security=kpis.n_security_review, context=kpis.n_context, threshold=kpis.threshold),
        t(lang, "reason_eval").format(
            recall="—" if kpis.event_recall is None else f"{100 * kpis.event_recall:.0f}%",
            precision="—" if kpis.precision_at_k is None else f"{100 * kpis.precision_at_k:.0f}%",
            fa="—" if kpis.false_alarms_per_account_day is None else f"{kpis.false_alarms_per_account_day:.3f}",
        ),
        t(lang, "reason_maint").format(n=kpis.maintenance_as_security),
        t(lang, "reason_score"),
    ]
    for issue in result.validation.issues[:6]:
        lines.append(f"{issue.severity}: {issue.message}")
    return lines


def annotate_finding(row: ChangeFinding) -> ChangeFinding:
    before = f"`{row.before_event_id}`" if row.before_state == StateKnown.KNOWN and row.before_event_id else "unknown"
    after = f"`{row.after_event_id or row.event_id}`" if row.after_state == StateKnown.KNOWN else "unknown"
    row.observed = [
        f"`{row.event_name}` by `{row.actor_alias}` ({row.actor_kind}/{row.actor_role}) on `{row.account_alias}` at `{row.timestamp}`",
        f"resource `{row.resource_alias}` ({row.resource_kind}) in `{row.region}`; change_type `{row.change_type}`",
        f"request summary: {row.request_summary or '—'}",
        f"before={before}; after={after}; ticket `{row.change_ticket or 'none'}`; approval `{row.approval_status.value}`",
        f"evidence event_id values: {', '.join(row.evidence_event_ids[:6]) or row.event_id}",
    ]
    row.inferred = [
        f"tag `{row.tag.value}` is a review hint, not proof of current cloud exposure",
        f"score={row.score:.2f}; methods={', '.join(row.methods_fired) or 'none'}",
        f"open_cidr={row.cidr_open}; public_policy={row.policy_public}; logging_off={row.logging_off}; detector_off={row.detector_off}; wildcard_trust={row.wildcard_trust}",
        f"severity `{row.severity.value}` is separate from approval `{row.approval_status.value}`",
    ]
    if row.gold_event_ids:
        row.inferred.append(f"overlaps lab event {', '.join(row.gold_event_ids)} ({row.gold_family or 'unlabeled'})")
    if row.incomplete:
        row.action = "Request parameters are missing. Mark as insufficient evidence. Do not conclude current exposure or apply a cloud change from this demo."
    elif row.tag == Tag.MAINTENANCE:
        row.action = "This matches the approved Sunday staging window and ticket. Keep it as context; severity can still be medium."
    elif row.tag == Tag.OPEN_SG:
        row.action = "The event requested 0.0.0.0/0. Review the security-group change. This screen does not update AWS."
    elif row.tag == Tag.PUBLIC_S3:
        row.action = "The event requested a public-access change. Current bucket exposure is unknown unless a before event is also in this export."
    elif row.tag == Tag.TRAIL_STOP:
        row.action = "Logging stop/delete was requested. Confirm with the change ticket; do not call the trail disabled in production from one event."
    elif row.tag == Tag.DETECTOR:
        row.action = "A detector or recorder disable was requested. Review as logging control, not as a confirmed blind spot."
    elif row.tag == Tag.ROOT:
        row.action = "Root activity is always reviewable. This demo never uses a root credential and never changes the account."
    elif row.tag == Tag.TRUST:
        row.action = "The trust policy request includes a wildcard principal. Review the role; do not assume the live policy equals this event."
    elif row.tag == Tag.IAM_ESCALATION:
        row.action = "A privilege-grant event is on the backlog. Confirm the intended role and ticket. No IAM write is sent from here."
    elif row.tag == Tag.ACCESS_KEY:
        row.action = "An access key create event needs a human look. Keys in this lab are fake and redacted."
    elif row.tag == Tag.RESTRICTED_SG:
        row.action = "Ingress is present but not 0.0.0.0/0. Treat as context unless other evidence appears."
    else:
        row.action = "No security-review alert. Keep the change as context or ignore read-only noise."
    row.claims = [
        Claim(kind=ClaimKind.OBSERVED, text=row.observed[0], locator=row.event_id, field="event"),
        Claim(kind=ClaimKind.INFERRED, text=row.inferred[0], locator=row.event_id, field="tag"),
        Claim(kind=ClaimKind.ACTION, text=row.action, locator=row.event_id, field="action"),
    ]
    if row.before_state == StateKnown.UNKNOWN or row.after_state == StateKnown.UNKNOWN:
        row.claims.append(
            Claim(
                kind=ClaimKind.UNKNOWN,
                text="Before/after configuration is unknown unless both events exist in this export.",
                locator=row.event_id,
                field="before_after",
            )
        )
    if row.alert_class == AlertClass.NONE and not row.gold_event_ids:
        row.claims.append(Claim(kind=ClaimKind.UNKNOWN, text="No authored lab event overlaps this change.", locator=row.event_id, field="gold"))
    return row


def finding_markdown(lang: str, row: ChangeFinding | None) -> str:
    if row is None:
        return t(lang, "empty_card")
    observed = "\n".join(f"- {text}" for text in row.observed) or "- —"
    inferred = "\n".join(f"- {text}" for text in row.inferred) or "- —"
    return (
        f"### `{row.finding_id}`\n\n"
        f"**{t(lang, 'observed')}**\n{observed}\n\n"
        f"**{t(lang, 'inferred')}**\n{inferred}\n\n"
        f"**{t(lang, 'action')}**\n- {row.action}\n\n"
        f"{t(lang, 'severity')} `{row.severity.value}` · {t(lang, 'confidence')} `{row.confidence.value}` · "
        f"{t(lang, 'workflow')} `{row.workflow.value}` · {t(lang, 'approval')} `{row.approval_status.value}` · "
        f"gold `{row.gold_family or '—'}`"
    )


def state_markdown(lang: str, row: ChangeFinding | None) -> str:
    if row is None:
        return t(lang, "empty_state")
    return (
        f"**{t(lang, 'state_card')}** `{row.resource_alias}`\n\n"
        f"- {t(lang, 'before')}: `{row.before_state.value}` {('· `' + row.before_event_id + '`') if row.before_event_id else ''}\n"
        f"- {t(lang, 'after')}: `{row.after_state.value}` {('· `' + (row.after_event_id or row.event_id) + '`') if row.after_state.value == 'known' else ''}\n"
        f"- {t(lang, 'state_note')}\n"
        f"- {t(lang, 'approval')}: `{row.approval_status.value}` · ticket `{row.change_ticket or '—'}`"
    )