blob: 6920574f0c75403311d8825674d655c461f4df82 [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 Udovichenkob3bb89b2021-01-27 18:41:45 +030046 case ~/^(core|iam)\/.*$/:
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030047 team_assignee = 'KaaS'
48 break
49 case ~/^lcm\/.*$/:
50 team_assignee = 'Kubernetes'
51 break
52 default:
53 team_assignee = 'Release Engineering'
54 break
55 }
56
57 return team_assignee
58}
59
60def updateDictionary (String jira_issue_key, Map dict, String uri, String auth, String jira_user_id) {
61 def response = callREST("${uri}/${jira_issue_key}", auth)
62 if ( response['responseCode'] == 200 ) {
63 def issueJSON = new JsonSlurper().parseText(response["responseText"])
64 if (issueJSON.containsKey('fields')) {
65 if (!dict.containsKey(jira_issue_key)) {
66 dict[jira_issue_key] = [
67 summary : '',
68 description: '',
69 comments: []
70 ]
71 }
72 if (issueJSON['fields'].containsKey('summary')){
73 dict[jira_issue_key].summary = issueJSON['fields']['summary']
74 }
75 if (issueJSON['fields'].containsKey('description')) {
76 dict[jira_issue_key].description = issueJSON['fields']['description']
77 }
78 if (issueJSON['fields'].containsKey('comment') && issueJSON['fields']['comment']['comments']) {
79 issueJSON['fields']['comment']['comments'].each {
80 if (it.containsKey('author') && it['author'].containsKey('accountId') && it['author']['accountId'] == jira_user_id) {
81 dict[jira_issue_key]['comments'].add(it['body'])
82 }
83 }
84 }
85 }
86 }
87 return dict
88}
89
90def cacheLookUp(Map dict, String image_short_name, String image_full_name = '', String cve_id = '' ) {
91 def found_key = ['','']
92 if (!found_key[0] && dict && image_short_name) {
93 dict.each { issue_key_name ->
94 if (!found_key[0]) {
Ivan Udovichenkobfe3aca2020-12-17 21:48:50 +030095 def s = dict[issue_key_name.key]['summary'] =~ /(?<=[\/\[])${image_short_name}(?=\])/
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030096 if (s) {
97 if (image_full_name) {
98 def d = dict[issue_key_name.key]['description'] =~ /(?m)\b${image_full_name}\b/
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +030099 if (d) {
100 found_key = [issue_key_name.key,'']
101 } else {
102 if (dict[issue_key_name.key]['comments']) {
103 def comment_match = false
104 dict[issue_key_name.key]['comments'].each{ comment ->
105 if (!comment_match) {
106 def c = comment =~ /(?m)\b${image_full_name}\b/
107 if (c) {
108 comment_match = true
109 }
110 }
111 }
112 if (!comment_match) {
113 found_key = [issue_key_name.key,'na']
114 } else {
115 found_key = [issue_key_name.key,'']
116 }
117 } else {
118 found_key = [issue_key_name.key,'na']
119 }
120 }
121 }
122 }
123 }
124 }
125 }
126 return found_key
127}
128
Ivan Udovichenko67398552020-12-25 20:13:35 +0300129def getLatestAffectedVersion(cred, productName, defaultJiraAffectedVersion = 'Backlog') {
130 def filterName = ''
131 if (productName == 'mosk') {
132 filterName = 'MOSK'
133 } else if (productName == 'kaas') {
134 filterName = 'KaaS'
135 } else {
136 return defaultJiraAffectedVersion
137 }
138
Ivan Udovichenko4c08b8d2021-01-20 22:15:49 +0000139 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 +0300140 def response = callREST("${search_api_url}", "${cred.username}:${cred.password}", 'GET')
141 def InputJSON = new JsonSlurper().parseText(response["responseText"])
142 def AffectedVersions = InputJSON['projects'][0]['issuetypes'][0]['fields']['versions']['allowedValues']
143
144 def versions = []
145 AffectedVersions.each{
Ivan Udovichenko14e87f62021-06-01 17:20:39 +0300146 // 'MOSK' doesn not contain 'released' field
147 if (productName != 'mosk' && it.containsKey('released') && it['released']) {
148 return
149 }
150 if (it.containsKey('name') && it['name'].startsWith(filterName)) {
151 def justVersion = it['name'].replaceAll(/.*_/, '')
152 justVersion = justVersion.replaceAll(/([0-9]+\.)([0-9])$/, '$10$2')
153 versions.add("${justVersion}`${it['name']}")
Ivan Udovichenko67398552020-12-25 20:13:35 +0300154 }
155 }
156 if (versions) {
Ivan Udovichenko14e87f62021-06-01 17:20:39 +0300157 return versions.sort()[0].split('`')[-1]
Ivan Udovichenko67398552020-12-25 20:13:35 +0300158 }
159 return defaultJiraAffectedVersion
160}
161
Ivan Udovichenko83b7ffc2021-05-07 12:50:16 +0300162def reportJiraTickets(String reportFileContents, String jiraCredentialsID, String jiraUserID, String productName = '', String ignoreImageListFileContents = '[]', String jiraNamespace = 'PRODX') {
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300163
164 def dict = [:]
165
Ivan Udovichenko6c870b72020-04-14 11:31:51 +0300166 def common = new com.mirantis.mk.Common()
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300167 def cred = common.getCredentialsById(jiraCredentialsID)
168 def auth = "${cred.username}:${cred.password}"
169 def uri = "${cred.description}/rest/api/2/issue"
170
171 def search_api_url = "${cred.description}/rest/api/2/search"
172
173 def search_json = """
174{
Ivan Udovichenko897e32b2020-08-07 10:10:34 +0300175 "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)", "maxResults":-1
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300176}
177"""
178
179 def response = callREST("${search_api_url}", auth, 'POST', search_json)
180
181 def InputJSON = new JsonSlurper().parseText(response["responseText"])
182
183 InputJSON['issues'].each {
184 dict[it['key']] = [
185 summary : '',
186 description: '',
187 comments: []
188 ]
189 }
190
191 InputJSON['issues'].each { jira_issue ->
192 dict = updateDictionary(jira_issue['key'], dict, uri, auth, jiraUserID)
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300193 }
194
Ivan Udovichenko6c870b72020-04-14 11:31:51 +0300195 def reportJSON = new JsonSlurper().parseText(reportFileContents)
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300196 def imageDict = [:]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300197 reportJSON.each{
198 image ->
199 if ("${image.value}".contains('issues')) { return }
200 image.value.each{
201 pkg ->
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300202 pkg.value.each{
203 cve ->
204 if (cve[2] && (cve[1].contains('High') || cve[1].contains('Critical'))) {
Ivan Udovichenkoc774c6e2020-04-15 01:55:41 +0300205 if (!imageDict.containsKey(image.key)) {
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300206 imageDict.put(image.key, [:])
207 }
208 if (!imageDict[image.key].containsKey(pkg.key)) {
209 imageDict[image.key].put(pkg.key, [])
210 }
Ivan Udovichenkob2e52352020-06-29 18:03:56 +0300211 imageDict[image.key][pkg.key].add("[${cve[0]}|${cve[4]}] (${cve[2]}) (${cve[3]})")
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300212 }
213 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300214 }
215 }
216
Ivan Udovichenko5e4ae9c2020-12-26 10:56:48 +0300217 def affectedVersion = ''
218 if (jiraNamespace == 'PRODX') {
219 affectedVersion = getLatestAffectedVersion(cred, productName)
220 }
221
Ivan Udovichenko83b7ffc2021-05-07 12:50:16 +0300222 def ignoreImageList = new JsonSlurper().parseText(ignoreImageListFileContents)
223
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300224 def jira_summary = ''
225 def jira_description = ''
226 imageDict.each{
227 image ->
228 def image_key = image.key.replaceAll(/(^[a-z0-9-.]+.mirantis.(net|com)\/|:.*$)/, '')
Ivan Udovichenko83b7ffc2021-05-07 12:50:16 +0300229
230 // Ignore images listed
231 if ((image.key in ignoreImageList) || (image.key.replaceAll(/:.*$/, '') in ignoreImageList)) {
232 print "\n\nIgnoring ${image.key} as it has been found in Docker image ignore list\n"
233 return
234 }
235
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300236 // Below change was produced due to other workflow for UCP Docker images (RE-274)
Ivan Udovichenko9721c312020-10-01 23:50:38 +0300237 if (image_key.startsWith('lcm/docker/ucp')) {
238 return
Ivan Udovichenko6bc5e182020-10-30 02:57:56 +0300239 } else if (image_key.startsWith('mirantis/ucp') || image_key.startsWith('mirantiseng/ucp')) {
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300240 jiraNamespace = 'ENGORC'
Ivan Udovichenkoe0ea4942021-02-18 17:50:20 +0300241 } else if (image_key.startsWith('mirantis/dtr') || image_key.startsWith('mirantiseng/dtr')) {
242 jiraNamespace = 'ENGDTR'
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300243 } else {
244 jiraNamespace = 'PRODX'
245 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300246 jira_summary = "[${image_key}] Found CVEs in Docker image"
Ivan Udovichenko62563612020-10-31 03:46:23 +0300247 jira_description = "${image.key}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300248 image.value.each{
249 pkg ->
Ivan Udovichenko62563612020-10-31 03:46:23 +0300250 jira_description += "__* ${pkg.key}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300251 pkg.value.each{
252 cve ->
Ivan Udovichenko62563612020-10-31 03:46:23 +0300253 jira_description += "________${cve}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300254 }
255 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300256
257 def team_assignee = getTeam(image_key)
258
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300259 def basicIssueJSON = new JsonSlurper().parseText('{"fields": {}}')
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300260
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300261 basicIssueJSON['fields'] = [
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300262 project:[
263 key:"${jiraNamespace}"
264 ],
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300265 summary:"${jira_summary}",
266 description:"${jira_description}",
267 issuetype:[
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300268 name:'Bug'
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300269 ],
270 labels:[
271 'security',
272 'cve'
273 ]
274 ]
275 if (jiraNamespace == 'PRODX') {
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300276 basicIssueJSON['fields']['customfield_19000'] = [value:"${team_assignee}"]
Ivan Udovichenko67398552020-12-25 20:13:35 +0300277 basicIssueJSON['fields']['versions'] = [["name": affectedVersion]]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300278 }
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300279 def post_issue_json = JsonOutput.toJson(basicIssueJSON)
Ivan Udovichenko62563612020-10-31 03:46:23 +0300280 def jira_comment = jira_description.replaceAll(/\n/, '\\\\n')
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300281 def post_comment_json = """
282{
Ivan Udovichenko62563612020-10-31 03:46:23 +0300283 "body": "${jira_comment}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300284}
285"""
286 def jira_key = cacheLookUp(dict, image_key, image.key)
287 if (jira_key[0] && jira_key[1] == 'na') {
288 def post_comment_response = callREST("${uri}/${jira_key[0]}/comment", auth, 'POST', post_comment_json)
289 if ( post_comment_response['responseCode'] == 201 ) {
290 def issueCommentJSON = new JsonSlurper().parseText(post_comment_response["responseText"])
Ivan Udovichenko67398552020-12-25 20:13:35 +0300291 print "\n\nComment was posted to ${jira_key[0]} ${affectedVersion} for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300292 } else {
293 print "\nComment to ${jira_key[0]} Jira issue was not posted"
294 }
295 } else if (!jira_key[0]) {
296 def post_issue_response = callREST("${uri}/", auth, 'POST', post_issue_json)
297 if (post_issue_response['responseCode'] == 201) {
298 def issueJSON = new JsonSlurper().parseText(post_issue_response["responseText"])
299 dict = updateDictionary(issueJSON['key'], dict, uri, auth, jiraUserID)
Ivan Udovichenko67398552020-12-25 20:13:35 +0300300 print "\n\nJira issue was created ${issueJSON['key']} ${affectedVersion} for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300301 } else {
302 print "\n${image.key} CVE issues were not published\n"
303 }
304 } else {
Ivan Udovichenko99467752020-04-21 02:28:06 +0300305 print "\n\nNothing to process for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300306 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300307 }
Ivan Udovichenko314a0732020-04-13 22:47:26 +0300308}
Ivan Udovichenko45252252020-04-14 22:45:53 +0300309
310def find_cves_by_severity(String reportJsonContent, String Severity) {
311 def cves = []
312 def reportJSON = new JsonSlurper().parseText(reportJsonContent)
313 reportJSON.each{
314 image ->
315 image.value.each{
316 pkg ->
317 pkg.value.each{
318 cve ->
319 if (cve[2]) {
320 if (cve[1].contains(Severity)) {
321 cves.add("${pkg.key} ${cve[0]} (${cve[2]})")
322 }
323 }
324 }
325 }
326 }
327 return cves
328}