diff --git a/.golangci.yml b/.golangci.yml
index 357557fb44..05219fd330 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -14,6 +14,7 @@ linters:
- unconvert
- unused
- errcheck
+ - gosimple
linters-settings:
depguard:
@@ -71,6 +72,8 @@ linters-settings:
# Before excluding files from gosec linter - an issue must be created and referenced in a comment.
issues:
+ max-issues-per-linter: 0 # show all issues
+ max-same-issues: 0 # show all issues
exclude-rules:
- path: server/datastore/mysql/migrations/[^/]+/[^/]+\.go
linters:
diff --git a/cmd/cpe/generate.go b/cmd/cpe/generate.go
index 076813d2f7..b2ed44ced7 100644
--- a/cmd/cpe/generate.go
+++ b/cmd/cpe/generate.go
@@ -42,7 +42,7 @@ func main() {
slog.SetDefault(slog.New(logHandler))
if apiKey == "" {
- log.Fatal(fmt.Sprintf("Must set %v environment variable", apiKeyEnvVar))
+ log.Fatalf("Must set %v environment variable", apiKeyEnvVar)
}
cwd, err := os.Getwd()
@@ -109,12 +109,12 @@ func getCPEs(client common.HTTPClient, apiKey string, resultPath string) string
// Sanity check
if totalResults <= 1 || len(cpes) != totalResults {
- log.Fatal(fmt.Sprintf("Invalid number of expected results:%v or actual results:%v", totalResults, len(cpes)))
+ log.Fatalf("Invalid number of expected results:%v or actual results:%v", totalResults, len(cpes))
}
slog.Info("Generating CPE sqlite DB...")
- dbPath := filepath.Join(resultPath, fmt.Sprint("cpe.sqlite"))
+ dbPath := filepath.Join(resultPath, "cpe.sqlite")
err = nvd.GenerateCPEDB(dbPath, cpes)
panicIf(err)
diff --git a/cmd/fleet/serve.go b/cmd/fleet/serve.go
index 9ba3618331..4c836bebdc 100644
--- a/cmd/fleet/serve.go
+++ b/cmd/fleet/serve.go
@@ -1251,8 +1251,7 @@ the way that the Fleet server works.
liveQueryRestPeriod += 10 * time.Second
// Create the handler based on whether tracing should be there
- var handler http.Handler
- handler = launcher.Handler(rootMux)
+ handler := launcher.Handler(rootMux)
srv := config.Server.DefaultHTTPServer(ctx, handler)
if liveQueryRestPeriod > srv.WriteTimeout {
diff --git a/cmd/fleet/vuln_process.go b/cmd/fleet/vuln_process.go
index 8d919720ed..189fe0ab81 100644
--- a/cmd/fleet/vuln_process.go
+++ b/cmd/fleet/vuln_process.go
@@ -116,7 +116,7 @@ by an exit code of zero.`,
return err
}
}
- level.Info(logger).Log("msg", "vulnerability processing finished", "took", time.Now().Sub(start))
+ level.Info(logger).Log("msg", "vulnerability processing finished", "took", time.Since(start))
return
},
diff --git a/cmd/fleetctl/mdm_test.go b/cmd/fleetctl/mdm_test.go
index 9d66c2126a..199c59e22c 100644
--- a/cmd/fleetctl/mdm_test.go
+++ b/cmd/fleetctl/mdm_test.go
@@ -149,23 +149,23 @@ func TestMDMRunCommand(t *testing.T) {
emptyAppleCmdFilePath, err := os.CreateTemp(t.TempDir(), "*.xml")
require.NoError(t, err)
- _, err = emptyAppleCmdFilePath.WriteString(fmt.Sprintf(`
+ _, err = emptyAppleCmdFilePath.WriteString(`
-`))
+`)
require.NoError(t, err)
emptyAppleCmdFilePath.Close()
emptyWinCmdFilePath, err := os.CreateTemp(t.TempDir(), "*.xml")
require.NoError(t, err)
- _, err = emptyWinCmdFilePath.WriteString(fmt.Sprintf(`
-`))
+ _, err = emptyWinCmdFilePath.WriteString(`
+`)
require.NoError(t, err)
emptyWinCmdFilePath.Close()
nonExecWinCmdFilePath, err := os.CreateTemp(t.TempDir(), "*.xml")
require.NoError(t, err)
- _, err = nonExecWinCmdFilePath.WriteString(fmt.Sprintf(`
+ _, err = nonExecWinCmdFilePath.WriteString(`
22
-
@@ -177,7 +177,7 @@ func TestMDMRunCommand(t *testing.T) {
NamedValuesList=MinPasswordLength,8;
-`))
+`)
require.NoError(t, err)
nonExecWinCmdFilePath.Close()
diff --git a/cmd/fleetctl/trigger.go b/cmd/fleetctl/trigger.go
index c00787b526..8d68ad2e59 100644
--- a/cmd/fleetctl/trigger.go
+++ b/cmd/fleetctl/trigger.go
@@ -37,14 +37,14 @@ func triggerCommand() *cli.Command {
root := ctxerr.Cause(err)
switch root.(type) {
case service.NotFoundErr, service.ConflictErr:
- fmt.Println(fmt.Sprintf("[!] %s", formatTriggerErrMsg(name, root.Error())))
+ fmt.Printf("[!] %s\n", formatTriggerErrMsg(name, root.Error()))
return nil
default:
return err
}
}
- fmt.Println(fmt.Sprintf("[+] Sent request to trigger %s schedule", name))
+ fmt.Printf("[+] Sent request to trigger %s schedule\n", name)
return nil
},
}
diff --git a/ee/server/service/software_installers.go b/ee/server/service/software_installers.go
index 045fa48ccd..fbbca0d4b9 100644
--- a/ee/server/service/software_installers.go
+++ b/ee/server/service/software_installers.go
@@ -283,7 +283,7 @@ func (svc *Service) UpdateSoftwareInstaller(ctx context.Context, payload *fleet.
// persist changes starting here, now that we've done all the validation/diffing we can
if len(dirty) > 0 {
- if len(dirty) == 1 && dirty["SelfService"] == true { // only self-service changed; use lighter update function
+ if len(dirty) == 1 && dirty["SelfService"] { // only self-service changed; use lighter update function
if err := svc.ds.UpdateInstallerSelfServiceFlag(ctx, *payload.SelfService, existingInstaller.InstallerID); err != nil {
return nil, ctxerr.Wrap(ctx, err, "updating installer self service flag")
}
@@ -301,7 +301,7 @@ func (svc *Service) UpdateSoftwareInstaller(ctx context.Context, payload *fleet.
if payload.UninstallScript == nil {
payload.UninstallScript = &existingInstaller.UninstallScript
}
- if payload.PostInstallScript == nil && dirty["PostInstallScript"] == false {
+ if payload.PostInstallScript == nil && !dirty["PostInstallScript"] {
payload.PostInstallScript = &existingInstaller.PostInstallScript
}
if payload.PreInstallQuery == nil {
@@ -319,7 +319,7 @@ func (svc *Service) UpdateSoftwareInstaller(ctx context.Context, payload *fleet.
// and if we're updating the package we reset counts. This is run in its own transaction internally
// for consistency, but independent of the installer update query as the main update should stick
// even if side effects fail.
- if err := svc.ds.ProcessInstallerUpdateSideEffects(ctx, existingInstaller.InstallerID, true, dirty["Package"] == true); err != nil {
+ if err := svc.ds.ProcessInstallerUpdateSideEffects(ctx, existingInstaller.InstallerID, true, dirty["Package"]); err != nil {
return nil, err
}
}
diff --git a/orbit/cmd/orbit/orbit.go b/orbit/cmd/orbit/orbit.go
index ddbc10f9ca..715567ddab 100644
--- a/orbit/cmd/orbit/orbit.go
+++ b/orbit/cmd/orbit/orbit.go
@@ -1096,9 +1096,7 @@ func main() {
// on their flagfiles.
hostIdentifier := c.String("host-identifier")
options = append(options, osquery.WithFlags([]string{"--host-identifier", hostIdentifier}))
- for _, option := range optionsAfterFlagfile {
- options = append(options, option)
- }
+ options = append(options, optionsAfterFlagfile...)
// Handle additional args after '--' in the command line. These are added last and should
// override all other flags and flagfile entries.
@@ -1622,9 +1620,9 @@ func getHostInfo(osqueryPath string, osqueryDBPath string) (*osqueryHostInfo, er
if unmarshalErr != nil {
// Since the original command failed, we log the original error and the output for debugging purposes.
log.Error().Str(
- "output", string(osquerydStdout.Bytes()),
+ "output", osquerydStdout.String(),
).Str(
- "stderr", string(osquerydStderr.Bytes()),
+ "stderr", osquerydStderr.String(),
).Msg("getHostInfo via osquery")
return nil, err
}
diff --git a/orbit/pkg/dataflatten/flatten.go b/orbit/pkg/dataflatten/flatten.go
index 132b33cc60..f1c9352c32 100644
--- a/orbit/pkg/dataflatten/flatten.go
+++ b/orbit/pkg/dataflatten/flatten.go
@@ -114,7 +114,7 @@ func WithDebugLogging() FlattenOpts {
// re-writing arrays into maps, and for filtering. See "Query
// Specification" for docs.
func WithQuery(q []string) FlattenOpts {
- if q == nil || len(q) == 0 || (len(q) == 1 && q[0] == "") {
+ if len(q) == 0 || (len(q) == 1 && q[0] == "") {
return func(_ *Flattener) {}
}
diff --git a/orbit/pkg/execuser/execuser_linux.go b/orbit/pkg/execuser/execuser_linux.go
index 748576e7ff..bfb7b797ad 100644
--- a/orbit/pkg/execuser/execuser_linux.go
+++ b/orbit/pkg/execuser/execuser_linux.go
@@ -144,9 +144,7 @@ func getLoginUID() (*user, error) {
// Returns the list of usernames.
func parseUsersOutput(s string) []string {
var users []string
- for _, userCol := range strings.Split(strings.TrimSpace(s), " ") {
- users = append(users, userCol)
- }
+ users = append(users, strings.Split(strings.TrimSpace(s), " ")...)
return users
}
diff --git a/orbit/pkg/keystore/keystore_darwin.go b/orbit/pkg/keystore/keystore_darwin.go
index 1ace32c1bd..c2f70224c8 100644
--- a/orbit/pkg/keystore/keystore_darwin.go
+++ b/orbit/pkg/keystore/keystore_darwin.go
@@ -108,8 +108,7 @@ func GetSecret() (string, error) {
mu.Lock()
defer mu.Unlock()
- var query C.CFMutableDictionaryRef
- query = C.CFDictionaryCreateMutable(
+ query := C.CFDictionaryCreateMutable(
C.kCFAllocatorDefault,
0,
&C.kCFTypeDictionaryKeyCallBacks,
diff --git a/orbit/pkg/table/crowdstrike/falconctl/parser.go b/orbit/pkg/table/crowdstrike/falconctl/parser.go
index 486af70f65..bad2053c18 100644
--- a/orbit/pkg/table/crowdstrike/falconctl/parser.go
+++ b/orbit/pkg/table/crowdstrike/falconctl/parser.go
@@ -61,9 +61,7 @@ func parseOptions(reader io.Reader) (any, error) {
kv[1] = strings.Trim(kv[1], `" `)
// Remove parenthetical note about an unset default
- if strings.HasSuffix(kv[1], " (unset default)") {
- kv[1] = kv[1][:len(kv[1])-len(" (unset default)")]
- }
+ kv[1] = strings.TrimSuffix(kv[1], " (unset default)")
if lastKey == "rfm-reason" && kv[0] == "code" {
kv[0] = "rfm-reason-code"
diff --git a/orbit/pkg/table/dataflattentable/exec.go b/orbit/pkg/table/dataflattentable/exec.go
index 6548451f76..94ade7264f 100644
--- a/orbit/pkg/table/dataflattentable/exec.go
+++ b/orbit/pkg/table/dataflattentable/exec.go
@@ -104,7 +104,7 @@ func (t *Table) exec(ctx context.Context) ([]byte, error) {
possibleBinaries := []string{}
- if t.binDirs == nil || len(t.binDirs) == 0 {
+ if len(t.binDirs) == 0 {
possibleBinaries = []string{t.execArgs[0]}
} else {
for _, possiblePath := range t.binDirs {
@@ -126,7 +126,7 @@ func (t *Table) exec(ctx context.Context) ([]byte, error) {
// try the next binary
continue
} else if err != nil {
- return nil, fmt.Errorf("calling %s. Got: %s: %w", t.execArgs[0], string(stderr.Bytes()), err)
+ return nil, fmt.Errorf("calling %s. Got: %s: %w", t.execArgs[0], stderr.String(), err)
}
// success!
diff --git a/orbit/pkg/table/find_cmd/find_cmd_darwin.go b/orbit/pkg/table/find_cmd/find_cmd_darwin.go
index 36c0fea6a6..f8955bacb4 100644
--- a/orbit/pkg/table/find_cmd/find_cmd_darwin.go
+++ b/orbit/pkg/table/find_cmd/find_cmd_darwin.go
@@ -41,7 +41,7 @@ func Columns() []table.ColumnDefinition {
}
}
-var permRegexp = regexp.MustCompile("[-+]*\\d+")
+var permRegexp = regexp.MustCompile(`[-+]*\d+`)
// Generate is called to return the results for the table at query time.
//
diff --git a/orbit/pkg/table/tablehelpers/exec.go b/orbit/pkg/table/tablehelpers/exec.go
index ec48c4f3fc..9b42399188 100644
--- a/orbit/pkg/table/tablehelpers/exec.go
+++ b/orbit/pkg/table/tablehelpers/exec.go
@@ -51,7 +51,7 @@ func Exec(ctx context.Context, log zerolog.Logger, timeoutSeconds int, possibleB
continue
default:
// an actual error
- return nil, fmt.Errorf("exec '%s'. Got: '%s': %w", cmd.String(), string(stderr.Bytes()), err)
+ return nil, fmt.Errorf("exec '%s'. Got: '%s': %w", cmd.String(), stderr.String(), err)
}
}
diff --git a/orbit/pkg/update/notifications.go b/orbit/pkg/update/notifications.go
index 58d31cd077..cd5f256458 100644
--- a/orbit/pkg/update/notifications.go
+++ b/orbit/pkg/update/notifications.go
@@ -356,7 +356,7 @@ func (h *runScriptsConfigReceiver) Run(cfg *fleet.OrbitConfig) error {
}
if runtime.GOOS == "darwin" {
- if cfg.Notifications.RunSetupExperience == true && !CanRun(h.rootDirPath, "swiftDialog", SwiftDialogMacOSTarget) {
+ if cfg.Notifications.RunSetupExperience && !CanRun(h.rootDirPath, "swiftDialog", SwiftDialogMacOSTarget) {
log.Debug().Msg("exiting scripts config runner early during setup experience: swiftDialog is not installed")
return nil
}
diff --git a/orbit/pkg/update/nudge_test.go b/orbit/pkg/update/nudge_test.go
index 5c8dd88519..4d592044cb 100644
--- a/orbit/pkg/update/nudge_test.go
+++ b/orbit/pkg/update/nudge_test.go
@@ -20,7 +20,7 @@ import (
func TestNudge(t *testing.T) {
testingSuite := new(nudgeTestSuite)
- testingSuite.s = &testingSuite.Suite
+ testingSuite.withTUF.s = &testingSuite.Suite
suite.Run(t, testingSuite)
}
@@ -268,13 +268,13 @@ func TestHelperProcess(t *testing.T) {
}
wantCmd := os.Getenv("GO_WANT_HELPER_PROCESS_COMMAND")
if gotCmd := os.Args[3]; gotCmd != wantCmd {
- fmt.Fprint(os.Stderr, fmt.Sprintf("expected command %s but got %s", wantCmd, gotCmd))
+ fmt.Fprintf(os.Stderr, "expected command %s but got %s", wantCmd, gotCmd)
os.Exit(1)
return
}
wantArgs := os.Getenv("GO_WANT_HELPER_PROCESS_ARGS")
if gotArgs := os.Args[4]; gotArgs != wantArgs {
- fmt.Fprint(os.Stderr, fmt.Sprintf("expected arg %s but got %s", wantArgs, gotArgs))
+ fmt.Fprintf(os.Stderr, "expected arg %s but got %s", wantArgs, gotArgs)
os.Exit(1)
return
}
@@ -287,8 +287,6 @@ func TestHelperProcess(t *testing.T) {
}
os.Exit(0)
-
- return
}
// mockExecCommand returns a function that can be used to mock exec.Command using TestHelperProcess.
diff --git a/orbit/pkg/update/runner.go b/orbit/pkg/update/runner.go
index 06f63671af..ae30f9c81c 100644
--- a/orbit/pkg/update/runner.go
+++ b/orbit/pkg/update/runner.go
@@ -388,7 +388,7 @@ func GetVersion(path string) (string, error) {
return "", err
}
matches := versionRegexp.FindStringSubmatch(strings.TrimSpace(string(out)))
- if matches != nil && len(matches) > 2 {
+ if len(matches) > 2 {
version = matches[2]
}
return version, nil
diff --git a/server/config/config.go b/server/config/config.go
index 5f3386a571..821c8547fc 100644
--- a/server/config/config.go
+++ b/server/config/config.go
@@ -395,11 +395,11 @@ func (s S3Config) CarvesToInternalCfg() S3ConfigInternal {
internal.StsExternalID = s.StsExternalID
}
internal.DisableSSL = s.CarvesDisableSSL
- if s.CarvesDisableSSL == false {
+ if !s.CarvesDisableSSL {
internal.DisableSSL = s.DisableSSL
}
internal.ForceS3PathStyle = s.CarvesForceS3PathStyle
- if s.CarvesForceS3PathStyle == false {
+ if !s.CarvesForceS3PathStyle {
internal.ForceS3PathStyle = s.ForceS3PathStyle
}
diff --git a/server/datastore/mysql/activities.go b/server/datastore/mysql/activities.go
index 4dd605f2ec..124c0e1b6b 100644
--- a/server/datastore/mysql/activities.go
+++ b/server/datastore/mysql/activities.go
@@ -340,7 +340,7 @@ func (ds *Datastore) ListHostUpcomingActivities(ctx context.Context, hostID uint
hsi.execution_id IS NULL
`,
// list pending software installs
- fmt.Sprintf(`SELECT
+ `SELECT
hsi.execution_id as uuid,
-- policies with automatic installers generate a host_software_installs with (user_id=NULL,self_service=0),
-- so we mark those as "Fleet"
@@ -376,9 +376,9 @@ func (ds *Datastore) ListHostUpcomingActivities(ctx context.Context, hostID uint
WHERE
hsi.host_id = :host_id AND
hsi.status = :software_status_install_pending
- `),
+ `,
// list pending software uninstalls
- fmt.Sprintf(`SELECT
+ `SELECT
hsi.execution_id as uuid,
-- policies with automatic installers generate a host_software_installs with (user_id=NULL,self_service=0),
-- so we mark those as "Fleet"
@@ -412,7 +412,7 @@ func (ds *Datastore) ListHostUpcomingActivities(ctx context.Context, hostID uint
WHERE
hsi.host_id = :host_id AND
hsi.status = :software_status_uninstall_pending
- `),
+ `,
`
SELECT
hvsi.command_uuid AS uuid,
@@ -481,8 +481,7 @@ WHERE
return nil, nil, ctxerr.Wrap(ctx, err, "select upcoming activities")
}
- var metaData *fleet.PaginationMetadata
- metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0, TotalResults: count}
+ metaData := &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0, TotalResults: count}
if len(activities) > int(opt.PerPage) { //nolint:gosec // dismiss G115
metaData.HasNextResults = true
activities = activities[:len(activities)-1]
diff --git a/server/datastore/mysql/apple_mdm.go b/server/datastore/mysql/apple_mdm.go
index b9c995dfb3..e96238645f 100644
--- a/server/datastore/mysql/apple_mdm.go
+++ b/server/datastore/mysql/apple_mdm.go
@@ -5069,14 +5069,14 @@ func (ds *Datastore) ReplaceMDMConfigAssets(ctx context.Context, assets []fleet.
func (ds *Datastore) ListIOSAndIPadOSToRefetch(ctx context.Context, interval time.Duration) (devices []fleet.AppleDevicesToRefetch,
err error,
) {
- hostsStmt := fmt.Sprintf(`
+ hostsStmt := `
SELECT h.id as host_id, h.uuid as uuid, JSON_ARRAYAGG(hmc.command_type) as commands_already_sent FROM hosts h
INNER JOIN host_mdm hmdm ON hmdm.host_id = h.id
LEFT JOIN host_mdm_commands hmc ON hmc.host_id = h.id
WHERE (h.platform = 'ios' OR h.platform = 'ipados')
AND TRIM(h.uuid) != ''
AND TIMESTAMPDIFF(SECOND, h.detail_updated_at, NOW()) > ?
-GROUP BY h.id`)
+GROUP BY h.id`
if err := sqlx.SelectContext(ctx, ds.reader(ctx), &devices, hostsStmt, interval.Seconds()); err != nil {
return nil, err
}
diff --git a/server/datastore/mysql/errors.go b/server/datastore/mysql/errors.go
index fa9bbac282..185f57ddfa 100644
--- a/server/datastore/mysql/errors.go
+++ b/server/datastore/mysql/errors.go
@@ -93,7 +93,7 @@ func (e *existsError) WithTeamID(teamID uint) error {
}
func (e *existsError) Error() string {
- msg := fmt.Sprintf("%s", e.ResourceType)
+ msg := e.ResourceType
if e.Identifier != nil {
msg += fmt.Sprintf(" %v", e.Identifier)
}
diff --git a/server/datastore/mysql/hosts_test.go b/server/datastore/mysql/hosts_test.go
index d87a880552..a6f418a49e 100644
--- a/server/datastore/mysql/hosts_test.go
+++ b/server/datastore/mysql/hosts_test.go
@@ -1118,7 +1118,7 @@ func testHostsUnenrollFromMDM(t *testing.T, ds *Datastore) {
SeenTime: time.Now(),
OsqueryHostID: ptr.String("foo"),
NodeKey: ptr.String("foo"),
- UUID: fmt.Sprintf("foo"),
+ UUID: "foo",
Hostname: "foo.local",
})
require.NoError(t, err)
@@ -1130,7 +1130,7 @@ func testHostsUnenrollFromMDM(t *testing.T, ds *Datastore) {
SeenTime: time.Now(),
OsqueryHostID: ptr.String("foo2"),
NodeKey: ptr.String("foo2"),
- UUID: fmt.Sprintf("foo2"),
+ UUID: "foo2",
Hostname: "foo2.local",
})
require.NoError(t, err)
@@ -4736,9 +4736,7 @@ func testHostsPackStatsForPlatform(t *testing.T, ds *Datastore) {
// Plus we set schedule query stats for a query that does not apply (globalSQuery1)
// (This could happen if the target platform of a schedule query is changed after creation.)
stats := make([]fleet.ScheduledQueryStats, len(globalStats))
- for i := range globalStats {
- stats[i] = globalStats[i]
- }
+ copy(stats, globalStats)
stats = append(stats, fleet.ScheduledQueryStats{
ScheduledQueryName: userSQuery1.Name,
ScheduledQueryID: userSQuery1.ID,
diff --git a/server/datastore/mysql/operating_system_vulnerabilities.go b/server/datastore/mysql/operating_system_vulnerabilities.go
index 8a6a30dec0..177a059fcc 100644
--- a/server/datastore/mysql/operating_system_vulnerabilities.go
+++ b/server/datastore/mysql/operating_system_vulnerabilities.go
@@ -36,7 +36,7 @@ func (ds *Datastore) ListVulnsByOsNameAndVersion(ctx context.Context, name, vers
var sqlstmt string
- if includeCVSS == true {
+ if includeCVSS {
sqlstmt = `
SELECT DISTINCT
osv.cve,
diff --git a/server/datastore/mysql/policies_test.go b/server/datastore/mysql/policies_test.go
index 3c943110ec..7eb2d82ee3 100644
--- a/server/datastore/mysql/policies_test.go
+++ b/server/datastore/mysql/policies_test.go
@@ -778,7 +778,8 @@ func testListMergedTeamPolicies(t *testing.T, ds *Datastore) {
// Test HostPolicyCounts
// Global Host
- host, err := ds.NewHost(context.Background(), &fleet.Host{OsqueryHostID: ptr.String(fmt.Sprint("host1")), NodeKey: ptr.String(fmt.Sprint("host1", 1)), TeamID: nil})
+ host, err := ds.NewHost(context.Background(),
+ &fleet.Host{OsqueryHostID: ptr.String("host1"), NodeKey: ptr.String(fmt.Sprint("host1", 1)), TeamID: nil})
require.NoError(t, err)
err = ds.RecordPolicyQueryExecutions(ctx, host, map[uint]*bool{gpol.ID: ptr.Bool(true)}, time.Now(), false)
diff --git a/server/datastore/mysql/software.go b/server/datastore/mysql/software.go
index 4ea0fb503a..f616e34d8d 100644
--- a/server/datastore/mysql/software.go
+++ b/server/datastore/mysql/software.go
@@ -407,9 +407,7 @@ func checkForDeletedInstalledSoftware(ctx context.Context, tx sqlx.ExtContext, d
// We don't support installing browser plugins as of 2024/08/22
if i.Browser == "" {
key := UniqueSoftwareTitleStr(i.Name, i.Source, i.BundleIdentifier)
- if _, ok := deletedTitles[key]; ok {
- delete(deletedTitles, key)
- }
+ delete(deletedTitles, key)
}
}
}
diff --git a/server/datastore/mysql/software_installers.go b/server/datastore/mysql/software_installers.go
index 04069f9bf7..82bba04ad0 100644
--- a/server/datastore/mysql/software_installers.go
+++ b/server/datastore/mysql/software_installers.go
@@ -591,7 +591,7 @@ func (ds *Datastore) InsertSoftwareUninstallRequest(ctx context.Context, executi
}
func (ds *Datastore) GetSoftwareInstallResults(ctx context.Context, resultsUUID string) (*fleet.HostSoftwareInstallerResult, error) {
- query := fmt.Sprintf(`
+ query := `
SELECT
hsi.execution_id AS execution_id,
hsi.pre_install_query_output,
@@ -615,7 +615,7 @@ FROM
LEFT JOIN software_titles st ON hsi.software_title_id = st.id
WHERE
hsi.execution_id = :execution_id
- `)
+ `
stmt, args, err := sqlx.Named(query, map[string]any{
"execution_id": resultsUUID,
@@ -639,7 +639,7 @@ WHERE
func (ds *Datastore) GetSummaryHostSoftwareInstalls(ctx context.Context, installerID uint) (*fleet.SoftwareInstallerStatusSummary, error) {
var dest fleet.SoftwareInstallerStatusSummary
- stmt := fmt.Sprintf(`
+ stmt := `
SELECT
COALESCE(SUM( IF(status = :software_status_pending_install, 1, 0)), 0) AS pending_install,
COALESCE(SUM( IF(status = :software_status_failed_install, 1, 0)), 0) AS failed_install,
@@ -663,7 +663,7 @@ WHERE
AND host_deleted_at IS NULL
AND removed = 0
GROUP BY
- host_id)) s`)
+ host_id)) s`
query, args, err := sqlx.Named(stmt, map[string]interface{}{
"installer_id": installerID,
@@ -771,7 +771,7 @@ WHERE
}
func (ds *Datastore) GetHostLastInstallData(ctx context.Context, hostID, installerID uint) (*fleet.HostLastInstallData, error) {
- stmt := fmt.Sprintf(`
+ stmt := `
SELECT execution_id, hsi.status
FROM host_software_installs hsi
WHERE hsi.id = (
@@ -782,7 +782,7 @@ func (ds *Datastore) GetHostLastInstallData(ctx context.Context, hostID, install
software_installer_id = :installer_id AND host_id = :host_id
GROUP BY
host_id, software_installer_id)
-`)
+`
stmt, args, err := sqlx.Named(stmt, map[string]interface{}{
"host_id": hostID,
diff --git a/server/datastore/mysql/software_test.go b/server/datastore/mysql/software_test.go
index a45192266b..23ac4f93db 100644
--- a/server/datastore/mysql/software_test.go
+++ b/server/datastore/mysql/software_test.go
@@ -4087,7 +4087,7 @@ func testListHostSoftware(t *testing.T, ds *Datastore) {
},
}
for _, c := range cases {
- t.Run(fmt.Sprintf("%s", c.name), func(t *testing.T) {
+ t.Run(c.name, func(t *testing.T) {
// always include metadata
c.opts.ListOptions.IncludeMetadata = true
c.opts.ListOptions.OrderKey = "name"
diff --git a/server/fleet/app.go b/server/fleet/app.go
index 483dd5fe79..59c5ef24f4 100644
--- a/server/fleet/app.go
+++ b/server/fleet/app.go
@@ -558,8 +558,7 @@ func (c *AppConfig) Copy() *AppConfig {
return nil
}
- var clone AppConfig
- clone = *c
+ clone := *c
// OrgInfo: nothing needs cloning
// FleetDesktopSettings: nothing needs cloning
@@ -570,8 +569,7 @@ func (c *AppConfig) Copy() *AppConfig {
}
if c.SMTPSettings != nil {
- var smtpSettings SMTPSettings
- smtpSettings = *c.SMTPSettings
+ smtpSettings := *c.SMTPSettings
clone.SMTPSettings = &smtpSettings
}
@@ -599,8 +597,7 @@ func (c *AppConfig) Copy() *AppConfig {
}
if c.SSOSettings != nil {
- var ssoSettings SSOSettings
- ssoSettings = *c.SSOSettings
+ ssoSettings := *c.SSOSettings
clone.SSOSettings = &ssoSettings
}
@@ -662,9 +659,7 @@ func (c *AppConfig) Copy() *AppConfig {
if c.MDM.AppleBusinessManager.Set {
abm := make([]MDMAppleABMAssignmentInfo, len(c.MDM.AppleBusinessManager.Value))
- for i, s := range c.MDM.AppleBusinessManager.Value {
- abm[i] = s
- }
+ copy(abm, c.MDM.AppleBusinessManager.Value)
clone.MDM.AppleBusinessManager = optjson.SetSlice(abm)
}
@@ -1031,8 +1026,7 @@ func (f *Features) Copy() *Features {
// EnableHostUsers and EnableSoftwareInventory don't have fields that require
// cloning (all fields are basic value types, no pointers/slices/maps).
- var clone Features
- clone = *f
+ clone := *f
if f.AdditionalQueries != nil {
aq := make(json.RawMessage, len(*f.AdditionalQueries))
diff --git a/server/fleet/cron_schedules.go b/server/fleet/cron_schedules.go
index d051715e84..42541a96d1 100644
--- a/server/fleet/cron_schedules.go
+++ b/server/fleet/cron_schedules.go
@@ -100,7 +100,7 @@ func (cs *CronSchedules) formatSupportedTriggerNames() string {
case 1:
return fmt.Sprintf("supported trigger name is %s", names[0])
default:
- return fmt.Sprintf("supported trigger names are %s, and %s", strings.Join(names[:len(names)-1], fmt.Sprint(", ")), names[len(names)-1])
+ return fmt.Sprintf("supported trigger names are %s, and %s", strings.Join(names[:len(names)-1], ", "), names[len(names)-1])
}
}
diff --git a/server/fleet/hosts.go b/server/fleet/hosts.go
index 70ff7900ba..0ff7d1bf62 100644
--- a/server/fleet/hosts.go
+++ b/server/fleet/hosts.go
@@ -214,7 +214,7 @@ type HostListOptions struct {
// TODO(Sarah): Are we missing any filters here? Should all MDM filters be included?
func (h HostListOptions) Empty() bool {
return h.ListOptions.Empty() &&
- h.DeviceMapping == false &&
+ !h.DeviceMapping &&
len(h.AdditionalFilters) == 0 &&
h.StatusFilter == "" &&
h.TeamFilter == nil &&
@@ -227,7 +227,7 @@ func (h HostListOptions) Empty() bool {
h.OSIDFilter == nil &&
h.OSNameFilter == nil &&
h.OSVersionFilter == nil &&
- h.DisableIssues == false &&
+ !h.DisableIssues &&
h.MacOSSettingsFilter == "" &&
h.MacOSSettingsDiskEncryptionFilter == "" &&
h.MDMBootstrapPackageFilter == nil &&
diff --git a/server/fleet/mdm.go b/server/fleet/mdm.go
index f5afed1e45..d6c2a2d000 100644
--- a/server/fleet/mdm.go
+++ b/server/fleet/mdm.go
@@ -548,8 +548,7 @@ func (p *MDMProfileSpec) Copy() *MDMProfileSpec {
return nil
}
- var clone MDMProfileSpec
- clone = *p
+ clone := *p
if len(p.Labels) > 0 {
clone.Labels = make([]string, len(p.Labels))
diff --git a/server/fleet/packs.go b/server/fleet/packs.go
index 2be91b6cf2..cb62ade47a 100644
--- a/server/fleet/packs.go
+++ b/server/fleet/packs.go
@@ -60,8 +60,7 @@ func (p *Pack) Copy() *Pack {
return nil
}
- var clone Pack
- clone = *p
+ clone := *p
if p.Type != nil {
clone.Type = ptr.String(*p.Type)
}
diff --git a/server/fleet/queries.go b/server/fleet/queries.go
index 4b4d3eaf70..70920c72f9 100644
--- a/server/fleet/queries.go
+++ b/server/fleet/queries.go
@@ -119,8 +119,7 @@ func (q *Query) Copy() *Query {
return nil
}
- var clone Query
- clone = *q
+ clone := *q
if q.TeamID != nil {
clone.TeamID = ptr.Uint(*q.TeamID)
diff --git a/server/fleet/scheduled_queries.go b/server/fleet/scheduled_queries.go
index 62d68e2fb8..aba564f4ef 100644
--- a/server/fleet/scheduled_queries.go
+++ b/server/fleet/scheduled_queries.go
@@ -70,8 +70,7 @@ func (q *ScheduledQuery) Copy() *ScheduledQuery {
return nil
}
- var clone ScheduledQuery
- clone = *q
+ clone := *q
if q.Snapshot != nil {
clone.Snapshot = ptr.Bool(*q.Snapshot)
diff --git a/server/fleet/software.go b/server/fleet/software.go
index c8c220ddc4..8ac54a1365 100644
--- a/server/fleet/software.go
+++ b/server/fleet/software.go
@@ -353,9 +353,7 @@ func (uhsdbr *UpdateHostSoftwareDBResult) CurrInstalled() []Software {
}
}
- for _, i := range uhsdbr.Inserted {
- r = append(r, i)
- }
+ r = append(r, uhsdbr.Inserted...)
return r
}
diff --git a/server/fleet/teams.go b/server/fleet/teams.go
index 4ee8b53aad..1fe65dbcc8 100644
--- a/server/fleet/teams.go
+++ b/server/fleet/teams.go
@@ -216,8 +216,7 @@ func (t *TeamMDM) Copy() *TeamMDM {
return nil
}
- var clone TeamMDM
- clone = *t
+ clone := *t
// EnableDiskEncryption, MacOSUpdates and MacOSSetup don't have fields that
// require cloning (all fields are basic value types, no
diff --git a/server/goose/migration_sql.go b/server/goose/migration_sql.go
index a2d5bafcec..0428f49bf8 100644
--- a/server/goose/migration_sql.go
+++ b/server/goose/migration_sql.go
@@ -62,27 +62,23 @@ func splitSQLStatements(r io.Reader, direction bool) (stmts []string) {
cmd := strings.TrimSpace(line[len(sqlCmdPrefix):])
switch cmd {
case "Up":
- directionIsActive = (direction == true)
+ directionIsActive = direction
upSections++
- break
case "Down":
- directionIsActive = (direction == false)
+ directionIsActive = !direction
downSections++
- break
case "StatementBegin":
if directionIsActive {
ignoreSemicolons = true
}
- break
case "StatementEnd":
if directionIsActive {
- statementEnded = (ignoreSemicolons == true)
+ statementEnded = ignoreSemicolons
ignoreSemicolons = false
}
- break
}
}
diff --git a/server/logging/firehose_test.go b/server/logging/firehose_test.go
index bf1e97df70..667727f61d 100644
--- a/server/logging/firehose_test.go
+++ b/server/logging/firehose_test.go
@@ -187,7 +187,7 @@ func TestFirehoseRecordTooBig(t *testing.T) {
ctx := context.Background()
newLogs := make([]json.RawMessage, len(logs))
copy(newLogs, logs)
- newLogs[0] = make(json.RawMessage, firehoseMaxSizeOfRecord+1, firehoseMaxSizeOfRecord+1)
+ newLogs[0] = make(json.RawMessage, firehoseMaxSizeOfRecord+1)
callCount := 0
putFunc := func(input *firehose.PutRecordBatchInput) (*firehose.PutRecordBatchOutput, error) {
callCount += 1
@@ -208,7 +208,7 @@ func TestFirehoseSplitBatchBySize(t *testing.T) {
// just under 4 MB each
logs := make([]json.RawMessage, 12)
for i := 0; i < len(logs); i++ {
- logs[i] = make(json.RawMessage, firehoseMaxSizeOfRecord-1, firehoseMaxSizeOfRecord-1)
+ logs[i] = make(json.RawMessage, firehoseMaxSizeOfRecord-1)
}
callCount := 0
putFunc := func(input *firehose.PutRecordBatchInput) (*firehose.PutRecordBatchOutput, error) {
diff --git a/server/logging/kinesis_test.go b/server/logging/kinesis_test.go
index f5e32cfc35..bc7fd1eccf 100644
--- a/server/logging/kinesis_test.go
+++ b/server/logging/kinesis_test.go
@@ -164,7 +164,7 @@ func TestKinesisRecordTooBig(t *testing.T) {
ctx := context.Background()
newLogs := make([]json.RawMessage, len(logs))
copy(newLogs, logs)
- newLogs[0] = make(json.RawMessage, kinesisMaxSizeOfRecord+1, kinesisMaxSizeOfRecord+1)
+ newLogs[0] = make(json.RawMessage, kinesisMaxSizeOfRecord+1)
callCount := 0
putFunc := func(input *kinesis.PutRecordsInput) (*kinesis.PutRecordsOutput, error) {
callCount += 1
@@ -185,7 +185,7 @@ func TestKinesisSplitBatchBySize(t *testing.T) {
// takes 3 total batches of just under 5 MB each
logs := make([]json.RawMessage, 15)
for i := 0; i < len(logs); i++ {
- logs[i] = make(json.RawMessage, kinesisMaxSizeOfRecord-1-256, kinesisMaxSizeOfRecord-1-256)
+ logs[i] = make(json.RawMessage, kinesisMaxSizeOfRecord-1-256)
}
callCount := 0
putFunc := func(input *kinesis.PutRecordsInput) (*kinesis.PutRecordsOutput, error) {
diff --git a/server/mdm/nanomdm/http/api/api.go b/server/mdm/nanomdm/http/api/api.go
index ccb6218d33..34a6a8717d 100644
--- a/server/mdm/nanomdm/http/api/api.go
+++ b/server/mdm/nanomdm/http/api/api.go
@@ -288,7 +288,6 @@ func readPEMCertAndKey(input []byte) (cert []byte, key []byte, err error) {
key = pem.EncodeToMemory(block)
default:
err = fmt.Errorf("unrecognized PEM type: %q", block.Type)
- break
}
}
return
diff --git a/server/mdm/nanomdm/push/service/service.go b/server/mdm/nanomdm/push/service/service.go
index 4dbe63048a..d74ae752a8 100644
--- a/server/mdm/nanomdm/push/service/service.go
+++ b/server/mdm/nanomdm/push/service/service.go
@@ -50,7 +50,7 @@ func (s *PushService) getProvider(ctx context.Context, topic string) (push.PushP
stale bool
)
s.providersMu.RLock()
- prov, _ := s.providers[topic]
+ prov := s.providers[topic]
s.providersMu.RUnlock()
if prov != nil && prov.provider != nil {
stale, err = s.certStore.IsPushCertStale(ctx, topic, prov.staleToken)
diff --git a/server/mdm/scep/depot/bolt/depot.go b/server/mdm/scep/depot/bolt/depot.go
index 4e6b75afe2..7afd3a0811 100644
--- a/server/mdm/scep/depot/bolt/depot.go
+++ b/server/mdm/scep/depot/bolt/depot.go
@@ -182,7 +182,7 @@ func (db *Depot) HasCN(cn string, allowTime int, cert *x509.Certificate, revokeO
curs := tx.Bucket([]byte(certBucket)).Cursor()
prefix := []byte(cert.Subject.CommonName)
for k, v := curs.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = curs.Next() {
- if bytes.Compare(v, cert.Raw) == 0 {
+ if bytes.Equal(v, cert.Raw) {
hasCN = true
return nil
}
diff --git a/server/service/apple_mdm.go b/server/service/apple_mdm.go
index 9567bd97e3..03636bf91f 100644
--- a/server/service/apple_mdm.go
+++ b/server/service/apple_mdm.go
@@ -3638,7 +3638,6 @@ func preprocessProfileContents(
return ctxerr.Wrap(ctx, err, "updating host MDM Apple profiles for unknown variable")
}
valid = false
- break
}
}
if !valid {
diff --git a/server/service/integration_core_test.go b/server/service/integration_core_test.go
index 12f4540f08..9fd083b1e9 100644
--- a/server/service/integration_core_test.go
+++ b/server/service/integration_core_test.go
@@ -10197,7 +10197,7 @@ func (s *integrationTestSuite) TestDirectIngestSoftwareWithInvalidFields() {
require.NoError(t, err)
logs1, err := io.ReadAll(&w1)
require.NoError(t, err)
- require.Contains(t, string(logs1), "host reported software with empty name", fmt.Sprintf("%s", logs1))
+ require.Contains(t, string(logs1), "host reported software with empty name", string(logs1))
require.Contains(t, string(logs1), "debug")
// Check that the software was not ingested.
diff --git a/server/service/integration_enterprise_test.go b/server/service/integration_enterprise_test.go
index 14655ab6ac..c7f5cb3612 100644
--- a/server/service/integration_enterprise_test.go
+++ b/server/service/integration_enterprise_test.go
@@ -4441,7 +4441,7 @@ func (s *integrationEnterpriseTestSuite) TestOSVersions() {
// generate aggregated stats
require.NoError(t, s.ds.UpdateOSVersions(context.Background()))
// team1 user does not have access to team0 host
- s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/os_versions"), nil, http.StatusOK, &osVersionsResp)
+ s.DoJSON("GET", "/api/latest/fleet/os_versions", nil, http.StatusOK, &osVersionsResp)
assert.Empty(t, osVersionsResp.OSVersions)
s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/os_versions/%d", osinfo.OSVersionID), nil, http.StatusOK, &osVersionResp)
assert.Zero(t, osVersionResp.OSVersion.HostsCount)
@@ -4449,7 +4449,7 @@ func (s *integrationEnterpriseTestSuite) TestOSVersions() {
// Move host from team0 to team1
require.NoError(t, s.ds.AddHostsToTeam(context.Background(), &team1.ID, []uint{hosts[0].ID}))
require.NoError(t, s.ds.UpdateOSVersions(context.Background()))
- s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/os_versions"), nil, http.StatusOK, &osVersionsResp)
+ s.DoJSON("GET", "/api/latest/fleet/os_versions", nil, http.StatusOK, &osVersionsResp)
require.Len(t, osVersionsResp.OSVersions, 1)
assert.Equal(t, expectedOSVersion, osVersionsResp.OSVersions[0])
s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/os_versions/%d", osinfo.OSVersionID), nil, http.StatusOK, &osVersionResp)
@@ -4463,20 +4463,20 @@ func (s *integrationEnterpriseTestSuite) TestOSVersions() {
// team user doesn't have acess to "no team"
osVersionsResp = osVersionsResponse{}
- s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/os_versions"), nil, http.StatusForbidden, &osVersionsResp, "team_id", "0")
+ s.DoJSON("GET", "/api/latest/fleet/os_versions", nil, http.StatusForbidden, &osVersionsResp, "team_id", "0")
require.Len(t, osVersionsResp.OSVersions, 0)
// team_id=0 is supported and returns results for hosts in "no team"
s.token = getTestAdminToken(t, s.server)
// no hosts, the results are empty
osVersionsResp = osVersionsResponse{}
- s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/os_versions"), nil, http.StatusOK, &osVersionsResp, "team_id", "0")
+ s.DoJSON("GET", "/api/latest/fleet/os_versions", nil, http.StatusOK, &osVersionsResp, "team_id", "0")
require.Len(t, osVersionsResp.OSVersions, 0)
osVersionsResp = osVersionsResponse{}
// move the host to "no team" and update the stats
require.NoError(t, s.ds.AddHostsToTeam(context.Background(), nil, []uint{hosts[0].ID}))
require.NoError(t, s.ds.UpdateOSVersions(context.Background()))
- s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/os_versions"), nil, http.StatusOK, &osVersionsResp, "team_id", "0")
+ s.DoJSON("GET", "/api/latest/fleet/os_versions", nil, http.StatusOK, &osVersionsResp, "team_id", "0")
require.Len(t, osVersionsResp.OSVersions, 1)
osVersionResp = getOSVersionResponse{}
s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/os_versions/%d", osinfo.OSVersionID), nil, http.StatusOK, &osVersionResp, "team_id", "0")
@@ -10498,7 +10498,8 @@ func (s *integrationEnterpriseTestSuite) TestSoftwareInstallerUploadDownloadAndD
installerID, titleID := checkSoftwareInstaller(t, payload)
// check activity
- s.lastActivityOfTypeMatches(fleet.ActivityTypeAddedSoftware{}.ActivityName(), fmt.Sprintf(`{"software_title": "ruby", "software_package": "ruby.deb", "team_name": null, "team_id": 0, "self_service": true}`), 0)
+ s.lastActivityOfTypeMatches(fleet.ActivityTypeAddedSoftware{}.ActivityName(),
+ `{"software_title": "ruby", "software_package": "ruby.deb", "team_name": null, "team_id": 0, "self_service": true}`, 0)
// upload again fails
s.uploadSoftwareInstaller(t, payload, http.StatusConflict, "already exists")
@@ -10562,7 +10563,8 @@ func (s *integrationEnterpriseTestSuite) TestSoftwareInstallerUploadDownloadAndD
s.Do("DELETE", fmt.Sprintf("/api/latest/fleet/software/titles/%d/available_for_install", titleID), nil, http.StatusNoContent, "team_id", "0")
// check activity
- s.lastActivityOfTypeMatches(fleet.ActivityTypeDeletedSoftware{}.ActivityName(), fmt.Sprintf(`{"software_title": "ruby", "software_package": "ruby.deb", "team_name": null, "team_id": 0, "self_service": true}`), 0)
+ s.lastActivityOfTypeMatches(fleet.ActivityTypeDeletedSoftware{}.ActivityName(),
+ `{"software_title": "ruby", "software_package": "ruby.deb", "team_name": null, "team_id": 0, "self_service": true}`, 0)
// download the installer, not found anymore
s.Do("GET", fmt.Sprintf("/api/latest/fleet/software/titles/%d/package?alt=media", titleID), nil, http.StatusNotFound, "team_id", fmt.Sprintf("%d", 0))
diff --git a/server/service/integration_mdm_dep_test.go b/server/service/integration_mdm_dep_test.go
index 670d1de5db..f1ae5b825a 100644
--- a/server/service/integration_mdm_dep_test.go
+++ b/server/service/integration_mdm_dep_test.go
@@ -1609,13 +1609,13 @@ func (s *integrationMDMTestSuite) TestSetupExperienceScript() {
// res = s.Do("GET", fmt.Sprintf("/api/latest/fleet/setup_experience/script?team_id=%d&alt=media", noTeamID), nil, http.StatusOK)
// delete the no-team script
- s.Do("DELETE", fmt.Sprintf("/api/latest/fleet/setup_experience/script"), nil, http.StatusOK)
+ s.Do("DELETE", "/api/latest/fleet/setup_experience/script", nil, http.StatusOK)
// try get the no-team script
s.Do("GET", "/api/latest/fleet/setup_experience/script", nil, http.StatusNotFound)
// try deleting the no-team script again
- s.Do("DELETE", fmt.Sprintf("/api/latest/fleet/setup_experience/script"), nil, http.StatusOK) // TODO: confirm if we want to return not found
+ s.Do("DELETE", "/api/latest/fleet/setup_experience/script", nil, http.StatusOK) // TODO: confirm if we want to return not found
// // TODO: confirm if we will allow team_id=0 requests
// s.Do("DELETE", fmt.Sprintf("/api/latest/fleet/setup_experience/script/?team_id=%d", noTeamID), nil, http.StatusOK)
diff --git a/server/service/integration_mdm_test.go b/server/service/integration_mdm_test.go
index bf4f9556f2..8adb4028a4 100644
--- a/server/service/integration_mdm_test.go
+++ b/server/service/integration_mdm_test.go
@@ -10408,7 +10408,7 @@ func (s *integrationMDMTestSuite) TestRefetchIOSIPadOS() {
// Check that we have the correct software titles
var resp listSoftwareTitlesResponse
- s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/software/titles"), nil, http.StatusOK, &resp, "query", "Evernote")
+ s.DoJSON("GET", "/api/latest/fleet/software/titles", nil, http.StatusOK, &resp, "query", "Evernote")
expectedTitles := []fleet.SoftwareTitleListResult{
{
BundleIdentifier: ptr.String("com.evernote.iPhone.Evernote"),
@@ -10442,7 +10442,7 @@ func (s *integrationMDMTestSuite) TestRefetchIOSIPadOS() {
hostsCountTs = time.Now().UTC()
require.NoError(t, s.ds.ReconcileSoftwareTitles(ctx))
require.NoError(t, s.ds.SyncHostsSoftwareTitles(ctx, hostsCountTs))
- s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/software/titles"), nil, http.StatusOK, &resp, "query", "Evernote")
+ s.DoJSON("GET", "/api/latest/fleet/software/titles", nil, http.StatusOK, &resp, "query", "Evernote")
require.Len(t, resp.SoftwareTitles, 2)
// Cleaning up the response to make it easier to compare using ElementsMatch
for index := range resp.SoftwareTitles {
diff --git a/server/service/osquery.go b/server/service/osquery.go
index c0f79bddcc..d235470b78 100644
--- a/server/service/osquery.go
+++ b/server/service/osquery.go
@@ -978,7 +978,7 @@ func (svc *Service) SubmitDistributedQueryResults(
}
ll.Log("query", query, "message", messages[query], "hostID", host.ID)
}
- queryStats, _ := stats[query]
+ queryStats := stats[query]
ingestedDetailUpdated, ingestedAdditionalUpdated, err := svc.ingestQueryResults(
ctx, query, host, rows, failed, messages, policyResults, labelResults, additionalResults, queryStats,
@@ -1358,7 +1358,7 @@ func preProcessSoftwareExtraResults(
}
// Extract the results of the extra query.
- softwareExtraRows, _ := (*results)[softwareExtraQuery]
+ softwareExtraRows := (*results)[softwareExtraQuery]
if len(softwareExtraRows) == 0 {
return
}
diff --git a/server/service/service_campaigns.go b/server/service/service_campaigns.go
index 1d00167618..9574d4c74d 100644
--- a/server/service/service_campaigns.go
+++ b/server/service/service_campaigns.go
@@ -465,5 +465,4 @@ func (svc Service) updateStats(
}
tracker.aggregationNeeded = false
}
- return
}
diff --git a/server/service/testing_utils.go b/server/service/testing_utils.go
index 055bbe6dbb..b0d91ca44f 100644
--- a/server/service/testing_utils.go
+++ b/server/service/testing_utils.go
@@ -569,9 +569,7 @@ func (m *memFailingPolicySet) ListHosts(policyID uint) ([]fleet.PolicySetHost, e
defer m.mMu.RUnlock()
hosts := make([]fleet.PolicySetHost, len(m.m[policyID]))
- for i := range m.m[policyID] {
- hosts[i] = m.m[policyID][i]
- }
+ copy(hosts, m.m[policyID])
return hosts, nil
}
diff --git a/server/vulnerabilities/msrc/analyzer.go b/server/vulnerabilities/msrc/analyzer.go
index 0452aa5364..d50d087eec 100644
--- a/server/vulnerabilities/msrc/analyzer.go
+++ b/server/vulnerabilities/msrc/analyzer.go
@@ -77,9 +77,7 @@ func Analyze(
return nil, err
}
var existing []fleet.OSVulnerability
- for _, osv := range osVulns {
- existing = append(existing, osv)
- }
+ existing = append(existing, osVulns...)
// Compute what needs to be inserted/deleted for this batch
insrt, del := utils.VulnsDelta(found, existing)
diff --git a/server/vulnerabilities/nvd/cpe_matching_rule.go b/server/vulnerabilities/nvd/cpe_matching_rule.go
index 9bd8a9b751..428e1a7f8a 100644
--- a/server/vulnerabilities/nvd/cpe_matching_rule.go
+++ b/server/vulnerabilities/nvd/cpe_matching_rule.go
@@ -57,10 +57,7 @@ func (rule CPEMatchingRule) CPEMatches(cpeMeta *wfn.Attributes) bool {
}
if rule.IgnoreIf != nil {
- if rule.IgnoreIf(cpeMeta) {
- return false
- }
- return true
+ return !rule.IgnoreIf(cpeMeta)
}
ver, err := semver.NewVersion(wfn.StripSlashes(cpeMeta.Version))
diff --git a/server/vulnerabilities/nvd/sync/cve_syncer.go b/server/vulnerabilities/nvd/sync/cve_syncer.go
index 8ecdb8e8da..f3e1225bb3 100644
--- a/server/vulnerabilities/nvd/sync/cve_syncer.go
+++ b/server/vulnerabilities/nvd/sync/cve_syncer.go
@@ -1131,8 +1131,6 @@ func updateWithVulnCheckConfigurations(cve *schema.NVDCVEFeedJSON10DefCVEItem, v
CVEDataVersion: "4.0", // All entries seem to have this version string.
Nodes: nodes,
}
-
- return
}
// convertAPI20TimeToLegacy converts the timestamps from API 2.0 format to the expected legacy feed time format.
diff --git a/server/vulnerabilities/utils/utils_test.go b/server/vulnerabilities/utils/utils_test.go
index 6a424ecaf7..480c989620 100644
--- a/server/vulnerabilities/utils/utils_test.go
+++ b/server/vulnerabilities/utils/utils_test.go
@@ -46,12 +46,8 @@ func TestRecentVulns(t *testing.T) {
}
var input []fleet.SoftwareVulnerability
- for _, e := range ovalVulns {
- input = append(input, e)
- }
- for _, e := range nvdVulns {
- input = append(input, e)
- }
+ input = append(input, ovalVulns...)
+ input = append(input, nvdVulns...)
var actual []string
vulns, meta := RecentVulns(input, meta)
diff --git a/tools/mdm/migration/mdmproxy/mdmproxy.go b/tools/mdm/migration/mdmproxy/mdmproxy.go
index 5f23c977b9..baff23a506 100644
--- a/tools/mdm/migration/mdmproxy/mdmproxy.go
+++ b/tools/mdm/migration/mdmproxy/mdmproxy.go
@@ -240,7 +240,7 @@ func (m *mdmProxy) isUDIDMigrated(udid string) bool {
func udidFromRequestBody(body []byte) (string, error) {
// Not all requests (eg. SCEP) contain a UDID. Return empty without an error in this case.
- if body == nil || len(body) == 0 {
+ if len(body) == 0 {
return "", nil
}
diff --git a/tools/nvd/nvdvuln/nvdvuln.go b/tools/nvd/nvdvuln/nvdvuln.go
index e0baec3e56..dfa9e41022 100644
--- a/tools/nvd/nvdvuln/nvdvuln.go
+++ b/tools/nvd/nvdvuln/nvdvuln.go
@@ -93,19 +93,17 @@ func main() {
defer cpuAndMemFile.Close()
go func() {
for {
- select {
- case <-time.After(1 * time.Second):
- cpuPercent, err := myProcess.CPUPercent()
- if err != nil {
- panic(err)
- }
- memInfo, err := myProcess.MemoryInfo()
- if err != nil {
- panic(err)
- }
- now := time.Now().UTC().Format("15:04:05")
- fmt.Fprintf(cpuAndMemFile, "%s %.2f %.2f\n", now, cpuPercent, float64(memInfo.RSS)/1024.0/1024.0)
+ time.Sleep(time.Second)
+ cpuPercent, err := myProcess.CPUPercent()
+ if err != nil {
+ panic(err)
}
+ memInfo, err := myProcess.MemoryInfo()
+ if err != nil {
+ panic(err)
+ }
+ now := time.Now().UTC().Format("15:04:05")
+ fmt.Fprintf(cpuAndMemFile, "%s %.2f %.2f\n", now, cpuPercent, float64(memInfo.RSS)/1024.0/1024.0)
}
}()
}
@@ -281,10 +279,7 @@ type softwareIterator struct {
}
func (s *softwareIterator) Next() bool {
- if s.i >= len(s.software) {
- return false
- }
- return true
+ return s.i < len(s.software)
}
func (s *softwareIterator) Value() (*fleet.Software, error) {