Skip to content

Commit

Permalink
Improve error handling in verifyConn
Browse files Browse the repository at this point in the history
- Avoid a panic when the http.Get resp is nil by returning the error
  before deferring resp.Body.Close()
- http.Get will not return an error for non-2xx response codes, so check
  the response code explicitly and return an error when it isn't the
  expected 200 response
- Return the error from ioutil.ReadAll
- Use fmt.Errorf across the board
- Include the caURL in the error messages to hopefully make the source
  of errors clearer up the stack
  • Loading branch information
ribbybibby committed Apr 28, 2021
1 parent dbdcbee commit c983a54
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions kube/client.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package kube

import (
"errors"
"fmt"
"io"

Expand All @@ -16,8 +15,6 @@ import (

// in case of local kube config
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"

"github.com/utilitywarehouse/semaphore-wireguard/log"
)

type certMan struct {
Expand All @@ -26,21 +23,24 @@ type certMan struct {

func (cm *certMan) verifyConn(cs tls.ConnectionState) error {
resp, err := http.Get(cm.caURL)
if err != nil {
return fmt.Errorf("error getting remote CA from %s: %v", cm.caURL, err)
}
defer func() {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
if err != nil {
log.Logger.Error(
"error getting remote CA",
"err", err)
return err
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("expected %d response from %s, got %d", http.StatusOK, cm.caURL, resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading response body from %s: %v", cm.caURL, err)
}
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM(body)
if !ok {
return errors.New("failed to parse root certificate")
return fmt.Errorf("failed to parse root certificate from %s", cm.caURL)
}
opts := x509.VerifyOptions{
DNSName: cs.ServerName,
Expand Down

0 comments on commit c983a54

Please sign in to comment.