-
Notifications
You must be signed in to change notification settings - Fork 451
/
reconciler.go
177 lines (148 loc) · 6.54 KB
/
reconciler.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
// Copyright 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package csrapprover
import (
"context"
"crypto/x509"
"fmt"
"strings"
machinev1alpha1 "github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1"
certificatesv1 "k8s.io/api/certificates/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apiserver/pkg/authentication/user"
certificatesclientv1 "k8s.io/client-go/kubernetes/typed/certificates/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/gardener/gardener/pkg/client/kubernetes"
"github.com/gardener/gardener/pkg/controllerutils"
"github.com/gardener/gardener/pkg/resourcemanager/apis/config"
"github.com/gardener/gardener/pkg/utils"
)
// Reconciler reconciles CertificateSigningRequest objects.
type Reconciler struct {
SourceClient client.Client
TargetClient client.Client
CertificatesClient certificatesclientv1.CertificateSigningRequestInterface
Config config.KubeletCSRApproverControllerConfig
}
// Reconcile performs the main reconciliation logic.
func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
log := logf.FromContext(ctx)
ctx, cancel := controllerutils.GetMainReconciliationContext(ctx, controllerutils.DefaultReconciliationTimeout)
defer cancel()
csr := &certificatesv1.CertificateSigningRequest{}
if err := r.TargetClient.Get(ctx, request.NamespacedName, csr); err != nil {
if apierrors.IsNotFound(err) {
log.V(1).Info("Object is gone, stop reconciling")
return reconcile.Result{}, nil
}
return reconcile.Result{}, fmt.Errorf("error retrieving object from store: %w", err)
}
var (
isInFinalState bool
finalState string
)
for _, c := range csr.Status.Conditions {
if c.Type == certificatesv1.CertificateApproved || c.Type == certificatesv1.CertificateDenied {
isInFinalState = true
finalState = string(c.Type)
}
}
if len(csr.Status.Certificate) != 0 || isInFinalState {
log.Info("Ignoring CSR, as it is in final state", "finalState", finalState)
return reconcile.Result{}, nil
}
x509cr, err := utils.DecodeCertificateRequest(csr.Spec.Request)
if err != nil {
return reconcile.Result{}, fmt.Errorf("unable to parse csr: %w", err)
}
reason, allowed, err := r.mustApprove(ctx, csr, x509cr)
if err != nil {
return reconcile.Result{}, fmt.Errorf("failed when checking for approval conditions: %w", err)
}
if allowed {
log.Info("Auto-approving CSR", "reason", reason)
csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1.CertificateSigningRequestCondition{
Type: certificatesv1.CertificateApproved,
Status: corev1.ConditionTrue,
Reason: "RequestApproved",
Message: fmt.Sprintf("Approving kubelet server certificate CSR (%s)", reason),
})
} else {
log.Info("Denying CSR", "reason", reason)
csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1.CertificateSigningRequestCondition{
Type: certificatesv1.CertificateDenied,
Status: corev1.ConditionTrue,
Reason: "RequestDenied",
Message: fmt.Sprintf("Denying kubelet server certificate CSR (%s)", reason),
})
}
_, err = r.CertificatesClient.UpdateApproval(ctx, csr.Name, csr, kubernetes.DefaultUpdateOptions())
return reconcile.Result{}, err
}
func (r *Reconciler) mustApprove(ctx context.Context, csr *certificatesv1.CertificateSigningRequest, x509cr *x509.CertificateRequest) (string, bool, error) {
if prefix := "system:node:"; !strings.HasPrefix(csr.Spec.Username, prefix) {
return fmt.Sprintf("username %q is not prefixed with %q", csr.Spec.Username, prefix), false, nil
}
if len(x509cr.DNSNames)+len(x509cr.IPAddresses) == 0 {
return "no DNS names or IP addresses in the SANs found", false, nil
}
if x509cr.Subject.CommonName != csr.Spec.Username {
return "common name in CSR does not match username", false, nil
}
if len(x509cr.Subject.Organization) != 1 || !utils.ValueExists(user.NodesGroup, x509cr.Subject.Organization) {
return "organization in CSR does not match nodes group", false, nil
}
nodeName := strings.TrimPrefix(x509cr.Subject.CommonName, "system:node:")
node := &corev1.Node{}
if err := r.TargetClient.Get(ctx, client.ObjectKey{Name: nodeName}, node); err != nil {
if apierrors.IsNotFound(err) {
return fmt.Sprintf("could not find node object with name %q", node.Name), false, nil
}
return "", false, err
}
machineList := &machinev1alpha1.MachineList{}
if err := r.SourceClient.List(ctx, machineList, client.InNamespace(r.Config.MachineNamespace), client.MatchingLabels{"node": node.Name}); err != nil {
return "", false, err
}
if length := len(machineList.Items); length != 1 {
return fmt.Sprintf("Expected exactly one machine in namespace %q for node %q but found %d", r.Config.MachineNamespace, node.Name, length), false, nil
}
var (
hostNames []string
ipAddresses []string
)
for _, address := range node.Status.Addresses {
if address.Type == corev1.NodeHostName || address.Type == corev1.NodeInternalDNS || address.Type == corev1.NodeExternalDNS {
hostNames = append(hostNames, address.Address)
}
if address.Type == corev1.NodeInternalIP || address.Type == corev1.NodeExternalIP {
ipAddresses = append(ipAddresses, address.Address)
}
}
if !sets.New(hostNames...).Equal(sets.New(x509cr.DNSNames...)) {
return "DNS names in CSR do not match addresses of type 'Hostname' or 'InternalDNS' or 'ExternalDNS' in node object", false, nil
}
var ipAddressesInCSR []string
for _, ip := range x509cr.IPAddresses {
ipAddressesInCSR = append(ipAddressesInCSR, ip.String())
}
if !sets.New(ipAddresses...).Equal(sets.New(ipAddressesInCSR...)) {
return "IP addresses in CSR do not match addresses of type 'InternalIP' or 'ExternalIP' in node object", false, nil
}
return "all checks passed", true, nil
}