-
Notifications
You must be signed in to change notification settings - Fork 38
/
secret_cert_controller.go
227 lines (191 loc) · 6.64 KB
/
secret_cert_controller.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
/*
Licensed under the Mozilla Public License (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.mozilla.org/en-US/MPL/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 controllers
import (
"context"
"encoding/json"
"time"
"github.com/TykTechnologies/tyk-operator/api/v1alpha1"
"github.com/TykTechnologies/tyk-operator/pkg/cert"
"github.com/TykTechnologies/tyk-operator/pkg/client/universal"
"github.com/TykTechnologies/tyk-operator/pkg/environmet"
"github.com/go-logr/logr"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
util "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)
const (
certFinalizerName = "finalizers.tyk.io/certs"
secretType = "kubernetes.io/tls"
)
// CertReconciler reconciles a Cert object
type SecretCertReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
UniversalClient universal.Client
Env environmet.Env
}
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;update
func (r *SecretCertReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.Log.WithValues("cert", req.NamespacedName)
log.Info("getting secret resource")
desired := &v1.Secret{}
if err := r.Get(ctx, req.NamespacedName, desired); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err) // Ignore not-found errors
}
// set context for all api calls inside this reconciliation loop
env, ctx := httpContext(ctx, r.Client, r.Env, desired, log)
// If object is being deleted
if !desired.ObjectMeta.DeletionTimestamp.IsZero() {
log.Info("secret being deleted")
// If our finalizer is present, need to delete from Tyk still
if util.ContainsFinalizer(desired, certFinalizerName) {
log.Info("running finalizer logic")
certPemBytes, ok := desired.Data["tls.crt"]
if !ok {
return ctrl.Result{}, nil
}
orgID := env.Org
certFingerPrint := cert.CalculateFingerPrint(certPemBytes)
certID := orgID + certFingerPrint
log.Info("deleting certificate from tyk certificate manager", "orgID", orgID, "fingerprint", certFingerPrint)
if err := r.UniversalClient.Certificate().Delete(ctx, certID); err != nil {
log.Error(err, "unable to delete certificate")
return ctrl.Result{RequeueAfter: time.Second * 5}, err
}
if err := r.UniversalClient.HotReload(ctx); err != nil {
return ctrl.Result{}, err
}
log.Info("removing finalizer from secret")
util.RemoveFinalizer(desired, certFinalizerName)
if err := r.Update(ctx, desired); err != nil {
return ctrl.Result{}, err
}
}
log.Info("secret successfully deleted")
return ctrl.Result{}, nil
}
log.Info("checking secret type is tls")
if desired.Type != secretType {
// it's not for us
return ctrl.Result{}, nil
}
log.Info("ensuring tls.key is present")
tlsKey, ok := desired.Data["tls.key"]
if !ok {
// cert doesn't exist yet
log.Info("missing tls.key, we don't care about it yet")
return ctrl.Result{}, nil
}
log.Info("ensuring tls.crt is present")
tlsCrt, ok := desired.Data["tls.crt"]
if !ok {
// cert doesn't exist yet
log.Info("missing tls.crt, we don't care about it yet")
return ctrl.Result{}, nil
}
// all apidefinitions in current namespace
apiDefList := v1alpha1.ApiDefinitionList{}
opts := []client.ListOption{
client.InNamespace(req.Namespace),
}
if err := r.List(ctx, &apiDefList, opts...); err != nil {
log.Info("unable to list api definitions")
return ctrl.Result{}, err
}
if len(apiDefList.Items) == 0 {
log.Info("no apidefinitions in namespace")
return ctrl.Result{}, nil
}
ret := true
for _, apiDef := range apiDefList.Items {
if containsString(apiDef.Spec.CertificateSecretNames, req.Name) {
log.Info("apidefinition references this secret", "apiid", apiDef.Status.ApiID)
ret = false
}
}
if ret {
log.Info("no apidefinitions reference this secret")
return ctrl.Result{}, nil
}
// If finalizer not present, add it; This is a new object
if !util.ContainsFinalizer(desired, certFinalizerName) {
log.Info("adding finalizer for cleanup")
desired.ObjectMeta.Finalizers = append(desired.ObjectMeta.Finalizers, certFinalizerName)
err := r.Update(ctx, desired)
return ctrl.Result{}, client.IgnoreNotFound(err)
}
certID, err := r.UniversalClient.Certificate().Upload(ctx, tlsKey, tlsCrt)
if err != nil {
return ctrl.Result{Requeue: true}, err
}
log.Info("uploaded certificate to Tyk", "certID", certID)
for _, apiDef := range apiDefList.Items {
if containsString(apiDef.Spec.CertificateSecretNames, req.Name) {
log.Info("replacing certificate", "apiID", apiDef.Status.ApiID, "certID", certID)
apiDefObj, _ := r.UniversalClient.Api().Get(ctx, apiDef.Status.ApiID)
apiDefObj.Certificates = []string{}
apiDefObj.Certificates = append(apiDefObj.Certificates, certID)
r.UniversalClient.Api().Update(ctx, apiDefObj)
// TODO: we only care about 1 secret - we don't need to support multiple for mvp
break
}
}
return ctrl.Result{}, nil
}
// https://sdk.operatorframework.io/docs/building-operators/golang/tutorial/#resources-watched-by-the-controller
func (r *SecretCertReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1.Secret{}).
WithEventFilter(r.ignoreNonTLSPredicate()).
Complete(r)
}
type mySecretType struct {
Meta struct {
Type string `json:"type"`
} `json:"Meta"`
MetaNew struct {
Type string `json:"type"`
} `json:"MetaNew"`
}
func (r *SecretCertReconciler) ignoreNonTLSPredicate() predicate.Predicate {
isTLSType := func(jsBytes []byte) bool {
secret := mySecretType{}
json.Unmarshal(jsBytes, &secret)
// if Update
if secret.MetaNew.Type != "" {
return secret.MetaNew.Type == secretType
}
// then it's a create / delete op
return secret.Meta.Type == secretType
}
return predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool {
//obj := runtime.Object
//return e.Meta.Type == "kubernetes.io/tls"
eBytes, _ := json.Marshal(e)
return isTLSType(eBytes)
},
UpdateFunc: func(e event.UpdateEvent) bool {
eBytes, _ := json.Marshal(e)
return isTLSType(eBytes)
},
DeleteFunc: func(e event.DeleteEvent) bool {
return true
},
}
}