Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix go vet errors with Go 1.24 #41076

Merged
merged 13 commits into from
Oct 21, 2024
5 changes: 2 additions & 3 deletions dev-tools/cmd/module_fields/module_fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
Expand Down Expand Up @@ -104,14 +103,14 @@ func main() {
log.Fatalf("Error creating golang file from template: %v", err)
}

err = ioutil.WriteFile(filepath.Join(dir, module, "fields.go"), bs, 0644)
err = os.WriteFile(filepath.Join(dir, module, "fields.go"), bs, 0644)
if err != nil {
log.Fatalf("Error writing fields.go: %v", err)
}
}
}

func usageFlag() {
fmt.Fprintf(os.Stderr, usageText)
fmt.Fprint(os.Stderr, usageText)
flag.PrintDefaults()
}
5 changes: 2 additions & 3 deletions dev-tools/cmd/module_include_list/module_include_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
Expand Down Expand Up @@ -164,13 +163,13 @@ func main() {
}

// Write the output file.
if err = ioutil.WriteFile(outFile, buf.Bytes(), 0644); err != nil {
if err = os.WriteFile(outFile, buf.Bytes(), 0644); err != nil {
log.Fatalf("Failed writing output file: %v", err)
}
}

func usageFlag() {
fmt.Fprintf(os.Stderr, usageText)
fmt.Fprint(os.Stderr, usageText)
flag.PrintDefaults()
}

Expand Down
64 changes: 42 additions & 22 deletions dev-tools/mage/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
Expand Down Expand Up @@ -125,7 +124,7 @@ func joinMaps(args ...map[string]interface{}) map[string]interface{} {
}

func expandFile(src, dst string, args ...map[string]interface{}) error {
tmplData, err := ioutil.ReadFile(src)
tmplData, err := os.ReadFile(src)
if err != nil {
return fmt.Errorf("failed reading from template %v: %w", src, err)
}
Expand All @@ -140,7 +139,7 @@ func expandFile(src, dst string, args ...map[string]interface{}) error {
return err
}

if err = ioutil.WriteFile(createDir(dst), []byte(output), 0644); err != nil {
if err = os.WriteFile(createDir(dst), []byte(output), 0644); err != nil {
return fmt.Errorf("failed to write rendered template: %w", err)
}

Expand Down Expand Up @@ -262,13 +261,13 @@ func FindReplace(file string, re *regexp.Regexp, repl string) error {
return err
}

contents, err := ioutil.ReadFile(file)
contents, err := os.ReadFile(file)
if err != nil {
return err
}

out := re.ReplaceAllString(string(contents), repl)
return ioutil.WriteFile(file, []byte(out), info.Mode().Perm())
return os.WriteFile(file, []byte(out), info.Mode().Perm())
}

// MustFindReplace invokes FindReplace and panics if an error occurs.
Expand All @@ -283,9 +282,14 @@ func MustFindReplace(file string, re *regexp.Regexp, repl string) {
func DownloadFile(url, destinationDir string) (string, error) {
log.Println("Downloading", url)

resp, err := http.Get(url)
req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, url, nil)
if err != nil {
return "", fmt.Errorf("http get failed: %w", err)
return "", fmt.Errorf("failed to create http request: %w", err)
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("failed to download file: %w", err)
}
defer resp.Body.Close()

Expand Down Expand Up @@ -338,9 +342,9 @@ func unzip(sourceFile, destinationDir string) error {
}
defer innerFile.Close()

path := filepath.Join(destinationDir, f.Name)
if !strings.HasPrefix(path, destinationDir) {
return fmt.Errorf("illegal file path in zip: %v", f.Name)
path, err := sanitizeFilePath(f.Name, destinationDir)
if err != nil {
return err
}

if f.FileInfo().IsDir() {
Expand All @@ -357,7 +361,7 @@ func unzip(sourceFile, destinationDir string) error {
}
defer out.Close()

if _, err = io.Copy(out, innerFile); err != nil {
if _, err = io.Copy(out, innerFile); err != nil { //nolint:gosec // this is only used for dev tools
return err
}

Expand All @@ -374,6 +378,16 @@ func unzip(sourceFile, destinationDir string) error {
return nil
}

// sanitizeExtractPath sanitizes against path traversal attacks.
// See https://security.snyk.io/research/zip-slip-vulnerability.
func sanitizeFilePath(filePath string, workdir string) (string, error) {
destPath := filepath.Join(workdir, filePath)
if !strings.HasPrefix(destPath, filepath.Clean(workdir)+string(os.PathSeparator)) {
return filePath, fmt.Errorf("failed to extract illegal file path: %s", filePath)
}
return destPath, nil
}

// Tar compress a directory using tar + gzip algorithms but without adding
// the directory
func TarWithOptions(src string, targetFile string, trimSource bool) error {
Expand All @@ -390,7 +404,7 @@ func TarWithOptions(src string, targetFile string, trimSource bool) error {
tw := tar.NewWriter(zr)

// walk through every file in the folder
filepath.Walk(src, func(file string, fi os.FileInfo, errFn error) error {
err = filepath.Walk(src, func(file string, fi os.FileInfo, errFn error) error {
if errFn != nil {
return fmt.Errorf("error traversing the file system: %w", errFn)
}
Expand Down Expand Up @@ -438,6 +452,9 @@ func TarWithOptions(src string, targetFile string, trimSource bool) error {
}
return nil
})
if err != nil {
return fmt.Errorf("error walking dir: %w", err)
}

// produce tar
if err := tw.Close(); err != nil {
Expand Down Expand Up @@ -477,15 +494,15 @@ func untar(sourceFile, destinationDir string) error {
for {
header, err := tarReader.Next()
if err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
return err
}

path := filepath.Join(destinationDir, header.Name)
if !strings.HasPrefix(path, destinationDir) {
return fmt.Errorf("illegal file path in tar: %v", header.Name)
path, err := sanitizeFilePath(header.Name, destinationDir)
if err != nil {
return err
}

switch header.Typeflag {
Expand All @@ -499,7 +516,7 @@ func untar(sourceFile, destinationDir string) error {
return err
}

if _, err = io.Copy(writer, tarReader); err != nil {
if _, err = io.Copy(writer, tarReader); err != nil { //nolint:gosec // this is only used for dev tools
return err
}

Expand Down Expand Up @@ -613,7 +630,7 @@ func ParallelCtx(ctx context.Context, fns ...interface{}) {

wg.Wait()
if len(errs) > 0 {
panic(fmt.Errorf(strings.Join(errs, "\n")))
panic(errors.New(strings.Join(errs, "\n")))
}
}

Expand Down Expand Up @@ -773,7 +790,7 @@ func CreateSHA512File(file string) error {
computedHash := hex.EncodeToString(sum.Sum(nil))
out := fmt.Sprintf("%v %v", computedHash, filepath.Base(file))

return ioutil.WriteFile(file+".sha512", []byte(out), 0644)
return os.WriteFile(file+".sha512", []byte(out), 0644)
}

// Mage executes mage targets in the specified directory.
Expand All @@ -800,7 +817,7 @@ func IsUpToDate(dst string, sources ...string) bool {

var files []string
for _, s := range sources {
filepath.Walk(s, func(path string, info os.FileInfo, err error) error {
err := filepath.Walk(s, func(path string, info os.FileInfo, err error) error {
if err != nil {
if os.IsNotExist(err) {
return nil
Expand All @@ -814,6 +831,9 @@ func IsUpToDate(dst string, sources ...string) bool {

return nil
})
if err != nil {
panic(fmt.Errorf("failed to walk source %v: %w", s, err))
}
}

execute, err := target.Path(dst, files...)
Expand Down Expand Up @@ -896,7 +916,7 @@ func ParseVersion(version string) (major, minor, patch int, err error) {
matches := parseVersionRegex.FindStringSubmatch(version)
if len(matches) == 0 {
err = fmt.Errorf("failed to parse version '%v'", version)
return
return major, minor, patch, err
}

data := map[string]string{}
Expand All @@ -906,7 +926,7 @@ func ParseVersion(version string) (major, minor, patch int, err error) {
major, _ = strconv.Atoi(data["major"])
minor, _ = strconv.Atoi(data["minor"])
patch, _ = strconv.Atoi(data["patch"])
return
return major, minor, patch, nil
}

// ListMatchingEnvVars returns all of the environment variables names that begin
Expand Down
2 changes: 1 addition & 1 deletion heartbeat/hbtestllext/isdefs.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ var IsMonitorStateInLocation = func(locName string) isdef.IsDef {
}

if !stateIdMatch.MatchString(s.ID) {
return llresult.SimpleResult(path, false, fmt.Sprintf("ID %s does not match regexp pattern /%s/", s.ID, locPattern))
return llresult.SimpleResult(path, false, "ID %s does not match regexp pattern /%s/", s.ID, locPattern)
rdner marked this conversation as resolved.
Show resolved Hide resolved
}
return llresult.ValidResult(path)
})
Expand Down
3 changes: 2 additions & 1 deletion heartbeat/look/look_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package look

import (
"errors"
"testing"
"time"

Expand Down Expand Up @@ -57,7 +58,7 @@ func TestReason(t *testing.T) {

func TestReasonGenericError(t *testing.T) {
msg := "An error"
res := Reason(fmt.Errorf(msg))
res := Reason(errors.New(msg))
assert.Equal(t, mapstr.M{
"type": "io",
"message": msg,
Expand Down
2 changes: 1 addition & 1 deletion heartbeat/monitors/active/icmp/stdloop.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func getStdLoop() (*stdICMPLoop, error) {
}

func noPingCapabilityError(message string) error {
return fmt.Errorf(fmt.Sprintf("Insufficient privileges to perform ICMP ping. %s", message))
return fmt.Errorf("Insufficient privileges to perform ICMP ping. %s", message)
}

func newICMPLoop() (*stdICMPLoop, error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ package summarizertesthelper
// prevent import cycles.

import (
"fmt"

"github.com/elastic/beats/v7/heartbeat/hbtestllext"
"github.com/elastic/beats/v7/heartbeat/monitors/wrappers/summarizer/jobsummary"
"github.com/elastic/go-lookslike"
Expand All @@ -46,11 +44,11 @@ func summaryIsdef(up uint16, down uint16) isdef.IsDef {
return isdef.Is("summary", func(path llpath.Path, v interface{}) *llresult.Results {
js, ok := v.(jobsummary.JobSummary)
if !ok {
return llresult.SimpleResult(path, false, fmt.Sprintf("expected a *jobsummary.JobSummary, got %v", v))
return llresult.SimpleResult(path, false, "expected a *jobsummary.JobSummary, got %v", v)
}

if js.Up != up || js.Down != down {
return llresult.SimpleResult(path, false, fmt.Sprintf("expected up/down to be %d/%d, got %d/%d", up, down, js.Up, js.Down))
return llresult.SimpleResult(path, false, "expected up/down to be %d/%d, got %d/%d", up, down, js.Up, js.Down)
mauri870 marked this conversation as resolved.
Show resolved Hide resolved
}

return llresult.ValidResult(path)
Expand Down
6 changes: 3 additions & 3 deletions libbeat/cmd/instance/beat.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ func NewBeatReceiver(settings Settings, receiverConfig map[string]interface{}, c
}

// log paths values to help with troubleshooting
logp.Info(paths.Paths.String())
logp.Info("%s", paths.Paths.String())
rdner marked this conversation as resolved.
Show resolved Hide resolved

metaPath := paths.Resolve(paths.Data, "meta.json")
err = b.loadMeta(metaPath)
Expand Down Expand Up @@ -603,7 +603,7 @@ func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) {
logp.Info("Output is configured through Central Management")
} else {
msg := "no outputs are defined, please define one under the output section"
logp.Info(msg)
logp.Info("%s", msg)
mauri870 marked this conversation as resolved.
Show resolved Hide resolved
return nil, errors.New(msg)
}
}
Expand Down Expand Up @@ -1055,7 +1055,7 @@ func (b *Beat) configure(settings Settings) error {
}

// log paths values to help with troubleshooting
logp.Info(paths.Paths.String())
logp.Info("%s", paths.Paths.String())
mauri870 marked this conversation as resolved.
Show resolved Hide resolved

metaPath := paths.Resolve(paths.Data, "meta.json")
err = b.loadMeta(metaPath)
Expand Down
6 changes: 3 additions & 3 deletions libbeat/common/cli/confirm.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ func Confirm(prompt string, def bool) (bool, error) {
}

func confirm(r io.Reader, out io.Writer, prompt string, def bool) (bool, error) {
options := " [Y/n]"
options := "[Y/n]"
if !def {
options = " [y/N]"
options = "[y/N]"
}

reader := bufio.NewScanner(r)
for {
fmt.Fprintf(out, prompt+options+":")
fmt.Fprintf(out, "%s %s:", prompt, options)

if !reader.Scan() {
break
Expand Down
2 changes: 1 addition & 1 deletion libbeat/common/cli/input.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func ReadInput(prompt string) (string, error) {

func input(r io.Reader, out io.Writer, prompt string) (string, error) {
reader := bufio.NewScanner(r)
fmt.Fprintf(out, prompt+" ")
fmt.Fprintf(out, "%s ", prompt)

if !reader.Scan() {
return "", errors.New("error reading user input")
Expand Down
Loading
Loading