blob: 817856477d5a2bec53d7b298cbb1fe679788efe6 [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
46 case ~/^iam\/.*$/:
47 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{
146 if (it.containsKey('released') && it['released']) {
147 if (it.containsKey('name') && it['name'].startsWith(filterName)) {
148 if (it.containsKey('releaseDate') && it['releaseDate']) {
149 versions.add("${it['releaseDate']}`${it['name']}")
150 }
151 }
152 }
153 }
154 if (versions) {
155 return versions.sort()[-1].split('`')[-1]
156 }
157 return defaultJiraAffectedVersion
158}
159
Ivan Udovichenko6d697142020-12-26 00:16:47 +0300160def reportJiraTickets(String reportFileContents, String jiraCredentialsID, String jiraUserID, String productName = '', 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
171 def search_json = """
172{
Ivan Udovichenko897e32b2020-08-07 10:10:34 +0300173 "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 +0300174}
175"""
176
177 def response = callREST("${search_api_url}", auth, 'POST', search_json)
178
179 def InputJSON = new JsonSlurper().parseText(response["responseText"])
180
181 InputJSON['issues'].each {
182 dict[it['key']] = [
183 summary : '',
184 description: '',
185 comments: []
186 ]
187 }
188
189 InputJSON['issues'].each { jira_issue ->
190 dict = updateDictionary(jira_issue['key'], dict, uri, auth, jiraUserID)
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300191 }
192
Ivan Udovichenko6c870b72020-04-14 11:31:51 +0300193 def reportJSON = new JsonSlurper().parseText(reportFileContents)
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300194 def imageDict = [:]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300195 reportJSON.each{
196 image ->
197 if ("${image.value}".contains('issues')) { return }
198 image.value.each{
199 pkg ->
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300200 pkg.value.each{
201 cve ->
202 if (cve[2] && (cve[1].contains('High') || cve[1].contains('Critical'))) {
Ivan Udovichenkoc774c6e2020-04-15 01:55:41 +0300203 if (!imageDict.containsKey(image.key)) {
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300204 imageDict.put(image.key, [:])
205 }
206 if (!imageDict[image.key].containsKey(pkg.key)) {
207 imageDict[image.key].put(pkg.key, [])
208 }
Ivan Udovichenkob2e52352020-06-29 18:03:56 +0300209 imageDict[image.key][pkg.key].add("[${cve[0]}|${cve[4]}] (${cve[2]}) (${cve[3]})")
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300210 }
211 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300212 }
213 }
214
Ivan Udovichenko5e4ae9c2020-12-26 10:56:48 +0300215 def affectedVersion = ''
216 if (jiraNamespace == 'PRODX') {
217 affectedVersion = getLatestAffectedVersion(cred, productName)
218 }
219
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300220 def jira_summary = ''
221 def jira_description = ''
222 imageDict.each{
223 image ->
224 def image_key = image.key.replaceAll(/(^[a-z0-9-.]+.mirantis.(net|com)\/|:.*$)/, '')
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300225 // Below change was produced due to other workflow for UCP Docker images (RE-274)
Ivan Udovichenko9721c312020-10-01 23:50:38 +0300226 if (image_key.startsWith('lcm/docker/ucp')) {
227 return
Ivan Udovichenko6bc5e182020-10-30 02:57:56 +0300228 } else if (image_key.startsWith('mirantis/ucp') || image_key.startsWith('mirantiseng/ucp')) {
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300229 jiraNamespace = 'ENGORC'
230 } else {
231 jiraNamespace = 'PRODX'
232 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300233 jira_summary = "[${image_key}] Found CVEs in Docker image"
Ivan Udovichenko62563612020-10-31 03:46:23 +0300234 jira_description = "${image.key}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300235 image.value.each{
236 pkg ->
Ivan Udovichenko62563612020-10-31 03:46:23 +0300237 jira_description += "__* ${pkg.key}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300238 pkg.value.each{
239 cve ->
Ivan Udovichenko62563612020-10-31 03:46:23 +0300240 jira_description += "________${cve}\n"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300241 }
242 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300243
244 def team_assignee = getTeam(image_key)
245
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300246 def basicIssueJSON = new JsonSlurper().parseText('{"fields": {}}')
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300247
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300248 basicIssueJSON['fields'] = [
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300249 project:[
250 key:"${jiraNamespace}"
251 ],
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300252 summary:"${jira_summary}",
253 description:"${jira_description}",
254 issuetype:[
Ivan Udovichenkofe3f11e2020-09-29 17:31:38 +0300255 name:'Bug'
Ivan Udovichenko6c337562020-08-06 16:22:26 +0300256 ],
257 labels:[
258 'security',
259 'cve'
260 ]
261 ]
262 if (jiraNamespace == 'PRODX') {
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300263 basicIssueJSON['fields']['customfield_19000'] = [value:"${team_assignee}"]
Ivan Udovichenko67398552020-12-25 20:13:35 +0300264 basicIssueJSON['fields']['versions'] = [["name": affectedVersion]]
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300265 }
Ivan Udovichenkoadee8b52020-08-06 17:07:28 +0300266 def post_issue_json = JsonOutput.toJson(basicIssueJSON)
Ivan Udovichenko62563612020-10-31 03:46:23 +0300267 def jira_comment = jira_description.replaceAll(/\n/, '\\\\n')
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300268 def post_comment_json = """
269{
Ivan Udovichenko62563612020-10-31 03:46:23 +0300270 "body": "${jira_comment}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300271}
272"""
273 def jira_key = cacheLookUp(dict, image_key, image.key)
274 if (jira_key[0] && jira_key[1] == 'na') {
275 def post_comment_response = callREST("${uri}/${jira_key[0]}/comment", auth, 'POST', post_comment_json)
276 if ( post_comment_response['responseCode'] == 201 ) {
277 def issueCommentJSON = new JsonSlurper().parseText(post_comment_response["responseText"])
Ivan Udovichenko67398552020-12-25 20:13:35 +0300278 print "\n\nComment was posted to ${jira_key[0]} ${affectedVersion} for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300279 } else {
280 print "\nComment to ${jira_key[0]} Jira issue was not posted"
281 }
282 } else if (!jira_key[0]) {
283 def post_issue_response = callREST("${uri}/", auth, 'POST', post_issue_json)
284 if (post_issue_response['responseCode'] == 201) {
285 def issueJSON = new JsonSlurper().parseText(post_issue_response["responseText"])
286 dict = updateDictionary(issueJSON['key'], dict, uri, auth, jiraUserID)
Ivan Udovichenko67398552020-12-25 20:13:35 +0300287 print "\n\nJira issue was created ${issueJSON['key']} ${affectedVersion} for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300288 } else {
289 print "\n${image.key} CVE issues were not published\n"
290 }
291 } else {
Ivan Udovichenko99467752020-04-21 02:28:06 +0300292 print "\n\nNothing to process for ${image_key} and ${image.key}"
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300293 }
Ivan Udovichenko894fd8a2020-04-13 17:24:50 +0300294 }
Ivan Udovichenko314a0732020-04-13 22:47:26 +0300295}
Ivan Udovichenko45252252020-04-14 22:45:53 +0300296
297def find_cves_by_severity(String reportJsonContent, String Severity) {
298 def cves = []
299 def reportJSON = new JsonSlurper().parseText(reportJsonContent)
300 reportJSON.each{
301 image ->
302 image.value.each{
303 pkg ->
304 pkg.value.each{
305 cve ->
306 if (cve[2]) {
307 if (cve[1].contains(Severity)) {
308 cves.add("${pkg.key} ${cve[0]} (${cve[2]})")
309 }
310 }
311 }
312 }
313 }
314 return cves
315}