This repository has been archived by the owner on Mar 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 100
/
cert.go
192 lines (166 loc) · 5.9 KB
/
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
package publish
import (
"crypto/x509"
"encoding/pem"
"fmt"
"sort"
"github.com/acorn-io/baaah/pkg/name"
"github.com/acorn-io/baaah/pkg/router"
"github.com/acorn-io/baaah/pkg/typed"
v1 "github.com/acorn-io/runtime/pkg/apis/internal.acorn.io/v1"
"github.com/acorn-io/runtime/pkg/labels"
"github.com/acorn-io/runtime/pkg/system"
"github.com/sirupsen/logrus"
"golang.org/x/exp/maps"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type TLSCert struct {
Certificate x509.Certificate `json:"certificate,omitempty"`
SecretName string `json:"secret-name,omitempty"`
SecretNamespace string `json:"secret-namespace,omitempty"`
}
func (cert *TLSCert) certForThisDomain(name string) bool {
if valid := cert.Certificate.VerifyHostname(name); valid == nil {
return true
}
return false
}
func convertTLSSecretToTLSCert(secret corev1.Secret) (cert TLSCert, _ error) {
tlsPEM, ok := secret.Data["tls.crt"]
if !ok {
return cert, fmt.Errorf("key tls.crt not found in secret %s", secret.Name)
}
tlsCertBytes, _ := pem.Decode(tlsPEM)
if tlsCertBytes == nil {
return cert, fmt.Errorf("failed to parse Cert PEM stored in secret %s", secret.Name)
}
tlsDataObj, err := x509.ParseCertificate(tlsCertBytes.Bytes)
if err != nil {
return cert, err
}
cert.SecretName = secret.Name
cert.SecretNamespace = secret.Namespace
cert.Certificate = *tlsDataObj
return
}
// getCerts looks for Secrets in the app namespace that contain TLS certs
func getCerts(req router.Request, namespace string) ([]TLSCert, error) {
var (
result []TLSCert
secrets corev1.SecretList
)
err := req.List(&secrets, &client.ListOptions{
Namespace: namespace,
})
if err != nil {
return result, err
}
wildcardCertSecret := &corev1.Secret{}
if err := req.Get(wildcardCertSecret, system.Namespace, system.TLSSecretName); err != nil && !apierrors.IsNotFound(err) {
return nil, err
}
if !apierrors.IsNotFound(err) {
secrets.Items = append(secrets.Items, *wildcardCertSecret)
}
for _, secret := range secrets.Items {
if secret.Type != corev1.SecretTypeTLS {
continue
}
cert, err := convertTLSSecretToTLSCert(secret)
if err != nil {
logrus.Errorf("Error processing TLScertificate in secret %s/%s. Recieved %s", secret.Namespace, secret.Name, err)
continue
}
result = append(result, cert)
}
sort.Slice(result, func(i, j int) bool {
return result[i].SecretName < result[j].SecretName
})
return result, nil
}
func copySecretsForCerts(req router.Request, svc *v1.ServiceInstance, filteredTLSCerts []TLSCert) (objs []client.Object, resultTLSCert []TLSCert, _ error) {
for _, tlsCert := range filteredTLSCerts {
originalSecret := &corev1.Secret{}
err := req.Get(originalSecret, tlsCert.SecretNamespace, tlsCert.SecretName)
if err != nil {
return nil, nil, err
}
secretName := name.SafeConcatName(tlsCert.SecretName, svc.Name, string(originalSecret.UID)[:12])
objs = append(objs, &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: svc.Namespace,
Labels: labels.Merge(originalSecret.Labels, labels.ManagedByApp(svc.Spec.AppNamespace, svc.Spec.AppName)),
Annotations: originalSecret.Annotations,
},
Type: corev1.SecretTypeTLS,
Data: originalSecret.Data,
})
//Override the secret name to the copied name
tlsCert.SecretName = secretName
tlsCert.SecretNamespace = svc.Namespace
resultTLSCert = append(resultTLSCert, tlsCert)
}
return
}
func setupCertsForRules(req router.Request, svc *v1.ServiceInstance, rules []networkingv1.IngressRule, customDomain bool, defaultClusterIssuer string) ([]client.Object, []networkingv1.IngressTLS, map[string]string, error) {
tlsCerts, err := getCerts(req, svc.Spec.AppNamespace)
if err != nil {
return nil, nil, nil, err
}
tlsCerts = getCertsMatchingRules(rules, tlsCerts)
secrets, tlsCerts, err := copySecretsForCerts(req, svc, tlsCerts)
if err != nil {
return nil, nil, nil, err
}
annotations := maps.Clone(svc.Spec.Annotations)
if annotations == nil {
annotations = map[string]string{}
}
ingressTLS := getCertsForPublishedHosts(rules, tlsCerts)
// In here, we want to setup cert-manager if:
// 1. The user has specified a cert-manager issuer in the annotations on top of acorn
// 2. The user has specified default cert-manager issuer in the settings, and there is no matching certs for this custom domain
if svc.Spec.Annotations["cert-manager.io/cluster-issuer"] != "" || svc.Spec.Annotations["cert-manager.io/issuer"] != "" || (len(ingressTLS) == 0 && customDomain && defaultClusterIssuer != "") {
if svc.Spec.Annotations["cert-manager.io/cluster-issuer"] == "" && svc.Spec.Annotations["cert-manager.io/issuer"] == "" {
annotations["cert-manager.io/cluster-issuer"] = defaultClusterIssuer
}
ingressTLS = setupCertManager(svc.Name, rules)
}
return secrets, ingressTLS, annotations, nil
}
func getCertsMatchingRules(rules []networkingv1.IngressRule, certs []TLSCert) (filteredCerts []TLSCert) {
for _, rule := range rules {
for _, cert := range certs {
if cert.certForThisDomain(rule.Host) {
filteredCerts = append(filteredCerts, cert)
break
}
}
}
return
}
func getCertsForPublishedHosts(rules []networkingv1.IngressRule, certs []TLSCert) (ingressTLS []networkingv1.IngressTLS) {
certSecretToHostMapping := map[string][]string{}
for _, rule := range rules {
for _, cert := range certs {
// Find the first cert and stop looking
if cert.certForThisDomain(rule.Host) {
certSecretToHostMapping[cert.SecretName] = append(certSecretToHostMapping[cert.SecretName], rule.Host)
break
}
}
}
for _, entry := range typed.Sorted(certSecretToHostMapping) {
secret, hosts := entry.Key, entry.Value
ingressTLS = append(ingressTLS, networkingv1.IngressTLS{
Hosts: hosts,
SecretName: secret,
})
}
return
}