/
common.go
79 lines (67 loc) · 1.99 KB
/
common.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
package fetchfixes
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
k8sserial "k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/cli-runtime/pkg/genericclioptions"
"github.com/openshift/oc-compliance/internal/common"
)
const roleKey = "machineconfiguration.openshift.io/role"
type FixPersister struct {
outputPath string
mcRoles []string
genericclioptions.IOStreams
}
func (fp *FixPersister) handleObjectPersistence(ys *k8sserial.Serializer, fileNameBase string, fix *unstructured.Unstructured) error {
// TODO: Handle enforcement remediations... This should probably
// be done via a cmd-line flag to detect which type to use.
if isEnforcementRemediation(fix) {
return nil
}
if fix.GetKind() == "MachineConfig" {
for _, role := range fp.mcRoles {
handleMCMetadata(fix, fileNameBase, role)
fileWithRole := fmt.Sprintf("%s-%s", role, fileNameBase)
err := fp.persistFix(ys, fileWithRole, fix)
if err != nil {
return err
}
}
return nil
}
err := fp.persistFix(ys, fileNameBase, fix)
if err != nil {
return err
}
return nil
}
func (fp *FixPersister) persistFix(ys *k8sserial.Serializer, fileNameBase string, fix *unstructured.Unstructured) error {
path, err := common.PersistObjectToYamlFile(fileNameBase, fix, fp.outputPath, ys)
if err != nil {
return err
}
fmt.Fprintf(fp.Out, "Persisted rule fix to %s\n", path)
return nil
}
func handleMCMetadata(obj *unstructured.Unstructured, baseName, role string) {
// priority, name and role
obj.SetName(fmt.Sprintf("75-%s-%s", role, baseName))
if len(obj.GetLabels()) == 0 {
obj.SetLabels(make(map[string]string))
}
labels := obj.GetLabels()
labels[roleKey] = role
obj.SetLabels(labels)
}
func isEnforcementRemediation(obj *unstructured.Unstructured) bool {
if len(obj.GetAnnotations()) == 0 {
return false
}
anns := obj.GetAnnotations()
rtype, ok := anns["complianceascode.io/remediation-type"]
if !ok {
return false
}
return strings.EqualFold(rtype, "Enforcement")
}