Skip to content

Commit d75a97d

Browse files
Replace kube-rbac-proxy to ensure the same level of protection with controller-runtime feature
Utilise Controller-Runtime's WithAuthenticationAndAuthorization feature to protect the metrics endpoint. This approach provides access control, similar to the functionality of kube-rbac-proxy. kube-rbac-proxy image from gcr.io/kubebuilder/kube-rbac-proxy is deprecated and should no longer be used More info: kubernetes-sigs/kubebuilder#3907
1 parent 53f15b5 commit d75a97d

File tree

8 files changed

+76
-30
lines changed

8 files changed

+76
-30
lines changed

cmd/manager/main.go

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ package main
1818

1919
import (
2020
"context"
21+
"crypto/tls"
2122
"flag"
2223
"fmt"
24+
"log"
2325
"net/http"
2426
"os"
2527
"path/filepath"
@@ -41,9 +43,11 @@ import (
4143
"k8s.io/klog/v2/textlogger"
4244
ctrl "sigs.k8s.io/controller-runtime"
4345
crcache "sigs.k8s.io/controller-runtime/pkg/cache"
46+
"sigs.k8s.io/controller-runtime/pkg/certwatcher"
4447
"sigs.k8s.io/controller-runtime/pkg/client"
4548
crfinalizer "sigs.k8s.io/controller-runtime/pkg/finalizer"
4649
"sigs.k8s.io/controller-runtime/pkg/healthz"
50+
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
4751
"sigs.k8s.io/controller-runtime/pkg/metrics/server"
4852

4953
catalogd "github.com/operator-framework/catalogd/api/v1"
@@ -70,6 +74,7 @@ import (
7074
var (
7175
setupLog = ctrl.Log.WithName("setup")
7276
defaultSystemNamespace = "olmv1-system"
77+
certWatcher *certwatcher.CertWatcher
7378
)
7479

7580
const authFilePrefix = "operator-controller-global-pull-secrets"
@@ -89,6 +94,8 @@ func podNamespace() string {
8994
func main() {
9095
var (
9196
metricsAddr string
97+
certFile string
98+
keyFile string
9299
enableLeaderElection bool
93100
probeAddr string
94101
cachePath string
@@ -97,9 +104,11 @@ func main() {
97104
caCertDir string
98105
globalPullSecret string
99106
)
100-
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
107+
flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address for the metrics endpoint. Use :8443 for HTTPS or set to 0 to disable. Requires both tls-cert and tls-key.")
101108
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
102109
flag.StringVar(&caCertDir, "ca-certs-dir", "", "The directory of TLS certificate to use for verifying HTTPS connections to the Catalogd and docker-registry web servers.")
110+
flag.StringVar(&certFile, "tls-cert", "", "The certificate file used for serving metrics contents over HTTPS. Requires tls-key.")
111+
flag.StringVar(&keyFile, "tls-key", "", "The key file used for serving metrics contents over HTTPS. Requires tls-cert.")
103112
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
104113
"Enable leader election for controller manager. "+
105114
"Enabling this will ensure there is only one active controller manager.")
@@ -119,6 +128,11 @@ func main() {
119128
os.Exit(0)
120129
}
121130

131+
if (certFile != "" && keyFile == "") || (certFile == "" && keyFile != "") {
132+
setupLog.Error(nil, "unable to configure TLS certificates: tls-cert and tls-key flags must be used together")
133+
os.Exit(1)
134+
}
135+
122136
ctrl.SetLogger(textlogger.NewLogger(textlogger.NewConfig()))
123137

124138
setupLog.Info("starting up the controller", "version info", version.String())
@@ -161,9 +175,38 @@ func main() {
161175
},
162176
}
163177
}
178+
179+
// Force serving be disabled by default if no certs are provided
180+
metricsServerOptions := server.Options{
181+
BindAddress: "0",
182+
}
183+
184+
if len(certFile) > 0 && len(keyFile) > 0 {
185+
setupLog.Info("Starting metrics server with TLS enabled.")
186+
187+
metricsServerOptions.BindAddress = metricsAddr
188+
metricsServerOptions.SecureServing = true
189+
metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
190+
191+
setupLog.Info("Using provided TLS certificate and key files for the metrics server.",
192+
"certFile", certFile, "keyFile", keyFile)
193+
194+
// If the certificate files change, the watcher will reload them.
195+
var err error
196+
certWatcher, err = certwatcher.New(certFile, keyFile)
197+
if err != nil {
198+
log.Fatalf("Failed to initialize certificate watcher: %v", err)
199+
}
200+
metricsServerOptions.TLSOpts = append(metricsServerOptions.TLSOpts, func(config *tls.Config) {
201+
config.GetCertificate = certWatcher.GetCertificate
202+
})
203+
} else {
204+
setupLog.Info("WARNING: Metrics Server will not be serving")
205+
}
206+
164207
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
165208
Scheme: scheme.Scheme,
166-
Metrics: server.Options{BindAddress: metricsAddr},
209+
Metrics: metricsServerOptions,
167210
HealthProbeBindAddress: probeAddr,
168211
LeaderElection: enableLeaderElection,
169212
LeaderElectionID: "9c4404e7.operatorframework.io",
@@ -220,6 +263,14 @@ func main() {
220263
os.Exit(1)
221264
}
222265

266+
if certWatcher != nil {
267+
setupLog.Info("Adding certificate watcher to manager")
268+
if err := mgr.Add(certWatcher); err != nil {
269+
setupLog.Error(err, "unable to add certificate watcher to manager")
270+
os.Exit(1)
271+
}
272+
}
273+
223274
unpacker := &source.ContainersImageRegistry{
224275
BaseCachePath: filepath.Join(cachePath, "unpack"),
225276
SourceContextFunc: func(logger logr.Logger) (*types.SystemContext, error) {

config/base/manager/manager.yaml

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,12 @@ spec:
5252
- /manager
5353
args:
5454
- "--health-probe-bind-address=:8081"
55-
- "--metrics-bind-address=127.0.0.1:8080"
55+
- "--metrics-bind-address=:8443"
5656
- "--leader-elect"
57+
ports:
58+
- containerPort: 8443
59+
protocol: TCP
60+
name: https
5761
image: controller:latest
5862
imagePullPolicy: IfNotPresent
5963
name: manager
@@ -84,27 +88,6 @@ spec:
8488
cpu: 10m
8589
memory: 64Mi
8690
terminationMessagePolicy: FallbackToLogsOnError
87-
- name: kube-rbac-proxy
88-
securityContext:
89-
allowPrivilegeEscalation: false
90-
capabilities:
91-
drop:
92-
- "ALL"
93-
image: gcr.io/kubebuilder/kube-rbac-proxy:v0.15.0
94-
args:
95-
- --secure-listen-address=0.0.0.0:8443
96-
- --http2-disable
97-
- --upstream=http://127.0.0.1:8080/
98-
- --logtostderr=true
99-
ports:
100-
- containerPort: 8443
101-
protocol: TCP
102-
name: https
103-
resources:
104-
requests:
105-
cpu: 5m
106-
memory: 64Mi
107-
terminationMessagePolicy: FallbackToLogsOnError
10891
serviceAccountName: operator-controller-controller-manager
10992
terminationGracePeriodSeconds: 10
11093
volumes:

config/base/rbac/kustomization.yaml

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,14 @@ resources:
1717
- extension_editor_role.yaml
1818
- extension_viewer_role.yaml
1919

20-
# Comment the following 4 lines if you want to disable
21-
# the auth proxy (https://github.com/brancz/kube-rbac-proxy)
22-
# which protects your /metrics endpoint.
20+
# The following RBAC configurations are used to protect
21+
# the metrics endpoint with authn/authz. These configurations
22+
# ensure that only authorized users and service accounts
23+
# can access the metrics endpoint. Comment the following
24+
# permissions if you want to disable this protection.
25+
# More info: https://book.kubebuilder.io/reference/metrics.html
2326
- auth_proxy_service.yaml
2427
- auth_proxy_role.yaml
2528
- auth_proxy_role_binding.yaml
2629
- auth_proxy_client_clusterrole.yaml
30+

config/components/coverage/manager_e2e_coverage_patch.yaml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ spec:
77
template:
88
spec:
99
containers:
10-
- name: kube-rbac-proxy
1110
- name: manager
1211
env:
1312
- name: GOCOVERDIR

config/components/registries-conf/manager_e2e_registries_conf_patch.yaml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ spec:
77
template:
88
spec:
99
containers:
10-
- name: kube-rbac-proxy
1110
- name: manager
1211
volumeMounts:
1312
- name: e2e-registries-conf
Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
- op: add
22
path: /spec/template/spec/volumes/-
3-
value: {"name":"olmv1-certificate", "secret":{"secretName":"olmv1-cert", "optional": false, "items": [{"key": "ca.crt", "path": "olm-ca.crt"}]}}
3+
value: {"name":"olmv1-certificate", "secret":{"secretName":"olmv1-cert", "optional": false, "items": [{"key": "ca.crt", "path": "olm-ca.crt"}, {"key": "tls.crt", "path": "tls.cert"}, {"key": "tls.key", "path": "tls.key"}]}}
44
- op: add
55
path: /spec/template/spec/containers/0/volumeMounts/-
66
value: {"name":"olmv1-certificate", "readOnly": true, "mountPath":"/var/certs/"}
77
- op: add
88
path: /spec/template/spec/containers/0/args/-
99
value: "--ca-certs-dir=/var/certs"
10+
- op: add
11+
path: /spec/template/spec/containers/0/args/-
12+
value: "--tls-cert=/var/certs/tls.cert"
13+
- op: add
14+
path: /spec/template/spec/containers/0/args/-
15+
value: "--tls-key=/var/certs/tls.key"

config/components/tls/resources/manager_cert.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ spec:
77
dnsNames:
88
- operator-controller.olmv1-system.svc
99
- operator-controller.olmv1-system.svc.cluster.local
10+
- operator-controller-controller-manager-metrics-service.olmv1-system.svc
11+
- operator-controller-controller-manager-metrics-service.olmv1-system.svc.cluster.local
1012
privateKey:
1113
algorithm: ECDSA
1214
size: 256

testdata/build-test-registry.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ spec:
4242
dnsNames:
4343
- ${name}.${namespace}.svc
4444
- ${name}.${namespace}.svc.cluster.local
45+
- controller-manager-metrics-service.${namespace}.svc
46+
- controller-manager-metrics-service.${namespace}.svc.cluster.local
4547
privateKey:
4648
algorithm: ECDSA
4749
size: 256

0 commit comments

Comments
 (0)