Skip to content

Commit 25eccd6

Browse files
CyberArk(servicediscovery): simplify client initialization and remove unused options
- Removed `WithHTTPClient` and `WithCustomEndpoint` options from the `servicediscovery.Client`. - Simplified `New` function to directly use `http.Client` and environment variable for base URL. - Updated tests to use `MockDiscoveryServer` with `testing.TB` for better integration. - Replaced hardcoded `ProdDiscoveryEndpoint` with `ProdDiscoveryAPIBaseURL` for consistency. - Adjusted dependent code to align with the new client initialization approach.
1 parent 0b4b1aa commit 25eccd6

File tree

5 files changed

+54
-84
lines changed

5 files changed

+54
-84
lines changed

pkg/internal/cyberark/dataupload/dataupload_test.go

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -144,10 +144,6 @@ func TestPostDataReadingsWithOptionsWithRealAPI(t *testing.T) {
144144
subdomain := os.Getenv("ARK_SUBDOMAIN")
145145
username := os.Getenv("ARK_USERNAME")
146146
secret := os.Getenv("ARK_SECRET")
147-
serviceDiscoveryAPI := os.Getenv("ARK_DISCOVERY_API")
148-
if serviceDiscoveryAPI == "" {
149-
serviceDiscoveryAPI = servicediscovery.ProdDiscoveryEndpoint
150-
}
151147

152148
if platformDomain == "" || subdomain == "" || username == "" || secret == "" {
153149
t.Skip("Skipping because one of the following environment variables is unset or empty: ARK_PLATFORM_DOMAIN, ARK_SUBDOMAIN, ARK_USERNAME, ARK_SECRET")
@@ -168,10 +164,7 @@ func TestPostDataReadingsWithOptionsWithRealAPI(t *testing.T) {
168164
httpClient := http_client.NewDefaultClient(version.UserAgent(), rootCAs)
169165
httpClient.Transport = transport.NewDebuggingRoundTripper(httpClient.Transport, transport.DebugByContext)
170166

171-
discoveryClient := servicediscovery.New(
172-
servicediscovery.WithHTTPClient(httpClient),
173-
servicediscovery.WithCustomEndpoint(serviceDiscoveryAPI),
174-
)
167+
discoveryClient := servicediscovery.New(httpClient)
175168

176169
identityAPI, err := discoveryClient.DiscoverIdentityAPIURL(ctx, subdomain)
177170
require.NoError(t, err)

pkg/internal/cyberark/identity/cmd/testidentity/main.go

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,9 @@ import (
2424
// To test against a tenant on the integration platform, set:
2525
// ARK_DISCOVERY_API=https://platform-discovery.integration-cyberark.cloud/api/v2
2626
const (
27-
subdomainFlag = "subdomain"
28-
usernameFlag = "username"
29-
passwordEnv = "ARK_SECRET"
30-
serviceDiscoveryAPIEnv = "ARK_DISCOVERY_API"
27+
subdomainFlag = "subdomain"
28+
usernameFlag = "username"
29+
passwordEnv = "ARK_SECRET"
3130
)
3231

3332
var (
@@ -49,19 +48,11 @@ func run(ctx context.Context) error {
4948
return fmt.Errorf("no password provided in %s", passwordEnv)
5049
}
5150

52-
serviceDiscoveryAPI := os.Getenv(serviceDiscoveryAPIEnv)
53-
if serviceDiscoveryAPI == "" {
54-
serviceDiscoveryAPI = servicediscovery.ProdDiscoveryEndpoint
55-
}
56-
5751
var rootCAs *x509.CertPool
5852
httpClient := http_client.NewDefaultClient(version.UserAgent(), rootCAs)
5953
httpClient.Transport = transport.NewDebuggingRoundTripper(httpClient.Transport, transport.DebugByContext)
6054

61-
sdClient := servicediscovery.New(
62-
servicediscovery.WithHTTPClient(httpClient),
63-
servicediscovery.WithCustomEndpoint(serviceDiscoveryAPI),
64-
)
55+
sdClient := servicediscovery.New(httpClient)
6556
identityAPI, err := sdClient.DiscoverIdentityAPIURL(ctx, subdomain)
6657
if err != nil {
6758
return fmt.Errorf("while performing service discovery: %s", err)

pkg/internal/cyberark/servicediscovery/discovery.go

Lines changed: 12 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,13 @@ import (
77
"io"
88
"net/http"
99
"net/url"
10-
"time"
11-
12-
"k8s.io/client-go/transport"
10+
"os"
1311

1412
"github.com/jetstack/preflight/pkg/version"
1513
)
1614

1715
const (
18-
ProdDiscoveryEndpoint = "https://platform-discovery.cyberark.cloud/api/v2/"
16+
ProdDiscoveryAPIBaseURL = "https://platform-discovery.cyberark.cloud/api/v2/"
1917

2018
// identityServiceName is the name of the identity service we're looking for in responses from the Service Discovery API
2119
// We were told to use the identity_administration field, not the identity_user_portal field.
@@ -30,40 +28,19 @@ const (
3028
// users to fetch URLs for various APIs available in CyberArk. This client is specialised to
3129
// fetch only API endpoints, since only API endpoints are required by the Venafi Kubernetes Agent currently.
3230
type Client struct {
33-
client *http.Client
34-
endpoint string
35-
}
36-
37-
// ClientOpt allows configuration of a Client when using New
38-
type ClientOpt func(*Client)
39-
40-
// WithHTTPClient allows the user to specify a custom HTTP client for the discovery client
41-
func WithHTTPClient(httpClient *http.Client) ClientOpt {
42-
return func(c *Client) {
43-
c.client = httpClient
44-
}
45-
}
46-
47-
// WithCustomEndpoint sets the endpoint to a custom URL without checking that the URL is a CyberArk Service Discovery
48-
// server.
49-
func WithCustomEndpoint(endpoint string) ClientOpt {
50-
return func(c *Client) {
51-
c.endpoint = endpoint
52-
}
31+
client *http.Client
32+
baseURL string
5333
}
5434

5535
// New creates a new CyberArk Service Discovery client, configurable with ClientOpt
56-
func New(clientOpts ...ClientOpt) *Client {
57-
client := &Client{
58-
client: &http.Client{
59-
Timeout: 10 * time.Second,
60-
Transport: transport.NewDebuggingRoundTripper(http.DefaultTransport, transport.DebugByContext),
61-
},
62-
endpoint: ProdDiscoveryEndpoint,
36+
func New(httpClient *http.Client) *Client {
37+
baseURL := os.Getenv("ARK_DISCOVERY_API")
38+
if baseURL == "" {
39+
baseURL = ProdDiscoveryAPIBaseURL
6340
}
64-
65-
for _, opt := range clientOpts {
66-
opt(client)
41+
client := &Client{
42+
client: httpClient,
43+
baseURL: baseURL,
6744
}
6845

6946
return client
@@ -72,7 +49,7 @@ func New(clientOpts ...ClientOpt) *Client {
7249
// DiscoverIdentityAPIURL fetches from the service discovery service for a given subdomain
7350
// and parses the CyberArk Identity API URL.
7451
func (c *Client) DiscoverIdentityAPIURL(ctx context.Context, subdomain string) (string, error) {
75-
endpoint, err := url.JoinPath(c.endpoint, "services", "subdomain", subdomain)
52+
endpoint, err := url.JoinPath(c.baseURL, "services", "subdomain", subdomain)
7653
if err != nil {
7754
return "", fmt.Errorf("failed to build a valid URL for subdomain %s; possibly an invalid endpoint: %s", subdomain, err)
7855
}

pkg/internal/cyberark/servicediscovery/discovery_test.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ package servicediscovery
33
import (
44
"fmt"
55
"testing"
6+
7+
"k8s.io/klog/v2"
8+
"k8s.io/klog/v2/ktesting"
9+
10+
_ "k8s.io/klog/v2/ktesting/init"
611
)
712

813
func Test_DiscoverIdentityAPIURL(t *testing.T) {
@@ -45,12 +50,12 @@ func Test_DiscoverIdentityAPIURL(t *testing.T) {
4550

4651
for name, testSpec := range tests {
4752
t.Run(name, func(t *testing.T) {
48-
ctx := t.Context()
53+
logger := ktesting.NewLogger(t, ktesting.DefaultConfig)
54+
ctx := klog.NewContext(t.Context(), logger)
4955

50-
ts := MockDiscoveryServer()
51-
defer ts.Close()
56+
httpClient := MockDiscoveryServer(t, mockIdentityAPIURL)
5257

53-
client := New(WithCustomEndpoint(ts.Server.URL))
58+
client := New(httpClient)
5459

5560
apiURL, err := client.DiscoverIdentityAPIURL(ctx, testSpec.subdomain)
5661
if err != nil {

pkg/internal/cyberark/servicediscovery/mock.go

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@ import (
88
"net/http"
99
"net/http/httptest"
1010
"strings"
11+
"testing"
1112
"text/template"
1213

14+
"k8s.io/client-go/transport"
15+
1316
"github.com/jetstack/preflight/pkg/version"
1417

1518
_ "embed"
@@ -19,50 +22,51 @@ const (
1922
// MockDiscoverySubdomain is the subdomain for which the MockDiscoveryServer will return a success response
2023
MockDiscoverySubdomain = "venafi-test"
2124

22-
defaultIdentityAPIURL = "https://ajp5871.id.integration-cyberark.cloud"
25+
mockIdentityAPIURL = "https://ajp5871.id.integration-cyberark.cloud"
2326
)
2427

2528
//go:embed testdata/discovery_success.json.template
2629
var discoverySuccessTemplate string
2730

2831
type mockDiscoveryServer struct {
29-
Server *httptest.Server
30-
32+
t testing.TB
3133
successResponse string
3234
}
3335

34-
// MockDiscoveryServer returns a mocked discovery server with a default value for the Identity API.
35-
// The returned server should be Closed by the caller after use.
36-
func MockDiscoveryServer() *mockDiscoveryServer {
37-
return MockDiscoveryServerWithCustomAPIURL(defaultIdentityAPIURL)
38-
}
39-
40-
func MockDiscoveryServerWithCustomAPIURL(apiURL string) *mockDiscoveryServer {
36+
// MockDiscoveryServer starts a mocked CyberArk service discovery server and an
37+
// HTTP client with the CA certs needed to connect to it.
38+
//
39+
// The URL of the mock server is set in the `ARK_DISCOVERY_API` environment
40+
// variable, so any code using the `servicediscovery.Client` will use this mock
41+
// server.
42+
//
43+
// The mock server will return a successful response when the subdomain is
44+
// `MockDiscoverySubdomain`, and the identity API URL in that response will be
45+
// `identityAPIURL`.
46+
// Other subdomains, can be used to trigger various failure responses.
47+
// The returned HTTP client has a transport which logs requests and responses
48+
// depending on log level of the logger supplied in the context.
49+
func MockDiscoveryServer(t testing.TB, identityAPIURL string) *http.Client {
4150
tmpl := template.Must(template.New("mockDiscoverySuccess").Parse(discoverySuccessTemplate))
42-
4351
buf := &bytes.Buffer{}
44-
45-
err := tmpl.Execute(buf, struct{ IdentityAPIURL string }{apiURL})
52+
err := tmpl.Execute(buf, struct{ IdentityAPIURL string }{identityAPIURL})
4653
if err != nil {
4754
panic(err)
4855
}
49-
5056
mds := &mockDiscoveryServer{
57+
t: t,
5158
successResponse: buf.String(),
5259
}
53-
54-
server := httptest.NewServer(mds)
55-
56-
mds.Server = server
57-
58-
return mds
59-
}
60-
61-
func (mds *mockDiscoveryServer) Close() {
62-
mds.Server.Close()
60+
server := httptest.NewTLSServer(mds)
61+
t.Cleanup(server.Close)
62+
t.Setenv("ARK_DISCOVERY_API", server.URL)
63+
httpClient := server.Client()
64+
httpClient.Transport = transport.NewDebuggingRoundTripper(httpClient.Transport, transport.DebugByContext)
65+
return httpClient
6366
}
6467

6568
func (mds *mockDiscoveryServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
69+
mds.t.Log(r.Method, r.RequestURI)
6670
if r.Method != http.MethodGet {
6771
// This was observed by making a POST request to the integration environment
6872
// Normally, we'd expect 405 Method Not Allowed but we match the observed response here

0 commit comments

Comments
 (0)