fleet/server/service/client_scripts.go
Jahziel Villasana-Espinoza 71b7b8b46c
feat: disable script endpoints and add error to cli (#15941)
> 📜 Relevant PR: #14500

# 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] Added/updated tests
- [x] Manual QA for all new/changed functionality
2024-01-08 16:28:45 -05:00

71 lines
1.8 KiB
Go

package service
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/fleetdm/fleet/v4/server/fleet"
)
func (c *Client) RunHostScriptSync(hostID uint, scriptContents []byte) (*fleet.HostScriptResult, error) {
verb, path := "POST", "/api/latest/fleet/scripts/run/sync"
req := fleet.HostScriptRequestPayload{
HostID: hostID,
ScriptContents: string(scriptContents),
}
var result fleet.HostScriptResult
res, err := c.AuthenticatedDo(verb, path, "", &req)
if err != nil {
return nil, err
}
defer res.Body.Close()
switch res.StatusCode {
case http.StatusOK:
b, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("reading %s %s response: %w", verb, path, err)
}
if err := json.Unmarshal(b, &result); err != nil {
return nil, fmt.Errorf("decoding %s %s response: %w, body: %s", verb, path, err, b)
}
case http.StatusForbidden:
errMsg, err := extractServerErrMsg(verb, path, res)
if err != nil {
return nil, err
}
if strings.Contains(errMsg, fleet.RunScriptScriptsDisabledGloballyErrMsg) {
return nil, errors.New(fleet.RunScriptScriptsDisabledGloballyErrMsg)
}
return nil, errors.New(fleet.RunScriptForbiddenErrMsg)
default:
msg, err := extractServerErrMsg(verb, path, res)
if err != nil {
return nil, err
}
if msg == "" {
msg = fmt.Sprintf("decoding %d response is missing expected message.", res.StatusCode)
}
return nil, errors.New(msg)
}
return &result, nil
}
// ApplyNoTeamScripts sends the list of scripts to be applied for the hosts in
// no team.
func (c *Client) ApplyNoTeamScripts(scripts []fleet.ScriptPayload, opts fleet.ApplySpecOptions) error {
verb, path := "POST", "/api/latest/fleet/scripts/batch"
return c.authenticatedRequestWithQuery(map[string]interface{}{"scripts": scripts}, verb, path, nil, opts.RawQuery())
}