fleet/server/service/client_queries.go
Victor Lyuboslavsky 0e040cc7b0
fleetctl now runs saved queries (#15667)
📺 Looom:
https://www.loom.com/share/1aec4616fa4449e7abac579084aef0ba?sid=0884f742-feb3-48bb-82dc-b7834bc9a6e1

Fixed fleetctl issue where it was creating a new query when running a
query by name, as opposed to using the existing saved query.
#15630

API change will be in a separate PR:
https://github.com/fleetdm/fleet/pull/15673

# 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/` or
`orbit/changes/`.
See [Changes
files](https://fleetdm.com/docs/contributing/committing-changes#changes-files)
for more information.
- [x] Input data is properly validated, `SELECT *` is avoided, SQL
injection is prevented (using placeholders for values in statements)
- [x] Added/updated tests
- [x] Manual QA for all new/changed functionality
2023-12-15 12:55:39 -06:00

55 lines
1.7 KiB
Go

package service
import (
"fmt"
"net/url"
"github.com/fleetdm/fleet/v4/server/fleet"
)
// ApplyQueries sends the list of Queries to be applied (upserted) to the
// Fleet instance.
func (c *Client) ApplyQueries(specs []*fleet.QuerySpec) error {
req := applyQuerySpecsRequest{Specs: specs}
verb, path := "POST", "/api/latest/fleet/spec/queries"
var responseBody applyQuerySpecsResponse
return c.authenticatedRequest(req, verb, path, &responseBody)
}
// GetQuerySpec returns the query spec of a query by its team+name.
func (c *Client) GetQuerySpec(teamID *uint, name string) (*fleet.QuerySpec, error) {
verb, path := "GET", "/api/latest/fleet/spec/queries/"+url.PathEscape(name)
query := url.Values{}
if teamID != nil {
query.Set("team_id", fmt.Sprint(*teamID))
}
var responseBody getQuerySpecResponse
err := c.authenticatedRequestWithQuery(nil, verb, path, &responseBody, query.Encode())
return responseBody.Spec, err
}
// GetQueries retrieves the list of all Queries.
func (c *Client) GetQueries(teamID *uint, name *string) ([]fleet.Query, error) {
verb, path := "GET", "/api/latest/fleet/queries"
query := url.Values{}
if teamID != nil {
query.Set("team_id", fmt.Sprint(*teamID))
}
if name != nil {
query.Set("query", *name)
}
var responseBody listQueriesResponse
err := c.authenticatedRequestWithQuery(nil, verb, path, &responseBody, query.Encode())
if err != nil {
return nil, err
}
return responseBody.Queries, nil
}
// DeleteQuery deletes the query with the matching name.
func (c *Client) DeleteQuery(name string) error {
verb, path := "DELETE", "/api/latest/fleet/queries/"+url.PathEscape(name)
var responseBody deleteQueryResponse
return c.authenticatedRequest(nil, verb, path, &responseBody)
}