-
Notifications
You must be signed in to change notification settings - Fork 3
/
fetch-alerts.py
274 lines (242 loc) · 8.51 KB
/
fetch-alerts.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport
import json
from github import Github
import psycopg2
from datetime import date, datetime
import os
db_user = os.environ["DB_USER"]
db_password = os.environ["DB_PASSWORD"]
db_host = os.environ["DB_HOST"]
host = os.environ["GH_HOST"]
gh_token = os.environ["GH_TOKEN"]
connection = psycopg2.connect(user=db_user,
password=db_password,
host=db_host,
port="5432",
database="dependabot")
def initialize_db():
try:
cursor = connection.cursor()
postgres_create_table = """
create table if not exists dependabot_alerts(
snapshot timestamp,
gh_repo varchar(100),
gh_org varchar(30),
created_at timestamp,
fixed_at timestamp,
alert_number int,
state varchar(10),
dismissed_at timestamp,
dismiss_reason varchar(300),
dismisser varchar(30),
vuln_ghsa_id varchar(30),
vuln_severity varchar(15),
vuln_summary text,
vuln_package varchar(100),
fix_pr_number int,
fix_pr_title text,
fix_merged_at timestamp
);
"""
cursor.execute(postgres_create_table)
connection.commit()
count = cursor.rowcount
except (Exception, psycopg2.Error) as error:
print("Failed to initialize dependabot_alerts table: ", error)
def insert_into_db(alert, gh_org, gh_repo):
try:
snapshot_date = date.today()
snapshot_timestamp = datetime.strptime(
str(snapshot_date), "%Y-%m-%d").strftime("%Y-%m-%dT00:00:00Z")
repo = gh_org + "/" + gh_repo
org = gh_org
created_at = alert.get("createdAt")
fixed_at = alert.get("fixedAt")
alert_number = alert.get("number")
state = alert.get("state")
dismissed_at = alert.get("dismissedAt")
dismiss_reason = alert.get("dismissReason")
dismisser = None
if alert.get("dismisser") is not None:
dismisser = alert.get("dismisser").get("login")
vuln_ghsa_id = alert.get("securityVulnerability").get("advisory").get("ghsaId")
vuln_severity = alert.get("securityVulnerability").get("severity")
vuln_summary = alert.get("securityVulnerability").get("advisory").get("summary")
vuln_package = alert.get("securityVulnerability").get("package").get("name")
fix_pr_number = None
fix_pr_title = None
fix_merged_at = None
if alert.get("dependabotUpdate") is not None:
if alert.get("dependabotUpdate").get("pullRequest") is not None:
fix_pr_number = alert.get("dependabotUpdate").get("pullRequest").get("number")
fix_pr_title = alert.get("dependabotUpdate").get("pullRequest").get("title")
fix_merged_at = alert.get("dependabotUpdate").get("pullRequest").get("mergedAt")
if state == "FIXED" or state == "DISMISSED":
tmp_now = datetime.strptime(
str(snapshot_date), "%Y-%m-%d")
if fixed_at is not None:
tmp_fixed_at = datetime.strptime(fixed_at, "%Y-%m-%dT%H:%M:%SZ")
if tmp_fixed_at >= tmp_now:
state = "OPEN"
if dismissed_at is not None:
tmp_dismissed_at = datetime.strptime(dismissed_at, "%Y-%m-%dT%H:%M:%SZ")
if tmp_dismissed_at >= tmp_now:
state = "OPEN"
insert_query = """
insert into dependabot_alerts (
snapshot,
gh_repo,
gh_org,
created_at,
fixed_at,
alert_number,
state,
dismissed_at,
dismiss_reason,
dismisser,
vuln_ghsa_id,
vuln_severity,
vuln_summary,
vuln_package,
fix_pr_number,
fix_pr_title,
fix_merged_at
) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
"""
db_values = (snapshot_timestamp, repo, org, created_at, fixed_at, alert_number, state, dismissed_at, dismiss_reason,
dismisser, vuln_ghsa_id, vuln_severity, vuln_summary, vuln_package, fix_pr_number, fix_pr_title, fix_merged_at)
cursor = connection.cursor()
cursor.execute(insert_query, db_values)
connection.commit()
except (Exception, psycopg2.Error) as error:
print("Error when inserting into table: ", error)
print("DEBUG: ", str(alert))
def get_repos(host, gh_token):
g = Github(base_url=host + "/api/v3", login_or_token=gh_token)
repos = []
# Add orgs that you need to ignore
blacklisted_orgs = ['test-org']
for org in g.get_organizations():
if org.login not in blacklisted_orgs:
for repo in org.get_repos():
if not repo.archived:
repos.append(repo.full_name)
return repos
def get_alerts(host, gh_token, gh_org, gh_repo):
# Handle pagination
headers = {
"Authorization": "Bearer " + gh_token,
"Accept": "application/vnd.github.v4.idl"
}
# Select your transport with a defined url endpoint
transport = AIOHTTPTransport(url=host+"/api/graphql", headers=headers)
# Create a GraphQL client using the defined transport
client = Client(transport=transport, fetch_schema_from_transport=True)
# Provide a GraphQL query
query = gql(
"""
{
repository(name: "%s", owner: "%s") {
vulnerabilityAlerts(first:100) {
pageInfo {
startCursor
hasNextPage
endCursor
}
nodes {
createdAt
fixedAt
number
dependabotUpdate {
pullRequest {
number
title
mergedAt
}
}
state
dismissedAt
dismisser {
login
}
dismissReason
securityVulnerability {
severity
advisory {
ghsaId
summary
}
package {
name
}
}
}
}
}
}
""" % (gh_repo, gh_org)
)
while True:
# Execute the query on the transport
result = client.execute(query)
for alert in result.get("repository").get("vulnerabilityAlerts").get("nodes"):
print(json.dumps(alert))
insert_into_db(alert, gh_org, gh_repo)
nextpage = result.get("repository").get(
"vulnerabilityAlerts").get("pageInfo").get("hasNextPage")
if not nextpage:
break
endcursor = result.get("repository").get(
"vulnerabilityAlerts").get("pageInfo").get("endCursor")
query = gql(
"""
{
repository(name: "%s", owner: "%s") {
vulnerabilityAlerts(first:100, after:"%s") {
pageInfo {
startCursor
hasNextPage
endCursor
}
nodes {
createdAt
fixedAt
number
dependabotUpdate {
pullRequest {
number
title
mergedAt
}
}
state
dismissedAt
dismisser {
login
}
dismissReason
securityVulnerability {
severity
advisory {
ghsaId
summary
}
package {
name
}
}
}
}
}
}
""" % (gh_repo, gh_org, endcursor)
)
return []
initialize_db()
repos = get_repos(host=host, gh_token=gh_token)
for repo in repos:
print("[+] Analyzing " + repo)
org = repo.split("/")[0]
repo_name = repo.split("/")[1]
get_alerts(host, gh_token, org, repo_name)