forked from kiali/kiali
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_factory_test.go
497 lines (400 loc) · 15.2 KB
/
client_factory_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package kubernetes
import (
"context"
_ "embed"
"encoding/base64"
"fmt"
"math/rand"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd/api"
"github.com/kiali/kiali/config"
)
var (
//go:embed testdata/remote-cluster-exec.yaml
remoteClusterExecYAML string
//go:embed testdata/remote-cluster.yaml
remoteClusterYAML string
//go:embed testdata/proxy-ca.pem
proxyCAData []byte
)
// TestClientExpiration Verify the details that clients expire are correct
func TestClientExpiration(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
conf := config.Get()
conf.Auth.Strategy = config.AuthStrategyOpenId
conf.Auth.OpenId.DisableRBAC = false
SetConfig(t, *conf)
clientFactory := NewTestingClientFactory(t)
// Make sure we are starting off with an empty set of clients
assert.Equal(0, clientFactory.getClientsLength())
// Create a single initial test clients
authInfo := api.NewAuthInfo()
authInfo.Token = "foo-token"
_, err := clientFactory.getRecycleClient(authInfo, 100*time.Millisecond, conf.KubernetesConfig.ClusterName)
require.NoError(err)
// Verify we have the client
assert.Equal(1, clientFactory.getClientsLength())
_, found := clientFactory.hasClient(authInfo)
assert.True(found)
// Sleep for a bit and add another client
time.Sleep(time.Millisecond * 60)
authInfo1 := api.NewAuthInfo()
authInfo1.Token = "bar-token"
_, err = clientFactory.getRecycleClient(authInfo1, 100*time.Millisecond, conf.KubernetesConfig.ClusterName)
require.NoError(err)
// Verify we have both the foo and bar clients
assert.Equal(2, clientFactory.getClientsLength())
_, found = clientFactory.hasClient(authInfo)
assert.True(found)
_, found = clientFactory.hasClient(authInfo1)
assert.True(found)
// Wait for foo to be expired
time.Sleep(time.Millisecond * 60)
// Verify the client has been removed
assert.Equal(1, clientFactory.getClientsLength())
_, found = clientFactory.hasClient(authInfo)
assert.False(found)
_, found = clientFactory.hasClient(authInfo1)
assert.True(found)
// Wait for bar to be expired
time.Sleep(time.Millisecond * 60)
assert.Equal(0, clientFactory.getClientsLength())
}
// TestConcurrentClientExpiration Verify Concurrent clients are expired correctly
func TestConcurrentClientExpiration(t *testing.T) {
assert := assert.New(t)
clientFactory := NewTestingClientFactory(t)
count := 100
wg := sync.WaitGroup{}
wg.Add(count)
for i := 0; i < count; i++ {
go func() {
defer wg.Done()
authInfo := api.NewAuthInfo()
authInfo.Token = fmt.Sprintf("%d", rand.Intn(10000000000))
_, innerErr := clientFactory.getRecycleClient(authInfo, 10*time.Millisecond, config.Get().KubernetesConfig.ClusterName)
assert.NoError(innerErr)
}()
}
wg.Wait()
time.Sleep(3 * time.Second)
assert.Equal(0, clientFactory.getClientsLength())
}
// TestConcurrentClientFactory test Concurrently create ClientFactory
func TestConcurrentClientFactory(t *testing.T) {
require := require.New(t)
istioConfig := rest.Config{}
count := 100
wg := sync.WaitGroup{}
wg.Add(count)
setGlobalKialiSAToken(t, "test-token")
for i := 0; i < count; i++ {
go func() {
defer wg.Done()
_, err := newClientFactory(&istioConfig)
require.NoError(err)
}()
}
wg.Wait()
}
func TestClientCreatedWithClusterInfo(t *testing.T) {
// Create a fake cluster info file.
// Ensure client gets created with this.
// Need to test newClient and newSAClient
// Need to test that home cluster gets this info as well
require := require.New(t)
assert := assert.New(t)
conf := config.NewConfig()
config.Set(conf)
const testClusterName = "TestRemoteCluster"
createTestRemoteClusterSecret(t, testClusterName, remoteClusterYAML)
clientFactory := NewTestingClientFactory(t)
// Service account clients
saClients := clientFactory.GetSAClients()
require.Contains(saClients, testClusterName)
require.Contains(saClients, conf.KubernetesConfig.ClusterName)
assert.Equal(testClusterName, saClients[testClusterName].ClusterInfo().Name)
assert.Equal("https://192.168.1.2:1234", saClients[testClusterName].ClusterInfo().ClientConfig.Host)
assert.Contains(saClients[conf.KubernetesConfig.ClusterName].ClusterInfo().Name, conf.KubernetesConfig.ClusterName)
// User clients
userClients, err := clientFactory.GetClients(api.NewAuthInfo())
require.NoError(err)
require.Contains(userClients, testClusterName)
require.Contains(userClients, conf.KubernetesConfig.ClusterName)
assert.Equal(testClusterName, userClients[testClusterName].ClusterInfo().Name)
assert.Equal("https://192.168.1.2:1234", userClients[testClusterName].ClusterInfo().ClientConfig.Host)
assert.Contains(userClients[conf.KubernetesConfig.ClusterName].ClusterInfo().Name, conf.KubernetesConfig.ClusterName)
}
func TestClientCreatedWithAuthStrategyAnonymous(t *testing.T) {
// Create a fake cluster info file.
// Ensure client gets created with this.
// For AuthStrategyAnonymous ensure newClient for remote cluster has token from remote config.
require := require.New(t)
assert := assert.New(t)
conf := config.NewConfig()
conf.Auth.Strategy = config.AuthStrategyAnonymous
config.Set(conf)
const testClusterName = "TestRemoteCluster"
const testUserToken = "TestUserToken"
createTestRemoteClusterSecret(t, testClusterName, remoteClusterYAML)
clientFactory := NewTestingClientFactory(t)
// Create a single initial test clients
authInfo := api.NewAuthInfo()
authInfo.Token = testUserToken
// User clients
userClients, err := clientFactory.GetClients(authInfo)
require.NoError(err)
require.Contains(userClients, testClusterName)
assert.Equal(testClusterName, userClients[testClusterName].ClusterInfo().Name)
assert.Equal(userClients[testClusterName].GetToken(), "token")
assert.NotEqual(userClients[testClusterName].GetToken(), testUserToken)
}
func TestClientCreatedWithAuthStrategyOpenIdAndDisableRBAC(t *testing.T) {
// Create a fake cluster info file.
// Ensure client gets created with this.
// For AuthStrategyOpenId and DisableRBAC ensure newClient for remote cluster has token from remote config.
require := require.New(t)
assert := assert.New(t)
conf := config.NewConfig()
conf.Auth.Strategy = config.AuthStrategyOpenId
conf.Auth.OpenId.DisableRBAC = true
config.Set(conf)
const testClusterName = "TestRemoteCluster"
const testUserToken = "TestUserToken"
createTestRemoteClusterSecret(t, testClusterName, remoteClusterYAML)
clientFactory := NewTestingClientFactory(t)
// Create a single initial test clients
authInfo := api.NewAuthInfo()
authInfo.Token = testUserToken
// User clients
userClients, err := clientFactory.GetClients(authInfo)
require.NoError(err)
require.Contains(userClients, testClusterName)
assert.Equal(userClients[testClusterName].GetToken(), "token")
assert.NotEqual(userClients[testClusterName].GetToken(), testUserToken)
}
func TestClientCreatedWithAuthStrategyOpenIdAndDisableRBACFalse(t *testing.T) {
// Create a fake cluster info file.
// Ensure client gets created with this.
// For AuthStrategyOpenId and DisableRBAC is off ensure newClient for remote cluster has user token.
require := require.New(t)
assert := assert.New(t)
conf := config.NewConfig()
conf.Auth.Strategy = config.AuthStrategyOpenId
conf.Auth.OpenId.DisableRBAC = false
config.Set(conf)
const testClusterName = "TestRemoteCluster"
const testUserToken = "TestUserToken"
createTestRemoteClusterSecret(t, testClusterName, remoteClusterYAML)
clientFactory := NewTestingClientFactory(t)
// Create a single initial test clients
authInfo := api.NewAuthInfo()
authInfo.Token = testUserToken
// User clients
userClients, err := clientFactory.GetClients(authInfo)
require.NoError(err)
require.Contains(userClients, testClusterName)
assert.Equal(testClusterName, userClients[testClusterName].ClusterInfo().Name)
assert.Equal(userClients[testClusterName].GetToken(), testUserToken)
assert.NotEqual(userClients[testClusterName].GetToken(), "token")
}
func TestSAClientCreatedWithExecProvider(t *testing.T) {
// by default, ExecProvider support should be disabled
cases := map[string]struct {
remoteSecretContents string
expected rest.Config
}{
"Only bearer token": {
remoteSecretContents: remoteClusterYAML,
expected: rest.Config{
BearerToken: "token",
ExecProvider: nil,
},
},
"Use bearer token and exec credentials (which should be ignored)": {
remoteSecretContents: remoteClusterExecYAML,
expected: rest.Config{
BearerToken: "token",
ExecProvider: nil,
},
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
require := require.New(t)
const clusterName = "TestRemoteCluster"
originalSecretsDir := RemoteClusterSecretsDir
t.Cleanup(func() {
RemoteClusterSecretsDir = originalSecretsDir
})
RemoteClusterSecretsDir = t.TempDir()
createTestRemoteClusterSecretFile(t, RemoteClusterSecretsDir, clusterName, tc.remoteSecretContents)
cf := NewTestingClientFactory(t)
saClients := cf.GetSAClients()
// Should be home cluster client and one remote client
require.Equal(2, len(saClients))
require.Contains(saClients, clusterName)
clientConfig := saClients[clusterName].ClusterInfo().ClientConfig
require.Equal(tc.expected.BearerToken, clientConfig.BearerToken)
require.Nil(clientConfig.ExecProvider)
})
}
// now enable ExecProvider support
conf := config.NewConfig()
conf.KialiFeatureFlags.Clustering.EnableExecProvider = true
SetConfig(t, *conf)
cases = map[string]struct {
remoteSecretContents string
expected rest.Config
}{
"Only bearer token": {
remoteSecretContents: remoteClusterYAML,
expected: rest.Config{
BearerToken: "token",
ExecProvider: nil,
},
},
"Use bearer token and exec credentials": {
remoteSecretContents: remoteClusterExecYAML,
expected: rest.Config{
BearerToken: "token",
ExecProvider: &api.ExecConfig{
Command: "command",
Args: []string{"arg1", "arg2"},
},
},
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
require := require.New(t)
const clusterName = "TestRemoteCluster"
originalSecretsDir := RemoteClusterSecretsDir
t.Cleanup(func() {
RemoteClusterSecretsDir = originalSecretsDir
})
RemoteClusterSecretsDir = t.TempDir()
createTestRemoteClusterSecretFile(t, RemoteClusterSecretsDir, clusterName, tc.remoteSecretContents)
cf := NewTestingClientFactory(t)
saClients := cf.GetSAClients()
// Should be home cluster client and one remote client
require.Equal(2, len(saClients))
require.Contains(saClients, clusterName)
clientConfig := saClients[clusterName].ClusterInfo().ClientConfig
require.Equal(tc.expected.BearerToken, clientConfig.BearerToken)
if tc.expected.ExecProvider != nil {
// Just check a few fields for sanity
require.Equal(tc.expected.ExecProvider.Command, clientConfig.ExecProvider.Command)
require.Equal(tc.expected.ExecProvider.Args, clientConfig.ExecProvider.Args)
}
})
}
}
func setGlobalKialiSAToken(t *testing.T, newToken string) {
t.Helper()
originalToken := KialiTokenForHomeCluster
t.Cleanup(func() {
KialiTokenForHomeCluster = originalToken
tokenRead = time.Time{}
})
KialiTokenForHomeCluster = newToken
tokenRead = time.Now()
}
func TestClientCreatedWithProxyInfo(t *testing.T) {
require := require.New(t)
cfg := config.NewConfig()
cfg.Deployment.RemoteSecretPath = t.TempDir() // Random dir so that the remote secret isn't read if it exists.
cfg.Auth.Strategy = config.AuthStrategyOpenId
cfg.Auth.OpenId.ApiProxyCAData = base64.StdEncoding.EncodeToString(proxyCAData)
cfg.Auth.OpenId.ApiProxy = "https://api-proxy:8443"
SetConfig(t, *cfg)
clientFactory := NewTestingClientFactory(t)
// Regular clients should have the proxy info
client, err := clientFactory.GetClient(api.NewAuthInfo())
require.NoError(err)
require.Equal(cfg.Auth.OpenId.ApiProxy, client.ClusterInfo().ClientConfig.Host)
require.Equal(proxyCAData, client.ClusterInfo().ClientConfig.CAData)
// Service account clients should not have the proxy info.
// Two ways to get a SA client: 1. GetClient with SA token and 2. GetSAClient
setGlobalKialiSAToken(t, "current-token")
authInfo := api.NewAuthInfo()
authInfo.Token = KialiTokenForHomeCluster
client, err = clientFactory.GetClient(authInfo)
require.NoError(err)
require.NotEqual(cfg.Auth.OpenId.ApiProxy, client.ClusterInfo().ClientConfig.Host)
require.NotEqual(proxyCAData, client.ClusterInfo().ClientConfig.CAData)
client = clientFactory.GetSAClient(cfg.KubernetesConfig.ClusterName)
require.NotEqual(cfg.Auth.OpenId.ApiProxy, client.ClusterInfo().ClientConfig.Host)
require.NotEqual(proxyCAData, client.ClusterInfo().ClientConfig.CAData)
}
func TestNewClientFactoryClosesRecycleWhenCTXCancelled(t *testing.T) {
require := require.New(t)
// Create the remote secret so that the "in cluster" config is not used.
// Otherwise the "in cluster" config looks for some env vars that are not present.
const testClusterName = "TestRemoteCluster"
filename := createTestRemoteClusterSecret(t, testClusterName, remoteClusterYAML)
cfg := config.NewConfig()
cfg.Deployment.RemoteSecretPath = filename
SetConfig(t, *cfg)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
f, err := NewClientFactory(ctx, *cfg)
t.Cleanup(func() {
KialiTokenForHomeCluster = "" // Need to reset this global because other tests depend on it being empty.
})
require.NoError(err)
factory := f.(*clientFactory)
cancel()
select {
case <-time.After(200 * time.Millisecond):
require.Fail("recycleChan should have been closed")
case <-factory.recycleChan:
}
}
func TestNewClientFactoryDoesNotSetGlobalClientFactory(t *testing.T) {
require := require.New(t)
// Make sure global is nil before test begins
if factory != nil {
factory = nil
}
// Create the remote secret so that the "in cluster" config is not used.
// Otherwise the "in cluster" config looks for some env vars that are not present.
const testClusterName = "TestRemoteCluster"
filename := createTestRemoteClusterSecret(t, testClusterName, remoteClusterYAML)
cfg := config.NewConfig()
cfg.Deployment.RemoteSecretPath = filename
SetConfig(t, *cfg)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
_, err := NewClientFactory(ctx, *cfg)
t.Cleanup(func() {
KialiTokenForHomeCluster = "" // Need to reset this global because other tests depend on it being empty.
})
require.NoError(err)
require.Nil(factory)
}
func TestClientFactoryReturnsSAClientWhenConfigClusterNameIsEmpty(t *testing.T) {
require := require.New(t)
// Create the remote secret so that the "in cluster" config is not used.
// Otherwise the "in cluster" config looks for some env vars that are not present.
const testClusterName = "TestRemoteCluster"
filename := createTestRemoteClusterSecret(t, testClusterName, remoteClusterYAML)
cfg := config.NewConfig()
cfg.Deployment.RemoteSecretPath = filename
cfg.KubernetesConfig.ClusterName = ""
SetConfig(t, *cfg)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
clientFactory, err := NewClientFactory(ctx, *cfg)
t.Cleanup(func() {
KialiTokenForHomeCluster = "" // Need to reset this global because other tests depend on it being empty.
})
require.NoError(err)
require.NotNil(clientFactory.GetSAHomeClusterClient())
}