Skip to content

Commit

Permalink
Make sure to handle error returned by io.Closer.Close() in 'defer' st…
Browse files Browse the repository at this point in the history
…atements

This is considered unsafe by gosec otherwise.

[1] securego/gosec#512
[2] securego/gosec#714
[3] https://www.joeshaw.org/dont-defer-close-on-writable-files/
  • Loading branch information
rm3l committed May 16, 2023
1 parent 7173112 commit b7eaaeb
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
18 changes: 12 additions & 6 deletions pkg/util/util.go
Expand Up @@ -492,7 +492,12 @@ func addFileToIgnoreFile(gitIgnoreFile, filename string, fs filesystem.Filesyste
// TODO(feloy) sync with devfile library?
func DisplayLog(followLog bool, rd io.ReadCloser, writer io.Writer, compName string, numberOfLastLines int) (err error) {

defer rd.Close()
defer func() {
cErr := rd.Close()
if err == nil {
err = cErr
}
}()

// Copy to stdout (in yellow)
color.Set(color.FgYellow)
Expand Down Expand Up @@ -529,14 +534,15 @@ func DisplayLog(followLog bool, rd io.ReadCloser, writer io.Writer, compName str
} else {
reader := bufio.NewReader(rd)
var lines []string
var line string
for {
line, err := reader.ReadString('\n')
line, err = reader.ReadString('\n')
if err != nil {
if err != io.EOF {
return err
} else {
break
}
err = nil
break
}

lines = append(lines, line)
Expand All @@ -548,13 +554,13 @@ func DisplayLog(followLog bool, rd io.ReadCloser, writer io.Writer, compName str
}

for i := index; i < len(lines); i++ {
_, err := fmt.Fprintf(writer, lines[i])
_, err = fmt.Fprintf(writer, lines[i])
if err != nil {
return err
}
}
}
return
return err

}

Expand Down
6 changes: 5 additions & 1 deletion tests/helper/helper_http.go
Expand Up @@ -34,7 +34,11 @@ func HttpWaitForWithStatus(url string, match string, maxRetry int, interval int,
time.Sleep(time.Duration(interval) * time.Second)
continue
}
defer resp.Body.Close()
defer func() {
if cErr := resp.Body.Close(); cErr != nil {
fmt.Fprintf(GinkgoWriter, "[warn] error closing response body: %v\n", cErr)
}
}()
if resp.StatusCode == expectedCode {
body, _ = io.ReadAll(resp.Body)
if strings.Contains(string(body), match) {
Expand Down
8 changes: 7 additions & 1 deletion tests/helper/helper_registry.go
Expand Up @@ -6,6 +6,8 @@ import (
"net/http"
"net/url"

. "github.com/onsi/ginkgo/v2"

"github.com/redhat-developer/odo/pkg/api"
)

Expand All @@ -28,7 +30,11 @@ func (o Registry) GetIndex() ([]api.DevfileStack, error) {
if err != nil {
return nil, err
}
defer resp.Body.Close()
defer func() {
if cErr := resp.Body.Close(); cErr != nil {
fmt.Fprintf(GinkgoWriter, "[warn] error closing response body: %v\n", cErr)
}
}()

var target []api.DevfileStack
err = json.NewDecoder(resp.Body).Decode(&target)
Expand Down

0 comments on commit b7eaaeb

Please sign in to comment.