-
Notifications
You must be signed in to change notification settings - Fork 8
/
audit.go
108 lines (95 loc) · 2.6 KB
/
audit.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
package cmd
import (
"encoding/json"
"fmt"
"os"
"strings"
"text/template"
audit "github.com/krakendio/krakend-audit"
"github.com/spf13/cobra"
)
const (
defaultFormatTmpl = "{{ range .Recommendations }}{{.Rule}}\t[{{.Severity}}] \t{{.Message}}\n{{ end }}"
terminalFormatTmpl = "{{ range .Recommendations }}{{.Rule}}\t[{{colored .Severity}}] \t{{.Message}}\n{{ end }}"
)
func auditFunc(cmd *cobra.Command, _ []string) {
if cfgFile == "" {
cmd.Println(errorMsg("Please, provide the path to the configuration file with --config or see all the options with --help"))
os.Exit(1)
return
}
cfg, err := parser.Parse(cfgFile)
if err != nil {
cmd.Println(errorMsg("ERROR parsing the configuration file:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1)
return
}
cfg.Normalize()
if formatTmpl == "" {
if IsTTY {
formatTmpl = terminalFormatTmpl
} else {
formatTmpl = defaultFormatTmpl
}
}
severitiesToInclude = strings.ReplaceAll(severitiesToInclude, " ", "")
rules := strings.Split(strings.ReplaceAll(rulesToExclude, " ", ""), ",")
if rulesToExcludePath != "" {
b, err := os.ReadFile(rulesToExcludePath)
if err != nil {
cmd.Println(errorMsg("ERROR accessing the ignore file:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1)
return
}
for _, line := range strings.Split(strings.ReplaceAll(string(b), " ", ""), "\n") {
if line == "" {
continue
}
rules = append(rules, line)
}
}
result, err := audit.Audit(
&cfg,
rules,
strings.Split(severitiesToInclude, ","),
)
if err != nil {
cmd.Println(errorMsg("ERROR auditing the configuration file:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1)
return
}
funcMap := template.FuncMap{
"marshal": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
"colored": func(s string) string {
switch s {
case audit.SeverityLow:
return fmt.Sprintf("\033[32;1m%s\033[0m", s)
case audit.SeverityMedium:
return fmt.Sprintf("\033[33;1m%s\033[0m", s)
case audit.SeverityHigh:
return fmt.Sprintf("\033[31;1m%s\033[0m", s)
case audit.SeverityCritical:
return fmt.Sprintf("\033[41;1m%s\033[0m", s)
default:
return s
}
},
}
tmpl, err := template.New("audit").Funcs(funcMap).Parse(formatTmpl)
if err != nil {
cmd.Println(errorMsg("ERROR parsing the template:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1)
return
}
if err := tmpl.Execute(os.Stderr, result); err != nil {
cmd.Println(errorMsg("ERROR rendering the results:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1)
return
}
if len(result.Recommendations) > 0 {
os.Exit(1)
}
}