-
Notifications
You must be signed in to change notification settings - Fork 216
/
Copy pathaudit.go
324 lines (296 loc) · 11.4 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
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
// Copyright 2020 FairwindsOps Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
workloads "github.com/fairwindsops/insights-plugins/plugins/workloads"
workloadsPkg "github.com/fairwindsops/insights-plugins/plugins/workloads/pkg"
"github.com/fairwindsops/polaris/pkg/auth"
cfg "github.com/fairwindsops/polaris/pkg/config"
"github.com/fairwindsops/polaris/pkg/insights"
"github.com/fairwindsops/polaris/pkg/kube"
"github.com/fairwindsops/polaris/pkg/validator"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"sigs.k8s.io/yaml"
)
var (
setExitCode bool
onlyShowFailedTests bool
minScore int
auditOutputURL string
auditOutputFile string
auditOutputFormat string
resourceToAudit string
useColor bool
helmChart string
helmValues []string
helmSkipTests bool
checks []string
auditNamespace string
severityLevel string
skipSslValidation bool
uploadInsights bool
clusterName string
quiet bool
)
func init() {
rootCmd.AddCommand(auditCmd)
auditCmd.PersistentFlags().StringVar(&auditPath, "audit-path", "", "If specified, audits one or more YAML files instead of a cluster.")
auditCmd.PersistentFlags().BoolVar(&setExitCode, "set-exit-code-on-danger", false, "Set an exit code of 3 when the audit contains danger-level issues.")
auditCmd.PersistentFlags().BoolVar(&onlyShowFailedTests, "only-show-failed-tests", false, "If specified, audit output will only show failed tests.")
auditCmd.PersistentFlags().IntVar(&minScore, "set-exit-code-below-score", 0, "Set an exit code of 4 when the score is below this threshold (1-100).")
auditCmd.PersistentFlags().StringVar(&auditOutputURL, "output-url", "", "Destination URL to send audit results.")
auditCmd.PersistentFlags().StringVar(&auditOutputFile, "output-file", "", "Destination file for audit results.")
auditCmd.PersistentFlags().StringVarP(&auditOutputFormat, "format", "f", "json", "Output format for results - json, yaml, pretty, or score.")
auditCmd.PersistentFlags().BoolVar(&useColor, "color", true, "Whether to use color in pretty format.")
auditCmd.PersistentFlags().StringVar(&displayName, "display-name", "", "An optional identifier for the audit.")
auditCmd.PersistentFlags().StringVar(&resourceToAudit, "resource", "", "Audit a specific resource, in the format namespace/kind/version/name, e.g. nginx-ingress/Deployment.apps/v1/default-backend.")
auditCmd.PersistentFlags().StringVar(&helmChart, "helm-chart", "", "Will fill out Helm template")
auditCmd.PersistentFlags().StringSliceVar(&helmValues, "helm-values", []string{}, "Optional flag to add helm values")
auditCmd.PersistentFlags().BoolVar(&helmSkipTests, "helm-skip-tests", false, "Corresponds to --skip-tests of helm template")
auditCmd.PersistentFlags().StringSliceVar(&checks, "checks", []string{}, "Optional flag to specify specific checks to check")
auditCmd.PersistentFlags().StringVar(&auditNamespace, "namespace", "", "Namespace to audit. Only applies to in-cluster audits")
auditCmd.PersistentFlags().StringVar(&severityLevel, "severity", "", "Severity level used to filter results. Behaves like log levels. 'danger' is the least verbose (warning, danger)")
auditCmd.PersistentFlags().BoolVar(&skipSslValidation, "skip-ssl-validation", false, "Skip https certificate verification")
auditCmd.PersistentFlags().BoolVar(&uploadInsights, "upload-insights", false, "Upload scan results to Fairwinds Insights")
auditCmd.PersistentFlags().StringVar(&clusterName, "cluster-name", "", "Set --cluster-name to a descriptive name for the cluster you're auditing")
auditCmd.PersistentFlags().BoolVar(&quiet, "quiet", false, "Suppress the 'upload to Insights' prompt.")
}
var auditCmd = &cobra.Command{
Use: "audit",
Short: "Runs a one-time audit.",
Long: `Runs a one-time audit.`,
Run: func(cmd *cobra.Command, args []string) {
if displayName != "" {
config.DisplayName = displayName
}
if len(checks) > 0 {
targetChecks := make(map[string]bool)
for _, check := range checks {
targetChecks[check] = true
}
for key := range config.Checks {
if isTarget := targetChecks[key]; !isTarget {
config.Checks[key] = cfg.SeverityIgnore
}
}
}
if auditNamespace != "" {
if helmChart != "" {
logrus.Warn("--namespace and --helm-chart are mutually exclusive. --namespace will be ignored.")
}
if auditPath != "" {
logrus.Warn("--namespace and --audit-path are mutually exclusive. --namespace will be ignored.")
}
config.Namespace = auditNamespace
}
if helmChart != "" {
var err error
auditPath, err = ProcessHelmTemplates(helmChart, helmValues, helmSkipTests)
if err != nil {
logrus.Errorf("Couldn't process helm chart: %v", err)
os.Exit(1)
}
}
if uploadInsights && len(clusterName) == 0 {
logrus.Error("cluster-name is required when using --upload-insights")
os.Exit(1)
}
if uploadInsights {
if auditPath != "" {
logrus.Errorf("upload-insights and audit-path are not supported when used simultaneously")
os.Exit(1)
}
if !auth.IsLoggedIn() {
err := auth.HandleLogin(insightsHost)
if err != nil {
logrus.Errorf("error handling logging: %v", err)
os.Exit(1)
}
}
}
ctx := context.TODO()
k, err := kube.CreateResourceProvider(ctx, auditPath, resourceToAudit, config)
if err != nil {
logrus.Errorf("Error fetching Kubernetes resources %v", err)
os.Exit(1)
}
auditData, err := validator.RunAudit(config, k)
if err != nil {
logrus.Errorf("Error while running audit on resources: %v", err)
os.Exit(1)
}
if uploadInsights {
auth, err := auth.GetAuth(insightsHost)
if err != nil {
logrus.Errorf("getting auth: %v", err)
os.Exit(1)
}
// fetch workloads using workload plugin... or should we adapt the workloads from above?
dynamicClient, restMapper, clientSet, host, err := kube.GetKubeClient(ctx, "")
if err != nil {
logrus.Errorf("getting the kubernetes client: %v", err)
os.Exit(1)
}
k8sResources, err := workloadsPkg.CreateResourceProviderFromAPI(ctx, dynamicClient, restMapper, clientSet, host)
if err != nil {
logrus.Errorf("creating resource provider: %v", err)
os.Exit(1)
}
insightsClient := insights.NewHTTPClient(insightsHost, auth.Organization, auth.Token)
insightsReporter := insights.NewInsightsReporter(insightsClient)
wr := insights.WorkloadsReport{Version: workloads.Version, Payload: *k8sResources}
pr := insights.PolarisReport{Version: version, Payload: auditData}
logrus.Infof("Uploading to Fairwinds Insights organization '%s/%s'...", auth.Organization, clusterName)
err = insightsReporter.ReportAuditToFairwindsInsights(clusterName, wr, pr)
if err != nil {
logrus.Errorf("reporting audit file to insights: %v", err)
os.Exit(1)
}
os.Stderr.WriteString("\n\nSuccess! You can see your results at:")
os.Stderr.WriteString(fmt.Sprintf("\n\n%s/orgs/%s/clusters/%s/action-items\n\n", insightsHost, auth.Organization, clusterName))
} else {
outputAudit(auditData, auditOutputFile, auditOutputURL, auditOutputFormat, useColor, onlyShowFailedTests, severityLevel)
if !quiet {
os.Stderr.WriteString("\n\n🚀 Upload your Polaris findings to Fairwinds Insights to see remediation advice, add teammates, integrate with Slack or Jira, and more:")
os.Stderr.WriteString("\n\n❯ polaris " + strings.Join(os.Args[1:], " ") + " --upload-insights --cluster-name=my-cluster\n\n")
}
}
summary := auditData.GetSummary()
score := summary.GetScore()
if setExitCode && summary.Dangers > 0 {
logrus.Infof("%d danger items found in audit", summary.Dangers)
os.Exit(3)
} else if minScore != 0 && score < uint(minScore) {
logrus.Infof("Audit score of %d is less than the provided minimum of %d", score, minScore)
os.Exit(4)
}
},
}
// ProcessHelmTemplates turns helm into yaml to be processed by Polaris or the other tools.
func ProcessHelmTemplates(helmChart string, helmValues []string, helmSkipTests bool) (string, error) {
cmd := exec.Command("helm", "dependency", "update", helmChart)
output, err := cmd.CombinedOutput()
if err != nil {
logrus.Error(string(output))
return "", err
}
dir, err := os.MkdirTemp("", "*")
if err != nil {
return "", err
}
params := []string{
"template", helmChart,
"--generate-name",
"--output-dir",
dir,
}
for _, v := range helmValues {
params = append(params, "--values", v)
}
if helmSkipTests {
params = append(params, "--skip-tests")
}
cmd = exec.Command("helm", params...)
output, err = cmd.CombinedOutput()
if err != nil {
logrus.Error(string(output))
return "", err
}
return dir, nil
}
func outputAudit(auditData validator.AuditData, outputFile, outputURL, outputFormat string, useColor bool, onlyShowFailedTests bool, severityLevel string) {
if onlyShowFailedTests {
auditData = auditData.RemoveSuccessfulResults()
}
if severityLevel != "" {
switch severityLevel {
case "danger":
auditData = auditData.FilterResultsBySeverityLevel(cfg.SeverityDanger)
case "warning":
auditData = auditData.FilterResultsBySeverityLevel(cfg.SeverityWarning)
}
}
var outputBytes []byte
var err error
if outputFormat == "score" {
outputBytes = []byte(fmt.Sprintf("%d\n", auditData.GetSummary().GetScore()))
} else if outputFormat == "yaml" {
var jsonBytes []byte
jsonBytes, err = json.Marshal(auditData)
if err == nil {
outputBytes, err = yaml.JSONToYAML(jsonBytes)
}
} else if outputFormat == "pretty" {
outputBytes = []byte(auditData.GetPrettyOutput(useColor))
} else {
outputBytes, err = json.MarshalIndent(auditData, "", " ")
}
if err != nil {
logrus.Errorf("Error marshalling audit: %v", err)
os.Exit(1)
}
if outputURL == "" && outputFile == "" {
os.Stdout.Write(outputBytes)
} else {
if outputURL != "" {
req, err := http.NewRequest("POST", outputURL, bytes.NewBuffer(outputBytes))
if err != nil {
logrus.Errorf("Error building request for output: %v", err)
os.Exit(1)
}
if outputFormat == "json" {
req.Header.Set("Content-Type", "application/json")
} else if outputFormat == "yaml" {
req.Header.Set("Content-Type", "application/x-yaml")
} else {
req.Header.Set("Content-Type", "text/plain")
}
client := &http.Client{}
if skipSslValidation {
transport := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
client = &http.Client{Transport: transport}
}
resp, err := client.Do(req)
if err != nil {
logrus.Errorf("Error making request for output: %v", err)
os.Exit(1)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
logrus.Errorf("Error reading response: %v", err)
os.Exit(1)
}
logrus.Infof("Received response: %v", body)
}
if outputFile != "" {
err := os.WriteFile(outputFile, outputBytes, 0644)
if err != nil {
logrus.Errorf("Error writing output to file: %v", err)
os.Exit(1)
}
}
}
}