-
Notifications
You must be signed in to change notification settings - Fork 8
/
store.go
291 lines (270 loc) · 9.21 KB
/
store.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
package report
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/kubewarden/audit-scanner/internal/constants"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
errorMachinery "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/util/retry"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
polReport "sigs.k8s.io/wg-policy-prototypes/policy-report/pkg/api/wgpolicyk8s.io/v1alpha2"
)
// PolicyReportStore caches the latest version of PolicyReports
type PolicyReportStore struct {
// For now, the store has K8s/etcd backend only
// client used to instantiate PolicyReport resources
client client.Client
}
// NewPolicyReportStore construct a PolicyReportStore, initializing the
// clusterwide ClusterPolicyReport and namesapcedPolicyReports.
func NewPolicyReportStore() (*PolicyReportStore, error) {
config := ctrl.GetConfigOrDie()
customScheme := scheme.Scheme
customScheme.AddKnownTypes(
polReport.SchemeGroupVersion,
&polReport.PolicyReport{},
&polReport.ClusterPolicyReport{},
&polReport.PolicyReportList{},
&polReport.ClusterPolicyReportList{},
)
metav1.AddToGroupVersion(customScheme, polReport.SchemeGroupVersion)
client, err := client.New(config, client.Options{Scheme: customScheme})
if err != nil {
return nil, fmt.Errorf("failed when creating new client: %w", err)
}
return &PolicyReportStore{client: client}, nil
}
// MockNewPolicyReportStore constructs a PolicyReportStore, initializing the
// clusterwide ClusterPolicyReport and namespacedPolicyReports, but setting the
// client. Useful for testing.
func MockNewPolicyReportStore(client client.Client) *PolicyReportStore {
return &PolicyReportStore{client: client}
}
// GetPolicyReport returns the Policy Report defined inside of the
// given namespace.
// An empty PolicyReport is returned when nothing is found
func (s *PolicyReportStore) GetPolicyReport(namespace string) (PolicyReport, error) {
report := polReport.PolicyReport{}
getErr := s.client.Get(context.TODO(), types.NamespacedName{
Namespace: namespace,
Name: getNamespacedReportName(namespace),
}, &report)
if getErr != nil {
if errorMachinery.IsNotFound(getErr) {
return PolicyReport{}, constants.ErrResourceNotFound
}
return PolicyReport{}, getErr
}
policyReport := &PolicyReport{
report,
}
log.Debug().Dict("dict", zerolog.Dict().
Str("report name", report.GetName()).
Str("report ns", report.GetNamespace()).
Str("report resourceVersion", report.GetResourceVersion())).
Msg("PolicyReport found")
return *policyReport, nil
}
// Get the ClusterPolicyReport
func (s *PolicyReportStore) GetClusterPolicyReport(name string) (ClusterPolicyReport, error) {
result := polReport.ClusterPolicyReport{}
if !strings.HasPrefix(name, PrefixNameClusterPolicyReport) {
name = getClusterReportName(name)
}
getErr := s.client.Get(context.Background(), client.ObjectKey{Name: name}, &result)
if getErr != nil {
if errorMachinery.IsNotFound(getErr) {
return ClusterPolicyReport{}, constants.ErrResourceNotFound
}
return ClusterPolicyReport{}, getErr
}
return ClusterPolicyReport{
result,
}, nil
}
// Update namespaced PolicyReport
func (s *PolicyReportStore) UpdatePolicyReport(report *PolicyReport) error {
err := s.client.Update(context.Background(), &report.PolicyReport)
if err != nil {
return err
}
summary, _ := report.GetSummaryJSON()
log.Info().
Dict("dict", zerolog.Dict().
Str("report name", report.GetName()).
Str("report ns", report.GetNamespace()).
Str("report resourceVersion", report.GetResourceVersion()).
Str("summary", summary),
).Msg("updated PolicyReport")
return nil
}
// Update ClusterPolicyReport or PolicyReport. ns argument is used in case
// of namespaced PolicyReport
func (s *PolicyReportStore) UpdateClusterPolicyReport(report *ClusterPolicyReport) error {
err := s.client.Update(context.Background(), &report.ClusterPolicyReport)
if err != nil {
return err
}
summary, _ := report.GetSummaryJSON()
log.Info().
Dict("dict", zerolog.Dict().
Str("report name", report.GetName()).
Str("report ns", report.GetNamespace()).
Str("summary", summary),
).Msg("updated ClusterPolicyReport")
return nil
}
// Delete PolicyReport by namespace
func (s *PolicyReportStore) RemovePolicyReport(namespace string) error {
if report, err := s.GetPolicyReport(namespace); err == nil {
err := s.client.Delete(context.Background(), &report.PolicyReport)
if err != nil {
return err
}
}
return nil
}
// Delete all namespaced PolicyReports
func (s *PolicyReportStore) RemoveAllNamespacedPolicyReports() error {
err := s.client.DeleteAllOf(context.Background(), &polReport.PolicyReport{},
client.MatchingLabels(map[string]string{
LabelAppManagedBy: LabelApp,
}))
if err != nil {
return err
}
return nil
}
// createPolicyReport should not be called directly. Use the SavePolicyReport
func (s *PolicyReportStore) createPolicyReport(report *PolicyReport) error {
err := s.client.Create(context.Background(), &report.PolicyReport)
if err != nil {
return fmt.Errorf("create failed: %w", err)
}
summary, _ := report.GetSummaryJSON()
log.Info().
Dict("dict", zerolog.Dict().
Str("report name", report.GetName()).
Str("report ns", report.GetNamespace()).
Str("summary", summary),
).Msg("created PolicyReport")
return nil
}
// createClusterPolicyReport should not be called directly. Use the SaveClusterPolicyReport
func (s *PolicyReportStore) createClusterPolicyReport(report *ClusterPolicyReport) error {
err := s.client.Create(context.Background(), &report.ClusterPolicyReport)
if err != nil {
return fmt.Errorf("create failed: %w", err)
}
summary, _ := report.GetSummaryJSON()
log.Info().
Dict("dict", zerolog.Dict().
Str("report name", report.GetName()).
Str("report ns", report.GetNamespace()).
Str("summary", summary),
).Msg("created ClusterPolicyReport")
return nil
}
// SavePolicyReport instantiates the passed namespaced PolicyReport if it doesn't exist, or
// updates it if one is found
func (s *PolicyReportStore) SavePolicyReport(report *PolicyReport) error {
// Check for existing Policy Report
_, getErr := s.GetPolicyReport(report.GetNamespace())
if getErr != nil {
// Create new Policy Report if not found
if errors.Is(getErr, constants.ErrResourceNotFound) {
return s.createPolicyReport(report)
}
return getErr
}
// Update existing Policy Report
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
// get the latest report version to be updated
latestReport, err := s.GetPolicyReport(report.GetNamespace())
if err != nil {
return err
}
latestReport.Summary = report.Summary
latestReport.Results = report.Results
return s.UpdatePolicyReport(&latestReport)
})
if retryErr != nil {
return fmt.Errorf("update failed: %w", retryErr)
}
return nil
}
// SavePolicyClusterPolicyReport instantiates the ClusterPolicyReport if it doesn't exist, or
// updates it one is found
func (s *PolicyReportStore) SaveClusterPolicyReport(report *ClusterPolicyReport) error {
// Check for existing Policy Report
_, getErr := s.GetClusterPolicyReport(report.GetName())
if getErr != nil {
// Create new Policy Report if not found
if errors.Is(getErr, constants.ErrResourceNotFound) {
return s.createClusterPolicyReport(report)
}
return getErr
}
// Update existing Policy Report
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
// get the latest report version to be updated
latestReport, err := s.GetClusterPolicyReport(report.GetName())
if err != nil {
return err
}
latestReport.Summary = report.Summary
latestReport.Results = report.Results
return s.UpdateClusterPolicyReport(&latestReport)
})
if retryErr != nil {
return fmt.Errorf("update failed: %w", retryErr)
}
return nil
}
// listPolicyReports returns all the Policy Reports
// An empty PolicyReport list is returned when nothing is found or an error happens
func (s *PolicyReportStore) listPolicyReports() ([]PolicyReport, error) {
reportList := polReport.PolicyReportList{}
err := s.client.List(context.Background(), &reportList, &client.ListOptions{
LabelSelector: labels.SelectorFromSet(labels.Set{LabelAppManagedBy: LabelApp}),
})
if err != nil {
if errorMachinery.IsNotFound(err) {
return []PolicyReport{}, constants.ErrResourceNotFound
}
return []PolicyReport{}, err
}
results := make([]PolicyReport, 0, len(reportList.Items))
for _, item := range reportList.Items {
results = append(results, PolicyReport{item})
}
return results, nil
}
// Marshal the contents of the store into a JSON string
func (s *PolicyReportStore) ToJSON() (string, error) {
recapJSON := make(map[string]interface{})
clusterReport, err := s.GetClusterPolicyReport(constants.DefaultClusterwideReportName)
if err != nil {
log.Error().Err(err).Msg("error fetching ClusterPolicyReport. Ignoring this error to allow user to read the namespaced reports")
}
recapJSON["cluster"] = clusterReport
nsReports, err := s.listPolicyReports()
if err != nil {
return "", err
}
recapJSON["namespaces"] = nsReports
marshaled, err := json.Marshal(recapJSON)
if err != nil {
return "", err
}
return string(marshaled), nil
}