-
Notifications
You must be signed in to change notification settings - Fork 46
/
privileged_namespaces_controller.go
72 lines (60 loc) · 2.11 KB
/
privileged_namespaces_controller.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
package psalabelsyncer
import (
"context"
"fmt"
"time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1apply "k8s.io/client-go/applyconfigurations/core/v1"
corev1informers "k8s.io/client-go/informers/core/v1"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
corev1listers "k8s.io/client-go/listers/core/v1"
psapi "k8s.io/pod-security-admission/api"
"github.com/openshift/library-go/pkg/controller/factory"
"github.com/openshift/library-go/pkg/operator/events"
)
const privilegedControllerName = "privileged-namespaces-psa-label-syncer"
type privilegedNamespacesPSALabelSyncer struct {
nsClient corev1client.NamespaceInterface
nsLister corev1listers.NamespaceLister
}
func NewPrivilegedNamespacesPSALabelSyncer(
namespaceClient corev1client.NamespaceInterface,
namespaceInformer corev1informers.NamespaceInformer,
eventRecorder events.Recorder,
) factory.Controller {
c := &privilegedNamespacesPSALabelSyncer{
nsClient: namespaceClient,
nsLister: namespaceInformer.Lister(),
}
return factory.New().
WithSync(c.sync).
WithFilteredEventsInformersQueueKeyFunc(
factory.ObjectNameToKey,
factory.NamesFilter("default", "kube-system", "kube-public"),
namespaceInformer.Informer(),
).
ResyncEvery(1*time.Hour).
ToController(
privilegedControllerName,
eventRecorder.WithComponentSuffix(privilegedControllerName),
)
}
func (c *privilegedNamespacesPSALabelSyncer) sync(ctx context.Context, controllerCtx factory.SyncContext) error {
qKey := controllerCtx.QueueKey()
ns, err := c.nsLister.Get(qKey)
if err != nil {
return fmt.Errorf("failed to retrieve ns %q: %w", qKey, err)
}
if ns.Labels[psapi.EnforceLevelLabel] == "privileged" &&
ns.Labels[psapi.WarnLevelLabel] == "privileged" &&
ns.Labels[psapi.AuditLevelLabel] == "privileged" {
return nil
}
nsApplyConfig := corev1apply.Namespace(ns.Name).WithLabels(map[string]string{
psapi.EnforceLevelLabel: "privileged",
psapi.WarnLevelLabel: "privileged",
psapi.AuditLevelLabel: "privileged",
})
_, err = c.nsClient.Apply(ctx, nsApplyConfig, v1.ApplyOptions{FieldManager: privilegedControllerName, Force: true})
return err
}