k8s.io/kubernetes@v1.29.3/pkg/controller/certificates/authority/policies_test.go (about) 1 /* 2 Copyright 2019 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package authority 18 19 import ( 20 "crypto/x509" 21 "fmt" 22 "reflect" 23 "testing" 24 25 capi "k8s.io/api/certificates/v1" 26 ) 27 28 func TestKeyUsagesFromStrings(t *testing.T) { 29 testcases := []struct { 30 usages []capi.KeyUsage 31 expectedKeyUsage x509.KeyUsage 32 expectedExtKeyUsage []x509.ExtKeyUsage 33 expectErr bool 34 }{ 35 { 36 usages: []capi.KeyUsage{"signing"}, 37 expectedKeyUsage: x509.KeyUsageDigitalSignature, 38 expectedExtKeyUsage: nil, 39 expectErr: false, 40 }, 41 { 42 usages: []capi.KeyUsage{"client auth"}, 43 expectedKeyUsage: 0, 44 expectedExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, 45 expectErr: false, 46 }, 47 { 48 usages: []capi.KeyUsage{"client auth", "client auth"}, 49 expectedKeyUsage: 0, 50 expectedExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, 51 expectErr: false, 52 }, 53 { 54 usages: []capi.KeyUsage{"cert sign", "encipher only"}, 55 expectedKeyUsage: x509.KeyUsageCertSign | x509.KeyUsageEncipherOnly, 56 expectedExtKeyUsage: nil, 57 expectErr: false, 58 }, 59 { 60 usages: []capi.KeyUsage{"ocsp signing", "crl sign", "s/mime", "content commitment"}, 61 expectedKeyUsage: x509.KeyUsageCRLSign | x509.KeyUsageContentCommitment, 62 expectedExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageEmailProtection, x509.ExtKeyUsageOCSPSigning}, 63 expectErr: false, 64 }, 65 { 66 usages: []capi.KeyUsage{"unsupported string"}, 67 expectedKeyUsage: 0, 68 expectedExtKeyUsage: nil, 69 expectErr: true, 70 }, 71 } 72 73 for _, tc := range testcases { 74 t.Run(fmt.Sprint(tc.usages), func(t *testing.T) { 75 ku, eku, err := keyUsagesFromStrings(tc.usages) 76 77 if tc.expectErr { 78 if err == nil { 79 t.Errorf("did not return an error, but expected one") 80 } 81 return 82 } 83 84 if err != nil { 85 t.Errorf("unexpected error: %v", err) 86 } 87 88 if ku != tc.expectedKeyUsage || !reflect.DeepEqual(eku, tc.expectedExtKeyUsage) { 89 t.Errorf("got=(%v, %v), want=(%v, %v)", ku, eku, tc.expectedKeyUsage, tc.expectedExtKeyUsage) 90 } 91 }) 92 } 93 }