SE: CLI setup experience changes (#22956)

This commit is contained in:
Martin Angers
2024-10-23 14:51:02 -04:00
committed by GitHub
parent aaea56de2b
commit d1c3b5b28e
42 changed files with 799 additions and 261 deletions
+79
View File
@@ -1,11 +1,15 @@
package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
@@ -139,3 +143,78 @@ func (c *Client) ApplyNoTeamScripts(scripts []fleet.ScriptPayload, opts fleet.Ap
return resp.Scripts, err
}
func (c *Client) validateMacOSSetupScript(fileName string) ([]byte, error) {
if err := c.CheckAppleMDMEnabled(); err != nil {
return nil, err
}
b, err := os.ReadFile(fileName)
if err != nil {
return nil, err
}
return b, nil
}
func (c *Client) deleteMacOSSetupScript(teamID *uint) error {
var query string
if teamID != nil {
query = fmt.Sprintf("team_id=%d", *teamID)
}
verb, path := "DELETE", "/api/latest/fleet/setup_experience/script"
var delResp deleteSetupExperienceScriptResponse
return c.authenticatedRequestWithQuery(nil, verb, path, &delResp, query)
}
func (c *Client) uploadMacOSSetupScript(filename string, data []byte, teamID *uint) error {
// there is no "replace setup experience script" endpoint, and none was
// planned, so to avoid delaying the feature I'm doing DELETE then SET, but
// that's not ideal (will always re-create the script when apply/gitops is
// run with the same yaml). Note though that we also redo software installers
// downloads on each run, so the churn of this one is minor in comparison.
if err := c.deleteMacOSSetupScript(teamID); err != nil {
return err
}
verb, path := "POST", "/api/latest/fleet/setup_experience/script"
var b bytes.Buffer
w := multipart.NewWriter(&b)
fw, err := w.CreateFormFile("script", filename)
if err != nil {
return err
}
if _, err := io.Copy(fw, bytes.NewBuffer(data)); err != nil {
return err
}
// add the team_id field
if teamID != nil {
if err := w.WriteField("team_id", fmt.Sprint(*teamID)); err != nil {
return err
}
}
w.Close()
response, err := c.doContextWithBodyAndHeaders(context.Background(), verb, path, "",
b.Bytes(),
map[string]string{
"Content-Type": w.FormDataContentType(),
"Accept": "application/json",
"Authorization": fmt.Sprintf("Bearer %s", c.token),
},
)
if err != nil {
return fmt.Errorf("do multipart request: %w", err)
}
defer response.Body.Close()
var resp setSetupExperienceScriptResponse
if err := c.parseResponse(verb, path, response, &resp); err != nil {
return fmt.Errorf("parse response: %w", err)
}
return nil
}