blob: 0f3cb4061ca2db8ec7c615f536262212f0a68a05 [file] [log] [blame]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +03001#!groovy
2
Ivan Udovichenko314a0732020-04-13 22:47:26 +03003package com.mirantis.mk
4
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +03005import groovy.json.JsonSlurper
Ivan Udovichenko6c337562020-08-06 16:22:26 +03006import groovy.json.JsonOutput
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +03007
8def callREST (String uri, String auth,
Ivan Udovichenko45252252020-04-14 22:45:53 +03009 String method = 'GET', String message = null) {
10 String authEnc = auth.bytes.encodeBase64()
11 def req = new URL(uri).openConnection()
12 req.setRequestMethod(method)
13 req.setRequestProperty('Content-Type', 'application/json')
14 req.setRequestProperty('Authorization', "Basic ${authEnc}")
15 if (message) {
16 req.setDoOutput(true)
17 req.getOutputStream().write(message.getBytes('UTF-8'))
18 }
19 Integer responseCode = req.getResponseCode()
20 String responseText = ''
21 if (responseCode == 200 || responseCode == 201) {
22 responseText = req.getInputStream().getText()
23 }
24 req = null
25 return [ 'responseCode': responseCode, 'responseText': responseText ]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030026}
27
28def getTeam (String image = '') {
29 def team_assignee = ''
30 switch(image) {
31 case ~/^(tungsten|tungsten-operator)\/.*$/:
32 team_assignee = 'OpenContrail'
33 break
Ivan Udovichenko8c78c352020-12-14 22:39:47 +030034 case ~/^(bm|general)\/.*$/:
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030035 team_assignee = 'BM/OS (KaaS BM)'
36 break
37 case ~/^openstack\/.*$/:
38 team_assignee = 'OpenStack hardening'
39 break
40 case ~/^stacklight\/.*$/:
41 team_assignee = 'Stacklight LMA'
42 break
43 case ~/^ceph\/.*$/:
44 team_assignee = 'Storage'
45 break
Ivan Udovichenko5d755da2021-08-09 14:58:56 +030046 case ~/^(core|iam|lcm)\/.*$/:
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030047 team_assignee = 'KaaS'
48 break
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030049 default:
50 team_assignee = 'Release Engineering'
51 break
52 }
53
54 return team_assignee
55}
56
57def updateDictionary (String jira_issue_key, Map dict, String uri, String auth, String jira_user_id) {
58 def response = callREST("${uri}/${jira_issue_key}", auth)
59 if ( response['responseCode'] == 200 ) {
60 def issueJSON = new JsonSlurper().parseText(response["responseText"])
61 if (issueJSON.containsKey('fields')) {
62 if (!dict.containsKey(jira_issue_key)) {
63 dict[jira_issue_key] = [
64 summary : '',
65 description: '',
66 comments: []
67 ]
68 }
69 if (issueJSON['fields'].containsKey('summary')){
70 dict[jira_issue_key].summary = issueJSON['fields']['summary']
71 }
72 if (issueJSON['fields'].containsKey('description')) {
73 dict[jira_issue_key].description = issueJSON['fields']['description']
74 }
75 if (issueJSON['fields'].containsKey('comment') && issueJSON['fields']['comment']['comments']) {
76 issueJSON['fields']['comment']['comments'].each {
77 if (it.containsKey('author') && it['author'].containsKey('accountId') && it['author']['accountId'] == jira_user_id) {
78 dict[jira_issue_key]['comments'].add(it['body'])
79 }
80 }
81 }
82 }
83 }
84 return dict
85}
86
87def cacheLookUp(Map dict, String image_short_name, String image_full_name = '', String cve_id = '' ) {
88 def found_key = ['','']
89 if (!found_key[0] && dict && image_short_name) {
90 dict.each { issue_key_name ->
91 if (!found_key[0]) {
Ivan Udovichenkobfe3aca2020-12-17 21:48:50 +030092 def s = dict[issue_key_name.key]['summary'] =~ /(?<=[\/\[])${image_short_name}(?=\])/
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030093 if (s) {
94 if (image_full_name) {
95 def d = dict[issue_key_name.key]['description'] =~ /(?m)\b${image_full_name}\b/
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030096 if (d) {
97 found_key = [issue_key_name.key,'']
98 } else {
99 if (dict[issue_key_name.key]['comments']) {
100 def comment_match = false
101 dict[issue_key_name.key]['comments'].each{ comment ->
102 if (!comment_match) {
103 def c = comment =~ /(?m)\b${image_full_name}\b/
104 if (c) {
105 comment_match = true
106 }
107 }
108 }
109 if (!comment_match) {
110 found_key = [issue_key_name.key,'na']
111 } else {
112 found_key = [issue_key_name.key,'']
113 }
114 } else {
115 found_key = [issue_key_name.key,'na']
116 }
117 }
118 }
119 }
120 }
121 }
122 }
123 return found_key
124}
125
Ivan Udovichenko67398552020-12-25 20:13:35 +0300126def getLatestAffectedVersion(cred, productName, defaultJiraAffectedVersion = 'Backlog') {
127 def filterName = ''
128 if (productName == 'mosk') {
129 filterName = 'MOSK'
130 } else if (productName == 'kaas') {
131 filterName = 'KaaS'
132 } else {
133 return defaultJiraAffectedVersion
134 }
135
Ivan Udovichenko4c08b8d2021-01-20 22:15:49 +0000136 def search_api_url = "${cred.description}/rest/api/2/issue/createmeta?projectKeys=PRODX&issuetypeNames=Bug&expand=projects.issuetypes.fields"
Ivan Udovichenko67398552020-12-25 20:13:35 +0300137 def response = callREST("${search_api_url}", "${cred.username}:${cred.password}", 'GET')
138 def InputJSON = new JsonSlurper().parseText(response["responseText"])
139 def AffectedVersions = InputJSON['projects'][0]['issuetypes'][0]['fields']['versions']['allowedValues']
140
141 def versions = []
142 AffectedVersions.each{
Ivan Udovichenko14e87f62021-06-01 17:20:39 +0300143 // 'MOSK' doesn not contain 'released' field
144 if (productName != 'mosk' && it.containsKey('released') && it['released']) {
145 return
146 }
147 if (it.containsKey('name') && it['name'].startsWith(filterName)) {
148 def justVersion = it['name'].replaceAll(/.*_/, '')
149 justVersion = justVersion.replaceAll(/([0-9]+\.)([0-9])$/, '$10$2')
150 versions.add("${justVersion}`${it['name']}")
Ivan Udovichenko67398552020-12-25 20:13:35 +0300151 }
152 }
153 if (versions) {
Ivan Udovichenko14e87f62021-06-01 17:20:39 +0300154 return versions.sort()[0].split('`')[-1]
Ivan Udovichenko67398552020-12-25 20:13:35 +0300155 }
156 return defaultJiraAffectedVersion
157}
158
Ivan Udovichenko16568a62021-09-16 12:50:59 +0300159
160def reportJiraTickets(String reportFileContents, String jiraCredentialsID, String jiraUserID, String productName = '', String ignoreImageListFileContents = '[]', Integer retryTry = 0, String jiraNamespace = 'PRODX') {
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300161
162 def dict = [:]
163
Ivan Udovichenko6c870b72020-04-14 11:31:51 +0300164 def common = new com.mirantis.mk.Common()
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300165 def cred = common.getCredentialsById(jiraCredentialsID)
166 def auth = "${cred.username}:${cred.password}"
167 def uri = "${cred.description}/rest/api/2/issue"
168
169 def search_api_url = "${cred.description}/rest/api/2/search"
170
Ivan Udovichenko16568a62021-09-16 12:50:59 +0300171
172 def jqlStartAt = 0
173 def jqlStep = 100
174 def jqlProcessedItems = 0
175 def jqlUnfinishedProcess = true
176 def jqlTotalItems = 0
177 while (jqlUnfinishedProcess) {
178 def search_json = """
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300179{
Ivan Udovichenko1c4efd82021-08-17 23:28:30 +0300180 "jql": "reporter = ${jiraUserID} and (labels = cve and labels = security) and (status = 'To Do' or status = 'For Triage' or status = Open or status = 'In Progress' or status = New or status = 'Input Required')", "maxResults":-1
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300181}
182"""
183
Ivan Udovichenko16568a62021-09-16 12:50:59 +0300184 def response = callREST("${search_api_url}", auth, 'POST', search_json)
185 def InputJSON = new JsonSlurper().parseText(response["responseText"])
186 if (InputJSON.containsKey('maxResults')){
187 if (jqlStep > InputJSON['maxResults']) {
188 jqlStep = InputJSON['maxResults']
189 }
190 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300191
Ivan Udovichenko16568a62021-09-16 12:50:59 +0300192 jqlStartAt = jqlStartAt + jqlStep
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300193
Ivan Udovichenko16568a62021-09-16 12:50:59 +0300194 if (InputJSON.containsKey('total')){
195 jqlTotalItems = InputJSON['total']
196 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300197
Ivan Udovichenko77fd79e2021-09-20 13:15:28 +0300198 if (InputJSON.containsKey('issues')){
Ivan Udovichenko16568a62021-09-16 12:50:59 +0300199 if (!InputJSON['issues'] && retryTry != 0) {
200 throw new Exception('"issues" list is empty')
201 }
202 } else {
203 throw new Exception('Returned JSON from jql does not contain "issues" section')
204 }
205 print 'Temporal debug information:'
206 InputJSON['issues'].each {
207 print it['key'] + ' -> ' + it['fields']['summary']
208 }
209
210 InputJSON['issues'].each {
211 dict[it['key']] = [
212 summary : '',
213 description: '',
214 comments: []
215 ]
216 }
217
218 InputJSON['issues'].each { jira_issue ->
219 dict = updateDictionary(jira_issue['key'], dict, uri, auth, jiraUserID)
220 jqlProcessedItems = jqlProcessedItems + 1
221 }
222 if (jqlProcessedItems >= jqlTotalItems) {
223 jqlUnfinishedProcess = false
224 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300225 }
226
Ivan Udovichenko6c870b72020-04-14 11:31:51 +0300227 def reportJSON = new JsonSlurper().parseText(reportFileContents)
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300228 def imageDict = [:]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300229 reportJSON.each{
230 image ->
231 if ("${image.value}".contains('issues')) { return }
232 image.value.each{
233 pkg ->
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300234 pkg.value.each{
235 cve ->
236 if (cve[2] && (cve[1].contains('High') || cve[1].contains('Critical'))) {
Ivan Udovichenkoc774c6e2020-04-15 01:55:41 +0300237 if (!imageDict.containsKey(image.key)) {
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300238 imageDict.put(image.key, [:])
239 }
240 if (!imageDict[image.key].containsKey(pkg.key)) {
241 imageDict[image.key].put(pkg.key, [])
242 }
Ivan Udovichenko5c60cde2021-08-12 23:52:58 +0300243 imageDict[image.key][pkg.key].add("[${cve[0]}|${cve[4]}] (${cve[2]}) (${cve[3]}) | ${cve[5]}")
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300244 }
245 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300246 }
247 }
248
Ivan Udovichenko5e4ae9c2020-12-26 10:56:48 +0300249 def affectedVersion = ''
250 if (jiraNamespace == 'PRODX') {
251 affectedVersion = getLatestAffectedVersion(cred, productName)
252 }
253
Ivan Udovichenko83b7ffc2021-05-07 12:50:16 +0300254 def ignoreImageList = new JsonSlurper().parseText(ignoreImageListFileContents)
255
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300256 def jira_summary = ''
257 def jira_description = ''
258 imageDict.each{
259 image ->
260 def image_key = image.key.replaceAll(/(^[a-z0-9-.]+.mirantis.(net|com)\/|:.*$)/, '')
Ivan Udovichenko83b7ffc2021-05-07 12:50:16 +0300261
262 // Ignore images listed
263 if ((image.key in ignoreImageList) || (image.key.replaceAll(/:.*$/, '') in ignoreImageList)) {
264 print "\n\nIgnoring ${image.key} as it has been found in Docker image ignore list\n"
265 return
266 }
267
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300268 // Below change was produced due to other workflow for UCP Docker images (RE-274)
Ivan Udovichenko9721c312020-10-01 23:50:38 +0300269 if (image_key.startsWith('lcm/docker/ucp')) {
270 return
Ivan Udovichenko6bc5e182020-10-30 02:57:56 +0300271 } else if (image_key.startsWith('mirantis/ucp') || image_key.startsWith('mirantiseng/ucp')) {
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300272 jiraNamespace = 'ENGORC'
Ivan Udovichenkoe0ea4942021-02-18 17:50:20 +0300273 } else if (image_key.startsWith('mirantis/dtr') || image_key.startsWith('mirantiseng/dtr')) {
274 jiraNamespace = 'ENGDTR'
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300275 } else {
276 jiraNamespace = 'PRODX'
277 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300278 jira_summary = "[${image_key}] Found CVEs in Docker image"
Ivan Udovichenko62563612020-10-31 03:46:23 +0300279 jira_description = "${image.key}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300280 image.value.each{
281 pkg ->
Ivan Udovichenko62563612020-10-31 03:46:23 +0300282 jira_description += "__* ${pkg.key}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300283 pkg.value.each{
284 cve ->
Ivan Udovichenko62563612020-10-31 03:46:23 +0300285 jira_description += "________${cve}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300286 }
287 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300288
289 def team_assignee = getTeam(image_key)
290
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300291 def basicIssueJSON = new JsonSlurper().parseText('{"fields": {}}')
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300292
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300293 basicIssueJSON['fields'] = [
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300294 project:[
295 key:"${jiraNamespace}"
296 ],
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300297 summary:"${jira_summary}",
298 description:"${jira_description}",
299 issuetype:[
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300300 name:'Bug'
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300301 ],
302 labels:[
303 'security',
304 'cve'
305 ]
306 ]
307 if (jiraNamespace == 'PRODX') {
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300308 basicIssueJSON['fields']['customfield_19000'] = [value:"${team_assignee}"]
Ivan Udovichenko67398552020-12-25 20:13:35 +0300309 basicIssueJSON['fields']['versions'] = [["name": affectedVersion]]
Ivan Udovichenko49955b22021-08-19 23:22:47 +0300310 if (image_key.startsWith('lcm/')) {
311 basicIssueJSON['fields']['components'] = [["name": 'KaaS: LCM']]
312 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300313 }
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300314 def post_issue_json = JsonOutput.toJson(basicIssueJSON)
Ivan Udovichenko62563612020-10-31 03:46:23 +0300315 def jira_comment = jira_description.replaceAll(/\n/, '\\\\n')
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300316 def post_comment_json = """
317{
Ivan Udovichenko62563612020-10-31 03:46:23 +0300318 "body": "${jira_comment}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300319}
320"""
321 def jira_key = cacheLookUp(dict, image_key, image.key)
322 if (jira_key[0] && jira_key[1] == 'na') {
323 def post_comment_response = callREST("${uri}/${jira_key[0]}/comment", auth, 'POST', post_comment_json)
324 if ( post_comment_response['responseCode'] == 201 ) {
325 def issueCommentJSON = new JsonSlurper().parseText(post_comment_response["responseText"])
Ivan Udovichenko67398552020-12-25 20:13:35 +0300326 print "\n\nComment was posted to ${jira_key[0]} ${affectedVersion} for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300327 } else {
328 print "\nComment to ${jira_key[0]} Jira issue was not posted"
329 }
330 } else if (!jira_key[0]) {
331 def post_issue_response = callREST("${uri}/", auth, 'POST', post_issue_json)
332 if (post_issue_response['responseCode'] == 201) {
333 def issueJSON = new JsonSlurper().parseText(post_issue_response["responseText"])
334 dict = updateDictionary(issueJSON['key'], dict, uri, auth, jiraUserID)
Ivan Udovichenko67398552020-12-25 20:13:35 +0300335 print "\n\nJira issue was created ${issueJSON['key']} ${affectedVersion} for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300336 } else {
337 print "\n${image.key} CVE issues were not published\n"
338 }
339 } else {
Ivan Udovichenko99467752020-04-21 02:28:06 +0300340 print "\n\nNothing to process for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300341 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300342 }
Ivan Udovichenko314a0732020-04-13 22:47:26 +0300343}
Ivan Udovichenko45252252020-04-14 22:45:53 +0300344
345def find_cves_by_severity(String reportJsonContent, String Severity) {
346 def cves = []
347 def reportJSON = new JsonSlurper().parseText(reportJsonContent)
348 reportJSON.each{
349 image ->
350 image.value.each{
351 pkg ->
352 pkg.value.each{
353 cve ->
354 if (cve[2]) {
355 if (cve[1].contains(Severity)) {
356 cves.add("${pkg.key} ${cve[0]} (${cve[2]})")
357 }
358 }
359 }
360 }
361 }
362 return cves
363}