github.com/blend/go-sdk@v1.20220411.3/certutil/cert_file_watcher_test.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package certutil 9 10 import ( 11 "crypto/x509" 12 "io" 13 "os" 14 "path/filepath" 15 "testing" 16 17 "github.com/blend/go-sdk/assert" 18 ) 19 20 func TestCertFileWatcher(t *testing.T) { 21 its := assert.New(t) 22 23 tempDir, err := os.MkdirTemp("", "") 24 its.Nil(err) 25 defer func() { _ = os.RemoveAll(tempDir) }() 26 27 tempCertPath := filepath.Join(tempDir, "tls.crt") 28 tempKeyPath := filepath.Join(tempDir, "tls.key") 29 30 err = copyFile("testdata/server.cert.pem", tempCertPath) 31 its.Nil(err) 32 err = copyFile("testdata/server.key.pem", tempKeyPath) 33 its.Nil(err) 34 35 w, err := NewCertFileWatcher( 36 KeyPair{CertPath: tempCertPath, KeyPath: tempKeyPath}, 37 ) 38 its.Nil(err) 39 40 its.Equal(tempCertPath, w.CertPath()) 41 its.Equal(tempKeyPath, w.KeyPath()) 42 43 cert := w.Certificate() 44 its.NotNil(cert) 45 46 err = copyFile("testdata/alt-server.cert.pem", tempCertPath) 47 its.Nil(err) 48 err = copyFile("testdata/alt-server.key.pem", tempKeyPath) 49 its.Nil(err) 50 51 err = w.Reload() 52 its.Nil(err) 53 54 newCert := w.Certificate() 55 its.NotNil(newCert) 56 57 cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) 58 its.Nil(err) 59 newCert.Leaf, err = x509.ParseCertificate(newCert.Certificate[0]) 60 its.Nil(err) 61 62 its.NotEqual(cert.Leaf.SerialNumber.String(), newCert.Leaf.SerialNumber.String()) 63 } 64 65 func copyFile(src, dst string) error { 66 srcFile, err := os.Open(src) 67 if err != nil { 68 return err 69 } 70 defer srcFile.Close() 71 72 dstFile, err := os.Create(dst) 73 if err != nil { 74 return err 75 } 76 defer dstFile.Close() 77 _, err = io.Copy(dstFile, srcFile) 78 if err != nil { 79 return err 80 } 81 return nil 82 }