-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTML.py
More file actions
225 lines (197 loc) · 7.97 KB
/
HTML.py
File metadata and controls
225 lines (197 loc) · 7.97 KB
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""Generates HTML reports for aggregated SAST analysis results."""
import io
from hashlib import sha256
from pathlib import Path
from codesectools.sasts.all.report import Report
from codesectools.utils import group_successive
class HTMLReport(Report):
"""Generate interactive HTML reports for SAST analysis results.
Attributes:
TEMPLATE (str): The HTML template used for report generation.
project (str): The name of the project.
all_sast (AllSAST): The AllSAST manager instance.
report_dir (Path): The directory where reports are saved.
result (AllSASTAnalysisResult): The parsed analysis results.
report_data (dict): The data prepared for rendering the report.
"""
format = "HTML"
TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
{stylesheet}
body {{
color: {foreground};
background-color: {background};
font-family: Menlo, 'DejaVu Sans Mono', consolas, 'Courier New', monospace;
}}
.tippy-box {{
background-color: white;
color: black;
}}
img {{
display: block;
margin: auto;
border: solid black 1px;
}}
#top {{
position: fixed;
bottom: 20px;
right: 30px;
background-color: white;
padding: 10px;
border: solid black 5px;
}}
</style>
</head>
<body>
<a href="./home.html"><h1>CodeSecTools All SAST Tools Report</h1></a>
<h3>SAST Tools used: [sasts]</h3>
<h2>[name]</h2>
<pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><code style="font-family:inherit">{code}</code></pre>
<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>
<script>[tippy_calls]</script>
<a href="#" id="top">^</a>
</body>
</html>
"""
def generate_single_defect(self, defect_file: dict) -> str:
"""Generate the HTML report for a single file with defects."""
from rich.console import Console
from rich.style import Style
from rich.syntax import Syntax
from rich.table import Table
from rich.text import Text
file_page = Console(record=True, file=io.StringIO())
file_page.print(f"Score: {defect_file['score']:.2f}")
# Defect table
defect_table = Table(title="", show_lines=True)
defect_table.add_column("Location", justify="center")
defect_table.add_column("SAST", justify="center")
defect_table.add_column("CWE", justify="center")
defect_table.add_column("Message")
rows = []
for defect in defect_file["defects"]:
groups = group_successive(defect.lines)
if groups:
for group in groups:
start, end = group[0], group[-1]
shortcut = Text(f"{start}", style=Style(link=f"#L{start}"))
cwe_link = (
Text(
f"CWE-{defect.cwe.id}",
style=Style(
link=f"https://cwe.mitre.org/data/definitions/{defect.cwe.id}.html"
),
)
if defect.cwe.id != -1
else "None"
)
rows.append(
(start, shortcut, defect.sast_name, cwe_link, defect.message)
)
else:
cwe_link = (
Text(
f"CWE-{defect.cwe.id}",
style=Style(
link=f"https://cwe.mitre.org/data/definitions/{defect.cwe.id}.html"
),
)
if defect.cwe.id != -1
else "None"
)
rows.append(
(float("inf"), "None", defect.sast_name, cwe_link, defect.message)
)
for row in sorted(rows, key=lambda r: r[0]):
defect_table.add_row(*row[1:])
file_page.print(defect_table)
# Syntax
if not Path(defect_file["source_path"]).is_file():
tippy_calls = ""
print(f"Source file {defect_file['source_path']} not found, skipping it...")
else:
syntax = Syntax.from_path(defect_file["source_path"], line_numbers=True)
tooltips = {}
highlights = {}
for location in defect_file["locations"]:
sast, cwe, message, (start, end) = location
for i in range(start, end + 1):
text = (
f"<b>{sast}</b>: <i>{message} (CWE-{cwe.id})</i>"
if cwe.id != -1
else f"<b>{sast}</b>: <i>{message}</i>"
)
if highlights.get(i):
highlights[i].add(text)
else:
highlights[i] = {text}
for line, texts in highlights.items():
element_id = f"L{line}"
bgcolor = "red" if len(texts) > 1 else "yellow"
syntax.stylize_range(
Style(bgcolor=bgcolor, link=f"HACK{element_id}"),
start=(line, 0),
end=(line + 1, 0),
)
tooltips[element_id] = "<hr>".join(text for text in texts)
tippy_calls = ""
for element_id, content in tooltips.items():
tippy_calls += f"""tippy('#{element_id}', {{ content: `{content.replace("`", "\\`")}`, allowHTML: true, interactive: true }});\n"""
file_page.print(syntax)
html_content = file_page.export_html(code_format=self.TEMPLATE)
html_content = html_content.replace('href="HACK', 'id="')
html_content = html_content.replace(
"[name]",
str(
Path(defect_file["source_path"]).relative_to(self.result.source_path) # ty:ignore[no-matching-overload]
),
)
html_content = html_content.replace("[tippy_calls]", tippy_calls)
return html_content
def generate(self) -> None:
"""Generate the HTML report."""
from rich.console import Console
from rich.progress import track
from rich.style import Style
from rich.table import Table
from rich.text import Text
self.TEMPLATE = self.TEMPLATE.replace(
"[sasts]", ", ".join(sast_name for sast_name in self.result.sast_names)
)
home_page = Console(record=True, file=io.StringIO())
main_table = Table(title="")
main_table.add_column("Score", justify="center")
main_table.add_column("Files")
for defect_file in track(
self.report_data.values(),
description="Generating report for source file with defects...",
):
html_content = self.generate_single_defect(defect_file)
file_report_name = (
f"{sha256(defect_file['source_path'].encode()).hexdigest()}.html"
)
file_report_redirect = Text(
str(
Path(defect_file["source_path"]).relative_to(
self.result.source_path
) # ty:ignore[no-matching-overload]
),
style=Style(link=file_report_name),
)
report_file = self.report_dir / file_report_name
report_file.write_text(html_content)
main_table.add_row(
Text(f"{defect_file['score']:.2f}"), file_report_redirect
)
home_page.print(main_table)
html_content = home_page.export_html(code_format=self.TEMPLATE)
html_content = html_content.replace(
"[name]", f"Project: {self.result.source_path}"
)
report_home_file = self.report_dir / "home.html"
report_home_file.write_text(html_content)