From f3635c2d1543055e9067caee6366d202c8deccf2 Mon Sep 17 00:00:00 2001 From: Chelsea Holland Komlo Date: Tue, 29 May 2018 18:44:30 -0400 Subject: [PATCH] refactor to remove duplication --- helper/tlsutil/config.go | 44 ++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/helper/tlsutil/config.go b/helper/tlsutil/config.go index 851316cd42e1..690685781a72 100644 --- a/helper/tlsutil/config.go +++ b/helper/tlsutil/config.go @@ -148,38 +148,38 @@ func (c *Config) AppendCA(pool *x509.CertPool) error { } block, rest := pem.Decode(data) - if block == nil { - return fmt.Errorf("Failed to decode CA file from pem format") + if err := validateCertificate(block); err != nil { + return err } - // Parse the certificate to ensure that it is properly formatted - if _, err := x509.ParseCertificates(block.Bytes); err != nil { - return fmt.Errorf("Failed to parse CA file: %v", err) + for len(rest) > 0 { + block, rest = pem.Decode(rest) + if err := validateCertificate(block); err != nil { + return err + } + + if len(rest) == 0 { + break + } } if !pool.AppendCertsFromPEM(data) { return fmt.Errorf("Failed to add any CA certificates") } - for len(rest) > 0 { - block, rest = pem.Decode(rest) - - if block == nil { - return fmt.Errorf("Failed to decode CA file from pem format") - } - - // Parse the certificate to ensure that it is properly formatted - if _, err := x509.ParseCertificates(block.Bytes); err != nil { - return fmt.Errorf("Failed to parse CA file: %v", err) - } + return nil +} - if !pool.AppendCertsFromPEM(data) { - return fmt.Errorf("Failed to add any CA certificates") - } +// validateCertificate checks to ensure a certificate is valid. If it is not, +// return a descriptive error of why the certificate is invalid. +func validateCertificate(block *pem.Block) error { + if block == nil { + return fmt.Errorf("Failed to decode CA file from pem format") + } - if len(rest) == 0 { - break - } + // Parse the certificate to ensure that it is properly formatted + if _, err := x509.ParseCertificates(block.Bytes); err != nil { + return fmt.Errorf("Failed to parse CA file: %v", err) } return nil