This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 59
/
init_cert.go
250 lines (213 loc) · 6.52 KB
/
init_cert.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
package webhook
import (
"bytes"
"context"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"os"
"path"
"time"
"github.com/flyteorg/flytepropeller/pkg/controller/config"
"github.com/flyteorg/flytepropeller/pkg/utils"
webhookConfig "github.com/flyteorg/flytepropeller/pkg/webhook/config"
"github.com/flyteorg/flytestdlib/logger"
corev1 "k8s.io/api/core/v1"
kubeErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
)
type webhookCerts struct {
// base64 Encoded CA Cert
CaPEM *bytes.Buffer
// base64 Encoded Server Cert
ServerPEM *bytes.Buffer
// base64 Encoded Server Cert Key
PrivateKeyPEM *bytes.Buffer
}
const (
CaCertKey = "ca.crt"
ServerCertKey = "tls.crt"
ServerCertPrivateKey = "tls.key"
podDefaultNamespace = "flyte"
permission = 0644
)
func InitCerts(ctx context.Context, propellerCfg *config.Config, cfg *webhookConfig.Config) error {
podNamespace, found := os.LookupEnv(PodNamespaceEnvVar)
if !found {
podNamespace = podDefaultNamespace
}
logger.Infof(ctx, "Issuing certs")
certs, err := createCerts(podNamespace)
if err != nil {
return err
}
kubeClient, _, err := utils.GetKubeConfig(ctx, propellerCfg)
if err != nil {
return err
}
logger.Infof(ctx, "Creating secret [%v] in Namespace [%v]", cfg.SecretName, podNamespace)
err = createWebhookSecret(ctx, podNamespace, cfg, certs, kubeClient.CoreV1().Secrets(podNamespace))
if err != nil {
return err
}
return nil
}
func createWebhookSecret(ctx context.Context, namespace string, cfg *webhookConfig.Config, certs webhookCerts, secretsClient v1.SecretInterface) error {
isImmutable := true
secretData := map[string][]byte{
CaCertKey: certs.CaPEM.Bytes(),
ServerCertKey: certs.ServerPEM.Bytes(),
ServerCertPrivateKey: certs.PrivateKeyPEM.Bytes(),
}
if cfg.LocalCert {
if _, err := os.Stat(cfg.CertDir); os.IsNotExist(err) {
if err := os.Mkdir(cfg.CertDir, permission); err != nil {
return err
}
}
if err := os.WriteFile(path.Join(cfg.CertDir, CaCertKey), certs.CaPEM.Bytes(), permission); err != nil {
return err
}
if err := os.WriteFile(path.Join(cfg.CertDir, ServerCertKey), certs.ServerPEM.Bytes(), permission); err != nil {
return err
}
if err := os.WriteFile(path.Join(cfg.CertDir, ServerCertPrivateKey), certs.PrivateKeyPEM.Bytes(), permission); err != nil {
return err
}
}
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: cfg.SecretName,
Namespace: namespace,
},
Type: corev1.SecretTypeOpaque,
Data: secretData,
Immutable: &isImmutable,
}
_, err := secretsClient.Create(ctx, secret, metav1.CreateOptions{})
if err == nil {
logger.Infof(ctx, "Created secret [%v]", cfg.SecretName)
return nil
}
if kubeErrors.IsAlreadyExists(err) {
logger.Infof(ctx, "A secret already exists with the same name. Validating.")
s, err := secretsClient.Get(ctx, cfg.SecretName, metav1.GetOptions{})
if err != nil {
return err
}
// If ServerCertKey or ServerCertPrivateKey are missing, update
requiresUpdate := false
for key := range secretData {
if key == CaCertKey {
continue
}
if _, exists := s.Data[key]; !exists {
requiresUpdate = true
break
}
}
if requiresUpdate {
logger.Infof(ctx, "The existing secret is missing one or more keys.")
secret.Annotations = map[string]string{
"flyteLastUpdate": "system-updated",
"flyteUpdatedAt": time.Now().String(),
}
_, err = secretsClient.Update(ctx, secret, metav1.UpdateOptions{})
if err != nil && kubeErrors.IsConflict(err) {
logger.Infof(ctx, "Another instance of flyteadmin has updated the same secret. Ignoring this update")
err = nil
}
return err
}
return nil
}
return err
}
func createCerts(serviceNamespace string) (certs webhookCerts, err error) {
// CA config
caRequest := &x509.Certificate{
SerialNumber: big.NewInt(2021),
Subject: pkix.Name{
Organization: []string{"flyte.org"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
// CA private key
caPrivateKey, err := rsa.GenerateKey(cryptorand.Reader, 4096)
if err != nil {
return webhookCerts{}, err
}
// Self signed CA certificate
caCert, err := x509.CreateCertificate(cryptorand.Reader, caRequest, caRequest, &caPrivateKey.PublicKey, caPrivateKey)
if err != nil {
return webhookCerts{}, err
}
// PEM encode CA cert
caPEM := new(bytes.Buffer)
err = pem.Encode(caPEM, &pem.Block{
Type: "CERTIFICATE",
Bytes: caCert,
})
if err != nil {
return webhookCerts{}, err
}
dnsNames := []string{"flyte-pod-webhook",
"flyte-pod-webhook." + serviceNamespace, "flyte-pod-webhook." + serviceNamespace + ".svc"}
commonName := "flyte-pod-webhook." + serviceNamespace + ".svc"
// server cert config
certRequest := &x509.Certificate{
DNSNames: dnsNames,
SerialNumber: big.NewInt(1658),
Subject: pkix.Name{
CommonName: commonName,
Organization: []string{"flyte.org"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
SubjectKeyId: []byte{1, 2, 3, 4, 6},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature,
}
// server private key
serverPrivateKey, err := rsa.GenerateKey(cryptorand.Reader, 4096)
if err != nil {
return webhookCerts{}, err
}
// sign the server cert
cert, err := x509.CreateCertificate(cryptorand.Reader, certRequest, caRequest, &serverPrivateKey.PublicKey, caPrivateKey)
if err != nil {
return webhookCerts{}, err
}
// PEM encode the server cert and key
serverCertPEM := new(bytes.Buffer)
err = pem.Encode(serverCertPEM, &pem.Block{
Type: "CERTIFICATE",
Bytes: cert,
})
if err != nil {
return webhookCerts{}, fmt.Errorf("failed to Encode CertPEM. Error: %w", err)
}
serverPrivKeyPEM := new(bytes.Buffer)
err = pem.Encode(serverPrivKeyPEM, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(serverPrivateKey),
})
if err != nil {
return webhookCerts{}, fmt.Errorf("failed to Encode Cert Private Key. Error: %w", err)
}
return webhookCerts{
CaPEM: caPEM,
ServerPEM: serverCertPEM,
PrivateKeyPEM: serverPrivKeyPEM,
}, nil
}