Skip to content

Commit 5476b9d

Browse files
authored
Merge pull request #662 from jetstack/cleanup_part2
Cleanup client interface
2 parents df72cd9 + 45824bc commit 5476b9d

File tree

7 files changed

+24
-127
lines changed

7 files changed

+24
-127
lines changed

pkg/agent/run.go

Lines changed: 10 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package agent
22

33
import (
4-
"bytes"
54
"context"
65
"encoding/json"
76
"errors"
@@ -425,7 +424,8 @@ func postData(ctx context.Context, config CombinedConfig, preflightClient client
425424

426425
log.V(logs.Debug).Info("Posting data", "baseURL", baseURL)
427426

428-
if config.TLSPKMode == VenafiCloudKeypair || config.TLSPKMode == VenafiCloudVenafiConnection {
427+
switch config.TLSPKMode { // nolint:exhaustive
428+
case VenafiCloudKeypair, VenafiCloudVenafiConnection:
429429
// orgID and clusterID are not required for Venafi Cloud auth
430430
err := preflightClient.PostDataReadingsWithOptions(ctx, readings, client.Options{
431431
ClusterName: config.ClusterID,
@@ -437,55 +437,22 @@ func postData(ctx context.Context, config CombinedConfig, preflightClient client
437437
log.Info("Data sent successfully")
438438

439439
return nil
440-
}
441-
442-
if config.OrganizationID == "" {
443-
data, err := json.Marshal(readings)
444-
if err != nil {
445-
return fmt.Errorf("Cannot marshal readings: %+v", err)
446-
}
447-
448-
// log and collect metrics about the upload size
449-
metric := metricPayloadSize.With(
450-
prometheus.Labels{"organization": config.OrganizationID, "cluster": config.ClusterID},
451-
)
452-
metric.Set(float64(len(data)))
453-
log.Info("Data readings", "uploadSize", len(data))
454-
path := config.EndpointPath
455-
if path == "" {
456-
path = "/api/v1/datareadings"
457-
}
458-
res, err := preflightClient.Post(ctx, path, bytes.NewBuffer(data))
459440

441+
case JetstackSecureOAuth, JetstackSecureAPIToken:
442+
err := preflightClient.PostDataReadingsWithOptions(ctx, readings, client.Options{
443+
OrgID: config.OrganizationID,
444+
ClusterID: config.ClusterID,
445+
})
460446
if err != nil {
461-
return fmt.Errorf("failed to post data: %+v", err)
462-
}
463-
if code := res.StatusCode; code < 200 || code >= 300 {
464-
errorContent := ""
465-
body, _ := io.ReadAll(res.Body)
466-
if err == nil {
467-
errorContent = string(body)
468-
}
469-
defer res.Body.Close()
470-
471-
return fmt.Errorf("received response with status code %d. Body: [%s]", code, errorContent)
447+
return fmt.Errorf("post to server failed: %+v", err)
472448
}
473449
log.Info("Data sent successfully")
474450

475451
return err
476-
}
477452

478-
if config.ClusterID == "" {
479-
return fmt.Errorf("post to server failed: missing clusterID from agent configuration")
453+
default:
454+
return fmt.Errorf("not implemented for mode %s", config.TLSPKMode)
480455
}
481-
482-
err := preflightClient.PostDataReadings(ctx, config.OrganizationID, config.ClusterID, readings)
483-
if err != nil {
484-
return fmt.Errorf("post to server failed: %+v", err)
485-
}
486-
log.Info("Data sent successfully")
487-
488-
return nil
489456
}
490457

491458
// listenAndServe starts the supplied HTTP server and stops it gracefully when

pkg/client/client.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ package client
33
import (
44
"context"
55
"fmt"
6-
"io"
7-
"net/http"
86
"strings"
97

108
"github.com/jetstack/preflight/api"
@@ -30,9 +28,7 @@ type (
3028

3129
// The Client interface describes types that perform requests against the Jetstack Secure backend.
3230
Client interface {
33-
PostDataReadings(ctx context.Context, orgID, clusterID string, readings []*api.DataReading) error
3431
PostDataReadingsWithOptions(ctx context.Context, readings []*api.DataReading, options Options) error
35-
Post(ctx context.Context, path string, body io.Reader) (*http.Response, error)
3632
}
3733

3834
// The Credentials interface describes methods for credential types to implement for verification.

pkg/client/client_api_token.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,12 @@ func NewAPITokenClient(agentMetadata *api.AgentMetadata, apiToken, baseURL strin
4848
// PostDataReadingsWithOptions uploads the slice of api.DataReading to the Jetstack Secure backend to be processed for later
4949
// viewing in the user-interface.
5050
func (c *APITokenClient) PostDataReadingsWithOptions(ctx context.Context, readings []*api.DataReading, opts Options) error {
51-
return c.PostDataReadings(ctx, opts.OrgID, opts.ClusterID, readings)
51+
return c.postDataReadings(ctx, opts.OrgID, opts.ClusterID, readings)
5252
}
5353

5454
// PostDataReadings uploads the slice of api.DataReading to the Jetstack Secure backend to be processed for later
5555
// viewing in the user-interface.
56-
func (c *APITokenClient) PostDataReadings(ctx context.Context, orgID, clusterID string, readings []*api.DataReading) error {
56+
func (c *APITokenClient) postDataReadings(ctx context.Context, orgID, clusterID string, readings []*api.DataReading) error {
5757
payload := api.DataReadingsPost{
5858
AgentMetadata: c.agentMetadata,
5959
DataGatherTime: time.Now().UTC(),
@@ -64,7 +64,7 @@ func (c *APITokenClient) PostDataReadings(ctx context.Context, orgID, clusterID
6464
return err
6565
}
6666

67-
res, err := c.Post(ctx, filepath.Join("/api/v1/org", orgID, "datareadings", clusterID), bytes.NewBuffer(data))
67+
res, err := c.post(ctx, filepath.Join("/api/v1/org", orgID, "datareadings", clusterID), bytes.NewBuffer(data))
6868
if err != nil {
6969
return err
7070
}
@@ -84,7 +84,7 @@ func (c *APITokenClient) PostDataReadings(ctx context.Context, orgID, clusterID
8484
}
8585

8686
// Post performs an HTTP POST request.
87-
func (c *APITokenClient) Post(ctx context.Context, path string, body io.Reader) (*http.Response, error) {
87+
func (c *APITokenClient) post(ctx context.Context, path string, body io.Reader) (*http.Response, error) {
8888
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL(c.baseURL, path), body)
8989
if err != nil {
9090
return nil, err

pkg/client/client_oauth.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,12 @@ func NewOAuthClient(agentMetadata *api.AgentMetadata, credentials *OAuthCredenti
104104
}
105105

106106
func (c *OAuthClient) PostDataReadingsWithOptions(ctx context.Context, readings []*api.DataReading, opts Options) error {
107-
return c.PostDataReadings(ctx, opts.OrgID, opts.ClusterID, readings)
107+
return c.postDataReadings(ctx, opts.OrgID, opts.ClusterID, readings)
108108
}
109109

110110
// PostDataReadings uploads the slice of api.DataReading to the Jetstack Secure backend to be processed for later
111111
// viewing in the user-interface.
112-
func (c *OAuthClient) PostDataReadings(ctx context.Context, orgID, clusterID string, readings []*api.DataReading) error {
112+
func (c *OAuthClient) postDataReadings(ctx context.Context, orgID, clusterID string, readings []*api.DataReading) error {
113113
payload := api.DataReadingsPost{
114114
AgentMetadata: c.agentMetadata,
115115
DataGatherTime: time.Now().UTC(),
@@ -120,7 +120,7 @@ func (c *OAuthClient) PostDataReadings(ctx context.Context, orgID, clusterID str
120120
return err
121121
}
122122

123-
res, err := c.Post(ctx, filepath.Join("/api/v1/org", orgID, "datareadings", clusterID), bytes.NewBuffer(data))
123+
res, err := c.post(ctx, filepath.Join("/api/v1/org", orgID, "datareadings", clusterID), bytes.NewBuffer(data))
124124
if err != nil {
125125
return err
126126
}
@@ -140,7 +140,7 @@ func (c *OAuthClient) PostDataReadings(ctx context.Context, orgID, clusterID str
140140
}
141141

142142
// Post performs an HTTP POST request.
143-
func (c *OAuthClient) Post(ctx context.Context, path string, body io.Reader) (*http.Response, error) {
143+
func (c *OAuthClient) post(ctx context.Context, path string, body io.Reader) (*http.Response, error) {
144144
token, err := c.getValidAccessToken(ctx)
145145
if err != nil {
146146
return nil, err

pkg/client/client_venafi_cloud.go

Lines changed: 2 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -205,43 +205,7 @@ func (c *VenafiCloudClient) PostDataReadingsWithOptions(ctx context.Context, rea
205205
}
206206
venafiCloudUploadURL.RawQuery = query.Encode()
207207

208-
res, err := c.Post(ctx, venafiCloudUploadURL.String(), bytes.NewBuffer(data))
209-
if err != nil {
210-
return err
211-
}
212-
defer res.Body.Close()
213-
214-
if code := res.StatusCode; code < 200 || code >= 300 {
215-
errorContent := ""
216-
body, err := io.ReadAll(res.Body)
217-
if err == nil {
218-
errorContent = string(body)
219-
}
220-
return fmt.Errorf("received response with status code %d. Body: [%s]", code, errorContent)
221-
}
222-
223-
return nil
224-
}
225-
226-
// PostDataReadings uploads the slice of api.DataReading to the Venafi Cloud backend to be processed for later
227-
// viewing in the user-interface.
228-
func (c *VenafiCloudClient) PostDataReadings(ctx context.Context, _ string, _ string, readings []*api.DataReading) error {
229-
// orgID and clusterID are ignored in Venafi Cloud auth
230-
231-
payload := api.DataReadingsPost{
232-
AgentMetadata: c.agentMetadata,
233-
DataGatherTime: time.Now().UTC(),
234-
DataReadings: readings,
235-
}
236-
data, err := json.Marshal(payload)
237-
if err != nil {
238-
return err
239-
}
240-
241-
if !strings.HasSuffix(c.uploadPath, "/") {
242-
c.uploadPath = fmt.Sprintf("%s/", c.uploadPath)
243-
}
244-
res, err := c.Post(ctx, filepath.Join(c.uploadPath, c.uploaderID), bytes.NewBuffer(data))
208+
res, err := c.post(ctx, venafiCloudUploadURL.String(), bytes.NewBuffer(data))
245209
if err != nil {
246210
return err
247211
}
@@ -260,7 +224,7 @@ func (c *VenafiCloudClient) PostDataReadings(ctx context.Context, _ string, _ st
260224
}
261225

262226
// Post performs an HTTP POST request.
263-
func (c *VenafiCloudClient) Post(ctx context.Context, path string, body io.Reader) (*http.Response, error) {
227+
func (c *VenafiCloudClient) post(ctx context.Context, path string, body io.Reader) (*http.Response, error) {
264228
token, err := c.getValidAccessToken(ctx)
265229
if err != nil {
266230
return nil, err

pkg/client/client_venconn.go

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -196,18 +196,3 @@ func (c *VenConnClient) PostDataReadingsWithOptions(ctx context.Context, reading
196196

197197
return nil
198198
}
199-
200-
// PostDataReadings isn't implemented for Venafi Cloud. This is because Venafi
201-
// Cloud needs a `clusterName` and `clusterDescription`, but this function can
202-
// only pass `orgID` and `clusterID` which are both useless in Venafi Cloud. Use
203-
// PostDataReadingsWithOptions instead.
204-
func (c *VenConnClient) PostDataReadings(_ context.Context, _orgID, _clusterID string, readings []*api.DataReading) error {
205-
return fmt.Errorf("programmer mistake: PostDataReadings is not implemented for Venafi Cloud")
206-
}
207-
208-
// Post isn't implemented for Venafi Cloud because /v1/tlspk/upload/clusterdata
209-
// requires using the query parameters `name` and `description` which can't be
210-
// set using Post. Use PostDataReadingsWithOptions instead.
211-
func (c *VenConnClient) Post(_ context.Context, path string, body io.Reader) (*http.Response, error) {
212-
return nil, fmt.Errorf("programmer mistake: Post is not implemented for Venafi Cloud")
213-
}

pkg/internal/cyberark/identity/mock.go

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -197,25 +197,10 @@ func (mis *mockIdentityServer) handleAdvanceAuthentication(w http.ResponseWriter
197197
return
198198
}
199199

200-
if advanceBody.SessionID != successSessionID {
201-
w.WriteHeader(http.StatusOK)
202-
_, _ = w.Write([]byte(advanceAuthenticationFailureResponse))
203-
return
204-
}
205-
206-
if advanceBody.MechanismID != successMechanismID {
207-
w.WriteHeader(http.StatusOK)
208-
_, _ = w.Write([]byte(advanceAuthenticationFailureResponse))
209-
return
210-
}
211-
212-
if advanceBody.Action != ActionAnswer {
213-
w.WriteHeader(http.StatusOK)
214-
_, _ = w.Write([]byte(advanceAuthenticationFailureResponse))
215-
return
216-
}
217-
218-
if advanceBody.Answer != successPassword {
200+
if advanceBody.SessionID != successSessionID ||
201+
advanceBody.MechanismID != successMechanismID ||
202+
advanceBody.Action != ActionAnswer ||
203+
advanceBody.Answer != successPassword {
219204
w.WriteHeader(http.StatusOK)
220205
_, _ = w.Write([]byte(advanceAuthenticationFailureResponse))
221206
return

0 commit comments

Comments
 (0)