-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathcertificate_manager.go
291 lines (253 loc) · 8.91 KB
/
certificate_manager.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package watcher
import (
"context"
"errors"
"fmt"
"time"
certmanagerv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
certmanagermetav1 "github.com/cert-manager/cert-manager/pkg/apis/meta/v1"
apicorev1 "k8s.io/api/core/v1"
apimetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8slabels "k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/controller-runtime/pkg/client"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"github.com/kyma-project/lifecycle-manager/api/shared"
"github.com/kyma-project/lifecycle-manager/api/v1beta2"
"github.com/kyma-project/lifecycle-manager/pkg/log"
"github.com/kyma-project/lifecycle-manager/pkg/util"
)
const (
DomainAnnotation = shared.SKRDomainAnnotation
caCertKey = "ca.crt"
tlsCertKey = "tls.crt"
tlsPrivateKeyKey = "tls.key"
)
var (
ErrDomainAnnotationEmpty = errors.New("domain annotation is empty")
ErrDomainAnnotationMissing = errors.New("domain annotation is missing")
ErrIssuerNotFound = errors.New("no certificate issuer found")
)
type SubjectAltName struct {
DNSNames []string
IPAddresses []string
URIs []string
EmailAddresses []string
}
type CertificateManager struct {
kcpClient client.Client
certificateName string
secretName string
labelSet k8slabels.Set
config CertificateConfig
}
type CertificateConfig struct {
// IstioNamespace represents the cluster resource namespace of istio
IstioNamespace string
// RemoteSyncNamespace indicates the sync namespace for Kyma and module catalog
RemoteSyncNamespace string
// CACertificateName indicates the Name of the CA Root Certificate in the Istio Namespace
CACertificateName string
// AdditionalDNSNames indicates the DNS Names which should be added additional to the Subject
// Alternative Names of each Kyma Certificate
AdditionalDNSNames []string
Duration time.Duration
RenewBefore time.Duration
RenewBuffer time.Duration
KeySize int
}
type CertificateSecret struct {
CACrt string
TLSCrt string
TLSKey string
ResourceVersion string
}
// NewCertificateManager returns a new CertificateManager, which can be used for creating a cert-manager Certificates.
func NewCertificateManager(kcpClient client.Client, kymaName string,
config CertificateConfig,
) *CertificateManager {
return &CertificateManager{
kcpClient: kcpClient,
certificateName: ResolveTLSCertName(kymaName),
secretName: ResolveTLSCertName(kymaName),
config: config,
labelSet: k8slabels.Set{
shared.PurposeLabel: shared.CertManager,
shared.ManagedBy: shared.OperatorName,
},
}
}
// CreateSelfSignedCert creates a cert-manager Certificate with a sufficient set of Subject-Alternative-Names.
func (c *CertificateManager) CreateSelfSignedCert(ctx context.Context, kyma *v1beta2.Kyma) (*certmanagerv1.Certificate,
error,
) {
subjectAltNames, err := c.getSubjectAltNames(kyma)
if err != nil {
return nil, fmt.Errorf("error get Subject Alternative Name from KymaCR: %w", err)
}
return c.patchCertificate(ctx, subjectAltNames)
}
// Remove removes the certificate including its certificate secret.
func (c *CertificateManager) Remove(ctx context.Context) error {
err := c.removeCertificate(ctx)
if err != nil {
return err
}
return c.removeSecret(ctx)
}
func (c *CertificateManager) removeCertificate(ctx context.Context) error {
certificate := &certmanagerv1.Certificate{}
err := c.kcpClient.Get(ctx, client.ObjectKey{
Name: c.certificateName,
Namespace: c.config.IstioNamespace,
}, certificate)
if err != nil && !util.IsNotFound(err) {
return fmt.Errorf("failed to get certificate: %w", err)
}
if err == nil {
if err = c.kcpClient.Delete(ctx, certificate); err != nil {
return fmt.Errorf("failed to delete certificate: %w", err)
}
}
return nil
}
func (c *CertificateManager) removeSecret(ctx context.Context) error {
certSecret := &apicorev1.Secret{}
err := c.kcpClient.Get(ctx, client.ObjectKey{
Name: c.secretName,
Namespace: c.config.IstioNamespace,
}, certSecret)
if err != nil && !util.IsNotFound(err) {
return fmt.Errorf("failed to get certificate secret: %w", err)
}
if err == nil {
if err = c.kcpClient.Delete(ctx, certSecret); err != nil {
return fmt.Errorf("failed to delete certificate secret: %w", err)
}
}
return nil
}
func (c *CertificateManager) patchCertificate(ctx context.Context,
subjectAltName *SubjectAltName,
) (*certmanagerv1.Certificate, error) {
issuer, err := c.getIssuer(ctx)
if err != nil {
return nil, fmt.Errorf("error getting issuer: %w", err)
}
cert := certmanagerv1.Certificate{
TypeMeta: apimetav1.TypeMeta{
Kind: certmanagerv1.CertificateKind,
APIVersion: certmanagerv1.SchemeGroupVersion.String(),
},
ObjectMeta: apimetav1.ObjectMeta{
Name: c.certificateName,
Namespace: c.config.IstioNamespace,
},
Spec: certmanagerv1.CertificateSpec{
Duration: &apimetav1.Duration{Duration: c.config.Duration},
RenewBefore: &apimetav1.Duration{Duration: c.config.RenewBefore},
DNSNames: subjectAltName.DNSNames,
IPAddresses: subjectAltName.IPAddresses,
URIs: subjectAltName.URIs,
EmailAddresses: subjectAltName.EmailAddresses,
SecretName: c.secretName,
SecretTemplate: &certmanagerv1.CertificateSecretTemplate{
Labels: c.labelSet,
},
IssuerRef: certmanagermetav1.ObjectReference{
Name: issuer.Name,
},
IsCA: false,
Usages: []certmanagerv1.KeyUsage{
certmanagerv1.UsageDigitalSignature,
certmanagerv1.UsageKeyEncipherment,
},
PrivateKey: &certmanagerv1.CertificatePrivateKey{
RotationPolicy: certmanagerv1.RotationPolicyAlways,
Encoding: certmanagerv1.PKCS1,
Algorithm: certmanagerv1.RSAKeyAlgorithm,
Size: c.config.KeySize,
},
},
}
err = c.kcpClient.Patch(ctx, &cert, client.Apply, client.ForceOwnership, skrChartFieldOwner)
if err != nil {
return nil, fmt.Errorf("failed to patch certificate: %w", err)
}
return &cert, nil
}
func (c *CertificateManager) getSubjectAltNames(kyma *v1beta2.Kyma) (*SubjectAltName, error) {
if domain, ok := kyma.Annotations[DomainAnnotation]; ok {
if domain == "" {
return nil, fmt.Errorf("%w (Kyma: %s)", ErrDomainAnnotationEmpty, kyma.Name)
}
svcSuffix := []string{"svc.cluster.local", "svc"}
dnsNames := []string{domain}
for _, suffix := range svcSuffix {
dnsNames = append(dnsNames, fmt.Sprintf("%s.%s.%s", SkrResourceName, c.config.RemoteSyncNamespace, suffix))
}
dnsNames = append(dnsNames, c.config.AdditionalDNSNames...)
return &SubjectAltName{
DNSNames: dnsNames,
}, nil
}
return nil, fmt.Errorf("%w (Kyma: %s)", ErrDomainAnnotationMissing, kyma.Name)
}
func (c *CertificateManager) getIssuer(ctx context.Context) (*certmanagerv1.Issuer, error) {
logger := logf.FromContext(ctx)
issuerList := &certmanagerv1.IssuerList{}
err := c.kcpClient.List(ctx, issuerList, &client.ListOptions{
LabelSelector: k8slabels.SelectorFromSet(c.labelSet),
Namespace: c.config.IstioNamespace,
})
if err != nil {
return nil, fmt.Errorf("could not list cert-manager issuer %w", err)
}
if len(issuerList.Items) == 0 {
return nil, fmt.Errorf("%w (Namespace: %s, Labels %s)",
ErrIssuerNotFound, c.config.IstioNamespace, c.labelSet.String())
} else if len(issuerList.Items) > 1 {
logger.Info("Found more than one issuer, will use by default first one in list",
"issuer", issuerList.Items)
}
return &issuerList.Items[0], nil
}
func (c *CertificateManager) getCertificateSecret(ctx context.Context) (*apicorev1.Secret, error) {
secret := &apicorev1.Secret{}
err := c.kcpClient.Get(ctx, client.ObjectKey{Name: c.secretName, Namespace: c.config.IstioNamespace},
secret)
if err != nil {
return nil, fmt.Errorf("failed to get secret for certificate %s-%s: %w", c.secretName, c.config.IstioNamespace,
err)
}
return secret, nil
}
type CertificateNotReadyError struct{}
func (e *CertificateNotReadyError) Error() string {
return "Certificate-Secret does not exist"
}
func (c *CertificateManager) RemoveSecretAfterCARotated(ctx context.Context, gatewaySecret *apicorev1.Secret,
kymaObjKey client.ObjectKey,
) error {
watcherSecret, err := c.getCertificateSecret(ctx)
if err != nil {
return err
}
if watcherSecret != nil && SecretRequiresRotation(gatewaySecret, watcherSecret) {
logf.FromContext(ctx).V(log.DebugLevel).Info("CA Certificate was rotated, removing certificate",
"kyma", kymaObjKey)
if err = c.removeSecret(ctx); err != nil {
return fmt.Errorf("error while removing certificate: %w", err)
}
}
return nil
}
func SecretRequiresRotation(gatewaySecret *apicorev1.Secret, watcherSecret *apicorev1.Secret) bool {
if gwSecretLastModifiedAtValue, ok := gatewaySecret.Annotations[shared.LastModifiedAtAnnotation]; ok {
if gwSecretLastModifiedAt, err := time.Parse(time.RFC3339, gwSecretLastModifiedAtValue); err == nil {
if watcherSecret.CreationTimestamp.Time.After(gwSecretLastModifiedAt) {
return false
}
}
}
return true
}