Updating golangci-lint to 1.61.0 (#22973)

This commit is contained in:
Victor Lyuboslavsky
2024-10-18 12:38:26 -05:00
committed by GitHub
parent 77862664d5
commit f85b6f776f
236 changed files with 877 additions and 831 deletions
+1 -1
View File
@@ -1350,7 +1350,7 @@ func cronActivitiesStreaming(
return multiErr
}
if len(activitiesToStream) < int(ActivitiesToStreamBatchCount) {
if len(activitiesToStream) < int(ActivitiesToStreamBatchCount) { //nolint:gosec // dismiss G115
return nil
}
page += 1
+4 -3
View File
@@ -1028,7 +1028,8 @@ func TestCronActivitiesStreaming(t *testing.T) {
// two pages of ActivitiesToStreamBatchCount and one extra page of one item.
as := make([]*fleet.Activity, ActivitiesToStreamBatchCount*2+1)
for i := range as {
as[i] = newActivity(uint(i), "foo", uint(i), "foog", "fooe", "bar", `{"bar": "foo"}`)
as[i] = newActivity(uint(i), "foo", uint(i), //nolint:gosec // dismiss G115
"foog", "fooe", "bar", `{"bar": "foo"}`)
}
ds.ListActivitiesFunc = func(ctx context.Context, opt fleet.ListActivitiesOptions) ([]*fleet.Activity, *fleet.PaginationMetadata, error) {
@@ -1053,7 +1054,7 @@ func TestCronActivitiesStreaming(t *testing.T) {
firstBatch[i] = as[i].ID
}
for i := range as[ActivitiesToStreamBatchCount : ActivitiesToStreamBatchCount*2] {
secondBatch[i] = as[int(ActivitiesToStreamBatchCount)+i].ID
secondBatch[i] = as[int(ActivitiesToStreamBatchCount)+i].ID //nolint:gosec // dismiss G115
}
thirdBatch := []uint{as[len(as)-1].ID}
ds.MarkActivitiesAsStreamedFunc = func(ctx context.Context, activityIDs []uint) error {
@@ -1074,7 +1075,7 @@ func TestCronActivitiesStreaming(t *testing.T) {
var auditLogger jsonLogger
err := cronActivitiesStreaming(context.Background(), ds, log.NewNopLogger(), &auditLogger)
require.NoError(t, err)
require.Len(t, auditLogger.logs, int(ActivitiesToStreamBatchCount)*2+1)
require.Len(t, auditLogger.logs, int(ActivitiesToStreamBatchCount)*2+1) //nolint:gosec // dismiss G115
require.Equal(t, 3, call)
})
}
+4 -4
View File
@@ -141,7 +141,7 @@ func TestApplyTeamSpecs(t *testing.T) {
i := 1
ds.NewTeamFunc = func(ctx context.Context, team *fleet.Team) (*fleet.Team, error) {
team.ID = uint(i)
team.ID = uint(i) //nolint:gosec // dismiss G115
i++
teamsByName[team.Name] = team
return team, nil
@@ -2031,7 +2031,7 @@ func TestApplyMacosSetup(t *testing.T) {
tmID := 1 // new teams will start at 2
ds.NewTeamFunc = func(ctx context.Context, team *fleet.Team) (*fleet.Team, error) {
tmID++
team.ID = uint(tmID)
team.ID = uint(tmID) //nolint:gosec // dismiss G115
clone := *team
teamsByName[team.Name] = &clone
teamsByID[team.ID] = &clone
@@ -2104,7 +2104,7 @@ func TestApplyMacosSetup(t *testing.T) {
asstID := 0
ds.SetOrUpdateMDMAppleSetupAssistantFunc = func(ctx context.Context, asst *fleet.MDMAppleSetupAssistant) (*fleet.MDMAppleSetupAssistant, error) {
asstID++
asst.ID = uint(asstID)
asst.ID = uint(asstID) //nolint:gosec // dismiss G115
asst.UploadedAt = time.Now()
var tmID uint
@@ -2790,7 +2790,7 @@ func TestApplySpecs(t *testing.T) {
i := 1 // new teams will start at 2
ds.NewTeamFunc = func(ctx context.Context, team *fleet.Team) (*fleet.Team, error) {
i++
team.ID = uint(i)
team.ID = uint(i) //nolint:gosec // dismiss G115
teamsByName[team.Name] = team
return team, nil
}
+14 -16
View File
@@ -464,23 +464,21 @@ or provide an <address> argument to debug: fleetctl debug connection localhost:8
// if a certificate is provided, use it as root CA
cc.RootCA = certPath
cc.TLSSkipVerify = false
} else { // --fleet-certificate is not set
if cc.RootCA == "" {
// If a certificate is not provided and a cc.RootCA is not set in the configuration,
// then use the embedded root CA which is used by osquery to connect to Fleet.
usingEmbeddedCA = true
tmpDir, err := os.MkdirTemp("", "")
if err != nil {
return fmt.Errorf("failed to create temporary directory: %w", err)
}
certPath := filepath.Join(tmpDir, "certs.pem")
if err := os.WriteFile(certPath, packaging.OsqueryCerts, 0o600); err != nil {
return fmt.Errorf("failed to create temporary certs.pem file: %s", err)
}
defer os.RemoveAll(certPath)
cc.RootCA = certPath
cc.TLSSkipVerify = false
} else if cc.RootCA == "" { // --fleet-certificate is not set
// If a certificate is not provided and a cc.RootCA is not set in the configuration,
// then use the embedded root CA which is used by osquery to connect to Fleet.
usingEmbeddedCA = true
tmpDir, err := os.MkdirTemp("", "")
if err != nil {
return fmt.Errorf("failed to create temporary directory: %w", err)
}
certPath := filepath.Join(tmpDir, "certs.pem")
if err := os.WriteFile(certPath, packaging.OsqueryCerts, 0o600); err != nil {
return fmt.Errorf("failed to create temporary certs.pem file: %s", err)
}
defer os.RemoveAll(certPath)
cc.RootCA = certPath
cc.TLSSkipVerify = false
}
}
+1 -1
View File
@@ -163,7 +163,7 @@ func TestDebugCheckAPIEndpoint(t *testing.T) {
cli, base, err := rawHTTPClientFromConfig(Context{Address: srv.URL, TLSSkipVerify: true})
require.NoError(t, err)
for i, c := range cases {
atomic.StoreInt32(&callCount, int32(i))
atomic.StoreInt32(&callCount, int32(i)) //nolint:gosec // dismiss G115
t.Run(fmt.Sprint(c.code), func(t *testing.T) {
err := checkAPIEndpoint(context.Background(), timeout, base, cli)
if c.errContains == "" {
+3 -3
View File
@@ -53,7 +53,7 @@ func deleteCommand() *cli.Command {
fmt.Printf("[+] deleting query %q\n", query.Name)
if err := fleet.DeleteQuery(query.Name); err != nil {
root := ctxerr.Cause(err)
switch root.(type) {
switch root.(type) { //nolint:gocritic // ignore singleCaseSwitch
case service.NotFoundErr:
fmt.Printf("[!] query %q doesn't exist\n", query.Name)
continue
@@ -66,7 +66,7 @@ func deleteCommand() *cli.Command {
fmt.Printf("[+] deleting pack %q\n", pack.Name)
if err := fleet.DeletePack(pack.Name); err != nil {
root := ctxerr.Cause(err)
switch root.(type) {
switch root.(type) { //nolint:gocritic // ignore singleCaseSwitch
case service.NotFoundErr:
fmt.Printf("[!] pack %q doesn't exist\n", pack.Name)
continue
@@ -79,7 +79,7 @@ func deleteCommand() *cli.Command {
fmt.Printf("[+] deleting label %q\n", label.Name)
if err := fleet.DeleteLabel(label.Name); err != nil {
root := ctxerr.Cause(err)
switch root.(type) {
switch root.(type) { //nolint:gocritic // ignore singleCaseSwitch
case service.NotFoundErr:
fmt.Printf("[!] label %q doesn't exist\n", label.Name)
continue
+2 -4
View File
@@ -453,9 +453,7 @@ func TestGetHosts(t *testing.T) {
{
name: "get hosts --yaml test_host",
goldenFile: "expectedHostDetailResponseYaml.yml",
scanner: func(s string) []string {
return spec.SplitYaml(s)
},
scanner: spec.SplitYaml,
args: []string{"get", "hosts", "--yaml", "test_host"},
prettifier: yamlPrettify,
},
@@ -1253,7 +1251,7 @@ func TestGetQueries(t *testing.T) {
return nil, &notFoundError{}
}
ds.ListQueriesFunc = func(ctx context.Context, opt fleet.ListQueryOptions) ([]*fleet.Query, error) {
if opt.TeamID == nil {
if opt.TeamID == nil { //nolint:gocritic // ignore ifElseChain
return []*fleet.Query{
{
ID: 33,
+3 -3
View File
@@ -1765,7 +1765,7 @@ func TestGitOpsTeamSofwareInstallers(t *testing.T) {
{"testdata/gitops/team_software_installer_not_found.yml", "Please make sure that URLs are reachable from your Fleet server."},
{"testdata/gitops/team_software_installer_unsupported.yml", "The file should be .pkg, .msi, .exe, .deb or .rpm."},
// commenting out, results in the process getting killed on CI and on some machines
//{"testdata/gitops/team_software_installer_too_large.yml", "The maximum file size is 3 GB"},
// {"testdata/gitops/team_software_installer_too_large.yml", "The maximum file size is 3 GB"},
{"testdata/gitops/team_software_installer_valid.yml", ""},
{"testdata/gitops/team_software_installer_valid_apply.yml", ""},
{"testdata/gitops/team_software_installer_pre_condition_multiple_queries.yml", "should have only one query."},
@@ -1821,7 +1821,7 @@ func TestGitOpsNoTeamSoftwareInstallers(t *testing.T) {
{"testdata/gitops/no_team_software_installer_not_found.yml", "Please make sure that URLs are reachable from your Fleet server."},
{"testdata/gitops/no_team_software_installer_unsupported.yml", "The file should be .pkg, .msi, .exe, .deb or .rpm."},
// commenting out, results in the process getting killed on CI and on some machines
//{"testdata/gitops/no_team_software_installer_too_large.yml", "The maximum file size is 3 GB"},
// {"testdata/gitops/no_team_software_installer_too_large.yml", "The maximum file size is 3 GB"},
{"testdata/gitops/no_team_software_installer_valid.yml", ""},
{"testdata/gitops/no_team_software_installer_pre_condition_multiple_queries.yml", "should have only one query."},
{"testdata/gitops/no_team_software_installer_pre_condition_not_found.yml", "no such file or directory"},
@@ -2276,7 +2276,7 @@ func setupFullGitOpsPremiumServer(t *testing.T) (*mock.Store, **fleet.AppConfig,
return job, nil
}
ds.NewTeamFunc = func(ctx context.Context, team *fleet.Team) (*fleet.Team, error) {
team.ID = uint(len(savedTeams) + 1)
team.ID = uint(len(savedTeams) + 1) //nolint:gosec // dismiss G115
savedTeams[team.Name] = &team
return team, nil
}
+5 -9
View File
@@ -69,10 +69,8 @@ Trying to login with SSO? First, login to the Fleet UI and retrieve your API tok
if err != nil {
return fmt.Errorf("error reading email: %w", err)
}
} else {
if definedAsEnvOnly("--email", "EMAIL") {
fmt.Printf("Using value of environment variable $EMAIL as email.\n")
}
} else if definedAsEnvOnly("--email", "EMAIL") {
fmt.Printf("Using value of environment variable $EMAIL as email.\n")
}
if flPassword == "" {
fmt.Print("Password: ")
@@ -82,16 +80,14 @@ Trying to login with SSO? First, login to the Fleet UI and retrieve your API tok
}
fmt.Println()
flPassword = string(passBytes)
} else {
if definedAsEnvOnly("--password", "PASSWORD") {
fmt.Printf("Using value of environment variable $PASSWORD as password.\n")
}
} else if definedAsEnvOnly("--password", "PASSWORD") {
fmt.Printf("Using value of environment variable $PASSWORD as password.\n")
}
token, err := fleet.Login(flEmail, flPassword)
if err != nil {
root := ctxerr.Cause(err)
switch root.(type) {
switch root.(type) { //nolint:gocritic // ignore singleCaseSwitch
case service.NotSetupErr:
return err
}
+3 -5
View File
@@ -457,11 +457,9 @@ Use the stop and reset subcommands to manage the server and dependencies once st
fmt.Println(string(out))
return fmt.Errorf("Failed to run %s", compose)
}
} else {
if !c.Bool(disableOpenBrowser) {
if err := open.Browser("http://localhost:1337/previewlogin"); err != nil {
fmt.Println("Automatic browser open failed. Please navigate to http://localhost:1337/previewlogin.")
}
} else if !c.Bool(disableOpenBrowser) {
if err := open.Browser("http://localhost:1337/previewlogin"); err != nil {
fmt.Println("Automatic browser open failed. Please navigate to http://localhost:1337/previewlogin.")
}
}
+2 -4
View File
@@ -119,10 +119,8 @@ func queryCommand() *cli.Command {
if queryID == nil {
return fmt.Errorf("Query '%s' not found", flQueryName)
}
} else {
if flQuery == "" {
return errors.New("Query must be specified with --query or --query-name")
}
} else if flQuery == "" {
return errors.New("Query must be specified with --query or --query-name")
}
var output outputWriter
+2 -2
View File
@@ -313,11 +313,11 @@ Fleet records the last 10,000 characters to prevent downtime.
},
// TODO: this would take 5 minutes to run, we don't want that kind of slowdown in our test suite
// but can be useful to have around for manual testing.
//{
// {
// name: "host timeout",
// scriptPath: generateValidPath,
// expectErrMsg: fleet.RunScriptHostTimeoutErrMsg,
//},
// },
{name: "disabled scripts globally", scriptPath: generateValidPath, expectErrMsg: fleet.RunScriptScriptsDisabledGloballyErrMsg},
}
+1 -1
View File
@@ -88,7 +88,7 @@ func setupCommand() *cli.Command {
token, err := fleet.Setup(flEmail, flName, flPassword, flOrgName)
if err != nil {
root := ctxerr.Cause(err)
switch root.(type) {
switch root.(type) { //nolint:gocritic // ignore singleCaseSwitch
case service.SetupAlreadyErr:
return err
}
+5 -4
View File
@@ -100,7 +100,7 @@ func createUserCommand() *cli.Command {
var globalRole *string
var teams []fleet.UserTeam
if globalRoleString != "" && len(teamStrings) > 0 {
if globalRoleString != "" && len(teamStrings) > 0 { //nolint:gocritic // ignore ifElseChain
return errors.New("Users may not have global_role and teams.")
} else if globalRoleString == "" && len(teamStrings) == 0 {
globalRole = ptr.String(fleet.RoleObserver)
@@ -123,7 +123,7 @@ func createUserCommand() *cli.Command {
return fmt.Errorf("'%s' is not a valid team role", parts[1])
}
teams = append(teams, fleet.UserTeam{Team: fleet.Team{ID: uint(teamID)}, Role: parts[1]})
teams = append(teams, fleet.UserTeam{Team: fleet.Team{ID: uint(teamID)}, Role: parts[1]}) //nolint:gosec // dismiss G115
}
}
@@ -237,7 +237,7 @@ func createBulkUsersCommand() *cli.Command {
var globalRole *string
var teams []fleet.UserTeam
if globalRoleString != "" && len(teamStrings) > 0 && teamStrings[0] != "" {
if globalRoleString != "" && len(teamStrings) > 0 && teamStrings[0] != "" { //nolint:gocritic // ignore ifElseChain
return errors.New("Users may not have global_role and teams.")
} else if globalRoleString == "" && (len(teamStrings) == 0 || teamStrings[0] == "") {
globalRole = ptr.String(fleet.RoleObserver)
@@ -260,7 +260,8 @@ func createBulkUsersCommand() *cli.Command {
return fmt.Errorf("'%s' is not a valid team role", parts[1])
}
teams = append(teams, fleet.UserTeam{Team: fleet.Team{ID: uint(teamID)}, Role: parts[1]})
teams = append(teams,
fleet.UserTeam{Team: fleet.Team{ID: uint(teamID)}, Role: parts[1]}) //nolint:gosec // dismiss G115
}
}
+1 -1
View File
@@ -219,7 +219,7 @@ func TestDeleteBulkUsers(t *testing.T) {
randId, err := rand.Int(rand.Reader, big.NewInt(1000))
require.NoError(t, err)
id := uint(randId.Int64())
id := uint(randId.Int64()) //nolint:gosec // dismiss G115
users = append(users, fleet.User{
Name: name,
+15 -10
View File
@@ -1285,7 +1285,7 @@ func (a *agent) installSoftwareItem(installerID string, orbitClient *service.Orb
failed := false
if installer.PreInstallCondition != "" {
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
if installer.PreInstallCondition == "select 1" {
if installer.PreInstallCondition == "select 1" { //nolint:gocritic // ignore ifElseChain
// Always pass
payload.PreInstallConditionOutput = ptr.String("1")
} else if installer.PreInstallCondition == "select 0" ||
@@ -1317,7 +1317,7 @@ func (a *agent) installSoftwareItem(installerID string, orbitClient *service.Orb
}
time.Sleep(time.Duration(rand.Intn(30)) * time.Second)
if installer.InstallScript == "exit 0" {
if installer.InstallScript == "exit 0" { //nolint:gocritic // ignore ifElseChain
// Always pass
payload.InstallScriptExitCode = ptr.Int(0)
payload.InstallScriptOutput = ptr.String("Installed on osquery-perf (always pass)")
@@ -1364,7 +1364,7 @@ func (a *agent) installSoftwareItem(installerID string, orbitClient *service.Orb
if installer.PostInstallScript != "" {
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
if installer.PostInstallScript == "exit 0" {
if installer.PostInstallScript == "exit 0" { //nolint:gocritic // ignore ifElseChain
// Always pass
payload.PostInstallScriptExitCode = ptr.Int(0)
payload.PostInstallScriptOutput = ptr.String("PostInstall on osquery-perf (always pass)")
@@ -1602,7 +1602,8 @@ func (a *agent) hostUsers() []map[string]string {
"shell": shells[i%len(shells)],
}
}
users := append(commonUsers, uniqueUsers...)
users := commonUsers
users = append(users, uniqueUsers...)
rand.Shuffle(len(users), func(i, j int) {
users[i], users[j] = users[j], users[i]
})
@@ -1669,7 +1670,8 @@ func (a *agent) softwareMacOS() []map[string]string {
"installed_path": fmt.Sprintf("/some/path/%s", sw.Name),
}
}
software := append(commonSoftware, uniqueSoftware...)
software := commonSoftware
software = append(software, uniqueSoftware...)
software = append(software, randomVulnerableSoftware...)
a.installedSoftware.Range(func(key, value interface{}) bool {
software = append(software, value.(map[string]string))
@@ -1712,7 +1714,8 @@ func (a *mdmAgent) softwareIOSandIPadOS(source string) []fleet.Software {
})
uniqueSoftware = uniqueSoftware[:a.softwareCount.unique-a.softwareCount.uniqueSoftwareUninstallCount]
}
software := append(commonSoftware, uniqueSoftware...)
software := commonSoftware
software = append(software, uniqueSoftware...)
rand.Shuffle(len(software), func(i, j int) {
software[i], software[j] = software[j], software[i]
})
@@ -1766,7 +1769,8 @@ func (a *agent) softwareVSCodeExtensions() []map[string]string {
"source": vsCodeExtension.Source,
})
}
software := append(commonVSCodeExtensionsSoftware, uniqueVSCodeExtensionsSoftware...)
software := commonVSCodeExtensionsSoftware
software = append(software, uniqueVSCodeExtensionsSoftware...)
software = append(software, vulnerableVSCodeExtensionsSoftware...)
rand.Shuffle(len(software), func(i, j int) {
software[i], software[j] = software[j], software[i]
@@ -2181,7 +2185,7 @@ func (a *agent) processQuery(name, query string) (
ss = fleet.OsqueryStatus(1)
}
if ss == fleet.StatusOK {
switch a.os {
switch a.os { //nolint:gocritic // ignore singleCaseSwitch
case "ubuntu":
results = ubuntuSoftware
a.installedSoftware.Range(func(key, value interface{}) bool {
@@ -2562,7 +2566,8 @@ func main() {
disableFleetDesktop = flag.Bool("disable_fleet_desktop", false, "Disable Fleet Desktop")
// logger_tls_max_lines is simulating the osquery setting with the same name.
loggerTLSMaxLines = flag.Int("", 1024, "Maximum number of buffered result log lines to send on every log request")
loggerTLSMaxLines = flag.Int("logger_tls_max_lines", 1024,
"Maximum number of buffered result log lines to send on every log request")
)
flag.Parse()
@@ -2638,7 +2643,7 @@ func main() {
for tmpl_, hostCount := range tmplsm {
if hostCount > 0 {
tmpl = tmpl_
tmplsm[tmpl_] = tmplsm[tmpl_] - 1
tmplsm[tmpl_]--
break
}
}