-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
1123 lines (956 loc) · 40.2 KB
/
main.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"archive/tar"
"bytes"
"context"
"crypto/dsa"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"embed"
_ "embed"
"encoding/hex"
"encoding/pem"
"errors"
"flag"
"fmt"
"html/template"
"io"
"log"
"net"
"net/http"
"net/mail"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
apiutil "github.com/cert-manager/cert-manager/pkg/api/util"
certmanagerv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
cmmetav1 "github.com/cert-manager/cert-manager/pkg/apis/meta/v1"
cmversioned "github.com/cert-manager/cert-manager/pkg/client/clientset/versioned"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
var (
listen = flag.String("listen", "127.0.0.1:8080", "Allows you to specify the address and port to listen on.")
kubeconfig = flag.String("kubeconfig", "", "Allows you to specify the path to the kubeconfig file.")
namespace = flag.String("namespace", "default", "Allows you to specify the namespace to use when creating the certificates.")
issuer = flag.String("issuer", "", "Name of the issuer resource to use when creating the certificates. When --issuer-kind=Issuer is used (which is the default), the issuer resource must be in the same namespace as in --namespace.")
issuerKind = flag.String("issuer-kind", "Issuer", "This flag can be used to select the namespaced 'Issuer', or to select an 'external' issuer, e.g., 'AWSPCAIssuer'.")
issuerGroup = flag.String("issuer-group", "cert-manager.io", "This flag allows you to give a different API group when using an 'external' issuer, e.g., 'awspca.cert-manager.io'.")
inCluster = flag.Bool("in-cluster", false, "Use the in-cluster kube config to connect to Kubernetes. Use this flag when running in a pod.")
guestbookURL = flag.String("guestbook-url", "https://guestbook.print-your-cert.cert-manager.io/write", "URL of the write path for the guestbook")
guestbookRootCAPath = flag.String("guestbook-ca", "guestbook/ca.crt", "Path to the CA certificate for the guestbook")
guestbookLocal = flag.Bool("guestbook-local", false, "If true, redirect guestbook requests to 127.0.0.1 for local testing while preserving the SNI header from guestbook-url")
)
const (
AnnotationPrint = "print"
ConditionPrinted = "Printed"
AnnotationFetchKey = "fetch-key"
AnnotationCardColor = "card-color"
)
// Config attempts to load the in-cluster config and falls back to using
// the local kube config in order to run out-of-cluster.
//
// The context is only useful for the local kube config. If context is left
// empty, the default context of the local kube config is used.
//
// The kubeconfig argument lets you specify the path to a kubeconfig file.
func Config(inCluster bool, kubeconfig string) (cfg *rest.Config, err error) {
if inCluster {
cfg, err = rest.InClusterConfig()
if err != nil {
return nil, err
}
cfg.UserAgent = fmt.Sprintf("print-your-cert")
return cfg, nil
}
log.Printf("Using the local kubeconfig. Note that you can use --in-cluster when running in a pod.")
rule := clientcmd.NewDefaultClientConfigLoadingRules()
if kubeconfig != "" {
rule.ExplicitPath = kubeconfig
}
apiCfg, err := rule.Load()
if err != nil {
return nil, fmt.Errorf("error loading kubeconfig: %v", err)
}
cfg, err = clientcmd.NewDefaultClientConfig(*apiCfg, nil).ClientConfig()
if err != nil {
return nil, fmt.Errorf("error loading kube config for context: %v", err)
}
cfg.UserAgent = fmt.Sprintf("print-your-cert")
return cfg, nil
}
//go:embed static/js/*.js
//go:embed static/*.css
//go:embed static/images/*
var static embed.FS
//go:embed *.html
var templates embed.FS
var tmpl = template.Must(template.ParseFS(templates, "*.html"))
// When the user lands on the website for the first time, they will get a
// blank form prompting them to fill in their name and email to receive a
// certificate.
//
// GET / HTTP/2.0
//
// When the user submits their name and email, the user is redirected to
// the same landing page, except it remember the name and email using query
// parameters:
//
// GET /?name=NAME&email=EMAIL HTTP/2.0
//
// For debugging purposes, one can set the query parameter "debug" to
// "true" (or any other value), and more information about the Kubernetes
// Certificate resource gets displayed:
//
// GET /?name=NAME&email=EMAIL&debug=true HTTP/2.0
func landingPage(kclient kubernetes.Interface, cmclient cmversioned.Interface) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, fmt.Sprintf("The path %s contains is expected to be /.", r.URL.Path), http.StatusNotFound)
return
}
// We want to display the count of printed certificates.
result, err := cmclient.CertmanagerV1().Certificates(*namespace).List(r.Context(), metav1.ListOptions{})
if err != nil {
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "landing.html", landingPageData{Refresh: 5, Error: "Issue with getting the number of certificate already printed. Retrying in 5 seconds."})
log.Printf("GET /: while listing the certificates that have Printed=True: %v", err)
return
}
var printed, pending int
for _, c := range result.Items {
if isAlreadyPrinted(&c) {
printed++
}
if isPendingPrint(&c) {
pending++
}
}
if r.Method != "GET" {
http.Error(w, fmt.Sprintf("The method %s is not allowed on %s", r.Method, r.URL.Path), http.StatusMethodNotAllowed)
return
}
personName := r.URL.Query().Get("name")
email := r.URL.Query().Get("email")
cardColor := strings.ToUpper(r.URL.Query().Get("cardcolor"))
if cardColor == "" {
// default to pink since that's usually the color we have most of
cardColor = "P"
}
// Happily return early if the name or email haven't been provided yet.
if personName == "" && email == "" {
w.WriteHeader(400)
tmpl.ExecuteTemplate(w, "landing.html", landingPageData{Name: personName, Email: email, CountPrinted: printed, CountPending: pending, Message: "Welcome! To get your certificate, fill in your name and email."})
return
}
// Let's check that both the email and name have been entered.
if personName == "" && email != "" || personName != "" && email == "" {
w.WriteHeader(400)
tmpl.ExecuteTemplate(w, "landing.html", landingPageData{Name: personName, Email: email, CountPrinted: printed, CountPending: pending, Message: "Please fill in both the email and name."})
log.Printf("GET /: the user has given an empty name %q or an empty email %q", personName, email)
return
}
if !valid(email) {
w.WriteHeader(400)
tmpl.ExecuteTemplate(w, "landing.html", landingPageData{Name: personName, Email: email, CountPrinted: printed, CountPending: pending, Error: "The email is invalid."})
log.Printf("GET /: the user %q has given an invalid email %q", personName, email)
return
}
commonName := personName
if len(personName) > 64 {
commonName = personName[:63]
}
certName := emailToCertName(email)
fetchKeyRaw := make([]byte, 32)
if _, err := rand.Read(fetchKeyRaw); err != nil {
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "landing.html", landingPageData{Refresh: 5, Error: "Internal server error: failed to generate a fetch key"})
log.Printf("GET /: failed to generate a fetch key: %v", err)
return
}
fetchKey := hex.EncodeToString(fetchKeyRaw)
_, err = cmclient.CertmanagerV1().Certificates(*namespace).Create(r.Context(), &certmanagerv1.Certificate{
ObjectMeta: metav1.ObjectMeta{
Name: certName,
Annotations: map[string]string{
AnnotationFetchKey: fetchKey,
AnnotationCardColor: cardColor,
},
},
Spec: certmanagerv1.CertificateSpec{
CommonName: commonName,
Duration: &metav1.Duration{Duration: 3 * 3650 * 24 * time.Hour}, // 30 years.
Subject: &certmanagerv1.X509Subject{
// Update this with the country you're issuing in!
Countries: []string{
"US",
},
// Update this with the city you're issuing in!
Localities: []string{
"Salt Lake City",
},
},
SecretName: certName,
IssuerRef: cmmetav1.ObjectReference{
Name: *issuer,
Kind: *issuerKind,
Group: *issuerGroup,
},
PrivateKey: &certmanagerv1.CertificatePrivateKey{
Algorithm: certmanagerv1.ECDSAKeyAlgorithm,
Size: 256,
},
EmailAddresses: []string{email},
},
}, metav1.CreateOptions{})
switch {
case k8serrors.IsAlreadyExists(err):
w.WriteHeader(409)
tmpl.ExecuteTemplate(w, "landing.html", landingPageData{Name: personName, CountPrinted: printed, CountPending: pending, Duplicate: true})
log.Printf("GET /: cannot create due to duplicate certificate name %s", certName)
return
case err != nil:
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "landing.html", landingPageData{Name: personName, Email: email, CountPrinted: printed, CountPending: pending, Refresh: 5, Error: "There was an error creating your certificate. The page will be reloaded every 5 seconds until this issue is resolved."})
log.Printf("GET /: issue while creating the Certificate named %s in namespace %s for '%s <%s>' in Kubernetes: %v", certName, *namespace, personName, email, err)
return
}
// We don't display the certificate on this page. Instead, we do that in
// the endpoint /certificate?email=...
query := url.Values{
"certName": []string{certName},
"fetchKey": []string{fetchKey},
}
destination := "/certificate?" + query.Encode()
log.Printf("GET /: successfully created a certificate, redirecting to %s", destination)
http.Redirect(w, r, destination, http.StatusFound)
tmpl.ExecuteTemplate(w, "landing.html", landingPageData{Error: "Redirecting..."})
}
}
// When the user clicks the button "Print my certificate" on the landing
// page, this POST gets called.
//
// When the user clicks the button "Go back to my certificate", they are
// redirected to GET /.
//
// POST /print HTTP/2.0
// Content-Type: application/x-www-form-urlencoded
// email=...&name=...
func printPage(kclient kubernetes.Interface, cmclient cmversioned.Interface) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/print" {
http.Error(w, fmt.Sprintf("The path %s is expected to be /print", r.URL.Path), http.StatusNotFound)
return
}
if r.Method != "POST" {
http.Error(w, "Only the POST method is supported for the path /print.", http.StatusMethodNotAllowed)
return
}
// Let's mark the certificate as "printable" in Kubernetes.
cert := CertFromContext(r.Context())
certName := cert.ObjectMeta.Name
fetchKey := FetchKeyFromContext(r.Context())
if cert.ObjectMeta.Annotations == nil {
cert.ObjectMeta.Annotations = make(map[string]string)
}
cert.ObjectMeta.Annotations[AnnotationPrint] = "true"
_, err := cmclient.CertmanagerV1().Certificates(*namespace).Update(r.Context(), cert, metav1.UpdateOptions{})
if err != nil {
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "after-print.html", afterEventPageData{CertName: certName, FetchKey: fetchKey, Error: "Could not trigger certificate printing. Please go to the previous page and press the button again."})
log.Printf("POST /: could not trigger the print of the certificate %s in namespace %s: %v", certName, *namespace, err)
return
}
// Done!
w.WriteHeader(200)
tmpl.ExecuteTemplate(w, "after-print.html", afterEventPageData{CertName: certName, FetchKey: fetchKey})
log.Printf("POST /: the certificate %s in namespace %s was added the annotation print:true", certName, *namespace)
})
}
func downloadCertPage(kclient kubernetes.Interface, ns string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, fmt.Sprintf("Only the GET method is supported supported on the path %s.\n", r.URL.Path), http.StatusMethodNotAllowed)
return
}
cert := CertFromContext(r.Context())
certName := cert.ObjectMeta.Name
secret, err := kclient.CoreV1().Secrets(ns).Get(r.Context(), cert.Spec.SecretName, metav1.GetOptions{})
if err != nil {
http.Error(w, "A certificate already exists, but the secret does not exist. Try again later.", 423)
log.Printf("GET /download: the requested certificate %s in namespace %s exists, but the Secret %s does not.", certName, *namespace, cert.Spec.SecretName)
return
}
certPem, ok := secret.Data["tls.crt"]
if !ok {
w.WriteHeader(423)
tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Error: "Internal issue with the stored certificate in Kubernetes."})
log.Printf("GET /download: the requested certificate %s in namespace %s exists, but the Secret %s does not contain a key 'tls.crt'.", certName, *namespace, cert.Spec.SecretName)
return
}
// Give the PEM-encoded certificate to the user.
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/x-pem-file")
w.Header().Set("Content-Disposition", `attachment; filename="chain.pem"`)
w.Header().Set("Content-Length", strconv.Itoa(len(certPem)))
w.Write(certPem)
})
}
func downloadPrivateKeyPage(kclient kubernetes.Interface, ns string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, fmt.Sprintf("Only the GET method is supported supported on the path %s.\n", r.URL.Path), http.StatusMethodNotAllowed)
return
}
cert := CertFromContext(r.Context())
certName := cert.ObjectMeta.Name
secret, err := kclient.CoreV1().Secrets(ns).Get(r.Context(), cert.Spec.SecretName, metav1.GetOptions{})
if err != nil {
http.Error(w, "A certificate already exists, but the secret does not exist. Try again later.", 423)
log.Printf("GET /download: the requested certificate %s in namespace %s exists, but the Secret %s does not.", certName, *namespace, cert.Spec.SecretName)
return
}
keyPEM, ok := secret.Data["tls.key"]
if !ok {
w.WriteHeader(423)
tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Error: "Internal issue with the stored certificate in Kubernetes."})
log.Printf("GET /downloadpkey: the requested certificate %s in namespace %s exists, but the Secret %s does not contain a key 'tls.crt'.", certName, *namespace, cert.Spec.SecretName)
return
}
// Give the PEM-encoded private key to the user.
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/x-pem-file")
w.Header().Set("Content-Disposition", `attachment; filename="pkey.pem"`)
w.Header().Set("Content-Length", strconv.Itoa(len(keyPEM)))
w.Write(keyPEM)
})
}
func downloadTarPage(kclient kubernetes.Interface, ns string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, fmt.Sprintf("Only the GET method is supported supported on the path %s.\n", r.URL.Path), http.StatusMethodNotAllowed)
return
}
cert := CertFromContext(r.Context())
certName := cert.ObjectMeta.Name
secret, err := kclient.CoreV1().Secrets(ns).Get(r.Context(), cert.Spec.SecretName, metav1.GetOptions{})
if err != nil {
http.Error(w, "A certificate already exists, but the secret does not exist. Try again later.", 423)
log.Printf("GET /download: the requested certificate %s in namespace %s exists, but the Secret %s does not.", certName, *namespace, cert.Spec.SecretName)
return
}
certPEM, ok := secret.Data["tls.crt"]
if !ok {
w.WriteHeader(423)
tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Error: "Internal issue with the stored certificate in Kubernetes."})
log.Printf("GET /download: the requested certificate %s in namespace %s exists, but the Secret %s does not contain a key 'tls.crt'.", certName, *namespace, cert.Spec.SecretName)
return
}
keyPEM, ok := secret.Data["tls.key"]
if !ok {
w.WriteHeader(423)
tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Error: "Internal issue with the stored certificate in Kubernetes."})
log.Printf("GET /downloadpkey: the requested certificate %s in namespace %s exists, but the Secret %s does not contain a key 'tls.crt'.", certName, *namespace, cert.Spec.SecretName)
return
}
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
var files = []struct {
Name string
Body []byte
Mode int64
}{
{"chain.pem", certPEM, 0o600},
{"pkey.pem", keyPEM, 0o600},
{"sign.sh", []byte(signSH), 0o700},
{"README.md", []byte(signREADME), 0o600},
}
for _, file := range files {
hdr := &tar.Header{
Name: file.Name,
Mode: file.Mode,
Size: int64(len(file.Body)),
}
if err := tw.WriteHeader(hdr); err != nil {
http.Error(w, "failed to write tar header", 500)
log.Printf("failed to write tar header: %v", err)
return
}
if _, err := tw.Write(file.Body); err != nil {
http.Error(w, "failed to write tar body", 500)
log.Printf("failed to write tar body: %v", err)
return
}
}
if err := tw.Close(); err != nil {
http.Error(w, "failed to write tar file", 500)
log.Printf("failed to write tar file: %v", err)
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/x-tar")
w.Header().Set("Content-Disposition", `attachment; filename="cert-manager-bundle.tar"`)
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
w.Write(buf.Bytes())
})
}
func signGuestbookPage(guestbookURL string, remoteRoots *x509.CertPool, kclient kubernetes.Interface, namespace string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, fmt.Sprintf("Only the POST method is supported on the path %s\n", r.URL.Path), http.StatusMethodNotAllowed)
return
}
cert := CertFromContext(r.Context())
certName := cert.ObjectMeta.Name
fetchKey := FetchKeyFromContext(r.Context())
secret, err := kclient.CoreV1().Secrets(namespace).Get(r.Context(), cert.Spec.SecretName, metav1.GetOptions{})
if err != nil {
http.Error(w, "A certificate already exists, but the secret does not exist. Try again later.", 423)
log.Printf("POST /sign-guestbook: the requested certificate %s in namespace %s exists, but the Secret %s does not.", certName, namespace, cert.Spec.SecretName)
return
}
certPEM, ok := secret.Data["tls.crt"]
if !ok {
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "after-sign.html", afterEventPageData{CertName: certName, FetchKey: fetchKey, Error: "Internal issue with stored certificate"})
log.Printf("POST /sign-guestbook: the requested certificate %s in namespace %s exists, but the Secret %s does not contain a key 'tls.crt'.", certName, namespace, cert.Spec.SecretName)
return
}
keyPEM, ok := secret.Data["tls.key"]
if !ok {
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "after-sign.html", afterEventPageData{CertName: certName, FetchKey: fetchKey, Error: "Internal issue with stored certificate"})
log.Printf("POST /sign-guestbook: the requested certificate %s in namespace %s exists, but the Secret %s does not contain a key 'tls.crt'.", certName, namespace, cert.Spec.SecretName)
return
}
clientCertKeyPair, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "after-sign.html", afterEventPageData{CertName: certName, FetchKey: fetchKey, Error: "Internal issue with stored certificate"})
log.Printf("POST /sign-guestbook: invalid certificate: %s", err)
return
}
transport := &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{clientCertKeyPair},
RootCAs: remoteRoots,
},
}
if *guestbookLocal {
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// redirect all connections to 127.0.0.1
// should only be used for dev
dialer := &net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 2 * time.Second,
}
addr = "127.0.0.1" + addr[strings.LastIndex(addr, ":"):]
return dialer.DialContext(ctx, network, addr)
}
}
guestbookClient := &http.Client{
Transport: transport,
Timeout: 15 * time.Second,
}
postValues := url.Values{}
postValues.Add("message", "hello from the cert-manager kiosk")
req, err := http.NewRequestWithContext(r.Context(), "POST", guestbookURL, strings.NewReader(postValues.Encode()))
if err != nil {
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "after-sign.html", afterEventPageData{CertName: certName, FetchKey: fetchKey, Error: "Internal issue with creating request for guestbook"})
log.Printf("POST /sign-guestbook: couldn't create request: %s", err)
return
}
req.Header.Add("content-type", "application/x-www-form-urlencoded")
req.Header.Add("user-agent", "kiosk")
req.Header.Add("host", "guestbook.print-your-cert.cert-manager.io")
guestbookResponse, err := guestbookClient.Do(req)
if err != nil {
// 503 might not be right but this is a demo, so we'll just use it unconditionally for simplicity
w.WriteHeader(503)
tmpl.ExecuteTemplate(w, "after-sign.html", afterEventPageData{CertName: certName, FetchKey: fetchKey, Error: "Internal issue with creating request for guestbook"})
log.Printf("POST /sign-guestbook: couldn't execute request: %s", err)
return
}
defer guestbookResponse.Body.Close()
if guestbookResponse.StatusCode != http.StatusOK {
body, err := io.ReadAll(guestbookResponse.Body)
if err != nil {
log.Println("failed to read error response body")
} else {
log.Printf("failed to sign guestbook: %s", string(body))
}
w.WriteHeader(503)
tmpl.ExecuteTemplate(w, "after-sign.html", afterEventPageData{CertName: certName, FetchKey: fetchKey, Error: fmt.Sprintf("Got error %d when trying to sign guestbook", guestbookResponse.StatusCode)})
return
}
w.WriteHeader(200)
tmpl.ExecuteTemplate(w, "after-sign.html", afterEventPageData{
CertName: certName,
FetchKey: fetchKey,
})
})
}
func parseNameAndEmail(cert *certmanagerv1.Certificate) (string, string, error) {
if cert == nil {
return "", "", errors.New("empty cert")
}
name := cert.Spec.CommonName
if name == "" {
return "", "", errors.New("invalid certificate: empty name in CommonName")
}
if len(cert.Spec.EmailAddresses) != 1 {
return "", "", fmt.Errorf("invalid certificate: expected 1 email address but got %d", len(cert.Spec.EmailAddresses))
}
email := cert.Spec.EmailAddresses[0]
return name, email, nil
}
// After the user clicks "Get your certificate" on the landing page, and if the
// certificate was successfully created, the user is redirected to /certificate
// to "visualize" their certificate and to print it. This page is similar to the
// one on GitHub Pages (https://cert-manager.github.io/print-your-cert?asn1=...)
// except that is also shows whether the certificate was printed or not.
//
// GET /certificate?certName=abcdef123 HTTP/2.0
func certificatePage(kclient kubernetes.Interface, ns string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/certificate" {
http.Error(w, fmt.Sprintf("The path %s contains is expected to be /.", r.URL.Path), http.StatusNotFound)
return
}
if r.Method != "GET" {
http.Error(w, fmt.Sprintf("The method %s is not allowed on %s", r.Method, r.URL.Path), http.StatusMethodNotAllowed)
return
}
cert := CertFromContext(r.Context())
fetchKey := FetchKeyFromContext(r.Context())
certName := cert.ObjectMeta.Name
debug := r.URL.Query().Get("debug") != ""
debugMsg := ""
if debug {
debugMsg += fmt.Sprintf("The annotation 'print' is set to '%s'.\nThe certificate conditions are:", cert.Annotations[AnnotationPrint])
for _, cond := range cert.Status.Conditions {
debugMsg += fmt.Sprintf("\n %s: %s (%s: %s)", cond.Type, cond.Status, cond.Reason, cond.Message)
}
}
personName, email, err := parseNameAndEmail(cert)
if err != nil {
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Error: "There is an issue with the certificate's common name. Please let know the cert-manager booth staff.", Debug: debugMsg})
if err != nil {
log.Printf("GET /certificate 500: while executing the template: %v", err)
}
log.Printf("GET /certificate: 500: certificate %s: %v", certName, err)
return
}
// Success: we found the Certificate in Kubernetes. Let's see if it's ready.
if !isReady(cert) {
w.WriteHeader(423)
err = tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Name: personName, Email: email, CertName: certName, FetchKey: fetchKey, CanPrint: false, MarkedToBePrinted: false, AlreadyPrinted: false, Refresh: 5, Debug: debugMsg})
if err != nil {
log.Printf("GET /certificate: 423: while executing the template: %v", err)
}
log.Printf("GET /certificate: 423: the requested certificate %s in namespace %s is not ready yet.", certName, *namespace)
return
}
// Let's show the user the Certificate.
secret, err := kclient.CoreV1().Secrets(ns).Get(r.Context(), cert.Spec.SecretName, metav1.GetOptions{})
if err != nil {
w.WriteHeader(423)
err = tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Name: personName, Email: email, CertName: certName, FetchKey: fetchKey, Refresh: 5, Error: "A certificate already exists, but the Secret does not exist; the page will be reloaded in 5 seconds until this issue is resolved.", Debug: debugMsg})
if err != nil {
log.Printf("GET /certificate: 423: while executing the template: %v", err)
}
log.Printf("GET /certificate: 423: the requested certificate %s in namespace %s exists, but the Secret %s does not.", certName, *namespace, cert.Spec.SecretName)
return
}
// Let's show the user the Certificate. First, parse the X.509
// certificate from the Secret.
certPem, ok := secret.Data["tls.crt"]
if !ok {
w.WriteHeader(423)
err = tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Name: personName, Email: email, CertName: certName, FetchKey: fetchKey, Refresh: 5, Error: "Internal issue with the stored certificate in Kubernetes. The page will be reloaded every 5 seconds until this issue is resolved.", Debug: debugMsg})
if err != nil {
log.Printf("GET /certificate: 423: while executing the template: %v", err)
}
log.Printf("GET /certificate: 423: the requested certificate %s in namespace %s exists, but the Secret %s does not contain a key 'tls.crt'.", certName, *namespace, cert.Spec.SecretName)
return
}
// Parse the certificate.
certBlock, _ := pem.Decode(certPem)
x509Cert, err := x509.ParseCertificate(certBlock.Bytes)
if err != nil {
w.WriteHeader(500)
err = tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Name: personName, Email: email, CertName: certName, FetchKey: fetchKey, Error: "Internal issue with parsing the issued certificate when parsing it.", Debug: debugMsg})
if err != nil {
log.Printf("GET /certificate: 500: while executing the template: %v", err)
}
log.Printf("GET /certificate: 500: the requested certificate %s in namespace %s exists, but the Secret %s contains in its tls.crt field an invalid PEM certificate", certName, *namespace, cert.Spec.SecretName)
return
}
alreadyPrinted := isAlreadyPrinted(cert)
pendingPrint := isPendingPrint(cert)
canPressPrintButton := !pendingPrint && !alreadyPrinted
// Let's show the user the Certificate.
certificateHTMLData := certificateToHTML(x509Cert)
log.Printf("GET /certificate: 200: certificate %s in namespace %s was found", certName, *namespace)
err = tmpl.ExecuteTemplate(w, "certificate.html", certificatePageData{Name: personName, Email: email, CertName: certName, FetchKey: fetchKey, Certificate: &certificateHTMLData, CanPrint: canPressPrintButton, MarkedToBePrinted: pendingPrint, AlreadyPrinted: alreadyPrinted, Debug: debugMsg})
if err != nil {
log.Printf("GET /certificate: 200: while executing the template: %v", err)
}
})
}
func isPendingPrint(cert *certmanagerv1.Certificate) bool {
return markedToBePrinted(cert) && !isAlreadyPrinted(cert)
}
// When the user goes to /list, they see a list of the previously submitted
// name and emails.
//
// GET /list HTTP/2.0
func listPage(kclient kubernetes.Interface, cmclient cmversioned.Interface) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, fmt.Sprintf("Only the GET method is supported supported on the path %s.\n", r.URL.Path), http.StatusMethodNotAllowed)
return
}
refreshStr := r.URL.Query().Get("refresh")
if refreshStr == "" {
http.Redirect(w, r, "/list?refresh=5", 301)
return
}
refresh, err := strconv.Atoi(refreshStr)
if err != nil {
http.Error(w, "Invalid refresh parameter. It should be an integer greater or equal to 0.", 400)
log.Printf("GET /list: 400: invalid refresh parameter %q, should be >=0", refreshStr)
return
}
// Let's get the list of certificates.
certs, err := cmclient.CertmanagerV1().Certificates(*namespace).List(r.Context(), metav1.ListOptions{})
if err != nil {
w.WriteHeader(500)
err = tmpl.ExecuteTemplate(w, "list.html", listPageData{Error: "Internal error: cannot list the last certificates that were printed."})
if err != nil {
log.Printf("GET /list: 500: while executing the template: %v", err)
}
log.Printf("GET /list: 500: %v", err)
return
}
// We want the newest certificates first.
sort.Slice(certs.Items, func(i, j int) bool {
return certs.Items[i].CreationTimestamp.Time.After(certs.Items[j].CreationTimestamp.Time)
})
var certsOut []certificateItem
for i, cert := range certs.Items {
personName, email, err := parseNameAndEmail(&cert)
if err != nil {
log.Printf("GET /list: while listing certificates, the certificate %s was skipped: %v", cert.Name, err)
continue
}
certsOut = append(certsOut, certificateItem{
Position: i + 1,
Name: personName,
Email: email,
State: stateOfCert(cert),
Date: cert.Status.NotBefore.Time,
})
}
// We also want to display the count of printed certificates.
var printed, pending int
for _, c := range certs.Items {
if isAlreadyPrinted(&c) {
printed++
}
if isPendingPrint(&c) {
pending++
}
}
err = tmpl.ExecuteTemplate(w, "list.html", listPageData{Certificates: certsOut, Refresh: refresh, CountPrinted: printed, CountPending: pending})
if err != nil {
log.Printf("GET /list: 200: while executing the template: %v", err)
}
}
}
func markedToBePrinted(cert *certmanagerv1.Certificate) bool {
return cert.Annotations[AnnotationPrint] == "true"
}
func isAlreadyPrinted(cert *certmanagerv1.Certificate) bool {
cond := apiutil.GetCertificateCondition(cert, ConditionPrinted)
alreadyPrinted := cond != nil && cond.Status == "True"
return alreadyPrinted
}
func isReady(cert *certmanagerv1.Certificate) bool {
cond := apiutil.GetCertificateCondition(cert, "Ready")
isReady := cond != nil && cond.Status == "True"
return isReady
}
func emailToCertName(email string) string {
h := sha256.Sum256([]byte(email))
return hex.EncodeToString(h[:])
}
func stateOfCert(cert certmanagerv1.Certificate) StateCert {
switch {
case isAlreadyPrinted(&cert):
return StatePrinted
case isReady(&cert):
return StateReady
default:
return StateUnknown
}
}
type landingPageData struct {
Name string // Optional.
Email string // Optional.
Certificate *certificateTemplateData // Optional.
Error string // Optional.
Message string // Optional.
CanPrint bool // Optional.
AlreadyPrinted bool // Optional.
MarkedToBePrinted bool // Optional.
Debug string // Optional.
Refresh int // Optional. In seconds.
CountPrinted int // Mandatory.
CountPending int // Mandatory.
Duplicate bool
}
type afterEventPageData struct {
CertName string // Mandatory.
FetchKey string // Mandatory.
Error string // Optional.
}
type StateCert string
var (
StateUnknown StateCert = "Unknown"
StateCreated StateCert = "CertificateCreated"
StateReady StateCert = "CertificateReady"
StatePendingPrint StateCert = "PrintPending"
StatePrinted StateCert = "Printed"
)
type errorPageData struct {
Error string
}
type listPageData struct {
Certificates []certificateItem // Optional.
Error string // Optional.
Refresh int // Optional. In seconds.
CountPrinted int // Mandatory.
CountPending int // Mandatory.
}
type certificateItem struct {
Position int
Name string
Email string
Date time.Time
State StateCert
}
type certificateTemplateData struct {
PublicKeyAlgorithm string
Serial string
Subject string
Issuer string
NotBefore string
NotAfter string
}
// For certificate.html.
type certificatePageData struct {
Name string // Optional.
Email string // Optional.
CertName string // Mandatory.
FetchKey string // Required if successful
Certificate *certificateTemplateData // Optional.
Error string // Optional.
Message string // Optional.
CanPrint bool // Optional.
AlreadyPrinted bool // Optional.
MarkedToBePrinted bool // Optional.
Debug string // Optional.
Refresh int // Optional. In seconds.
}
func certificateToHTML(cert *x509.Certificate) certificateTemplateData {
data := certificateTemplateData{
PublicKeyAlgorithm: getPublicKeyAlgorithm(cert.PublicKeyAlgorithm, cert.PublicKey),
Serial: cert.SerialNumber.String(),
Subject: cert.Subject.CommonName,
Issuer: cert.Issuer.CommonName,
NotBefore: cert.NotBefore.Format(time.RFC3339),
NotAfter: cert.NotAfter.Format(time.RFC3339),
}
return data
}
type contextKey int
const (
certificateContextKey contextKey = 0
fetchKeyContextKey contextKey = 1
)
func CertFromContext(ctx context.Context) *certmanagerv1.Certificate {
cert, ok := ctx.Value(certificateContextKey).(*certmanagerv1.Certificate)
if !ok {
panic("CertFromContext called without certFetch middleware being called first")
}
return cert
}
func FetchKeyFromContext(ctx context.Context) string {
cert, ok := ctx.Value(fetchKeyContextKey).(string)
if !ok {
panic("FetchKeyFromContext called without certFetch middleware being called first")
}
return cert
}
func cachingHeadersMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Vary", "Accept-Encoding")
w.Header().Set("Cache-Control", "public, max-age=7776000")
h.ServeHTTP(w, req)
})
}
func certFetchMiddleware(cmclient cmversioned.Interface, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var certName string
var fetchKey string
var source string
if r.Method != "GET" {
source = "form entry"
err := r.ParseForm()
if err != nil {
w.WriteHeader(400)
tmpl.ExecuteTemplate(w, "error.html", errorPageData{Error: "Failed to parse a valid POSTed form"})
log.Printf("certFetch: error while parsing form: %v", err)
return
}
certName = r.Form.Get("certName")
fetchKey = r.Form.Get("fetchKey")
} else {
source = "query parameter"
certName = r.URL.Query().Get("certName")
fetchKey = r.URL.Query().Get("fetchKey")
}
if certName == "" {
w.WriteHeader(400)
tmpl.ExecuteTemplate(w, "error.html", errorPageData{Error: fmt.Sprintf("Missing required %s certName", source)})
return
}
if fetchKey == "" {
w.WriteHeader(401)
tmpl.ExecuteTemplate(w, "error.html", errorPageData{Error: fmt.Sprintf("Missing required %s fetchKey", source)})
return
}
cert, err := cmclient.CertmanagerV1().Certificates(*namespace).Get(r.Context(), certName, metav1.GetOptions{})
switch {
case k8serrors.IsNotFound(err):
w.WriteHeader(404)
tmpl.ExecuteTemplate(w, "error.html", errorPageData{Error: "No certificate found matching that name"})
log.Printf("certFetch: the certificate named %s in namespace %s was not found in Kubernetes: %v", certName, *namespace, err)
return
case err != nil:
w.WriteHeader(500)
tmpl.ExecuteTemplate(w, "error.html", errorPageData{Error: "Failed getting the certificate resource in Kubernetes."})
log.Printf("certFetch: while getting the Certificate %s in namespace %s in Kubernetes: %v", certName, *namespace, err)
return