Skip to content

Commit 908d317

Browse files
authored
chore: re-scaffold project (#109)
## Issue #108 ## Description This PR re-scaffolds the project using `kubebuilder alpha generate`. The 2 major changes are: - Remove all usage of `kube-rbac-proxy` and replace with [WithAuthenticationAndAuthorization ](https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/metrics/filters#WithAuthenticationAndAuthorization) due to `kube-rbac-proxy` being deprecated - Initialize e2e tests. For now, we are only testing basic functionality. The tests should be expanded to cover validator-specific use-cases. --------- Signed-off-by: Artur Shad Nik <[email protected]>
1 parent 1ecb02f commit 908d317

30 files changed

+1119
-273
lines changed

.golangci.yml

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ issues:
66
# don't skip warning about doc comments
77
# don't exclude the default set of lint
88
exclude-use-default: false
9+
# restore some of the defaults
10+
# (fill in the rest as needed)
11+
exclude-dirs:
12+
- tests
913
exclude-files:
1014
- ".*_test\\.go"
1115

@@ -14,7 +18,7 @@ linters:
1418
enable:
1519
- dupl
1620
- errcheck
17-
- exportloopref
21+
- copyloopvar
1822
- ginkgolinter
1923
- goconst
2024
- gocyclo
@@ -32,3 +36,8 @@ linters:
3236
- unconvert
3337
- unparam
3438
- unused
39+
40+
linters-settings:
41+
revive:
42+
rules:
43+
- name: comment-spacings

api/v1alpha1/kubescapevalidator_types.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import (
2727

2828
// KubescapeValidatorSpec defines the desired state of KubescapeValidator
2929
type KubescapeValidatorSpec struct {
30-
//+kubebuilder:default=kubescape
30+
// +kubebuilder:default=kubescape
3131
Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
3232
// Global Severity Limit Rule
3333
SeverityLimitRule SeverityLimitRule `json:"severityLimitRule,omitempty" yaml:"severityLimitRule,omitempty"`
@@ -76,8 +76,8 @@ type KubescapeValidatorStatus struct {
7676
// Important: Run "make" to regenerate code after modifying this file
7777
}
7878

79-
//+kubebuilder:object:root=true
80-
//+kubebuilder:subresource:status
79+
// +kubebuilder:object:root=true
80+
// +kubebuilder:subresource:status
8181

8282
// KubescapeValidator is the Schema for the kubescapevalidators API
8383
type KubescapeValidator struct {
@@ -88,7 +88,7 @@ type KubescapeValidator struct {
8888
Status KubescapeValidatorStatus `json:"status,omitempty"`
8989
}
9090

91-
//+kubebuilder:object:root=true
91+
// +kubebuilder:object:root=true
9292

9393
// KubescapeValidatorList contains a list of KubescapeValidator
9494
type KubescapeValidatorList struct {

chart/validator-plugin-kubescape/README.md

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,7 @@ The following table lists the configurable parameters of the Validator-plugin-ku
1111

1212
| Parameter | Description | Default |
1313
| ------------------------ | ----------------------- | -------------- |
14-
| `controllerManager.kubeRbacProxy.args` | | `["--secure-listen-address=0.0.0.0:8443", "--upstream=http://127.0.0.1:8080/", "--logtostderr=true", "--v=0"]` |
15-
| `controllerManager.kubeRbacProxy.containerSecurityContext.allowPrivilegeEscalation` | | `false` |
16-
| `controllerManager.kubeRbacProxy.containerSecurityContext.capabilities.drop` | | `["ALL"]` |
17-
| `controllerManager.kubeRbacProxy.image.repository` | | `"gcr.io/kubebuilder/kube-rbac-proxy"` |
18-
| `controllerManager.kubeRbacProxy.image.tag` | | `"v0.16.0"` |
19-
| `controllerManager.kubeRbacProxy.resources.limits.cpu` | | `"500m"` |
20-
| `controllerManager.kubeRbacProxy.resources.limits.memory` | | `"128Mi"` |
21-
| `controllerManager.kubeRbacProxy.resources.requests.cpu` | | `"5m"` |
22-
| `controllerManager.kubeRbacProxy.resources.requests.memory` | | `"64Mi"` |
23-
| `controllerManager.manager.args` | | `["--health-probe-bind-address=:8081", "--leader-elect"]` |
14+
| `controllerManager.manager.args` | | `["--health-probe-bind-address=:8081", "--metrics-bind-address=:8443", "--leader-elect"]` |
2415
| `controllerManager.manager.containerSecurityContext.allowPrivilegeEscalation` | | `false` |
2516
| `controllerManager.manager.containerSecurityContext.capabilities.drop` | | `["ALL"]` |
2617
| `controllerManager.manager.image.repository` | | `"quay.io/validator-labs/validator-plugin-kubescape"` |

chart/validator-plugin-kubescape/crds/validation.spectrocloud.labs_kubescapevalidators.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
33
kind: CustomResourceDefinition
44
metadata:
55
annotations:
6-
controller-gen.kubebuilder.io/version: v0.15.0
6+
controller-gen.kubebuilder.io/version: v0.16.4
77
name: kubescapevalidators.validation.spectrocloud.labs
88
spec:
99
group: validation.spectrocloud.labs

chart/validator-plugin-kubescape/templates/deployment.yaml

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,6 @@ spec:
2626
kubectl.kubernetes.io/default-container: manager
2727
spec:
2828
containers:
29-
- args: {{- toYaml .Values.controllerManager.kubeRbacProxy.args | nindent 8 }}
30-
env:
31-
- name: KUBERNETES_CLUSTER_DOMAIN
32-
value: {{ quote .Values.kubernetesClusterDomain }}
33-
image: {{ .Values.controllerManager.kubeRbacProxy.image.repository }}:{{ .Values.controllerManager.kubeRbacProxy.image.tag | default .Chart.AppVersion }}
34-
name: kube-rbac-proxy
35-
ports:
36-
- containerPort: 8443
37-
name: https
38-
protocol: TCP
39-
resources: {{- toYaml .Values.controllerManager.kubeRbacProxy.resources | nindent 10 }}
40-
securityContext: {{- toYaml .Values.controllerManager.kubeRbacProxy.containerSecurityContext | nindent 10 }}
4129
- args: {{- toYaml .Values.controllerManager.manager.args | nindent 8 }}
4230
command:
4331
- /manager

chart/validator-plugin-kubescape/templates/proxy-rbac.yaml renamed to chart/validator-plugin-kubescape/templates/metrics-auth-rbac.yaml

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
apiVersion: rbac.authorization.k8s.io/v1
22
kind: ClusterRole
33
metadata:
4-
name: {{ include "chart.fullname" . }}-proxy-role
4+
name: {{ include "chart.fullname" . }}-metrics-auth-role
55
labels:
6-
app.kubernetes.io/component: kube-rbac-proxy
7-
app.kubernetes.io/created-by: validator-plugin-kubescape
8-
app.kubernetes.io/part-of: validator-plugin-kubescape
96
{{- include "chart.labels" . | nindent 4 }}
107
rules:
118
- apiGroups:
@@ -24,16 +21,13 @@ rules:
2421
apiVersion: rbac.authorization.k8s.io/v1
2522
kind: ClusterRoleBinding
2623
metadata:
27-
name: {{ include "chart.fullname" . }}-proxy-rolebinding
24+
name: {{ include "chart.fullname" . }}-metrics-auth-rolebinding
2825
labels:
29-
app.kubernetes.io/component: kube-rbac-proxy
30-
app.kubernetes.io/created-by: validator-plugin-kubescape
31-
app.kubernetes.io/part-of: validator-plugin-kubescape
3226
{{- include "chart.labels" . | nindent 4 }}
3327
roleRef:
3428
apiGroup: rbac.authorization.k8s.io
3529
kind: ClusterRole
36-
name: '{{ include "chart.fullname" . }}-proxy-role'
30+
name: '{{ include "chart.fullname" . }}-metrics-auth-role'
3731
subjects:
3832
- kind: ServiceAccount
3933
name: '{{ include "chart.fullname" . }}-controller-manager'

chart/validator-plugin-kubescape/values.yaml

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,8 @@
11
controllerManager:
2-
kubeRbacProxy:
3-
args:
4-
- --secure-listen-address=0.0.0.0:8443
5-
- --upstream=http://127.0.0.1:8080/
6-
- --logtostderr=true
7-
- --v=0
8-
containerSecurityContext:
9-
allowPrivilegeEscalation: false
10-
capabilities:
11-
drop:
12-
- ALL
13-
image:
14-
repository: gcr.io/kubebuilder/kube-rbac-proxy
15-
tag: v0.16.0
16-
resources:
17-
limits:
18-
cpu: 500m
19-
memory: 128Mi
20-
requests:
21-
cpu: 5m
22-
memory: 64Mi
232
manager:
243
args:
254
- --health-probe-bind-address=:8081
5+
- --metrics-bind-address=:8443
266
- --leader-elect
277
containerSecurityContext:
288
allowPrivilegeEscalation: false

cmd/main.go

Lines changed: 69 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17-
// Package main initializes a KubescapeValidator controller.
1817
package main
1918

2019
import (
20+
"crypto/tls"
2121
"flag"
2222
"os"
2323

@@ -31,11 +31,14 @@ import (
3131
ctrl "sigs.k8s.io/controller-runtime"
3232
"sigs.k8s.io/controller-runtime/pkg/healthz"
3333
"sigs.k8s.io/controller-runtime/pkg/log/zap"
34+
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
35+
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
36+
"sigs.k8s.io/controller-runtime/pkg/webhook"
3437

35-
validationv1 "github.com/validator-labs/validator-plugin-kubescape/api/v1alpha1"
38+
validationv1alpha1 "github.com/validator-labs/validator-plugin-kubescape/api/v1alpha1"
3639
"github.com/validator-labs/validator-plugin-kubescape/internal/controller"
3740
validatorv1alpha1 "github.com/validator-labs/validator/api/v1alpha1"
38-
//+kubebuilder:scaffold:imports
41+
// +kubebuilder:scaffold:imports
3942
)
4043

4144
var (
@@ -45,23 +48,28 @@ var (
4548

4649
func init() {
4750
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
48-
49-
utilruntime.Must(validationv1.AddToScheme(scheme))
50-
5151
utilruntime.Must(validatorv1alpha1.AddToScheme(scheme))
52-
53-
//+kubebuilder:scaffold:scheme
52+
utilruntime.Must(validationv1alpha1.AddToScheme(scheme))
53+
// +kubebuilder:scaffold:scheme
5454
}
5555

5656
func main() {
5757
var metricsAddr string
5858
var enableLeaderElection bool
5959
var probeAddr string
60-
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
60+
var secureMetrics bool
61+
var enableHTTP2 bool
62+
var tlsOpts []func(*tls.Config)
63+
flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+
64+
"Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.")
6165
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
6266
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
6367
"Enable leader election for controller manager. "+
6468
"Enabling this will ensure there is only one active controller manager.")
69+
flag.BoolVar(&secureMetrics, "metrics-secure", true,
70+
"If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.")
71+
flag.BoolVar(&enableHTTP2, "enable-http2", false,
72+
"If set, HTTP/2 will be enabled for the metrics and webhook servers")
6573
opts := zap.Options{
6674
Development: true,
6775
}
@@ -70,11 +78,61 @@ func main() {
7078

7179
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
7280

81+
// if the enable-http2 flag is false (the default), http/2 should be disabled
82+
// due to its vulnerabilities. More specifically, disabling http/2 will
83+
// prevent from being vulnerable to the HTTP/2 Stream Cancellation and
84+
// Rapid Reset CVEs. For more information see:
85+
// - https://github.com/advisories/GHSA-qppj-fm5r-hxr3
86+
// - https://github.com/advisories/GHSA-4374-p667-p6c8
87+
disableHTTP2 := func(c *tls.Config) {
88+
setupLog.Info("disabling http/2")
89+
c.NextProtos = []string{"http/1.1"}
90+
}
91+
92+
if !enableHTTP2 {
93+
tlsOpts = append(tlsOpts, disableHTTP2)
94+
}
95+
96+
webhookServer := webhook.NewServer(webhook.Options{
97+
TLSOpts: tlsOpts,
98+
})
99+
100+
// Metrics endpoint is enabled in 'config/default/kustomization.yaml'. The Metrics options configure the server.
101+
// More info:
102+
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/metrics/server
103+
// - https://book.kubebuilder.io/reference/metrics.html
104+
metricsServerOptions := metricsserver.Options{
105+
BindAddress: metricsAddr,
106+
SecureServing: secureMetrics,
107+
TLSOpts: tlsOpts,
108+
}
109+
110+
if secureMetrics {
111+
// FilterProvider is used to protect the metrics endpoint with authn/authz.
112+
// These configurations ensure that only authorized users and service accounts
113+
// can access the metrics endpoint. The RBAC are configured in 'config/rbac/kustomization.yaml'. More info:
114+
// https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/metrics/filters#WithAuthenticationAndAuthorization
115+
metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
116+
117+
// TODO(user): If CertDir, CertName, and KeyName are not specified, controller-runtime will automatically
118+
// generate self-signed certificates for the metrics server. While convenient for development and testing,
119+
// this setup is not recommended for production.
120+
121+
// TODO(user): If cert-manager is enabled in config/default/kustomization.yaml,
122+
// you can uncomment the following lines to use the certificate managed by cert-manager.
123+
124+
// metricsServerOptions.CertDir = "/tmp/k8s-metrics-server/metrics-certs"
125+
// metricsServerOptions.CertName = "tls.crt"
126+
// metricsServerOptions.KeyName = "tls.key"
127+
}
128+
73129
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
74130
Scheme: scheme,
131+
Metrics: metricsServerOptions,
132+
WebhookServer: webhookServer,
75133
HealthProbeBindAddress: probeAddr,
76134
LeaderElection: enableLeaderElection,
77-
LeaderElectionID: "21f802fb.spectrocloud.labs",
135+
LeaderElectionID: "cf0b361a.spectrocloud.labs",
78136
// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
79137
// when the Manager ends. This requires the binary to immediately end when the
80138
// Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
@@ -100,7 +158,7 @@ func main() {
100158
setupLog.Error(err, "unable to create controller", "controller", "KubescapeValidator")
101159
os.Exit(1)
102160
}
103-
//+kubebuilder:scaffold:builder
161+
// +kubebuilder:scaffold:builder
104162

105163
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
106164
setupLog.Error(err, "unable to set up health check")

config/crd/bases/validation.spectrocloud.labs_kubescapevalidators.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
33
kind: CustomResourceDefinition
44
metadata:
55
annotations:
6-
controller-gen.kubebuilder.io/version: v0.15.0
6+
controller-gen.kubebuilder.io/version: v0.16.4
77
name: kubescapevalidators.validation.spectrocloud.labs
88
spec:
99
group: validation.spectrocloud.labs

0 commit comments

Comments
 (0)