Skip to content

Commit 5de2287

Browse files
authored
fix go vet errors with Go 1.24 (elastic#41076)
* fix go vet errors with Go 1.24 The cmd/vet in Go 1.24 reports printf calls with non-const format and no args, causing failures. ``` $ go install golang.org/dl/gotip@latest $ gotip download $ gotip vet ./... ``` * use os.WriteFile * more linter fixes * even more linter fixes * more more more linter fixes * fix wrong variable name * fix linter issues with emptyIface
1 parent 7be47da commit 5de2287

File tree

22 files changed

+114
-107
lines changed

22 files changed

+114
-107
lines changed

dev-tools/cmd/module_fields/module_fields.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ package main
2020
import (
2121
"flag"
2222
"fmt"
23-
"io/ioutil"
2423
"log"
2524
"os"
2625
"path/filepath"
@@ -104,14 +103,14 @@ func main() {
104103
log.Fatalf("Error creating golang file from template: %v", err)
105104
}
106105

107-
err = ioutil.WriteFile(filepath.Join(dir, module, "fields.go"), bs, 0644)
106+
err = os.WriteFile(filepath.Join(dir, module, "fields.go"), bs, 0644)
108107
if err != nil {
109108
log.Fatalf("Error writing fields.go: %v", err)
110109
}
111110
}
112111
}
113112

114113
func usageFlag() {
115-
fmt.Fprintf(os.Stderr, usageText)
114+
fmt.Fprint(os.Stderr, usageText)
116115
flag.PrintDefaults()
117116
}

dev-tools/cmd/module_include_list/module_include_list.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import (
2222
"bytes"
2323
"flag"
2424
"fmt"
25-
"io/ioutil"
2625
"log"
2726
"os"
2827
"path/filepath"
@@ -164,13 +163,13 @@ func main() {
164163
}
165164

166165
// Write the output file.
167-
if err = ioutil.WriteFile(outFile, buf.Bytes(), 0644); err != nil {
166+
if err = os.WriteFile(outFile, buf.Bytes(), 0644); err != nil {
168167
log.Fatalf("Failed writing output file: %v", err)
169168
}
170169
}
171170

172171
func usageFlag() {
173-
fmt.Fprintf(os.Stderr, usageText)
172+
fmt.Fprint(os.Stderr, usageText)
174173
flag.PrintDefaults()
175174
}
176175

dev-tools/mage/common.go

+42-22
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ import (
3232
"errors"
3333
"fmt"
3434
"io"
35-
"io/ioutil"
3635
"log"
3736
"net/http"
3837
"os"
@@ -125,7 +124,7 @@ func joinMaps(args ...map[string]interface{}) map[string]interface{} {
125124
}
126125

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

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

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

265-
contents, err := ioutil.ReadFile(file)
264+
contents, err := os.ReadFile(file)
266265
if err != nil {
267266
return err
268267
}
269268

270269
out := re.ReplaceAllString(string(contents), repl)
271-
return ioutil.WriteFile(file, []byte(out), info.Mode().Perm())
270+
return os.WriteFile(file, []byte(out), info.Mode().Perm())
272271
}
273272

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

286-
resp, err := http.Get(url)
285+
req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, url, nil)
287286
if err != nil {
288-
return "", fmt.Errorf("http get failed: %w", err)
287+
return "", fmt.Errorf("failed to create http request: %w", err)
288+
}
289+
290+
resp, err := http.DefaultClient.Do(req)
291+
if err != nil {
292+
return "", fmt.Errorf("failed to download file: %w", err)
289293
}
290294
defer resp.Body.Close()
291295

@@ -338,9 +342,9 @@ func unzip(sourceFile, destinationDir string) error {
338342
}
339343
defer innerFile.Close()
340344

341-
path := filepath.Join(destinationDir, f.Name)
342-
if !strings.HasPrefix(path, destinationDir) {
343-
return fmt.Errorf("illegal file path in zip: %v", f.Name)
345+
path, err := sanitizeFilePath(f.Name, destinationDir)
346+
if err != nil {
347+
return err
344348
}
345349

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

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

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

381+
// sanitizeExtractPath sanitizes against path traversal attacks.
382+
// See https://security.snyk.io/research/zip-slip-vulnerability.
383+
func sanitizeFilePath(filePath string, workdir string) (string, error) {
384+
destPath := filepath.Join(workdir, filePath)
385+
if !strings.HasPrefix(destPath, filepath.Clean(workdir)+string(os.PathSeparator)) {
386+
return filePath, fmt.Errorf("failed to extract illegal file path: %s", filePath)
387+
}
388+
return destPath, nil
389+
}
390+
377391
// Tar compress a directory using tar + gzip algorithms but without adding
378392
// the directory
379393
func TarWithOptions(src string, targetFile string, trimSource bool) error {
@@ -390,7 +404,7 @@ func TarWithOptions(src string, targetFile string, trimSource bool) error {
390404
tw := tar.NewWriter(zr)
391405

392406
// walk through every file in the folder
393-
filepath.Walk(src, func(file string, fi os.FileInfo, errFn error) error {
407+
err = filepath.Walk(src, func(file string, fi os.FileInfo, errFn error) error {
394408
if errFn != nil {
395409
return fmt.Errorf("error traversing the file system: %w", errFn)
396410
}
@@ -438,6 +452,9 @@ func TarWithOptions(src string, targetFile string, trimSource bool) error {
438452
}
439453
return nil
440454
})
455+
if err != nil {
456+
return fmt.Errorf("error walking dir: %w", err)
457+
}
441458

442459
// produce tar
443460
if err := tw.Close(); err != nil {
@@ -477,15 +494,15 @@ func untar(sourceFile, destinationDir string) error {
477494
for {
478495
header, err := tarReader.Next()
479496
if err != nil {
480-
if err == io.EOF {
497+
if errors.Is(err, io.EOF) {
481498
break
482499
}
483500
return err
484501
}
485502

486-
path := filepath.Join(destinationDir, header.Name)
487-
if !strings.HasPrefix(path, destinationDir) {
488-
return fmt.Errorf("illegal file path in tar: %v", header.Name)
503+
path, err := sanitizeFilePath(header.Name, destinationDir)
504+
if err != nil {
505+
return err
489506
}
490507

491508
switch header.Typeflag {
@@ -499,7 +516,7 @@ func untar(sourceFile, destinationDir string) error {
499516
return err
500517
}
501518

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

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

614631
wg.Wait()
615632
if len(errs) > 0 {
616-
panic(fmt.Errorf(strings.Join(errs, "\n")))
633+
panic(errors.New(strings.Join(errs, "\n")))
617634
}
618635
}
619636

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

776-
return ioutil.WriteFile(file+".sha512", []byte(out), 0644)
793+
return os.WriteFile(file+".sha512", []byte(out), 0644)
777794
}
778795

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

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

815832
return nil
816833
})
834+
if err != nil {
835+
panic(fmt.Errorf("failed to walk source %v: %w", s, err))
836+
}
817837
}
818838

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

902922
data := map[string]string{}
@@ -906,7 +926,7 @@ func ParseVersion(version string) (major, minor, patch int, err error) {
906926
major, _ = strconv.Atoi(data["major"])
907927
minor, _ = strconv.Atoi(data["minor"])
908928
patch, _ = strconv.Atoi(data["patch"])
909-
return
929+
return major, minor, patch, nil
910930
}
911931

912932
// ListMatchingEnvVars returns all of the environment variables names that begin

heartbeat/hbtestllext/isdefs.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ var IsMonitorStateInLocation = func(locName string) isdef.IsDef {
7474
}
7575

7676
if !stateIdMatch.MatchString(s.ID) {
77-
return llresult.SimpleResult(path, false, fmt.Sprintf("ID %s does not match regexp pattern /%s/", s.ID, locPattern))
77+
return llresult.SimpleResult(path, false, "ID %s does not match regexp pattern /%s/", s.ID, locPattern)
7878
}
7979
return llresult.ValidResult(path)
8080
})

heartbeat/look/look_test.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
package look
1919

2020
import (
21+
"errors"
2122
"testing"
2223
"time"
2324

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

5859
func TestReasonGenericError(t *testing.T) {
5960
msg := "An error"
60-
res := Reason(fmt.Errorf(msg))
61+
res := Reason(errors.New(msg))
6162
assert.Equal(t, mapstr.M{
6263
"type": "io",
6364
"message": msg,

heartbeat/monitors/active/icmp/stdloop.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ func getStdLoop() (*stdICMPLoop, error) {
110110
}
111111

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

116116
func newICMPLoop() (*stdICMPLoop, error) {

heartbeat/monitors/wrappers/summarizer/summarizertesthelper/testhelper.go

+2-4
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@ package summarizertesthelper
2222
// prevent import cycles.
2323

2424
import (
25-
"fmt"
26-
2725
"github.com/elastic/beats/v7/heartbeat/hbtestllext"
2826
"github.com/elastic/beats/v7/heartbeat/monitors/wrappers/summarizer/jobsummary"
2927
"github.com/elastic/go-lookslike"
@@ -46,11 +44,11 @@ func summaryIsdef(up uint16, down uint16) isdef.IsDef {
4644
return isdef.Is("summary", func(path llpath.Path, v interface{}) *llresult.Results {
4745
js, ok := v.(jobsummary.JobSummary)
4846
if !ok {
49-
return llresult.SimpleResult(path, false, fmt.Sprintf("expected a *jobsummary.JobSummary, got %v", v))
47+
return llresult.SimpleResult(path, false, "expected a *jobsummary.JobSummary, got %v", v)
5048
}
5149

5250
if js.Up != up || js.Down != down {
53-
return llresult.SimpleResult(path, false, fmt.Sprintf("expected up/down to be %d/%d, got %d/%d", up, down, js.Up, js.Down))
51+
return llresult.SimpleResult(path, false, "expected up/down to be %d/%d, got %d/%d", up, down, js.Up, js.Down)
5452
}
5553

5654
return llresult.ValidResult(path)

libbeat/cmd/instance/beat.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ func NewBeatReceiver(settings Settings, receiverConfig map[string]interface{}, c
388388
}
389389

390390
// log paths values to help with troubleshooting
391-
logp.Info(paths.Paths.String())
391+
logp.Info("%s", paths.Paths.String())
392392

393393
metaPath := paths.Resolve(paths.Data, "meta.json")
394394
err = b.loadMeta(metaPath)
@@ -603,7 +603,7 @@ func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) {
603603
logp.Info("Output is configured through Central Management")
604604
} else {
605605
msg := "no outputs are defined, please define one under the output section"
606-
logp.Info(msg)
606+
logp.Info("%s", msg)
607607
return nil, errors.New(msg)
608608
}
609609
}
@@ -1055,7 +1055,7 @@ func (b *Beat) configure(settings Settings) error {
10551055
}
10561056

10571057
// log paths values to help with troubleshooting
1058-
logp.Info(paths.Paths.String())
1058+
logp.Info("%s", paths.Paths.String())
10591059

10601060
metaPath := paths.Resolve(paths.Data, "meta.json")
10611061
err = b.loadMeta(metaPath)

libbeat/common/cli/confirm.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,14 @@ func Confirm(prompt string, def bool) (bool, error) {
3535
}
3636

3737
func confirm(r io.Reader, out io.Writer, prompt string, def bool) (bool, error) {
38-
options := " [Y/n]"
38+
options := "[Y/n]"
3939
if !def {
40-
options = " [y/N]"
40+
options = "[y/N]"
4141
}
4242

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

4747
if !reader.Scan() {
4848
break

libbeat/common/cli/input.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func ReadInput(prompt string) (string, error) {
3434

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

3939
if !reader.Scan() {
4040
return "", errors.New("error reading user input")

0 commit comments

Comments
 (0)