mirror of
https://github.com/fleetdm/fleet
synced 2026-04-21 13:37:30 +00:00
Updating golangci-lint to 1.61.0 (#22973)
This commit is contained in:
parent
77862664d5
commit
f85b6f776f
236 changed files with 877 additions and 831 deletions
2
.github/workflows/golangci-lint.yml
vendored
2
.github/workflows/golangci-lint.yml
vendored
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
2
Makefile
2
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
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -464,23 +464,21 @@ or provide an <address> argument to debug: fleetctl debug connection localhost:8
|
|||
// if a certificate is provided, use it as root CA
|
||||
cc.RootCA = certPath
|
||||
cc.TLSSkipVerify = false
|
||||
} else { // --fleet-certificate is not set
|
||||
if cc.RootCA == "" {
|
||||
// If a certificate is not provided and a cc.RootCA is not set in the configuration,
|
||||
// then use the embedded root CA which is used by osquery to connect to Fleet.
|
||||
usingEmbeddedCA = true
|
||||
tmpDir, err := os.MkdirTemp("", "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temporary directory: %w", err)
|
||||
}
|
||||
certPath := filepath.Join(tmpDir, "certs.pem")
|
||||
if err := os.WriteFile(certPath, packaging.OsqueryCerts, 0o600); err != nil {
|
||||
return fmt.Errorf("failed to create temporary certs.pem file: %s", err)
|
||||
}
|
||||
defer os.RemoveAll(certPath)
|
||||
cc.RootCA = certPath
|
||||
cc.TLSSkipVerify = false
|
||||
} else if cc.RootCA == "" { // --fleet-certificate is not set
|
||||
// If a certificate is not provided and a cc.RootCA is not set in the configuration,
|
||||
// then use the embedded root CA which is used by osquery to connect to Fleet.
|
||||
usingEmbeddedCA = true
|
||||
tmpDir, err := os.MkdirTemp("", "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temporary directory: %w", err)
|
||||
}
|
||||
certPath := filepath.Join(tmpDir, "certs.pem")
|
||||
if err := os.WriteFile(certPath, packaging.OsqueryCerts, 0o600); err != nil {
|
||||
return fmt.Errorf("failed to create temporary certs.pem file: %s", err)
|
||||
}
|
||||
defer os.RemoveAll(certPath)
|
||||
cc.RootCA = certPath
|
||||
cc.TLSSkipVerify = false
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 == "" {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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"},
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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{
|
||||
|
|
|
|||
|
|
@ -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"},
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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)))
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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"])
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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, "")
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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'
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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"))
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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] })
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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{}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
))
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
))
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
))
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
))
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
))
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue