istio.io/istio@v0.0.0-20240520182934-d79c90f27776/security/pkg/pki/ca/mock/fakeca.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package mock 16 17 import ( 18 "istio.io/istio/security/pkg/pki/ca" 19 caerror "istio.io/istio/security/pkg/pki/error" 20 "istio.io/istio/security/pkg/pki/util" 21 ) 22 23 // FakeCA is a mock of CertificateAuthority. 24 type FakeCA struct { 25 SignedCert []byte 26 SignErr *caerror.Error 27 KeyCertBundle *util.KeyCertBundle 28 ReceivedIDs []string 29 } 30 31 // Sign returns the SignErr if SignErr is not nil, otherwise, it returns SignedCert. 32 func (ca *FakeCA) Sign(csr []byte, certOpts ca.CertOpts) ([]byte, error) { 33 ca.ReceivedIDs = certOpts.SubjectIDs 34 if ca.SignErr != nil { 35 return nil, ca.SignErr 36 } 37 return ca.SignedCert, nil 38 } 39 40 // SignWithCertChain returns the SignErr if SignErr is not nil, otherwise, it returns SignedCert and the cert chain. 41 func (ca *FakeCA) SignWithCertChain(csr []byte, certOpts ca.CertOpts) ([]string, error) { 42 if ca.SignErr != nil { 43 return nil, ca.SignErr 44 } 45 cert := ca.SignedCert 46 respCertChain := []string{string(cert)} 47 if ca.KeyCertBundle != nil { 48 respCertChain = append(respCertChain, string(ca.KeyCertBundle.GetCertChainPem())) 49 } 50 _, _, _, rootCertBytes := ca.GetCAKeyCertBundle().GetAll() 51 if len(rootCertBytes) != 0 { 52 respCertChain = append(respCertChain, string(rootCertBytes)) 53 } 54 return respCertChain, nil 55 } 56 57 // GetCAKeyCertBundle returns KeyCertBundle if KeyCertBundle is not nil, otherwise, it returns an empty 58 // FakeKeyCertBundle. 59 func (ca *FakeCA) GetCAKeyCertBundle() *util.KeyCertBundle { 60 if ca.KeyCertBundle == nil { 61 return util.NewKeyCertBundleFromPem([]byte{}, []byte("foo"), []byte("fake"), []byte("fake")) 62 } 63 return ca.KeyCertBundle 64 }