-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathrest_api.py
More file actions
273 lines (224 loc) · 9 KB
/
rest_api.py
File metadata and controls
273 lines (224 loc) · 9 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
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
"""Definition of the routes for gemini server."""
import flask
import requests
from flask import Flask, request
from flask_cors import CORS
from utils import DatabaseIngestion, scan_repo, validate_request_data,\
retrieve_worker_result, alert_user
from f8a_worker.setup_celery import init_selinon
from auth import login_required, init_auth_sa_token
from exceptions import HTTPError
app = Flask(__name__)
CORS(app)
init_selinon()
SERVICE_TOKEN = 'token'
try:
SERVICE_TOKEN = init_auth_sa_token()
except requests.exceptions.RequestException as e:
print('Unable to set authentication token for internal service calls. {}'
.format(e))
@app.route('/api/v1/readiness')
def readiness():
"""Readiness probe."""
return flask.jsonify({}), 200
@app.route('/api/v1/liveness')
def liveness():
"""Liveness probe."""
return flask.jsonify({}), 200
@app.route('/api/v1/register', methods=['POST'])
@login_required
def register():
"""
Endpoint for registering a new repository.
Registers new information and
updates existing repo information.
"""
resp_dict = {
"success": True,
"summary": ""
}
input_json = request.get_json()
if request.content_type != 'application/json':
resp_dict["success"] = False
resp_dict["summary"] = "Set content type to application/json"
return flask.jsonify(resp_dict), 400
validated_data = validate_request_data(input_json)
if not validated_data[0]:
resp_dict["success"] = False
resp_dict["summary"] = validated_data[1]
return flask.jsonify(resp_dict), 404
try:
repo_info = DatabaseIngestion.get_info(input_json.get('git-url'))
if repo_info.get('is_valid'):
data = repo_info.get('data')
# Update the record to reflect new git_sha if any.
DatabaseIngestion.update_data(input_json)
else:
try:
# First time ingestion
DatabaseIngestion.store_record(input_json)
status = scan_repo(input_json, SERVICE_TOKEN)
if status is not True:
resp_dict["success"] = False
resp_dict["summary"] = "New Repo Scan Initialization Failure"
return flask.jsonify(resp_dict), 500
resp_dict["summary"] = "Repository {} with commit-hash {} " \
"has been successfully registered. " \
"Please check back for report after some time." \
.format(input_json.get('git-url'),
input_json.get('git-sha'))
return flask.jsonify(resp_dict), 200
except Exception as e:
resp_dict["success"] = False
resp_dict["summary"] = "Database Ingestion Failure due to: {}" \
.format(e)
return flask.jsonify(resp_dict), 500
except Exception as e:
resp_dict["success"] = False
resp_dict["summary"] = "Cannot get information about repository {} " \
"due to {}" \
.format(input_json.get('git-url'), e)
return flask.jsonify(resp_dict), 500
# Scan the repository irrespective of report is available or not.
status = scan_repo(input_json)
if status is not True:
resp_dict["success"] = False
resp_dict["summary"] = "New Repo Scan Initialization Failure"
return flask.jsonify(resp_dict), 500
resp_dict.update({
"summary": "Repository {} was already registered, but no report for "
"commit-hash {} was found. Please check back later."
.format(input_json.get('git-url'), input_json.get('git-sha')),
"last_scanned_at": data['last_scanned_at'],
"last_scan_report": None
})
return flask.jsonify(resp_dict), 200
@app.route('/api/v1/report')
@login_required
def report():
"""Endpoint for fetching generated scan report."""
repo = request.args.get('git-url')
sha = request.args.get('git-sha')
response = dict()
result = retrieve_worker_result(sha, "ReportGenerationTask")
if result:
task_result = result.get('task_result')
if task_result:
response.update({
"git_url": repo,
"git_sha": sha,
"scanned_at": task_result.get("scanned_at"),
"dependencies": task_result.get("dependencies")
})
return flask.jsonify(response), 200
else:
response.update({
"status": "failure",
"message": "Failed to retrieve scan report"
})
return flask.jsonify(response), 404
else:
response.update({
"status": "failure",
"message": "No report found for this repository"
})
return flask.jsonify(response), 404
@app.route('/api/v1/user-repo/scan', methods=['POST'])
@login_required
def user_repo_scan():
"""
Endpoint for scanning an OSIO user's repository.
Runs a scan to find out security vulnerability in a user's repository
"""
resp_dict = {
"status": "success",
"summary": ""
}
if request.content_type != 'application/json':
resp_dict["status"] = "failure"
resp_dict["summary"] = "Set content type to application/json"
return flask.jsonify(resp_dict), 400
input_json = request.get_json()
# Return a dummy response for the endpoint while the development is in progress
if 'dev' not in input_json:
return flask.jsonify({'summary': 'Repository scan initiated'}), 200
validate_string = "{} cannot be empty"
if 'git-url' not in input_json:
validate_string = validate_string.format("git-url")
return False, validate_string
# Call the worker flow to run a user repository scan asynchronously
status = alert_user(input_json, SERVICE_TOKEN)
if status is not True:
resp_dict["status"] = "failure"
resp_dict["summary"] = "Scan initialization failure"
return flask.jsonify(resp_dict), 500
resp_dict.update({
"summary": "Report for {} is being generated in the background. You will "
"be notified via your preferred openshift.io notification mechanism "
"on its completion.".format(input_json.get('git-url')),
})
return flask.jsonify(resp_dict), 200
@app.route('/api/v1/user-repo/notify', methods=['POST'])
@login_required
def notify_user():
"""
Endpoint for notifying security vulnerability in a repository.
Runs a scan to find out security vulnerability in a user's repository
"""
resp_dict = {
"status": "success",
"summary": ""
}
if request.content_type != 'application/json':
resp_dict["status"] = "failure"
resp_dict["summary"] = "Set content type to application/json"
return flask.jsonify(resp_dict), 400
input_json = request.get_json()
# Return a dummy response for the endpoint while the development is in progress
if 'dev' not in input_json:
return flask.jsonify({'summary': 'Notification service called'}), 200
validate_string = "{} cannot be empty"
if 'epv_list' not in input_json:
resp_dict["status"] = "failure"
resp_dict["summary"] = "Required parameter 'epv_list' is missing " \
"in the request"
return flask.jsonify(resp_dict), 400
# Call the worker flow to run a user repository scan asynchronously
status = alert_user(input_json, SERVICE_TOKEN, epv_list=input_json['epv_list'])
if status is not True:
resp_dict["status"] = "failure"
resp_dict["summary"] = "Scan initialization failure"
return flask.jsonify(resp_dict), 500
resp_dict.update({
"summary": "Report for {} is being generated in the background. You will "
"be notified via your preferred openshift.io notification mechanism "
"on its completion.".format(input_json.get('git-url')),
})
return flask.jsonify(resp_dict), 200
@app.route('/api/v1/user-repo/drop', methods=['POST'])
@login_required
def drop():
"""
Endpoint to stop monitoring OSIO users' repository.
Runs a scan to find out security vulnerability in a user's repository
"""
resp_dict = {
"status": "success",
"summary": ""
}
if request.content_type != 'application/json':
resp_dict["status"] = "failure"
resp_dict["summary"] = "Set content type to application/json"
return flask.jsonify(resp_dict), 400
input_json = request.get_json()
# Return a dummy response for the endpoint while the development is in progress
if 'dev' not in input_json:
return flask.jsonify({'summary': 'Repository scan unsubscribed'}), 200
@app.errorhandler(HTTPError)
def handle_error(e): # pragma: no cover
"""Handle http error response."""
return flask.jsonify({
"error": e.error
}), e.status_code
if __name__ == "__main__": # pragma: no cover
app.run()