blob: c1ab392fb255b6441465a882d37a1789fd737af4 [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
6
7def callREST (String uri, String auth,
8 String method = 'GET', String message = null) {
9 String authEnc = auth.bytes.encodeBase64()
10 def req = new URL(uri).openConnection()
11 req.setRequestMethod(method)
12 req.setRequestProperty('Content-Type', 'application/json')
13 req.setRequestProperty('Authorization', "Basic ${authEnc}")
14 if (message) {
15 req.setDoOutput(true)
16 req.getOutputStream().write(message.getBytes('UTF-8'))
17 }
18 Integer responseCode = req.getResponseCode()
19 String responseText = ''
20 if (responseCode == 200 || responseCode == 201) {
21 responseText = req.getInputStream().getText()
22 }
23 req = null
24 return [ 'responseCode': responseCode, 'responseText': responseText ]
25}
26
27def getTeam (String image = '') {
28 def team_assignee = ''
29 switch(image) {
30 case ~/^(tungsten|tungsten-operator)\/.*$/:
31 team_assignee = 'OpenContrail'
32 break
33 case ~/^bm\/.*$/:
34 team_assignee = 'BM/OS (KaaS BM)'
35 break
36 case ~/^openstack\/.*$/:
37 team_assignee = 'OpenStack hardening'
38 break
39 case ~/^stacklight\/.*$/:
40 team_assignee = 'Stacklight LMA'
41 break
42 case ~/^ceph\/.*$/:
43 team_assignee = 'Storage'
44 break
45 case ~/^iam\/.*$/:
46 team_assignee = 'KaaS'
47 break
48 case ~/^lcm\/.*$/:
49 team_assignee = 'Kubernetes'
50 break
51 default:
52 team_assignee = 'Release Engineering'
53 break
54 }
55
56 return team_assignee
57}
58
59def updateDictionary (String jira_issue_key, Map dict, String uri, String auth, String jira_user_id) {
60 def response = callREST("${uri}/${jira_issue_key}", auth)
61 if ( response['responseCode'] == 200 ) {
62 def issueJSON = new JsonSlurper().parseText(response["responseText"])
63 if (issueJSON.containsKey('fields')) {
64 if (!dict.containsKey(jira_issue_key)) {
65 dict[jira_issue_key] = [
66 summary : '',
67 description: '',
68 comments: []
69 ]
70 }
71 if (issueJSON['fields'].containsKey('summary')){
72 dict[jira_issue_key].summary = issueJSON['fields']['summary']
73 }
74 if (issueJSON['fields'].containsKey('description')) {
75 dict[jira_issue_key].description = issueJSON['fields']['description']
76 }
77 if (issueJSON['fields'].containsKey('comment') && issueJSON['fields']['comment']['comments']) {
78 issueJSON['fields']['comment']['comments'].each {
79 if (it.containsKey('author') && it['author'].containsKey('accountId') && it['author']['accountId'] == jira_user_id) {
80 dict[jira_issue_key]['comments'].add(it['body'])
81 }
82 }
83 }
84 }
85 }
86 return dict
87}
88
89def cacheLookUp(Map dict, String image_short_name, String image_full_name = '', String cve_id = '' ) {
90 def found_key = ['','']
91 if (!found_key[0] && dict && image_short_name) {
92 dict.each { issue_key_name ->
93 if (!found_key[0]) {
94 def s = dict[issue_key_name.key]['summary'] =~ /\b${image_short_name}\b/
95 if (s) {
96 if (image_full_name) {
97 def d = dict[issue_key_name.key]['description'] =~ /(?m)\b${image_full_name}\b/
98
99 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
129def reportJiraTickets(String pathToResultsJSON, String jiraCredentialsID, String jiraUserID) {
130
131 def dict = [:]
132
133 def cred = common.getCredentialsById(jiraCredentialsID)
134 def auth = "${cred.username}:${cred.password}"
135 def uri = "${cred.description}/rest/api/2/issue"
136
137 def search_api_url = "${cred.description}/rest/api/2/search"
138
139 def search_json = """
140{
141 "jql": "reporter = ${jiraUserID} and (labels = cve and labels = security) and (status = 'To Do' or status = 'For Triage' or status = Open or status = 'In Progress')"
142}
143"""
144
145 def response = callREST("${search_api_url}", auth, 'POST', search_json)
146
147 def InputJSON = new JsonSlurper().parseText(response["responseText"])
148
149 InputJSON['issues'].each {
150 dict[it['key']] = [
151 summary : '',
152 description: '',
153 comments: []
154 ]
155 }
156
157 InputJSON['issues'].each { jira_issue ->
158 dict = updateDictionary(jira_issue['key'], dict, uri, auth, jiraUserID)
159 sleep(1000)
160 }
161
162 def reportFile = new File(pathToResultsJSON)
163 def reportJSON = new JsonSlurper().parseText(reportFile.text)
164 def imageDict = [:]
165 def cves = []
166 reportJSON.each{
167 image ->
168 if ("${image.value}".contains('issues')) { return }
169 image.value.each{
170 pkg ->
171 cves = []
172 pkg.value.each{
173 cve ->
174 if (cve[2] && (cve[1].contains('High') || cve[1].contains('Critical'))) {
175 if (!imageDict.containsKey("${image.key}")) {
176 imageDict.put(image.key, [:])
177 }
178 if (!imageDict[image.key].containsKey(pkg.key)) {
179 imageDict[image.key].put(pkg.key, [])
180 }
181 cves.add("${cve[0]} (${cve[2]})")
182 }
183 }
184 if (cves) {
185 imageDict[image.key] = [
186 "${pkg.key}": cves
187 ]
188 }
189 }
190 }
191
192 def jira_summary = ''
193 def jira_description = ''
194 imageDict.each{
195 image ->
196 def image_key = image.key.replaceAll(/(^[a-z0-9-.]+.mirantis.(net|com)\/|:.*$)/, '')
197 // Temporary exclude tungsten images
198 if (image_key.startsWith('tungsten/') || image_key.startsWith('tungsten-operator/')) { return }
199 jira_summary = "[${image_key}] Found CVEs in Docker image"
200 jira_description = "{noformat}${image.key}\\n"
201 image.value.each{
202 pkg ->
203 jira_description += " * ${pkg.key}\\n"
204 pkg.value.each{
205 cve ->
206 jira_description += " - ${cve}\\n"
207 }
208 }
209 jira_description += "{noformat}"
210
211 def team_assignee = getTeam(image_key)
212
213 def post_issue_json = """
214{
215 "fields": {
216 "project": {
217 "key": "PRODX"
218 },
219 "summary": "${jira_summary}",
220 "description": "${jira_description}",
221 "issuetype": {
222 "name": "Bug"
223 },
224 "labels": [
225 "security",
226 "cve"
227 ],
228 "customfield_19000": {
229 "value": "${team_assignee}"
230 },
231 "versions": [
232 {
233 "name": "Backlog"
234 }
235 ]
236 }
237}
238"""
239 def post_comment_json = """
240{
241 "body": "${jira_description}"
242}
243"""
244 def jira_key = cacheLookUp(dict, image_key, image.key)
245 if (jira_key[0] && jira_key[1] == 'na') {
246 def post_comment_response = callREST("${uri}/${jira_key[0]}/comment", auth, 'POST', post_comment_json)
247 if ( post_comment_response['responseCode'] == 201 ) {
248 def issueCommentJSON = new JsonSlurper().parseText(post_comment_response["responseText"])
249 } else {
250 print "\nComment to ${jira_key[0]} Jira issue was not posted"
251 }
252 } else if (!jira_key[0]) {
253 def post_issue_response = callREST("${uri}/", auth, 'POST', post_issue_json)
254 if (post_issue_response['responseCode'] == 201) {
255 def issueJSON = new JsonSlurper().parseText(post_issue_response["responseText"])
256 dict = updateDictionary(issueJSON['key'], dict, uri, auth, jiraUserID)
257 } else {
258 print "\n${image.key} CVE issues were not published\n"
259 }
260 } else {
261 print "\n\nNothing to process for for ${image_key} and ${image.key}"
262 }
263 sleep(10000)
264 }
Ivan Udovichenko314a0732020-04-13 22:47:26 +0300265}