Files
cert-manager/pkg/controller/expcertificates/util_test.go
T
2020-04-16 19:10:41 +01:00

100 lines
2.9 KiB
Go

/*
Copyright 2020 The Jetstack cert-manager contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package certificates
import (
"crypto"
"reflect"
"testing"
cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha2"
"github.com/jetstack/cert-manager/pkg/util/pki"
)
func mustGenerateRSA(t *testing.T, keySize int) crypto.PrivateKey {
pk, err := pki.GenerateRSAPrivateKey(keySize)
if err != nil {
t.Fatal(err)
}
return pk
}
func mustGenerateECDSA(t *testing.T, keySize int) crypto.PrivateKey {
pk, err := pki.GenerateECPrivateKey(keySize)
if err != nil {
t.Fatal(err)
}
return pk
}
func TestPrivateKeyMatchesSpec(t *testing.T) {
tests := map[string]struct {
key crypto.PrivateKey
expectedAlgo cmapi.KeyAlgorithm
expectedSize int
violations []string
err string
}{
"should match if keySize and algorithm are correct (RSA)": {
key: mustGenerateRSA(t, 2048),
expectedAlgo: cmapi.RSAKeyAlgorithm,
expectedSize: 2048,
},
"should not match if RSA keySize is incorrect": {
key: mustGenerateRSA(t, 2048),
expectedAlgo: cmapi.RSAKeyAlgorithm,
expectedSize: 4096,
violations: []string{"spec.keySize"},
},
"should match if keySize and algorithm are correct (ECDSA)": {
key: mustGenerateECDSA(t, pki.ECCurve256),
expectedAlgo: cmapi.ECDSAKeyAlgorithm,
expectedSize: 256,
},
"should not match if ECDSA keySize is incorrect": {
key: mustGenerateECDSA(t, pki.ECCurve256),
expectedAlgo: cmapi.ECDSAKeyAlgorithm,
expectedSize: pki.ECCurve521,
violations: []string{"spec.keySize"},
},
"should not match if keyAlgorithm is incorrect": {
key: mustGenerateECDSA(t, pki.ECCurve256),
expectedAlgo: cmapi.RSAKeyAlgorithm,
expectedSize: 2048,
violations: []string{"spec.keyAlgorithm"},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
violations, err := PrivateKeyMatchesSpec(test.key, cmapi.CertificateSpec{KeyAlgorithm: test.expectedAlgo, KeySize: test.expectedSize})
switch {
case err != nil:
if test.err != err.Error() {
t.Errorf("error text did not match, got=%s, exp=%s", err.Error(), test.err)
}
default:
if test.err != "" {
t.Errorf("got no error but expected: %s", test.err)
}
}
if !reflect.DeepEqual(violations, test.violations) {
t.Errorf("violations did not match, got=%s, exp=%s", violations, test.violations)
}
})
}
}