-
Notifications
You must be signed in to change notification settings - Fork 2
/
snyk-charts.py
212 lines (170 loc) · 6.26 KB
/
snyk-charts.py
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
import os
import requests
import time
import json
import pandas as pd
from getpass import getpass
import plotly.graph_objects as go
import pyfiglet
from simple_term_menu import TerminalMenu
from rich import print as rprint
def main():
if not os.path.exists("images"):
os.mkdir("images")
with open("parameters.txt") as f:
data = {}
for line in f:
key, value = line.strip().split("=")
data[key] = value
f.close()
orgId = data['ORGID']
apiToken = data['TOKEN']
startDate = data['START_DATE']
endDate = data['END_DATE']
perPage = data['ISSUE_PER_PAGE']
if (len(perPage)==0 or int(perPage) > 1000):
perPage = 100
title = pyfiglet.figlet_format("Snyk Charts", font="slant")
rprint("[bold magenta]" + title)
rprint("[cyan]GENERATE INTERACTIVE CHARTS DERIVED FROM THE SNYK API[/cyan] \n \n")
options = ["Issues over time", "Trending Issues"]
cursor_style = ("fg_purple", "bold")
terminal_menu = TerminalMenu(options, title="Please select your desired chart: \n", menu_cursor_style=cursor_style)
menu_entry_index = terminal_menu.show()
print("Loading ", end="")
# this logic could be turned into a function once chart options increase
if (menu_entry_index == 0):
endpoint = "https://snyk.io/api/v1/reporting/counts/issues?from=" + startDate + "&to=" + endDate + "&groupBy=severity"
else:
endpoint = "https://snyk.io/api/v1/reporting/issues/?from=" + startDate + "&to=" + endDate + "&page=1&perPage=" + str(perPage) + "&sortBy=introducedDate&order=asc&groupBy=issue"
response = api_request(apiToken, orgId, endpoint)
if (menu_entry_index == 0):
generate_issues_over_time(response)
else:
generate_issues_trending(response, startDate, endDate)
def generate_issues_over_time(obj):
time_period = []
low_count = []
medium_count = []
high_count = []
critical_count = []
print("\rLoading...", end="")
while obj['results']:
result = obj['results'].pop()
date = result['day']
time_period.append(date)
severity = result['severity']
critical_count.append(severity['critical'])
high_count.append(severity['high'])
medium_count.append(severity['medium'])
low_count.append(severity['low'])
fig = go.Figure()
# Create and style traces
fig.add_trace(go.Scatter(x=time_period, y=low_count, name='Low',
line=dict(color='gray', width=4)))
fig.add_trace(go.Scatter(x=time_period, y=medium_count, name = 'Medium',
line=dict(color='burlywood', width=4)))
fig.add_trace(go.Scatter(x=time_period, y=high_count, name = 'High',
line=dict(color='coral', width=4)))
fig.add_trace(go.Scatter(x=time_period, y=critical_count, name = 'Critical',
line=dict(color='crimson', width=4)))
# Edit the layout of the chart
fig.update_layout(title='Issues over time (Open Source)',
xaxis_title='Month',
yaxis_title='Issues')
print("Chart coming out of the oven!")
save_chart(fig, 0)
fig.show()
def generate_issues_trending(obj, startDate, endDate):
issueList = []
while obj['results']:
result = obj['results'].pop()
issue = result['issue']
issueTitle = issue['title']
issueList.append(issueTitle)
df = pd.DataFrame(issueList, columns=["Issues"])
issuesLabel = df["Issues"].value_counts().keys().tolist()
issuesCount = df["Issues"].value_counts().tolist()
fig = go.Figure([go.Bar(x=issuesLabel, y=issuesCount)])
fig.update_layout(title="Trending issues " + startDate + " - " + endDate + " (Open Source)")
save_chart(fig, 1)
fig.show()
def save_chart(obj, chartType):
options = ["No", "Yes"]
cursor_style = ("fg_purple", "bold")
terminal_menu = TerminalMenu(options, title="Would you like to save a copy of this chart now ? \n", menu_cursor_style=cursor_style)
menu_entry_index = terminal_menu.show()
# Save chart locally to images folder with unique name
if (menu_entry_index == 1):
ts = str(time.time())
ts = ts.replace(".","")
fileType = ["HTML", "PNG"]
cursor_style = ("fg_purple", "bold")
terminal_menu = TerminalMenu(fileType, title="Please select your file type \n", menu_cursor_style=cursor_style)
menu_entry_index = terminal_menu.show()
match chartType:
case 0: #issues over time
fileName = ts + "_issues_over_time_chart"
case 1: #trending issues
fileName = ts + "_trending_issues_chart"
if (menu_entry_index == 0):
obj.write_html("images/" + fileName + ".html")
else:
obj.write_image("images/" + fileName + ".png")
def api_request(apiToken, orgId, endpoint):
headers = {
'Content-Type': 'application/json',
'Authorization': 'token ' + apiToken
}
print("\rLoading. ", end="")
values = json.dumps({
"filters": {
"orgs": [orgId],
"severity": [
"critical",
"high",
"medium",
"low"
],
"types": [
"vuln"
],
"languages": [
"node",
"javascript",
"ruby",
"java",
"scala",
"python",
"golang",
"php",
"dotnet",
"swift-objective-c",
"elixir",
"docker",
"linux",
"dockerfile",
"terraform",
"kubernetes",
"helm",
"cloudformation"
],
"projects": [],
"ignored": False,
"patched": False,
"fixable": False,
"isUpgradable": False,
"isPatchable": False,
"isPinnable": False,
"priorityScore": {
"min": 0,
"max": 1000
}
}
}, indent=4)
print("\rLoading.. \n", end="")
request = requests.request("POST", endpoint, headers=headers, data=values)
response = request.json()
return response
if __name__ == "__main__":
main()