-
Notifications
You must be signed in to change notification settings - Fork 237
/
detection_results.go
393 lines (341 loc) · 14.4 KB
/
detection_results.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package detector
import (
"fmt"
"log"
"os"
"strings"
"talisman/gitrepo"
"talisman/prompt"
"talisman/talismanrc"
"talisman/utility"
"github.com/spf13/afero"
"gopkg.in/yaml.v2"
"github.com/olekukonko/tablewriter"
)
type Details struct {
Category string `json:"type"`
Message string `json:"message"`
Commits []string `json:"commits"`
}
type ResultsDetails struct {
Filename gitrepo.FilePath `json:"filename"`
FailureList []Details `json:"failure_list"`
WarningList []Details `json:"warning_list"`
IgnoreList []Details `json:"ignore_list"`
}
type FailureTypes struct {
Filecontent int `json:"filecontent"`
Filesize int `json:"filesize"`
Filename int `json:"filename"`
Warnings int `json:"warnings"`
Ignores int `json:"ignores"`
}
type ResultsSummary struct {
Types FailureTypes `json:"types"`
}
//
//
//type FailureData struct {
// FailuresInCommits map[string][]string
//}
//DetectionResults represents all interesting information collected during a detection run.
//It serves as a collecting parameter for the tests performed by the various Detectors in the DetectorChain
//Currently, it keeps track of failures and ignored files.
//The results are grouped by FilePath for easy reporting of all detected problems with individual files.
type DetectionResults struct {
Summary ResultsSummary `json:"summary"`
Results []ResultsDetails `json:"results"`
}
func (r *ResultsDetails) getWarningDataByCategoryAndMessage(failureMessage string, category string) *Details {
detail := getDetaisByCategoryAndMessage(r.WarningList, category, failureMessage)
r.WarningList = append(r.WarningList, *detail)
return detail
}
func (r *ResultsDetails) getFailureDataByCategoryAndMessage(failureMessage string, category string) *Details {
detail := getDetaisByCategoryAndMessage(r.FailureList, category, failureMessage)
if detail == nil {
detail = &Details{category, failureMessage, make([]string, 0)}
r.FailureList = append(r.FailureList, *detail)
}
return detail
}
func (r *ResultsDetails) addIgnoreDataByCategory(category string) {
isCategoryAlreadyPresent := false
for _, detail := range r.IgnoreList {
if strings.Compare(detail.Category, category) == 0 {
isCategoryAlreadyPresent = true
}
}
if !isCategoryAlreadyPresent {
detail := Details{category, "", make([]string, 0)}
r.IgnoreList = append(r.IgnoreList, detail)
}
}
func getDetaisByCategoryAndMessage(detailsList []Details, category string, failureMessage string) *Details {
for _, detail := range detailsList {
if strings.Compare(detail.Category, category) == 0 && strings.Compare(detail.Message, failureMessage) == 0 {
return &detail
}
}
return nil
}
func (r *DetectionResults) getResultDetailsForFilePath(fileName gitrepo.FilePath) *ResultsDetails {
for _, resultDetail := range r.Results {
if resultDetail.Filename == fileName {
return &resultDetail
}
}
//resultDetail := ResultsDetails{fileName, make([]Details, 0), make([]Details, 0), make([]Details, 0)}
//r.Results = append(r.Results, resultDetail)
return nil
}
//NewDetectionResults is a new DetectionResults struct. It represents the pre-run state of a Detection run.
func NewDetectionResults() *DetectionResults {
result := DetectionResults{ResultsSummary{FailureTypes{0, 0, 0, 0, 0}}, make([]ResultsDetails, 0)}
return &result
}
//Fail is used to mark the supplied FilePath as failing a detection for a supplied reason.
//Detectors are encouraged to provide context sensitive messages so that fixing the errors is made simple for the end user
//Fail may be called multiple times for each FilePath and the calls accumulate the provided reasons
func (r *DetectionResults) Fail(filePath gitrepo.FilePath, category string, message string, commits []string) {
isFilePresentInResults := false
for resultIndex := 0; resultIndex < len(r.Results); resultIndex++ {
if r.Results[resultIndex].Filename == filePath {
isFilePresentInResults = true
isEntryPresentForGivenCategoryAndMessage := false
for detailIndex := 0; detailIndex < len(r.Results[resultIndex].FailureList); detailIndex++ {
if strings.Compare(r.Results[resultIndex].FailureList[detailIndex].Category, category) == 0 && strings.Compare(r.Results[resultIndex].FailureList[detailIndex].Message, message) == 0 {
isEntryPresentForGivenCategoryAndMessage = true
r.Results[resultIndex].FailureList[detailIndex].Commits = append(r.Results[resultIndex].FailureList[detailIndex].Commits, commits...)
}
}
if !isEntryPresentForGivenCategoryAndMessage {
r.Results[resultIndex].FailureList = append(r.Results[resultIndex].FailureList, Details{category, message, commits})
}
}
}
if !isFilePresentInResults {
failureDetails := Details{category, message, commits}
resultDetails := ResultsDetails{filePath, make([]Details, 0), make([]Details, 0), make([]Details, 0)}
resultDetails.FailureList = append(resultDetails.FailureList, failureDetails)
r.Results = append(r.Results, resultDetails)
}
r.updateResultsSummary(category)
}
func (r *DetectionResults) Warn(filePath gitrepo.FilePath, category string, message string, commits []string) {
isFilePresentInResults := false
for resultIndex := 0; resultIndex < len(r.Results); resultIndex++ {
if r.Results[resultIndex].Filename == filePath {
isFilePresentInResults = true
isEntryPresentForGivenCategoryAndMessage := false
for detailIndex := 0; detailIndex < len(r.Results[resultIndex].WarningList); detailIndex++ {
if strings.Compare(r.Results[resultIndex].WarningList[detailIndex].Category, category) == 0 && strings.Compare(r.Results[resultIndex].WarningList[detailIndex].Message, message) == 0 {
isEntryPresentForGivenCategoryAndMessage = true
r.Results[resultIndex].WarningList[detailIndex].Commits = append(r.Results[resultIndex].WarningList[detailIndex].Commits, commits...)
}
}
if !isEntryPresentForGivenCategoryAndMessage {
r.Results[resultIndex].WarningList = append(r.Results[resultIndex].WarningList, Details{category, message, commits})
}
}
}
if !isFilePresentInResults {
warningDetails := Details{category, message, commits}
resultDetails := ResultsDetails{filePath, make([]Details, 0), make([]Details, 0), make([]Details, 0)}
resultDetails.WarningList = append(resultDetails.WarningList, warningDetails)
r.Results = append(r.Results, resultDetails)
}
r.Summary.Types.Warnings++
}
//Ignore is used to mark the supplied FilePath as being ignored.
//The most common reason for this is that the FilePath is Denied by the Ignores supplied to the Detector, however, Detectors may use more sophisticated reasons to ignore files.
func (r *DetectionResults) Ignore(filePath gitrepo.FilePath, category string) {
isFilePresentInResults := false
for resultIndex := 0; resultIndex < len(r.Results); resultIndex++ {
if r.Results[resultIndex].Filename == filePath {
isFilePresentInResults = true
isEntryPresentForGivenCategory := false
for detailIndex := 0; detailIndex < len(r.Results[resultIndex].IgnoreList); detailIndex++ {
if strings.Compare(r.Results[resultIndex].IgnoreList[detailIndex].Category, category) == 0 {
isEntryPresentForGivenCategory = true
}
}
if !isEntryPresentForGivenCategory {
detail := Details{category, "", make([]string, 0)}
r.Results[resultIndex].IgnoreList = append(r.Results[resultIndex].IgnoreList, detail)
}
}
}
if !isFilePresentInResults {
ignoreDetails := Details{category, "", make([]string, 0)}
resultDetails := ResultsDetails{filePath, make([]Details, 0), make([]Details, 0), make([]Details, 0)}
resultDetails.IgnoreList = append(resultDetails.IgnoreList, ignoreDetails)
r.Results = append(r.Results, resultDetails)
}
r.Summary.Types.Ignores++
}
func createNewResultForFile(category string, message string, commits []string, filePath gitrepo.FilePath) ResultsDetails {
failureDetails := Details{category, message, commits}
resultDetails := ResultsDetails{filePath, make([]Details, 0), make([]Details, 0), make([]Details, 0)}
resultDetails.FailureList = append(resultDetails.FailureList, failureDetails)
return resultDetails
}
func (r *DetectionResults) updateResultsSummary(category string) {
if strings.Compare("filecontent", category) == 0 {
r.Summary.Types.Filecontent++
} else if strings.Compare("filename", category) == 0 {
r.Summary.Types.Filename++
} else if strings.Compare("filesize", category) == 0 {
r.Summary.Types.Filesize++
}
}
//HasFailures answers if any Failures were detected for any FilePath in the current run
func (r *DetectionResults) HasFailures() bool {
return r.Summary.Types.Filesize > 0 || r.Summary.Types.Filename > 0 || r.Summary.Types.Filecontent > 0
}
//HasIgnores answers if any FilePaths were ignored in the current run
func (r *DetectionResults) HasIgnores() bool {
return r.Summary.Types.Ignores > 0
}
func (r *DetectionResults) HasWarnings() bool {
return r.Summary.Types.Warnings > 0
}
func (r *DetectionResults) HasDetectionMessages() bool {
return r.HasWarnings() || r.HasFailures() || r.HasIgnores()
}
//Successful answers if no detector was able to find any possible result to fail the run
func (r *DetectionResults) Successful() bool {
return !r.HasFailures()
}
//GetFailures returns the various reasons that a given FilePath was marked as failing by all the detectors in the current run
func (r *DetectionResults) GetFailures(fileName gitrepo.FilePath) []Details {
results := r.getResultDetailsForFilePath(fileName)
if results == nil {
return []Details{}
}
return results.FailureList
}
func (r *DetectionResults) ReportWarnings() string {
var result string
var filePathsForWarnings []string
var data [][]string
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"File", "Warnings"})
table.SetRowLine(true)
for _, resultDetails := range r.Results {
if len(resultDetails.WarningList) > 0 {
filePathsForWarnings = append(filePathsForWarnings, string(resultDetails.Filename))
warningData := r.ReportFileWarnings(resultDetails.Filename)
data = append(data, warningData...)
}
}
filePathsForWarnings = utility.UniqueItems(filePathsForWarnings)
if r.Summary.Types.Warnings > 0 {
fmt.Printf("\n\x1b[1m\x1b[31mTalisman Warnings:\x1b[0m\x1b[0m\n")
table.AppendBulk(data)
table.Render()
result = result + fmt.Sprintf("\n\x1b[33mPlease review the above file(s) to make sure that no sensitive content is being pushed\x1b[0m\n")
result = result + fmt.Sprintf("\n")
}
return result
}
//Report returns a string documenting the various failures and ignored files for the current run
func (r *DetectionResults) Report(fs afero.Fs, ignoreFile string, promptContext prompt.PromptContext) string {
var result string
var filePathsForIgnoresAndFailures []string
var data [][]string
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"File", "Errors"})
table.SetRowLine(true)
for _, resultDetails := range r.Results {
if len(resultDetails.FailureList) > 0 || len(resultDetails.IgnoreList) > 0 {
filePathsForIgnoresAndFailures = append(filePathsForIgnoresAndFailures, string(resultDetails.Filename))
failureData := r.ReportFileFailures(resultDetails.Filename)
data = append(data, failureData...)
}
}
filePathsForIgnoresAndFailures = utility.UniqueItems(filePathsForIgnoresAndFailures)
if r.HasFailures() {
fmt.Printf("\n\x1b[1m\x1b[31mTalisman Report:\x1b[0m\x1b[0m\n")
table.AppendBulk(data)
table.Render()
r.suggestTalismanRC(fs, ignoreFile, filePathsForIgnoresAndFailures, promptContext)
}
return result
}
func (r *DetectionResults) suggestTalismanRC(fs afero.Fs, ignoreFile string, filePaths []string, promptContext prompt.PromptContext) {
var entriesToAdd []talismanrc.FileIgnoreConfig
for _, filePath := range filePaths {
currentChecksum := utility.DefaultSHA256Hasher{}.CollectiveSHA256Hash([]string{filePath})
fileIgnoreConfig := talismanrc.FileIgnoreConfig{filePath, currentChecksum, []string{}}
entriesToAdd = append(entriesToAdd, fileIgnoreConfig)
}
if promptContext.Interactive {
confirmedEntries := getUserConfirmation(entriesToAdd, promptContext)
talismanrc.Get().AddFileIgnores(confirmedEntries)
} else {
printTalismanIgnoreSuggestion(entriesToAdd)
return
}
}
func getUserConfirmation(configs []talismanrc.FileIgnoreConfig, promptContext prompt.PromptContext) []talismanrc.FileIgnoreConfig {
confirmed := []talismanrc.FileIgnoreConfig{}
for _, config := range configs {
if confirm(config, promptContext) {
confirmed = append(confirmed, config)
}
}
return confirmed
}
func printTalismanIgnoreSuggestion(entriesToAdd []talismanrc.FileIgnoreConfig) {
talismanRCConfig := talismanrc.TalismanRC{FileIgnoreConfig: entriesToAdd}
ignoreEntries, _ := yaml.Marshal(&talismanRCConfig)
suggestString := fmt.Sprintf("\n\x1b[33mIf you are absolutely sure that you want to ignore the " +
"above files from talisman detectors, consider pasting the following format in .talismanrc file" +
" in the project root\x1b[0m\n")
fmt.Println(suggestString)
fmt.Println(string(ignoreEntries))
}
func confirm(config talismanrc.FileIgnoreConfig, promptContext prompt.PromptContext) bool {
bytes, err := yaml.Marshal(&config)
if err != nil {
log.Printf("error marshalling file ignore config: %s", err)
}
fmt.Println(string(bytes))
confirmationString := "Do you want to add this entry in talismanrc ?"
return promptContext.Prompt.Confirm(confirmationString)
}
//ReportFileFailures adds a string to table documenting the various failures detected on the supplied FilePath by all detectors in the current run
func (r *DetectionResults) ReportFileFailures(filePath gitrepo.FilePath) [][]string {
failureList := r.getResultDetailsForFilePath(filePath).FailureList
var data [][]string
if len(failureList) > 0 {
for _, detail := range failureList {
if len(detail.Message) > 150 {
detail.Message = detail.Message[:150] + "\n" + detail.Message[150:]
}
data = append(data, []string{string(filePath), detail.Message})
}
}
return data
}
func (r *DetectionResults) ReportFileWarnings(filePath gitrepo.FilePath) [][]string {
warningList := r.getResultDetailsForFilePath(filePath).WarningList
var data [][]string
if len(warningList) > 0 {
for _, detail := range warningList {
if len(detail.Message) > 150 {
detail.Message = detail.Message[:150] + "\n" + detail.Message[150:]
}
data = append(data, []string{string(filePath), detail.Message})
}
}
return data
}
func keys(aMap map[gitrepo.FilePath][]string) []gitrepo.FilePath {
var result []gitrepo.FilePath
for filePath := range aMap {
result = append(result, filePath)
}
return result
}