blob: 1395a47744a3075c6470ff738574190490fd9af7 [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 Udovichenko83b7ffc2021-05-07 12:50:16 +0300159def reportJiraTickets(String reportFileContents, String jiraCredentialsID, String jiraUserID, String productName = '', String ignoreImageListFileContents = '[]', String jiraNamespace = 'PRODX') {
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300160
161 def dict = [:]
162
Ivan Udovichenko6c870b72020-04-14 11:31:51 +0300163 def common = new com.mirantis.mk.Common()
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300164 def cred = common.getCredentialsById(jiraCredentialsID)
165 def auth = "${cred.username}:${cred.password}"
166 def uri = "${cred.description}/rest/api/2/issue"
167
168 def search_api_url = "${cred.description}/rest/api/2/search"
169
170 def search_json = """
171{
Ivan Udovichenko1c4efd82021-08-17 23:28:30 +0300172 "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 +0300173}
174"""
175
176 def response = callREST("${search_api_url}", auth, 'POST', search_json)
177
178 def InputJSON = new JsonSlurper().parseText(response["responseText"])
179
180 InputJSON['issues'].each {
181 dict[it['key']] = [
182 summary : '',
183 description: '',
184 comments: []
185 ]
186 }
187
188 InputJSON['issues'].each { jira_issue ->
189 dict = updateDictionary(jira_issue['key'], dict, uri, auth, jiraUserID)
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300190 }
191
Ivan Udovichenko6c870b72020-04-14 11:31:51 +0300192 def reportJSON = new JsonSlurper().parseText(reportFileContents)
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300193 def imageDict = [:]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300194 reportJSON.each{
195 image ->
196 if ("${image.value}".contains('issues')) { return }
197 image.value.each{
198 pkg ->
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300199 pkg.value.each{
200 cve ->
201 if (cve[2] && (cve[1].contains('High') || cve[1].contains('Critical'))) {
Ivan Udovichenkoc774c6e2020-04-15 01:55:41 +0300202 if (!imageDict.containsKey(image.key)) {
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300203 imageDict.put(image.key, [:])
204 }
205 if (!imageDict[image.key].containsKey(pkg.key)) {
206 imageDict[image.key].put(pkg.key, [])
207 }
Ivan Udovichenko5c60cde2021-08-12 23:52:58 +0300208 imageDict[image.key][pkg.key].add("[${cve[0]}|${cve[4]}] (${cve[2]}) (${cve[3]}) | ${cve[5]}")
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300209 }
210 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300211 }
212 }
213
Ivan Udovichenko5e4ae9c2020-12-26 10:56:48 +0300214 def affectedVersion = ''
215 if (jiraNamespace == 'PRODX') {
216 affectedVersion = getLatestAffectedVersion(cred, productName)
217 }
218
Ivan Udovichenko83b7ffc2021-05-07 12:50:16 +0300219 def ignoreImageList = new JsonSlurper().parseText(ignoreImageListFileContents)
220
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300221 def jira_summary = ''
222 def jira_description = ''
223 imageDict.each{
224 image ->
225 def image_key = image.key.replaceAll(/(^[a-z0-9-.]+.mirantis.(net|com)\/|:.*$)/, '')
Ivan Udovichenko83b7ffc2021-05-07 12:50:16 +0300226
227 // Ignore images listed
228 if ((image.key in ignoreImageList) || (image.key.replaceAll(/:.*$/, '') in ignoreImageList)) {
229 print "\n\nIgnoring ${image.key} as it has been found in Docker image ignore list\n"
230 return
231 }
232
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300233 // Below change was produced due to other workflow for UCP Docker images (RE-274)
Ivan Udovichenko9721c312020-10-01 23:50:38 +0300234 if (image_key.startsWith('lcm/docker/ucp')) {
235 return
Ivan Udovichenko6bc5e182020-10-30 02:57:56 +0300236 } else if (image_key.startsWith('mirantis/ucp') || image_key.startsWith('mirantiseng/ucp')) {
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300237 jiraNamespace = 'ENGORC'
Ivan Udovichenkoe0ea4942021-02-18 17:50:20 +0300238 } else if (image_key.startsWith('mirantis/dtr') || image_key.startsWith('mirantiseng/dtr')) {
239 jiraNamespace = 'ENGDTR'
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300240 } else {
241 jiraNamespace = 'PRODX'
242 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300243 jira_summary = "[${image_key}] Found CVEs in Docker image"
Ivan Udovichenko62563612020-10-31 03:46:23 +0300244 jira_description = "${image.key}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300245 image.value.each{
246 pkg ->
Ivan Udovichenko62563612020-10-31 03:46:23 +0300247 jira_description += "__* ${pkg.key}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300248 pkg.value.each{
249 cve ->
Ivan Udovichenko62563612020-10-31 03:46:23 +0300250 jira_description += "________${cve}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300251 }
252 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300253
254 def team_assignee = getTeam(image_key)
255
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300256 def basicIssueJSON = new JsonSlurper().parseText('{"fields": {}}')
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300257
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300258 basicIssueJSON['fields'] = [
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300259 project:[
260 key:"${jiraNamespace}"
261 ],
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300262 summary:"${jira_summary}",
263 description:"${jira_description}",
264 issuetype:[
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300265 name:'Bug'
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300266 ],
267 labels:[
268 'security',
269 'cve'
270 ]
271 ]
272 if (jiraNamespace == 'PRODX') {
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300273 basicIssueJSON['fields']['customfield_19000'] = [value:"${team_assignee}"]
Ivan Udovichenko67398552020-12-25 20:13:35 +0300274 basicIssueJSON['fields']['versions'] = [["name": affectedVersion]]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300275 }
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300276 def post_issue_json = JsonOutput.toJson(basicIssueJSON)
Ivan Udovichenko62563612020-10-31 03:46:23 +0300277 def jira_comment = jira_description.replaceAll(/\n/, '\\\\n')
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300278 def post_comment_json = """
279{
Ivan Udovichenko62563612020-10-31 03:46:23 +0300280 "body": "${jira_comment}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300281}
282"""
283 def jira_key = cacheLookUp(dict, image_key, image.key)
284 if (jira_key[0] && jira_key[1] == 'na') {
285 def post_comment_response = callREST("${uri}/${jira_key[0]}/comment", auth, 'POST', post_comment_json)
286 if ( post_comment_response['responseCode'] == 201 ) {
287 def issueCommentJSON = new JsonSlurper().parseText(post_comment_response["responseText"])
Ivan Udovichenko67398552020-12-25 20:13:35 +0300288 print "\n\nComment was posted to ${jira_key[0]} ${affectedVersion} for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300289 } else {
290 print "\nComment to ${jira_key[0]} Jira issue was not posted"
291 }
292 } else if (!jira_key[0]) {
293 def post_issue_response = callREST("${uri}/", auth, 'POST', post_issue_json)
294 if (post_issue_response['responseCode'] == 201) {
295 def issueJSON = new JsonSlurper().parseText(post_issue_response["responseText"])
296 dict = updateDictionary(issueJSON['key'], dict, uri, auth, jiraUserID)
Ivan Udovichenko67398552020-12-25 20:13:35 +0300297 print "\n\nJira issue was created ${issueJSON['key']} ${affectedVersion} for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300298 } else {
299 print "\n${image.key} CVE issues were not published\n"
300 }
301 } else {
Ivan Udovichenko99467752020-04-21 02:28:06 +0300302 print "\n\nNothing to process for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300303 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300304 }
Ivan Udovichenko314a0732020-04-13 22:47:26 +0300305}
Ivan Udovichenko45252252020-04-14 22:45:53 +0300306
307def find_cves_by_severity(String reportJsonContent, String Severity) {
308 def cves = []
309 def reportJSON = new JsonSlurper().parseText(reportJsonContent)
310 reportJSON.each{
311 image ->
312 image.value.each{
313 pkg ->
314 pkg.value.each{
315 cve ->
316 if (cve[2]) {
317 if (cve[1].contains(Severity)) {
318 cves.add("${pkg.key} ${cve[0]} (${cve[2]})")
319 }
320 }
321 }
322 }
323 }
324 return cves
325}