-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrack.py
258 lines (228 loc) · 8.13 KB
/
track.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
import requests
from datetime import datetime
import json
import os
import logging
import threading
import sys
import pymongo
import config
MINIMUM_DAYS = 7
alerted_repos = []
def get_outside_collabs(organization, headers):
baseurl ="https://api.github.com/orgs/{}/outside_collaborators".format(organization)
users = []
i = 1
while True:
r = requests.get("{}?per_page=100&page={}".format(baseurl, i), headers=headers)
if (r.status_code != 200):
raise Exception(r.text)
data = json.loads(r.text)
for user in data:
users.append(user)
if len(data) == 0:
break
i += 1
return users
def get_user_list(organization, headers):
baseurl ="https://api.github.com/orgs/{}/members".format(organization)
users = []
i = 1
while True:
r = requests.get("{}?per_page=100&page={}".format(baseurl, i), headers=headers)
if (r.status_code != 200):
raise Exception(r.text)
data = json.loads(r.text)
for user in data:
users.append(user)
if len(data) == 0:
break
i += 1
return users
def run_gquery(query, headers):
request = requests.post('https://api.github.com/graphql', json={'query': query}, headers=headers)
if request.status_code == 200:
return request.json()
else:
raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))
def get_git_org_members_emails(organization):
query1 = """{{
organization(login: "{org}") {{
name
url
membersWithRole(first: 100) {{
nodes {{
login
organizationVerifiedDomainEmails(login: "{org}")
}}
pageInfo {{
hasNextPage
endCursor
}}
}}
}}
}}
"""
query2 = """{{
organization(login: "{org}") {{
name
url
membersWithRole(first: 100, after: "{cursor}") {{
nodes {{
login
organizationVerifiedDomainEmails(login: "{org}")
}}
pageInfo {{
hasNextPage
endCursor
}}
}}
}}
}}
"""
cursor = ""
members = []
while True:
if (cursor == ""):
# First run
result = run_gquery(query1.format(org=organization))
else:
result = run_gquery(query2.format(org=organization, cursor=cursor))
cursor = result['data']['organization']['membersWithRole']['pageInfo']['endCursor']
for member in result['data']['organization']['membersWithRole']['nodes']:
try:
email = member['organizationVerifiedDomainEmails'][0]
except:
email = ""
members.append(
{
"name": member['login'],
"email": email
}
)
if (False == result['data']['organization']['membersWithRole']['pageInfo']['hasNextPage']):
break
return members
def scan_repos_for_user(user_data):
results = []
for repo in user_data:
# if forked, we don't care
if (True == repo['fork']):
continue
# if over MINIMUM_DAYS days old (or more than once), we don't care
created_at = datetime.strptime(repo['created_at'], "%Y-%m-%dT%H:%M:%SZ")
delta = datetime.now()-created_at
if (delta.days <= MINIMUM_DAYS):
if (repo['html_url'] in alerted_repos):
continue
alerted_repos.append(repo['html_url'])
finding = {
'name': repo['owner']['login'],
'repo_url': repo['html_url'],
'days_old': delta.days
}
results.append(finding)
return results
def scan_users_directory(organization):
results = []
directory = 'temp/{}/users'.format(organization)
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
if os.path.isfile(f):
with open(f, 'r') as file:
data = json.loads(file.read())
if (len(data) > 0):
results += scan_repos_for_user(data)
return results
def download_users_list(organization, users, headers):
threads = list()
total = len(users)
index = 0
for user in users:
file = "temp/{}/users/{}.json".format(organization, user['login'])
x = threading.Thread(target=thread_download_user, args=(file, user['repos_url'],index,total,headers,))
threads.append(x)
x.start()
index += 1
for file, thread in enumerate(threads):
thread.join()
maxthreads = 5
sema = threading.Semaphore(value=maxthreads)
def thread_download_user(filepath, repos_url, index, total, headers):
sema.acquire()
r = requests.get(repos_url, headers=headers)
if (r.status_code != 200):
raise Exception(r.text)
f = open(filepath, "w")
f.write(json.dumps(json.loads(r.text), indent=4))
f.close
sema.release()
def send_notifications_to_slack(notifications, webhookurl):
for item in notifications:
repo_name = item['repo_url'].rsplit('/', 1)[-1]
payload = {
"blocks": [{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "New public repo found on git user *{}* <{}|{}> ({} days old)".format(item['name'], item['repo_url'], repo_name, item['days_old'])
}}]
}
r = requests.post(webhookurl, data=json.dumps(payload))
if (r.status_code != 200):
raise Exception("Error while sending slack notification: {}".format(r.text))
def add_notifications_to_db(organization, notifications):
myclient = pymongo.MongoClient(config.get_mongo_connection_string())
mydb = myclient[config.get_mongo_db()]
mycol = mydb["notifications"]
for item in notifications:
# check if item already exists:
myquery = { "gitorg": organization, "gitusername": item['name'], "repo_url": item['repo_url'] }
x = mycol.find_one(myquery)
if x is not None:
continue
# doesn't exist, add as new
mydict = {
"gitorg": organization,
"gitusername": item['name'],
"repo_url": item['repo_url'],
"days_old": item['days_old'],
"acknowledged": False,
"createdAt": datetime.utcnow(),
"updatedAt": datetime.utcnow()
}
x = mycol.insert_one(mydict)
def run(organization, auth_token, slackwebhook):
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
headers = {
'Accept': 'application/vnd.github.v3+json',
'Authorization': 'Bearer {token}'
}
headers['Authorization'] = headers['Authorization'].format(token=auth_token)
dirs = "temp/{}/users/".format(organization)
isExist = os.path.exists(dirs)
if not isExist:
os.makedirs("temp/")
os.makedirs("temp/{}".format(organization))
os.makedirs("temp/{}/users/".format(organization))
users = get_user_list(organization, headers)
logging.info("Downloading {} users".format(len(users)))
download_users_list(organization, users, headers)
notifications = (scan_users_directory(organization))
logging.info("Found {} notifications".format(len(notifications)))
if (len(notifications) == 0):
return
if slackwebhook is not None:
logging.info("Sending to slack webhook")
send_notifications_to_slack(notifications, slackwebhook)
if config.get_mongo_state():
logging.info("Sending to mongo collection")
add_notifications_to_db(organization, notifications)
def main(argv):
run(argv[1], argv[2], argv[3])
#TODO: send slack / email to user via his personal info
#print(get_git_org_members_emails())
if __name__ == "__main__":
main(sys.argv)