forked from AppViewX/appviewx-signer
/
certificatesigningrequest_controller.go
250 lines (209 loc) · 9.23 KB
/
certificatesigningrequest_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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*
Copyright 2020 The cert-manager authors.
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 controllers
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/go-logr/logr"
"github.com/google/uuid"
capi "k8s.io/api/certificates/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
capihelper "github.com/gopaltirupur/appviewx-signer/internal/api"
"github.com/gopaltirupur/appviewx-signer/internal/kubernetes/signer"
"github.com/gopaltirupur/appviewx-signer/internal/signer/appviewx"
"github.com/gopaltirupur/appviewx-signer/internal/signer/monitor"
)
var appviewxMode string
var concurrentReconciles = 5
var csrUpdateMutex sync.Mutex
func init() {
appviewxMode = os.Getenv("APPVIEWX_MODE")
if os.Getenv("CONCURRENT_RECONCILE") != "" {
var err error
concurrentReconciles, err = strconv.Atoi(os.Getenv("CONCURRENT_RECONCILE"))
if err != nil {
log.Fatalf("Error in parsing the CONCURRENT_RECONCILE")
}
}
log.Printf("CONCURRENT_RECONCILE is set to : %d\n", concurrentReconciles)
go spinAHealthServer()
}
const (
retryInSeconds = 1
EXTERNAL_REQUEST_ID = "certificates.k8s.io/externalRequestId"
)
// CertificateSigningRequestSigningReconciler reconciles a CertificateSigningRequest object
type CertificateSigningRequestSigningReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
SignerName string
Signer *signer.Signer
EventRecorder record.EventRecorder
ApViewXSigner *appviewx.ApViewXSigner
}
// +kubebuilder:rbac:groups=certificates.k8s.io,resources=certificatesigningrequests,verbs=get;list;watch
// +kubebuilder:rbac:groups=certificates.k8s.io,resources=certificatesigningrequests/status,verbs=patch
// +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch
func (r *CertificateSigningRequestSigningReconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
// ctx = ctx..WithValue(context.Background(), "name", req.NamespacedName)
log := r.Log.WithValues("certificatesigningrequest", req.NamespacedName)
defer func() {
r := recover()
if r != nil {
err = errors.New("recovery error at Reconcile")
log.V(1).Info(fmt.Sprintf("Error - recovered from a panic : %+v", r))
}
}()
var csr capi.CertificateSigningRequest
if err := r.Client.Get(ctx, req.NamespacedName, &csr); client.IgnoreNotFound(err) != nil {
log.V(1).Info("Error in Get ", "req.NamespacedName", req.NamespacedName)
return ctrl.Result{}, nil
}
log.V(1).Info(fmt.Sprintf("csr.DeletionGracePeriodSeconds : %d", csr.DeletionGracePeriodSeconds))
switch {
case !csr.DeletionTimestamp.IsZero():
log.V(1).Info("CSR has been deleted. Ignoring.")
case csr.Spec.SignerName == "":
log.V(1).Info("CSR does not have a signer name. Ignoring.")
case csr.Spec.SignerName != r.SignerName:
log.V(1).Info("CSR signer name does not match. Ignoring.", "signer-name", csr.Spec.SignerName)
case csr.Status.Certificate != nil:
log.V(1).Info("CSR has already been signed. Ignoring.")
case !capihelper.IsCertificateRequestApproved(&csr):
log.V(1).Info("CSR is not approved, Ignoring.")
default:
if appviewxMode == "SYNC" {
log.V(1).Info("Signing - Sync")
csrUpdateMutex.Lock()
monitor.CSRCount.Inc()
csrUpdateMutex.Unlock()
//TODO: make configurable
//Don't consider csr if it is old
// if time.Now().After(csr.CreationTimestamp.Time.Add(time.Second * 6).Add(time.Millisecond * 500)) {
// return ctrl.Result{Requeue: false}, fmt.Errorf("timeout not proceeding with enrollment")
// }
externalRequestID := uuid.New().String()
csrContents := string(csr.Spec.Request)
cert, _, err := r.ApViewXSigner.MakeCallToAppViewXAndGetCertificate(ctx, &csrContents, nil, true, externalRequestID, false)
if err != nil {
log.V(1).Info("Error in MakeCallToAppViewXAndGetCertificate ", "err", err, "externalRequestID", externalRequestID)
return ctrl.Result{}, nil
}
if cert == nil {
log.V(1).Info("Error in MakeCallToAppViewXAndGetCertificate - cert byte array is nil", "externalRequestID", externalRequestID)
return ctrl.Result{}, nil
}
//Don't go for patch if already late
// if time.Now().After(csr.CreationTimestamp.Time.Add(time.Second * 9).Add(time.Millisecond * 500)) {
// return ctrl.Result{Requeue: false}, fmt.Errorf("timeout not patching")
// }
patch := client.MergeFrom(csr.DeepCopy())
csr.Status.Certificate = cert
if err := r.Client.Status().Patch(ctx, &csr, patch); err != nil {
log.V(1).Info("Error in Patch ")
return ctrl.Result{}, nil
}
log.V(1).Info("Signing - Sync - Success", "externalRequestID", externalRequestID)
r.EventRecorder.Event(&csr, v1.EventTypeNormal, "Signed", "The CSR has been signed")
} else if appviewxMode == "ASYNC" {
switch {
case csr.Annotations[EXTERNAL_REQUEST_ID] == "":
log.V(1).Info("Signing - Async")
//TODO: make configurable
//Don't consider csr if it is old
// if time.Now().After(csr.CreationTimestamp.Time.Add(time.Second * 6).Add(time.Millisecond * 500)) {
// return ctrl.Result{Requeue: false}, fmt.Errorf("timeout not proceeding with enrollment")
// }
externalRequestID := uuid.New().String()
csrContents := string(csr.Spec.Request)
_, _, err = r.ApViewXSigner.MakeCallToAppViewXAndGetCertificate(ctx, &csrContents, nil, false, externalRequestID, false)
if err != nil {
log.V(1).Info("Error in MakeCallToAppViewXAndGetCertificate - Call 1 ", "err", err, "externalRequestID", externalRequestID)
return ctrl.Result{}, nil
}
//Don't go for patch if already late
// if time.Now().After(csr.CreationTimestamp.Time.Add(time.Second * 9).Add(time.Millisecond * 500)) {
// return ctrl.Result{Requeue: false}, fmt.Errorf("timeout not patching")
// }
patch := client.MergeFrom(csr.DeepCopy())
metav1.SetMetaDataAnnotation(&csr.ObjectMeta, EXTERNAL_REQUEST_ID, externalRequestID)
if err := r.Client.Status().Patch(ctx, &csr, patch); err != nil {
log.V(1).Info("Error in Patch ")
return ctrl.Result{}, nil
}
log.V(1).Info("Signing - Async - Success", "externalRequestID", externalRequestID)
default:
externalRequestID := csr.Annotations[EXTERNAL_REQUEST_ID]
log.V(1).Info(fmt.Sprintf("Picking up with externalResourceID %s", externalRequestID))
//TODO: make configurable
//Don't consider csr if it is old
// if time.Now().After(csr.CreationTimestamp.Time.Add(time.Second * 8).Add(time.Millisecond * 500)) {
// return ctrl.Result{Requeue: false}, fmt.Errorf("timeout not proceeding with enrollment")
// }
cert, _, err := r.ApViewXSigner.MakeCallToAppViewXAndGetCertificate(ctx, nil, nil, true, externalRequestID, true)
if err != nil {
log.V(1).Info("Error in MakeCallToAppViewXAndGetCertificate - Call 2", "err", err, "externalRequestID", externalRequestID)
return ctrl.Result{Requeue: false}, nil
}
if len(cert) == 0 {
log.V(1).Info(fmt.Sprintf("Certificate not generated : will retry again : %v", err), "externalRequestID", externalRequestID)
return ctrl.Result{RequeueAfter: time.Second * retryInSeconds}, fmt.Errorf("Certificate not generated ")
}
//Don't go for patch if already late
// if time.Now().After(csr.CreationTimestamp.Time.Add(time.Second * 9).Add(time.Millisecond * 500)) {
// log.V(1).Info("Time out not patching the certificate", "externalRequestID", externalRequestID)
// return ctrl.Result{Requeue: false}, fmt.Errorf("timeout not patching")
// }
log.V(1).Info("patching the certificate", "externalRequestID", externalRequestID)
patch := client.MergeFrom(csr.DeepCopy())
delete(csr.Annotations, EXTERNAL_REQUEST_ID)
csr.Status.Certificate = cert
if err := r.Client.Status().Patch(ctx, &csr, patch); err != nil {
return ctrl.Result{}, fmt.Errorf("Error in patching the CSR with the certificate : %v", err)
}
log.V(1).Info("Picking up with externalResourceID - Success", "externalRequestID", externalRequestID)
r.EventRecorder.Event(&csr, v1.EventTypeNormal, "Signed", "The CSR has been signed")
}
} else {
panic("APPVIEWX_MODE should be SYNC or ASYNC")
}
}
return ctrl.Result{}, nil
}
func (r *CertificateSigningRequestSigningReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&capi.CertificateSigningRequest{}).
WithOptions(controller.Options{MaxConcurrentReconciles: concurrentReconciles}).
Complete(r)
}
func spinAHealthServer() {
http.HandleFunc("/healthz", healthz)
http.ListenAndServe(":8000", nil)
}
func healthz(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}