github.com/verrazzano/verrazzano-monitoring-operator@v0.0.30/pkg/vmo/certificate_test.go (about) 1 // Copyright (c) 2020, 2021, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 4 package vmo 5 6 import ( 7 "crypto/x509" 8 "encoding/pem" 9 "fmt" 10 "io/ioutil" 11 "os" 12 "testing" 13 14 "github.com/stretchr/testify/assert" 15 ) 16 17 // TestCreateCertificates tests that the certificates needed for webhooks are created 18 // GIVEN an output directory for certificates 19 // 20 // WHEN I call CreateCertificates 21 // THEN all the needed certificate artifacts are created 22 func TestCreateCertificates(t *testing.T) { 23 assert := assert.New(t) 24 25 dir, err := ioutil.TempDir("", "certs") 26 if err != nil { 27 assert.Nil(err, "error should not be returned creating temporary directory") 28 } 29 defer os.RemoveAll(dir) 30 caBundle, err := CreateCertificates(dir) 31 assert.Nil(err, "error should not be returned setting up certificates") 32 assert.NotNil(caBundle, "CA bundle should be returned") 33 34 crtFile := fmt.Sprintf("%s/%s", dir, "tls.crt") 35 keyFile := fmt.Sprintf("%s/%s", dir, "tls.key") 36 assert.FileExists(crtFile, dir, "tls.crt", "expected tls.crt file not found") 37 assert.FileExists(keyFile, dir, "tls.key", "expected tls.key file not found") 38 39 crtBytes, err := ioutil.ReadFile(crtFile) 40 if assert.NoError(err) { 41 block, _ := pem.Decode(crtBytes) 42 assert.NotEmptyf(block, "failed to decode PEM block containing public key") 43 assert.Equal("CERTIFICATE", block.Type) 44 cert, err := x509.ParseCertificate(block.Bytes) 45 if assert.NoError(err) { 46 assert.NotEmpty(cert.DNSNames, "Certificate DNSNames SAN field should not be empty") 47 assert.Equal("verrazzano-monitoring-operator.verrazzano-system.svc", cert.DNSNames[0]) 48 } 49 } 50 } 51 52 // TestCreateWebhookCertificatesFail tests that the certificates needed for webhooks are not created 53 // GIVEN an invalid output directory for certificates 54 // 55 // WHEN I call CreateCertificates 56 // THEN all the needed certificate artifacts are not created 57 func TestCreateWebhookCertificatesFail(t *testing.T) { 58 assert := assert.New(t) 59 60 _, err := CreateCertificates("/bad-dir") 61 assert.Error(err, "error should be returned setting up certificates") 62 }