agentlatch-security 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
agent_latch/report.py ADDED
@@ -0,0 +1,241 @@
1
+ """Human-readable, JSON, and SARIF report serializers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict
7
+ from typing import Any
8
+
9
+ from agent_latch import __version__
10
+ from agent_latch.owasp import (
11
+ OWASP_AGENTIC_TITLE,
12
+ OWASP_AGENTIC_URL,
13
+ category_entries,
14
+ category_label,
15
+ coverage,
16
+ coverage_status,
17
+ )
18
+ from agent_latch.rules import Finding
19
+
20
+ _SEVERITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4, "unknown": 5}
21
+ _SARIF_LEVEL = {
22
+ "critical": "error",
23
+ "high": "error",
24
+ "medium": "warning",
25
+ "low": "note",
26
+ "info": "note",
27
+ "unknown": "warning",
28
+ }
29
+
30
+
31
+ def severity_sort_key(finding: Finding) -> tuple[int, str, int]:
32
+ return (_SEVERITY_ORDER.get(finding.severity, 99), finding.path, finding.line)
33
+
34
+
35
+ def finding_dict(finding: Finding) -> dict[str, Any]:
36
+ result = asdict(finding)
37
+ result["owasp"] = list(finding.owasp)
38
+ result["owasp_categories"] = category_entries(finding.owasp)
39
+ return result
40
+
41
+
42
+ def owasp_labels(finding: Finding) -> str:
43
+ return "; ".join(category_label(cid) for cid in finding.owasp) or "none"
44
+
45
+
46
+ def coverage_lines(findings: list[Finding]) -> list[str]:
47
+ """Plain-text ASI01–ASI10 summary; categories without any rule are called out explicitly."""
48
+ lines = [f"{OWASP_AGENTIC_TITLE} (informational mapping):"]
49
+ for entry in coverage(findings):
50
+ lines.append(f" {entry['id']} {entry['name']}: {coverage_status(entry)}")
51
+ return lines
52
+
53
+
54
+ def json_report(
55
+ findings: list[Finding],
56
+ scanned_path: str,
57
+ dependency_manifests: int | None = None,
58
+ manifest: str | None = None,
59
+ suppressed: int = 0,
60
+ min_severity: str | None = None,
61
+ hidden: int = 0,
62
+ ) -> str:
63
+ payload = {
64
+ "scanner": {"name": "AgentLatch", "version": __version__},
65
+ "scan_target": scanned_path,
66
+ "manifest": manifest,
67
+ "finding_count": len(findings),
68
+ "suppressed_count": suppressed,
69
+ "min_severity": min_severity,
70
+ "hidden_below_min_severity": hidden,
71
+ "dependency_audit": (
72
+ {
73
+ "status": "completed" if dependency_manifests else "no_supported_manifests",
74
+ "manifest_count": dependency_manifests,
75
+ "note": "Uses pip-audit advisory data; package names and versions are sent to its configured vulnerability service. No package installation or dependency resolution is performed.",
76
+ }
77
+ if dependency_manifests is not None
78
+ else None
79
+ ),
80
+ "findings": [finding_dict(item) for item in findings],
81
+ "owasp_agentic": {
82
+ "title": OWASP_AGENTIC_TITLE,
83
+ "url": OWASP_AGENTIC_URL,
84
+ "categories": coverage(findings),
85
+ "note": "Informational mapping, not a compliance assessment. has_checks=false means AgentLatch has no rule for that category yet.",
86
+ },
87
+ "disclaimer": "Selected static checks only; this is not a certification or proof that the project is secure.",
88
+ }
89
+ return json.dumps(payload, indent=2, ensure_ascii=False)
90
+
91
+
92
+ def sarif_report(
93
+ findings: list[Finding],
94
+ scanned_path: str,
95
+ dependency_manifests: int | None = None,
96
+ manifest: str | None = None,
97
+ suppressed: int = 0,
98
+ min_severity: str | None = None,
99
+ hidden: int = 0,
100
+ ) -> str:
101
+ rules_by_id: dict[str, dict[str, Any]] = {}
102
+ results: list[dict[str, Any]] = []
103
+ for finding in findings:
104
+ rules_by_id.setdefault(
105
+ finding.rule_id,
106
+ {
107
+ "id": finding.rule_id,
108
+ "name": finding.title,
109
+ "shortDescription": {"text": finding.title},
110
+ "help": {
111
+ "text": f"{finding.message}\n\nOWASP Agentic mapping: {owasp_labels(finding)}"
112
+ },
113
+ "properties": {
114
+ "tags": ["security", *finding.owasp],
115
+ "owaspCategories": category_entries(finding.owasp),
116
+ },
117
+ },
118
+ )
119
+ results.append(
120
+ {
121
+ "ruleId": finding.rule_id,
122
+ "level": _SARIF_LEVEL.get(finding.severity, "warning"),
123
+ "message": {"text": finding.message},
124
+ "locations": [
125
+ {
126
+ "physicalLocation": {
127
+ "artifactLocation": {"uri": finding.path},
128
+ "region": {
129
+ "startLine": finding.line,
130
+ "startColumn": finding.column,
131
+ "snippet": {"text": finding.evidence},
132
+ },
133
+ }
134
+ }
135
+ ],
136
+ "properties": {
137
+ "severity": finding.severity,
138
+ "confidence": finding.confidence,
139
+ "owasp": list(finding.owasp),
140
+ "owaspCategories": category_entries(finding.owasp),
141
+ },
142
+ }
143
+ )
144
+ payload = {
145
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
146
+ "version": "2.1.0",
147
+ "runs": [
148
+ {
149
+ "tool": {
150
+ "driver": {
151
+ "name": "AgentLatch",
152
+ "version": __version__,
153
+ "rules": list(rules_by_id.values()),
154
+ }
155
+ },
156
+ "artifacts": [{"location": {"uri": scanned_path}}],
157
+ "properties": {
158
+ "agentManifest": manifest,
159
+ "dependencyAuditManifestCount": dependency_manifests,
160
+ "dependencyAuditStatus": (
161
+ ("completed" if dependency_manifests else "no_supported_manifests")
162
+ if dependency_manifests is not None
163
+ else "not_requested"
164
+ ),
165
+ "owaspAgenticCoverage": coverage(findings),
166
+ "suppressedCount": suppressed,
167
+ "minSeverity": min_severity,
168
+ "hiddenBelowMinSeverityCount": hidden,
169
+ },
170
+ "results": results,
171
+ }
172
+ ],
173
+ }
174
+ return json.dumps(payload, indent=2, ensure_ascii=False)
175
+
176
+
177
+ def text_report(
178
+ findings: list[Finding],
179
+ scanned_path: str,
180
+ dependency_manifests: int | None = None,
181
+ manifest: str | None = None,
182
+ suppressed: int = 0,
183
+ min_severity: str | None = None,
184
+ hidden: int = 0,
185
+ ) -> str:
186
+ header = f"AgentLatch scan: {scanned_path}"
187
+ if manifest is not None:
188
+ header += f"\nManifest: {manifest}"
189
+ if suppressed:
190
+ header += f"\n{suppressed} finding(s) suppressed by ignore rules or inline comments."
191
+ if hidden:
192
+ header += f"\n{hidden} finding(s) below --min-severity {min_severity} not shown."
193
+ if not findings:
194
+ lines = [
195
+ header,
196
+ "No findings from the enabled checks. This does not mean the project is secure.",
197
+ ]
198
+ if dependency_manifests is not None:
199
+ lines.append(
200
+ "Dependency audit: "
201
+ + (
202
+ f"completed ({dependency_manifests} requirements manifest(s)); no known advisories found."
203
+ if dependency_manifests
204
+ else "not run; no supported requirements*.txt manifest found."
205
+ )
206
+ )
207
+ lines.append(
208
+ "The dependency audit sends package names and versions to the configured vulnerability service; it does not install packages."
209
+ )
210
+ lines.extend(["", *coverage_lines(findings)])
211
+ return "\n".join(lines)
212
+ lines = [header, f"Findings: {len(findings)}", ""]
213
+ if dependency_manifests is not None:
214
+ lines.insert(
215
+ 2,
216
+ "Dependency audit: "
217
+ + (
218
+ f"completed ({dependency_manifests} requirements manifest(s))."
219
+ if dependency_manifests
220
+ else "not run; no supported requirements*.txt manifest found."
221
+ ),
222
+ )
223
+ lines.insert(
224
+ 3,
225
+ "Dependency audit sends package names and versions to the configured advisory service; no packages are installed.",
226
+ )
227
+ ordered = sorted(findings, key=severity_sort_key)
228
+ for finding in ordered:
229
+ lines.extend(
230
+ [
231
+ f"[{finding.severity.upper()}] {finding.rule_id} {finding.title}",
232
+ f" {finding.path}:{finding.line}:{finding.column}",
233
+ f" {finding.message}",
234
+ f" OWASP Agentic: {owasp_labels(finding)} | confidence: {finding.confidence}",
235
+ f" Evidence: {finding.evidence}",
236
+ "",
237
+ ]
238
+ )
239
+ lines.extend([*coverage_lines(findings), ""])
240
+ lines.append("Selected static checks only; findings require human review.")
241
+ return "\n".join(lines)