Skip to content

Commit 77f9a57

Browse files
feat(dataupload): replace PostDataReadingsWithOptions with PutSnapshot
- Introduced a new `Snapshot` struct to represent the payload for the CyberArk Discovery and Context API. - Replaced the `PostDataReadingsWithOptions` method with `PutSnapshot`, which now uses the `Snapshot` struct and removes the dependency on `api.DataReadingsPost`. - Updated the `retrievePresignedUploadURL` method to accept `clusterID` directly instead of relying on `Options`. - Refactored tests to align with the new `PutSnapshot` method and `Snapshot` struct. Removed unused imports and legacy test cases. Signed-off-by: Richard Wall <[email protected]>
1 parent b82d7ce commit 77f9a57

File tree

2 files changed

+51
-61
lines changed

2 files changed

+51
-61
lines changed

pkg/internal/cyberark/dataupload/dataupload.go

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ import (
1212
"net/http"
1313
"net/url"
1414

15-
"github.com/jetstack/preflight/api"
15+
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
16+
1617
"github.com/jetstack/preflight/pkg/version"
1718
)
1819

@@ -46,7 +47,27 @@ func New(httpClient *http.Client, baseURL string, authenticateRequest func(req *
4647
}
4748
}
4849

49-
// PostDataReadingsWithOptions PUTs the supplied payload to an [AWS presigned URL] which it obtains via the CyberArk inventory API.
50+
// snapshot is the JSON that the CyberArk Discovery and Context API expects to
51+
// be uploaded to the AWS presigned URL.
52+
type Snapshot struct {
53+
AgentVersion string `json:"agent_version"`
54+
ClusterID string `json:"cluster_id"`
55+
K8SVersion string `json:"k8s_version"`
56+
Secrets []*unstructured.Unstructured `json:"secrets"`
57+
ServiceAccounts []*unstructured.Unstructured `json:"serviceaccounts"`
58+
Roles []*unstructured.Unstructured `json:"roles"`
59+
ClusterRoles []*unstructured.Unstructured `json:"clusterroles"`
60+
RoleBindings []*unstructured.Unstructured `json:"rolebindings"`
61+
ClusterRoleBindings []*unstructured.Unstructured `json:"clusterrolebindings"`
62+
Jobs []*unstructured.Unstructured `json:"jobs"`
63+
CronJobs []*unstructured.Unstructured `json:"cronjobs"`
64+
Deployments []*unstructured.Unstructured `json:"deployments"`
65+
Statefulsets []*unstructured.Unstructured `json:"statefulsets"`
66+
Daemonsets []*unstructured.Unstructured `json:"daemonsets"`
67+
Pods []*unstructured.Unstructured `json:"pods"`
68+
}
69+
70+
// PutSnapshot PUTs the supplied snapshot to an [AWS presigned URL] which it obtains via the CyberArk inventory API.
5071
// [AWS presigned URL]: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
5172
//
5273
// A SHA256 checksum header is included in the request, to verify that the payload
@@ -60,20 +81,16 @@ func New(httpClient *http.Client, baseURL string, authenticateRequest func(req *
6081
// If you omit that header, it is possible to PUT any data.
6182
// There is a work around listed in that issue which we have shared with the
6283
// CyberArk API team.
63-
func (c *CyberArkClient) PostDataReadingsWithOptions(ctx context.Context, payload api.DataReadingsPost, opts Options) error {
64-
if opts.ClusterName == "" {
65-
return fmt.Errorf("programmer mistake: the cluster name (aka `cluster_id` in the config file) cannot be left empty")
66-
}
67-
84+
func (c *CyberArkClient) PutSnapshot(ctx context.Context, snapshot Snapshot) error {
6885
encodedBody := &bytes.Buffer{}
6986
hash := sha256.New()
70-
if err := json.NewEncoder(io.MultiWriter(encodedBody, hash)).Encode(payload); err != nil {
87+
if err := json.NewEncoder(io.MultiWriter(encodedBody, hash)).Encode(snapshot); err != nil {
7188
return err
7289
}
7390
checksum := hash.Sum(nil)
7491
checksumHex := hex.EncodeToString(checksum)
7592
checksumBase64 := base64.StdEncoding.EncodeToString(checksum)
76-
presignedUploadURL, err := c.retrievePresignedUploadURL(ctx, checksumHex, opts)
93+
presignedUploadURL, err := c.retrievePresignedUploadURL(ctx, checksumHex, snapshot.ClusterID)
7794
if err != nil {
7895
return fmt.Errorf("while retrieving snapshot upload URL: %s", err)
7996
}
@@ -103,7 +120,7 @@ func (c *CyberArkClient) PostDataReadingsWithOptions(ctx context.Context, payloa
103120
return nil
104121
}
105122

106-
func (c *CyberArkClient) retrievePresignedUploadURL(ctx context.Context, checksum string, opts Options) (string, error) {
123+
func (c *CyberArkClient) retrievePresignedUploadURL(ctx context.Context, checksum string, clusterID string) (string, error) {
107124
uploadURL, err := url.JoinPath(c.baseURL, apiPathSnapshotLinks)
108125
if err != nil {
109126
return "", err
@@ -114,7 +131,7 @@ func (c *CyberArkClient) retrievePresignedUploadURL(ctx context.Context, checksu
114131
Checksum string `json:"checksum_sha256"`
115132
AgentVersion string `json:"agent_version"`
116133
}{
117-
ClusterID: opts.ClusterName,
134+
ClusterID: clusterID,
118135
Checksum: checksum,
119136
AgentVersion: version.PreflightVersion,
120137
}

pkg/internal/cyberark/dataupload/dataupload_test.go

Lines changed: 23 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,13 @@ import (
66
"net/http"
77
"os"
88
"testing"
9-
"time"
109

1110
"github.com/jetstack/venafi-connection-lib/http_client"
1211
"github.com/stretchr/testify/require"
1312
"k8s.io/client-go/transport"
1413
"k8s.io/klog/v2"
1514
"k8s.io/klog/v2/ktesting"
1615

17-
"github.com/jetstack/preflight/api"
1816
"github.com/jetstack/preflight/pkg/internal/cyberark/dataupload"
1917
"github.com/jetstack/preflight/pkg/internal/cyberark/identity"
2018
"github.com/jetstack/preflight/pkg/internal/cyberark/servicediscovery"
@@ -23,28 +21,7 @@ import (
2321
_ "k8s.io/klog/v2/ktesting/init"
2422
)
2523

26-
func TestCyberArkClient_PostDataReadingsWithOptions(t *testing.T) {
27-
fakeTime := time.Unix(123, 0)
28-
defaultPayload := api.DataReadingsPost{
29-
AgentMetadata: &api.AgentMetadata{
30-
Version: "test-version",
31-
ClusterID: "test",
32-
},
33-
DataGatherTime: fakeTime,
34-
DataReadings: []*api.DataReading{
35-
{
36-
ClusterID: "success-cluster-id",
37-
DataGatherer: "test-gatherer",
38-
Timestamp: api.Time{Time: fakeTime},
39-
Data: map[string]interface{}{"test": "data"},
40-
SchemaVersion: "v1",
41-
},
42-
},
43-
}
44-
defaultOpts := dataupload.Options{
45-
ClusterName: "success-cluster-id",
46-
}
47-
24+
func TestCyberArkClient_PutSnapshot(t *testing.T) {
4825
setToken := func(token string) func(*http.Request) error {
4926
return func(req *http.Request) error {
5027
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
@@ -54,51 +31,49 @@ func TestCyberArkClient_PostDataReadingsWithOptions(t *testing.T) {
5431

5532
tests := []struct {
5633
name string
57-
payload api.DataReadingsPost
34+
snapshot dataupload.Snapshot
5835
authenticate func(req *http.Request) error
59-
opts dataupload.Options
6036
requireFn func(t *testing.T, err error)
6137
}{
6238
{
63-
name: "successful upload",
64-
payload: defaultPayload,
65-
opts: defaultOpts,
39+
name: "successful upload",
40+
snapshot: dataupload.Snapshot{
41+
ClusterID: "success-cluster-id",
42+
AgentVersion: "test-version",
43+
},
6644
authenticate: setToken("success-token"),
6745
requireFn: func(t *testing.T, err error) {
6846
require.NoError(t, err)
6947
},
7048
},
7149
{
72-
name: "error when cluster name is empty",
73-
payload: defaultPayload,
74-
opts: dataupload.Options{ClusterName: ""},
75-
authenticate: setToken("success-token"),
76-
requireFn: func(t *testing.T, err error) {
77-
require.ErrorContains(t, err, "programmer mistake: the cluster name")
50+
name: "error when bearer token is incorrect",
51+
snapshot: dataupload.Snapshot{
52+
ClusterID: "test",
53+
AgentVersion: "test-version",
7854
},
79-
},
80-
{
81-
name: "error when bearer token is incorrect",
82-
payload: defaultPayload,
83-
opts: defaultOpts,
8455
authenticate: setToken("fail-token"),
8556
requireFn: func(t *testing.T, err error) {
8657
require.ErrorContains(t, err, "while retrieving snapshot upload URL: received response with status code 500: should authenticate using the correct bearer token")
8758
},
8859
},
8960
{
90-
name: "invalid JSON from server (RetrievePresignedUploadURL step)",
91-
payload: defaultPayload,
92-
opts: dataupload.Options{ClusterName: "invalid-json-retrieve-presigned"},
61+
name: "invalid JSON from server (RetrievePresignedUploadURL step)",
62+
snapshot: dataupload.Snapshot{
63+
ClusterID: "invalid-json-retrieve-presigned",
64+
AgentVersion: "test-version",
65+
},
9366
authenticate: setToken("success-token"),
9467
requireFn: func(t *testing.T, err error) {
9568
require.ErrorContains(t, err, "while retrieving snapshot upload URL: rejecting JSON response from server as it was too large or was truncated")
9669
},
9770
},
9871
{
99-
name: "500 from server (RetrievePresignedUploadURL step)",
100-
payload: defaultPayload,
101-
opts: dataupload.Options{ClusterName: "invalid-response-post-data"},
72+
name: "500 from server (RetrievePresignedUploadURL step)",
73+
snapshot: dataupload.Snapshot{
74+
ClusterID: "invalid-response-post-data",
75+
AgentVersion: "test-version",
76+
},
10277
authenticate: setToken("success-token"),
10378
requireFn: func(t *testing.T, err error) {
10479
require.ErrorContains(t, err, "while retrieving snapshot upload URL: received response with status code 500: mock error")
@@ -115,7 +90,7 @@ func TestCyberArkClient_PostDataReadingsWithOptions(t *testing.T) {
11590

11691
cyberArkClient := dataupload.New(httpClient, datauploadAPIBaseURL, tc.authenticate)
11792

118-
err := cyberArkClient.PostDataReadingsWithOptions(ctx, tc.payload, tc.opts)
93+
err := cyberArkClient.PutSnapshot(ctx, tc.snapshot)
11994
tc.requireFn(t, err)
12095
})
12196
}
@@ -159,8 +134,6 @@ func TestPostDataReadingsWithOptionsWithRealAPI(t *testing.T) {
159134
require.NoError(t, err)
160135

161136
cyberArkClient := dataupload.New(httpClient, services.DiscoveryContext.API, identityClient.AuthenticateRequest)
162-
err = cyberArkClient.PostDataReadingsWithOptions(ctx, api.DataReadingsPost{}, dataupload.Options{
163-
ClusterName: "bb068932-c80d-460d-88df-34bc7f3f3297",
164-
})
137+
err = cyberArkClient.PutSnapshot(ctx, dataupload.Snapshot{})
165138
require.NoError(t, err)
166139
}

0 commit comments

Comments
 (0)