Skip to content

Commit f00b5fa

Browse files
committed
config_test: add a failing test to showcase that uploader_id missing
I found that, in venafi cloud key pair service account mode, the arbitrary path segment "/no" was now missing due to my refactoring. This commit adds a unit test to show this. Test result: --- FAIL: Test_ValidateAndCombineConfig_VenafiCloudKeyPair (0.00s) --- FAIL: Test_ValidateAndCombineConfig_VenafiCloudKeyPair/server,_uploader_id,_and_cluster_name_are_correctly_passed (0.00s) envtest.go:188: fake api.venafi.cloud received request: POST /v1/oauth/token/serviceaccount envtest.go:188: fake api.venafi.cloud received request: POST /v1/tlspk/upload/clusterdata config_test.go:586: Error: Not equal: expected: "/v1/tlspk/upload/clusterdata/no" actual : "/v1/tlspk/upload/clusterdata" Diff: --- Expected +++ Actual @@ -1 +1 @@ -/v1/tlspk/upload/clusterdata/no +/v1/tlspk/upload/clusterdata Test: Test_ValidateAndCombineConfig_VenafiCloudKeyPair/server,_uploader_id,_and_cluster_name_are_correctly_passed
1 parent 23f26bd commit f00b5fa

File tree

3 files changed

+74
-22
lines changed

3 files changed

+74
-22
lines changed

pkg/agent/config_test.go

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ func Test_ValidateAndCombineConfig(t *testing.T) {
8181
assert.Equal(t, testutil.Undent(`
8282
Using the Jetstack Secure OAuth auth mode since --credentials-file was specified without --venafi-cloud.
8383
Both the 'period' field and --period are set. Using the value provided with --period.
84-
8584
`), gotLogs.String())
8685
assert.Equal(t, 99*time.Minute, got.Period)
8786
})
@@ -572,9 +571,44 @@ func Test_ValidateAndCombineConfig(t *testing.T) {
572571
})
573572
}
574573

574+
func Test_ValidateAndCombineConfig_VenafiCloudKeyPair(t *testing.T) {
575+
t.Run("server, uploader_id, and cluster name are correctly passed", func(t *testing.T) {
576+
srv, cert, setVenafiCloudAssert := testutil.FakeVenafiCloud(t)
577+
setVenafiCloudAssert(func(t testing.TB, gotReq *http.Request) {
578+
// Only care about /v1/tlspk/upload/clusterdata/:uploader_id?name=
579+
if gotReq.URL.Path == "/v1/oauth/token/serviceaccount" {
580+
return
581+
}
582+
583+
assert.Equal(t, srv.URL, "https://"+gotReq.Host)
584+
assert.Equal(t, "test cluster name", gotReq.URL.Query().Get("name"))
585+
assert.Equal(t, "/v1/tlspk/upload/clusterdata/no", gotReq.URL.Path)
586+
})
587+
588+
privKeyPath := withFile(t, fakePrivKeyPEM)
589+
got, cl, err := ValidateAndCombineConfig(discardLogs(),
590+
withConfig(testutil.Undent(`
591+
server: `+srv.URL+`
592+
period: 1h
593+
cluster_id: "test cluster name"
594+
venafi-cloud:
595+
uploader_id: no
596+
upload_path: /v1/tlspk/upload/clusterdata
597+
`)),
598+
withCmdLineFlags("--client-id", "5bc7d07c-45da-11ef-a878-523f1e1d7de1", "--private-key-path", privKeyPath),
599+
)
600+
testutil.TrustCA(t, cl, cert)
601+
assert.Equal(t, VenafiCloudKeypair, got.AuthMode)
602+
require.NoError(t, err)
603+
604+
err = cl.PostDataReadingsWithOptions(nil, client.Options{ClusterName: "test cluster name"})
605+
require.NoError(t, err)
606+
})
607+
}
608+
575609
// Slower test cases due to envtest. That's why they are separated from the
576610
// other tests.
577-
func Test_ValidateAndCombineConfig_urlWhenVenafiConnection(t *testing.T) {
611+
func Test_ValidateAndCombineConfig_VenafiConnection(t *testing.T) {
578612
_, cfg, kcl := testutil.WithEnvtest(t)
579613
t.Setenv("KUBECONFIG", testutil.WithKubeconfig(t, cfg))
580614
srv, cert, setVenafiCloudAssert := testutil.FakeVenafiCloud(t)
@@ -588,7 +622,7 @@ func Test_ValidateAndCombineConfig_urlWhenVenafiConnection(t *testing.T) {
588622
namespace: venafi
589623
spec:
590624
vcp:
591-
url: "%s"
625+
url: "`+srv.URL+`"
592626
accessToken:
593627
- secret:
594628
name: accesstoken
@@ -626,7 +660,7 @@ func Test_ValidateAndCombineConfig_urlWhenVenafiConnection(t *testing.T) {
626660
- kind: ServiceAccount
627661
name: venafi-connection
628662
namespace: venafi
629-
`, srv.URL))) {
663+
`))) {
630664
require.NoError(t, kcl.Create(context.Background(), obj))
631665
}
632666

@@ -654,7 +688,7 @@ func Test_ValidateAndCombineConfig_urlWhenVenafiConnection(t *testing.T) {
654688
require.NoError(t, err)
655689

656690
testutil.VenConnStartWatching(t, cl)
657-
testutil.VenConnTrustCA(t, cl, cert)
691+
testutil.TrustCA(t, cl, cert)
658692

659693
// TODO(mael): the client should keep track of the cluster ID, we
660694
// shouldn't need to pass it as an option to

pkg/client/client_venafi_cloud.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,15 @@ type (
4343
accessToken *venafiCloudAccessToken
4444
baseURL string
4545
agentMetadata *api.AgentMetadata
46-
client *http.Client
4746

4847
uploaderID string
4948
uploadPath string
5049
privateKey crypto.PrivateKey
5150
jwtSigningAlg jwt.SigningMethod
5251
lock sync.RWMutex
52+
53+
// Made public for testing purposes.
54+
Client *http.Client
5355
}
5456

5557
VenafiSvcAccountCredentials struct {
@@ -109,7 +111,7 @@ func NewVenafiCloudClient(agentMetadata *api.AgentMetadata, credentials *VenafiS
109111
credentials: credentials,
110112
baseURL: baseURL,
111113
accessToken: &venafiCloudAccessToken{},
112-
client: &http.Client{Timeout: time.Minute},
114+
Client: &http.Client{Timeout: time.Minute},
113115
uploaderID: uploaderID,
114116
uploadPath: uploadPath,
115117
privateKey: privateKey,
@@ -270,7 +272,7 @@ func (c *VenafiCloudClient) Post(path string, body io.Reader) (*http.Response, e
270272
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.accessToken))
271273
}
272274

273-
return c.client.Do(req)
275+
return c.Client.Do(req)
274276
}
275277

276278
// getValidAccessToken returns a valid access token. It will fetch a new access
@@ -325,7 +327,7 @@ func (c *VenafiCloudClient) updateAccessToken() error {
325327
}
326328

327329
func (c *VenafiCloudClient) sendHTTPRequest(request *http.Request, responseObject interface{}) error {
328-
response, err := c.client.Do(request)
330+
response, err := c.Client.Do(request)
329331
if err != nil {
330332
return err
331333
}

pkg/testutil/envtest.go

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import (
1212
"sync"
1313
"testing"
1414

15-
"github.com/jetstack/preflight/pkg/client"
1615
"github.com/jetstack/venafi-connection-lib/api/v1alpha1"
1716
"github.com/stretchr/testify/require"
1817
corev1 "k8s.io/api/core/v1"
@@ -25,6 +24,8 @@ import (
2524
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
2625
ctrlruntime "sigs.k8s.io/controller-runtime/pkg/client"
2726
"sigs.k8s.io/controller-runtime/pkg/envtest"
27+
28+
"github.com/jetstack/preflight/pkg/client"
2829
)
2930

3031
// To see the API server logs, set:
@@ -123,21 +124,31 @@ func VenConnStartWatching(t *testing.T, cl client.Client) {
123124
t.Cleanup(cancel)
124125
}
125126

126-
func VenConnTrustCA(t *testing.T, cl client.Client, cert *x509.Certificate) {
127+
// Works with VenafiCloudClient and VenConnClient. Allows you to trust a given
128+
// CA.
129+
func TrustCA(t *testing.T, cl client.Client, cert *x509.Certificate) {
127130
t.Helper()
128-
require.IsType(t, &client.VenConnClient{}, cl)
129-
vcCl := cl.(*client.VenConnClient)
131+
132+
var httpClient *http.Client
133+
switch c := cl.(type) {
134+
case *client.VenafiCloudClient:
135+
httpClient = c.Client
136+
case *client.VenConnClient:
137+
httpClient = c.Client
138+
default:
139+
t.Fatalf("unsupported client type: %T", cl)
140+
}
130141

131142
pool := x509.NewCertPool()
132143
pool.AddCert(cert)
133144

134-
if vcCl.Client.Transport == nil {
135-
vcCl.Client.Transport = http.DefaultTransport
145+
if httpClient.Transport == nil {
146+
httpClient.Transport = http.DefaultTransport
136147
}
137-
if vcCl.Client.Transport.(*http.Transport).TLSClientConfig == nil {
138-
vcCl.Client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{}
148+
if httpClient.Transport.(*http.Transport).TLSClientConfig == nil {
149+
httpClient.Transport.(*http.Transport).TLSClientConfig = &tls.Config{}
139150
}
140-
vcCl.Client.Transport.(*http.Transport).TLSClientConfig.RootCAs = pool
151+
httpClient.Transport.(*http.Transport).TLSClientConfig.RootCAs = pool
141152
}
142153

143154
// Parses the YAML manifest. Useful for inlining YAML manifests in Go test
@@ -180,10 +191,19 @@ func FakeVenafiCloud(t *testing.T) (_ *httptest.Server, _ *x509.Certificate, set
180191
defer assertFnMu.Unlock()
181192
assertFn(t, r)
182193

194+
if r.URL.Path == "/v1/oauth2/v2.0/756db001-280e-11ee-84fb-991f3177e2d0/token" {
195+
_, _ = w.Write([]byte(`{"access_token":"VALID_ACCESS_TOKEN","expires_in":900,"token_type":"bearer"}`))
196+
return
197+
} else if r.URL.Path == "/v1/oauth/token/serviceaccount" {
198+
_, _ = w.Write([]byte(`{"access_token":"VALID_ACCESS_TOKEN","expires_in":900,"token_type":"bearer"}`))
199+
return
200+
}
201+
183202
accessToken := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
184203
apiKey := r.Header.Get("tppl-api-key")
185204
if accessToken != "VALID_ACCESS_TOKEN" && apiKey != "VALID_API_KEY" {
186205
w.WriteHeader(http.StatusUnauthorized)
206+
w.Write([]byte(`{"error":"expected header 'Authorization: Bearer VALID_ACCESS_TOKEN' or 'tppl-api-key: VALID_API_KEY', but got Authorization=` + r.Header.Get("Authorization") + ` and tppl-api-key=` + r.Header.Get("tppl-api-key")))
187207
return
188208
}
189209
if r.URL.Path == "/v1/tlspk/upload/clusterdata/no" {
@@ -194,11 +214,7 @@ func FakeVenafiCloud(t *testing.T) (_ *httptest.Server, _ *x509.Certificate, set
194214
}
195215
_, _ = w.Write([]byte(`{"status":"ok","organization":"756db001-280e-11ee-84fb-991f3177e2d0"}`))
196216
} else if r.URL.Path == "/v1/useraccounts" {
197-
w.WriteHeader(http.StatusOK)
198217
_, _ = w.Write([]byte(`{"user": {"username": "user","id": "76a126f0-280e-11ee-84fb-991f3177e2d0"}}`))
199-
200-
} else if r.URL.Path == "/v1/oauth2/v2.0/756db001-280e-11ee-84fb-991f3177e2d0/token" {
201-
_, _ = w.Write([]byte(`{"access_token":"VALID_ACCESS_TOKEN","expires_in":900,"token_type":"bearer"}`))
202218
} else {
203219
w.WriteHeader(http.StatusInternalServerError)
204220
_, _ = w.Write([]byte(`{"error":"unexpected path in the test server","path":"` + r.URL.Path + `"}`))

0 commit comments

Comments
 (0)