From f85b6f776f12ea94260528129de91ea7cb33d9a6 Mon Sep 17 00:00:00 2001 From: Victor Lyuboslavsky Date: Fri, 18 Oct 2024 12:38:26 -0500 Subject: [PATCH] Updating golangci-lint to 1.61.0 (#22973) --- .github/workflows/golangci-lint.yml | 2 +- .golangci.yml | 2 +- Makefile | 2 +- cmd/fleet/cron.go | 2 +- cmd/fleet/serve_test.go | 7 +- cmd/fleetctl/apply_test.go | 8 +- cmd/fleetctl/debug.go | 30 +++-- cmd/fleetctl/debug_test.go | 2 +- cmd/fleetctl/delete.go | 6 +- cmd/fleetctl/get_test.go | 6 +- cmd/fleetctl/gitops_test.go | 6 +- cmd/fleetctl/login.go | 14 +-- cmd/fleetctl/preview.go | 8 +- cmd/fleetctl/query.go | 6 +- cmd/fleetctl/scripts_test.go | 4 +- cmd/fleetctl/setup.go | 2 +- cmd/fleetctl/user.go | 9 +- cmd/fleetctl/users_test.go | 2 +- cmd/osquery-perf/agent.go | 25 +++-- ee/server/calendar/google_calendar.go | 2 +- .../load_test/calendar_http_handler.go | 9 +- ee/server/service/calendar.go | 2 +- ee/server/service/mdm_external_test.go | 9 +- ee/server/service/teams_test.go | 2 +- orbit/cmd/desktop/desktop.go | 2 +- orbit/cmd/orbit/orbit.go | 16 ++- orbit/pkg/cryptoinfo/identify_test.go | 2 +- orbit/pkg/cryptoinfo/try_pem.go | 3 +- orbit/pkg/dataflatten/ini.go | 1 - orbit/pkg/installer/installer_test.go | 6 +- orbit/pkg/keystore/keystore_darwin.go | 12 +- orbit/pkg/scripts/exec_nonwindows_test.go | 2 +- orbit/pkg/scripts/scripts_test.go | 2 +- orbit/pkg/table/app-icons/app_icons_darwin.go | 2 +- orbit/pkg/table/csrutil_info/csrutil_info.go | 15 +-- .../table/firmwarepasswd/firmwarepasswd.go | 6 +- orbit/pkg/table/fleetd_logs/fleetd_logs.go | 10 +- orbit/pkg/table/tcc_access/tcc_access.go | 4 +- orbit/pkg/table/tcc_access/tcc_access_test.go | 7 +- orbit/pkg/update/filestore/filestore.go | 7 +- orbit/pkg/update/flag_runner.go | 2 +- orbit/pkg/update/nudge_test.go | 4 +- orbit/pkg/update/runner.go | 2 +- orbit/pkg/useraction/mdm_migration_darwin.go | 15 ++- orbit/tools/build/build-windows.go | 2 +- pkg/buildpkg/buildpkg.go | 10 +- pkg/download/download_test.go | 2 +- pkg/file/file_test.go | 4 +- pkg/file/msi.go | 11 +- pkg/rawjson/rawjson.go | 3 +- pkg/secure/secure.go | 2 +- pkg/spec/gitops.go | 7 +- server/config/config.go | 4 +- server/contexts/ctxerr/stack_test.go | 4 +- server/cron/calendar_cron_test.go | 22 ++-- .../cached_mysql/cached_mysql_test.go | 3 +- server/datastore/mysql/activities.go | 6 +- server/datastore/mysql/aggregated_stats.go | 4 +- server/datastore/mysql/app_configs.go | 2 +- server/datastore/mysql/apple_mdm.go | 11 +- server/datastore/mysql/apple_mdm_test.go | 58 +++++----- server/datastore/mysql/calendar_events.go | 2 +- server/datastore/mysql/campaigns.go | 6 +- server/datastore/mysql/campaigns_test.go | 3 +- server/datastore/mysql/carves.go | 4 +- server/datastore/mysql/delete.go | 2 +- server/datastore/mysql/hosts.go | 5 +- server/datastore/mysql/hosts_test.go | 4 +- server/datastore/mysql/invites.go | 2 +- server/datastore/mysql/jobs.go | 2 +- server/datastore/mysql/labels.go | 2 +- server/datastore/mysql/maintained_apps.go | 6 +- .../datastore/mysql/maintained_apps_test.go | 24 ++-- server/datastore/mysql/mdm.go | 7 +- server/datastore/mysql/mdm_test.go | 3 +- ...0171116163618_CreateTableOsqueryOptions.go | 3 +- .../20210601000008_TeamsEnrollSecrets.go | 4 +- ...323152301_CleanupHostRelatedTables_test.go | 4 +- ...5082126_AddMDMAppleSetupAssistants_test.go | 6 +- ...AppleSetupAssistantsAddProfileUUID_test.go | 4 +- ...230503101418_AlterJobsAddNotBefore_test.go | 2 +- ..._AddMDMAppleDefaultSetupAssistants_test.go | 4 +- ...hanedMDMAppleConfigurationProfiles_test.go | 2 +- ...0131083822_AddUniqueHashToPolicies_test.go | 5 +- ...40221112844_FixUniquePolicyNameBug_test.go | 7 +- ..._AddCertInfoToNanoCertAssociations_test.go | 6 +- ..._AddScriptContentsTableAndRelationships.go | 2 +- ...40314085226_AddCalendarEventTables_test.go | 4 +- ...20240430111727_CleanupQueryResults_test.go | 6 +- ...195531_AddTimezoneToCalendarEvents_test.go | 4 +- ...0707134035_AddUUIDToCalendarEvents_test.go | 4 +- ...7134036_CreateIOSAndIPADOSBuiltinLabels.go | 4 +- ...36_CreateIOSAndIPADOSBuiltinLabels_test.go | 2 +- ...40710155623_FixResetLastEnrolledAt_test.go | 2 +- ..._AddGlobalStatToSoftwareHostCounts_test.go | 2 +- ...lobalStatToSoftwareTitleHostCounts_test.go | 2 +- ...829165448_SupportMultipleABMTokens_test.go | 4 +- ...20240905200001_AddPoliciesToNoTeam_test.go | 6 +- .../20241002104104_UpdateUninstallScript.go | 2 +- .../migrations/tables/deprecated_types.go | 3 +- .../mysql/migrations/tables/migration_test.go | 4 +- server/datastore/mysql/mysql.go | 14 +-- .../datastore/mysql/operating_systems_test.go | 2 +- server/datastore/mysql/packs.go | 2 +- server/datastore/mysql/password_reset.go | 2 +- server/datastore/mysql/password_reset_test.go | 2 +- server/datastore/mysql/policies.go | 13 ++- server/datastore/mysql/policies_test.go | 10 +- server/datastore/mysql/queries.go | 2 +- server/datastore/mysql/scheduled_queries.go | 2 +- server/datastore/mysql/scripts.go | 21 ++-- server/datastore/mysql/scripts_test.go | 6 +- server/datastore/mysql/sessions.go | 4 +- server/datastore/mysql/software.go | 6 +- server/datastore/mysql/software_installers.go | 2 +- server/datastore/mysql/software_test.go | 6 +- server/datastore/mysql/software_titles.go | 2 +- server/datastore/mysql/targets.go | 6 +- server/datastore/mysql/targets_test.go | 2 +- server/datastore/mysql/teams.go | 2 +- server/datastore/mysql/users.go | 2 +- server/datastore/mysql/vpp.go | 4 +- server/datastore/mysql/vulnerabilities.go | 8 +- .../datastore/mysql/vulnerabilities_test.go | 8 +- .../datastore/mysql/windows_updates_test.go | 4 +- server/datastore/redis/redis.go | 3 +- server/fleet/hosts.go | 21 ++-- server/fleet/microsoft_mdm.go | 7 +- server/fleet/policytest/policytest.go | 2 +- server/fleet/scheduled_queries.go | 6 +- server/fleet/software.go | 3 +- server/goose/migrate.go | 2 +- server/goose/migrate_test.go | 7 +- server/goose/migration.go | 2 +- server/launcher/launcher.go | 10 +- server/logging/firehose.go | 2 +- server/logging/kinesis.go | 2 +- server/mdm/apple/itunes/api.go | 3 +- server/mdm/apple/util.go | 4 +- server/mdm/maintainedapps/scripts.go | 4 +- server/mdm/microsoft/wstep_csr.go | 20 ++-- server/mdm/microsoft/wstep_csr_test.go | 2 +- server/mdm/nanodep/cmd/depsyncer/main.go | 2 +- server/mdm/nanomdm/http/api/api.go | 7 +- server/mdm/nanomdm/mdm/type.go | 4 +- server/mdm/scep/cmd/scepserver/scepserver.go | 7 +- server/mock/mockimpl/impl.go | 2 +- server/pubsub/inmem_query_results.go | 4 +- server/pubsub/query_results_test.go | 4 +- server/service/apple_mdm.go | 6 +- server/service/async/async.go | 3 +- server/service/async/async_host_seen_test.go | 2 +- server/service/async/async_label.go | 4 +- server/service/async/async_label_test.go | 2 +- server/service/async/async_policy_test.go | 6 +- server/service/async/async_test.go | 5 +- server/service/campaigns.go | 3 +- server/service/client_policies.go | 4 +- server/service/client_queries.go | 4 +- server/service/client_sessions.go | 3 +- server/service/devices.go | 2 +- server/service/endpoint_utils.go | 6 +- server/service/hosts.go | 2 +- server/service/integration_core_test.go | 32 +++--- server/service/integration_enterprise_test.go | 94 ++++++++++------ .../service/integration_live_queries_test.go | 4 +- server/service/integration_mdm_dep_test.go | 3 +- .../service/integration_mdm_profiles_test.go | 106 ++++++++++-------- server/service/integration_mdm_test.go | 51 +++++---- server/service/jitter.go | 2 +- server/service/jitter_test.go | 4 +- server/service/live_queries.go | 5 +- server/service/maintained_apps.go | 2 +- server/service/mdm.go | 4 +- server/service/microsoft_mdm.go | 5 +- server/service/osquery.go | 38 +++---- server/service/osquery_test.go | 13 +-- server/service/osquery_utils/queries.go | 2 +- server/service/osquery_utils/queries_test.go | 15 ++- server/service/queries_test.go | 4 +- server/service/redis_lock/redis_lock_test.go | 2 +- .../redis_policy_set/redis_policy_set.go | 8 +- server/service/schedule/schedule_test.go | 2 +- server/service/schedule/testing_utils.go | 4 +- server/service/scheduled_queries.go | 2 +- server/service/service_campaigns.go | 10 +- server/service/software.go | 6 +- server/service/software_installers_test.go | 12 +- server/service/team_schedule.go | 2 +- server/service/testing_client.go | 2 +- server/service/testing_utils.go | 12 +- server/service/transport.go | 4 +- server/service/transport_error.go | 2 +- server/service/users_test.go | 2 +- server/shellquote/shellquote.go | 9 +- server/test/comparisons.go | 34 ++---- server/vulnerabilities/io/github.go | 4 +- server/vulnerabilities/io/metadata.go | 4 +- server/vulnerabilities/msrc/parsed/product.go | 46 ++++---- server/vulnerabilities/msrc/parser.go | 2 +- .../vulnerabilities/msrc/xml/vulnerability.go | 2 +- server/vulnerabilities/nvd/cpe.go | 6 +- server/vulnerabilities/nvd/cve.go | 4 +- server/vulnerabilities/nvd/sanitize.go | 24 ++-- .../nvd/tools/cvefeed/nvd/match_cpe.go | 6 +- .../nvd/tools/cvefeed/nvd/match_node.go | 12 +- server/vulnerabilities/nvd/tools/wfn/uri.go | 9 +- server/vulnerabilities/nvd/tools/wfn/wfn.go | 2 +- .../vulnerabilities/nvd/tools/wfn/wfn_test.go | 7 +- server/vulnerabilities/oval/analyzer_test.go | 2 +- .../vulnerabilities/oval/parsed/definition.go | 12 +- server/vulnerabilities/oval/parsed/utils.go | 2 +- server/vulnerabilities/oval/parser.go | 6 +- server/vulnerabilities/utils/rpmvercmp.go | 2 +- server/webhooks/failing_policies_test.go | 2 +- server/webhooks/mapper.go | 3 +- server/worker/macos_setup_assistant_test.go | 3 +- tools/calendar/calendar.go | 10 +- tools/calendar/delete-events/delete-events.go | 15 +-- tools/calendar/get-events/get-events.go | 2 +- tools/calendar/move-events/move-events.go | 15 +-- tools/calendar/stop-channel/stop-channel.go | 13 ++- tools/jira-integration/main.go | 6 +- tools/mdm/apple/appmanifest/main.go | 2 +- tools/mdm/assets/main.go | 8 +- tools/mdm/migration/jamf/main.go | 2 +- tools/mdm/migration/kandji/main.go | 5 +- tools/mdm/migration/mdmproxy/mdmproxy.go | 10 +- tools/mdm/migration/micromdm/main.go | 6 +- .../mdm/migration/micromdm/touchless/main.go | 2 +- tools/nvd/nvdvuln/nvdvuln.go | 6 +- tools/osquery-agent-options/main.go | 2 +- tools/seed_data/queries/seed_queries.go | 2 +- .../vulnerabilities/seed_vuln_data.go | 2 +- .../download-artifacts/download-artifacts.go | 11 +- tools/zendesk-integration/main.go | 6 +- 236 files changed, 877 insertions(+), 831 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 3d3e95ed2c..27aa009a5b 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -64,7 +64,7 @@ jobs: # Don't forget to update # docs/Contributing/Testing-and-local-development.md when this # version changes - go install github.com/golangci/golangci-lint/cmd/golangci-lint@e3c2265f4939976874989e159386b3bb7dcf8e1f # v1.55.2 + go install github.com/golangci/golangci-lint/cmd/golangci-lint@a1d6c560de1a193a0c68ffed68cd5928ef39e884 # v1.61.0 make lint-go - name: Run cloner-check tool diff --git a/.golangci.yml b/.golangci.yml index 2e31094f13..357557fb44 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -26,10 +26,10 @@ linters-settings: errcheck: check-type-assertions: false check-blank: false - ignore: fmt:.* disable-default-exclusions: false exclude-functions: - "(github.com/go-kit/log.Logger).Log" + - fmt:.* gosec: config: diff --git a/Makefile b/Makefile index af4a0175f6..0c689f4fd3 100644 --- a/Makefile +++ b/Makefile @@ -136,7 +136,7 @@ lint-js: yarn lint lint-go: - golangci-lint run --skip-dirs ./node_modules --timeout 15m + golangci-lint run --exclude-dirs ./node_modules --timeout 15m lint: lint-go lint-js diff --git a/cmd/fleet/cron.go b/cmd/fleet/cron.go index 90aa97d4df..877166d6d2 100644 --- a/cmd/fleet/cron.go +++ b/cmd/fleet/cron.go @@ -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 diff --git a/cmd/fleet/serve_test.go b/cmd/fleet/serve_test.go index 9763e3476d..5294e302e8 100644 --- a/cmd/fleet/serve_test.go +++ b/cmd/fleet/serve_test.go @@ -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) }) } diff --git a/cmd/fleetctl/apply_test.go b/cmd/fleetctl/apply_test.go index bd80bb8434..ba5ba641f7 100644 --- a/cmd/fleetctl/apply_test.go +++ b/cmd/fleetctl/apply_test.go @@ -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 } diff --git a/cmd/fleetctl/debug.go b/cmd/fleetctl/debug.go index 8e18d63f0f..4f1b3ea946 100644 --- a/cmd/fleetctl/debug.go +++ b/cmd/fleetctl/debug.go @@ -464,23 +464,21 @@ or provide an
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 } } diff --git a/cmd/fleetctl/debug_test.go b/cmd/fleetctl/debug_test.go index 6d26c4f497..732e6f0cd2 100644 --- a/cmd/fleetctl/debug_test.go +++ b/cmd/fleetctl/debug_test.go @@ -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 == "" { diff --git a/cmd/fleetctl/delete.go b/cmd/fleetctl/delete.go index 2173a51459..0edc063d63 100644 --- a/cmd/fleetctl/delete.go +++ b/cmd/fleetctl/delete.go @@ -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 diff --git a/cmd/fleetctl/get_test.go b/cmd/fleetctl/get_test.go index 6e3d4dcb06..41b89ea6ba 100644 --- a/cmd/fleetctl/get_test.go +++ b/cmd/fleetctl/get_test.go @@ -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, ¬FoundError{} } 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, diff --git a/cmd/fleetctl/gitops_test.go b/cmd/fleetctl/gitops_test.go index 7ec1ea83fe..22f34287b0 100644 --- a/cmd/fleetctl/gitops_test.go +++ b/cmd/fleetctl/gitops_test.go @@ -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 } diff --git a/cmd/fleetctl/login.go b/cmd/fleetctl/login.go index 3ba21d2fd5..b7c4d9a3a8 100644 --- a/cmd/fleetctl/login.go +++ b/cmd/fleetctl/login.go @@ -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 } diff --git a/cmd/fleetctl/preview.go b/cmd/fleetctl/preview.go index cddf401309..b009c0ca70 100644 --- a/cmd/fleetctl/preview.go +++ b/cmd/fleetctl/preview.go @@ -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.") } } diff --git a/cmd/fleetctl/query.go b/cmd/fleetctl/query.go index 145698e287..3c64d2c191 100644 --- a/cmd/fleetctl/query.go +++ b/cmd/fleetctl/query.go @@ -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 diff --git a/cmd/fleetctl/scripts_test.go b/cmd/fleetctl/scripts_test.go index ebc83e2f7c..8c31e6d19c 100644 --- a/cmd/fleetctl/scripts_test.go +++ b/cmd/fleetctl/scripts_test.go @@ -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}, } diff --git a/cmd/fleetctl/setup.go b/cmd/fleetctl/setup.go index 5adac9cf90..b65a61ccdc 100644 --- a/cmd/fleetctl/setup.go +++ b/cmd/fleetctl/setup.go @@ -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 } diff --git a/cmd/fleetctl/user.go b/cmd/fleetctl/user.go index ce0a842c7d..1be6393227 100644 --- a/cmd/fleetctl/user.go +++ b/cmd/fleetctl/user.go @@ -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 } } diff --git a/cmd/fleetctl/users_test.go b/cmd/fleetctl/users_test.go index c3b43a5820..342723c1f8 100644 --- a/cmd/fleetctl/users_test.go +++ b/cmd/fleetctl/users_test.go @@ -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, diff --git a/cmd/osquery-perf/agent.go b/cmd/osquery-perf/agent.go index 50df1861bf..5c73a3ce89 100644 --- a/cmd/osquery-perf/agent.go +++ b/cmd/osquery-perf/agent.go @@ -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 } } diff --git a/ee/server/calendar/google_calendar.go b/ee/server/calendar/google_calendar.go index 7abbc6c4c6..91abdcf07d 100644 --- a/ee/server/calendar/google_calendar.go +++ b/ee/server/calendar/google_calendar.go @@ -670,7 +670,7 @@ func (c *GoogleCalendar) createEvent( secondsToEventEnd := (eventEnd.Sub(now).Milliseconds() / 1000) + (7 * 24 * 60 * 60) eventUUID = strings.ToUpper(uuid.New().String()) // Standardize on uppercase UUIDs since that's how they come from DB channelID = uuid.New().String() - resourceID, err = c.config.API.Watch(eventUUID, channelID, uint64(secondsToEventEnd)) + resourceID, err = c.config.API.Watch(eventUUID, channelID, uint64(secondsToEventEnd)) //nolint:gosec // dismiss G115 if err != nil { return nil, ctxerr.Wrap(c.config.Context, err, "watching Google calendar event") } diff --git a/ee/server/calendar/load_test/calendar_http_handler.go b/ee/server/calendar/load_test/calendar_http_handler.go index e69c945523..2c81bf03a8 100644 --- a/ee/server/calendar/load_test/calendar_http_handler.go +++ b/ee/server/calendar/load_test/calendar_http_handler.go @@ -9,15 +9,16 @@ import ( "encoding/json" "errors" "fmt" - "github.com/fleetdm/fleet/v4/server/contexts/ctxerr" - _ "github.com/mattn/go-sqlite3" - "google.golang.org/api/calendar/v3" "hash/fnv" "io" "log" "net/http" "os" "time" + + "github.com/fleetdm/fleet/v4/server/contexts/ctxerr" + _ "github.com/mattn/go-sqlite3" + "google.golang.org/api/calendar/v3" ) // This calendar does not support all-day events. @@ -106,7 +107,7 @@ func getSetting(w http.ResponseWriter, r *http.Request) { // The timezone is determined by the user's email address func getTimezone(email string) string { - index := hash(email) % uint32(len(timezones)) + index := hash(email) % uint32(len(timezones)) //nolint:gosec // dismiss G115 (only used for tests) timezone := timezones[index] return timezone } diff --git a/ee/server/service/calendar.go b/ee/server/service/calendar.go index 57ac9834bc..0515486087 100644 --- a/ee/server/service/calendar.go +++ b/ee/server/service/calendar.go @@ -230,7 +230,7 @@ func (svc *Service) processCalendarEvent(ctx context.Context, eventDetails *flee if updated && event != nil { // Event was updated, so we set a flag. _, err = svc.distributedLock.SetIfNotExist(ctx, calendar.RecentUpdateKeyPrefix+event.UUID, calendar.RecentCalendarUpdateValue, - uint64(calendar.RecentCalendarUpdateDuration.Milliseconds())) + uint64(calendar.RecentCalendarUpdateDuration.Milliseconds())) //nolint:gosec // dismiss G115 if err != nil { return ctxerr.Wrap(ctx, err, "set recent update flag") } diff --git a/ee/server/service/mdm_external_test.go b/ee/server/service/mdm_external_test.go index 9522a87e51..9cb9aa46f0 100644 --- a/ee/server/service/mdm_external_test.go +++ b/ee/server/service/mdm_external_test.go @@ -296,7 +296,7 @@ func TestGetOrCreatePreassignTeam(t *testing.T) { return nil, errors.New("team name already exists") } } - id := uint(len(teamStore) + 1) + id := uint(len(teamStore) + 1) //nolint:gosec // dismiss G115 _, ok := teamStore[id] require.False(t, ok) // sanity check team.ID = id @@ -441,7 +441,8 @@ func TestGetOrCreatePreassignTeam(t *testing.T) { // a custom setup assistant setupAsstByTeam[0] = nil - preassignGrousWithFoo := append(preassignGroups, "foo") + preassignGrousWithFoo := preassignGroups + preassignGrousWithFoo = append(preassignGrousWithFoo, "foo") team, err = svc.GetOrCreatePreassignTeam(ctx, preassignGrousWithFoo) require.NoError(t, err) require.Equal(t, uint(4), team.ID) @@ -504,7 +505,7 @@ func TestGetOrCreatePreassignTeam(t *testing.T) { return nil, errors.New("team name already exists") } } - id := uint(len(teamStore) + 1) + id := uint(len(teamStore) + 1) //nolint:gosec // dismiss G115 _, ok := teamStore[id] require.False(t, ok) // sanity check require.Equal(t, "new team", team.Name) @@ -542,7 +543,7 @@ func TestGetOrCreatePreassignTeam(t *testing.T) { return nil, errors.New("team name already exists") } } - id := uint(len(teamStore) + 1) + id := uint(len(teamStore) + 1) //nolint:gosec // dismiss G115 _, ok := teamStore[id] require.False(t, ok) // sanity check require.Equal(t, "new team spec", team.Name) // set diff --git a/ee/server/service/teams_test.go b/ee/server/service/teams_test.go index 265a514c6f..6225899b46 100644 --- a/ee/server/service/teams_test.go +++ b/ee/server/service/teams_test.go @@ -13,7 +13,7 @@ func TestObfuscateSecrets(t *testing.T) { r := make([]*fleet.Team, 0, n) for i := 1; i <= n; i++ { r = append(r, &fleet.Team{ - ID: uint(i), + ID: uint(i), //nolint:gosec // dismiss G115 Secrets: []*fleet.EnrollSecret{ {Secret: "abc"}, {Secret: "123"}, diff --git a/orbit/cmd/desktop/desktop.go b/orbit/cmd/desktop/desktop.go index 89915c8f4a..f0f1a5b2cf 100644 --- a/orbit/cmd/desktop/desktop.go +++ b/orbit/cmd/desktop/desktop.go @@ -464,7 +464,7 @@ func refreshMenuItems(sum fleet.DesktopSummary, selfServiceItem *systray.MenuIte failingPolicies := 0 if sum.FailingPolicies != nil { - failingPolicies = int(*sum.FailingPolicies) + failingPolicies = int(*sum.FailingPolicies) //nolint:gosec // dismiss G115 } if failingPolicies > 0 { diff --git a/orbit/cmd/orbit/orbit.go b/orbit/cmd/orbit/orbit.go index 334d69be85..5f44a7c2ba 100644 --- a/orbit/cmd/orbit/orbit.go +++ b/orbit/cmd/orbit/orbit.go @@ -314,7 +314,7 @@ func main() { if keystore.Supported() && !c.Bool("disable-keystore") { // Check if secret is already in the keystore. secretFromKeystore, err := keystore.GetSecret() - if err != nil { + if err != nil { //nolint:gocritic // ignore ifElseChain log.Warn().Err(err).Msgf("failed to retrieve enroll secret from %v", keystore.Name()) } else if secretFromKeystore == "" { // Keystore secret not found, so we will add it to the keystore. @@ -323,7 +323,7 @@ func main() { } else { // Sanity check that the secret was added to the keystore. checkSecret, err := keystore.GetSecret() - if err != nil { + if err != nil { //nolint:gocritic // ignore ifElseChain log.Warn().Err(err).Msgf("failed to check that enroll secret was saved in %v", keystore.Name()) } else if checkSecret != secret { log.Warn().Msgf("enroll secret was not saved correctly in %v", keystore.Name()) @@ -339,7 +339,7 @@ func main() { } else { // Sanity check that the secret was updated in the keystore. checkSecret, err := keystore.GetSecret() - if err != nil { + if err != nil { //nolint:gocritic // ignore ifElseChain log.Warn().Err(err).Msgf("failed to check that enroll secret was updated in %v", keystore.Name()) } else if checkSecret != secret { log.Warn().Msgf("enroll secret was not updated correctly in %v", keystore.Name()) @@ -743,7 +743,7 @@ func main() { certPath = filepath.Join(proxyDirectory, "fleet.crt") // Write cert that proxy uses - err = os.WriteFile(certPath, []byte(insecure.ServerCert), os.ModePerm) + err = os.WriteFile(certPath, []byte(insecure.ServerCert), os.FileMode(0o644)) if err != nil { return fmt.Errorf("write server cert: %w", err) } @@ -940,11 +940,9 @@ func main() { // - `command_line_flags` (osquery startup flags) if err := orbitClient.RunConfigReceivers(); err != nil { log.Error().Msgf("failed initial config fetch: %s", err) - } else { - if orbitClient.RestartTriggered() { - log.Info().Msg("exiting after early config fetch") - return nil - } + } else if orbitClient.RestartTriggered() { + log.Info().Msg("exiting after early config fetch") + return nil } addSubsystem(&g, "config receivers", &wrapSubsystem{ diff --git a/orbit/pkg/cryptoinfo/identify_test.go b/orbit/pkg/cryptoinfo/identify_test.go index 761c5eb9fc..79226af68a 100644 --- a/orbit/pkg/cryptoinfo/identify_test.go +++ b/orbit/pkg/cryptoinfo/identify_test.go @@ -59,7 +59,7 @@ func TestIdentify(t *testing.T) { expectedSubjects: []string{"www.example.com"}, }, { - in: []string{filepath.Join("testdata", "test-enc.p12")}, //password is test123 + in: []string{filepath.Join("testdata", "test-enc.p12")}, // password is test123 password: "test123", expectedCount: 2, expectedSubjects: []string{"www.example.com"}, diff --git a/orbit/pkg/cryptoinfo/try_pem.go b/orbit/pkg/cryptoinfo/try_pem.go index 7549e4be68..f2064b4f5f 100644 --- a/orbit/pkg/cryptoinfo/try_pem.go +++ b/orbit/pkg/cryptoinfo/try_pem.go @@ -31,8 +31,7 @@ func tryPem(pemBytes []byte, _password string) ([]*KeyInfo, error) { } func expandPem(block *pem.Block) *KeyInfo { - switch block.Type { - case "CERTIFICATE": + if block.Type == "CERTIFICATE" { return NewCertificate(kiPEM).SetHeaders(block.Headers).SetData(parseCertificate(block.Bytes)) } diff --git a/orbit/pkg/dataflatten/ini.go b/orbit/pkg/dataflatten/ini.go index 023556073d..a3bea1d0d5 100644 --- a/orbit/pkg/dataflatten/ini.go +++ b/orbit/pkg/dataflatten/ini.go @@ -36,7 +36,6 @@ func flattenIni(in interface{}, opts ...FlattenOpts) ([]Row, error) { // booleans. Everything else we leave as string sectionMap := make(map[string]interface{}) for _, key := range section.Keys() { - //fmt.Println(section.Name(), key.Name(), key.Value()) asBool, ok := iniToBool(key.Value()) if ok { sectionMap[key.Name()] = asBool diff --git a/orbit/pkg/installer/installer_test.go b/orbit/pkg/installer/installer_test.go index 76d6173071..c8dd78dc2e 100644 --- a/orbit/pkg/installer/installer_test.go +++ b/orbit/pkg/installer/installer_test.go @@ -3,11 +3,11 @@ package installer import ( "context" "errors" + "fmt" "os" "os/exec" "path/filepath" "runtime" - "strconv" "strings" "testing" @@ -154,7 +154,7 @@ func TestInstallerRun(t *testing.T) { var downloadInstallerFnCalled bool downloadInstallerDefaultFn := func(installerID uint, downloadDir string) (string, error) { downloadInstallerFnCalled = true - return filepath.Join(downloadDir, strconv.Itoa(int(installerID))+".pkg"), nil + return filepath.Join(downloadDir, fmt.Sprint(installerID)+".pkg"), nil } oc.downloadInstallerFn = downloadInstallerDefaultFn @@ -294,7 +294,7 @@ func TestInstallerRun(t *testing.T) { } require.Contains(t, executedScripts, filepath.Join(tmpDir, "install-script"+scriptExtension)) require.Contains(t, executedScripts, filepath.Join(tmpDir, "post-install-script"+scriptExtension)) - require.Contains(t, execEnv, "INSTALLER_PATH="+filepath.Join(tmpDir, strconv.Itoa(int(installDetails.InstallerID))+".pkg")) + require.Contains(t, execEnv, "INSTALLER_PATH="+filepath.Join(tmpDir, fmt.Sprint(installDetails.InstallerID)+".pkg")) require.True(t, queryFnCalled) require.Equal(t, installDetails.PreInstallCondition, queryFnQuery) diff --git a/orbit/pkg/keystore/keystore_darwin.go b/orbit/pkg/keystore/keystore_darwin.go index 6364ecdcd5..1ace32c1bd 100644 --- a/orbit/pkg/keystore/keystore_darwin.go +++ b/orbit/pkg/keystore/keystore_darwin.go @@ -43,7 +43,7 @@ func AddSecret(secret string) error { C.kCFAllocatorDefault, 0, &C.kCFTypeDictionaryKeyCallBacks, - &C.kCFTypeDictionaryValueCallBacks, + &C.kCFTypeDictionaryValueCallBacks, //nolint:gocritic // dubSubExpr false positive ) defer C.CFRelease(C.CFTypeRef(query)) @@ -75,7 +75,7 @@ func UpdateSecret(secret string) error { C.kCFAllocatorDefault, 0, &C.kCFTypeDictionaryKeyCallBacks, - &C.kCFTypeDictionaryValueCallBacks, + &C.kCFTypeDictionaryValueCallBacks, //nolint:gocritic // dubSubExpr false positive ) defer C.CFRelease(C.CFTypeRef(query)) @@ -86,7 +86,7 @@ func UpdateSecret(secret string) error { C.kCFAllocatorDefault, 0, &C.kCFTypeDictionaryKeyCallBacks, - &C.kCFTypeDictionaryValueCallBacks, + &C.kCFTypeDictionaryValueCallBacks, //nolint:gocritic // dubSubExpr false positive ) defer C.CFRelease(C.CFTypeRef(update)) @@ -113,7 +113,7 @@ func GetSecret() (string, error) { C.kCFAllocatorDefault, 0, &C.kCFTypeDictionaryKeyCallBacks, - &C.kCFTypeDictionaryValueCallBacks, + &C.kCFTypeDictionaryValueCallBacks, //nolint:gocritic // dubSubExpr false positive ) defer C.CFRelease(C.CFTypeRef(query)) @@ -123,7 +123,7 @@ func GetSecret() (string, error) { C.CFDictionaryAddValue(query, unsafe.Pointer(C.kSecAttrLabel), unsafe.Pointer(serviceStringRef)) var data C.CFTypeRef - status := C.SecItemCopyMatching(C.CFDictionaryRef(query), &data) + status := C.SecItemCopyMatching(C.CFDictionaryRef(query), &data) //nolint:gocritic // dubSubExpr false positive if status != C.errSecSuccess { if status == C.errSecItemNotFound { return "", nil @@ -146,7 +146,7 @@ func deleteSecret() error { C.kCFAllocatorDefault, 0, &C.kCFTypeDictionaryKeyCallBacks, - &C.kCFTypeDictionaryValueCallBacks, + &C.kCFTypeDictionaryValueCallBacks, //nolint:gocritic // dubSubExpr false positive ) defer C.CFRelease(C.CFTypeRef(query)) diff --git a/orbit/pkg/scripts/exec_nonwindows_test.go b/orbit/pkg/scripts/exec_nonwindows_test.go index 360efea855..a7997ebc85 100644 --- a/orbit/pkg/scripts/exec_nonwindows_test.go +++ b/orbit/pkg/scripts/exec_nonwindows_test.go @@ -70,7 +70,7 @@ func TestExecCmdNonWindows(t *testing.T) { } scriptPath := strings.ReplaceAll(tc.name, " ", "_") + ".sh" scriptPath = filepath.Join(tmpDir, scriptPath) - err := os.WriteFile(scriptPath, []byte(tc.contents), os.ModePerm) + err := os.WriteFile(scriptPath, []byte(tc.contents), os.ModePerm) //nolint:gosec // ignore non-standard permissions require.NoError(t, err) output, exitCode, err := ExecCmd(context.Background(), scriptPath, nil) diff --git a/orbit/pkg/scripts/scripts_test.go b/orbit/pkg/scripts/scripts_test.go index fa3a5cea3d..19c8ca2421 100644 --- a/orbit/pkg/scripts/scripts_test.go +++ b/orbit/pkg/scripts/scripts_test.go @@ -305,7 +305,7 @@ func TestRunnerResults(t *testing.T) { output: output44K, exitCode: 1, runErr: nil, - wantOutput: output44K[strings.Index(output44K, "b"):], + wantOutput: output44K[strings.Index(output44K, "b"):], //nolint:gocritic // ignore offBy1 since this is a test }, { desc: "empty with error", diff --git a/orbit/pkg/table/app-icons/app_icons_darwin.go b/orbit/pkg/table/app-icons/app_icons_darwin.go index a612e754a0..245816659b 100644 --- a/orbit/pkg/table/app-icons/app_icons_darwin.go +++ b/orbit/pkg/table/app-icons/app_icons_darwin.go @@ -80,7 +80,7 @@ func generateAppIcons(ctx context.Context, queryContext table.QueryContext) ([]m func getAppIcon(appPath string, queryContext table.QueryContext) (image.Image, uint64, error) { var data C.CFDataRef - C.Icon(&data, C.CString(appPath)) + C.Icon(&data, C.CString(appPath)) //nolint:gocritic // ignore dubSubExpr defer C.CFRelease(C.CFTypeRef(data)) tiffBytes := C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(data)), C.int(C.CFDataGetLength(data))) diff --git a/orbit/pkg/table/csrutil_info/csrutil_info.go b/orbit/pkg/table/csrutil_info/csrutil_info.go index cd53ba1a78..d4c903f962 100644 --- a/orbit/pkg/table/csrutil_info/csrutil_info.go +++ b/orbit/pkg/table/csrutil_info/csrutil_info.go @@ -5,11 +5,12 @@ package csrutil_info import ( "context" - "github.com/osquery/osquery-go/plugin/table" - "github.com/rs/zerolog/log" "os/exec" "strings" "time" + + "github.com/osquery/osquery-go/plugin/table" + "github.com/rs/zerolog/log" ) // Columns is the schema of the table. @@ -28,16 +29,16 @@ func Generate(ctx context.Context, queryContext table.QueryContext) ([]map[strin }, err } -func getSSVEnabled(ctx context.Context) (SSVEnabled string, err error) { +func getSSVEnabled(ctx context.Context) (ssvEnabled string, err error) { res, err := runCommand(ctx, "/usr/bin/csrutil", "authenticated-root", "status") - SSVEnabled = "" + ssvEnabled = "" if err == nil { - SSVEnabled = "0" + ssvEnabled = "0" if strings.Contains(res, "Authenticated Root status: enabled") { - SSVEnabled = "1" + ssvEnabled = "1" } } - return SSVEnabled, err + return ssvEnabled, err } func runCommand(ctx context.Context, name string, arg ...string) (res string, err error) { diff --git a/orbit/pkg/table/firmwarepasswd/firmwarepasswd.go b/orbit/pkg/table/firmwarepasswd/firmwarepasswd.go index 05496e27d2..b11b27f6cf 100644 --- a/orbit/pkg/table/firmwarepasswd/firmwarepasswd.go +++ b/orbit/pkg/table/firmwarepasswd/firmwarepasswd.go @@ -41,17 +41,17 @@ func New(logger zerolog.Logger) *Table { { Match: func(in string) bool { return strings.HasPrefix(in, "Password Enabled: ") }, KeyFunc: func(_ string) (string, error) { return "password_enabled", nil }, - ValFunc: func(in string) (string, error) { return passwordValue(in) }, + ValFunc: passwordValue, }, { Match: func(in string) bool { return strings.HasPrefix(in, "Mode: ") }, KeyFunc: func(_ string) (string, error) { return "mode", nil }, - ValFunc: func(in string) (string, error) { return modeValue(in) }, + ValFunc: modeValue, }, { Match: func(in string) bool { return strings.HasPrefix(in, "Option roms ") }, KeyFunc: func(_ string) (string, error) { return "option_roms_allowed", nil }, - ValFunc: func(in string) (string, error) { return optionRomValue(in) }, + ValFunc: optionRomValue, }, }) diff --git a/orbit/pkg/table/fleetd_logs/fleetd_logs.go b/orbit/pkg/table/fleetd_logs/fleetd_logs.go index cdb5a84f69..6b70945ef1 100644 --- a/orbit/pkg/table/fleetd_logs/fleetd_logs.go +++ b/orbit/pkg/table/fleetd_logs/fleetd_logs.go @@ -19,7 +19,7 @@ import ( const timeFormatString = "2006-01-02 15:04:05.999999999" var Logger = logger{} -var MaxEntries uint = 10_000 +var maxEntries = 10_000 func TablePlugin() *table.Plugin { columns := []table.ColumnDefinition{ @@ -74,8 +74,8 @@ func (l *logger) Write(event []byte) (int, error) { l.logs = append(l.logs, msgs...) - if MaxEntries > 0 && len(l.logs) > int(MaxEntries) { - l.logs = l.logs[len(l.logs)-int(MaxEntries):] + if maxEntries > 0 && len(l.logs) > maxEntries { + l.logs = l.logs[len(l.logs)-maxEntries:] } return len(event), nil @@ -96,8 +96,8 @@ func (l *logger) WriteLevel(level zerolog.Level, event []byte) (int, error) { l.logs = append(l.logs, msgs...) - if MaxEntries > 0 && len(l.logs) > int(MaxEntries) { - l.logs = l.logs[len(l.logs)-int(MaxEntries):] + if maxEntries > 0 && len(l.logs) > maxEntries { + l.logs = l.logs[len(l.logs)-maxEntries:] } return len(event), nil diff --git a/orbit/pkg/table/tcc_access/tcc_access.go b/orbit/pkg/table/tcc_access/tcc_access.go index e5f83f7a66..57f270bb78 100644 --- a/orbit/pkg/table/tcc_access/tcc_access.go +++ b/orbit/pkg/table/tcc_access/tcc_access.go @@ -129,7 +129,7 @@ func getTCCAccessRows(uid, tccPath string) ([]map[string]string, error) { func parseTCCDbReadOutput(dbOut []byte) [][]string { // split by newLine for rows, then by "|" for columns - rawRows := strings.Split(string(dbOut[:]), "\n") + rawRows := strings.Split(string(dbOut), "\n") n := len(rawRows) if n == 0 { return nil @@ -202,7 +202,7 @@ func getUsersInfo() ([][]string, error) { if err != nil { return nil, err } - usersInfo := strings.Split(string(out[:]), "\n") + usersInfo := strings.Split(string(out), "\n") for _, userInfo := range usersInfo { if len(userInfo) > 0 { split := strings.Fields(userInfo) diff --git a/orbit/pkg/table/tcc_access/tcc_access_test.go b/orbit/pkg/table/tcc_access/tcc_access_test.go index adc2b98025..a627e6b64d 100644 --- a/orbit/pkg/table/tcc_access/tcc_access_test.go +++ b/orbit/pkg/table/tcc_access/tcc_access_test.go @@ -29,11 +29,12 @@ func TestGenerate(t *testing.T) { // Check "uid" of the returned rows match the entries in the TCC files. for _, row := range rows { - if strings.HasPrefix(row["service"], "test-sys-service-") { + switch { + case strings.HasPrefix(row["service"], "test-sys-service-"): require.Equal(t, "0", row["uid"]) - } else if strings.HasPrefix(row["service"], "test-u1-service-") { + case strings.HasPrefix(row["service"], "test-u1-service-"): require.Equal(t, "1", row["uid"]) - } else if strings.HasPrefix(row["service"], "test-u2-service-") { + case strings.HasPrefix(row["service"], "test-u2-service-"): require.Equal(t, "2", row["uid"]) } } diff --git a/orbit/pkg/update/filestore/filestore.go b/orbit/pkg/update/filestore/filestore.go index 7b93a4d24a..20e434d69d 100644 --- a/orbit/pkg/update/filestore/filestore.go +++ b/orbit/pkg/update/filestore/filestore.go @@ -77,13 +77,14 @@ func (s *fileStore) Close() error { func (s *fileStore) readData() error { stat, err := os.Stat(s.filename) - if err != nil && !errors.Is(err, os.ErrNotExist) { + switch { + case err != nil && !errors.Is(err, os.ErrNotExist): return fmt.Errorf("stat file store: %w", err) - } else if errors.Is(err, os.ErrNotExist) { + case errors.Is(err, os.ErrNotExist): // initialize empty s.metadata = metadataMap{} return nil - } else if !stat.Mode().IsRegular() { + case !stat.Mode().IsRegular(): return errors.New("expected file store to be regular file") } diff --git a/orbit/pkg/update/flag_runner.go b/orbit/pkg/update/flag_runner.go index f8b3db8bf1..b03a5deb40 100644 --- a/orbit/pkg/update/flag_runner.go +++ b/orbit/pkg/update/flag_runner.go @@ -164,7 +164,7 @@ func (r *ExtensionRunner) Run(config *fleet.OrbitConfig) error { // All Windows executables must end with `.exe`. if runtime.GOOS == "windows" { - filename = filename + ".exe" + filename += ".exe" } // we don't want path traversal and the like in the filename diff --git a/orbit/pkg/update/nudge_test.go b/orbit/pkg/update/nudge_test.go index 987e9dd44a..5c8dd88519 100644 --- a/orbit/pkg/update/nudge_test.go +++ b/orbit/pkg/update/nudge_test.go @@ -278,11 +278,11 @@ func TestHelperProcess(t *testing.T) { os.Exit(1) return } - fmt.Fprintf(os.Stdout, os.Getenv("GO_WANT_HELPER_PROCESS_STDOUT")) + fmt.Fprint(os.Stdout, os.Getenv("GO_WANT_HELPER_PROCESS_STDOUT")) err := os.Getenv("GO_WANT_HELPER_PROCESS_STDERR") if err != "" { - fmt.Fprintf(os.Stderr, err) + fmt.Fprint(os.Stderr, err) os.Exit(1) } diff --git a/orbit/pkg/update/runner.go b/orbit/pkg/update/runner.go index 361d69278b..f618eb077a 100644 --- a/orbit/pkg/update/runner.go +++ b/orbit/pkg/update/runner.go @@ -173,7 +173,7 @@ func (r *Runner) Execute() error { if err != nil { log.Info().Err(err).Msg("randomization of initial update interval failed") } else { - initialInterval = initialInterval + randomizedInterval + initialInterval += randomizedInterval } ticker := time.NewTicker(initialInterval) diff --git a/orbit/pkg/useraction/mdm_migration_darwin.go b/orbit/pkg/useraction/mdm_migration_darwin.go index e4daeab997..d835dad2d6 100644 --- a/orbit/pkg/useraction/mdm_migration_darwin.go +++ b/orbit/pkg/useraction/mdm_migration_darwin.go @@ -276,7 +276,7 @@ func (m *swiftDialogMDMMigrator) render(message string, flags ...string) (chan s func (m *swiftDialogMDMMigrator) renderLoadingSpinner(preSonoma, isManual bool) (chan swiftDialogExitCode, chan error) { var body string - switch true { + switch { case preSonoma: body = fmt.Sprintf(unenrollBody, "![Image showing MDM migration notification](https://fleetdm.com/images/permanent/mdm-migration-pre-sonoma-unenroll-1024x500.png)") case isManual: @@ -322,27 +322,26 @@ func (m *swiftDialogMDMMigrator) waitForUnenrollment(isADEMigration bool) error } checkStatusFn := m.testEnrollmentCheckStatusFn if checkStatusFn == nil { - checkStatusFn = func() (bool, string, error) { - return profiles.IsEnrolledInMDM() - } + checkStatusFn = profiles.IsEnrolledInMDM } return retry.Do(func() error { var unenrolled bool if isADEMigration { fileExists, fileErr := checkFileFn() - if fileErr != nil { + switch { + case fileErr != nil: log.Error().Err(fileErr).Msg("checking for existence of cloudConfigProfileInstalled in migration modal") - } else if fileExists { + case fileExists: log.Info().Msg("checking for existence of cloudConfigProfileInstalled in migration modal: found") - } else { + default: log.Info().Msg("checking for existence of cloudConfigProfileInstalled in migration modal: not found") unenrolled = true } } statusEnrolled, serverURL, statusErr := checkStatusFn() - if statusErr != nil { + if statusErr != nil { //nolint:gocritic // ignore ifElseChain log.Error().Err(statusErr).Msgf("checking profiles status in migration modal") } else if statusEnrolled { log.Info().Msgf("checking profiles status in migration modal: enrolled to %s", serverURL) diff --git a/orbit/tools/build/build-windows.go b/orbit/tools/build/build-windows.go index f695f7e490..7b77760c18 100644 --- a/orbit/tools/build/build-windows.go +++ b/orbit/tools/build/build-windows.go @@ -66,7 +66,7 @@ func main() { vi, err := createVersionInfo(vParts, targetIconPath, manifestPath) if err != nil { zlog.Fatal().Err(err).Msg("parsing versioninfo") - os.Exit(1) + os.Exit(1) //nolint:gocritic // ignore exitAfterDefer } // and finally we can write the 'resource.syso' file diff --git a/pkg/buildpkg/buildpkg.go b/pkg/buildpkg/buildpkg.go index 95ac0d598f..18f9f3d9b6 100644 --- a/pkg/buildpkg/buildpkg.go +++ b/pkg/buildpkg/buildpkg.go @@ -77,20 +77,20 @@ func MakeMacOSFatExecutable(outPath string, inPaths ...string) error { } else { hdr = append(hdr, macho.MagicFat) } - hdr = append(hdr, uint32(len(inputs))) + hdr = append(hdr, uint32(len(inputs))) //nolint:gosec // dismiss G115 // Build a fat_arch for each input file. for _, i := range inputs { hdr = append(hdr, i.cpu) hdr = append(hdr, i.subcpu) if sixtyfour { - hdr = append(hdr, uint32(i.offset>>32)) // big endian + hdr = append(hdr, uint32(i.offset>>32)) //nolint:gosec // dismiss G115, big endian } - hdr = append(hdr, uint32(i.offset)) + hdr = append(hdr, uint32(i.offset)) //nolint:gosec // dismiss G115 if sixtyfour { - hdr = append(hdr, uint32(len(i.data)>>32)) // big endian + hdr = append(hdr, uint32(len(i.data)>>32)) //nolint:gosec // dismiss G115, big endian } - hdr = append(hdr, uint32(len(i.data))) + hdr = append(hdr, uint32(len(i.data))) //nolint:gosec // dismiss G115 hdr = append(hdr, alignBits) if sixtyfour { hdr = append(hdr, 0) // reserved diff --git a/pkg/download/download_test.go b/pkg/download/download_test.go index 9b5bf19014..ff179e4162 100644 --- a/pkg/download/download_test.go +++ b/pkg/download/download_test.go @@ -13,7 +13,7 @@ import ( func TestDownloadNotFoundNoRetries(t *testing.T) { c := fleethttp.NewClient() tmpDir := t.TempDir() - outputFile := filepath.Join(tmpDir) + outputFile := filepath.Join(tmpDir, "not-used") url, err := url.Parse("https://github.com/fleetdm/non-existent") require.NoError(t, err) start := time.Now() diff --git a/pkg/file/file_test.go b/pkg/file/file_test.go index 73d1ad5573..7e520c41db 100644 --- a/pkg/file/file_test.go +++ b/pkg/file/file_test.go @@ -22,7 +22,7 @@ func TestCopy(t *testing.T) { dstPath := filepath.Join(tmp, "copy") expectedContents := []byte("foo") expectedMode := fs.FileMode(0644) - require.NoError(t, os.WriteFile(originalPath, expectedContents, os.ModePerm)) + require.NoError(t, os.WriteFile(originalPath, expectedContents, os.ModePerm)) //nolint:gosec // allow write file with 0o777 require.NoError(t, os.WriteFile(dstPath, []byte("this should be overwritten"), expectedMode)) // Test @@ -76,7 +76,7 @@ func TestExists(t *testing.T) { // Setup path := filepath.Join(tmp, "file") - require.NoError(t, os.WriteFile(path, []byte(""), os.ModePerm)) + require.NoError(t, os.WriteFile(path, []byte(""), os.ModePerm)) //nolint:gosec // allow write file with 0o777 require.NoError(t, os.MkdirAll(filepath.Join(tmp, "dir", "nested"), os.ModePerm)) // Test diff --git a/pkg/file/msi.go b/pkg/file/msi.go index 2568261e64..78ac33f86d 100644 --- a/pkg/file/msi.go +++ b/pkg/file/msi.go @@ -252,15 +252,16 @@ func decodeStrings(dataReader, poolReader io.Reader) ([]string, error) { func msiDecodeName(msiName string) string { out := "" for _, x := range msiName { - if x >= 0x3800 && x < 0x4800 { + switch { + case x >= 0x3800 && x < 0x4800: x -= 0x3800 out += string(msiDecodeRune(x&0x3f)) + string(msiDecodeRune(x>>6)) - } else if x >= 0x4800 && x < 0x4840 { + case x >= 0x4800 && x < 0x4840: x -= 0x4800 out += string(msiDecodeRune(x)) - } else if x == 0x4840 { + case x == 0x4840: out += "Table." - } else { + default: out += string(x) } } @@ -268,7 +269,7 @@ func msiDecodeName(msiName string) string { } func msiDecodeRune(x rune) rune { - if x < 10 { + if x < 10 { //nolint:gocritic // ignore ifElseChain return x + '0' } else if x < 10+26 { return x - 10 + 'A' diff --git a/pkg/rawjson/rawjson.go b/pkg/rawjson/rawjson.go index d6bb2189a8..56b599a6ef 100644 --- a/pkg/rawjson/rawjson.go +++ b/pkg/rawjson/rawjson.go @@ -32,7 +32,8 @@ func CombineRoots(a, b json.RawMessage) (json.RawMessage, error) { } // remove '}' from the first object and add a trailing ',' - combined := append(a[:len(a)-1], ',') + combined := a[:len(a)-1] + combined = append(combined, ',') // remove '{' from the second object and combine the two combined = append(combined, b[1:]...) return combined, nil diff --git a/pkg/secure/secure.go b/pkg/secure/secure.go index 33a52f4f47..f89db0efd5 100644 --- a/pkg/secure/secure.go +++ b/pkg/secure/secure.go @@ -22,7 +22,7 @@ func isMorePermissive(currentMode, newMode os.FileMode) bool { func checkPermPath(path string, perm os.FileMode) error { if !perm.IsDir() { - perm = perm ^ os.ModeDir + perm ^= os.ModeDir } dir, err := os.Stat(path) diff --git a/pkg/spec/gitops.go b/pkg/spec/gitops.go index 2706271e4b..f7aefa97d1 100644 --- a/pkg/spec/gitops.go +++ b/pkg/spec/gitops.go @@ -141,13 +141,14 @@ func GitOpsFromFile(filePath, baseDir string, appConfig *fleet.EnrichedAppConfig teamRaw, teamOk := top["name"] teamSettingsRaw, teamSettingsOk := top["team_settings"] orgSettingsRaw, orgOk := top["org_settings"] - if orgOk { + switch { + case orgOk: if teamOk || teamSettingsOk { multiError = multierror.Append(multiError, errors.New("'org_settings' cannot be used with 'name', 'team_settings'")) } else { multiError = parseOrgSettings(orgSettingsRaw, result, baseDir, multiError) } - } else if teamOk { + case teamOk: multiError = parseName(teamRaw, result, multiError) if result.IsNoTeam() { if teamSettingsOk { @@ -163,7 +164,7 @@ func GitOpsFromFile(filePath, baseDir string, appConfig *fleet.EnrichedAppConfig multiError = parseTeamSettings(teamSettingsRaw, result, baseDir, multiError) } } - } else { + default: multiError = multierror.Append(multiError, errors.New("either 'org_settings' or 'name' and 'team_settings' is required")) } diff --git a/server/config/config.go b/server/config/config.go index 5f6a9164eb..5f3386a571 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -1657,12 +1657,12 @@ func (man Manager) IsSet(key string) bool { // envNameFromConfigKey converts a config key into the corresponding // environment variable name func envNameFromConfigKey(key string) string { - return envPrefix + "_" + strings.ToUpper(strings.Replace(key, ".", "_", -1)) + return envPrefix + "_" + strings.ToUpper(strings.ReplaceAll(key, ".", "_")) } // flagNameFromConfigKey converts a config key into the corresponding flag name func flagNameFromConfigKey(key string) string { - return strings.Replace(key, ".", "_", -1) + return strings.ReplaceAll(key, ".", "_") } // Manager manages the addition and retrieval of config values for Fleet diff --git a/server/contexts/ctxerr/stack_test.go b/server/contexts/ctxerr/stack_test.go index ed65f774f5..9694a11f72 100644 --- a/server/contexts/ctxerr/stack_test.go +++ b/server/contexts/ctxerr/stack_test.go @@ -205,7 +205,9 @@ func TestElasticStack(t *testing.T) { // the culprit should be the function name of the top of the stack of the // cause error. - fnName := strings.TrimSpace(c.causeStackContains[0][strings.Index(c.causeStackContains[0], "TestElasticStack"):]) + fnIndex := strings.Index(c.causeStackContains[0], "TestElasticStack") + require.GreaterOrEqual(t, fnIndex, 0) + fnName := strings.TrimSpace(c.causeStackContains[0][fnIndex:]) require.Equal(t, fnName, apmErr.Culprit) // the APM stack should match the cause stack (i.e. APM should have diff --git a/server/cron/calendar_cron_test.go b/server/cron/calendar_cron_test.go index 3e780ee515..3ac3cdbe2e 100644 --- a/server/cron/calendar_cron_test.go +++ b/server/cron/calendar_cron_test.go @@ -356,7 +356,7 @@ func TestCalendarEventsMultipleHosts(t *testing.T) { require.NotZero(t, endTime) eventsMu.Lock() - calendarEventID := uint(len(calendarEvents) + 1) + calendarEventID := uint(len(calendarEvents) + 1) //nolint:gosec // dismiss G115 calendarEvents[email] = &fleet.CalendarEvent{ ID: calendarEventID, Email: email, @@ -364,7 +364,7 @@ func TestCalendarEventsMultipleHosts(t *testing.T) { EndTime: endTime, Data: data, } - hostCalendarEventID := uint(len(hostCalendarEvents) + 1) + hostCalendarEventID := uint(len(hostCalendarEvents) + 1) //nolint:gosec // dismiss G115 hostCalendarEvents[hostID] = &fleet.HostCalendarEvent{ ID: hostCalendarEventID, HostID: hostID, @@ -572,7 +572,7 @@ func TestCalendarEvents1KHosts(t *testing.T) { newHost := fleet.HostPolicyMembershipData{ Email: fmt.Sprintf("user%d@example.com", i), Passing: i%2 == 0, - HostID: uint(i), + HostID: uint(i), //nolint:gosec // dismiss G115 HostDisplayName: fmt.Sprintf("display_name%d", i), HostHardwareSerial: fmt.Sprintf("serial%d", i), } @@ -680,7 +680,7 @@ func TestCalendarEvents1KHosts(t *testing.T) { hosts = append(hosts, fleet.HostPolicyMembershipData{ Email: fmt.Sprintf("user%d@example.com", i), Passing: true, - HostID: uint(i), + HostID: uint(i), //nolint:gosec // dismiss G115 HostDisplayName: fmt.Sprintf("display_name%d", i), HostHardwareSerial: fmt.Sprintf("serial%d", i), }) @@ -692,13 +692,13 @@ func TestCalendarEvents1KHosts(t *testing.T) { if hostID%2 == 0 { return nil, nil, notFoundErr{} } - require.Contains(t, eventPerHost, uint(hostID)) + require.Contains(t, eventPerHost, uint(hostID)) //nolint:gosec // dismiss G115 return &fleet.HostCalendarEvent{ - ID: uint(hostID), - HostID: uint(hostID), - CalendarEventID: uint(hostID), + ID: uint(hostID), //nolint:gosec // dismiss G115 + HostID: uint(hostID), //nolint:gosec // dismiss G115 + CalendarEventID: uint(hostID), //nolint:gosec // dismiss G115 WebhookStatus: fleet.CalendarWebhookStatusNone, - }, eventPerHost[uint(hostID)], nil + }, eventPerHost[uint(hostID)], nil //nolint:gosec // dismiss G115 } ds.DeleteCalendarEventFunc = func(ctx context.Context, calendarEventID uint) error { @@ -935,7 +935,7 @@ func TestEventBody(t *testing.T) { require.NotZero(t, endTime) eventsMu.Lock() - calendarEventID := uint(len(calendarEvents) + 1) + calendarEventID := uint(len(calendarEvents) + 1) //nolint:gosec // dismiss G115 calendarEvents[hostID] = &fleet.CalendarEvent{ ID: calendarEventID, Email: email, @@ -943,7 +943,7 @@ func TestEventBody(t *testing.T) { EndTime: endTime, Data: data, } - hostCalendarEventID := uint(len(hostCalendarEvents) + 1) + hostCalendarEventID := uint(len(hostCalendarEvents) + 1) //nolint:gosec // dismiss G115 hostCalendarEvents[hostID] = &fleet.HostCalendarEvent{ ID: hostCalendarEventID, HostID: hostID, diff --git a/server/datastore/cached_mysql/cached_mysql_test.go b/server/datastore/cached_mysql/cached_mysql_test.go index bb41f514c6..81c5f23fe0 100644 --- a/server/datastore/cached_mysql/cached_mysql_test.go +++ b/server/datastore/cached_mysql/cached_mysql_test.go @@ -70,8 +70,7 @@ func TestClone(t *testing.T) { // ensure that writing to src does not alter the cloned value (i.e. that // the nested fields are deeply cloned too). - switch src := tc.src.(type) { - case *fleet.AppConfig: + if src, ok := tc.src.(*fleet.AppConfig); ok { if len(src.ServerSettings.DebugHostIDs) > 0 { src.ServerSettings.DebugHostIDs[0] = 999 require.NotEqual(t, src.ServerSettings.DebugHostIDs, clone.(*fleet.AppConfig).ServerSettings.DebugHostIDs) diff --git a/server/datastore/mysql/activities.go b/server/datastore/mysql/activities.go index a2bdd5eff9..4dd605f2ec 100644 --- a/server/datastore/mysql/activities.go +++ b/server/datastore/mysql/activities.go @@ -218,7 +218,7 @@ func (ds *Datastore) ListActivities(ctx context.Context, opt fleet.ListActivitie var metaData *fleet.PaginationMetadata if opt.ListOptions.IncludeMetadata { metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0} - if len(activities) > int(opt.ListOptions.PerPage) { + if len(activities) > int(opt.ListOptions.PerPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true activities = activities[:len(activities)-1] } @@ -483,7 +483,7 @@ WHERE var metaData *fleet.PaginationMetadata metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0, TotalResults: count} - if len(activities) > int(opt.PerPage) { + if len(activities) > int(opt.PerPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true activities = activities[:len(activities)-1] } @@ -523,7 +523,7 @@ func (ds *Datastore) ListHostPastActivities(ctx context.Context, hostID uint, op var metaData *fleet.PaginationMetadata if opt.IncludeMetadata { metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0} - if len(activities) > int(opt.PerPage) { + if len(activities) > int(opt.PerPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true activities = activities[:len(activities)-1] } diff --git a/server/datastore/mysql/aggregated_stats.go b/server/datastore/mysql/aggregated_stats.go index 0ba22ce21f..21ffb74532 100644 --- a/server/datastore/mysql/aggregated_stats.go +++ b/server/datastore/mysql/aggregated_stats.go @@ -49,7 +49,7 @@ const ( ) func getPercentileQuery(aggregate fleet.AggregatedStatsType, time string, percentile string) string { - switch aggregate { + switch aggregate { //nolint:gocritic // ignore singleCaseSwitch case fleet.AggregatedStatsTypeScheduledQuery: return fmt.Sprintf(scheduledQueryPercentileQuery, time, percentile) } @@ -140,7 +140,7 @@ func (ds *Datastore) CalculateAggregatedPerfStatsPercentiles(ctx context.Context } func getTotalExecutionsQuery(aggregate fleet.AggregatedStatsType) string { - switch aggregate { + switch aggregate { //nolint:gocritic // ignore singleCaseSwitch case fleet.AggregatedStatsTypeScheduledQuery: return scheduledQueryTotalExecutions } diff --git a/server/datastore/mysql/app_configs.go b/server/datastore/mysql/app_configs.go index 298d81738c..be9d0c427a 100644 --- a/server/datastore/mysql/app_configs.go +++ b/server/datastore/mysql/app_configs.go @@ -135,7 +135,7 @@ func (ds *Datastore) IsEnrollSecretAvailable(ctx context.Context, secret string, return false, nil } // Secret is in use, but we're checking if it's already assigned to the team - if (teamID == nil && !secretTeamID.Valid) || (teamID != nil && secretTeamID.Valid && uint(secretTeamID.Int64) == *teamID) { + if (teamID == nil && !secretTeamID.Valid) || (teamID != nil && secretTeamID.Valid && uint(secretTeamID.Int64) == *teamID) { //nolint:gosec // dismiss G115 return true, nil } diff --git a/server/datastore/mysql/apple_mdm.go b/server/datastore/mysql/apple_mdm.go index 06497f1517..38fed9ff92 100644 --- a/server/datastore/mysql/apple_mdm.go +++ b/server/datastore/mysql/apple_mdm.go @@ -101,7 +101,7 @@ INSERT INTO return &fleet.MDMAppleConfigProfile{ ProfileUUID: profUUID, - ProfileID: uint(profileID), + ProfileID: uint(profileID), //nolint:gosec // dismiss G115 Identifier: cp.Identifier, Name: cp.Name, Mobileconfig: cp.Mobileconfig, @@ -511,7 +511,7 @@ ON DUPLICATE KEY UPDATE } id, _ := res.LastInsertId() return &fleet.MDMAppleEnrollmentProfile{ - ID: uint(id), + ID: uint(id), //nolint:gosec // dismiss G115 Token: payload.Token, Type: payload.Type, DEPProfile: payload.DEPProfile, @@ -683,7 +683,7 @@ func (ds *Datastore) NewMDMAppleInstaller(ctx context.Context, name string, size } id, _ := res.LastInsertId() return &fleet.MDMAppleInstaller{ - ID: uint(id), + ID: uint(id), //nolint:gosec // dismiss G115 Size: size, Name: name, Manifest: manifest, @@ -4335,7 +4335,8 @@ func batchSetDeclarationLabelAssociationsDB(ctx context.Context, tx sqlx.ExtCont for k := range setProfileUUIDs { profUUIDs = append(profUUIDs, k) } - deleteArgs := append(deleteParams, profUUIDs) + deleteArgs := deleteParams + deleteArgs = append(deleteArgs, profUUIDs) deleteStmt, args, err := sqlx.In(deleteStmt, deleteArgs...) if err != nil { @@ -5069,7 +5070,7 @@ VALUES (?, ?, ?, ?, ?, ?, ?, ?) tokenID, _ := res.LastInsertId() - tok.ID = uint(tokenID) + tok.ID = uint(tokenID) //nolint:gosec // dismiss G115 cfg, err := ds.AppConfig(ctx) if err != nil { diff --git a/server/datastore/mysql/apple_mdm_test.go b/server/datastore/mysql/apple_mdm_test.go index 5a74e0b595..7c4f58661e 100644 --- a/server/datastore/mysql/apple_mdm_test.go +++ b/server/datastore/mysql/apple_mdm_test.go @@ -1928,7 +1928,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err := ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)), res.Pending) + require.EqualValues(t, len(hosts), res.Pending) require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -1938,7 +1938,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)), res.Pending) // still pending because filevault not installed + require.EqualValues(t, len(hosts), res.Pending) // still pending because filevault not installed require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -1948,7 +1948,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)), res.Pending) // still pending because filevault not installed + require.EqualValues(t, len(hosts), res.Pending) // still pending because filevault not installed require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -1958,7 +1958,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)), res.Pending) // still pending because filevault pending + require.EqualValues(t, len(hosts), res.Pending) // still pending because filevault pending require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -1967,7 +1967,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)), res.Pending) // still pending because no disk encryption key + require.EqualValues(t, len(hosts), res.Pending) // still pending because no disk encryption key require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -1978,7 +1978,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) require.NoError(t, err) require.NotNil(t, res) // hosts still pending because disk encryption key decryptable is not set - require.Equal(t, uint(len(hosts)-1), res.Pending) + require.EqualValues(t, len(hosts)-1, res.Pending) require.Equal(t, uint(0), res.Failed) // one host is verifying because the disk is encrypted and we're verifying the key require.Equal(t, uint(1), res.Verifying) @@ -1989,7 +1989,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)), res.Pending) // still pending because disk encryption key decryptable is false + require.EqualValues(t, len(hosts), res.Pending) // still pending because disk encryption key decryptable is false require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -1999,7 +1999,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-1), res.Pending) + require.EqualValues(t, len(hosts)-1, res.Pending) require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(1), res.Verifying) // hosts[0] now has filevault fully enforced but not verified require.Equal(t, uint(0), res.Verified) @@ -2009,7 +2009,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-1), res.Pending) + require.EqualValues(t, len(hosts)-1, res.Pending) require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(1), res.Verified) // hosts[0] now has filevault fully enforced and verified @@ -2021,7 +2021,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-1), res.Pending) // hosts[1] still pending because disk encryption key decryptable is false + require.EqualValues(t, len(hosts)-1, res.Pending) // hosts[1] still pending because disk encryption key decryptable is false require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(1), res.Verified) @@ -2031,7 +2031,7 @@ func testAggregateMacOSSettingsStatusWithFileVault(t *testing.T, ds *Datastore) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-2), res.Pending) + require.EqualValues(t, len(hosts)-2, res.Pending) require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(1), res.Verifying) // hosts[1] now has filevault fully enforced require.Equal(t, uint(1), res.Verified) @@ -2202,7 +2202,7 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { res, err := ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)), res.Pending) // each host only counts once + require.EqualValues(t, len(hosts), res.Pending) // each host only counts once require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -2220,7 +2220,7 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)), res.Pending) // each host only counts once + require.EqualValues(t, len(hosts), res.Pending) // each host only counts once require.Equal(t, uint(0), res.Failed) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -2246,7 +2246,7 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) // get summary for profiles with no team require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-2), res.Pending) // two hosts are failing at least one profile (hosts[0] and hosts[1]) + require.EqualValues(t, len(hosts)-2, res.Pending) // two hosts are failing at least one profile (hosts[0] and hosts[1]) require.Equal(t, uint(2), res.Failed) // only count one failure per host (hosts[0] failed two profiles but only counts once) require.Equal(t, uint(0), res.Verifying) require.Equal(t, uint(0), res.Verified) @@ -2264,7 +2264,7 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) // get summary for profiles with no team require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-2), res.Pending) // no change + require.EqualValues(t, len(hosts)-2, res.Pending) // no change require.Equal(t, uint(2), res.Failed) // no change require.Equal(t, uint(0), res.Verifying) // no change, host must apply all profiles count as latest require.Equal(t, uint(0), res.Verified) @@ -2282,11 +2282,12 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { require.NoError(t, err) require.NoError(t, ds.deleteMDMOSCustomSettingsForHost(ctx, tx, hosts[6].UUID, "darwin")) require.NoError(t, tx.Commit()) - pendingHosts := append(hosts[2:6:6], hosts[7:]...) + pendingHosts := hosts[2:6:6] + pendingHosts = append(pendingHosts, hosts[7:]...) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) // get summary for profiles with no team require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-3), res.Pending) // hosts[6] not reported here anymore + require.EqualValues(t, len(hosts)-3, res.Pending) // hosts[6] not reported here anymore require.Equal(t, uint(2), res.Failed) // no change require.Equal(t, uint(0), res.Verifying) // no change, host must apply all profiles count as latest require.Equal(t, uint(0), res.Verified) @@ -2302,11 +2303,12 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { // hosts[9] installed all profiles but one is with status nil (pending) upsertHostCPs(hosts[9:10], noTeamCPs[:9], fleet.MDMOperationTypeInstall, &fleet.MDMDeliveryVerifying, ctx, ds, t) upsertHostCPs(hosts[9:10], noTeamCPs[9:10], fleet.MDMOperationTypeInstall, nil, ctx, ds, t) - pendingHosts = append(hosts[2:6:6], hosts[7:]...) + pendingHosts = hosts[2:6:6] + pendingHosts = append(pendingHosts, hosts[7:]...) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) // get summary for profiles with no team require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-3), res.Pending) // hosts[6] not reported here anymore, hosts[9] still pending + require.EqualValues(t, len(hosts)-3, res.Pending) // hosts[6] not reported here anymore, hosts[9] still pending require.Equal(t, uint(2), res.Failed) // no change require.Equal(t, uint(0), res.Verifying) // no change, host must apply all profiles count as latest require.Equal(t, uint(0), res.Verified) @@ -2321,11 +2323,12 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { // hosts[9] installed all profiles upsertHostCPs(hosts[9:10], noTeamCPs, fleet.MDMOperationTypeInstall, &fleet.MDMDeliveryVerifying, ctx, ds, t) - pendingHosts = append(hosts[2:6:6], hosts[7:9]...) + pendingHosts = hosts[2:6:6] + pendingHosts = append(pendingHosts, hosts[7:9]...) res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) // get summary for profiles with no team require.NoError(t, err) require.NotNil(t, res) - require.Equal(t, uint(len(hosts)-4), res.Pending) // subtract hosts[6 and 9] from pending + require.EqualValues(t, len(hosts)-4, res.Pending) // subtract hosts[6 and 9] from pending require.Equal(t, uint(2), res.Failed) // no change require.Equal(t, uint(1), res.Verifying) // add one host that has installed all profiles require.Equal(t, uint(0), res.Verified) @@ -2362,8 +2365,9 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { res, err = ds.GetMDMAppleProfilesSummary(ctx, nil) // get summary for profiles with no team require.NoError(t, err) require.NotNil(t, res) - pendingHosts = append(hosts[2:6:6], hosts[7:9]...) - require.Equal(t, uint(len(hosts)-4), res.Pending) // hosts[9] is still not pending, transferred to team + pendingHosts = hosts[2:6:6] + pendingHosts = append(pendingHosts, hosts[7:9]...) + require.EqualValues(t, len(hosts)-4, res.Pending) // hosts[9] is still not pending, transferred to team require.Equal(t, uint(2), res.Failed) // no change require.Equal(t, uint(0), res.Verifying) // hosts[9] was transferred so this is now zero require.True(t, checkListHosts(fleet.OSSettingsPending, nil, pendingHosts)) @@ -2455,8 +2459,9 @@ func testMDMAppleHostsProfilesStatus(t *testing.T, ds *Datastore) { res, err = ds.GetMDMAppleProfilesSummary(ctx, ptr.Uint(0)) // team id zero represents no team require.NoError(t, err) require.NotNil(t, res) - pendingHosts = append(hosts[2:6:6], hosts[7:9]...) - require.Equal(t, uint(len(hosts)-4), res.Pending) // subtract two failed hosts, one without profiles and hosts[9] transferred + pendingHosts = hosts[2:6:6] + pendingHosts = append(pendingHosts, hosts[7:9]...) + require.EqualValues(t, len(hosts)-4, res.Pending) // subtract two failed hosts, one without profiles and hosts[9] transferred require.Equal(t, uint(2), res.Failed) // two failed hosts require.Equal(t, uint(0), res.Verifying) // hosts[9] transferred to new team so is not counted under no team require.Equal(t, uint(0), res.Verified) @@ -6850,7 +6855,8 @@ func testHostMDMCommands(t *testing.T, ds *Datastore) { } badHostID := h.ID + 1 - allCommands := append(hostCommands, fleet.HostMDMCommand{ + allCommands := hostCommands + allCommands = append(allCommands, fleet.HostMDMCommand{ HostID: badHostID, CommandType: "command-1", }) diff --git a/server/datastore/mysql/calendar_events.go b/server/datastore/mysql/calendar_events.go index 21004cf83a..3de934b718 100644 --- a/server/datastore/mysql/calendar_events.go +++ b/server/datastore/mysql/calendar_events.go @@ -98,7 +98,7 @@ func (ds *Datastore) CreateOrUpdateCalendarEvent( return nil, ctxerr.Wrap(ctx, err) } - calendarEvent, err := getCalendarEventByID(ctx, ds.writer(ctx), uint(id)) + calendarEvent, err := getCalendarEventByID(ctx, ds.writer(ctx), uint(id)) //nolint:gosec // dismiss G115 if err != nil { return nil, ctxerr.Wrap(ctx, err, "get created calendar event by id") } diff --git a/server/datastore/mysql/campaigns.go b/server/datastore/mysql/campaigns.go index fa0af95f21..c9debe5d80 100644 --- a/server/datastore/mysql/campaigns.go +++ b/server/datastore/mysql/campaigns.go @@ -38,7 +38,7 @@ func (ds *Datastore) NewDistributedQueryCampaign(ctx context.Context, camp *flee } id, _ := result.LastInsertId() - camp.ID = uint(id) + camp.ID = uint(id) //nolint:gosec // dismiss G115 return camp, nil } @@ -130,7 +130,7 @@ func (ds *Datastore) NewDistributedQueryCampaignTarget(ctx context.Context, targ } id, _ := result.LastInsertId() - target.ID = uint(id) + target.ID = uint(id) //nolint:gosec // dismiss G115 return target, nil } @@ -194,5 +194,5 @@ func (ds *Datastore) CleanupDistributedQueryCampaigns(ctx context.Context, now t if err != nil { return 0, ctxerr.Wrap(ctx, err, "rows affected updating distributed query campaign") } - return uint(exp), nil + return uint(exp), nil //nolint:gosec // dismiss G115 } diff --git a/server/datastore/mysql/campaigns_test.go b/server/datastore/mysql/campaigns_test.go index b7154d92fd..e26cd6d4eb 100644 --- a/server/datastore/mysql/campaigns_test.go +++ b/server/datastore/mysql/campaigns_test.go @@ -243,7 +243,8 @@ func testCompletedCampaigns(t *testing.T, ds *Datastore) { } filter = append(filter, c1.ID) } - for j := filter[len(filter)-1] / 2; j < uint(totalFilterSize); j++ { // some IDs are duplicated + for j := filter[len(filter)-1] / 2; j < uint(totalFilterSize); j++ { //nolint:gosec // dismiss G115 + // some IDs are duplicated filter = append(filter, j) } rand.Shuffle(len(filter), func(i, j int) { filter[i], filter[j] = filter[j], filter[i] }) diff --git a/server/datastore/mysql/carves.go b/server/datastore/mysql/carves.go index 87d939b667..0b61006a77 100644 --- a/server/datastore/mysql/carves.go +++ b/server/datastore/mysql/carves.go @@ -179,7 +179,7 @@ func (ds *Datastore) Carve(ctx context.Context, carveId int64) (*fleet.CarveMeta var metadata fleet.CarveMetadata if err := sqlx.GetContext(ctx, ds.reader(ctx), &metadata, stmt, carveId); err != nil { if err == sql.ErrNoRows { - return nil, ctxerr.Wrap(ctx, notFound("Carve").WithID(uint(carveId))) + return nil, ctxerr.Wrap(ctx, notFound("Carve").WithID(uint(carveId))) //nolint:gosec // dismiss G115 } return nil, ctxerr.Wrap(ctx, err, "get carve by ID") } @@ -280,7 +280,7 @@ func (ds *Datastore) GetBlock(ctx context.Context, metadata *fleet.CarveMetadata var data []byte if err := sqlx.GetContext(ctx, ds.reader(ctx), &data, stmt, metadata.ID, blockId); err != nil { if err == sql.ErrNoRows { - return nil, ctxerr.Wrap(ctx, notFound("CarveBlock").WithID(uint(blockId))) + return nil, ctxerr.Wrap(ctx, notFound("CarveBlock").WithID(uint(blockId))) //nolint:gosec // dismiss G115 } return nil, ctxerr.Wrap(ctx, err, "select data") } diff --git a/server/datastore/mysql/delete.go b/server/datastore/mysql/delete.go index 7971b14c95..47285401d9 100644 --- a/server/datastore/mysql/delete.go +++ b/server/datastore/mysql/delete.go @@ -61,5 +61,5 @@ func (ds *Datastore) deleteEntities(ctx context.Context, dbTable entity, ids []u return 0, ctxerr.Wrapf(ctx, err, "fetching delete entities query rows affected %s", dbTable) } - return uint(deleted), nil + return uint(deleted), nil //nolint:gosec // dismiss G115 } diff --git a/server/datastore/mysql/hosts.go b/server/datastore/mysql/hosts.go index 62254ed499..d669a302bc 100644 --- a/server/datastore/mysql/hosts.go +++ b/server/datastore/mysql/hosts.go @@ -1216,7 +1216,8 @@ func (ds *Datastore) applyHostFilters( sqlStmt, whereParams, _ = hostSearchLike(sqlStmt, whereParams, opt.MatchQuery, append(hostSearchColumns, "display_name")...) sqlStmt, whereParams = appendListOptionsWithCursorToSQL(sqlStmt, whereParams, &opt.ListOptions) - params := append(selectParams, joinParams...) + params := selectParams + params = append(params, joinParams...) params = append(params, whereParams...) return sqlStmt, params, nil @@ -1278,7 +1279,7 @@ func filterHostsByConnectedToFleet(sql string, opt fleet.HostListOptions, params } func filterHostsByOS(sql string, opt fleet.HostListOptions, params []interface{}) (string, []interface{}) { - if opt.OSIDFilter != nil { + if opt.OSIDFilter != nil { //nolint:gocritic // ignore ifElseChain sql += ` AND hos.os_id = ?` params = append(params, *opt.OSIDFilter) } else if opt.OSNameFilter != nil && opt.OSVersionFilter != nil { diff --git a/server/datastore/mysql/hosts_test.go b/server/datastore/mysql/hosts_test.go index c0ccb22d85..1a5513c5bd 100644 --- a/server/datastore/mysql/hosts_test.go +++ b/server/datastore/mysql/hosts_test.go @@ -458,7 +458,7 @@ func testSaveHostPackStatsDB(t *testing.T, ds *Datastore) { }) assert.Equal(t, host.PackStats[1].PackName, "test2") // Server calculates WallTimeMs if WallTimeMs==0 coming in. (osquery wall_time -> wall_time_ms -> DB wall_time) - stats2[0].WallTime = stats2[0].WallTime * 1000 + stats2[0].WallTime *= 1000 assert.ElementsMatch(t, host.PackStats[1].QueryStats, stats2) } @@ -2654,7 +2654,7 @@ func testHostsAddToTeam(t *testing.T, ds *Datastore) { host, err := ds.Host(context.Background(), uint(i)) require.NoError(t, err) var expectedID *uint - switch { + switch { //nolint:gocritic // ignore singleCaseSwitch case i >= 5: expectedID = &team1.ID } diff --git a/server/datastore/mysql/invites.go b/server/datastore/mysql/invites.go index d9328d1973..845837513a 100644 --- a/server/datastore/mysql/invites.go +++ b/server/datastore/mysql/invites.go @@ -34,7 +34,7 @@ func (ds *Datastore) NewInvite(ctx context.Context, i *fleet.Invite) (*fleet.Inv } id, _ := result.LastInsertId() - i.ID = uint(id) + i.ID = uint(id) //nolint:gosec // dismiss G115 if len(i.Teams) == 0 { i.Teams = []fleet.UserTeam{} diff --git a/server/datastore/mysql/jobs.go b/server/datastore/mysql/jobs.go index d674ad26c2..1dbc0e4c5c 100644 --- a/server/datastore/mysql/jobs.go +++ b/server/datastore/mysql/jobs.go @@ -30,7 +30,7 @@ VALUES (?, ?, ?, ?, ?, COALESCE(?, NOW())) } id, _ := result.LastInsertId() - job.ID = uint(id) + job.ID = uint(id) //nolint:gosec // dismiss G115 return job, nil } diff --git a/server/datastore/mysql/labels.go b/server/datastore/mysql/labels.go index 5ac777be39..21c4e0eb94 100644 --- a/server/datastore/mysql/labels.go +++ b/server/datastore/mysql/labels.go @@ -217,7 +217,7 @@ func (ds *Datastore) NewLabel(ctx context.Context, label *fleet.Label, opts ...f } id, _ := result.LastInsertId() - label.ID = uint(id) + label.ID = uint(id) //nolint:gosec // dismiss G115 return label, nil } diff --git a/server/datastore/mysql/maintained_apps.go b/server/datastore/mysql/maintained_apps.go index 285db769cb..951bf4b473 100644 --- a/server/datastore/mysql/maintained_apps.go +++ b/server/datastore/mysql/maintained_apps.go @@ -54,7 +54,7 @@ ON DUPLICATE KEY UPDATE res, err := tx.ExecContext(ctx, upsertStmt, app.Name, app.Token, app.Version, app.Platform, app.InstallerURL, app.SHA256, app.BundleIdentifier, installScriptID, uninstallScriptID) id, _ := res.LastInsertId() - appID = uint(id) + appID = uint(id) //nolint:gosec // dismiss G115 return ctxerr.Wrap(ctx, err, "upsert maintained app") }) if err != nil { @@ -155,8 +155,8 @@ WHERE NOT EXISTS ( return nil, nil, ctxerr.Wrap(ctx, err, "selecting available fleet managed apps") } - meta := &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0, TotalResults: uint(counts)} - if len(avail) > int(opt.PerPage) { + meta := &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0, TotalResults: uint(counts)} //nolint:gosec // dismiss G115 + if len(avail) > int(opt.PerPage) { //nolint:gosec // dismiss G115 meta.HasNextResults = true avail = avail[:len(avail)-1] } diff --git a/server/datastore/mysql/maintained_apps_test.go b/server/datastore/mysql/maintained_apps_test.go index f95c9cb804..97f5959751 100644 --- a/server/datastore/mysql/maintained_apps_test.go +++ b/server/datastore/mysql/maintained_apps_test.go @@ -171,7 +171,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err := ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 3) - require.Equal(t, int(meta.TotalResults), 3) + require.EqualValues(t, meta.TotalResults, 3) assertUpdatedAt(apps) require.Equal(t, expectedApps, apps) require.False(t, meta.HasNextResults) @@ -179,7 +179,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{PerPage: 1, IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 1) - require.Equal(t, int(meta.TotalResults), 3) + require.EqualValues(t, meta.TotalResults, 3) assertUpdatedAt(apps) require.Equal(t, expectedApps[:1], apps) require.True(t, meta.HasNextResults) @@ -187,7 +187,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{PerPage: 1, Page: 1, IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 1) - require.Equal(t, int(meta.TotalResults), 3) + require.EqualValues(t, meta.TotalResults, 3) assertUpdatedAt(apps) require.Equal(t, expectedApps[1:2], apps) require.True(t, meta.HasNextResults) @@ -196,7 +196,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{PerPage: 1, Page: 2, IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 1) - require.Equal(t, int(meta.TotalResults), 3) + require.EqualValues(t, meta.TotalResults, 3) assertUpdatedAt(apps) require.Equal(t, expectedApps[2:3], apps) require.False(t, meta.HasNextResults) @@ -220,7 +220,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 3) - require.Equal(t, int(meta.TotalResults), 3) + require.EqualValues(t, meta.TotalResults, 3) assertUpdatedAt(apps) require.Equal(t, expectedApps, apps) @@ -239,7 +239,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 3) - require.Equal(t, int(meta.TotalResults), 3) + require.EqualValues(t, meta.TotalResults, 3) assertUpdatedAt(apps) require.Equal(t, expectedApps, apps) @@ -258,7 +258,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 3) - require.Equal(t, int(meta.TotalResults), 3) + require.EqualValues(t, meta.TotalResults, 3) assertUpdatedAt(apps) require.Equal(t, expectedApps, apps) @@ -271,7 +271,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 2) - require.Equal(t, int(meta.TotalResults), 2) + require.EqualValues(t, meta.TotalResults, 2) assertUpdatedAt(apps) require.Equal(t, expectedApps[1:], apps) @@ -297,7 +297,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 2) - require.Equal(t, int(meta.TotalResults), 2) + require.EqualValues(t, meta.TotalResults, 2) assertUpdatedAt(apps) require.Equal(t, expectedApps[1:], apps) @@ -318,7 +318,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 2) - require.Equal(t, int(meta.TotalResults), 2) + require.EqualValues(t, meta.TotalResults, 2) assertUpdatedAt(apps) require.Equal(t, expectedApps[1:], apps) @@ -329,7 +329,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 1) - require.Equal(t, int(meta.TotalResults), 1) + require.EqualValues(t, meta.TotalResults, 1) assertUpdatedAt(apps) require.Equal(t, expectedApps[2:], apps) @@ -351,7 +351,7 @@ func testListAvailableApps(t *testing.T, ds *Datastore) { apps, meta, err = ds.ListAvailableFleetMaintainedApps(ctx, team1.ID, fleet.ListOptions{IncludeMetadata: true}) require.NoError(t, err) require.Len(t, apps, 1) - require.Equal(t, int(meta.TotalResults), 1) + require.EqualValues(t, meta.TotalResults, 1) assertUpdatedAt(apps) require.Equal(t, expectedApps[2:], apps) } diff --git a/server/datastore/mysql/mdm.go b/server/datastore/mysql/mdm.go index d3bbba82de..5a68667bf3 100644 --- a/server/datastore/mysql/mdm.go +++ b/server/datastore/mysql/mdm.go @@ -241,7 +241,7 @@ FROM ( var metaData *fleet.PaginationMetadata if opt.IncludeMetadata { metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0} - if len(profs) > int(opt.PerPage) { + if len(profs) > int(opt.PerPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true profs = profs[:len(profs)-1] } @@ -375,7 +375,7 @@ func (ds *Datastore) bulkSetPendingMDMHostProfilesDB( // split into mac and win profiles for _, puid := range profileUUIDs { - if strings.HasPrefix(puid, fleet.MDMAppleProfileUUIDPrefix) { + if strings.HasPrefix(puid, fleet.MDMAppleProfileUUIDPrefix) { //nolint:gocritic // ignore ifElseChain macProfUUIDs = append(macProfUUIDs, puid) } else if strings.HasPrefix(puid, fleet.MDMAppleDeclarationUUIDPrefix) { hasAppleDecls = true @@ -1104,7 +1104,8 @@ func batchSetProfileLabelAssociationsDB( for k := range setProfileUUIDs { profUUIDs = append(profUUIDs, k) } - deleteArgs := append(deleteParams, profUUIDs) + deleteArgs := deleteParams + deleteArgs = append(deleteArgs, profUUIDs) deleteStmt, args, err := sqlx.In(deleteStmt, deleteArgs...) if err != nil { diff --git a/server/datastore/mysql/mdm_test.go b/server/datastore/mysql/mdm_test.go index a8d765baca..760b2dac58 100644 --- a/server/datastore/mysql/mdm_test.go +++ b/server/datastore/mysql/mdm_test.go @@ -1114,7 +1114,8 @@ func testBulkSetPendingMDMHostProfiles(t *testing.T, ds *Datastore) { require.Error(t, err) // bulk set for all created hosts, no profiles yet so nothing changed - allHosts := append(darwinHosts, unenrolledHost, linuxHost) + allHosts := darwinHosts + allHosts = append(allHosts, unenrolledHost, linuxHost) allHosts = append(allHosts, windowsHosts...) updates, err = ds.BulkSetPendingMDMHostProfiles(ctx, hostIDsFromHosts(allHosts...), nil, nil, nil) require.NoError(t, err) diff --git a/server/datastore/mysql/migrations/tables/20171116163618_CreateTableOsqueryOptions.go b/server/datastore/mysql/migrations/tables/20171116163618_CreateTableOsqueryOptions.go index 1a0138e931..1a2afca0d4 100644 --- a/server/datastore/mysql/migrations/tables/20171116163618_CreateTableOsqueryOptions.go +++ b/server/datastore/mysql/migrations/tables/20171116163618_CreateTableOsqueryOptions.go @@ -4,7 +4,6 @@ import ( "database/sql" "encoding/json" "fmt" - "strconv" "github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx/reflectx" @@ -128,7 +127,7 @@ func migrateOptions(tx *sql.Tx) error { case decoratorAlways: decConfig.Always = append(decConfig.Always, dec.Query) case decoratorInterval: - key := strconv.Itoa(int(dec.Interval)) + key := fmt.Sprint(dec.Interval) decConfig.Interval[key] = append(decConfig.Interval[key], dec.Query) default: fmt.Printf("Unable to migrate decorator. Please migrate manually: '%s'\n", dec.Query) diff --git a/server/datastore/mysql/migrations/tables/20210601000008_TeamsEnrollSecrets.go b/server/datastore/mysql/migrations/tables/20210601000008_TeamsEnrollSecrets.go index 9596240f28..b42949b894 100644 --- a/server/datastore/mysql/migrations/tables/20210601000008_TeamsEnrollSecrets.go +++ b/server/datastore/mysql/migrations/tables/20210601000008_TeamsEnrollSecrets.go @@ -32,10 +32,10 @@ func Up_20210601000008(tx *sql.Tx) error { // ********* TEST ONLY BEGIN ********* // This will make an enroll secrets test fail because it should end up with one unexpected secret - //if _, err := tx.Exec( + // if _, err := tx.Exec( // `INSERT INTO enroll_secrets (secret, name) VALUES ('aaaa', '1'), ('aaaa', '2'), ('aaaa', '3')`); err != nil { // return errors.Wrap(err, "add red hat label") - //} + // } // ********* TEST ONLY ENDS ********* //nolint diff --git a/server/datastore/mysql/migrations/tables/20220323152301_CleanupHostRelatedTables_test.go b/server/datastore/mysql/migrations/tables/20220323152301_CleanupHostRelatedTables_test.go index 1546802218..49ddbae2d6 100644 --- a/server/datastore/mysql/migrations/tables/20220323152301_CleanupHostRelatedTables_test.go +++ b/server/datastore/mysql/migrations/tables/20220323152301_CleanupHostRelatedTables_test.go @@ -105,7 +105,7 @@ func createHostsWithSoftware(t *testing.T, db *sqlx.DB) []*fleet.Host { ) require.NoError(t, err) id, _ := res.LastInsertId() - host.ID = uint(id) + host.ID = uint(id) //nolint:gosec // dismiss G115 hosts[i] = host } @@ -124,7 +124,7 @@ func createHostsWithSoftware(t *testing.T, db *sqlx.DB) []*fleet.Host { res, err := db.Exec(insSw, sw.Name, sw.Version, sw.Source, sw.Release, sw.Vendor, sw.Arch, sw.BundleIdentifier) require.NoError(t, err) id, _ := res.LastInsertId() - sw.ID = uint(id) + sw.ID = uint(id) //nolint:gosec // dismiss G115 } for _, host := range hosts { diff --git a/server/datastore/mysql/migrations/tables/20230425082126_AddMDMAppleSetupAssistants_test.go b/server/datastore/mysql/migrations/tables/20230425082126_AddMDMAppleSetupAssistants_test.go index 500d21b07f..eb0d89953c 100644 --- a/server/datastore/mysql/migrations/tables/20230425082126_AddMDMAppleSetupAssistants_test.go +++ b/server/datastore/mysql/migrations/tables/20230425082126_AddMDMAppleSetupAssistants_test.go @@ -34,7 +34,8 @@ func TestUp_20230425082126(t *testing.T) { var asst assistant err = db.Get(&asst, `SELECT id, name, profile, team_id, global_or_team_id FROM mdm_apple_setup_assistants WHERE id = ?`, id) require.NoError(t, err) - require.Equal(t, assistant{ID: uint(id), Name: "Test", Profile: "{}", TeamID: nil, GlobalOrTeamID: 0}, asst) + require.Equal(t, assistant{ID: uint(id), Name: "Test", Profile: "{}", TeamID: nil, GlobalOrTeamID: 0}, //nolint:gosec // dismiss G115 + asst) // create a team r, err = db.Exec(`INSERT INTO teams (name) VALUES (?)`, "Test Team") @@ -48,7 +49,8 @@ func TestUp_20230425082126(t *testing.T) { err = db.Get(&asst, `SELECT id, name, profile, team_id, global_or_team_id FROM mdm_apple_setup_assistants WHERE id = ?`, id2) require.NoError(t, err) - require.Equal(t, assistant{ID: uint(id2), Name: "Test2", Profile: "{}", TeamID: ptr.Uint(uint(tmID)), GlobalOrTeamID: uint(tmID)}, asst) + require.Equal(t, assistant{ID: uint(id2), Name: "Test2", Profile: "{}", TeamID: ptr.Uint(uint(tmID)), //nolint:gosec // dismiss G115 + GlobalOrTeamID: uint(tmID)}, asst) //nolint:gosec // dismiss G115 // delete the team, that deletes the row _, err = db.Exec(`DELETE FROM teams WHERE id = ?`, tmID) diff --git a/server/datastore/mysql/migrations/tables/20230501154913_AlterMDMAppleSetupAssistantsAddProfileUUID_test.go b/server/datastore/mysql/migrations/tables/20230501154913_AlterMDMAppleSetupAssistantsAddProfileUUID_test.go index 552902aa3f..86f4939c0c 100644 --- a/server/datastore/mysql/migrations/tables/20230501154913_AlterMDMAppleSetupAssistantsAddProfileUUID_test.go +++ b/server/datastore/mysql/migrations/tables/20230501154913_AlterMDMAppleSetupAssistantsAddProfileUUID_test.go @@ -24,7 +24,7 @@ func TestUp_20230501154913(t *testing.T) { var asst assistant err = db.Get(&asst, `SELECT id, name, profile_uuid FROM mdm_apple_setup_assistants WHERE id = ?`, id) require.NoError(t, err) - require.Equal(t, assistant{ID: uint(id), Name: "Test", ProfileUUID: ""}, asst) + require.Equal(t, assistant{ID: uint(id), Name: "Test", ProfileUUID: ""}, asst) //nolint:gosec // dismiss G115 // create a team r, err = db.Exec(`INSERT INTO teams (name) VALUES (?)`, "Test Team") @@ -38,5 +38,5 @@ func TestUp_20230501154913(t *testing.T) { err = db.Get(&asst, `SELECT id, name, profile_uuid FROM mdm_apple_setup_assistants WHERE id = ?`, id) require.NoError(t, err) - require.Equal(t, assistant{ID: uint(id), Name: "Test2", ProfileUUID: "abc"}, asst) + require.Equal(t, assistant{ID: uint(id), Name: "Test2", ProfileUUID: "abc"}, asst) //nolint:gosec // dismiss G115 } diff --git a/server/datastore/mysql/migrations/tables/20230503101418_AlterJobsAddNotBefore_test.go b/server/datastore/mysql/migrations/tables/20230503101418_AlterJobsAddNotBefore_test.go index 2d2f64926e..b2956a236d 100644 --- a/server/datastore/mysql/migrations/tables/20230503101418_AlterJobsAddNotBefore_test.go +++ b/server/datastore/mysql/migrations/tables/20230503101418_AlterJobsAddNotBefore_test.go @@ -30,5 +30,5 @@ func TestUp_20230503101418(t *testing.T) { require.NotZero(t, j.NotBefore) j.UpdatedAt = time.Time{} j.NotBefore = time.Time{} - require.Equal(t, job{ID: uint(id), Name: "Test"}, j) + require.Equal(t, job{ID: uint(id), Name: "Test"}, j) //nolint:gosec // dismiss G115 } diff --git a/server/datastore/mysql/migrations/tables/20230515144206_AddMDMAppleDefaultSetupAssistants_test.go b/server/datastore/mysql/migrations/tables/20230515144206_AddMDMAppleDefaultSetupAssistants_test.go index 70c6f9caab..e9cfd37e01 100644 --- a/server/datastore/mysql/migrations/tables/20230515144206_AddMDMAppleDefaultSetupAssistants_test.go +++ b/server/datastore/mysql/migrations/tables/20230515144206_AddMDMAppleDefaultSetupAssistants_test.go @@ -24,7 +24,7 @@ func TestUp_20230515144206(t *testing.T) { err = db.Get(&asst, `SELECT id, profile_uuid FROM mdm_apple_default_setup_assistants WHERE id = ?`, id) require.NoError(t, err) - require.Equal(t, assistant{ID: uint(id), ProfileUUID: "abc"}, asst) + require.Equal(t, assistant{ID: uint(id), ProfileUUID: "abc"}, asst) //nolint:gosec // dismiss G115 // create a team r, err = db.Exec(`INSERT INTO teams (name) VALUES (?)`, "Test Team") @@ -38,5 +38,5 @@ func TestUp_20230515144206(t *testing.T) { err = db.Get(&asst, `SELECT id, profile_uuid FROM mdm_apple_default_setup_assistants WHERE id = ?`, id) require.NoError(t, err) - require.Equal(t, assistant{ID: uint(id), ProfileUUID: "def"}, asst) + require.Equal(t, assistant{ID: uint(id), ProfileUUID: "def"}, asst) //nolint:gosec // dismiss G115 } diff --git a/server/datastore/mysql/migrations/tables/20230608103123_CleanupOrphanedMDMAppleConfigurationProfiles_test.go b/server/datastore/mysql/migrations/tables/20230608103123_CleanupOrphanedMDMAppleConfigurationProfiles_test.go index ca6ff0d6f0..cf88997a86 100644 --- a/server/datastore/mysql/migrations/tables/20230608103123_CleanupOrphanedMDMAppleConfigurationProfiles_test.go +++ b/server/datastore/mysql/migrations/tables/20230608103123_CleanupOrphanedMDMAppleConfigurationProfiles_test.go @@ -31,5 +31,5 @@ func TestUp_20230608103123(t *testing.T) { var teamIDs []uint err = db.Select(&teamIDs, "SELECT team_id FROM mdm_apple_configuration_profiles GROUP BY team_id") require.NoError(t, err) - require.ElementsMatch(t, []uint{0, uint(tmID)}, teamIDs) + require.ElementsMatch(t, []uint{0, uint(tmID)}, teamIDs) //nolint:gosec // dismiss G115 } diff --git a/server/datastore/mysql/migrations/tables/20240131083822_AddUniqueHashToPolicies_test.go b/server/datastore/mysql/migrations/tables/20240131083822_AddUniqueHashToPolicies_test.go index c63fe61f66..1b9a39300e 100644 --- a/server/datastore/mysql/migrations/tables/20240131083822_AddUniqueHashToPolicies_test.go +++ b/server/datastore/mysql/migrations/tables/20240131083822_AddUniqueHashToPolicies_test.go @@ -2,8 +2,9 @@ package tables import ( "context" - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" ) func TestUp_20240131083822(t *testing.T) { @@ -38,7 +39,7 @@ func TestUp_20240131083822(t *testing.T) { gotIDs := make([]int64, len(wantIDs)) for i, pc := range policyCheck { - if pc.ID == policy1 { + if pc.ID == policy1 { //nolint:gocritic // ignore ifelseChain require.Equal(t, pc.Name, "policy1") } else if pc.ID == policy2 { require.Equal(t, pc.Name, "policy2") diff --git a/server/datastore/mysql/migrations/tables/20240221112844_FixUniquePolicyNameBug_test.go b/server/datastore/mysql/migrations/tables/20240221112844_FixUniquePolicyNameBug_test.go index b1add49216..0d54823dc9 100644 --- a/server/datastore/mysql/migrations/tables/20240221112844_FixUniquePolicyNameBug_test.go +++ b/server/datastore/mysql/migrations/tables/20240221112844_FixUniquePolicyNameBug_test.go @@ -5,11 +5,12 @@ import ( "crypto/md5" //nolint:gosec // (only used for tests) "encoding/hex" "fmt" + "strings" + "testing" + "github.com/fleetdm/fleet/v4/server/fleet" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "strings" - "testing" ) func TestUp_20240221112844(t *testing.T) { @@ -69,7 +70,7 @@ func TestUp_20240221112844(t *testing.T) { gotIDs := make([]int64, len(wantIDs)) for i, pc := range policyCheck { - if pc.ID == policy1 { + if pc.ID == policy1 { //nolint:gocritic // ignore ifelseChain assert.Equal(t, "policy", pc.Name) } else if pc.ID == policy2 { assert.Equal(t, "policy3", pc.Name) // name changed diff --git a/server/datastore/mysql/migrations/tables/20240222073518_AddCertInfoToNanoCertAssociations_test.go b/server/datastore/mysql/migrations/tables/20240222073518_AddCertInfoToNanoCertAssociations_test.go index 75c62777fe..244a359aab 100644 --- a/server/datastore/mysql/migrations/tables/20240222073518_AddCertInfoToNanoCertAssociations_test.go +++ b/server/datastore/mysql/migrations/tables/20240222073518_AddCertInfoToNanoCertAssociations_test.go @@ -57,7 +57,7 @@ func TestUp_20240222073518(t *testing.T) { require.Equal(t, sha1, assoc.SHA256) require.Equal(t, threeDaysAgo, assoc.CreatedAt) require.Equal(t, threeDaysAgo, assoc.UpdatedAt) - require.Equal(t, "2025-02-20 19:57:24", (*assoc.CertNotValidAfter).Format("2006-01-02 15:04:05")) + require.Equal(t, "2025-02-20 19:57:24", assoc.CertNotValidAfter.Format("2006-01-02 15:04:05")) require.Nil(t, assoc.RenewCommandUUID) err = sqlx.Get(db, &assoc, selectStmt, "uuid-2") @@ -66,7 +66,7 @@ func TestUp_20240222073518(t *testing.T) { require.Equal(t, sha2, assoc.SHA256) require.Equal(t, threeDaysAgo, assoc.CreatedAt) require.Equal(t, threeDaysAgo, assoc.UpdatedAt) - require.Equal(t, "2025-02-20 19:57:25", (*assoc.CertNotValidAfter).Format("2006-01-02 15:04:05")) + require.Equal(t, "2025-02-20 19:57:25", assoc.CertNotValidAfter.Format("2006-01-02 15:04:05")) require.Nil(t, assoc.RenewCommandUUID) err = sqlx.Get(db, &assoc, selectStmt, "uuid-3") @@ -75,7 +75,7 @@ func TestUp_20240222073518(t *testing.T) { require.Equal(t, sha2, assoc.SHA256) require.Equal(t, threeDaysAgo, assoc.CreatedAt) require.Equal(t, threeDaysAgo, assoc.UpdatedAt) - require.Equal(t, "2025-02-20 19:57:25", (*assoc.CertNotValidAfter).Format("2006-01-02 15:04:05")) + require.Equal(t, "2025-02-20 19:57:25", assoc.CertNotValidAfter.Format("2006-01-02 15:04:05")) require.Nil(t, assoc.RenewCommandUUID) // creating a new association sets NULL as default values diff --git a/server/datastore/mysql/migrations/tables/20240302111134_AddScriptContentsTableAndRelationships.go b/server/datastore/mysql/migrations/tables/20240302111134_AddScriptContentsTableAndRelationships.go index b965fea8b7..7fcdcbe2fe 100644 --- a/server/datastore/mysql/migrations/tables/20240302111134_AddScriptContentsTableAndRelationships.go +++ b/server/datastore/mysql/migrations/tables/20240302111134_AddScriptContentsTableAndRelationships.go @@ -227,7 +227,7 @@ func createScriptContentsEntries(txx *sqlx.Tx, stmtTable, stmt string, scriptCon return fmt.Errorf("create script_contents from %s: %w", stmtTable, err) } id, _ := res.LastInsertId() - scriptContentsIDLookup[hexChecksum] = uint(id) + scriptContentsIDLookup[hexChecksum] = uint(id) //nolint:gosec // dismiss G115 } } } diff --git a/server/datastore/mysql/migrations/tables/20240314085226_AddCalendarEventTables_test.go b/server/datastore/mysql/migrations/tables/20240314085226_AddCalendarEventTables_test.go index 85f61b342b..a5c5a6fafa 100644 --- a/server/datastore/mysql/migrations/tables/20240314085226_AddCalendarEventTables_test.go +++ b/server/datastore/mysql/migrations/tables/20240314085226_AddCalendarEventTables_test.go @@ -18,7 +18,7 @@ func TestUp_20240314085226(t *testing.T) { EndTime: time.Now().UTC().Add(30 * time.Minute), Data: []byte("{\"foo\": \"bar\"}"), } - sampleEvent.ID = uint(execNoErrLastID(t, db, + sampleEvent.ID = uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO calendar_events (email, start_time, end_time, event) VALUES (?, ?, ?, ?);`, sampleEvent.Email, sampleEvent.StartTime, sampleEvent.EndTime, sampleEvent.Data, )) @@ -28,7 +28,7 @@ func TestUp_20240314085226(t *testing.T) { CalendarEventID: sampleEvent.ID, WebhookStatus: fleet.CalendarWebhookStatusPending, } - sampleHostEvent.ID = uint(execNoErrLastID(t, db, + sampleHostEvent.ID = uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO host_calendar_events (host_id, calendar_event_id, webhook_status) VALUES (?, ?, ?);`, sampleHostEvent.HostID, sampleHostEvent.CalendarEventID, sampleHostEvent.WebhookStatus, )) diff --git a/server/datastore/mysql/migrations/tables/20240430111727_CleanupQueryResults_test.go b/server/datastore/mysql/migrations/tables/20240430111727_CleanupQueryResults_test.go index a2f7df2bf8..43e57f3460 100644 --- a/server/datastore/mysql/migrations/tables/20240430111727_CleanupQueryResults_test.go +++ b/server/datastore/mysql/migrations/tables/20240430111727_CleanupQueryResults_test.go @@ -13,7 +13,7 @@ func TestUp_20240430111727(t *testing.T) { hostID := 1 newTeam := func(name string) uint { - return uint(execNoErrLastID(t, db, + return uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO teams (name) VALUES (?);`, name, )) @@ -21,13 +21,13 @@ func TestUp_20240430111727(t *testing.T) { newHost := func(teamID *uint) uint { id := fmt.Sprintf("%d", hostID) hostID++ - return uint(execNoErrLastID(t, db, + return uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO hosts (osquery_host_id, node_key, team_id) VALUES (?, ?, ?);`, id, id, teamID, )) } newQuery := func(name string, teamID *uint) uint { - return uint(execNoErrLastID(t, db, + return uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO queries (name, description, logging_type, team_id, query, saved) VALUES (?, '', 'snapshot', ?, 'SELECT 1;', 1);`, name, teamID, )) diff --git a/server/datastore/mysql/migrations/tables/20240626195531_AddTimezoneToCalendarEvents_test.go b/server/datastore/mysql/migrations/tables/20240626195531_AddTimezoneToCalendarEvents_test.go index 58920d69b1..ee5d771d78 100644 --- a/server/datastore/mysql/migrations/tables/20240626195531_AddTimezoneToCalendarEvents_test.go +++ b/server/datastore/mysql/migrations/tables/20240626195531_AddTimezoneToCalendarEvents_test.go @@ -18,7 +18,7 @@ func TestUp_20240626195531(t *testing.T) { EndTime: time.Now().UTC().Add(30 * time.Minute), Data: []byte("{\"foo\": \"bar\"}"), } - sampleEvent.ID = uint(execNoErrLastID(t, db, + sampleEvent.ID = uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO calendar_events (email, start_time, end_time, event) VALUES (?, ?, ?, ?);`, sampleEvent.Email, sampleEvent.StartTime, sampleEvent.EndTime, sampleEvent.Data, )) @@ -28,7 +28,7 @@ func TestUp_20240626195531(t *testing.T) { CalendarEventID: sampleEvent.ID, WebhookStatus: fleet.CalendarWebhookStatusPending, } - sampleHostEvent.ID = uint(execNoErrLastID(t, db, + sampleHostEvent.ID = uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO host_calendar_events (host_id, calendar_event_id, webhook_status) VALUES (?, ?, ?);`, sampleHostEvent.HostID, sampleHostEvent.CalendarEventID, sampleHostEvent.WebhookStatus, )) diff --git a/server/datastore/mysql/migrations/tables/20240707134035_AddUUIDToCalendarEvents_test.go b/server/datastore/mysql/migrations/tables/20240707134035_AddUUIDToCalendarEvents_test.go index 4372053c53..b72c0c8882 100644 --- a/server/datastore/mysql/migrations/tables/20240707134035_AddUUIDToCalendarEvents_test.go +++ b/server/datastore/mysql/migrations/tables/20240707134035_AddUUIDToCalendarEvents_test.go @@ -15,8 +15,8 @@ func TestUp_20240707134035(t *testing.T) { endTime := time.Now().UTC().Add(30 * time.Minute) data := []byte("{\"foo\": \"bar\"}") const insertStmt = `INSERT INTO calendar_events (email, start_time, end_time, event) VALUES (?, ?, ?, ?)` - event1ID := uint(execNoErrLastID(t, db, insertStmt, "foo@example.com", startTime, endTime, data)) - event2ID := uint(execNoErrLastID(t, db, insertStmt, "bar@example.com", startTime, endTime, data)) + event1ID := uint(execNoErrLastID(t, db, insertStmt, "foo@example.com", startTime, endTime, data)) //nolint:gosec // dismiss G115 + event2ID := uint(execNoErrLastID(t, db, insertStmt, "bar@example.com", startTime, endTime, data)) //nolint:gosec // dismiss G115 // Apply current migration. applyNext(t, db) diff --git a/server/datastore/mysql/migrations/tables/20240707134036_CreateIOSAndIPADOSBuiltinLabels.go b/server/datastore/mysql/migrations/tables/20240707134036_CreateIOSAndIPADOSBuiltinLabels.go index 70c8dcb129..b7dc6b4fa4 100644 --- a/server/datastore/mysql/migrations/tables/20240707134036_CreateIOSAndIPADOSBuiltinLabels.go +++ b/server/datastore/mysql/migrations/tables/20240707134036_CreateIOSAndIPADOSBuiltinLabels.go @@ -101,9 +101,9 @@ func createBuiltinManualIOSAndIPadOSLabels(tx *sql.Tx) (iOSLabelID uint, iPadOSL } labelID, _ := res.LastInsertId() if label.name == fleet.BuiltinLabelIOS { - iOSLabelID = uint(labelID) + iOSLabelID = uint(labelID) //nolint:gosec // dismiss G115 } else { - iPadOSLabelID = uint(labelID) + iPadOSLabelID = uint(labelID) //nolint:gosec // dismiss G115 } } return iOSLabelID, iPadOSLabelID, nil diff --git a/server/datastore/mysql/migrations/tables/20240707134036_CreateIOSAndIPADOSBuiltinLabels_test.go b/server/datastore/mysql/migrations/tables/20240707134036_CreateIOSAndIPADOSBuiltinLabels_test.go index c24ed8e1f9..aa273aa6a4 100644 --- a/server/datastore/mysql/migrations/tables/20240707134036_CreateIOSAndIPADOSBuiltinLabels_test.go +++ b/server/datastore/mysql/migrations/tables/20240707134036_CreateIOSAndIPADOSBuiltinLabels_test.go @@ -16,7 +16,7 @@ func TestUp_20240707134036(t *testing.T) { newHost := func(platform, uuid string) uint { id := fmt.Sprintf("%d", hostID) hostID++ - return uint(execNoErrLastID(t, db, + return uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO hosts (osquery_host_id, node_key, uuid, platform) VALUES (?, ?, ?, ?);`, id, id, uuid, platform, )) diff --git a/server/datastore/mysql/migrations/tables/20240710155623_FixResetLastEnrolledAt_test.go b/server/datastore/mysql/migrations/tables/20240710155623_FixResetLastEnrolledAt_test.go index 275933b033..5b16d209d7 100644 --- a/server/datastore/mysql/migrations/tables/20240710155623_FixResetLastEnrolledAt_test.go +++ b/server/datastore/mysql/migrations/tables/20240710155623_FixResetLastEnrolledAt_test.go @@ -15,7 +15,7 @@ func TestUp_20240710155623(t *testing.T) { newHost := func(platform, lastEnrolledAt string, hostDisk bool) uint { id := fmt.Sprintf("%d", i) i++ - hostID := uint(execNoErrLastID(t, db, + hostID := uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO hosts (osquery_host_id, node_key, uuid, platform, last_enrolled_at) VALUES (?, ?, ?, ?, ?);`, id, id, id, platform, lastEnrolledAt, )) diff --git a/server/datastore/mysql/migrations/tables/20240730174056_AddGlobalStatToSoftwareHostCounts_test.go b/server/datastore/mysql/migrations/tables/20240730174056_AddGlobalStatToSoftwareHostCounts_test.go index 61c0e9d386..821b05a947 100644 --- a/server/datastore/mysql/migrations/tables/20240730174056_AddGlobalStatToSoftwareHostCounts_test.go +++ b/server/datastore/mysql/migrations/tables/20240730174056_AddGlobalStatToSoftwareHostCounts_test.go @@ -56,7 +56,7 @@ func TestUp_20240730174056(t *testing.T) { res := db.QueryRow("SELECT `software_id`, `hosts_count`, `team_id`, `global_stats` FROM `software_host_counts` WHERE `software_id` = ? AND `team_id` = ? AND global_stats = ?", softwareID, teamID, globalStats) err = res.Scan(&result.SoftwareID, &result.HostsCount, &result.TeamID, &result.GlobalStats) require.NoError(t, err) - require.Equal(t, softwareID, int(result.SoftwareID)) + require.EqualValues(t, softwareID, result.SoftwareID) require.Equal(t, hostsCount, result.HostsCount) require.Equal(t, teamID, result.TeamID) require.Equal(t, globalStats, result.GlobalStats) diff --git a/server/datastore/mysql/migrations/tables/20240730215453_AddGlobalStatToSoftwareTitleHostCounts_test.go b/server/datastore/mysql/migrations/tables/20240730215453_AddGlobalStatToSoftwareTitleHostCounts_test.go index 050f5a82e6..3d906bc475 100644 --- a/server/datastore/mysql/migrations/tables/20240730215453_AddGlobalStatToSoftwareTitleHostCounts_test.go +++ b/server/datastore/mysql/migrations/tables/20240730215453_AddGlobalStatToSoftwareTitleHostCounts_test.go @@ -56,7 +56,7 @@ func TestUp_20240730215453(t *testing.T) { res := db.QueryRow("SELECT `software_title_id`, `hosts_count`, `team_id`, `global_stats` FROM `software_titles_host_counts` WHERE `software_title_id` = ? AND `team_id` = ? AND global_stats = ?", softwareID, teamID, globalStats) err = res.Scan(&result.SoftwareID, &result.HostsCount, &result.TeamID, &result.GlobalStats) require.NoError(t, err) - require.Equal(t, softwareID, int(result.SoftwareID)) + require.EqualValues(t, softwareID, result.SoftwareID) require.Equal(t, hostsCount, result.HostsCount) require.Equal(t, teamID, result.TeamID) require.Equal(t, globalStats, result.GlobalStats) diff --git a/server/datastore/mysql/migrations/tables/20240829165448_SupportMultipleABMTokens_test.go b/server/datastore/mysql/migrations/tables/20240829165448_SupportMultipleABMTokens_test.go index 07804074fd..8ee788b781 100644 --- a/server/datastore/mysql/migrations/tables/20240829165448_SupportMultipleABMTokens_test.go +++ b/server/datastore/mysql/migrations/tables/20240829165448_SupportMultipleABMTokens_test.go @@ -72,7 +72,7 @@ func TestUp_20240829165448(t *testing.T) { tmID := execNoErrLastID(t, db, `INSERT INTO teams (name) VALUES (?)`, "team1") // create a host with a DEP assignment - hostID := insertHost(t, db, ptr.Uint(uint(tmID))) + hostID := insertHost(t, db, ptr.Uint(uint(tmID))) //nolint:gosec // dismiss G115 execNoErr(t, db, `INSERT INTO host_dep_assignments (host_id) VALUES (?)`, hostID) // Apply current migration. @@ -132,7 +132,7 @@ LIMIT 1`) tmID := execNoErrLastID(t, db, `INSERT INTO teams (name) VALUES (?)`, "team1") // create a host with a DEP assignment - hostID := insertHost(t, db, ptr.Uint(uint(tmID))) + hostID := insertHost(t, db, ptr.Uint(uint(tmID))) //nolint:gosec // dismiss G115 execNoErr(t, db, `INSERT INTO host_dep_assignments (host_id) VALUES (?)`, hostID) // Apply current migration. diff --git a/server/datastore/mysql/migrations/tables/20240905200001_AddPoliciesToNoTeam_test.go b/server/datastore/mysql/migrations/tables/20240905200001_AddPoliciesToNoTeam_test.go index 90a2495ea5..4c7675b60f 100644 --- a/server/datastore/mysql/migrations/tables/20240905200001_AddPoliciesToNoTeam_test.go +++ b/server/datastore/mysql/migrations/tables/20240905200001_AddPoliciesToNoTeam_test.go @@ -10,12 +10,12 @@ import ( func TestUp_20240905200001(t *testing.T) { db := applyUpToPrev(t) - team1ID := uint(execNoErrLastID(t, db, `INSERT INTO teams (name) VALUES ('team1');`)) - globalPolicy0 := uint(execNoErrLastID(t, db, + team1ID := uint(execNoErrLastID(t, db, `INSERT INTO teams (name) VALUES ('team1');`)) //nolint:gosec // dismiss G115 + globalPolicy0 := uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO policies (name, query, description, checksum) VALUES ('globalPolicy0', 'SELECT 0', 'Description', 'checksum');`, )) - policy1Team1 := uint(execNoErrLastID(t, db, + policy1Team1 := uint(execNoErrLastID(t, db, //nolint:gosec // dismiss G115 `INSERT INTO policies (name, query, description, team_id, checksum) VALUES ('policy1Team1', 'SELECT 1', 'Description', ?, 'checksum2');`, team1ID, diff --git a/server/datastore/mysql/migrations/tables/20241002104104_UpdateUninstallScript.go b/server/datastore/mysql/migrations/tables/20241002104104_UpdateUninstallScript.go index 99b6dac45e..ffaf297047 100644 --- a/server/datastore/mysql/migrations/tables/20241002104104_UpdateUninstallScript.go +++ b/server/datastore/mysql/migrations/tables/20241002104104_UpdateUninstallScript.go @@ -80,7 +80,7 @@ ON DUPLICATE KEY UPDATE return 0, fmt.Errorf("get last insert ID: %w", err) } - return uint(newID), nil + return uint(newID), nil //nolint:gosec // dismiss G115 } // Go to script contents and check if it is the default uninstall script diff --git a/server/datastore/mysql/migrations/tables/deprecated_types.go b/server/datastore/mysql/migrations/tables/deprecated_types.go index 9a7bc9cd44..5d2fba492b 100644 --- a/server/datastore/mysql/migrations/tables/deprecated_types.go +++ b/server/datastore/mysql/migrations/tables/deprecated_types.go @@ -90,8 +90,7 @@ func (ov *optionValue) Scan(src interface{}) error { if err := json.Unmarshal(src.([]byte), &ov.Val); err != nil { return err } - switch v := ov.Val.(type) { - case float64: + if v, ok := ov.Val.(float64); ok { ov.Val = int(v) } return nil diff --git a/server/datastore/mysql/migrations/tables/migration_test.go b/server/datastore/mysql/migrations/tables/migration_test.go index 6ea84ec50c..3a85481300 100644 --- a/server/datastore/mysql/migrations/tables/migration_test.go +++ b/server/datastore/mysql/migrations/tables/migration_test.go @@ -151,7 +151,7 @@ func insertQuery(t *testing.T, db *sqlx.DB) uint { id, err := res.LastInsertId() require.NoError(t, err) - return uint(id) + return uint(id) //nolint:gosec // dismiss G115 } func insertHost(t *testing.T, db *sqlx.DB, teamID *uint) uint { @@ -187,7 +187,7 @@ func insertHost(t *testing.T, db *sqlx.DB, teamID *uint) uint { id, err := res.LastInsertId() require.NoError(t, err) - return uint(id) + return uint(id) //nolint:gosec // dismiss G115 } func assertRowCount(t *testing.T, db *sqlx.DB, table string, count int) { diff --git a/server/datastore/mysql/mysql.go b/server/datastore/mysql/mysql.go index 3acfa46f63..ac7c9d976a 100644 --- a/server/datastore/mysql/mysql.go +++ b/server/datastore/mysql/mysql.go @@ -886,7 +886,7 @@ func (ds *Datastore) whereFilterHostsByTeams(filter fleet.TeamFilter, hostKey st team.Role == fleet.RoleMaintainer || team.Role == fleet.RoleObserverPlus || (team.Role == fleet.RoleObserver && filter.IncludeObserver) { - idStrs = append(idStrs, strconv.Itoa(int(team.ID))) + idStrs = append(idStrs, fmt.Sprint(team.ID)) if filter.TeamID != nil && *filter.TeamID == team.ID { teamIDSeen = true } @@ -962,7 +962,7 @@ func (ds *Datastore) whereFilterGlobalOrTeamIDByTeamsWithSqlFilter( team.Role == fleet.RoleMaintainer || team.Role == fleet.RoleObserverPlus || (team.Role == fleet.RoleObserver && filter.IncludeObserver) { - idStrs = append(idStrs, strconv.Itoa(int(team.ID))) + idStrs = append(idStrs, fmt.Sprint(team.ID)) if filter.TeamID != nil && *filter.TeamID == team.ID { teamIDSeen = true } @@ -1021,7 +1021,7 @@ func (ds *Datastore) whereFilterTeams(filter fleet.TeamFilter, teamKey string) s team.Role == fleet.RoleGitOps || team.Role == fleet.RoleObserverPlus || (team.Role == fleet.RoleObserver && filter.IncludeObserver) { - idStrs = append(idStrs, strconv.Itoa(int(team.ID))) + idStrs = append(idStrs, fmt.Sprint(team.ID)) } } @@ -1042,7 +1042,7 @@ func (ds *Datastore) whereOmitIDs(colName string, omit []uint) string { var idStrs []string for _, id := range omit { - idStrs = append(idStrs, strconv.Itoa(int(id))) + idStrs = append(idStrs, fmt.Sprint(id)) } return fmt.Sprintf("%s NOT IN (%s)", colName, strings.Join(idStrs, ",")) @@ -1132,8 +1132,8 @@ type patternReplacer func(string) string // likePattern returns a pattern to match m with LIKE. func likePattern(m string) string { - m = strings.Replace(m, "_", "\\_", -1) - m = strings.Replace(m, "%", "\\%", -1) + m = strings.ReplaceAll(m, "_", "\\_") + m = strings.ReplaceAll(m, "%", "\\%") return "%" + m + "%" } @@ -1322,7 +1322,7 @@ func (ds *Datastore) optimisticGetOrInsertWithWriter(ctx context.Context, writer return 0, ctxerr.Wrap(ctx, err, "insert") } id, _ := res.LastInsertId() - return uint(id), nil + return uint(id), nil //nolint:gosec // dismiss G115 } return 0, ctxerr.Wrap(ctx, err, "get id from reader") } diff --git a/server/datastore/mysql/operating_systems_test.go b/server/datastore/mysql/operating_systems_test.go index 5819d269a7..d67b726178 100644 --- a/server/datastore/mysql/operating_systems_test.go +++ b/server/datastore/mysql/operating_systems_test.go @@ -160,7 +160,7 @@ func TestUniqueOS(t *testing.T) { for i := range testHostIDs { wg.Add(1) go func(id int) { - err := ds.UpdateHostOperatingSystem(ctx, uint(id), testOS) + err := ds.UpdateHostOperatingSystem(ctx, uint(id), testOS) //nolint:gosec // dismiss G115 assert.NoError(t, err) wg.Done() }(i) diff --git a/server/datastore/mysql/packs.go b/server/datastore/mysql/packs.go index b89922c737..cb1cf9142e 100644 --- a/server/datastore/mysql/packs.go +++ b/server/datastore/mysql/packs.go @@ -272,7 +272,7 @@ func (ds *Datastore) NewPack(ctx context.Context, pack *fleet.Pack, opts ...flee } id, _ := result.LastInsertId() - pack.ID = uint(id) + pack.ID = uint(id) //nolint:gosec // dismiss G115 if err := replacePackTargetsDB(ctx, tx, pack); err != nil { return err diff --git a/server/datastore/mysql/password_reset.go b/server/datastore/mysql/password_reset.go index 0728eb5dcb..4edd3f3951 100644 --- a/server/datastore/mysql/password_reset.go +++ b/server/datastore/mysql/password_reset.go @@ -25,7 +25,7 @@ func (ds *Datastore) NewPasswordResetRequest(ctx context.Context, req *fleet.Pas } id, _ := response.LastInsertId() - req.ID = uint(id) + req.ID = uint(id) //nolint:gosec // dismiss G115 return req, nil } diff --git a/server/datastore/mysql/password_reset_test.go b/server/datastore/mysql/password_reset_test.go index d8acfd43c5..2427c32544 100644 --- a/server/datastore/mysql/password_reset_test.go +++ b/server/datastore/mysql/password_reset_test.go @@ -95,7 +95,7 @@ func testPasswordResetTokenExpiration(t *testing.T, ds *Datastore) { require.NoError(t, err) id, _ := res.LastInsertId() - req.ID = uint(id) + req.ID = uint(id) //nolint:gosec // dismiss G115 found, err := ds.FindPasswordResetByToken(context.Background(), req.Token) diff --git a/server/datastore/mysql/policies.go b/server/datastore/mysql/policies.go index 20340f1683..a174d1bd38 100644 --- a/server/datastore/mysql/policies.go +++ b/server/datastore/mysql/policies.go @@ -70,7 +70,7 @@ func (ds *Datastore) NewGlobalPolicy(ctx context.Context, authorID *uint, args f if err != nil { return nil, ctxerr.Wrap(ctx, err, "getting last id after inserting policy") } - return policyDB(ctx, ds.writer(ctx), uint(lastIdInt64), nil) + return policyDB(ctx, ds.writer(ctx), uint(lastIdInt64), nil) //nolint:gosec // dismiss G115 } func policiesChecksumComputedColumn() string { @@ -461,7 +461,7 @@ func listPoliciesDB(ctx context.Context, q sqlx.QueryerContext, teamID *uint, op // getInheritedPoliciesForTeam returns the list of global policies with the // passing and failing host counts for the provided teamID -func getInheritedPoliciesForTeam(ctx context.Context, q sqlx.QueryerContext, TeamID uint, opts fleet.ListOptions) ([]*fleet.Policy, error) { +func getInheritedPoliciesForTeam(ctx context.Context, q sqlx.QueryerContext, teamID uint, opts fleet.ListOptions) ([]*fleet.Policy, error) { var args []interface{} query := ` @@ -478,7 +478,7 @@ func getInheritedPoliciesForTeam(ctx context.Context, q sqlx.QueryerContext, Tea WHERE p.team_id IS NULL ` - args = append(args, TeamID) + args = append(args, teamID) // We must normalize the name for full Unicode support (Unicode equivalence). match := norm.NFC.String(opts.MatchQuery) @@ -685,7 +685,7 @@ func (ds *Datastore) NewTeamPolicy(ctx context.Context, teamID uint, authorID *u if err != nil { return nil, ctxerr.Wrap(ctx, err, "getting last id after inserting policy") } - return policyDB(ctx, ds.writer(ctx), uint(lastIdInt64), &teamID) + return policyDB(ctx, ds.writer(ctx), uint(lastIdInt64), &teamID) //nolint:gosec // dismiss G115 } func (ds *Datastore) ListTeamPolicies(ctx context.Context, teamID uint, opts fleet.ListOptions, iopts fleet.ListOptions) (teamPolicies, inheritedPolicies []*fleet.Policy, err error) { @@ -931,7 +931,8 @@ func (ds *Datastore) ApplyPolicySpecs(ctx context.Context, authorID uint, specs } } if err = cleanupPolicy( - ctx, tx, tx, uint(lastID), spec.Platform, shouldRemoveAllPolicyMemberships, removePolicyStats, ds.logger, + ctx, tx, tx, uint(lastID), spec.Platform, shouldRemoveAllPolicyMemberships, //nolint:gosec // dismiss G115 + removePolicyStats, ds.logger, ); err != nil { return err } @@ -1422,7 +1423,7 @@ func amountPolicyViolationDaysDB(ctx context.Context, tx sqlx.QueryerContext) (i return 0, 0, ctxerr.Wrap(ctx, err, "unmarshal policy violation counts") } - return int(counts.FailingHostCount), int(counts.TotalHostCount), nil + return int(counts.FailingHostCount), int(counts.TotalHostCount), nil //nolint:gosec // dismiss G115 } func (ds *Datastore) UpdateHostPolicyCounts(ctx context.Context) error { diff --git a/server/datastore/mysql/policies_test.go b/server/datastore/mysql/policies_test.go index e93175f5d2..3c943110ec 100644 --- a/server/datastore/mysql/policies_test.go +++ b/server/datastore/mysql/policies_test.go @@ -889,7 +889,7 @@ type expectedPolicyResults struct { func expectedPolicyQueries(policies ...*fleet.Policy) expectedPolicyResults { queries := make(map[string]string) for _, policy := range policies { - queries[strconv.Itoa(int(policy.ID))] = policy.Query + queries[fmt.Sprint(policy.ID)] = policy.Query } hostPolicies := make([]*fleet.HostPolicy, len(policies)) for i := range policies { @@ -1208,7 +1208,9 @@ func testPolicyQueriesForHost(t *testing.T, ds *Datastore) { require.NoError(t, err) id, err := res.LastInsertId() require.NoError(t, err) - require.NoError(t, ds.RecordPolicyQueryExecutions(context.Background(), host2, map[uint]*bool{uint(id): nil}, time.Now(), false)) + require.NoError(t, + ds.RecordPolicyQueryExecutions(context.Background(), host2, map[uint]*bool{uint(id): nil}, //nolint:gosec // dismiss G115 + time.Now(), false)) policies, err = ds.ListPoliciesForHost(context.Background(), host2) require.NoError(t, err) @@ -2633,7 +2635,7 @@ func testPolicyViolationDays(t *testing.T, ds *Datastore) { res, err := ds.writer(ctx).ExecContext(ctx, createPolStmt, "test_pol", "select 1", user.ID, "", then, then) require.NoError(t, err) id, _ := res.LastInsertId() - pol, err := ds.Policy(ctx, uint(id)) + pol, err := ds.Policy(ctx, uint(id)) //nolint:gosec // dismiss G115 require.NoError(t, err) require.NoError(t, ds.InitializePolicyViolationDays(ctx)) // sets starting violation count to zero @@ -2739,7 +2741,7 @@ func testPolicyCleanupPolicyMembership(t *testing.T, ds *Datastore) { res, err := ds.writer(ctx).ExecContext(ctx, createPolStmt, "p"+strconv.Itoa(i+1), "select 1", user.ID, "", dt, dt) require.NoError(t, err) id, _ := res.LastInsertId() - pol, err := ds.Policy(ctx, uint(id)) + pol, err := ds.Policy(ctx, uint(id)) //nolint:gosec // dismiss G115 require.NoError(t, err) pols[i] = pol } diff --git a/server/datastore/mysql/queries.go b/server/datastore/mysql/queries.go index c52e33eacf..e2cecd201d 100644 --- a/server/datastore/mysql/queries.go +++ b/server/datastore/mysql/queries.go @@ -241,7 +241,7 @@ func (ds *Datastore) NewQuery( } id, _ := result.LastInsertId() - query.ID = uint(id) + query.ID = uint(id) //nolint:gosec // dismiss G115 query.Packs = []fleet.Pack{} return query, nil } diff --git a/server/datastore/mysql/scheduled_queries.go b/server/datastore/mysql/scheduled_queries.go index 8fb85a4f57..1b36f70753 100644 --- a/server/datastore/mysql/scheduled_queries.go +++ b/server/datastore/mysql/scheduled_queries.go @@ -113,7 +113,7 @@ func insertScheduledQueryDB(ctx context.Context, q sqlx.ExtContext, sq *fleet.Sc } id, _ := result.LastInsertId() - sq.ID = uint(id) + sq.ID = uint(id) //nolint:gosec // dismiss G115 query = `SELECT query, name FROM queries WHERE id = ? LIMIT 1` metadata := []struct { diff --git a/server/datastore/mysql/scripts.go b/server/datastore/mysql/scripts.go index bc23f3b13b..68ddf4d128 100644 --- a/server/datastore/mysql/scripts.go +++ b/server/datastore/mysql/scripts.go @@ -30,7 +30,7 @@ func (ds *Datastore) NewHostScriptExecutionRequest(ctx context.Context, request } id, _ := scRes.LastInsertId() - request.ScriptContentID = uint(id) + request.ScriptContentID = uint(id) //nolint:gosec // dismiss G115 } res, err = newHostScriptExecutionRequest(ctx, tx, request) return err @@ -148,7 +148,7 @@ func (ds *Datastore) SetHostScriptExecutionResult(ctx context.Context, result *f // software that receives them is responsible for casting // it to a 32-bit signed integer. // See /orbit/pkg/scripts/exec_windows.go - int32(result.ExitCode), + int32(result.ExitCode), //nolint:gosec // dismiss G115 result.Timeout, result.HostID, result.ExecutionID, @@ -303,14 +303,14 @@ func (ds *Datastore) NewScript(ctx context.Context, script *fleet.Script) (*flee id, _ := scRes.LastInsertId() // then create the script entity - res, err = insertScript(ctx, tx, script, uint(id)) + res, err = insertScript(ctx, tx, script, uint(id)) //nolint:gosec // dismiss G115 return err }) if err != nil { return nil, err } id, _ := res.LastInsertId() - return ds.getScriptDB(ctx, ds.writer(ctx), uint(id)) + return ds.getScriptDB(ctx, ds.writer(ctx), uint(id)) //nolint:gosec // dismiss G115 } func insertScript(ctx context.Context, tx sqlx.ExtContext, script *fleet.Script, scriptContentsID uint) (sql.Result, error) { @@ -488,7 +488,7 @@ WHERE var metaData *fleet.PaginationMetadata if opt.IncludeMetadata { metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0} - if len(scripts) > int(opt.PerPage) { + if len(scripts) > int(opt.PerPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true scripts = scripts[:len(scripts)-1] } @@ -605,7 +605,7 @@ WHERE var metaData *fleet.PaginationMetadata if opt.IncludeMetadata { metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.Page > 0} - if len(rows) > int(opt.PerPage) { + if len(rows) > int(opt.PerPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true rows = rows[:len(rows)-1] } @@ -742,7 +742,8 @@ ON DUPLICATE KEY UPDATE return ctxerr.Wrapf(ctx, err, "inserting script contents for script with name %q", s.Name) } id, _ := scRes.LastInsertId() - if _, err := tx.ExecContext(ctx, insertNewOrEditedScript, tmID, globalOrTeamID, s.Name, uint(id)); err != nil { + if _, err := tx.ExecContext(ctx, insertNewOrEditedScript, tmID, globalOrTeamID, s.Name, + uint(id)); err != nil { //nolint:gosec // dismiss G115 return ctxerr.Wrapf(ctx, err, "insert new/edited script with name %q", s.Name) } } @@ -952,7 +953,7 @@ func (ds *Datastore) LockHostViaScript(ctx context.Context, request *fleet.HostS } id, _ := scRes.LastInsertId() - request.ScriptContentID = uint(id) + request.ScriptContentID = uint(id) //nolint:gosec // dismiss G115 res, err = newHostScriptExecutionRequest(ctx, tx, request) if err != nil { @@ -1002,7 +1003,7 @@ func (ds *Datastore) UnlockHostViaScript(ctx context.Context, request *fleet.Hos } id, _ := scRes.LastInsertId() - request.ScriptContentID = uint(id) + request.ScriptContentID = uint(id) //nolint:gosec // dismiss G115 res, err = newHostScriptExecutionRequest(ctx, tx, request) if err != nil { @@ -1053,7 +1054,7 @@ func (ds *Datastore) WipeHostViaScript(ctx context.Context, request *fleet.HostS } id, _ := scRes.LastInsertId() - request.ScriptContentID = uint(id) + request.ScriptContentID = uint(id) //nolint:gosec // dismiss G115 res, err = newHostScriptExecutionRequest(ctx, tx, request) if err != nil { diff --git a/server/datastore/mysql/scripts_test.go b/server/datastore/mysql/scripts_test.go index 251d2092ed..eb7d266e0a 100644 --- a/server/datastore/mysql/scripts_test.go +++ b/server/datastore/mysql/scripts_test.go @@ -924,7 +924,7 @@ func testLockUnlockWipeViaScripts(t *testing.T, ds *Datastore) { user := test.NewUser(t, ds, "Bob", "bob@example.com", true) for i, platform := range []string{"windows", "linux"} { - hostID := uint(i + 1) + hostID := uint(i + 1) //nolint:gosec // dismiss G115 t.Run(platform, func(t *testing.T) { status, err := ds.GetHostLockWipeStatus(ctx, &fleet.Host{ID: hostID, Platform: platform, UUID: "uuid"}) @@ -1203,7 +1203,7 @@ func testInsertScriptContents(t *testing.T, ds *Datastore) { require.NoError(t, err) require.Len(t, sc, 1) - require.Equal(t, uint(id), sc[0].ID) + require.EqualValues(t, id, sc[0].ID) require.Equal(t, expectedCS, sc[0].Checksum) } @@ -1324,7 +1324,7 @@ func testGetAnyScriptContents(t *testing.T, ds *Datastore) { require.NoError(t, err) id, _ := res.LastInsertId() - result, err := ds.GetAnyScriptContents(ctx, uint(id)) + result, err := ds.GetAnyScriptContents(ctx, uint(id)) //nolint:gosec // dismiss G115 require.NoError(t, err) require.Equal(t, contents, string(result)) } diff --git a/server/datastore/mysql/sessions.go b/server/datastore/mysql/sessions.go index 6acb1ca3d8..47bd93978a 100644 --- a/server/datastore/mysql/sessions.go +++ b/server/datastore/mysql/sessions.go @@ -81,8 +81,8 @@ func (ds *Datastore) NewSession(ctx context.Context, userID uint, sessionKey str return nil, ctxerr.Wrap(ctx, err, "inserting session") } - id, _ := result.LastInsertId() // cannot fail with the mysql driver - return ds.sessionByID(ctx, ds.writer(ctx), uint(id)) + id, _ := result.LastInsertId() // cannot fail with the mysql driver + return ds.sessionByID(ctx, ds.writer(ctx), uint(id)) //nolint:gosec // dismiss G115 } func (ds *Datastore) DestroySession(ctx context.Context, session *fleet.Session) error { diff --git a/server/datastore/mysql/software.go b/server/datastore/mysql/software.go index ff9315eb16..1dd06848ba 100644 --- a/server/datastore/mysql/software.go +++ b/server/datastore/mysql/software.go @@ -1014,7 +1014,7 @@ func selectSoftwareSQL(opts fleet.SoftwareListOptions) (string, []interface{}, e "shc.team_id", ) - if opts.TeamID == nil { + if opts.TeamID == nil { //nolint:gocritic // ignore ifElseChain ds = ds.Where( goqu.And( goqu.I("shc.team_id").Eq(0), @@ -1413,7 +1413,7 @@ func (ds *Datastore) ListSoftware(ctx context.Context, opt fleet.SoftwareListOpt perPage = defaultSelectLimit } metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.ListOptions.Page > 0} - if len(software) > int(perPage) { + if len(software) > int(perPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true software = software[:len(software)-1] } @@ -2623,7 +2623,7 @@ INNER JOIN software_cve scve ON scve.software_id = s.id HasPreviousResults: opts.ListOptions.Page > 0, TotalResults: titleCount, } - if len(hostSoftwareList) > int(perPage) { + if len(hostSoftwareList) > int(perPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true hostSoftwareList = hostSoftwareList[:len(hostSoftwareList)-1] } diff --git a/server/datastore/mysql/software_installers.go b/server/datastore/mysql/software_installers.go index d41a44d226..7a93ff539f 100644 --- a/server/datastore/mysql/software_installers.go +++ b/server/datastore/mysql/software_installers.go @@ -166,7 +166,7 @@ INSERT INTO software_installers ( id, _ := res.LastInsertId() - return uint(id), nil + return uint(id), nil //nolint:gosec // dismiss G115 } func (ds *Datastore) getOrGenerateSoftwareInstallerTitleID(ctx context.Context, payload *fleet.UploadSoftwareInstallerPayload) (uint, error) { diff --git a/server/datastore/mysql/software_test.go b/server/datastore/mysql/software_test.go index 8a21f4a819..cc9e7ddd86 100644 --- a/server/datastore/mysql/software_test.go +++ b/server/datastore/mysql/software_test.go @@ -1751,7 +1751,7 @@ func testUpdateHostSoftware(t *testing.T, ds *Datastore) { case lts != nil && rts == nil: return false default: - return (*lts).Before(*rts) || ((*lts).Equal(*rts) && lsw.Name < rsw.Name) + return lts.Before(*rts) || (lts.Equal(*rts) && lsw.Name < rsw.Name) } } } @@ -1972,7 +1972,7 @@ func testInsertSoftwareVulnerability(t *testing.T, ds *Datastore) { occurrence := make(map[string]int) for _, v := range storedVulns[host.ID] { - occurrence[v.CVE] = occurrence[v.CVE] + 1 + occurrence[v.CVE]++ } require.Equal(t, 1, occurrence["cve-1"]) }) @@ -2016,7 +2016,7 @@ func testInsertSoftwareVulnerability(t *testing.T, ds *Datastore) { occurrence := make(map[string]int) for _, v := range storedVulns[host.ID] { - occurrence[v.CVE] = occurrence[v.CVE] + 1 + occurrence[v.CVE]++ } require.Equal(t, 1, occurrence["cve-1"]) require.Equal(t, 1, occurrence["cve-2"]) diff --git a/server/datastore/mysql/software_titles.go b/server/datastore/mysql/software_titles.go index b4e2bb6e60..e62cb4d7a7 100644 --- a/server/datastore/mysql/software_titles.go +++ b/server/datastore/mysql/software_titles.go @@ -204,7 +204,7 @@ func (ds *Datastore) ListSoftwareTitles( var metaData *fleet.PaginationMetadata if opt.ListOptions.IncludeMetadata { metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.ListOptions.Page > 0} - if len(softwareList) > int(opt.ListOptions.PerPage) { + if len(softwareList) > int(opt.ListOptions.PerPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true softwareList = softwareList[:len(softwareList)-1] } diff --git a/server/datastore/mysql/targets.go b/server/datastore/mysql/targets.go index cbb244acb7..dfc4865806 100644 --- a/server/datastore/mysql/targets.go +++ b/server/datastore/mysql/targets.go @@ -95,11 +95,11 @@ func targetSQLCondAndArgs(targets fleet.HostTargets) (sql string, args []interfa // all situations (no need to remove the clause when there are no values) queryLabelIDs := []int{-1} for _, id := range targets.LabelIDs { - queryLabelIDs = append(queryLabelIDs, int(id)) + queryLabelIDs = append(queryLabelIDs, int(id)) //nolint:gosec // dismiss G115 } queryHostIDs := []int{-1} for _, id := range targets.HostIDs { - queryHostIDs = append(queryHostIDs, int(id)) + queryHostIDs = append(queryHostIDs, int(id)) //nolint:gosec // dismiss G115 } queryTeamIDs := []int{-1} extraTeamIDCondition := "" @@ -108,7 +108,7 @@ func targetSQLCondAndArgs(targets fleet.HostTargets) (sql string, args []interfa extraTeamIDCondition = "OR team_id IS NULL" continue } - queryTeamIDs = append(queryTeamIDs, int(id)) + queryTeamIDs = append(queryTeamIDs, int(id)) //nolint:gosec // dismiss G115 } labelsSpecified := len(queryLabelIDs) > 1 diff --git a/server/datastore/mysql/targets_test.go b/server/datastore/mysql/targets_test.go index f58e8085e0..3d6a4d77ce 100644 --- a/server/datastore/mysql/targets_test.go +++ b/server/datastore/mysql/targets_test.go @@ -730,7 +730,7 @@ func testTargetsHostIDsInTargets(t *testing.T, ds *Datastore) { metrics, err := ds.CountHostsInTargets(context.Background(), filter, targets, time.Now()) require.NoError(t, err) - require.Len(t, tc.expectedHostIDs, int(metrics.TotalHosts)) + require.Len(t, tc.expectedHostIDs, int(metrics.TotalHosts)) //nolint:gosec // dismiss G115 }) } diff --git a/server/datastore/mysql/teams.go b/server/datastore/mysql/teams.go index da012174e7..568efeaf70 100644 --- a/server/datastore/mysql/teams.go +++ b/server/datastore/mysql/teams.go @@ -45,7 +45,7 @@ func (ds *Datastore) NewTeam(ctx context.Context, team *fleet.Team) (*fleet.Team } id, _ := result.LastInsertId() - team.ID = uint(id) + team.ID = uint(id) //nolint:gosec // dismiss G115 return saveTeamSecretsDB(ctx, tx, team) }) diff --git a/server/datastore/mysql/users.go b/server/datastore/mysql/users.go index 1cd04c0da7..a2ec851640 100644 --- a/server/datastore/mysql/users.go +++ b/server/datastore/mysql/users.go @@ -56,7 +56,7 @@ func (ds *Datastore) NewUser(ctx context.Context, user *fleet.User) (*fleet.User } id, _ := result.LastInsertId() - user.ID = uint(id) + user.ID = uint(id) //nolint:gosec // dismiss G115 if err := saveTeamsForUserDB(ctx, tx, user); err != nil { return err diff --git a/server/datastore/mysql/vpp.go b/server/datastore/mysql/vpp.go index cecb68ab38..a53fb79b9f 100644 --- a/server/datastore/mysql/vpp.go +++ b/server/datastore/mysql/vpp.go @@ -630,7 +630,7 @@ func (ds *Datastore) InsertVPPToken(ctx context.Context, tok *fleet.VPPTokenData id, _ := res.LastInsertId() - vppTokenDB.ID = uint(id) + vppTokenDB.ID = uint(id) //nolint:gosec // dismiss G115 return vppTokenDB, nil } @@ -876,7 +876,7 @@ func (ds *Datastore) UpdateVPPTokenTeams(ctx context.Context, id uint, teams []u if errors.As(err, &mysqlErr) && IsDuplicate(err) { var dupeTeamID uint var dupeTeamName string - fmt.Sscanf(mysqlErr.Message, "Duplicate entry '%d' for", &dupeTeamID) + _, _ = fmt.Sscanf(mysqlErr.Message, "Duplicate entry '%d' for", &dupeTeamID) if err := sqlx.GetContext(ctx, ds.reader(ctx), &dupeTeamName, stmtTeamName, dupeTeamID); err != nil { return nil, ctxerr.Wrap(ctx, err, "getting team name for vpp token conflict error") } diff --git a/server/datastore/mysql/vulnerabilities.go b/server/datastore/mysql/vulnerabilities.go index 81a26ea58b..932482f79f 100644 --- a/server/datastore/mysql/vulnerabilities.go +++ b/server/datastore/mysql/vulnerabilities.go @@ -294,7 +294,7 @@ func (ds *Datastore) ListVulnerabilities(ctx context.Context, opt fleet.VulnList var metaData *fleet.PaginationMetadata if opt.ListOptions.IncludeMetadata { metaData = &fleet.PaginationMetadata{HasPreviousResults: opt.ListOptions.Page > 0} - if len(vulns) > int(opt.ListOptions.PerPage) { + if len(vulns) > int(opt.ListOptions.PerPage) { //nolint:gosec // dismiss G115 metaData.HasNextResults = true vulns = vulns[:len(vulns)-1] } @@ -318,14 +318,14 @@ func (ds *Datastore) CountVulnerabilities(ctx context.Context, opt fleet.VulnLis ` var args []interface{} if opt.TeamID == nil { - selectStmt = selectStmt + " AND global_stats = 1" + selectStmt += " AND global_stats = 1" } else { - selectStmt = selectStmt + " AND global_stats = 0 AND vhc.team_id = ?" + selectStmt += " AND global_stats = 0 AND vhc.team_id = ?" args = append(args, opt.TeamID) } if opt.KnownExploit { - selectStmt = selectStmt + " AND cm.cisa_known_exploit = 1" + selectStmt += " AND cm.cisa_known_exploit = 1" } if match := opt.ListOptions.MatchQuery; match != "" { diff --git a/server/datastore/mysql/vulnerabilities_test.go b/server/datastore/mysql/vulnerabilities_test.go index f989951488..89a81df01d 100644 --- a/server/datastore/mysql/vulnerabilities_test.go +++ b/server/datastore/mysql/vulnerabilities_test.go @@ -407,7 +407,7 @@ func testVulnerabilitiesTeamFilter(t *testing.T, ds *Datastore) { } for _, vuln := range list { - require.Equal(t, checkCounts[vuln.CVE.CVE], int(vuln.HostsCount), vuln.CVE) + require.EqualValues(t, checkCounts[vuln.CVE.CVE], vuln.HostsCount, vuln.CVE) } // @@ -432,7 +432,7 @@ func testVulnerabilitiesTeamFilter(t *testing.T, ds *Datastore) { } for _, vuln := range list { - require.Equal(t, checkCounts[vuln.CVE.CVE], int(vuln.HostsCount), vuln.CVE) + require.EqualValues(t, checkCounts[vuln.CVE.CVE], vuln.HostsCount, vuln.CVE) } // @@ -456,7 +456,7 @@ func testVulnerabilitiesTeamFilter(t *testing.T, ds *Datastore) { } for _, vuln := range list { - require.Equal(t, checkCounts[vuln.CVE.CVE], int(vuln.HostsCount), vuln.CVE) + require.EqualValues(t, checkCounts[vuln.CVE.CVE], vuln.HostsCount, vuln.CVE) } } @@ -759,7 +759,7 @@ func testInsertVulnerabilityCounts(t *testing.T, ds *Datastore) { Platform: "darwin", } for i := 4; i < 9; i++ { - err = ds.UpdateHostOperatingSystem(context.Background(), uint(i), macOSPatched) + err = ds.UpdateHostOperatingSystem(context.Background(), uint(i), macOSPatched) //nolint:gosec // dismiss G115 require.NoError(t, err) } diff --git a/server/datastore/mysql/windows_updates_test.go b/server/datastore/mysql/windows_updates_test.go index 9559baca7a..3f7b16b920 100644 --- a/server/datastore/mysql/windows_updates_test.go +++ b/server/datastore/mysql/windows_updates_test.go @@ -30,7 +30,7 @@ func TestWindowsUpdates(t *testing.T) { func testListWindowsUpdatesByHostID(t *testing.T, ds *Datastore) { ctx := context.Background() - now := uint(time.Now().Unix()) + now := uint(time.Now().Unix()) //nolint:gosec // dismiss G115 t.Run("with no stored updates", func(t *testing.T) { actual, err := ds.ListWindowsUpdatesByHostID(ctx, 1) @@ -69,7 +69,7 @@ func testListWindowsUpdatesByHostID(t *testing.T, ds *Datastore) { func testInsertWindowsUpdates(t *testing.T, ds *Datastore) { ctx := context.Background() - now := uint(time.Now().Unix()) + now := uint(time.Now().Unix()) //nolint:gosec // dismiss G115 smt := `SELECT kb_id, date_epoch FROM windows_updates WHERE host_id = ?` t.Run("with no stored updates", func(t *testing.T) { diff --git a/server/datastore/redis/redis.go b/server/datastore/redis/redis.go index 34b5fc9408..39f6ba9e49 100644 --- a/server/datastore/redis/redis.go +++ b/server/datastore/redis/redis.go @@ -330,7 +330,8 @@ func newCluster(conf PoolConfig) (*redisc.Cluster, error) { } if conf.ConnectRetryAttempts > 0 { - boff := backoff.WithMaxRetries(backoff.NewExponentialBackOff(), uint64(conf.ConnectRetryAttempts)) + boff := backoff.WithMaxRetries(backoff.NewExponentialBackOff(), + uint64(conf.ConnectRetryAttempts)) //nolint:gosec // G115 false positive if err := backoff.Retry(op, boff); err != nil { return nil, err } diff --git a/server/fleet/hosts.go b/server/fleet/hosts.go index 2f07240b16..70ff7900ba 100644 --- a/server/fleet/hosts.go +++ b/server/fleet/hosts.go @@ -558,7 +558,7 @@ func (d *MDMHostData) PopulateOSSettingsAndMacOSSettings(profiles []HostMDMApple case MDMOperationTypeInstall: switch { case fvprof.Status != nil && (*fvprof.Status == MDMDeliveryVerifying || *fvprof.Status == MDMDeliveryVerified): - if d.rawDecryptable != nil && *d.rawDecryptable == 1 { + if d.rawDecryptable != nil && *d.rawDecryptable == 1 { //nolint:gocritic // ignore ifElseChain // if a FileVault profile has been successfully installed on the host // AND we have fetched and are able to decrypt the key switch *fvprof.Status { @@ -690,14 +690,14 @@ func (h *Host) IsEligibleForWindowsMDMUnenrollment(isConnectedToFleetMDM bool) b // empty. If Hostname is empty and both HardwareSerial and HardwareModel are not empty, it returns a // composite string with HardwareModel and HardwareSerial. If all else fails, it returns an empty // string. -func HostDisplayName(ComputerName string, Hostname string, HardwareModel string, HardwareSerial string) string { +func HostDisplayName(computerName string, hostname string, hardwareModel string, hardwareSerial string) string { switch { - case ComputerName != "": - return ComputerName - case Hostname != "": - return Hostname - case HardwareModel != "" && HardwareSerial != "": - return fmt.Sprintf("%s (%s)", HardwareModel, HardwareSerial) + case computerName != "": + return computerName + case hostname != "": + return hostname + case hardwareModel != "" && hardwareSerial != "": + return fmt.Sprintf("%s (%s)", hardwareModel, hardwareSerial) default: return "" } @@ -786,7 +786,7 @@ func (h *Host) Status(now time.Time) HostStatus { onlineInterval += OnlineIntervalBuffer switch { - case h.SeenTime.Add(time.Duration(onlineInterval) * time.Second).Before(now): + case h.SeenTime.Add(time.Duration(onlineInterval) * time.Second).Before(now): //nolint:gosec // dismiss G115 return StatusOffline default: return StatusOnline @@ -827,7 +827,8 @@ func IsLinux(hostPlatform string) bool { } func IsUnixLike(hostPlatform string) bool { - unixLikeOSs := append(HostLinuxOSs, "darwin") + unixLikeOSs := HostLinuxOSs + unixLikeOSs = append(unixLikeOSs, "darwin") for _, p := range unixLikeOSs { if p == hostPlatform { return true diff --git a/server/fleet/microsoft_mdm.go b/server/fleet/microsoft_mdm.go index 33941a6201..5de21393b4 100644 --- a/server/fleet/microsoft_mdm.go +++ b/server/fleet/microsoft_mdm.go @@ -1410,11 +1410,12 @@ func GetEncodedBinarySecurityToken(typeID WindowsMDMEnrollmentType, payload stri var pld WindowsMDMAccessTokenPayload pld.Type = typeID - if typeID == WindowsMDMProgrammaticEnrollmentType { + switch typeID { + case WindowsMDMProgrammaticEnrollmentType: pld.Payload.OrbitNodeKey = payload - } else if typeID == WindowsMDMAutomaticEnrollmentType { + case WindowsMDMAutomaticEnrollmentType: pld.Payload.AuthToken = payload - } else { + default: return "", fmt.Errorf("invalid enrollment type: %v", typeID) } diff --git a/server/fleet/policytest/policytest.go b/server/fleet/policytest/policytest.go index 9aae6fef32..70dd404ae0 100644 --- a/server/fleet/policytest/policytest.go +++ b/server/fleet/policytest/policytest.go @@ -13,7 +13,7 @@ func RunFailing1000hosts(t *testing.T, r fleet.FailingPolicySet) { hosts := make([]fleet.PolicySetHost, 1000) for i := range hosts { hosts[i] = fleet.PolicySetHost{ - ID: uint(i + 1), + ID: uint(i + 1), //nolint:gosec // dismiss G115 Hostname: fmt.Sprintf("test.hostname.%d", i+1), } } diff --git a/server/fleet/scheduled_queries.go b/server/fleet/scheduled_queries.go index 00b84a9455..62d68e2fb8 100644 --- a/server/fleet/scheduled_queries.go +++ b/server/fleet/scheduled_queries.go @@ -192,7 +192,7 @@ func ScheduledQueryFromQuery(query *Query) *ScheduledQuery { snapshot *bool removed *bool ) - if query.Logging == "" || query.Logging == "snapshot" { + if query.Logging == "" || query.Logging == "snapshot" { //nolint:gocritic // ignore ifElseChain snapshot = ptr.Bool(true) removed = ptr.Bool(false) } else if query.Logging == "differential" { @@ -221,7 +221,7 @@ func ScheduledQueryFromQuery(query *Query) *ScheduledQuery { func ScheduledQueryToQueryPayloadForNewQuery(originalQuery *Query, scheduledQuery *ScheduledQuery) QueryPayload { logging := ptr.String(LoggingSnapshot) // default is snapshot. if scheduledQuery.Snapshot != nil && scheduledQuery.Removed != nil { - if *scheduledQuery.Snapshot { + if *scheduledQuery.Snapshot { //nolint:gocritic // ignore ifElseChain logging = ptr.String(LoggingSnapshot) } else if *scheduledQuery.Removed { logging = ptr.String(LoggingDifferential) @@ -249,7 +249,7 @@ func ScheduledQueryToQueryPayloadForNewQuery(originalQuery *Query, scheduledQuer func ScheduledQueryPayloadToQueryPayloadForModifyQuery(payload ScheduledQueryPayload) QueryPayload { var logging *string if payload.Snapshot != nil && payload.Removed != nil { - if *payload.Snapshot { + if *payload.Snapshot { //nolint:gocritic // ignore ifElseChain logging = ptr.String(LoggingSnapshot) } else if *payload.Removed { logging = ptr.String(LoggingDifferential) diff --git a/server/fleet/software.go b/server/fleet/software.go index 9045d7e375..a75538d03b 100644 --- a/server/fleet/software.go +++ b/server/fleet/software.go @@ -123,8 +123,7 @@ type VulnSoftwareFilter struct { type SliceString []string func (c *SliceString) Scan(v interface{}) error { - switch tv := v.(type) { - case []byte: + if tv, ok := v.([]byte); ok { return json.Unmarshal(tv, &c) } return errors.New("unsupported type") diff --git a/server/goose/migrate.go b/server/goose/migrate.go index bf5ca921b2..ee8d3504fa 100644 --- a/server/goose/migrate.go +++ b/server/goose/migrate.go @@ -178,7 +178,7 @@ func (c *Client) GetDBVersion(db *sql.DB) (int64, error) { for rows.Next() { var row MigrationRecord if err = rows.Scan(&row.VersionId, &row.IsApplied); err != nil { - log.Fatal("error scanning rows:", err) + log.Fatal("error scanning rows:", err) //nolint:gocritic // ignore exitAfterDefer } // have we already marked this version to be skipped? diff --git a/server/goose/migrate_test.go b/server/goose/migrate_test.go index 97a0a1fee4..fb64aad640 100644 --- a/server/goose/migrate_test.go +++ b/server/goose/migrate_test.go @@ -32,13 +32,14 @@ func validateMigrationSort(t *testing.T, ms Migrations, sorted []int64) { var next, prev int64 - if i == 0 { + switch i { + case 0: prev = -1 next = ms[i+1].Version - } else if i == len(ms)-1 { + case len(ms) - 1: prev = ms[i-1].Version next = -1 - } else { + default: prev = ms[i-1].Version next = ms[i+1].Version } diff --git a/server/goose/migration.go b/server/goose/migration.go index 28767a5b15..b3c2c55f7a 100644 --- a/server/goose/migration.go +++ b/server/goose/migration.go @@ -34,7 +34,7 @@ const ( ) func (m *Migration) String() string { - return fmt.Sprintf(m.Source) + return fmt.Sprint(m.Source) } func (c *Client) runMigration(db *sql.DB, m *Migration, direction bool) error { diff --git a/server/launcher/launcher.go b/server/launcher/launcher.go index 007ac423c9..8ed4bba155 100644 --- a/server/launcher/launcher.go +++ b/server/launcher/launcher.go @@ -82,7 +82,7 @@ func (svc *launcherWrapper) RequestQueries(ctx context.Context, nodeKey string) result := &distributed.GetQueriesResult{ Queries: queryMap, Discovery: discoveryMap, - AccelerateSeconds: int(accelerate), + AccelerateSeconds: int(accelerate), //nolint:gosec // dismiss G115 } return result, false, nil @@ -131,10 +131,10 @@ func (svc *launcherWrapper) PublishResults(ctx context.Context, nodeKey string, osqueryResults[result.QueryName] = result.Rows if result.QueryStats != nil { stats[result.QueryName] = &fleet.Stats{ - WallTimeMs: uint64(result.QueryStats.WallTimeMs), - UserTime: uint64(result.QueryStats.UserTime), - SystemTime: uint64(result.QueryStats.SystemTime), - Memory: uint64(result.QueryStats.Memory), + WallTimeMs: uint64(result.QueryStats.WallTimeMs), //nolint:gosec // dismiss G115 + UserTime: uint64(result.QueryStats.UserTime), //nolint:gosec // dismiss G115 + SystemTime: uint64(result.QueryStats.SystemTime), //nolint:gosec // dismiss G115 + Memory: uint64(result.QueryStats.Memory), //nolint:gosec // dismiss G115 } } } diff --git a/server/logging/firehose.go b/server/logging/firehose.go index 783f38f842..4e0d371852 100644 --- a/server/logging/firehose.go +++ b/server/logging/firehose.go @@ -91,7 +91,7 @@ func (f *firehoseLogWriter) validateStream() error { return fmt.Errorf("describe stream %s: %w", f.stream, err) } - if (*(*out.DeliveryStreamDescription).DeliveryStreamStatus) != firehose.DeliveryStreamStatusActive { + if (*out.DeliveryStreamDescription.DeliveryStreamStatus) != firehose.DeliveryStreamStatusActive { return fmt.Errorf("delivery stream %s not active", f.stream) } diff --git a/server/logging/kinesis.go b/server/logging/kinesis.go index 3b304fbb52..717662c639 100644 --- a/server/logging/kinesis.go +++ b/server/logging/kinesis.go @@ -98,7 +98,7 @@ func (k *kinesisLogWriter) validateStream() error { return fmt.Errorf("describe stream %s: %w", k.stream, err) } - if (*(*out.StreamDescription).StreamStatus) != kinesis.StreamStatusActive { + if (*out.StreamDescription.StreamStatus) != kinesis.StreamStatusActive { return fmt.Errorf("stream %s not active", k.stream) } diff --git a/server/mdm/apple/itunes/api.go b/server/mdm/apple/itunes/api.go index a1db6ba0e7..6da88971e7 100644 --- a/server/mdm/apple/itunes/api.go +++ b/server/mdm/apple/itunes/api.go @@ -7,7 +7,6 @@ import ( "net/http" "net/url" "os" - "strconv" "strings" "time" @@ -65,7 +64,7 @@ func GetAssetMetadata(adamIDs []string, filter *AssetMetadataFilter) (map[string metadata := make(map[string]AssetMetadata) for _, a := range bodyResp.Results { - metadata[strconv.Itoa(int(a.TrackID))] = a + metadata[fmt.Sprint(a.TrackID)] = a } return metadata, nil diff --git a/server/mdm/apple/util.go b/server/mdm/apple/util.go index c98dcc48d8..a52cb8bb9e 100644 --- a/server/mdm/apple/util.go +++ b/server/mdm/apple/util.go @@ -60,7 +60,7 @@ func EncodePrivateKeyPEM(key *rsa.PrivateKey) []byte { // // The implementation details have been mostly taken from https://github.com/pquerna/otp func GenerateRandomPin(length int) string { - counter := uint64(time.Now().Unix()) + counter := uint64(time.Now().Unix()) //nolint:gosec // dismiss G115 buf := make([]byte, 8) binary.BigEndian.PutUint64(buf, counter) m := sha256.New() @@ -71,7 +71,7 @@ func GenerateRandomPin(length int) string { ((int(sum[offset+1] & 0xff)) << 16) | ((int(sum[offset+2] & 0xff)) << 8) | (int(sum[offset+3]) & 0xff)) - v := int32(value % int64(math.Pow10(length))) + v := int32(value % int64(math.Pow10(length))) //nolint:gosec // dismiss G115 f := fmt.Sprintf("%%0%dd", length) return fmt.Sprintf(f, v) } diff --git a/server/mdm/maintainedapps/scripts.go b/server/mdm/maintainedapps/scripts.go index 46871f5611..6b748af75e 100644 --- a/server/mdm/maintainedapps/scripts.go +++ b/server/mdm/maintainedapps/scripts.go @@ -179,11 +179,11 @@ func processUninstallArtifact(u *brewUninstall, sb *scriptBuilder) { if u.Script.IsOther { addUserVar() for _, path := range u.Script.Other { - sb.Writef(fmt.Sprintf(`sudo -u "$LOGGED_IN_USER" '%s'`, path)) + sb.Writef(`sudo -u "$LOGGED_IN_USER" '%s'`, path) } } else if len(u.Script.String) > 0 { addUserVar() - sb.Writef(fmt.Sprintf(`sudo -u "$LOGGED_IN_USER" '%s'`, u.Script.String)) + sb.Writef(`sudo -u "$LOGGED_IN_USER" '%s'`, u.Script.String) } process(u.PkgUtil, func(pkgID string) { diff --git a/server/mdm/microsoft/wstep_csr.go b/server/mdm/microsoft/wstep_csr.go index 86a929e86b..8d6064a684 100644 --- a/server/mdm/microsoft/wstep_csr.go +++ b/server/mdm/microsoft/wstep_csr.go @@ -3,10 +3,14 @@ package microsoft_mdm import ( "bytes" "crypto" + "crypto/dsa" //lint:ignore required for crypto.RegisterHash "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" "crypto/rsa" + _ "crypto/sha1" //nolint:gosec + _ "crypto/sha256" + _ "crypto/sha512" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" @@ -27,12 +31,6 @@ import ( // Explicitly import these for their crypto.RegisterHash init side-effects. // Keep these as blank imports, even if they're imported above. - "crypto/dsa" //lint:ignore required for crypto.RegisterHash - - _ "crypto/sha1" //nolint:gosec - _ "crypto/sha256" - _ "crypto/sha512" - "golang.org/x/crypto/cryptobyte" cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" ) @@ -405,7 +403,7 @@ func parseCertificateRequest(in *certificateRequest) (*x509.CertificateRequest, } for _, extension := range out.Extensions { - switch { + switch { //nolint:gocritic // ignore singleCaseSwitch case extension.Id.Equal(oidExtensionSubjectAltName): out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value) if err != nil { @@ -1293,8 +1291,8 @@ func parseInt64(bytes []byte) (ret int64, err error) { } // Shift up and down in order to sign extend the result. - ret <<= 64 - uint8(len(bytes))*8 - ret >>= 64 - uint8(len(bytes))*8 + ret <<= 64 - uint8(len(bytes))*8 //nolint:gosec // dismiss G115 + ret >>= 64 - uint8(len(bytes))*8 //nolint:gosec // dismiss G115 return } @@ -1484,10 +1482,10 @@ func parseInt32(bytes []byte) (int32, error) { if err != nil { return 0, err } - if ret64 != int64(int32(ret64)) { + if ret64 != int64(int32(ret64)) { //nolint:gosec // dismiss G115 return 0, asn1.StructuralError{Msg: "integer too large"} } - return int32(ret64), nil + return int32(ret64), nil //nolint:gosec // dismiss G115 } var bigOne = big.NewInt(1) diff --git a/server/mdm/microsoft/wstep_csr_test.go b/server/mdm/microsoft/wstep_csr_test.go index f5d5e59800..eef70e4483 100644 --- a/server/mdm/microsoft/wstep_csr_test.go +++ b/server/mdm/microsoft/wstep_csr_test.go @@ -135,7 +135,7 @@ func TestCreateCertificateRequest(t *testing.T) { continue } - if out.Subject.CommonName != template.Subject.CommonName { + if out.Subject.CommonName != template.Subject.CommonName { //nolint:gocritic // ignore ifElseChain t.Errorf("%s: output subject common name and template subject common name don't match", test.name) } else if len(out.Subject.Organization) != len(template.Subject.Organization) { t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name) diff --git a/server/mdm/nanodep/cmd/depsyncer/main.go b/server/mdm/nanodep/cmd/depsyncer/main.go index b3157ced94..bee9f04bd7 100644 --- a/server/mdm/nanodep/cmd/depsyncer/main.go +++ b/server/mdm/nanodep/cmd/depsyncer/main.go @@ -166,7 +166,7 @@ func main() { depsync.WithCallback(callback), } if *flDur > 0 { - syncerOpts = append(syncerOpts, depsync.WithDuration(time.Duration(*flDur)*time.Second)) + syncerOpts = append(syncerOpts, depsync.WithDuration(time.Duration(*flDur)*time.Second)) //nolint:gosec // ignore G115 } if *flLimit > 0 { syncerOpts = append(syncerOpts, depsync.WithLimit(*flLimit)) diff --git a/server/mdm/nanomdm/http/api/api.go b/server/mdm/nanomdm/http/api/api.go index 6cdcda6893..ccb6218d33 100644 --- a/server/mdm/nanomdm/http/api/api.go +++ b/server/mdm/nanomdm/http/api/api.go @@ -277,15 +277,16 @@ func readPEMCertAndKey(input []byte) (cert []byte, key []byte, err error) { if block == nil { break } - if block.Type == "CERTIFICATE" { + switch { + case block.Type == "CERTIFICATE": cert = pem.EncodeToMemory(block) - } else if block.Type == "PRIVATE KEY" || strings.HasSuffix(block.Type, " PRIVATE KEY") { + case block.Type == "PRIVATE KEY" || strings.HasSuffix(block.Type, " PRIVATE KEY"): if x509.IsEncryptedPEMBlock(block) { err = errors.New("private key PEM appears to be encrypted") break } key = pem.EncodeToMemory(block) - } else { + default: err = fmt.Errorf("unrecognized PEM type: %q", block.Type) break } diff --git a/server/mdm/nanomdm/mdm/type.go b/server/mdm/nanomdm/mdm/type.go index 40070986cd..6e270bcdad 100644 --- a/server/mdm/nanomdm/mdm/type.go +++ b/server/mdm/nanomdm/mdm/type.go @@ -2,7 +2,7 @@ package mdm import ( "errors" - "strconv" + "fmt" ) // Shared iPad users have a static UserID that they connect to MDM with. @@ -40,7 +40,7 @@ func (et EnrollType) String() string { case SharediPad: return "Shared iPad" default: - return "unknown enroll type value " + strconv.Itoa(int(et)) + return "unknown enroll type value " + fmt.Sprint(uint(et)) } } diff --git a/server/mdm/scep/cmd/scepserver/scepserver.go b/server/mdm/scep/cmd/scepserver/scepserver.go index 58e624501f..a8d41e6fe6 100644 --- a/server/mdm/scep/cmd/scepserver/scepserver.go +++ b/server/mdm/scep/cmd/scepserver/scepserver.go @@ -75,12 +75,13 @@ func main() { httpAddrSet := setByUser("http-addr", "SCEP_HTTP_ADDR") portSet := setByUser("port", "SCEP_HTTP_LISTEN_PORT") var httpAddr string - if httpAddrSet && portSet { + switch { + case httpAddrSet && portSet: fmt.Fprintln(os.Stderr, "cannot set both -http-addr and -port") os.Exit(1) - } else if httpAddrSet { + case httpAddrSet: httpAddr = *flHTTPAddr - } else { + default: httpAddr = ":" + *flPort } diff --git a/server/mock/mockimpl/impl.go b/server/mock/mockimpl/impl.go index 5988d277aa..d06425b1f4 100644 --- a/server/mock/mockimpl/impl.go +++ b/server/mock/mockimpl/impl.go @@ -413,7 +413,7 @@ func main() { defer f.Close() _, err = f.Write(imp) if err != nil { - log.Fatal(err) + log.Fatal(err) //nolint:gocritic // ignore exitAfterDefer } } } diff --git a/server/pubsub/inmem_query_results.go b/server/pubsub/inmem_query_results.go index 3d943e8619..3a37da2485 100644 --- a/server/pubsub/inmem_query_results.go +++ b/server/pubsub/inmem_query_results.go @@ -2,7 +2,7 @@ package pubsub import ( "context" - "strconv" + "fmt" "sync" "github.com/fleetdm/fleet/v4/server/fleet" @@ -40,7 +40,7 @@ func (im *inmemQueryResults) WriteResult(result fleet.DistributedQueryResult) er case channel <- result: // intentionally do nothing default: - return noSubscriberError{strconv.Itoa(int(result.DistributedQueryCampaignID))} + return noSubscriberError{fmt.Sprint(result.DistributedQueryCampaignID)} } return nil diff --git a/server/pubsub/query_results_test.go b/server/pubsub/query_results_test.go index 47ab85ff4b..3784aa5d03 100644 --- a/server/pubsub/query_results_test.go +++ b/server/pubsub/query_results_test.go @@ -153,7 +153,7 @@ func TestQueryResultsStore(t *testing.T) { go func() { defer readerWg.Done() for res := range channel1 { - switch res := res.(type) { + switch res := res.(type) { //nolint:gocritic // ignore singleCaseSwitch case fleet.DistributedQueryResult: results1 = append(results1, res) } @@ -163,7 +163,7 @@ func TestQueryResultsStore(t *testing.T) { go func() { defer readerWg.Done() for res := range channel2 { - switch res := res.(type) { + switch res := res.(type) { //nolint:gocritic // ignore singleCaseSwitch case fleet.DistributedQueryResult: results2 = append(results2, res) } diff --git a/server/service/apple_mdm.go b/server/service/apple_mdm.go index 4a50c4665f..9eb53c32b8 100644 --- a/server/service/apple_mdm.go +++ b/server/service/apple_mdm.go @@ -319,7 +319,7 @@ func (newMDMAppleConfigProfileRequest) DecodeRequest(ctx context.Context, r *htt if err != nil { return nil, &fleet.BadRequestError{Message: fmt.Sprintf("failed to decode team_id in multipart form: %s", err.Error())} } - decoded.TeamID = uint(teamID) + decoded.TeamID = uint(teamID) //nolint:gosec // dismiss G115 } fhs, ok := r.MultipartForm.File["profile"] @@ -2209,7 +2209,7 @@ func (uploadBootstrapPackageRequest) DecodeRequest(ctx context.Context, r *http. if err != nil { return nil, &fleet.BadRequestError{Message: fmt.Sprintf("failed to decode team_id in multipart form: %s", err.Error())} } - decoded.TeamID = uint(teamID) + decoded.TeamID = uint(teamID) //nolint:gosec // dismiss G115 } return &decoded, nil @@ -4477,7 +4477,7 @@ func (renewABMTokenRequest) DecodeRequest(ctx context.Context, r *http.Request) return &renewABMTokenRequest{ Token: token[0], - TokenID: uint(id), + TokenID: uint(id), //nolint:gosec // dismiss G115 }, nil } diff --git a/server/service/async/async.go b/server/service/async/async.go index d75162dc87..c1ad2b9d12 100644 --- a/server/service/async/async.go +++ b/server/service/async/async.go @@ -141,7 +141,8 @@ func loadActiveHostIDs(pool fleet.RedisPool, zsetKey string, scanCount int) ([]h return nil, fmt.Errorf("convert scan results: %w", err) } for i := 0; i < len(hostVals); i += 2 { - hosts = append(hosts, hostIDLastReported{HostID: hostVals[i], LastReported: int64(hostVals[i+1])}) + hosts = append(hosts, + hostIDLastReported{HostID: hostVals[i], LastReported: int64(hostVals[i+1])}) //nolint:gosec // dismiss G115 } if cursor == 0 { diff --git a/server/service/async/async_host_seen_test.go b/server/service/async/async_host_seen_test.go index 8b6af10214..cd2c60bfa2 100644 --- a/server/service/async/async_host_seen_test.go +++ b/server/service/async/async_host_seen_test.go @@ -32,7 +32,7 @@ func testCollectHostsLastSeen(t *testing.T, ds *mysql.Datastore, pool fleet.Redi hostIDs := createHosts(t, ds, 4, startTime) t.Logf("real host IDs: %v", hostIDs) hid := func(id int) int { - return int(hostIDs[id-1]) + return int(hostIDs[id-1]) //nolint:gosec // dismiss G115 } // note that cases cannot be run in isolation, each case builds on the diff --git a/server/service/async/async_label.go b/server/service/async/async_label.go index f194fc4f37..ac92a4cff8 100644 --- a/server/service/async/async_label.go +++ b/server/service/async/async_label.go @@ -121,9 +121,9 @@ func (t *Task) collectLabelQueryExecutions(ctx context.Context, ds fleet.Datasto switch score { case 1: - inserts = append(inserts, [2]uint{uint(labelID), hostID}) + inserts = append(inserts, [2]uint{uint(labelID), hostID}) //nolint:gosec // dismiss G115 case -1: - deletes = append(deletes, [2]uint{uint(labelID), hostID}) + deletes = append(deletes, [2]uint{uint(labelID), hostID}) //nolint:gosec // dismiss G115 } } if items < cfg.RedisPopCount { diff --git a/server/service/async/async_label_test.go b/server/service/async/async_label_test.go index 8d237fb527..3236208469 100644 --- a/server/service/async/async_label_test.go +++ b/server/service/async/async_label_test.go @@ -29,7 +29,7 @@ func testCollectLabelQueryExecutions(t *testing.T, ds *mysql.Datastore, pool fle hostIDs := createHosts(t, ds, 4, time.Now().Add(-24*time.Hour)) t.Logf("real host IDs: %v", hostIDs) hid := func(id int) int { - return int(hostIDs[id-1]) + return int(hostIDs[id-1]) //nolint:gosec // dismiss G115 } // note that cases cannot be run in isolation, each case builds on the diff --git a/server/service/async/async_policy_test.go b/server/service/async/async_policy_test.go index b7e57b365f..2e973d55d5 100644 --- a/server/service/async/async_policy_test.go +++ b/server/service/async/async_policy_test.go @@ -35,13 +35,13 @@ func testCollectPolicyQueryExecutions(t *testing.T, ds *mysql.Datastore, pool fl t.Logf("real host IDs: %v", hostIDs) t.Logf("real policy IDs: %v", policyIDs) hid := func(id int) int { - return int(hostIDs[id-1]) + return int(hostIDs[id-1]) //nolint:gosec // dismiss G115 } pid := func(id int) int { if id < 0 || id >= len(policyIDs) { return id } - return int(policyIDs[id-1]) + return int(policyIDs[id-1]) //nolint:gosec // dismiss G115 } nbTrue := sql.NullBool{Valid: true, Bool: true} @@ -534,7 +534,7 @@ func createPolicies(t *testing.T, ds *mysql.Datastore, count int) []uint { return err } pid, _ := res.LastInsertId() - ids[i] = uint(pid) + ids[i] = uint(pid) //nolint:gosec // dismiss G115 } return nil }) diff --git a/server/service/async/async_test.go b/server/service/async/async_test.go index dfe92a4b13..78259f347c 100644 --- a/server/service/async/async_test.go +++ b/server/service/async/async_test.go @@ -188,7 +188,7 @@ func TestActiveHostIDsSet(t *testing.T) { } // none ever get deleted, all are after tpurgeNone - n, err := storePurgeActiveHostID(pool, zkey, uint(i+1), time.Unix(ts[i], 0), tpurgeNone) + n, err := storePurgeActiveHostID(pool, zkey, uint(i+1), time.Unix(ts[i], 0), tpurgeNone) //nolint:gosec // dismiss G115 require.NoError(t, err) require.Equal(t, 0, n) } @@ -201,7 +201,8 @@ func TestActiveHostIDsSet(t *testing.T) { } // store a new one but now use t[1] as purge date - will remove two - ts2 := append(ts, time.Unix(ts[len(ts)-1], 0).Add(time.Second).Unix()) + ts2 := ts + ts2 = append(ts2, time.Unix(ts[len(ts)-1], 0).Add(time.Second).Unix()) n, err := storePurgeActiveHostID(pool, zkey, uint(len(ts2)), time.Unix(ts2[len(ts2)-1], 0), time.Unix(ts2[1], 0)) require.NoError(t, err) require.Equal(t, 2, n) diff --git a/server/service/campaigns.go b/server/service/campaigns.go index 81e0520c0f..053b3cf256 100644 --- a/server/service/campaigns.go +++ b/server/service/campaigns.go @@ -3,7 +3,6 @@ package service import ( "context" "fmt" - "strconv" "strings" "time" @@ -162,7 +161,7 @@ func (svc *Service) NewDistributedQueryCampaign(ctx context.Context, queryString return nil, ctxerr.Wrap(ctx, err, "counting hosts") } - err = svc.liveQueryStore.RunQuery(strconv.Itoa(int(campaign.ID)), queryString, hostIDs) + err = svc.liveQueryStore.RunQuery(fmt.Sprint(campaign.ID), queryString, hostIDs) if err != nil { return nil, ctxerr.Wrap(ctx, err, "run query") } diff --git a/server/service/client_policies.go b/server/service/client_policies.go index 089e6a2d47..388d7d80d9 100644 --- a/server/service/client_policies.go +++ b/server/service/client_policies.go @@ -46,9 +46,9 @@ func (c *Client) GetPolicies(teamID *uint) ([]*fleet.Policy, error) { } // DeletePolicies deletes several policies. -func (c *Client) DeletePolicies(teamID *uint, IDs []uint) error { +func (c *Client) DeletePolicies(teamID *uint, ids []uint) error { verb, path := "POST", "" - req := deleteTeamPoliciesRequest{IDs: IDs} + req := deleteTeamPoliciesRequest{IDs: ids} if teamID != nil { path = fmt.Sprintf("/api/latest/fleet/teams/%d/policies/delete", *teamID) req.TeamID = *teamID diff --git a/server/service/client_queries.go b/server/service/client_queries.go index 146cac01ae..0870482632 100644 --- a/server/service/client_queries.go +++ b/server/service/client_queries.go @@ -54,8 +54,8 @@ func (c *Client) DeleteQuery(name string) error { } // DeleteQueries deletes several queries. -func (c *Client) DeleteQueries(IDs []uint) error { - req := deleteQueriesRequest{IDs: IDs} +func (c *Client) DeleteQueries(ids []uint) error { + req := deleteQueriesRequest{IDs: ids} verb, path := "POST", "/api/latest/fleet/queries/delete" var responseBody deleteQueriesResponse return c.authenticatedRequest(req, verb, path, &responseBody) diff --git a/server/service/client_sessions.go b/server/service/client_sessions.go index 5d5f837e9d..7ba0f78ff1 100644 --- a/server/service/client_sessions.go +++ b/server/service/client_sessions.go @@ -20,8 +20,7 @@ func (c *Client) Login(email, password string) (string, error) { } defer response.Body.Close() - switch response.StatusCode { - case http.StatusNotFound: + if response.StatusCode == http.StatusNotFound { return "", notSetupErr{} } if response.StatusCode != http.StatusOK { diff --git a/server/service/devices.go b/server/service/devices.go index 9eb1ba3a3a..18f404748b 100644 --- a/server/service/devices.go +++ b/server/service/devices.go @@ -642,5 +642,5 @@ func getDeviceSoftwareEndpoint(ctx context.Context, request interface{}, svc fle if res == nil { res = []*fleet.HostSoftwareWithInstaller{} } - return getDeviceSoftwareResponse{Software: res, Meta: meta, Count: int(meta.TotalResults)}, nil + return getDeviceSoftwareResponse{Software: res, Meta: meta, Count: int(meta.TotalResults)}, nil //nolint:gosec // dismiss G115 } diff --git a/server/service/endpoint_utils.go b/server/service/endpoint_utils.go index 055eb2cba1..d4914b1ac3 100644 --- a/server/service/endpoint_utils.go +++ b/server/service/endpoint_utils.go @@ -272,7 +272,7 @@ func makeDecoder(iface interface{}) kithttp.DecodeRequestFunc { if err != nil { return nil, badRequestErr("parsing uint from query", err) } - field.SetUint(uint64(queryValUint)) + field.SetUint(uint64(queryValUint)) //nolint:gosec // dismiss G115 case reflect.Float64: queryValFloat, err := strconv.ParseFloat(queryVal, 64) if err != nil { @@ -464,9 +464,7 @@ func capabilitiesResponseFunc(capabilities fleet.CapabilityMap) kithttp.ServerOp } func capabilitiesContextFunc() kithttp.ServerOption { - return kithttp.ServerBefore(func(ctx context.Context, r *http.Request) context.Context { - return capabilities.NewContext(ctx, r) - }) + return kithttp.ServerBefore(capabilities.NewContext) } func writeCapabilitiesHeader(w http.ResponseWriter, capabilities fleet.CapabilityMap) { diff --git a/server/service/hosts.go b/server/service/hosts.go index eef4cb65f2..06d1b14c66 100644 --- a/server/service/hosts.go +++ b/server/service/hosts.go @@ -2591,7 +2591,7 @@ func getHostSoftwareEndpoint(ctx context.Context, request interface{}, svc fleet if res == nil { res = []*fleet.HostSoftwareWithInstaller{} } - return getHostSoftwareResponse{Software: res, Meta: meta, Count: int(meta.TotalResults)}, nil + return getHostSoftwareResponse{Software: res, Meta: meta, Count: int(meta.TotalResults)}, nil //nolint:gosec // dismiss G115 } func (svc *Service) ListHostSoftware(ctx context.Context, hostID uint, opts fleet.HostSoftwareTitleListOptions) ([]*fleet.HostSoftwareWithInstaller, *fleet.PaginationMetadata, error) { diff --git a/server/service/integration_core_test.go b/server/service/integration_core_test.go index 7a38268a9f..12f4540f08 100644 --- a/server/service/integration_core_test.go +++ b/server/service/integration_core_test.go @@ -7822,10 +7822,10 @@ func (s *integrationTestSuite) TestPasswordReset() { // TODO: tested manually (adds too much time to the test), works but hitting the rate // limit returns 500 instead of 429, see #4406. We get the authz check missing error instead. - //// trigger the rate limit with a batch of requests in a short burst - //for i := 0; i < 20; i++ { + // // trigger the rate limit with a batch of requests in a short burst + // for i := 0; i < 20; i++ { // s.DoJSON("POST", "/api/latest/fleet/forgot_password", forgotPasswordRequest{Email: "invalid@asd.com"}, http.StatusAccepted, &forgotResp) - //} + // } // request forgot password, valid email res = s.DoRawNoAuth("POST", "/api/latest/fleet/forgot_password", jsonMustMarshal(t, forgotPasswordRequest{Email: u.Email}), http.StatusAccepted) @@ -9934,8 +9934,8 @@ func (s *integrationTestSuite) TestDirectIngestScheduledQueryStats() { } for _, sqs := range scheduledQueriesStats { row := rowsMap[sqs.ScheduledQueryName] - require.Equal(t, strconv.FormatInt(int64(sqs.AverageMemory), 10), row["average_memory"]) - require.Equal(t, strconv.FormatInt(int64(sqs.Executions), 10), row["executions"]) + require.Equal(t, fmt.Sprint(sqs.AverageMemory), row["average_memory"]) + require.Equal(t, fmt.Sprint(sqs.Executions), row["executions"]) interval := row["interval"] if sqs.ScheduledQueryName == "non-scheduled-global-query" { interval = "0" // this query has metrics because it runs on a pack. @@ -9944,10 +9944,10 @@ func (s *integrationTestSuite) TestDirectIngestScheduledQueryStats() { lastExecuted, err := strconv.ParseInt(row["last_executed"], 10, 64) require.NoError(t, err) require.WithinDuration(t, sqs.LastExecuted, time.Unix(lastExecuted, 0), 1*time.Second) - require.Equal(t, strconv.FormatInt(int64(sqs.OutputSize), 10), row["output_size"]) - require.Equal(t, strconv.FormatInt(int64(sqs.SystemTime), 10), row["system_time"]) - require.Equal(t, strconv.FormatInt(int64(sqs.UserTime), 10), row["user_time"]) - assert.Equal(t, strconv.FormatInt(int64(sqs.WallTime), 10), row["wall_time_ms"]) + require.Equal(t, fmt.Sprint(sqs.OutputSize), row["output_size"]) + require.Equal(t, fmt.Sprint(sqs.SystemTime), row["system_time"]) + require.Equal(t, fmt.Sprint(sqs.UserTime), row["user_time"]) + assert.Equal(t, fmt.Sprint(sqs.WallTime), row["wall_time_ms"]) } // Now let's simulate a osquery instance running in the global host returning the @@ -10003,16 +10003,16 @@ func (s *integrationTestSuite) TestDirectIngestScheduledQueryStats() { queryName := parts[len(parts)-1] sqs := scheduledQueriesStats[0] require.Equal(t, scheduledQueriesStats[0].ScheduledQueryName, queryName) - require.Equal(t, strconv.FormatInt(int64(sqs.AverageMemory), 10), row["average_memory"]) - require.Equal(t, strconv.FormatInt(int64(sqs.Executions), 10), row["executions"]) - require.Equal(t, strconv.FormatInt(int64(sqs.Interval), 10), row["interval"]) + require.Equal(t, fmt.Sprint(sqs.AverageMemory), row["average_memory"]) + require.Equal(t, fmt.Sprint(sqs.Executions), row["executions"]) + require.Equal(t, fmt.Sprint(sqs.Interval), row["interval"]) lastExecuted, err := strconv.ParseInt(row["last_executed"], 10, 64) require.NoError(t, err) require.WithinDuration(t, sqs.LastExecuted, time.Unix(lastExecuted, 0), 1*time.Second) - require.Equal(t, strconv.FormatInt(int64(sqs.OutputSize), 10), row["output_size"]) - require.Equal(t, strconv.FormatInt(int64(sqs.SystemTime), 10), row["system_time"]) - require.Equal(t, strconv.FormatInt(int64(sqs.UserTime), 10), row["user_time"]) - require.Equal(t, strconv.FormatInt(int64(sqs.WallTime), 10), row["wall_time_ms"]) + require.Equal(t, fmt.Sprint(sqs.OutputSize), row["output_size"]) + require.Equal(t, fmt.Sprint(sqs.SystemTime), row["system_time"]) + require.Equal(t, fmt.Sprint(sqs.UserTime), row["user_time"]) + require.Equal(t, fmt.Sprint(sqs.WallTime), row["wall_time_ms"]) } // TestDirectIngestSoftwareWithLongFields tests that software with reported long fields diff --git a/server/service/integration_enterprise_test.go b/server/service/integration_enterprise_test.go index 46c24187e9..636bdc833a 100644 --- a/server/service/integration_enterprise_test.go +++ b/server/service/integration_enterprise_test.go @@ -142,7 +142,7 @@ func (s *integrationEnterpriseTestSuite) TestTeamSpecs() { Name: teamNameDecomposed, Description: "desc team1", } - teamName = teamName + "ê°€" + teamName += "ê°€" s.Do("POST", "/api/latest/fleet/teams", team, http.StatusOK) @@ -5075,7 +5075,7 @@ func (s *integrationEnterpriseTestSuite) TestGitOpsUserActions() { h1, err := s.ds.NewHost(ctx, &fleet.Host{ NodeKey: ptr.String(t.Name() + "1"), UUID: t.Name() + "1", - Hostname: strings.Replace(t.Name()+"foo.local", "/", "_", -1), + Hostname: strings.ReplaceAll(t.Name()+"foo.local", "/", "_"), }) require.NoError(t, err) t1, err := s.ds.NewTeam(ctx, &fleet.Team{ @@ -5093,14 +5093,14 @@ func (s *integrationEnterpriseTestSuite) TestGitOpsUserActions() { team1Host, err := s.ds.NewHost(ctx, &fleet.Host{ NodeKey: ptr.String(t.Name() + "2"), UUID: t.Name() + "2", - Hostname: strings.Replace(t.Name()+"zoo.local", "/", "_", -1), + Hostname: strings.ReplaceAll(t.Name()+"zoo.local", "/", "_"), TeamID: &t1.ID, }) require.NoError(t, err) globalHost, err := s.ds.NewHost(ctx, &fleet.Host{ NodeKey: ptr.String(t.Name() + "3"), UUID: t.Name() + "3", - Hostname: strings.Replace(t.Name()+"global.local", "/", "_", -1), + Hostname: strings.ReplaceAll(t.Name()+"global.local", "/", "_"), }) require.NoError(t, err) acr := appConfigResponse{} @@ -7127,7 +7127,7 @@ VALUES return err } - scID = uint(id) + scID = uint(id) //nolint:gosec // dismiss G115 return nil }) if script.ID == 0 { @@ -7366,7 +7366,7 @@ VALUES return err } - oldScriptContentsID = uint(id) + oldScriptContentsID = uint(id) //nolint:gosec // dismiss G115 res, err = tx.ExecContext(ctx, ` INSERT INTO @@ -7385,7 +7385,7 @@ VALUES if err != nil { return err } - oldScriptID = uint(id) + oldScriptID = uint(id) //nolint:gosec // dismiss G115 return nil }) @@ -7595,7 +7595,7 @@ func (s *integrationEnterpriseTestSuite) TestBatchApplyScriptsEndpoints() { teamActivity := `{"team_id": null, "team_name": null}` if team != nil { teamID = &team.ID - teamIDStr = strconv.Itoa(int(team.ID)) + teamIDStr = fmt.Sprint(team.ID) teamActivity = fmt.Sprintf(`{"team_id": %d, "team_name": %q}`, team.ID, team.Name) } @@ -7640,7 +7640,7 @@ func (s *integrationEnterpriseTestSuite) TestBatchApplyScriptsEndpoints() { // apply to both team id and name s.Do("POST", "/api/v1/fleet/scripts/batch", batchSetScriptsRequest{Scripts: nil}, - http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID)), "team_name", tm.Name) + http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID), "team_name", tm.Name) // invalid team name s.Do("POST", "/api/v1/fleet/scripts/batch", batchSetScriptsRequest{Scripts: nil}, @@ -7650,17 +7650,17 @@ func (s *integrationEnterpriseTestSuite) TestBatchApplyScriptsEndpoints() { s.Do("POST", "/api/v1/fleet/scripts/batch", batchSetScriptsRequest{Scripts: []fleet.ScriptPayload{ {Name: "N1.sh", ScriptContents: []byte("foo")}, {Name: "N1.sh", ScriptContents: []byte("bar")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) // invalid script name s.Do("POST", "/api/v1/fleet/scripts/batch", batchSetScriptsRequest{Scripts: []fleet.ScriptPayload{ {Name: "N1", ScriptContents: []byte("foo")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) // empty script name s.Do("POST", "/api/v1/fleet/scripts/batch", batchSetScriptsRequest{Scripts: []fleet.ScriptPayload{ {Name: "", ScriptContents: []byte("foo")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) // successfully apply a scripts for the team saveAndCheckScripts(tm, []fleet.ScriptPayload{ @@ -10951,7 +10951,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallers() { // check the application status titlesResp := listSoftwareTitlesResponse{} - s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", + fmt.Sprint(tm.ID)) require.Equal(t, 1, titlesResp.Count) require.Len(t, titlesResp.SoftwareTitles, 1) // Check that the URL is set to software installers uploaded via batch. @@ -10977,7 +10978,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallers() { require.NotNil(t, packages[0].TeamID) require.Equal(t, tm.ID, *packages[0].TeamID) newTitlesResp := listSoftwareTitlesResponse{} - s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &newTitlesResp, "available_for_install", "true", "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &newTitlesResp, "available_for_install", "true", "team_id", + fmt.Sprint(tm.ID)) require.Equal(t, titlesResp, newTitlesResp) // setting self-service to true updates the software title metadata @@ -10990,7 +10992,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallers() { require.NotNil(t, packages[0].TeamID) require.Equal(t, tm.ID, *packages[0].TeamID) newTitlesResp = listSoftwareTitlesResponse{} - s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &newTitlesResp, "available_for_install", "true", "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &newTitlesResp, "available_for_install", "true", "team_id", + fmt.Sprint(tm.ID)) titlesResp.SoftwareTitles[0].SoftwarePackage.SelfService = ptr.Bool(true) require.Equal(t, titlesResp, newTitlesResp) @@ -11000,7 +11003,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallers() { packages = waitBatchSetSoftwareInstallersCompleted(t, s, tm.Name, batchResponse.RequestUUID) require.Empty(t, packages) titlesResp = listSoftwareTitlesResponse{} - s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", + fmt.Sprint(tm.ID)) require.Equal(t, 0, titlesResp.Count) require.Len(t, titlesResp.SoftwareTitles, 0) @@ -11132,9 +11136,11 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersSideEffec require.Equal(t, tm.ID, *packages[0].TeamID) require.Equal(t, srv.URL, packages[0].URL) titlesResp := listSoftwareTitlesResponse{} - s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", + fmt.Sprint(tm.ID)) titleResponse := getSoftwareTitleResponse{} - s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", titlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", titlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, + "team_id", fmt.Sprint(tm.ID)) uploadedAt := titleResponse.SoftwareTitle.SoftwarePackage.UploadedAt // create a host that doesn't have fleetd installed @@ -11176,7 +11182,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersSideEffec require.Equal(t, tm.ID, *packages[0].TeamID) require.Equal(t, srv.URL, packages[0].URL) newTitlesResp := listSoftwareTitlesResponse{} - s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &newTitlesResp, "available_for_install", "true", "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &newTitlesResp, "available_for_install", "true", "team_id", + fmt.Sprint(tm.ID)) require.Equal(t, true, *newTitlesResp.SoftwareTitles[0].SoftwarePackage.SelfService) // Install should still be pending @@ -11196,7 +11203,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersSideEffec require.Equal(t, tm.ID, *packages[0].TeamID) require.Equal(t, srv.URL, packages[0].URL) titleResponse = getSoftwareTitleResponse{} - s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", newTitlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", newTitlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, + "team_id", fmt.Sprint(tm.ID)) require.Equal(t, "SELECT * FROM os_version", titleResponse.SoftwareTitle.SoftwarePackage.PreInstallQuery) require.Equal(t, uint(0), titleResponse.SoftwareTitle.SoftwarePackage.Status.PendingInstall) @@ -11218,7 +11226,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersSideEffec }`, *h.OrbitNodeKey, installUUID)), http.StatusNoContent) // ensure install count is updated - s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", newTitlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", newTitlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, + "team_id", fmt.Sprint(tm.ID)) require.Equal(t, uint(1), titleResponse.SoftwareTitle.SoftwarePackage.Status.Installed) require.Equal(t, uint(0), titleResponse.SoftwareTitle.SoftwarePackage.Status.PendingInstall) @@ -11240,7 +11249,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersSideEffec require.Equal(t, srv.URL, packages[0].URL) // ensure install count is the same, and uploaded_at hasn't changed - s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", newTitlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", newTitlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, + "team_id", fmt.Sprint(tm.ID)) require.Equal(t, uint(1), titleResponse.SoftwareTitle.SoftwarePackage.Status.Installed) require.Equal(t, uint(0), titleResponse.SoftwareTitle.SoftwarePackage.Status.PendingInstall) require.Equal(t, uploadedAt, titleResponse.SoftwareTitle.SoftwarePackage.UploadedAt) @@ -11261,7 +11271,8 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersSideEffec require.Equal(t, srv.URL, packages[0].URL) // ensure install count is zeroed and uploaded_at HAS changed - s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", newTitlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, "team_id", strconv.Itoa(int(tm.ID))) + s.DoJSON("GET", fmt.Sprintf("/api/v1/fleet/software/titles/%d", newTitlesResp.SoftwareTitles[0].ID), nil, http.StatusOK, &titleResponse, + "team_id", fmt.Sprint(tm.ID)) require.Equal(t, uint(0), titleResponse.SoftwareTitle.SoftwarePackage.Status.Installed) require.Equal(t, uint(0), titleResponse.SoftwareTitle.SoftwarePackage.Status.PendingInstall) require.NotEqual(t, uploadedAt, titleResponse.SoftwareTitle.SoftwarePackage.UploadedAt) @@ -11393,12 +11404,14 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersWithPolic require.Nil(t, policy1Team1.SoftwareInstallerID) // team1 should be empty. titlesResp := listSoftwareTitlesResponse{} - s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", strconv.Itoa(int(team1.ID))) + s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", + fmt.Sprint(team1.ID)) require.Equal(t, 0, titlesResp.Count) // team2 should be untouched. titlesResp = listSoftwareTitlesResponse{} - s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", strconv.Itoa(int(team2.ID))) + s.DoJSON("GET", "/api/v1/fleet/software/titles", nil, http.StatusOK, &titlesResp, "available_for_install", "true", "team_id", + fmt.Sprint(team2.ID)) require.Equal(t, 2, titlesResp.Count) require.Len(t, titlesResp.SoftwareTitles, 2) require.NotNil(t, titlesResp.SoftwareTitles[0].SoftwarePackage.PackageURL) @@ -11474,7 +11487,7 @@ func (s *integrationEnterpriseTestSuite) TestSoftwareInstallerNewInstallRequestP return err } titleID, _ := res.LastInsertId() - softwareTitles[kind] = uint(titleID) + softwareTitles[kind] = uint(titleID) //nolint:gosec // dismiss G115 _, err = q.ExecContext(ctx, ` INSERT INTO software_installers @@ -11686,7 +11699,8 @@ func (s *integrationEnterpriseTestSuite) TestSoftwareInstallerHostRequests() { // status is reflected in software title response titleResp := getSoftwareTitleResponse{} - s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/software/titles/%d", titleID), nil, http.StatusOK, &titleResp, "team_id", strconv.Itoa(int(*teamID))) + s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/software/titles/%d", titleID), nil, http.StatusOK, &titleResp, "team_id", + fmt.Sprint(*teamID)) // TODO: confirm expected behavior of the title response host counts (unspecified) require.Zero(t, titleResp.SoftwareTitle.HostsCount) require.Nil(t, titleResp.SoftwareTitle.CountsUpdatedAt) @@ -11720,7 +11734,8 @@ func (s *integrationEnterpriseTestSuite) TestSoftwareInstallerHostRequests() { for _, c := range cases { t.Run(c.status, func(t *testing.T) { var listResp listHostsResponse - s.DoJSON("GET", "/api/latest/fleet/hosts", nil, http.StatusOK, &listResp, "software_status", c.status, "team_id", strconv.Itoa(int(*teamID)), "software_title_id", strconv.Itoa(int(titleID))) + s.DoJSON("GET", "/api/latest/fleet/hosts", nil, http.StatusOK, &listResp, "software_status", c.status, "team_id", + fmt.Sprint(*teamID), "software_title_id", fmt.Sprint(titleID)) require.Len(t, listResp.Hosts, c.count) gotIDs := make([]uint, 0, c.count) for _, h := range listResp.Hosts { @@ -11729,16 +11744,19 @@ func (s *integrationEnterpriseTestSuite) TestSoftwareInstallerHostRequests() { require.ElementsMatch(t, c.hostIDs, gotIDs) var countResp countHostsResponse - s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", c.status, "team_id", strconv.Itoa(int(*teamID)), "software_title_id", strconv.Itoa(int(titleID))) + s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", c.status, "team_id", + fmt.Sprint(*teamID), "software_title_id", fmt.Sprint(titleID)) require.Equal(t, c.count, countResp.Count) // count with label filter countResp = countHostsResponse{} - s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", c.status, "team_id", strconv.Itoa(int(*teamID)), "software_title_id", strconv.Itoa(int(titleID)), "label_id", strconv.Itoa(int(labelResp.Label.ID))) + s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", c.status, "team_id", + fmt.Sprint(*teamID), "software_title_id", fmt.Sprint(titleID), "label_id", fmt.Sprint(labelResp.Label.ID)) require.Equal(t, c.count, countResp.Count) listResp = listHostsResponse{} - s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/labels/%d/hosts", labelResp.Label.ID), nil, http.StatusOK, &listResp, "software_status", c.status, "team_id", strconv.Itoa(int(*teamID)), "software_title_id", strconv.Itoa(int(titleID))) + s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/labels/%d/hosts", labelResp.Label.ID), nil, http.StatusOK, &listResp, + "software_status", c.status, "team_id", fmt.Sprint(*teamID), "software_title_id", fmt.Sprint(titleID)) require.Len(t, listResp.Hosts, c.count) gotIDs = make([]uint, 0, c.count) for _, h := range listResp.Hosts { @@ -11836,7 +11854,7 @@ func (s *integrationEnterpriseTestSuite) TestSoftwareInstallerHostRequests() { // Check that status is reflected in software title response titleResp = getSoftwareTitleResponse{} s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/software/titles/%d", titleID), nil, http.StatusOK, &titleResp, "team_id", - strconv.Itoa(int(*teamID))) + fmt.Sprint(*teamID)) require.NotNil(t, titleResp.SoftwareTitle.SoftwarePackage) assert.Equal(t, "ruby.deb", titleResp.SoftwareTitle.SoftwarePackage.Name) require.NotNil(t, titleResp.SoftwareTitle.SoftwarePackage.Status) @@ -12202,7 +12220,7 @@ func (s *integrationEnterpriseTestSuite) TestHostScriptSoftDelete() { // create a saved script execution request var newScriptResp createScriptResponse body, headers := generateNewScriptMultipartRequest(t, - "script1.sh", []byte(`echo "hello"`), s.token, map[string][]string{"team_id": {strconv.Itoa(int(tm.ID))}}) + "script1.sh", []byte(`echo "hello"`), s.token, map[string][]string{"team_id": {fmt.Sprint(tm.ID)}}) res := s.DoRawWithHeaders("POST", "/api/latest/fleet/scripts", body.Bytes(), http.StatusOK, headers) err = json.NewDecoder(res.Body).Decode(&newScriptResp) require.NoError(t, err) @@ -13207,7 +13225,7 @@ func (s *integrationEnterpriseTestSuite) TestCalendarCallback() { require.NoError(t, err) newStartTime := st.Add(5 * time.Minute).Format(time.RFC3339) e.Start.DateTime = newStartTime - e.Etag = e.Etag + "1" + e.Etag += "1" } // Grab the lock @@ -14959,7 +14977,8 @@ func (s *integrationEnterpriseTestSuite) TestMaintainedApps() { // Check apps returned var listMAResp listFleetMaintainedAppsResponse - s.DoJSON(http.MethodGet, "/api/latest/fleet/software/fleet_maintained_apps", listFleetMaintainedAppsRequest{}, http.StatusOK, &listMAResp, "team_id", strconv.Itoa(int(team.ID))) + s.DoJSON(http.MethodGet, "/api/latest/fleet/software/fleet_maintained_apps", listFleetMaintainedAppsRequest{}, http.StatusOK, + &listMAResp, "team_id", fmt.Sprint(team.ID)) require.Nil(t, listMAResp.Err) require.False(t, listMAResp.Meta.HasPreviousResults) require.False(t, listMAResp.Meta.HasNextResults) @@ -14984,7 +15003,7 @@ func (s *integrationEnterpriseTestSuite) TestMaintainedApps() { listFleetMaintainedAppsRequest{}, http.StatusOK, &listMAResp2, - "team_id", strconv.Itoa(int(team.ID)), + "team_id", fmt.Sprint(team.ID), "per_page", "2", "page", "2", ) @@ -15018,7 +15037,8 @@ func (s *integrationEnterpriseTestSuite) TestMaintainedApps() { s.DoJSON("POST", "/api/latest/fleet/software/fleet_maintained_apps", req, http.StatusOK, &addMAResp) require.Nil(t, addMAResp.Err) - s.DoJSON(http.MethodGet, "/api/latest/fleet/software/fleet_maintained_apps", listFleetMaintainedAppsRequest{}, http.StatusOK, &listMAResp, "team_id", strconv.Itoa(int(team.ID))) + s.DoJSON(http.MethodGet, "/api/latest/fleet/software/fleet_maintained_apps", listFleetMaintainedAppsRequest{}, http.StatusOK, + &listMAResp, "team_id", fmt.Sprint(team.ID)) require.Nil(t, listMAResp.Err) require.False(t, listMAResp.Meta.HasPreviousResults) require.Len(t, listMAResp.FleetMaintainedApps, len(expectedApps)-1) diff --git a/server/service/integration_live_queries_test.go b/server/service/integration_live_queries_test.go index 7d3cfef7f1..5d5c009aa4 100644 --- a/server/service/integration_live_queries_test.go +++ b/server/service/integration_live_queries_test.go @@ -130,7 +130,7 @@ func (s *liveQueriesTestSuite) TestLiveQueriesRestOneHostOneQuery() { oneLiveQueryResp := runOneLiveQueryResponse{} liveQueryResp := runLiveQueryResponse{} liveQueryOnHostResp := runLiveQueryOnHostResponse{} - if endpoint == oneQueryEndpoint { + if endpoint == oneQueryEndpoint { //nolint:gocritic // ignore ifElseChain liveQueryRequest := runOneLiveQueryRequest{ HostIDs: []uint{host.ID}, } @@ -237,7 +237,7 @@ func (s *liveQueriesTestSuite) TestLiveQueriesRestOneHostOneQuery() { wg.Wait() var result fleet.QueryResult - if endpoint == oneQueryEndpoint { + if endpoint == oneQueryEndpoint { //nolint:gocritic // ignore ifElseChain assert.Equal(t, q1.ID, oneLiveQueryResp.QueryID) assert.Equal(t, 1, oneLiveQueryResp.TargetedHostCount) assert.Equal(t, 1, oneLiveQueryResp.RespondedHostCount) diff --git a/server/service/integration_mdm_dep_test.go b/server/service/integration_mdm_dep_test.go index 95bd4a5b35..4a35a623f3 100644 --- a/server/service/integration_mdm_dep_test.go +++ b/server/service/integration_mdm_dep_test.go @@ -325,7 +325,8 @@ func (s *integrationMDMTestSuite) runDEPEnrollReleaseDeviceTest(t *testing.T, de switch cmd.Command.RequestType { case "InstallProfile": installProfileCount++ - if strings.Contains(string(cmd.Command.InstallProfile.Payload), fmt.Sprintf("%s", customProfileIdent)) { + if strings.Contains(string(cmd.Command.InstallProfile.Payload), //nolint:gocritic // ignore ifElseChain + fmt.Sprintf("%s", customProfileIdent)) { profileCustomSeen = true } else if strings.Contains(string(cmd.Command.InstallProfile.Payload), fmt.Sprintf("%s", mobileconfig.FleetdConfigPayloadIdentifier)) { profileFleetdSeen = true diff --git a/server/service/integration_mdm_profiles_test.go b/server/service/integration_mdm_profiles_test.go index 2b74bdcde9..a9a5ad60aa 100644 --- a/server/service/integration_mdm_profiles_test.go +++ b/server/service/integration_mdm_profiles_test.go @@ -12,7 +12,6 @@ import ( "net/http" "net/url" "sort" - "strconv" "strings" "testing" "time" @@ -72,8 +71,9 @@ func (s *integrationMDMTestSuite) TestAppleProfileManagement() { mobileconfigForTest("N1", "I1"), mobileconfigForTest("N2", "I2"), } - wantGlobalProfiles := append( - globalProfiles, + wantGlobalProfiles := globalProfiles + wantGlobalProfiles = append( + wantGlobalProfiles, setupExpectedFleetdProfile(t, s.server.URL, t.Name(), nil), ) @@ -94,12 +94,14 @@ func (s *integrationMDMTestSuite) TestAppleProfileManagement() { teamProfiles := [][]byte{ mobileconfigForTest("N3", "I3"), } - wantTeamProfiles := append( - teamProfiles, + wantTeamProfiles := teamProfiles + wantTeamProfiles = append( + wantTeamProfiles, setupExpectedFleetdProfile(t, s.server.URL, "team1_enroll_sec", &tm.ID), ) // add profiles to the team - s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: teamProfiles}, http.StatusNoContent, "team_id", strconv.Itoa(int(tm.ID))) + s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: teamProfiles}, http.StatusNoContent, + "team_id", fmt.Sprint(tm.ID)) // create a non-macOS host _, err = s.ds.NewHost(context.Background(), &fleet.Host{ @@ -175,7 +177,8 @@ func (s *integrationMDMTestSuite) TestAppleProfileManagement() { mobileconfigForTest("N5", "I5"), } wantTeamProfiles = teamProfiles - s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: teamProfiles}, http.StatusNoContent, "team_id", strconv.Itoa(int(tm.ID))) + s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: teamProfiles}, http.StatusNoContent, + "team_id", fmt.Sprint(tm.ID)) // trigger a profile sync s.awaitTriggerProfileSchedule(t) @@ -395,8 +398,9 @@ func (s *integrationMDMTestSuite) TestAppleProfileRetries() { mobileconfigForTest("N1", "I1"), mobileconfigForTest("N2", "I2"), } - initialExpectedProfiles := append( - testProfiles, + initialExpectedProfiles := testProfiles + initialExpectedProfiles = append( + initialExpectedProfiles, setupExpectedFleetdProfile(t, s.server.URL, enrollSecret, nil), setupExpectedCAProfile(t, s.ds), ) @@ -1669,7 +1673,7 @@ func (s *integrationMDMTestSuite) TestMDMAppleListConfigProfiles() { require.NotNil(t, resp.ConfigProfiles) require.Len(t, resp.ConfigProfiles, 2) for _, p := range resp.ConfigProfiles { - if p.Name == p2.Name { + if p.Name == p2.Name { //nolint:gocritic // ignore ifElseChain require.Equal(t, p2.Identifier, p.Identifier) } else if p.Name == p3.Name { require.Equal(t, p3.Identifier, p.Identifier) @@ -1939,7 +1943,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMAppleProfiles() { // apply to both team id and name s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: nil}, - http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID)), "team_name", tm.Name) + http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID), "team_name", tm.Name) // invalid team name s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: nil}, @@ -1954,14 +1958,14 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMAppleProfiles() { s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: [][]byte{ mobileconfigForTest("N1", "I1"), mobileconfigForTest("N1", "I2"), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) // profiles with reserved identifiers for p := range mobileconfig.FleetPayloadIdentifiers() { res := s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: [][]byte{ mobileconfigForTest("N1", "I1"), mobileconfigForTest(p, p), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: payload identifier %s is not allowed", p)) } @@ -1970,7 +1974,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMAppleProfiles() { for p := range mobileconfig.FleetPayloadTypes() { res := s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: [][]byte{ mobileconfigForTestWithContent("N1", "I1", "II1", p, ""), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: unsupported PayloadType(s): %s", p)) } @@ -1979,7 +1983,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMAppleProfiles() { for p := range mobileconfig.FleetPayloadIdentifiers() { res := s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: [][]byte{ mobileconfigForTestWithContent("N1", "I1", p, "random", ""), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: unsupported PayloadIdentifier(s): %s", p)) } @@ -1987,7 +1991,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMAppleProfiles() { // successfully apply a profile for the team s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: [][]byte{ mobileconfigForTest("N1", "I1"), - }}, http.StatusNoContent, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusNoContent, "team_id", fmt.Sprint(tm.ID)) s.lastActivityMatches( fleet.ActivityTypeEditedMacosProfile{}.ActivityName(), fmt.Sprintf(`{"team_id": %d, "team_name": %q}`, tm.ID, tm.Name), @@ -2075,7 +2079,7 @@ func (s *integrationMDMTestSuite) TestHostMDMAppleProfilesStatus() { } s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: tm1Profiles}, http.StatusNoContent, - "team_id", strconv.Itoa(int(tm1.ID))) + "team_id", fmt.Sprint(tm1.ID)) // create the team 1 enroll secret var teamResp teamEnrollSecretsResponse tm1EnrollSec := "team1_enroll_sec" @@ -2092,7 +2096,7 @@ func (s *integrationMDMTestSuite) TestHostMDMAppleProfilesStatus() { } s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: tm2Profiles}, http.StatusNoContent, - "team_id", strconv.Itoa(int(tm2.ID))) + "team_id", fmt.Sprint(tm2.ID)) // enroll a couple hosts in no team h1 := createManualMDMEnrollWithOrbit(globalEnrollSec) @@ -2625,7 +2629,7 @@ func (s *integrationMDMTestSuite) TestMDMConfigProfileCRUD() { addLabelsFields := func(labelNames []string) map[string][]string { var deprLabels, inclLabels, exclLabels []string for _, lbl := range labelNames { - if strings.HasPrefix(lbl, "-") { + if strings.HasPrefix(lbl, "-") { //nolint:gocritic // ignore ifElseChain exclLabels = append(exclLabels, strings.TrimPrefix(lbl, "-")) } else if strings.HasPrefix(lbl, "!") { deprLabels = append(deprLabels, strings.TrimPrefix(lbl, "!")) @@ -2940,7 +2944,7 @@ func (s *integrationMDMTestSuite) TestMDMConfigProfileCRUD() { resp := s.Do("GET", fmt.Sprintf("/api/latest/fleet/configuration_profiles/%s", prof.ProfileUUID), nil, http.StatusOK, "alt", "media") require.NotZero(t, resp.ContentLength) require.Contains(t, resp.Header.Get("Content-Disposition"), "attachment;") - if strings.HasPrefix(prof.ProfileUUID, "a") { + if strings.HasPrefix(prof.ProfileUUID, "a") { //nolint:gocritic // ignore ifElseChain require.Contains(t, resp.Header.Get("Content-Type"), "application/x-apple-aspen-config") } else if strings.HasPrefix(prof.ProfileUUID, fleet.MDMAppleDeclarationUUIDPrefix) { require.Contains(t, resp.Header.Get("Content-Type"), "application/json") @@ -3816,7 +3820,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { // apply to both team id and name s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: nil}, - http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID)), "team_name", tm.Name) + http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID), "team_name", tm.Name) // invalid team name s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: nil}, @@ -3828,7 +3832,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N2", Contents: mobileconfigForTest("N1", "I2")}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: declarationForTest("D1")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) // profiles with reserved macOS identifiers for p := range mobileconfig.FleetPayloadIdentifiers() { @@ -3837,7 +3841,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: p, Contents: mobileconfigForTest(p, p)}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: declarationForTest("D1")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: payload identifier %s is not allowed", p)) } @@ -3848,7 +3852,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTestWithContent("N1", "I1", "II1", p, "")}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: declarationForTest("D1")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: unsupported PayloadType(s): %s", p)) } @@ -3859,7 +3863,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTestWithContent("N1", "I1", p, "random", "")}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: declarationForTest("D1")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: unsupported PayloadIdentifier(s): %s", p)) } @@ -3870,7 +3874,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTest("N1", "I1")}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: declarationForTestWithType("D1", dt)}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, "Only configuration declarations that don’t require an asset reference are supported", dt) } @@ -3879,7 +3883,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTest("N1", "I1")}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: declarationForTestWithType("D1", "com.apple.configuration.softwareupdate.enforcement.specific")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, "Declaration profile can’t include OS updates settings. To control these settings, go to OS updates.") @@ -3888,7 +3892,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTest("N1", "I1")}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: []byte(`{"foo":}`)}, - }}, http.StatusBadRequest, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusBadRequest, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, "The file should include valid JSON") @@ -3898,7 +3902,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTest("N1", "I1")}, {Name: syncml.FleetBitLockerTargetLocURI, Contents: syncMLForTest(fmt.Sprintf("%s/Foo", syncml.FleetBitLockerTargetLocURI))}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, "Custom configuration profiles can't include BitLocker settings. To control these settings, use the mdm.enable_disk_encryption option.") @@ -3907,21 +3911,21 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTest("N1", "I1")}, {Name: syncml.FleetOSUpdateTargetLocURI, Contents: syncMLForTest(fmt.Sprintf("%s/Foo", syncml.FleetOSUpdateTargetLocURI))}, {Name: "N3", Contents: syncMLForTest("./Foo/Bar")}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, "Custom configuration profiles can't include Windows updates settings. To control these settings, use the mdm.windows_updates option.") // invalid windows tag res = s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: []fleet.MDMProfileBatchPayload{ {Name: "N3", Contents: []byte(``)}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, "Windows configuration profiles can only have or top level elements.") // invalid xml res = s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: []fleet.MDMProfileBatchPayload{ {Name: "N3", Contents: []byte(`foo`)}, - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, "Windows configuration profiles can only have or top level elements.") @@ -3930,7 +3934,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTest("N1", "I1")}, {Name: "N2", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: declarationForTest("D1")}, - }}, http.StatusNoContent, "team_id", strconv.Itoa(int(tm.ID)), "dry_run", "true") + }}, http.StatusNoContent, "team_id", fmt.Sprint(tm.ID), "dry_run", "true") s.assertConfigProfilesByIdentifier(&tm.ID, "I1", false) s.assertWindowsConfigProfilesByName(&tm.ID, "N1", false) @@ -3939,7 +3943,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { {Name: "N1", Contents: mobileconfigForTest("N1", "I1")}, {Name: "N2", Contents: syncMLForTest("./Foo/Bar")}, {Name: "N4", Contents: declarationForTest("D1")}, - }}, http.StatusNoContent, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusNoContent, "team_id", fmt.Sprint(tm.ID)) s.assertConfigProfilesByIdentifier(&tm.ID, "I1", true) s.assertWindowsConfigProfilesByName(&tm.ID, "N2", true) s.lastActivityOfTypeMatches( @@ -4058,7 +4062,8 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfiles() { }, } { // team profiles - res = s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: p.payload}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + res = s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: p.payload}, + http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, p.expectErr) // no team profiles @@ -4092,7 +4097,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { // apply to both team id and name s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", map[string]any{"profiles": nil}, - http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID)), "team_name", tm.Name) + http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID), "team_name", tm.Name) // invalid team name s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", map[string]any{"profiles": nil}, @@ -4103,7 +4108,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { "N1": mobileconfigForTest("N1", "I1"), "N2": mobileconfigForTest("N1", "I2"), "N3": syncMLForTest("./Foo/Bar"), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) // profiles with reserved macOS identifiers for p := range mobileconfig.FleetPayloadIdentifiers() { @@ -4111,7 +4116,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { "N1": mobileconfigForTest("N1", "I1"), p: mobileconfigForTest(p, p), "N3": syncMLForTest("./Foo/Bar"), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: payload identifier %s is not allowed", p)) } @@ -4121,7 +4126,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { res := s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", map[string]any{"profiles": map[string][]byte{ "N1": mobileconfigForTestWithContent("N1", "I1", "II1", p, ""), "N3": syncMLForTest("./Foo/Bar"), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: unsupported PayloadType(s): %s", p)) } @@ -4131,7 +4136,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { res := s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", map[string]any{"profiles": map[string][]byte{ "N1": mobileconfigForTestWithContent("N1", "I1", p, "random", ""), "N3": syncMLForTest("./Foo/Bar"), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, fmt.Sprintf("Validation Failed: unsupported PayloadIdentifier(s): %s", p)) } @@ -4142,7 +4147,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { "N1": mobileconfigForTest("N1", "I1"), syncml.FleetBitLockerTargetLocURI: syncMLForTest(fmt.Sprintf("%s/Foo", syncml.FleetBitLockerTargetLocURI)), "N3": syncMLForTest("./Foo/Bar"), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg := extractServerErrorText(res.Body) require.Contains(t, errMsg, "Custom configuration profiles can't include BitLocker settings. To control these settings, use the mdm.enable_disk_encryption option.") @@ -4151,21 +4156,21 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { "N1": mobileconfigForTest("N1", "I1"), syncml.FleetOSUpdateTargetLocURI: syncMLForTest(fmt.Sprintf("%s/Foo", syncml.FleetOSUpdateTargetLocURI)), "N3": syncMLForTest("./Foo/Bar"), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, "Custom configuration profiles can't include Windows updates settings. To control these settings, use the mdm.windows_updates option.") // invalid windows tag res = s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", map[string]any{"profiles": map[string][]byte{ "N3": []byte(``), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, "Windows configuration profiles can only have or top level elements.") // invalid xml res = s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", map[string]any{"profiles": map[string][]byte{ "N3": []byte(`foo`), - }}, http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusUnprocessableEntity, "team_id", fmt.Sprint(tm.ID)) errMsg = extractServerErrorText(res.Body) require.Contains(t, errMsg, "Windows configuration profiles can only have or top level elements.") @@ -4173,7 +4178,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", map[string]any{"profiles": map[string][]byte{ "N1": mobileconfigForTest("N1", "I1"), "N2": syncMLForTest("./Foo/Bar"), - }}, http.StatusNoContent, "team_id", strconv.Itoa(int(tm.ID)), "dry_run", "true") + }}, http.StatusNoContent, "team_id", fmt.Sprint(tm.ID), "dry_run", "true") s.assertConfigProfilesByIdentifier(&tm.ID, "I1", false) s.assertWindowsConfigProfilesByName(&tm.ID, "N1", false) @@ -4181,7 +4186,7 @@ func (s *integrationMDMTestSuite) TestBatchSetMDMProfilesBackwardsCompat() { s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", map[string]any{"profiles": map[string][]byte{ "N1": mobileconfigForTest("N1", "I1"), "N2": syncMLForTest("./Foo/Bar"), - }}, http.StatusNoContent, "team_id", strconv.Itoa(int(tm.ID))) + }}, http.StatusNoContent, "team_id", fmt.Sprint(tm.ID)) s.assertConfigProfilesByIdentifier(&tm.ID, "I1", true) s.assertWindowsConfigProfilesByName(&tm.ID, "N2", true) s.lastActivityOfTypeMatches( @@ -4329,7 +4334,8 @@ func (s *integrationMDMTestSuite) TestMDMBatchSetProfilesKeepsReservedNames() { Name: "n1", Contents: newWinProfile, }) - s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: testTeamProfiles}, http.StatusNoContent, "team_id", strconv.Itoa(int(tmResp.Team.ID))) + s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: testTeamProfiles}, http.StatusNoContent, + "team_id", fmt.Sprint(tmResp.Team.ID)) checkMacProfs(&tmResp.Team.ID, servermdm.ListFleetReservedMacOSProfileNames()...) checkWinProfs(&tmResp.Team.ID, append(servermdm.ListFleetReservedWindowsProfileNames(), "n1")...) @@ -4338,7 +4344,8 @@ func (s *integrationMDMTestSuite) TestMDMBatchSetProfilesKeepsReservedNames() { Name: "n2", Contents: newMacProfile, }) - s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: testTeamProfiles}, http.StatusNoContent, "team_id", strconv.Itoa(int(tmResp.Team.ID))) + s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: testTeamProfiles}, http.StatusNoContent, + "team_id", fmt.Sprint(tmResp.Team.ID)) checkMacProfs(&tmResp.Team.ID, append(servermdm.ListFleetReservedMacOSProfileNames(), "n2")...) checkWinProfs(&tmResp.Team.ID, append(servermdm.ListFleetReservedWindowsProfileNames(), "n1")...) @@ -4347,7 +4354,8 @@ func (s *integrationMDMTestSuite) TestMDMBatchSetProfilesKeepsReservedNames() { Name: "n2", Contents: newMacProfile, }} - s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: testTeamProfiles}, http.StatusNoContent, "team_id", strconv.Itoa(int(tmResp.Team.ID))) + s.Do("POST", "/api/v1/fleet/mdm/profiles/batch", batchSetMDMProfilesRequest{Profiles: testTeamProfiles}, http.StatusNoContent, + "team_id", fmt.Sprint(tmResp.Team.ID)) checkMacProfs(&tmResp.Team.ID, append(servermdm.ListFleetReservedMacOSProfileNames(), "n2")...) checkWinProfs(&tmResp.Team.ID, servermdm.ListFleetReservedWindowsProfileNames()...) } diff --git a/server/service/integration_mdm_test.go b/server/service/integration_mdm_test.go index 0aac57fba6..26b19f62a2 100644 --- a/server/service/integration_mdm_test.go +++ b/server/service/integration_mdm_test.go @@ -543,8 +543,7 @@ func (s *integrationMDMTestSuite) SetupSuite() { Version: "2024-06-25_03-01-17", } downloadFleetdmSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/stable/meta.json": + if r.URL.Path == "/stable/meta.json" { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) require.NoError(s.T(), json.NewEncoder(w).Encode(s.mockedDownloadFleetdmMeta)) @@ -2481,7 +2480,7 @@ func (s *integrationMDMTestSuite) TestTeamsMDMAppleDiskEncryption() { // apply an empty set of batch profiles to the team s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{Profiles: nil}, - http.StatusUnprocessableEntity, "team_id", strconv.Itoa(int(team.ID)), "team_name", team.Name) + http.StatusUnprocessableEntity, "team_id", fmt.Sprint(team.ID), "team_name", team.Name) // the configuration profile is still there s.assertConfigProfilesByIdentifier(ptr.Uint(team.ID), mobileconfig.FleetFileVaultPayloadIdentifier, true) @@ -3346,10 +3345,10 @@ func (s *integrationMDMTestSuite) TestBootstrapPackageStatus() { if manifest := fullCmd.Command.InstallEnterpriseApplication.Manifest; manifest != nil { require.Equal(t, "InstallEnterpriseApplication", cmd.Command.RequestType) require.NotNil(t, manifest) - require.Equal(t, "software-package", (*manifest).ManifestItems[0].Assets[0].Kind) + require.Equal(t, "software-package", manifest.ManifestItems[0].Assets[0].Kind) wantURL, err := bp.URL(s.server.URL) require.NoError(t, err) - require.Equal(t, wantURL, (*manifest).ManifestItems[0].Assets[0].URL) + require.Equal(t, wantURL, manifest.ManifestItems[0].Assets[0].URL) // respond to the command accordingly switch d.bootstrapResponse { @@ -4948,7 +4947,7 @@ func (s *integrationMDMTestSuite) TestGitOpsUserActions() { } s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{ Profiles: teamProfiles, - }, http.StatusNoContent, "team_id", strconv.Itoa(int(t1.ID))) + }, http.StatusNoContent, "team_id", fmt.Sprint(t1.ID)) // // Start running permission tests with user gitops2-mdm, @@ -4975,7 +4974,7 @@ func (s *integrationMDMTestSuite) TestGitOpsUserActions() { } s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{ Profiles: teamProfiles, - }, http.StatusNoContent, "team_id", strconv.Itoa(int(t1.ID))) + }, http.StatusNoContent, "team_id", fmt.Sprint(t1.ID)) // Attempt to set profile batch for team t2, should not allow. teamProfiles = [][]byte{ @@ -4984,7 +4983,7 @@ func (s *integrationMDMTestSuite) TestGitOpsUserActions() { } s.Do("POST", "/api/v1/fleet/mdm/apple/profiles/batch", batchSetMDMAppleProfilesRequest{ Profiles: teamProfiles, - }, http.StatusForbidden, "team_id", strconv.Itoa(int(t2.ID))) + }, http.StatusForbidden, "team_id", fmt.Sprint(t2.ID)) // Attempt to retrieve host profiles fails if the host doesn't belong to the team h1, err := s.ds.NewHost(ctx, &fleet.Host{ @@ -10589,7 +10588,8 @@ func (s *integrationMDMTestSuite) TestVPPApps() { // We're passing team 1 here, but we haven't added any app store apps to that team, so we get // back all available apps in our VPP location. var appResp getAppStoreAppsResponse - s.DoJSON("GET", "/api/latest/fleet/software/app_store_apps", &getAppStoreAppsRequest{}, http.StatusOK, &appResp, "team_id", strconv.Itoa(int(team.ID))) + s.DoJSON("GET", "/api/latest/fleet/software/app_store_apps", &getAppStoreAppsRequest{}, http.StatusOK, &appResp, "team_id", + fmt.Sprint(team.ID)) require.NoError(t, appResp.Err) macOSApp := fleet.VPPApp{ VPPAppTeam: fleet.VPPAppTeam{ @@ -10672,7 +10672,8 @@ func (s *integrationMDMTestSuite) TestVPPApps() { // Now we should be filtering out the app we added to team 1 appResp = getAppStoreAppsResponse{} - s.DoJSON("GET", "/api/latest/fleet/software/app_store_apps", &getAppStoreAppsRequest{}, http.StatusOK, &appResp, "team_id", strconv.Itoa(int(team.ID))) + s.DoJSON("GET", "/api/latest/fleet/software/app_store_apps", &getAppStoreAppsRequest{}, http.StatusOK, &appResp, "team_id", + fmt.Sprint(team.ID)) require.NoError(t, appResp.Err) assert.ElementsMatch(t, expectedApps[1:], appResp.AppStoreApps) @@ -10723,7 +10724,7 @@ func (s *integrationMDMTestSuite) TestVPPApps() { // Now we should be filtering out the app we added to team 1 appResp = getAppStoreAppsResponse{} s.DoJSON("GET", "/api/latest/fleet/software/app_store_apps", &getAppStoreAppsRequest{}, http.StatusOK, &appResp, "team_id", - strconv.Itoa(int(team.ID))) + fmt.Sprint(team.ID)) require.NoError(t, appResp.Err) assert.ElementsMatch(t, append(expectedApps[2:], expectedApps[0]), appResp.AppStoreApps) @@ -10888,11 +10889,13 @@ func (s *integrationMDMTestSuite) TestVPPApps() { // Check if the host is listed as pending var listResp listHostsResponse - s.DoJSON("GET", "/api/latest/fleet/hosts", nil, http.StatusOK, &listResp, "software_status", "pending", "team_id", strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(errTitleID))) + s.DoJSON("GET", "/api/latest/fleet/hosts", nil, http.StatusOK, &listResp, "software_status", "pending", "team_id", fmt.Sprint(team.ID), + "software_title_id", fmt.Sprint(errTitleID)) require.Len(t, listResp.Hosts, 1) require.Equal(t, listResp.Hosts[0].ID, mdmHost.ID) var countResp countHostsResponse - s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", "pending", "team_id", strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(errTitleID))) + s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", "pending", "team_id", + fmt.Sprint(team.ID), "software_title_id", fmt.Sprint(errTitleID)) require.Equal(t, 1, countResp.Count) // Simulate failed installation on the host @@ -10901,7 +10904,7 @@ func (s *integrationMDMTestSuite) TestVPPApps() { require.NoError(t, err) for cmd != nil { var fullCmd micromdm.CommandPayload - switch cmd.Command.RequestType { + switch cmd.Command.RequestType { //nolint:gocritic // ignore singleCaseSwitch case "InstallApplication": require.NoError(t, plist.Unmarshal(cmd.Raw, &fullCmd)) failedCmdUUID = cmd.CommandUUID @@ -10911,11 +10914,13 @@ func (s *integrationMDMTestSuite) TestVPPApps() { } listResp = listHostsResponse{} - s.DoJSON("GET", "/api/latest/fleet/hosts", nil, http.StatusOK, &listResp, "software_status", "failed", "team_id", strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(errTitleID))) + s.DoJSON("GET", "/api/latest/fleet/hosts", nil, http.StatusOK, &listResp, "software_status", "failed", "team_id", fmt.Sprint(team.ID), + "software_title_id", fmt.Sprint(errTitleID)) require.Len(t, listResp.Hosts, 1) require.Equal(t, listResp.Hosts[0].ID, mdmHost.ID) countResp = countHostsResponse{} - s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", "failed", "team_id", strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(errTitleID))) + s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", "failed", "team_id", + fmt.Sprint(team.ID), "software_title_id", fmt.Sprint(errTitleID)) require.Equal(t, 1, countResp.Count) s.lastActivityMatches( @@ -10938,7 +10943,7 @@ func (s *integrationMDMTestSuite) TestVPPApps() { http.StatusAccepted, &installResp) countResp = countHostsResponse{} s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", "pending", "team_id", - strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(macOSTitleID))) + fmt.Sprint(team.ID), "software_title_id", fmt.Sprint(macOSTitleID)) require.Equal(t, 1, countResp.Count) // Simulate successful installation on the host @@ -10947,7 +10952,7 @@ func (s *integrationMDMTestSuite) TestVPPApps() { require.NoError(t, err) for cmd != nil { var fullCmd micromdm.CommandPayload - switch cmd.Command.RequestType { + switch cmd.Command.RequestType { //nolint:gocritic // ignore singleCaseSwitch case "InstallApplication": require.NoError(t, plist.Unmarshal(cmd.Raw, &fullCmd)) cmdUUID = cmd.CommandUUID @@ -10958,11 +10963,11 @@ func (s *integrationMDMTestSuite) TestVPPApps() { listResp = listHostsResponse{} s.DoJSON("GET", "/api/latest/fleet/hosts", nil, http.StatusOK, &listResp, "software_status", "installed", "team_id", - strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(macOSTitleID))) + fmt.Sprint(team.ID), "software_title_id", fmt.Sprint(macOSTitleID)) require.Len(t, listResp.Hosts, 1) countResp = countHostsResponse{} s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", "installed", "team_id", - strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(macOSTitleID))) + fmt.Sprint(team.ID), "software_title_id", fmt.Sprint(macOSTitleID)) require.Equal(t, 1, countResp.Count) s.lastActivityMatches( @@ -11118,7 +11123,7 @@ func (s *integrationMDMTestSuite) TestVPPApps() { } countResp = countHostsResponse{} s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", "pending", "team_id", - strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(titleID))) + fmt.Sprint(team.ID), "software_title_id", fmt.Sprint(titleID)) require.Equal(t, 1, countResp.Count) // send an idle request to grab the command uuid @@ -11163,11 +11168,11 @@ func (s *integrationMDMTestSuite) TestVPPApps() { listResp = listHostsResponse{} s.DoJSON("GET", "/api/latest/fleet/hosts", nil, http.StatusOK, &listResp, "software_status", "installed", "team_id", - strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(titleID))) + fmt.Sprint(team.ID), "software_title_id", fmt.Sprint(titleID)) assert.Len(t, listResp.Hosts, install.hostCount) countResp = countHostsResponse{} s.DoJSON("GET", "/api/latest/fleet/hosts/count", nil, http.StatusOK, &countResp, "software_status", "installed", "team_id", - strconv.Itoa(int(team.ID)), "software_title_id", strconv.Itoa(int(titleID))) + fmt.Sprint(team.ID), "software_title_id", fmt.Sprint(titleID)) assert.Equal(t, install.hostCount, countResp.Count) s.lastActivityMatches( diff --git a/server/service/jitter.go b/server/service/jitter.go index e69fd39c82..34f2932375 100644 --- a/server/service/jitter.go +++ b/server/service/jitter.go @@ -63,7 +63,7 @@ func (jh *jitterHashTable) jitterForHost(hostID uint) time.Duration { } for i := 0; i < jh.bucketCount; i++ { - possibleBucket := (int(hostID) + i) % jh.bucketCount + possibleBucket := (int(hostID) + i) % jh.bucketCount //nolint:gosec // dismiss G115 // if the next bucket has capacity, great! if jh.buckets[possibleBucket] < jh.maxCapacity { diff --git a/server/service/jitter_test.go b/server/service/jitter_test.go index cc838fc973..9329f92317 100644 --- a/server/service/jitter_test.go +++ b/server/service/jitter_test.go @@ -17,7 +17,7 @@ func TestJitterForHost(t *testing.T) { for i := 0; i < hostCount; i++ { hostID, err := crand.Int(crand.Reader, big.NewInt(10000)) require.NoError(t, err) - jitter := jh.jitterForHost(uint(hostID.Int64() + 10000)) + jitter := jh.jitterForHost(uint(hostID.Int64() + 10000)) //nolint:gosec // dismiss G115 jitterMinutes := int64(jitter.Minutes()) histogram[jitterMinutes]++ } @@ -45,7 +45,7 @@ func TestNoJitter(t *testing.T) { for i := 0; i < hostCount; i++ { hostID, err := crand.Int(crand.Reader, big.NewInt(10000)) require.NoError(t, err) - jitter := jh.jitterForHost(uint(hostID.Int64() + 10000)) + jitter := jh.jitterForHost(uint(hostID.Int64() + 10000)) //nolint:gosec // dismiss G115 jitterMinutes := int64(jitter.Minutes()) require.Equal(t, int64(0), jitterMinutes) } diff --git a/server/service/live_queries.go b/server/service/live_queries.go index 11c46457b5..5f1327c0a1 100644 --- a/server/service/live_queries.go +++ b/server/service/live_queries.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "os" - "strconv" "strings" "sync" "time" @@ -181,7 +180,7 @@ func runLiveQueryOnHost(svc fleet.Service, ctx context.Context, host *fleet.Host if len(queryResults) > 0 { var err error - if queryResults[0].Err != nil { + if queryResults[0].Err != nil { //nolint:gocritic // ignore ifelseChain err = queryResults[0].Err } else if len(queryResults[0].Results) > 0 { queryResult := queryResults[0].Results[0] @@ -404,7 +403,7 @@ func (svc *Service) CompleteCampaign(ctx context.Context, campaign *fleet.Distri if err != nil { return ctxerr.Wrap(ctx, err, "saving distributed campaign after complete") } - err = svc.liveQueryStore.StopQuery(strconv.Itoa(int(campaign.ID))) + err = svc.liveQueryStore.StopQuery(fmt.Sprint(campaign.ID)) if err != nil { return ctxerr.Wrap(ctx, err, "stopping query after after complete") } diff --git a/server/service/maintained_apps.go b/server/service/maintained_apps.go index caa87118e6..ad08e3542a 100644 --- a/server/service/maintained_apps.go +++ b/server/service/maintained_apps.go @@ -91,7 +91,7 @@ func listFleetMaintainedAppsEndpoint(ctx context.Context, request any, svc fleet listResp := listFleetMaintainedAppsResponse{ FleetMaintainedApps: apps, - Count: int(meta.TotalResults), + Count: int(meta.TotalResults), //nolint:gosec // dismiss G115 Meta: meta, } if !latest.IsZero() { diff --git a/server/service/mdm.go b/server/service/mdm.go index 9d7702decf..90da395ceb 100644 --- a/server/service/mdm.go +++ b/server/service/mdm.go @@ -1111,7 +1111,7 @@ func deleteMDMConfigProfileEndpoint(ctx context.Context, request interface{}, sv req := request.(*deleteMDMConfigProfileRequest) var err error - if isAppleProfileUUID(req.ProfileUUID) { + if isAppleProfileUUID(req.ProfileUUID) { //nolint:gocritic // ignore ifElseChain err = svc.DeleteMDMAppleConfigProfile(ctx, req.ProfileUUID) } else if isAppleDeclarationUUID(req.ProfileUUID) { // TODO: we could potentially combined with the other service methods @@ -1233,7 +1233,7 @@ func (newMDMConfigProfileRequest) DecodeRequest(ctx context.Context, r *http.Req if err != nil { return nil, &fleet.BadRequestError{Message: fmt.Sprintf("failed to decode team_id in multipart form: %s", err.Error())} } - decoded.TeamID = uint(teamID) + decoded.TeamID = uint(teamID) //nolint:gosec // dismiss G115 } // add profile diff --git a/server/service/microsoft_mdm.go b/server/service/microsoft_mdm.go index b247137cf2..78fde975ff 100644 --- a/server/service/microsoft_mdm.go +++ b/server/service/microsoft_mdm.go @@ -494,7 +494,7 @@ func NewSoapResponse(payload interface{}, relatesTo string) (fleet.SoapResponse, // Setting the target action case *mdm_types.SoapFault: - if msg.OriginalMessageType == mdm_types.MDEDiscovery { + if msg.OriginalMessageType == mdm_types.MDEDiscovery { //nolint:gocritic // ignore ifElseChain action = urlDiscovery } else if msg.OriginalMessageType == mdm_types.MDEPolicy { action = urlPolicy @@ -1610,7 +1610,8 @@ func (svc *Service) getManagementResponse(ctx context.Context, reqMsg *fleet.Syn } // Combined cmd responses - resCmds := append(resIncomingCmds, resPendingCmds...) + resCmds := resIncomingCmds + resCmds = append(resCmds, resPendingCmds...) // Create the response SyncML message msg, err := svc.createResponseSyncML(ctx, reqMsg, resCmds) diff --git a/server/service/osquery.go b/server/service/osquery.go index e5ecef270f..55afcd433f 100644 --- a/server/service/osquery.go +++ b/server/service/osquery.go @@ -242,7 +242,7 @@ func getHostIdentifier(logger log.Logger, identifierOption, providedIdentifier s case "instance": r, ok := details["osquery_info"] - if !ok { + if !ok { //nolint:gocritic // ignore ifElseChain level.Info(logger).Log( "msg", "could not get host identifier", "reason", "missing osquery_info", @@ -260,7 +260,7 @@ func getHostIdentifier(logger log.Logger, identifierOption, providedIdentifier s case "uuid": r, ok := details["osquery_info"] - if !ok { + if !ok { //nolint:gocritic // ignore ifElseChain level.Info(logger).Log( "msg", "could not get host identifier", "reason", "missing osquery_info", @@ -278,7 +278,7 @@ func getHostIdentifier(logger log.Logger, identifierOption, providedIdentifier s case "hostname": r, ok := details["system_info"] - if !ok { + if !ok { //nolint:gocritic // ignore ifElseChain level.Info(logger).Log( "msg", "could not get host identifier", "reason", "missing system_info", @@ -1027,10 +1027,8 @@ func (svc *Service) SubmitDistributedQueryResults( team, err := svc.ds.Team(ctx, *host.TeamID) if err != nil { logging.WithErr(ctx, err) - } else { - if teamPolicyAutomationsEnabled(team.Config.WebhookSettings, team.Config.Integrations) { - policyIDs = append(policyIDs, team.Config.WebhookSettings.FailingPoliciesWebhook.PolicyIDs...) - } + } else if teamPolicyAutomationsEnabled(team.Config.WebhookSettings, team.Config.Integrations) { + policyIDs = append(policyIDs, team.Config.WebhookSettings.FailingPoliciesWebhook.PolicyIDs...) } } @@ -1058,12 +1056,10 @@ func (svc *Service) SubmitDistributedQueryResults( if err := svc.task.RecordPolicyQueryExecutions(ctx, host, policyResults, svc.clock.Now(), ac.ServerSettings.DeferredSaveHost); err != nil { logging.WithErr(ctx, err) } - } else { - if hostWithoutPolicies { - // RecordPolicyQueryExecutions called with results=nil will still update the host's policy_updated_at column. - if err := svc.task.RecordPolicyQueryExecutions(ctx, host, nil, svc.clock.Now(), ac.ServerSettings.DeferredSaveHost); err != nil { - logging.WithErr(ctx, err) - } + } else if hostWithoutPolicies { + // RecordPolicyQueryExecutions called with results=nil will still update the host's policy_updated_at column. + if err := svc.task.RecordPolicyQueryExecutions(ctx, host, nil, svc.clock.Now(), ac.ServerSettings.DeferredSaveHost); err != nil { + logging.WithErr(ctx, err) } } @@ -1538,7 +1534,7 @@ func (svc *Service) ingestDistributedQuery( // Write the results to the pubsub store res := fleet.DistributedQueryResult{ - DistributedQueryCampaignID: uint(campaignID), + DistributedQueryCampaignID: uint(campaignID), //nolint:gosec // dismiss G115 Host: fleet.ResultHostData{ ID: host.ID, Hostname: host.Hostname, @@ -1562,7 +1558,7 @@ func (svc *Service) ingestDistributedQuery( // If there are no subscribers, the campaign is "orphaned" // and should be closed so that we don't continue trying to // execute that query when we can't write to any subscriber - campaign, err := svc.ds.DistributedQueryCampaign(ctx, uint(campaignID)) + campaign, err := svc.ds.DistributedQueryCampaign(ctx, uint(campaignID)) //nolint:gosec // dismiss G115 if err != nil { if err := svc.liveQueryStore.StopQuery(strconv.Itoa(campaignID)); err != nil { return newOsqueryError("stop orphaned campaign after load failure: " + err.Error()) @@ -1624,9 +1620,9 @@ func ingestMembershipQuery( // A label/policy query matches if there is at least one result for that // query. We must also store negative results. if failed { - results[uint(trimmedQueryNum)] = nil + results[uint(trimmedQueryNum)] = nil //nolint:gosec // dismiss G115 } else { - results[uint(trimmedQueryNum)] = ptr.Bool(len(rows) > 0) + results[uint(trimmedQueryNum)] = ptr.Bool(len(rows) > 0) //nolint:gosec // dismiss G115 } return nil @@ -2127,12 +2123,10 @@ func (svc *Service) preProcessOsqueryResults( // field could not be unmarshalled. // // In both scenarios we want to add `result` to `unmarshaledResults`. - } else { + } else if result != nil && result.QueryName == "" { // If the unmarshaled result doesn't have a "name" field then we ignore the result. - if result != nil && result.QueryName == "" { - level.Debug(svc.logger).Log("msg", "missing name field", "result", lograw(raw)) - result = nil - } + level.Debug(svc.logger).Log("msg", "missing name field", "result", lograw(raw)) + result = nil } unmarshaledResults = append(unmarshaledResults, result) } diff --git a/server/service/osquery_test.go b/server/service/osquery_test.go index d5fc4a219a..d73b564d6e 100644 --- a/server/service/osquery_test.go +++ b/server/service/osquery_test.go @@ -12,7 +12,6 @@ import ( "os" "reflect" "sort" - "strconv" "strings" "sync" "testing" @@ -2233,11 +2232,11 @@ func TestDistributedQueryResults(t *testing.T) { lq.On("QueriesForHost", uint(1)).Return( map[string]string{ - strconv.Itoa(int(campaign.ID)): "select * from time", + fmt.Sprint(campaign.ID): "select * from time", }, nil, ) - lq.On("QueryCompletedByHost", strconv.Itoa(int(campaign.ID)), host.ID).Return(nil) + lq.On("QueryCompletedByHost", fmt.Sprint(campaign.ID), host.ID).Return(nil) // Now we should get the active distributed query queries, discovery, acc, err := svc.GetDistributedQueries(hostCtx) @@ -2463,7 +2462,7 @@ func TestIngestDistributedQueryOrphanedStopError(t *testing.T) { ds.SaveDistributedQueryCampaignFunc = func(ctx context.Context, campaign *fleet.DistributedQueryCampaign) error { return nil } - lq.On("StopQuery", strconv.Itoa(int(campaign.ID))).Return(errors.New("failed")) + lq.On("StopQuery", fmt.Sprint(campaign.ID)).Return(errors.New("failed")) host := fleet.Host{ID: 1} @@ -2500,7 +2499,7 @@ func TestIngestDistributedQueryOrphanedStop(t *testing.T) { ds.SaveDistributedQueryCampaignFunc = func(ctx context.Context, campaign *fleet.DistributedQueryCampaign) error { return nil } - lq.On("StopQuery", strconv.Itoa(int(campaign.ID))).Return(nil) + lq.On("StopQuery", fmt.Sprint(campaign.ID)).Return(nil) host := fleet.Host{ID: 1} @@ -2526,7 +2525,7 @@ func TestIngestDistributedQueryRecordCompletionError(t *testing.T) { campaign := &fleet.DistributedQueryCampaign{ID: 42} host := fleet.Host{ID: 1} - lq.On("QueryCompletedByHost", strconv.Itoa(int(campaign.ID)), host.ID).Return(errors.New("fail")) + lq.On("QueryCompletedByHost", fmt.Sprint(campaign.ID), host.ID).Return(errors.New("fail")) go func() { ch, err := rs.ReadChannel(context.Background(), *campaign) @@ -2557,7 +2556,7 @@ func TestIngestDistributedQuery(t *testing.T) { campaign := &fleet.DistributedQueryCampaign{ID: 42} host := fleet.Host{ID: 1} - lq.On("QueryCompletedByHost", strconv.Itoa(int(campaign.ID)), host.ID).Return(nil) + lq.On("QueryCompletedByHost", fmt.Sprint(campaign.ID), host.ID).Return(nil) go func() { ch, err := rs.ReadChannel(context.Background(), *campaign) diff --git a/server/service/osquery_utils/queries.go b/server/service/osquery_utils/queries.go index 3858915f9e..5797dd9697 100644 --- a/server/service/osquery_utils/queries.go +++ b/server/service/osquery_utils/queries.go @@ -1718,7 +1718,7 @@ func directIngestUsers(ctx context.Context, logger log.Logger, host *fleet.Host, groupname := row["groupname"] shell := row["shell"] u := fleet.HostUser{ - Uid: uint(uid), + Uid: uint(uid), // nolint:gosec // dismiss G115 Username: username, Type: type_, GroupName: groupname, diff --git a/server/service/osquery_utils/queries_test.go b/server/service/osquery_utils/queries_test.go index 512a30208e..08ee059ac1 100644 --- a/server/service/osquery_utils/queries_test.go +++ b/server/service/osquery_utils/queries_test.go @@ -299,12 +299,15 @@ func TestGetDetailQueries(t *testing.T) { require.Len(t, queriesWithoutWinOSVuln, 25) queriesWithUsers := GetDetailQueries(context.Background(), config.FleetConfig{App: config.AppConfig{EnableScheduledQueryStats: true}}, nil, &fleet.Features{EnableHostUsers: true}) - qs := append(baseQueries, "users", "users_chrome", "scheduled_query_stats") + qs := baseQueries + qs = append(qs, "users", "users_chrome", "scheduled_query_stats") require.Len(t, queriesWithUsers, len(qs)) sortedKeysCompare(t, queriesWithUsers, qs) queriesWithUsersAndSoftware := GetDetailQueries(context.Background(), config.FleetConfig{App: config.AppConfig{EnableScheduledQueryStats: true}}, nil, &fleet.Features{EnableHostUsers: true, EnableSoftwareInventory: true}) - qs = append(baseQueries, "users", "users_chrome", "software_macos", "software_linux", "software_windows", "software_vscode_extensions", "software_chrome", "scheduled_query_stats", "software_macos_firefox") + qs = baseQueries + qs = append(qs, "users", "users_chrome", "software_macos", "software_linux", "software_windows", "software_vscode_extensions", + "software_chrome", "scheduled_query_stats", "software_macos_firefox") require.Len(t, queriesWithUsersAndSoftware, len(qs)) sortedKeysCompare(t, queriesWithUsersAndSoftware, qs) @@ -322,7 +325,8 @@ func TestGetDetailQueries(t *testing.T) { ac.MDM.EnabledAndConfigured = true // windows mdm is disabled by default, windows mdm queries should not be present gotQueries := GetDetailQueries(context.Background(), config.FleetConfig{}, &ac, nil) - wantQueries := append(baseQueries, mdmQueriesBase...) + wantQueries := baseQueries + wantQueries = append(wantQueries, mdmQueriesBase...) require.Len(t, gotQueries, len(wantQueries)) sortedKeysCompare(t, gotQueries, wantQueries) // enable windows mdm, windows mdm queries should be present @@ -1239,12 +1243,13 @@ func TestDirectIngestOSUnixLike(t *testing.T) { } { t.Run(tc.expected.Name, func(t *testing.T) { ds.UpdateHostOperatingSystemFunc = func(ctx context.Context, hostID uint, hostOS fleet.OperatingSystem) error { - require.Equal(t, uint(i), hostID) + require.Equal(t, uint(i), hostID) //nolint:gosec // dismiss G115 require.Equal(t, tc.expected, hostOS) return nil } - err := directIngestOSUnixLike(context.Background(), log.NewNopLogger(), &fleet.Host{ID: uint(i)}, ds, tc.data) + err := directIngestOSUnixLike(context.Background(), log.NewNopLogger(), &fleet.Host{ID: uint(i)}, //nolint:gosec // dismiss G115 + ds, tc.data) require.NoError(t, err) require.True(t, ds.UpdateHostOperatingSystemFuncInvoked) diff --git a/server/service/queries_test.go b/server/service/queries_test.go index 95ae244d7a..856bfa6c74 100644 --- a/server/service/queries_test.go +++ b/server/service/queries_test.go @@ -359,7 +359,7 @@ func TestQueryAuth(t *testing.T) { return query, nil } ds.QueryByNameFunc = func(ctx context.Context, teamID *uint, name string) (*fleet.Query, error) { - if teamID == nil && name == "global query" { + if teamID == nil && name == "global query" { //nolint:gocritic // ignore ifElseChain return &globalQuery, nil } else if teamID != nil && *teamID == team.ID && name == "team query" { return &teamQuery, nil @@ -377,7 +377,7 @@ func TestQueryAuth(t *testing.T) { return nil } ds.QueryFunc = func(ctx context.Context, id uint) (*fleet.Query, error) { - if id == 99 { + if id == 99 { //nolint:gocritic // ignore ifElseChain return &globalQuery, nil } else if id == 88 { return &teamQuery, nil diff --git a/server/service/redis_lock/redis_lock_test.go b/server/service/redis_lock/redis_lock_test.go index c6663cded4..543b970c6a 100644 --- a/server/service/redis_lock/redis_lock_test.go +++ b/server/service/redis_lock/redis_lock_test.go @@ -93,7 +93,7 @@ func testRedisAcquireLock(t *testing.T, lock fleet.Lock) { assert.True(t, result) // Try to acquire the same lock after waiting - duration := time.Duration(expire+1) * time.Millisecond + duration := time.Duration(expire+1) * time.Millisecond //nolint:gosec // dismiss G115 time.Sleep(duration) result, err = lock.SetIfNotExist(ctx, "testE", "1", 0) require.NoError(t, err) diff --git a/server/service/redis_policy_set/redis_policy_set.go b/server/service/redis_policy_set/redis_policy_set.go index 0b908880fc..7b3936db51 100644 --- a/server/service/redis_policy_set/redis_policy_set.go +++ b/server/service/redis_policy_set/redis_policy_set.go @@ -49,7 +49,7 @@ func (r *redisFailingPolicySet) ListSets() ([]uint, error) { conn := redis.ConfigureDoer(r.pool, r.pool.Get()) defer conn.Close() - ids, err := redigo.Ints(conn.Do("SMEMBERS", r.policySetOfSetsKey())) + ids, err := redigo.Uint64s(conn.Do("SMEMBERS", r.policySetOfSetsKey())) if err != nil && err != redigo.ErrNil { return nil, err } @@ -202,7 +202,7 @@ func (r *redisFailingPolicySet) removePolicyFromSetOfSets(policyID uint) error { } func (r *redisFailingPolicySet) policySetKey(policyID uint) string { - return r.testPrefix + policySetKeyPrefix + strconv.Itoa(int(policyID)) + return r.testPrefix + policySetKeyPrefix + fmt.Sprint(policyID) } func (r *redisFailingPolicySet) policySetOfSetsKey() string { @@ -210,7 +210,7 @@ func (r *redisFailingPolicySet) policySetOfSetsKey() string { } func hostEntry(host fleet.PolicySetHost) string { - return strconv.Itoa(int(host.ID)) + "," + host.Hostname + return fmt.Sprint(host.ID) + "," + host.Hostname } func parseHostEntry(v string) (*fleet.PolicySetHost, error) { @@ -218,7 +218,7 @@ func parseHostEntry(v string) (*fleet.PolicySetHost, error) { if len(parts) != 2 { return nil, fmt.Errorf("invalid format: %s", v) } - id, err := strconv.Atoi(parts[0]) + id, err := strconv.ParseUint(parts[0], 10, 64) if err != nil { return nil, fmt.Errorf("invalid id: %s", v) } diff --git a/server/service/schedule/schedule_test.go b/server/service/schedule/schedule_test.go index 0acda392fb..f0cf41ba26 100644 --- a/server/service/schedule/schedule_test.go +++ b/server/service/schedule/schedule_test.go @@ -760,7 +760,7 @@ func TestTriggerMultipleInstances(t *testing.T) { }() <-timer.C - require.Equal(t, uint32(c.jobsExpected), atomic.LoadUint32(&jobsRun)) + require.EqualValues(t, c.jobsExpected, atomic.LoadUint32(&jobsRun)) cancelFunc() } } diff --git a/server/service/schedule/testing_utils.go b/server/service/schedule/testing_utils.go index a15d0d7b62..4bafa74d18 100644 --- a/server/service/schedule/testing_utils.go +++ b/server/service/schedule/testing_utils.go @@ -64,7 +64,7 @@ func (ml *MockLock) Lock(ctx context.Context, name string, owner string, expirat if ml.owner == owner || now.After(ml.expiresAt) { ml.owner = owner ml.expiresAt = now.Add(expiration) - ml.LockCount = ml.LockCount + 1 + ml.LockCount++ if ml.Locked != nil { ml.Locked <- struct{}{} } @@ -84,7 +84,7 @@ func (ml *MockLock) Unlock(ctx context.Context, name string, owner string) error if owner != ml.owner { return errors.New("owner doesn't match") } - ml.UnlockCount = ml.UnlockCount + 1 + ml.UnlockCount++ if ml.Unlocked != nil { ml.Unlocked <- struct{}{} } diff --git a/server/service/scheduled_queries.go b/server/service/scheduled_queries.go index 381179f860..3e54f84c26 100644 --- a/server/service/scheduled_queries.go +++ b/server/service/scheduled_queries.go @@ -275,7 +275,7 @@ func (svc *Service) unauthorizedModifyScheduledQuery(ctx context.Context, id uin if p.Shard != nil { if p.Shard.Valid { - val := uint(p.Shard.Int64) + val := uint(p.Shard.Int64) //nolint:gosec // dismiss G115 sq.Shard = &val } else { sq.Shard = nil diff --git a/server/service/service_campaigns.go b/server/service/service_campaigns.go index 5b2ec0e40f..1d00167618 100644 --- a/server/service/service_campaigns.go +++ b/server/service/service_campaigns.go @@ -388,11 +388,11 @@ func (svc Service) updateStats( } else { // Combine old and new stats. stats.AverageMemory = (stats.AverageMemory*stats.Executions + gatheredStats.Memory) / (stats.Executions + 1) - stats.Executions = stats.Executions + 1 - stats.SystemTime = stats.SystemTime + gatheredStats.SystemTime - stats.UserTime = stats.UserTime + gatheredStats.UserTime - stats.WallTime = stats.WallTime + gatheredStats.WallTimeMs - stats.OutputSize = stats.OutputSize + gatheredStats.outputSize + stats.Executions++ + stats.SystemTime += gatheredStats.SystemTime + stats.UserTime += gatheredStats.UserTime + stats.WallTime += gatheredStats.WallTimeMs + stats.OutputSize += gatheredStats.outputSize stats.LastExecuted = lastExecuted } } diff --git a/server/service/software.go b/server/service/software.go index e589ac7fe6..eae55218f9 100644 --- a/server/service/software.go +++ b/server/service/software.go @@ -21,7 +21,7 @@ type listSoftwareRequest struct { fleet.SoftwareListOptions } -// DEPRECATED: listSoftwareResponse is the response struct for the deprecated +// Deprecated: listSoftwareResponse is the response struct for the deprecated // listSoftwareEndpoint. It differs from listSoftwareVersionsResponse in that // the latter includes a count of the total number of software items. type listSoftwareResponse struct { @@ -32,7 +32,7 @@ type listSoftwareResponse struct { func (r listSoftwareResponse) error() error { return r.Err } -// DEPRECATED: use listSoftwareVersionsEndpoint instead +// Deprecated: use listSoftwareVersionsEndpoint instead func listSoftwareEndpoint(ctx context.Context, request interface{}, svc fleet.Service) (errorer, error) { req := request.(*listSoftwareRequest) resp, _, err := svc.ListSoftware(ctx, req.SoftwareListOptions) @@ -213,7 +213,7 @@ type countSoftwareResponse struct { func (r countSoftwareResponse) error() error { return r.Err } -// DEPRECATED: counts are now included directly in the listSoftwareVersionsResponse. This +// Deprecated: counts are now included directly in the listSoftwareVersionsResponse. This // endpoint is retained for backwards compatibility. func countSoftwareEndpoint(ctx context.Context, request interface{}, svc fleet.Service) (errorer, error) { req := request.(*countSoftwareRequest) diff --git a/server/service/software_installers_test.go b/server/service/software_installers_test.go index c0714c2cfb..ece1bba81a 100644 --- a/server/service/software_installers_test.go +++ b/server/service/software_installers_test.go @@ -139,19 +139,15 @@ func TestSoftwareInstallersAuth(t *testing.T) { _, err = svc.GetAppStoreApps(ctx, tt.teamID) if tt.teamID == nil { require.Error(t, err) - } else { - if tt.shouldFailRead { - checkAuthErr(t, true, err) - } + } else if tt.shouldFailRead { + checkAuthErr(t, true, err) } err = svc.AddAppStoreApp(ctx, tt.teamID, fleet.VPPAppTeam{VPPAppID: fleet.VPPAppID{AdamID: "123", Platform: fleet.IOSPlatform}}) if tt.teamID == nil { require.Error(t, err) - } else { - if tt.shouldFailWrite { - checkAuthErr(t, true, err) - } + } else if tt.shouldFailWrite { + checkAuthErr(t, true, err) } // TODO: configure test with mock software installer store and add tests to check upload auth diff --git a/server/service/team_schedule.go b/server/service/team_schedule.go index da31740a77..e48b53067c 100644 --- a/server/service/team_schedule.go +++ b/server/service/team_schedule.go @@ -85,7 +85,7 @@ func nullIntToPtrUint(v *null.Int) *uint { if v == nil { return nil } - return ptr.Uint(uint(v.ValueOrZero())) + return ptr.Uint(uint(v.ValueOrZero())) //nolint:gosec // dismiss G115 } func teamScheduleQueryEndpoint(ctx context.Context, request interface{}, svc fleet.Service) (errorer, error) { diff --git a/server/service/testing_client.go b/server/service/testing_client.go index 2250f4cf33..8450808a94 100644 --- a/server/service/testing_client.go +++ b/server/service/testing_client.go @@ -136,7 +136,7 @@ func (ts *withServer) commonTearDownTest(t *testing.T) { if len(queryIDs) > 0 { count, err := ts.ds.DeleteQueries(ctx, queryIDs) require.NoError(t, err) - require.Equal(t, len(queries), int(count)) + require.EqualValues(t, len(queries), count) } users, err := ts.ds.ListUsers(ctx, fleet.UserListOptions{}) diff --git a/server/service/testing_utils.go b/server/service/testing_utils.go index 0df3089b43..b9a1a7152a 100644 --- a/server/service/testing_utils.go +++ b/server/service/testing_utils.go @@ -722,12 +722,12 @@ func mdmConfigurationRequiredEndpoints() []struct { // parsed before the MDM check, we need to refactor this // function to return more information to the caller, or find a // better way to test these endpoints. - //{"POST", "/api/latest/fleet/mdm/profiles", false, false}, - //{"POST", "/api/latest/fleet/configuration_profiles", false, false}, - //{"POST", "/api/latest/fleet/mdm/setup/eula"}, - //{"POST", "/api/latest/fleet/setup_experience/eula"}, - //{"POST", "/api/latest/fleet/mdm/bootstrap", false, true}, - //{"POST", "/api/latest/fleet/bootstrap", false, true}, + // {"POST", "/api/latest/fleet/mdm/profiles", false, false}, + // {"POST", "/api/latest/fleet/configuration_profiles", false, false}, + // {"POST", "/api/latest/fleet/mdm/setup/eula"}, + // {"POST", "/api/latest/fleet/setup_experience/eula"}, + // {"POST", "/api/latest/fleet/mdm/bootstrap", false, true}, + // {"POST", "/api/latest/fleet/bootstrap", false, true}, {"GET", "/api/latest/fleet/mdm/profiles", false, false}, {"GET", "/api/latest/fleet/configuration_profiles", false, false}, {"GET", "/api/latest/fleet/mdm/manual_enrollment_profile", false, true}, diff --git a/server/service/transport.go b/server/service/transport.go index 145fa78c1f..d2518e146c 100644 --- a/server/service/transport.go +++ b/server/service/transport.go @@ -195,8 +195,8 @@ func listOptionsFromRequest(r *http.Request) (fleet.ListOptions, error) { query := r.URL.Query().Get("query") return fleet.ListOptions{ - Page: uint(page), - PerPage: uint(perPage), + Page: uint(page), //nolint:gosec // dismiss G115 + PerPage: uint(perPage), //nolint:gosec // dismiss G115 OrderKey: orderKey, OrderDirection: orderDirection, MatchQuery: strings.TrimSpace(query), diff --git a/server/service/transport_error.go b/server/service/transport_error.go index d7ebf7a86c..f59a349e4f 100644 --- a/server/service/transport_error.go +++ b/server/service/transport_error.go @@ -115,7 +115,7 @@ func encodeError(ctx context.Context, err error, w http.ResponseWriter) { "error": e.Error(), "uuid": uuid, } - if e.NodeInvalid() { + if e.NodeInvalid() { //nolint:gocritic // ignore ifElseChain w.WriteHeader(http.StatusUnauthorized) errMap["node_invalid"] = true } else if e.Status() != 0 { diff --git a/server/service/users_test.go b/server/service/users_test.go index 2f935d1c83..36e5635911 100644 --- a/server/service/users_test.go +++ b/server/service/users_test.go @@ -728,7 +728,7 @@ func testUsersChangePassword(t *testing.T, ds *mysql.Datastore) { ctx = viewer.NewContext(ctx, viewer.Viewer{User: &tt.user}) err := svc.ChangePassword(ctx, tt.oldPassword, tt.newPassword) - if tt.anyErr { + if tt.anyErr { //nolint:gocritic // ignore ifElseChain require.NotNil(t, err) } else if tt.wantErr != nil { require.Equal(t, tt.wantErr, ctxerr.Cause(err)) diff --git a/server/shellquote/shellquote.go b/server/shellquote/shellquote.go index 8960a427c3..b09fc386b8 100644 --- a/server/shellquote/shellquote.go +++ b/server/shellquote/shellquote.go @@ -75,19 +75,20 @@ raw: for len(cur) > 0 { c, l := utf8.DecodeRuneInString(cur) cur = cur[l:] - if c == singleChar { + switch { + case c == singleChar: buf.WriteString(input[0 : len(input)-len(cur)-l]) input = cur goto single - } else if c == doubleChar { + case c == doubleChar: buf.WriteString(input[0 : len(input)-len(cur)-l]) input = cur goto double - } else if c == escapeChar { + case c == escapeChar: buf.WriteString(input[0 : len(input)-len(cur)-l]) input = cur goto escape - } else if strings.ContainsRune(splitChars, c) { + case strings.ContainsRune(splitChars, c): buf.WriteString(input[0 : len(input)-len(cur)-l]) return buf.String(), cur, nil } diff --git a/server/test/comparisons.go b/server/test/comparisons.go index 2bb66d8b6d..3e9c420616 100644 --- a/server/test/comparisons.go +++ b/server/test/comparisons.go @@ -23,11 +23,8 @@ func ElementsMatchSkipID(t TestingT, listA, listB interface{}, msgAndArgs ...int opt := cmp.FilterPath(func(p cmp.Path) bool { for _, ps := range p { - switch ps := ps.(type) { - case cmp.StructField: - if strings.HasSuffix(ps.Name(), "ID") { - return true - } + if ps, ok := ps.(cmp.StructField); ok && strings.HasSuffix(ps.Name(), "ID") { + return true } } return false @@ -42,11 +39,8 @@ func ElementsMatchSkipIDAndHostCount(t TestingT, listA, listB interface{}, msgAn opt := cmp.FilterPath(func(p cmp.Path) bool { for _, ps := range p { - switch ps := ps.(type) { - case cmp.StructField: - if ps.Name() == "ID" || ps.Name() == "HostCount" { - return true - } + if ps, ok := ps.(cmp.StructField); ok && (ps.Name() == "ID" || ps.Name() == "HostCount") { + return true } } return false @@ -61,9 +55,8 @@ func ElementsMatchSkipTimestampsID(t TestingT, listA, listB interface{}, msgAndA opt := cmp.FilterPath(func(p cmp.Path) bool { for _, ps := range p { - switch ps := ps.(type) { - case cmp.StructField: - switch ps.Name() { + if ps, ok := ps.(cmp.StructField); ok { + switch ps.Name() { //nolint:gocritic // ignore singleCaseSwitch case "ID", "UpdateCreateTimestamps", "CreateTimestamp", "UpdateTimestamp", "CreatedAt", "UpdatedAt": return true } @@ -82,9 +75,8 @@ func EqualSkipTimestampsID(t TestingT, a, b interface{}, msgAndArgs ...interface opt := cmp.FilterPath(func(p cmp.Path) bool { for _, ps := range p { - switch ps := ps.(type) { - case cmp.StructField: - switch ps.Name() { + if ps, ok := ps.(cmp.StructField); ok { + switch ps.Name() { //nolint:gocritic // ignore singleCaseSwitch case "ID", "UpdateCreateTimestamps", "CreateTimestamp", "UpdateTimestamp", "CreatedAt", "UpdatedAt": return true } @@ -237,9 +229,8 @@ func QueryElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...inte opt := cmp.FilterPath(func(p cmp.Path) bool { for _, ps := range p { - switch ps := ps.(type) { - case cmp.StructField: - switch ps.Name() { + if ps, ok := ps.(cmp.StructField); ok { + switch ps.Name() { //nolint:gocritic // ignore singleCaseSwitch case "ID", "UpdateCreateTimestamps", "AuthorID", @@ -262,9 +253,8 @@ func QueriesMatch(t TestingT, a, b interface{}, msgAndArgs ...interface{}) (ok b opt := cmp.FilterPath(func(p cmp.Path) bool { for _, ps := range p { - switch ps := ps.(type) { - case cmp.StructField: - switch ps.Name() { + if ps, ok := ps.(cmp.StructField); ok { + switch ps.Name() { //nolint:gocritic // ignore singleCaseSwitch case "ID", "UpdateCreateTimestamps", "AuthorID", diff --git a/server/vulnerabilities/io/github.go b/server/vulnerabilities/io/github.go index 005a894281..36694db3e5 100644 --- a/server/vulnerabilities/io/github.go +++ b/server/vulnerabilities/io/github.go @@ -50,8 +50,8 @@ func NewGitHubClient(client *http.Client, releases ReleaseLister, workDir string // Download downloads the metadata file located at 'URL' in 'workDir', returns the path of // the downloaded metadata file. -func (gh GitHubClient) Download(URL string) (string, error) { - u, err := url.Parse(URL) +func (gh GitHubClient) Download(urlStr string) (string, error) { + u, err := url.Parse(urlStr) if err != nil { return "", err } diff --git a/server/vulnerabilities/io/metadata.go b/server/vulnerabilities/io/metadata.go index 2f02c7d82c..9b66d54ff5 100644 --- a/server/vulnerabilities/io/metadata.go +++ b/server/vulnerabilities/io/metadata.go @@ -78,7 +78,7 @@ func (mfn MetadataFileName) ProductName() string { return "" } - return strings.Replace(parts[0], "_", " ", -1) + return strings.ReplaceAll(parts[0], "_", " ") } func (mfn MetadataFileName) String() string { @@ -86,7 +86,7 @@ func (mfn MetadataFileName) String() string { } func MSRCFileName(productName string, date time.Time) string { - pName := strings.Replace(productName, " ", "_", -1) + pName := strings.ReplaceAll(productName, " ", "_") return fmt.Sprintf("%s%s-%d_%02d_%02d.%s", mSRCFilePrefix, pName, date.Year(), date.Month(), date.Day(), fileExt) } diff --git a/server/vulnerabilities/msrc/parsed/product.go b/server/vulnerabilities/msrc/parsed/product.go index b6317abfca..2da20eac86 100644 --- a/server/vulnerabilities/msrc/parsed/product.go +++ b/server/vulnerabilities/msrc/parsed/product.go @@ -33,7 +33,7 @@ func (p Products) GetMatchForOS(ctx context.Context, os fleet.OperatingSystem) ( continue } - if product.HasDisplayVersion() && os.DisplayVersion != "" && strings.Index(string(product), os.DisplayVersion) != -1 { + if product.HasDisplayVersion() && os.DisplayVersion != "" && strings.Contains(string(product), os.DisplayVersion) { dvMatch = pID break } @@ -81,17 +81,17 @@ func NewProductFromOS(os fleet.OperatingSystem) Product { func (p Product) Arch() string { val := string(p) switch { - case strings.Index(val, "ARM 64-bit") != -1 || - strings.Index(val, "ARM64") != -1: + case strings.Contains(val, "ARM 64-bit") || + strings.Contains(val, "ARM64"): return "arm64" - case strings.Index(val, "x64") != -1 || - strings.Index(val, "64-bit") != -1 || - strings.Index(val, "x86_64") != -1: + case strings.Contains(val, "x64") || + strings.Contains(val, "64-bit") || + strings.Contains(val, "x86_64"): return "64-bit" - case strings.Index(val, "32-bit") != -1 || - strings.Index(val, "x86") != -1: + case strings.Contains(val, "32-bit") || + strings.Contains(val, "x86"): return "32-bit" - case strings.Index(val, "Itanium-Based") != -1: + case strings.Contains(val, "Itanium-Based"): return "itanium" default: return "all" @@ -107,7 +107,7 @@ func (p Product) Arch() string { func (p Product) HasDisplayVersion() bool { keywords := []string{"version", "edition"} for _, k := range keywords { - if strings.Index(strings.ToLower(string(p)), k) != -1 { + if strings.Contains(strings.ToLower(string(p)), k) { return true } } @@ -123,34 +123,34 @@ func (p Product) Name() string { val := string(p) switch { // Desktop versions - case strings.Index(val, "Windows 7") != -1: + case strings.Contains(val, "Windows 7"): return "Windows 7" - case strings.Index(val, "Windows 8.1") != -1: + case strings.Contains(val, "Windows 8.1"): return "Windows 8.1" - case strings.Index(val, "Windows RT 8.1") != -1: + case strings.Contains(val, "Windows RT 8.1"): return "Windows RT 8.1" - case strings.Index(val, "Windows 10") != -1: + case strings.Contains(val, "Windows 10"): return "Windows 10" - case strings.Index(val, "Windows 11") != -1: + case strings.Contains(val, "Windows 11"): return "Windows 11" // Server versions - case strings.Index(val, "Windows Server 2008 R2") != -1: + case strings.Contains(val, "Windows Server 2008 R2"): return "Windows Server 2008 R2" - case strings.Index(val, "Windows Server 2012 R2") != -1: + case strings.Contains(val, "Windows Server 2012 R2"): return "Windows Server 2012 R2" - case strings.Index(val, "Windows Server 2008") != -1: + case strings.Contains(val, "Windows Server 2008"): return "Windows Server 2008" - case strings.Index(val, "Windows Server 2012") != -1: + case strings.Contains(val, "Windows Server 2012"): return "Windows Server 2012" - case strings.Index(val, "Windows Server 2016") != -1: + case strings.Contains(val, "Windows Server 2016"): return "Windows Server 2016" - case strings.Index(val, "Windows Server 2019") != -1: + case strings.Contains(val, "Windows Server 2019"): return "Windows Server 2019" - case strings.Index(val, "Windows Server 2022") != -1: + case strings.Contains(val, "Windows Server 2022"): return "Windows Server 2022" - case strings.Index(val, "Windows Server,") != -1: + case strings.Contains(val, "Windows Server,"): return "Windows Server" default: diff --git a/server/vulnerabilities/msrc/parser.go b/server/vulnerabilities/msrc/parser.go index 734a96e962..d71ab7e4dc 100644 --- a/server/vulnerabilities/msrc/parser.go +++ b/server/vulnerabilities/msrc/parser.go @@ -137,7 +137,7 @@ func parseXML(reader io.Reader) (*msrcxml.FeedResult, error) { return nil, fmt.Errorf("decoding token: %v", err) } - switch t := t.(type) { + switch t := t.(type) { //nolint:gocritic // ignore singleCaseSwitch case xml.StartElement: if t.Name.Local == "Branch" { branch := msrcxml.ProductBranch{} diff --git a/server/vulnerabilities/msrc/xml/vulnerability.go b/server/vulnerabilities/msrc/xml/vulnerability.go index 817dabed77..e44926d8ab 100644 --- a/server/vulnerabilities/msrc/xml/vulnerability.go +++ b/server/vulnerabilities/msrc/xml/vulnerability.go @@ -54,7 +54,7 @@ func (v *Vulnerability) IncludesVendorFix(pID string) bool { // PublishedDateEpoch returns the date the vuln was published (if any) as an epoch func (v *Vulnerability) PublishedDateEpoch() *int64 { for _, rev := range v.Revisions { - if strings.Index(rev.Description, "Information published") != -1 { + if strings.Contains(rev.Description, "Information published") { dPublished, err := time.Parse("2006-01-02T15:04:05", rev.Date) if err != nil { return nil diff --git a/server/vulnerabilities/nvd/cpe.go b/server/vulnerabilities/nvd/cpe.go index d1d9f1944a..b1623853b1 100644 --- a/server/vulnerabilities/nvd/cpe.go +++ b/server/vulnerabilities/nvd/cpe.go @@ -270,18 +270,18 @@ func CPEFromSoftware(logger log.Logger, db *sqlx.DB, software *fleet.Software, t sName := strings.ToLower(software.Name) for _, sN := range strings.Split(item.Product, "_") { - hasAllTerms = hasAllTerms && strings.Index(sName, sN) != -1 + hasAllTerms = hasAllTerms && strings.Contains(sName, sN) } sVendor := strings.ToLower(software.Vendor) sBundle := strings.ToLower(software.BundleIdentifier) for _, sV := range strings.Split(item.Vendor, "_") { if sVendor != "" { - hasAllTerms = hasAllTerms && strings.Index(sVendor, sV) != -1 + hasAllTerms = hasAllTerms && strings.Contains(sVendor, sV) } if sBundle != "" { - hasAllTerms = hasAllTerms && strings.Index(sBundle, sV) != -1 + hasAllTerms = hasAllTerms && strings.Contains(sBundle, sV) } } diff --git a/server/vulnerabilities/nvd/cve.go b/server/vulnerabilities/nvd/cve.go index 7b321ef947..62a9bfcfa3 100644 --- a/server/vulnerabilities/nvd/cve.go +++ b/server/vulnerabilities/nvd/cve.go @@ -402,7 +402,7 @@ func matchesExactTargetSW(softwareCPETargetSW string, targetSWs []string, config func checkCVEs( ctx context.Context, logger kitlog.Logger, - CPEItems []itemWithNVDMeta, + cpeItems []itemWithNVDMeta, jsonFile string, knownNVDBugRules CPEMatchingRules, ) ([]fleet.SoftwareVulnerability, []fleet.OSVulnerability, error) { @@ -542,7 +542,7 @@ func checkCVEs( level.Debug(logger).Log("msg", "pushing cpes") - for _, cpe := range CPEItems { + for _, cpe := range cpeItems { CPEItemCh <- cpe } close(CPEItemCh) diff --git a/server/vulnerabilities/nvd/sanitize.go b/server/vulnerabilities/nvd/sanitize.go index dce39c36a3..ab1dcd6c6e 100644 --- a/server/vulnerabilities/nvd/sanitize.go +++ b/server/vulnerabilities/nvd/sanitize.go @@ -93,10 +93,10 @@ func sanitizeSoftwareName(s *fleet.Software) string { r = strings.TrimSuffix(r, ".app") // Remove vendor, for 'apps' the vendor name is usually after the top level domain part. - r = strings.Replace(r, strings.ToLower(s.Vendor), "", -1) + r = strings.ReplaceAll(r, strings.ToLower(s.Vendor), "") bundleParts := strings.Split(s.BundleIdentifier, ".") if len(bundleParts) > 2 { - r = strings.Replace(r, strings.ToLower(bundleParts[1]), "", -1) + r = strings.ReplaceAll(r, strings.ToLower(bundleParts[1]), "") } if len(r) == 0 { @@ -114,11 +114,11 @@ func sanitizeSoftwareName(s *fleet.Software) string { for l := range langCodes { ln := strings.ToLower(l) - r = strings.Replace(r, ln, "", -1) + r = strings.ReplaceAll(r, ln, "") } - r = strings.Replace(r, "(", " ", -1) - r = strings.Replace(r, ")", " ", -1) + r = strings.ReplaceAll(r, "(", " ") + r = strings.ReplaceAll(r, ")", " ") r = strings.Join(strings.Fields(r), " ") // Remove @ from homebrew names @@ -138,15 +138,15 @@ func productVariations(s *fleet.Software) []string { withoutVendorParts := sn for _, p := range strings.Split(s.Vendor, " ") { pL := strings.ToLower(p) - withoutVendorParts = strings.Join(strings.Fields(strings.Replace(withoutVendorParts, pL, "", -1)), " ") + withoutVendorParts = strings.Join(strings.Fields(strings.ReplaceAll(withoutVendorParts, pL, "")), " ") } if withoutVendorParts != "" { - rSet[strings.Replace(withoutVendorParts, " ", "", -1)] = true - rSet[strings.Replace(withoutVendorParts, " ", "_", -1)] = true + rSet[strings.ReplaceAll(withoutVendorParts, " ", "")] = true + rSet[strings.ReplaceAll(withoutVendorParts, " ", "_")] = true } - rSet[strings.Replace(sn, " ", "_", -1)] = true - rSet[strings.Replace(sn, " ", "", -1)] = true + rSet[strings.ReplaceAll(sn, " ", "_")] = true + rSet[strings.ReplaceAll(sn, " ", "")] = true for re := range rSet { r = append(r, re) @@ -177,8 +177,8 @@ func vendorVariations(s *fleet.Software) []string { rSet[strings.ToLower(v)] = true } } - rSet[strings.ToLower(strings.Replace(s.Vendor, " ", "_", -1))] = true - rSet[strings.ToLower(strings.Replace(s.Vendor, " ", "", -1))] = true + rSet[strings.ToLower(strings.ReplaceAll(s.Vendor, " ", "_"))] = true + rSet[strings.ToLower(strings.ReplaceAll(s.Vendor, " ", ""))] = true } for _, v := range strings.Split(s.BundleIdentifier, ".") { diff --git a/server/vulnerabilities/nvd/tools/cvefeed/nvd/match_cpe.go b/server/vulnerabilities/nvd/tools/cvefeed/nvd/match_cpe.go index 32e69ce1df..7c9c22b3a3 100644 --- a/server/vulnerabilities/nvd/tools/cvefeed/nvd/match_cpe.go +++ b/server/vulnerabilities/nvd/tools/cvefeed/nvd/match_cpe.go @@ -33,10 +33,10 @@ type cpeMatch struct { } // Matcher returns an object which knows how to match attributes -func cpeMatcher(ID string, nvdMatch *schema.NVDCVEFeedJSON10DefCPEMatch) (wfn.Matcher, error) { +func cpeMatcher(id string, nvdMatch *schema.NVDCVEFeedJSON10DefCPEMatch) (wfn.Matcher, error) { parse := func(uri string) (*wfn.Attributes, error) { if uri == "" { - return nil, fmt.Errorf("%s: can't parse empty uri", ID) + return nil, fmt.Errorf("%s: can't parse empty uri", id) } return wfn.Parse(uri) } @@ -46,7 +46,7 @@ func cpeMatcher(ID string, nvdMatch *schema.NVDCVEFeedJSON10DefCPEMatch) (wfn.Ma var err error if match.Attributes, err = parse(nvdMatch.Cpe23Uri); err != nil { if match.Attributes, err = parse(nvdMatch.Cpe22Uri); err != nil { - return nil, fmt.Errorf("%s: unable to parse both cpe2.2 and cpe2.3", ID) + return nil, fmt.Errorf("%s: unable to parse both cpe2.2 and cpe2.3", id) } } diff --git a/server/vulnerabilities/nvd/tools/cvefeed/nvd/match_node.go b/server/vulnerabilities/nvd/tools/cvefeed/nvd/match_node.go index e1a1b988bf..72d623045a 100644 --- a/server/vulnerabilities/nvd/tools/cvefeed/nvd/match_node.go +++ b/server/vulnerabilities/nvd/tools/cvefeed/nvd/match_node.go @@ -24,36 +24,36 @@ import ( ) // Matcher returns an object which knows how to match attributes -func nodeMatcher(ID string, node *schema.NVDCVEFeedJSON10DefNode) (wfn.Matcher, error) { +func nodeMatcher(id string, node *schema.NVDCVEFeedJSON10DefNode) (wfn.Matcher, error) { if node == nil { - return nil, fmt.Errorf("%s: node is nil", ID) + return nil, fmt.Errorf("%s: node is nil", id) } var ms []wfn.Matcher for _, match := range node.CPEMatch { if match != nil { - if m, err := cpeMatcher(ID, match); err == nil { + if m, err := cpeMatcher(id, match); err == nil { ms = append(ms, m) } } } for _, child := range node.Children { if child != nil { - if m, err := nodeMatcher(ID, child); err == nil { + if m, err := nodeMatcher(id, child); err == nil { ms = append(ms, m) } } } if len(ms) == 0 { - return nil, fmt.Errorf("%s: empty configuration for node", ID) + return nil, fmt.Errorf("%s: empty configuration for node", id) } var m wfn.Matcher switch strings.ToUpper(node.Operator) { default: - flog.Warningf("%s: unknown operator, defaulting to OR: got %q", ID, node.Operator) + flog.Warningf("%s: unknown operator, defaulting to OR: got %q", id, node.Operator) fallthrough case "OR": m = wfn.MatchAny(ms...) diff --git a/server/vulnerabilities/nvd/tools/wfn/uri.go b/server/vulnerabilities/nvd/tools/wfn/uri.go index 5e2f502f5f..b1172ddfdf 100644 --- a/server/vulnerabilities/nvd/tools/wfn/uri.go +++ b/server/vulnerabilities/nvd/tools/wfn/uri.go @@ -141,10 +141,11 @@ func bindValueURI(s string) string { } for i := 0; i < len(s); i++ { b := s[i] - if b >= '0' && b <= '9' || b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b == '_' { + switch { + case b >= '0' && b <= '9' || b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b == '_': // alnum + '_' pass untouched out = append(out, b) - } else if b == '\\' { + case b == '\\': // percent-encode escaped characters // sanity check should be done during unbinding, so here we silently skip all // illegal characters @@ -153,9 +154,9 @@ func bindValueURI(s string) string { break } out = append(out, pctEncode(s[i])...) - } else if b == '?' { // unquoted '?' -> "%01" + case b == '?': // unquoted '?' -> "%01" out = append(out, '%', '0', '1') - } else if b == '*' { // unquoted '*' -> "%02" + case b == '*': // unquoted '*' -> "%02" out = append(out, '%', '0', '2') } } diff --git a/server/vulnerabilities/nvd/tools/wfn/wfn.go b/server/vulnerabilities/nvd/tools/wfn/wfn.go index 0cce686050..b71c6225e3 100644 --- a/server/vulnerabilities/nvd/tools/wfn/wfn.go +++ b/server/vulnerabilities/nvd/tools/wfn/wfn.go @@ -104,7 +104,7 @@ func newAttributes(defaultValue string) *Attributes { func WFNize(s string) (string, error) { const allowedPunct = "-!\"#$%&'()+,./:;<=>@[]^`{|}!~" // replace spaces with underscores - in := strings.Replace(s, " ", "_", -1) + in := strings.ReplaceAll(s, " ", "_") buf := make([]byte, 0, len(in)) // remove illegal characters for n, c := range in { diff --git a/server/vulnerabilities/nvd/tools/wfn/wfn_test.go b/server/vulnerabilities/nvd/tools/wfn/wfn_test.go index 63cd33450f..d96f1f51ad 100644 --- a/server/vulnerabilities/nvd/tools/wfn/wfn_test.go +++ b/server/vulnerabilities/nvd/tools/wfn/wfn_test.go @@ -33,13 +33,14 @@ func TestWFNize(t *testing.T) { } for _, c := range cases { res, err := WFNize(c.in) - if err != nil { + switch { + case err != nil: if !c.expectErr { t.Errorf("WFNize(%q) returned error: %v", c.in, err) } - } else if c.expectErr { + case c.expectErr: t.Errorf("WFNize(%q) was expected to fail, but succedeed", c.in) - } else if res != c.expected { + case res != c.expected: t.Errorf("WFNize(%q) returned %q, %q was expected", c.in, res, c.expected) } } diff --git a/server/vulnerabilities/oval/analyzer_test.go b/server/vulnerabilities/oval/analyzer_test.go index 415c1ca4e6..2df65a1348 100644 --- a/server/vulnerabilities/oval/analyzer_test.go +++ b/server/vulnerabilities/oval/analyzer_test.go @@ -170,7 +170,7 @@ func assertVulns( continue } - if len(row) > 1 && row[1] == "#ignore:" || strings.Index(row[0], "ignore") != -1 { + if len(row) > 1 && row[1] == "#ignore:" || strings.Contains(row[0], "ignore") { continue } diff --git a/server/vulnerabilities/oval/parsed/definition.go b/server/vulnerabilities/oval/parsed/definition.go index 6d64eb95a5..ce71cb8903 100644 --- a/server/vulnerabilities/oval/parsed/definition.go +++ b/server/vulnerabilities/oval/parsed/definition.go @@ -27,12 +27,12 @@ type Definition struct { // Tests results can come from two sources: // - OSTstResults: Test results from making assertions against the installed OS Version // - pkTstResults: Tests results from making assertions against the installed software packages. -func (d Definition) Eval(OSTstResults map[int]bool, pkgTstResults map[int][]fleet.Software) bool { - if d.Criteria == nil || (len(OSTstResults) == 0 && len(pkgTstResults) == 0) { +func (d Definition) Eval(osTstResults map[int]bool, pkgTstResults map[int][]fleet.Software) bool { + if d.Criteria == nil || (len(osTstResults) == 0 && len(pkgTstResults) == 0) { return false } - rEval, err := evalCriteria(d.Criteria, OSTstResults, pkgTstResults) + rEval, err := evalCriteria(d.Criteria, osTstResults, pkgTstResults) if err != nil { return false } @@ -57,7 +57,7 @@ func (d Definition) CollectTestIds() []int { return results } -func evalCriteria(c *Criteria, OSTstResults map[int]bool, pkgTstResults map[int][]fleet.Software) (bool, error) { +func evalCriteria(c *Criteria, osTstResults map[int]bool, pkgTstResults map[int][]fleet.Software) (bool, error) { var vals []bool var result bool @@ -67,7 +67,7 @@ func evalCriteria(c *Criteria, OSTstResults map[int]bool, pkgTstResults map[int] vals = append(vals, len(pkgTstR) > 0) } - OSTstR, OSTstOk := OSTstResults[co] + OSTstR, OSTstOk := osTstResults[co] if OSTstOk { vals = append(vals, OSTstR) } @@ -80,7 +80,7 @@ func evalCriteria(c *Criteria, OSTstResults map[int]bool, pkgTstResults map[int] result = c.Operator.Eval(vals...) for _, ci := range c.Criterias { - rEval, err := evalCriteria(ci, OSTstResults, pkgTstResults) + rEval, err := evalCriteria(ci, osTstResults, pkgTstResults) if err != nil { return false, err } diff --git a/server/vulnerabilities/oval/parsed/utils.go b/server/vulnerabilities/oval/parsed/utils.go index ad6ffafd67..1a9a3dd8b7 100644 --- a/server/vulnerabilities/oval/parsed/utils.go +++ b/server/vulnerabilities/oval/parsed/utils.go @@ -15,7 +15,7 @@ import ( // 'Fedora Linux 12.0.0' => 'Red Hat Enterprise Linux 6.0.0' // 'Fedora Linux 13.0.0' => 'Red Hat Enterprise Linux 6.0.0' func ReplaceFedoraOSVersion(version string) string { - if strings.Index(version, "Fedora") != -1 { + if strings.Contains(version, "Fedora") { rules := map[string]*regexp.Regexp{ "Red Hat Enterprise Linux 6.0.0": regexp.MustCompile(`Fedora Linux (12|13|14|15|16|17|18)\.`), "Red Hat Enterprise Linux 7.0.0": regexp.MustCompile(`Fedora Linux (19|20|21|22|23|24|25|26|27)\.`), diff --git a/server/vulnerabilities/oval/parser.go b/server/vulnerabilities/oval/parser.go index 5f1b937bb8..06ecd51dd7 100644 --- a/server/vulnerabilities/oval/parser.go +++ b/server/vulnerabilities/oval/parser.go @@ -74,8 +74,7 @@ func parseRhelXML(reader io.Reader) (*oval_input.RhelResultXML, error) { return nil, fmt.Errorf("decoding token: %v", err) } - switch t := t.(type) { - case xml.StartElement: + if t, ok := t.(xml.StartElement); ok { if t.Name.Local == "definition" { def := oval_input.DefinitionXML{} if err = d.DecodeElement(&def, &t); err != nil { @@ -286,8 +285,7 @@ func parseUbuntuXML(reader io.Reader) (*oval_input.UbuntuResultXML, error) { return nil, fmt.Errorf("decoding token: %v", err) } - switch t := t.(type) { - case xml.StartElement: + if t, ok := t.(xml.StartElement); ok { if t.Name.Local == "definition" { def := oval_input.DefinitionXML{} if err = d.DecodeElement(&def, &t); err != nil { diff --git a/server/vulnerabilities/utils/rpmvercmp.go b/server/vulnerabilities/utils/rpmvercmp.go index beabd1035d..8f33072e63 100644 --- a/server/vulnerabilities/utils/rpmvercmp.go +++ b/server/vulnerabilities/utils/rpmvercmp.go @@ -64,7 +64,7 @@ func (s segment) compare(b segment) int { // Both are numeric, in which case we compare // their numeric values - if s.number != nil && b.number != nil { + if s.number != nil && b.number != nil { //nolint:gocritic // ignore ifElseChain if *s.number == *b.number { return 0 } else if *s.number < *b.number { diff --git a/server/webhooks/failing_policies_test.go b/server/webhooks/failing_policies_test.go index 4a75d4758e..8cf2829f31 100644 --- a/server/webhooks/failing_policies_test.go +++ b/server/webhooks/failing_policies_test.go @@ -382,7 +382,7 @@ func TestSendBatchedPOSTs(t *testing.T) { hosts := make([]fleet.PolicySetHost, c) for i := 0; i < len(hosts); i++ { hosts[i] = fleet.PolicySetHost{ - ID: uint(i + 1), + ID: uint(i + 1), //nolint:gosec // dismiss G115 Hostname: fmt.Sprintf("hostname-%d", i+1), } } diff --git a/server/webhooks/mapper.go b/server/webhooks/mapper.go index 85f9959ae5..c2e82dcd66 100644 --- a/server/webhooks/mapper.go +++ b/server/webhooks/mapper.go @@ -4,7 +4,6 @@ import ( "fmt" "net/url" "path" - "strconv" "time" "github.com/fleetdm/fleet/v4/server/fleet" @@ -48,7 +47,7 @@ func (m *Mapper) getHostPayloadPart( shortHosts := make([]*hostPayloadPart, len(hosts)) for i, h := range hosts { hostURL := *hostBaseURL - hostURL.Path = path.Join(hostURL.Path, "hosts", strconv.Itoa(int(h.ID))) + hostURL.Path = path.Join(hostURL.Path, "hosts", fmt.Sprint(h.ID)) hostPayload := hostPayloadPart{ ID: h.ID, Hostname: h.Hostname, diff --git a/server/worker/macos_setup_assistant_test.go b/server/worker/macos_setup_assistant_test.go index f137b418bb..e22fdf3819 100644 --- a/server/worker/macos_setup_assistant_test.go +++ b/server/worker/macos_setup_assistant_test.go @@ -8,7 +8,6 @@ import ( "io" "net/http" "net/http/httptest" - "strconv" "strings" "testing" "time" @@ -181,7 +180,7 @@ func TestMacosSetupAssistant(t *testing.T) { return "null" } - return strconv.Itoa(int(*tmID)) + return fmt.Sprint(*tmID) } tmIDs := []*uint{nil, ptr.Uint(tm1.ID), ptr.Uint(tm2.ID)} diff --git a/tools/calendar/calendar.go b/tools/calendar/calendar.go index 64b70c7a94..4c2d7d292f 100644 --- a/tools/calendar/calendar.go +++ b/tools/calendar/calendar.go @@ -3,12 +3,13 @@ package main import ( "flag" "fmt" - calendartest "github.com/fleetdm/fleet/v4/ee/server/calendar/load_test" - _ "github.com/mattn/go-sqlite3" "log" "net/http" "os" "time" + + calendartest "github.com/fleetdm/fleet/v4/ee/server/calendar/load_test" + _ "github.com/mattn/go-sqlite3" ) func main() { @@ -35,5 +36,8 @@ func main() { } // Start the HTTP server - log.Fatal(server.ListenAndServe()) + err = server.ListenAndServe() + if err != nil { + log.Print(err) + } } diff --git a/tools/calendar/delete-events/delete-events.go b/tools/calendar/delete-events/delete-events.go index f3f1355548..2fa71f31f8 100644 --- a/tools/calendar/delete-events/delete-events.go +++ b/tools/calendar/delete-events/delete-events.go @@ -4,18 +4,19 @@ import ( "context" "errors" "flag" - "github.com/cenkalti/backoff/v4" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "google.golang.org/api/calendar/v3" - "google.golang.org/api/googleapi" - "google.golang.org/api/option" "log" "net/http" "os" "strings" "sync" "time" + + "github.com/cenkalti/backoff/v4" + "golang.org/x/oauth2/google" + "golang.org/x/oauth2/jwt" + "google.golang.org/api/calendar/v3" + "google.golang.org/api/googleapi" + "google.golang.org/api/option" ) // Delete all events with eventTitle from the primary calendar of the specified users. @@ -35,7 +36,7 @@ func main() { log.Fatal("FLEET_TEST_GOOGLE_CALENDAR_SERVICE_EMAIL and FLEET_TEST_GOOGLE_CALENDAR_PRIVATE_KEY must be set") } // Strip newlines from private key - privateKey = strings.Replace(privateKey, "\\n", "\n", -1) + privateKey = strings.ReplaceAll(privateKey, "\\n", "\n") userEmails := flag.String("users", "", "Comma-separated list of user emails to impersonate") flag.Parse() if *userEmails == "" { diff --git a/tools/calendar/get-events/get-events.go b/tools/calendar/get-events/get-events.go index 46ce64cd4a..74535ea3af 100644 --- a/tools/calendar/get-events/get-events.go +++ b/tools/calendar/get-events/get-events.go @@ -40,7 +40,7 @@ func main() { log.Fatal("FLEET_TEST_GOOGLE_CALENDAR_SERVICE_EMAIL and FLEET_TEST_GOOGLE_CALENDAR_PRIVATE_KEY must be set") } // Strip newlines from private key - privateKey = strings.Replace(privateKey, "\\n", "\n", -1) + privateKey = strings.ReplaceAll(privateKey, "\\n", "\n") userEmails := flag.String("users", "", "Comma-separated list of user emails to impersonate") flag.Parse() if *userEmails == "" { diff --git a/tools/calendar/move-events/move-events.go b/tools/calendar/move-events/move-events.go index 616418b196..e3123087f7 100644 --- a/tools/calendar/move-events/move-events.go +++ b/tools/calendar/move-events/move-events.go @@ -4,18 +4,19 @@ import ( "context" "errors" "flag" - "github.com/cenkalti/backoff/v4" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "google.golang.org/api/calendar/v3" - "google.golang.org/api/googleapi" - "google.golang.org/api/option" "log" "net/http" "os" "strings" "sync" "time" + + "github.com/cenkalti/backoff/v4" + "golang.org/x/oauth2/google" + "golang.org/x/oauth2/jwt" + "google.golang.org/api/calendar/v3" + "google.golang.org/api/googleapi" + "google.golang.org/api/option" ) // Move all events with eventTitle from the primary calendar of the user to the new time. @@ -36,7 +37,7 @@ func main() { log.Fatal("FLEET_TEST_GOOGLE_CALENDAR_SERVICE_EMAIL and FLEET_TEST_GOOGLE_CALENDAR_PRIVATE_KEY must be set") } // Strip newlines from private key - privateKey = strings.Replace(privateKey, "\\n", "\n", -1) + privateKey = strings.ReplaceAll(privateKey, "\\n", "\n") userEmails := flag.String("users", "", "Comma-separated list of user emails to impersonate") dateTimeStr := flag.String("datetime", "", "Event time in "+time.RFC3339+" format") flag.Parse() diff --git a/tools/calendar/stop-channel/stop-channel.go b/tools/calendar/stop-channel/stop-channel.go index 15e61a27e2..cdbdb0b816 100644 --- a/tools/calendar/stop-channel/stop-channel.go +++ b/tools/calendar/stop-channel/stop-channel.go @@ -4,17 +4,18 @@ import ( "context" "errors" "flag" + "log" + "net/http" + "os" + "strings" + "time" + "github.com/cenkalti/backoff/v4" "golang.org/x/oauth2/google" "golang.org/x/oauth2/jwt" "google.golang.org/api/calendar/v3" "google.golang.org/api/googleapi" "google.golang.org/api/option" - "log" - "net/http" - "os" - "strings" - "time" ) // Stop watching the channel with the given ID. This command only accepts one user. @@ -32,7 +33,7 @@ func main() { log.Fatal("FLEET_TEST_GOOGLE_CALENDAR_SERVICE_EMAIL and FLEET_TEST_GOOGLE_CALENDAR_PRIVATE_KEY must be set") } // Strip newlines from private key - privateKey = strings.Replace(privateKey, "\\n", "\n", -1) + privateKey = strings.ReplaceAll(privateKey, "\\n", "\n") userEmails := flag.String("users", "", "Comma-separated list of user emails to impersonate") channelIDStr := flag.String("channel-id", "", "Channel ID") resourceIDStr := flag.String("resource-id", "", "Resource ID") diff --git a/tools/jira-integration/main.go b/tools/jira-integration/main.go index 80da821341..1dc64f7bfb 100644 --- a/tools/jira-integration/main.go +++ b/tools/jira-integration/main.go @@ -83,7 +83,9 @@ func main() { ds.HostsByCVEFunc = func(ctx context.Context, cve string) ([]fleet.HostVulnerabilitySummary, error) { hosts := make([]fleet.HostVulnerabilitySummary, *hostsCount) for i := 0; i < *hostsCount; i++ { - hosts[i] = fleet.HostVulnerabilitySummary{ID: uint(i + 1), Hostname: fmt.Sprintf("host-test-%d", i+1), DisplayName: fmt.Sprintf("host-test-%d", i+1)} + hosts[i] = fleet.HostVulnerabilitySummary{ID: uint(i + 1), //nolint:gosec // dismiss G115 + Hostname: fmt.Sprintf("host-test-%d", i+1), + DisplayName: fmt.Sprintf("host-test-%d", i+1)} } return hosts, nil } @@ -171,7 +173,7 @@ func main() { jsonStr += `"hosts": ` hosts := make([]fleet.PolicySetHost, 0, *hostsCount) for i := 1; i <= *hostsCount; i++ { - hosts = append(hosts, fleet.PolicySetHost{ID: uint(i), Hostname: fmt.Sprintf("host-test-%d", i)}) + hosts = append(hosts, fleet.PolicySetHost{ID: uint(i), Hostname: fmt.Sprintf("host-test-%d", i)}) //nolint:gosec // dismiss G115 } b, _ := json.Marshal(hosts) jsonStr += string(b) + "}}" diff --git a/tools/mdm/apple/appmanifest/main.go b/tools/mdm/apple/appmanifest/main.go index 6bbc6b9125..780a376dfb 100644 --- a/tools/mdm/apple/appmanifest/main.go +++ b/tools/mdm/apple/appmanifest/main.go @@ -27,7 +27,7 @@ func main() { m, err := appmanifest.NewPlist(fp, *pkgURL) if err != nil { - log.Fatal(err) + log.Fatal(err) //nolint:gocritic // ignoring exitAfterDefer } fmt.Println(string(m)) diff --git a/tools/mdm/assets/main.go b/tools/mdm/assets/main.go index 9a2e8ed58b..12d4a9b5d4 100644 --- a/tools/mdm/assets/main.go +++ b/tools/mdm/assets/main.go @@ -88,7 +88,7 @@ func setupDS(privateKey, userName, password, address, name string) *mysql.Datast }), ) if err != nil { - log.Fatal("creating datastore instance:", err) + log.Fatal("creating datastore instance:", err) //nolint:gocritic // ignore exitAfterDefer } return ds @@ -126,7 +126,7 @@ func main() { // Check required flags if flagDir != "" { if err := os.MkdirAll(flagDir, os.ModePerm); err != nil { - log.Fatal("ensuring directory: ", err) + log.Fatal("ensuring directory: ", err) //nolint:gocritic // ignore exitAfterDefer } } @@ -202,9 +202,9 @@ func main() { path := filepath.Join(flagDir, string(asset.Name)) switch { case strings.Contains(path, "_key"): - path = path + ".key" + path += ".key" case strings.Contains(path, "_cert"): - path = path + ".crt" + path += ".crt" } if err := os.WriteFile(path, asset.Value, 0o600); err != nil { log.Fatal("writing asset:", err) diff --git a/tools/mdm/migration/jamf/main.go b/tools/mdm/migration/jamf/main.go index be7ac393fa..d3b50a286d 100644 --- a/tools/mdm/migration/jamf/main.go +++ b/tools/mdm/migration/jamf/main.go @@ -83,7 +83,7 @@ func main() { ReadHeaderTimeout: 3 * time.Second, } if err := server.ListenAndServe(); err != nil { - log.Fatalf(err.Error()) + log.Fatal(err.Error()) } } diff --git a/tools/mdm/migration/kandji/main.go b/tools/mdm/migration/kandji/main.go index df54c9433d..7e46384d41 100644 --- a/tools/mdm/migration/kandji/main.go +++ b/tools/mdm/migration/kandji/main.go @@ -5,12 +5,13 @@ import ( "errors" "flag" "fmt" - "github.com/fleetdm/fleet/v4/pkg/fleethttp" "io" "log" "net/http" "os" "time" + + "github.com/fleetdm/fleet/v4/pkg/fleethttp" ) var ( @@ -72,7 +73,7 @@ func main() { ReadHeaderTimeout: 3 * time.Second, } if err := server.ListenAndServe(); err != nil { - log.Fatalf(err.Error()) + log.Fatal(err.Error()) } } diff --git a/tools/mdm/migration/mdmproxy/mdmproxy.go b/tools/mdm/migration/mdmproxy/mdmproxy.go index c59bf4b425..5f23c977b9 100644 --- a/tools/mdm/migration/mdmproxy/mdmproxy.go +++ b/tools/mdm/migration/mdmproxy/mdmproxy.go @@ -173,8 +173,8 @@ func (m *mdmProxy) handleUpdatePercentage(w http.ResponseWriter, r *http.Request m.migratePercentage = percentage msg := fmt.Sprintf("Migrate percentage updated: %v\n", percentage) - log.Printf(msg) - fmt.Fprintf(w, msg) + log.Print(msg) + fmt.Fprint(w, msg) } func (m *mdmProxy) handleUpdateMigrateUDIDs(w http.ResponseWriter, r *http.Request) { @@ -209,8 +209,8 @@ func (m *mdmProxy) handleUpdateMigrateUDIDs(w http.ResponseWriter, r *http.Reque m.migrateUDIDs = udids msg := fmt.Sprintf("Migrate UDIDs updated: %v\n", udids) - log.Printf(msg) - fmt.Fprintf(w, msg) + log.Print(msg) + fmt.Fprint(w, msg) } func processUDIDs(in io.Reader) (map[string]struct{}, error) { @@ -267,7 +267,7 @@ func hashUDID(udid string) uint { func udidIncludedByPercentage(udid string, percentage int) bool { index := hashUDID(udid) % 100 - return int(index) < percentage + return int(index) < percentage //nolint:gosec // G115 false positive } func makeExistingProxy(existingURL, existingDNSName string) *httputil.ReverseProxy { diff --git a/tools/mdm/migration/micromdm/main.go b/tools/mdm/migration/micromdm/main.go index 87e73246b9..6216e44efa 100644 --- a/tools/mdm/migration/micromdm/main.go +++ b/tools/mdm/migration/micromdm/main.go @@ -72,7 +72,7 @@ func main() { ReadHeaderTimeout: 3 * time.Second, } if err := server.ListenAndServe(); err != nil { - log.Fatalf(err.Error()) + log.Fatal(err.Error()) } } @@ -134,14 +134,14 @@ func (m *microMDMClient) do(method, path string, data any) ([]byte, error) { return m.doWithRequest(req) } -func (m *microMDMClient) unmanageDevice(UUID string) error { +func (m *microMDMClient) unmanageDevice(uuid string) error { req := struct { RequestType string `json:"request_type"` UDID string `json:"udid"` Identifier string `json:"identifier"` }{ RequestType: "RemoveProfile", - UDID: UUID, + UDID: uuid, Identifier: "com.github.micromdm.micromdm.enroll", } _, err := m.do("POST", fmt.Sprintf("%s/v1/commands", m.url), &req) diff --git a/tools/mdm/migration/micromdm/touchless/main.go b/tools/mdm/migration/micromdm/touchless/main.go index 92801a7623..6898ba8605 100644 --- a/tools/mdm/migration/micromdm/touchless/main.go +++ b/tools/mdm/migration/micromdm/touchless/main.go @@ -335,7 +335,7 @@ ON DUPLICATE KEY UPDATE updated_at = updated_at, -- preserve updated_at sha256 = VALUES(sha256), cert_not_valid_after = VALUES(cert_not_valid_after); - `, device.UDID, hex.EncodeToString(certHash[:]), certExpiration, referenceTime, device.UDID, referenceTime)) + `, device.UDID, hex.EncodeToString(certHash), certExpiration, referenceTime, device.UDID, referenceTime)) } sb.WriteString("\n") diff --git a/tools/nvd/nvdvuln/nvdvuln.go b/tools/nvd/nvdvuln/nvdvuln.go index 41335c6103..e0baec3e56 100644 --- a/tools/nvd/nvdvuln/nvdvuln.go +++ b/tools/nvd/nvdvuln/nvdvuln.go @@ -82,7 +82,7 @@ func main() { if *debug { // Sample the process CPU and memory usage every second // and store it on a file under the dbDir. - process, err := process.NewProcess(int32(os.Getpid())) + myProcess, err := process.NewProcess(int32(os.Getpid())) //nolint:gosec // dismiss G115 if err != nil { panic(err) } @@ -95,11 +95,11 @@ func main() { for { select { case <-time.After(1 * time.Second): - cpuPercent, err := process.CPUPercent() + cpuPercent, err := myProcess.CPUPercent() if err != nil { panic(err) } - memInfo, err := process.MemoryInfo() + memInfo, err := myProcess.MemoryInfo() if err != nil { panic(err) } diff --git a/tools/osquery-agent-options/main.go b/tools/osquery-agent-options/main.go index 1426cceba2..762c680f74 100644 --- a/tools/osquery-agent-options/main.go +++ b/tools/osquery-agent-options/main.go @@ -81,7 +81,7 @@ func main() { defer os.RemoveAll(tmpDir) osquerydAppTarGzPath := filepath.Join(tmpDir, "osqueryd.app.tar.gz") if err := download.Download(http.DefaultClient, osqueryTUFURL, osquerydAppTarGzPath); err != nil { - log.Fatalf("download osqueryd.app.tar.gz to %s: %s", osquerydAppTarGzPath, err) + log.Fatalf("download osqueryd.app.tar.gz to %s: %s", osquerydAppTarGzPath, err) //nolint:gocritic // ignore exitAfterDefer } if err := extractTarGz(osquerydAppTarGzPath); err != nil { log.Fatalf("extract tar.gz %q: %s", osquerydAppTarGzPath, err) diff --git a/tools/seed_data/queries/seed_queries.go b/tools/seed_data/queries/seed_queries.go index 857fe4b2b4..c7e1f00dd1 100644 --- a/tools/seed_data/queries/seed_queries.go +++ b/tools/seed_data/queries/seed_queries.go @@ -35,7 +35,7 @@ func main() { // Disable foreign key checks to improve performance _, err = db.Exec("SET FOREIGN_KEY_CHECKS=0") if err != nil { - log.Fatal(err) + log.Fatal(err) //nolint:gocritic // ignore exitAfterDefer } // Prepare the insert statement diff --git a/tools/seed_data/vulnerabilities/seed_vuln_data.go b/tools/seed_data/vulnerabilities/seed_vuln_data.go index 503d1a835c..63f54cb59e 100644 --- a/tools/seed_data/vulnerabilities/seed_vuln_data.go +++ b/tools/seed_data/vulnerabilities/seed_vuln_data.go @@ -286,7 +286,7 @@ func main() { host.NodeKey = "macos-seed-host" macosID, err := insertOrUpdateHost(db, host) if err != nil { - log.Fatal(err) + log.Fatal(err) //nolint:gocritic // ignore exitAfterDefer } // windows Host diff --git a/tools/tuf/download-artifacts/download-artifacts.go b/tools/tuf/download-artifacts/download-artifacts.go index 78a7e624fd..2b7b8c5500 100644 --- a/tools/tuf/download-artifacts/download-artifacts.go +++ b/tools/tuf/download-artifacts/download-artifacts.go @@ -292,15 +292,16 @@ func downloadComponents(workflowName string, headBranch string, artifactNames ma } urls = make(map[string]string) for _, artifact := range artifactList.Artifacts { - if *artifact.Name == artifactNames["linux"] { + switch { + case *artifact.Name == artifactNames["linux"]: urls["linux"] = *artifact.ArchiveDownloadURL - } else if *artifact.Name == artifactNames["linux-arm64"] { + case *artifact.Name == artifactNames["linux-arm64"]: urls["linux-arm64"] = *artifact.ArchiveDownloadURL - } else if *artifact.Name == artifactNames["macos"] { + case *artifact.Name == artifactNames["macos"]: urls["macos"] = *artifact.ArchiveDownloadURL - } else if *artifact.Name == artifactNames["windows"] { + case *artifact.Name == artifactNames["windows"]: urls["windows"] = *artifact.ArchiveDownloadURL - } else { + default: fmt.Printf("skipping artifact name: %q\n", *artifact.Name) } } diff --git a/tools/zendesk-integration/main.go b/tools/zendesk-integration/main.go index 61218c12c7..d48e60a597 100644 --- a/tools/zendesk-integration/main.go +++ b/tools/zendesk-integration/main.go @@ -83,7 +83,9 @@ func main() { ds.HostsByCVEFunc = func(ctx context.Context, cve string) ([]fleet.HostVulnerabilitySummary, error) { hosts := make([]fleet.HostVulnerabilitySummary, *hostsCount) for i := 0; i < *hostsCount; i++ { - hosts[i] = fleet.HostVulnerabilitySummary{ID: uint(i + 1), Hostname: fmt.Sprintf("host-test-%d", i+1), DisplayName: fmt.Sprintf("host-test-%d", i+1)} + hosts[i] = fleet.HostVulnerabilitySummary{ID: uint(i + 1), //nolint:gosec // dismiss G115 + Hostname: fmt.Sprintf("host-test-%d", i+1), + DisplayName: fmt.Sprintf("host-test-%d", i+1)} } return hosts, nil } @@ -171,7 +173,7 @@ func main() { jsonStr += `"hosts": ` hosts := make([]fleet.PolicySetHost, 0, *hostsCount) for i := 1; i <= *hostsCount; i++ { - hosts = append(hosts, fleet.PolicySetHost{ID: uint(i), Hostname: fmt.Sprintf("host-test-%d", i)}) + hosts = append(hosts, fleet.PolicySetHost{ID: uint(i), Hostname: fmt.Sprintf("host-test-%d", i)}) //nolint:gosec // dismiss G115 } b, _ := json.Marshal(hosts) jsonStr += string(b) + "}}"