Skip to content

Commit

Permalink
Cleanup and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksmaus committed Aug 1, 2023
1 parent 5adb648 commit 189862e
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 95 deletions.
142 changes: 55 additions & 87 deletions kibana/fleet.go
Original file line number Diff line number Diff line change
Expand Up @@ -557,10 +557,10 @@ type DeletePackagePolicyResponse struct {

// InstallFleetPackage uses the Fleet package policies API install an integration package as specified in the request.
// Note that the package policy ID and Name must be globally unique across all installed packages.
func (client *Client) InstallFleetPackage(ctx context.Context, req PackagePolicyRequest) (*PackagePolicyResponse, error) {
func (client *Client) InstallFleetPackage(ctx context.Context, req PackagePolicyRequest) (r PackagePolicyResponse, err error) {
reqBytes, err := json.Marshal(&req)
if err != nil {
return nil, fmt.Errorf("marshalling request json: %w", err)
return r, fmt.Errorf("marshalling request json: %w", err)
}

resp, err := client.Connection.SendWithContext(ctx,
Expand All @@ -571,33 +571,20 @@ func (client *Client) InstallFleetPackage(ctx context.Context, req PackagePolicy
bytes.NewReader(reqBytes),
)
if err != nil {
return nil, fmt.Errorf("posting %s: %w", fleetPackagePoliciesAPI, err)
return r, fmt.Errorf("posting %s: %w", fleetPackagePoliciesAPI, err)
}
defer resp.Body.Close()

pkgRespBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response body: %w", err)
}

if resp.StatusCode != http.StatusOK {
return nil, extractError(pkgRespBytes)
}

pkgPolicyResp := PackagePolicyResponse{}
err = json.Unmarshal(pkgRespBytes, &pkgPolicyResp)
if err != nil {
return nil, fmt.Errorf("unmarshalling response json: %w", err)
}
err = readJSONResponse(resp, &r)

Check failure on line 578 in kibana/fleet.go

View workflow job for this annotation

GitHub Actions / lint (windows)

ineffectual assignment to err (ineffassign)

return &pkgPolicyResp, nil
return r, nil
}

// DeleteFleetPackage deletes integration with packagePolicyID from the policy ID
func (client *Client) DeleteFleetPackage(ctx context.Context, packagePolicyID string) (*DeletePackagePolicyResponse, error) {
func (client *Client) DeleteFleetPackage(ctx context.Context, packagePolicyID string) (r DeletePackagePolicyResponse, err error) {
u, err := url.JoinPath(fleetPackagePoliciesAPI, packagePolicyID)
if err != nil {
return nil, err
return r, err
}

resp, err := client.Connection.SendWithContext(ctx,
Expand All @@ -607,110 +594,81 @@ func (client *Client) DeleteFleetPackage(ctx context.Context, packagePolicyID st
nil,
nil,
)
if err != nil {
return nil, fmt.Errorf("DELETE %s: %w", u, err)
}
defer resp.Body.Close()

respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response body: %w", err)
return r, fmt.Errorf("DELETE %s: %w", u, err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return nil, extractError(respBytes)
}
err = readJSONResponse(resp, &r)

var pkgPolicyResp DeletePackagePolicyResponse
err = json.Unmarshal(respBytes, &pkgPolicyResp)
if err != nil {
return nil, fmt.Errorf("unmarshalling response json: %w", err)
}
return r, err
}

return &pkgPolicyResp, nil
// UninstallTokenResponse uninstall tokens response with resolved token values
type UninstallTokenResponse struct {
Items []UninstallTokenItem `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
PerPage int `json:"perPage"`
}

type getUninstallTokenItem struct {
type UninstallTokenItem struct {
ID string `json:"id"`
PolicyID string `json:"policy_id"`
Token string `json:"token"`
CreatedAt string `json:"created_at"`
}

type getUninstallTokensResponse struct {
Items []getUninstallTokenItem `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
PerPage int `json:"per_page"`
type uninstallTokenValueResponse struct {
Item UninstallTokenItem `json:"item"`
}

// GetPolicyUninstallTokens Retrieves the the policy uninstall tokens
func (client *Client) GetPolicyUninstallTokens(ctx context.Context, policyID string) ([]UninstallTokenResponse, error) {
func (client *Client) GetPolicyUninstallTokens(ctx context.Context, policyID string) (r UninstallTokenResponse, err error) {
u, err := url.Parse(fleetUninstallTokensAPI)
if err != nil {
return nil, err
return r, err
}
// Compose URL with params

// Fetch uninstall token for the policy
// /api/fleet/uninstall_tokens?policyId={policyId}&page=1&perPage=1000
q := u.Query()
q := make(url.Values)
q.Add("policyId", policyID)
q.Add("page", "1")
q.Add("perPage", "1000")

resp, err := client.Connection.SendWithContext(ctx,
http.MethodGet,
u.String(),
fleetUninstallTokensAPI,
q,
nil,
nil,
)
if err != nil {
return nil, fmt.Errorf("getting %s: %w", u.String(), err)
return r, fmt.Errorf("getting %s: %w", u.String(), err)
}
defer resp.Body.Close()

b, err := io.ReadAll(resp.Body)
err = readJSONResponse(resp, &r)
if err != nil {
return nil, fmt.Errorf("reading response body: %w", err)
}

if resp.StatusCode != http.StatusOK {
return nil, extractError(b)
}

var itResp getUninstallTokensResponse
err = json.Unmarshal(b, &itResp)
if err != nil {
return nil, fmt.Errorf("unmarshalling response json: %w", err)
return r, err
}

sz := len(itResp.Items)

tokenResps := make([]UninstallTokenResponse, 0, sz)

for _, e := range itResp.Items {
tokenResp, err := client.GetUninstallToken(ctx, e.ID)
// Resolve token values for token ID
for i := 0; i < len(r.Items); i++ {
tokRes, err := client.GetUninstallToken(ctx, r.Items[i].ID)
if err != nil {
return nil, err
return r, err
}
tokenResps = append(tokenResps, tokenResp)
r.Items[i] = tokRes
}

return tokenResps, nil
}

type UninstallTokenItem struct {
ID string `json:"id"`
PolicyID string `json:"policy_id"`
Token string `json:"token"`
CreatedAt string `json:"created_at"`
}

type UninstallTokenResponse struct {
Item UninstallTokenItem `json:"item"`
return r, nil
}

// GetUninstallToken return uninstall token value for the given token ID
func (client *Client) GetUninstallToken(ctx context.Context, tokenID string) (r UninstallTokenResponse, err error) {
func (client *Client) GetUninstallToken(ctx context.Context, tokenID string) (r UninstallTokenItem, err error) {
u, err := url.JoinPath(fleetUninstallTokensAPI, tokenID)
if err != nil {
return r, err
Expand All @@ -729,18 +687,28 @@ func (client *Client) GetUninstallToken(ctx context.Context, tokenID string) (r
}
defer resp.Body.Close()

b, err := io.ReadAll(resp.Body)
var res uninstallTokenValueResponse
err = readJSONResponse(resp, &res)
if err != nil {
return r, err
}

return res.Item, nil
}

func readJSONResponse(r *http.Response, v any) error {
b, err := io.ReadAll(r.Body)
if err != nil {
return r, fmt.Errorf("reading response body: %w", err)
return fmt.Errorf("reading response body: %w", err)
}

if resp.StatusCode != http.StatusOK {
return r, extractError(b)
if r.StatusCode != http.StatusOK {
return extractError(b)
}

err = json.Unmarshal(b, &r)
err = json.Unmarshal(b, v)
if err != nil {
return r, fmt.Errorf("unmarshalling response json: %w", err)
return fmt.Errorf("unmarshalling response json: %w", err)
}
return r, nil
return nil
}
16 changes: 8 additions & 8 deletions kibana/fleet_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,10 @@ func TestUpdatePolicyKibana(t *testing.T) {
require.Equal(t, *updatePolicyTamperProtection.IsProtected, updateResp.IsProtected)

// Get uninstall tokens, should be one
uninstallTokenResps, err := client.GetPolicyUninstallTokens(context.Background(), respPolicy.ID)
uninstallTokenResp, err := client.GetPolicyUninstallTokens(context.Background(), respPolicy.ID)
require.NoError(t, err)
require.Greater(t, len(uninstallTokenResps), 0, "Expected non-zero number of tokens")
require.Greater(t, len(uninstallTokenResps[0].Item.Token), 0, "expected non-empty token")
require.Greater(t, len(uninstallTokenResp.Items), 0, "Expected non-zero number of tokens")
require.Greater(t, len(uninstallTokenResp.Items[0].Token), 0, "expected non-empty token")

// Disable tamper protection
updatePolicyTamperProtection = AgentPolicyUpdateRequest{
Expand Down Expand Up @@ -216,7 +216,7 @@ func TestFleetPackage(t *testing.T) {
require.NoError(t, err)
}

func installElasticDefendPackage(t *testing.T, client *Client, policyID, packagePolicyID string) (*PackagePolicyResponse, error) {
func installElasticDefendPackage(t *testing.T, client *Client, policyID, packagePolicyID string) (r PackagePolicyResponse, err error) {
t.Helper()

ctx, cn := context.WithCancel(context.Background())
Expand All @@ -225,7 +225,7 @@ func installElasticDefendPackage(t *testing.T, client *Client, policyID, package
t.Log("Templating endpoint package policy request")
tmpl, err := template.New("pkgpolicy").Parse(endpointPackagePolicyTemplate)
if err != nil {
return nil, fmt.Errorf("error creating new template: %w", err)
return r, fmt.Errorf("error creating new template: %w", err)
}

var pkgPolicyBuf bytes.Buffer
Expand All @@ -239,21 +239,21 @@ func installElasticDefendPackage(t *testing.T, client *Client, policyID, package
Version: endpointPackageVersion,
})
if err != nil {
return nil, fmt.Errorf("error executing template: %w", err)
return r, fmt.Errorf("error executing template: %w", err)
}

// Make sure the templated value is actually valid JSON before making the API request.
// Using json.Unmarshal will give us the actual syntax error, calling json.Valid() would not.
var packagePolicyReq PackagePolicyRequest
err = json.Unmarshal(pkgPolicyBuf.Bytes(), &packagePolicyReq)
if err != nil {
return nil, fmt.Errorf("templated package policy is not valid JSON: %s, %w", pkgPolicyBuf.String(), err)
return r, fmt.Errorf("templated package policy is not valid JSON: %s, %w", pkgPolicyBuf.String(), err)
}

pkgResp, err := client.InstallFleetPackage(ctx, packagePolicyReq)
if err != nil {
t.Logf("Error installing fleet package: %v", err)
return nil, fmt.Errorf("error installing fleet package: %w", err)
return r, fmt.Errorf("error installing fleet package: %w", err)
}
t.Logf("Endpoint package Policy Response:\n%+v", pkgResp)
return pkgResp, err
Expand Down

0 comments on commit 189862e

Please sign in to comment.