github.com/openshift/installer@v1.4.17/pkg/asset/tls/certkey_test.go (about) 1 package tls 2 3 import ( 4 "context" 5 "crypto/x509" 6 "crypto/x509/pkix" 7 "net" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func TestSignedCertKeyGenerate(t *testing.T) { 14 tests := []struct { 15 name string 16 certCfg *CertCfg 17 filenameBase string 18 certFileName string 19 appendParent AppendParentChoice 20 errString string 21 }{ 22 { 23 name: "simple ca", 24 certCfg: &CertCfg{ 25 Subject: pkix.Name{CommonName: "test0-ca", OrganizationalUnit: []string{"openshift"}}, 26 KeyUsages: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, 27 Validity: ValidityTenYears, 28 DNSNames: []string{"test.openshift.io"}, 29 }, 30 filenameBase: "test0-ca", 31 appendParent: DoNotAppendParent, 32 }, 33 { 34 name: "more complicated ca", 35 certCfg: &CertCfg{ 36 Subject: pkix.Name{CommonName: "test1-ca", OrganizationalUnit: []string{"openshift"}}, 37 KeyUsages: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, 38 Validity: ValidityTenYears, 39 DNSNames: []string{"test.openshift.io"}, 40 IPAddresses: []net.IP{net.ParseIP("10.0.0.1")}, 41 }, 42 filenameBase: "test1-ca", 43 appendParent: AppendParent, 44 }, 45 } 46 47 for _, tt := range tests { 48 t.Run(tt.name, func(t *testing.T) { 49 rootCA := &RootCA{} 50 err := rootCA.Generate(context.Background(), nil) 51 assert.NoError(t, err, "failed to generate root CA") 52 53 certKey := &SignedCertKey{} 54 err = certKey.Generate(context.Background(), tt.certCfg, rootCA, tt.filenameBase, tt.appendParent) 55 if err != nil { 56 assert.EqualErrorf(t, err, tt.errString, tt.name) 57 return 58 } else if tt.errString != "" { 59 t.Errorf("expect error %v, saw nil", err) 60 } 61 62 actualFiles := certKey.Files() 63 64 assert.Equal(t, 2, len(actualFiles), "unexpected number of files") 65 assert.Equal(t, assetFilePath(tt.filenameBase+".key"), actualFiles[0].Filename, "unexpected key file name") 66 assert.Equal(t, assetFilePath(tt.filenameBase+".crt"), actualFiles[1].Filename, "unexpected cert file name") 67 68 assert.Equal(t, certKey.Key(), actualFiles[0].Data, "key file data does not match key") 69 assert.Equal(t, certKey.Cert(), actualFiles[1].Data, "cert file does not match cert") 70 71 // Briefly check the certs. 72 certPool := x509.NewCertPool() 73 if !certPool.AppendCertsFromPEM(certKey.Cert()) { 74 t.Error("failed to append certs from PEM") 75 } 76 77 opts := x509.VerifyOptions{ 78 Roots: certPool, 79 DNSName: tt.certCfg.Subject.CommonName, 80 } 81 if tt.certCfg.DNSNames != nil { 82 opts.DNSName = "test.openshift.io" 83 } 84 85 cert, err := PemToCertificate(certKey.Cert()) 86 assert.NoError(t, err, tt.name) 87 88 _, err = cert.Verify(opts) 89 assert.NoError(t, err, tt.name) 90 }) 91 } 92 }