Improved label(s) validation when running queries (#23834)

Previously when passing labels to the query run endpoints that do not
exist, the labels would simply be ignored. Now the endpoint will return
an error indicating which labels are invalid. This change also affects
the `fleetctl query` command `--labels` flag.

https://github.com/fleetdm/fleet/issues/23015

# Checklist for submitter

If some of the following don't apply, delete the relevant line.

<!-- Note that API documentation changes are now addressed by the
product design team. -->

- [x] Changes file added for user-visible changes in `changes/`,
`orbit/changes/` or `ee/fleetd-chrome/changes`.
See [Changes
files](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/Committing-Changes.md#changes-files)
for more information.
- [x] Added/updated tests
- [x] Manual QA for all new/changed functionality

---------

Co-authored-by: Ian Littman <iansltx@gmail.com>
This commit is contained in:
Konstantin Sykulev
2024-11-21 16:13:30 -06:00
committed by GitHub
co-authored by Ian Littman
parent ecc2bfb1f0
commit 46f10b85cd
10 changed files with 192 additions and 2 deletions
+7
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"regexp"
"strings"
"time"
@@ -138,6 +139,12 @@ func queryCommand() *cli.Command {
if strings.Contains(err.Error(), "no hosts targeted") {
return errors.New(fleet.NoHostsTargetedErrMsg)
}
if strings.Contains(err.Error(), fleet.InvalidLabelSpecifiedErrMsg) {
pattern := fmt.Sprintf("(%s.*)$", regexp.QuoteMeta(fleet.InvalidLabelSpecifiedErrMsg))
regex := regexp.MustCompile(pattern)
match := regex.FindString(err.Error())
return errors.New(match)
}
return err
}
+10 -1
View File
@@ -219,8 +219,9 @@ func TestAdHocLiveQuery(t *testing.T) {
return []uint{1234}, nil
}
ds.LabelIDsByNameFunc = func(ctx context.Context, labels []string) (map[string]uint, error) {
return nil, nil
return map[string]uint{"label1": uint(1)}, nil
}
ds.AppConfigFunc = func(ctx context.Context) (*fleet.AppConfig, error) {
return &fleet.AppConfig{}, nil
}
@@ -299,6 +300,14 @@ func TestAdHocLiveQuery(t *testing.T) {
)
}()
// test label not found
_, err = runAppNoChecks([]string{"query", "--hosts", "1234", "--labels", "iamnotalabel", "--query", "select 42, * from time"})
assert.ErrorContains(t, err, "Invalid label name(s): iamnotalabel.")
// test if some labels were not found
_, err = runAppNoChecks([]string{"query", "--labels", "label1, mac, windows", "--hosts", "1234", "--query", "select 42, * from time"})
assert.ErrorContains(t, err, "Invalid label name(s): mac, windows.")
expected := `{"host":"somehostname","rows":[{"bing":"fds","host_display_name":"somehostname","host_hostname":"somehostname"}]}
`
assert.Equal(t, expected, runAppForTest(t, []string{"query", "--hosts", "1234", "--query", "select 42, * from time"}))