github.com/outbrain/consul@v1.4.5/agent/connect/testing_ca_test.go (about) 1 package connect 2 3 import ( 4 "io/ioutil" 5 "os" 6 "os/exec" 7 "path/filepath" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 // hasOpenSSL is used to determine if the openssl CLI exists for unit tests. 14 var hasOpenSSL bool 15 16 func init() { 17 _, err := exec.LookPath("openssl") 18 hasOpenSSL = err == nil 19 } 20 21 // Test that the TestCA and TestLeaf functions generate valid certificates. 22 func TestTestCAAndLeaf(t *testing.T) { 23 if !hasOpenSSL { 24 t.Skip("openssl not found") 25 return 26 } 27 28 assert := assert.New(t) 29 30 // Create the certs 31 ca := TestCA(t, nil) 32 leaf, _ := TestLeaf(t, "web", ca) 33 34 // Create a temporary directory for storing the certs 35 td, err := ioutil.TempDir("", "consul") 36 assert.Nil(err) 37 defer os.RemoveAll(td) 38 39 // Write the cert 40 assert.Nil(ioutil.WriteFile(filepath.Join(td, "ca.pem"), []byte(ca.RootCert), 0644)) 41 assert.Nil(ioutil.WriteFile(filepath.Join(td, "leaf.pem"), []byte(leaf), 0644)) 42 43 // Use OpenSSL to verify so we have an external, known-working process 44 // that can verify this outside of our own implementations. 45 cmd := exec.Command( 46 "openssl", "verify", "-verbose", "-CAfile", "ca.pem", "leaf.pem") 47 cmd.Dir = td 48 output, err := cmd.Output() 49 t.Log(string(output)) 50 assert.Nil(err) 51 } 52 53 // Test cross-signing. 54 func TestTestCAAndLeaf_xc(t *testing.T) { 55 if !hasOpenSSL { 56 t.Skip("openssl not found") 57 return 58 } 59 60 assert := assert.New(t) 61 62 // Create the certs 63 ca1 := TestCA(t, nil) 64 ca2 := TestCA(t, ca1) 65 leaf1, _ := TestLeaf(t, "web", ca1) 66 leaf2, _ := TestLeaf(t, "web", ca2) 67 68 // Create a temporary directory for storing the certs 69 td, err := ioutil.TempDir("", "consul") 70 assert.Nil(err) 71 defer os.RemoveAll(td) 72 73 // Write the cert 74 xcbundle := []byte(ca1.RootCert) 75 xcbundle = append(xcbundle, '\n') 76 xcbundle = append(xcbundle, []byte(ca2.SigningCert)...) 77 assert.Nil(ioutil.WriteFile(filepath.Join(td, "ca.pem"), xcbundle, 0644)) 78 assert.Nil(ioutil.WriteFile(filepath.Join(td, "leaf1.pem"), []byte(leaf1), 0644)) 79 assert.Nil(ioutil.WriteFile(filepath.Join(td, "leaf2.pem"), []byte(leaf2), 0644)) 80 81 // OpenSSL verify the cross-signed leaf (leaf2) 82 { 83 cmd := exec.Command( 84 "openssl", "verify", "-verbose", "-CAfile", "ca.pem", "leaf2.pem") 85 cmd.Dir = td 86 output, err := cmd.Output() 87 t.Log(string(output)) 88 assert.Nil(err) 89 } 90 91 // OpenSSL verify the old leaf (leaf1) 92 { 93 cmd := exec.Command( 94 "openssl", "verify", "-verbose", "-CAfile", "ca.pem", "leaf1.pem") 95 cmd.Dir = td 96 output, err := cmd.Output() 97 t.Log(string(output)) 98 assert.Nil(err) 99 } 100 }