github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/certutils/certutils.go (about) 1 package certutils 2 3 import ( 4 "io" 5 "net/http" 6 7 piperhttp "github.com/SAP/jenkins-library/pkg/http" 8 "github.com/SAP/jenkins-library/pkg/log" 9 "github.com/SAP/jenkins-library/pkg/piperutils" 10 "github.com/pkg/errors" 11 ) 12 13 // CertificateUpdate adds certificates to the given truststore 14 func CertificateUpdate(certLinks []string, httpClient piperhttp.Sender, fileUtils piperutils.FileUtils, caCertsFile string) error { 15 // TODO this implementation doesn't work on non-linux machines, is not failsafe and should be implemented differently 16 17 if len(certLinks) == 0 { 18 return nil 19 } 20 21 caCerts, err := fileUtils.FileRead(caCertsFile) 22 if err != nil { 23 return errors.Wrapf(err, "failed to load file '%v'", caCertsFile) 24 } 25 26 byteCerts, err := CertificateDownload(certLinks, httpClient) 27 if err != nil { 28 return err 29 } 30 31 caCerts = append(caCerts, byteCerts...) 32 33 err = fileUtils.FileWrite(caCertsFile, caCerts, 0644) 34 if err != nil { 35 return errors.Wrapf(err, "failed to update file '%v'", caCertsFile) 36 } 37 return nil 38 } 39 40 // CertificateDownload downloads certificates and returns them as a byte slice 41 func CertificateDownload(certLinks []string, client piperhttp.Sender) ([]byte, error) { 42 if len(certLinks) == 0 { 43 return nil, nil 44 } 45 46 var certs []byte 47 for _, certLink := range certLinks { 48 log.Entry().Debugf("Downloading CA certificate from URL: %s", certLink) 49 response, err := client.SendRequest(http.MethodGet, certLink, nil, nil, nil) 50 if err != nil { 51 return nil, errors.Wrap(err, "failed to load certificate from url") 52 } 53 54 content, err := io.ReadAll(response.Body) 55 if err != nil { 56 return nil, errors.Wrap(err, "failed to read response") 57 } 58 _ = response.Body.Close() 59 content = append(content, []byte("\n")...) 60 certs = append(certs, content...) 61 } 62 63 return certs, nil 64 }