-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathlogin_test.go
More file actions
762 lines (603 loc) · 32 KB
/
login_test.go
File metadata and controls
762 lines (603 loc) · 32 KB
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
package login
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
"github.com/trivago/tgo/tcontainer"
"go.uber.org/mock/gomock"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
"github.com/andygrunwald/go-jira"
BackplaneApi "github.com/openshift/backplane-api/pkg/client"
"github.com/openshift/backplane-cli/pkg/backplaneapi"
backplaneapiMock "github.com/openshift/backplane-cli/pkg/backplaneapi/mocks"
"github.com/openshift/backplane-cli/pkg/cli/config"
"github.com/openshift/backplane-cli/pkg/client/mocks"
jiraClient "github.com/openshift/backplane-cli/pkg/jira"
jiraMock "github.com/openshift/backplane-cli/pkg/jira/mocks"
"github.com/openshift/backplane-cli/pkg/login"
"github.com/openshift/backplane-cli/pkg/ocm"
ocmMock "github.com/openshift/backplane-cli/pkg/ocm/mocks"
"github.com/openshift/backplane-cli/pkg/utils"
)
func MakeIoReader(s string) io.ReadCloser {
r := io.NopCloser(strings.NewReader(s)) // r type is io.ReadCloser
return r
}
var _ = Describe("Login command", func() {
var (
mockCtrl *gomock.Controller
mockClient *mocks.MockClientInterface
mockClientWithResp *mocks.MockClientWithResponsesInterface
mockOcmInterface *ocmMock.MockOCMInterface
mockClientUtil *backplaneapiMock.MockClientUtils
mockIssueService *jiraMock.MockIssueServiceInterface
testClusterID string
testToken string
trueClusterID string
managingClusterID string
backplaneAPIURI string
serviceClusterID string
serviceClusterName string
fakeResp *http.Response
ocmEnv *cmv1.Environment
kubeConfigPath string
mockCluster *cmv1.Cluster
backplaneConfiguration config.BackplaneConfiguration
falsePagerDutyAPITkn string
truePagerDutyAPITkn string
falsePagerDutyIncidentID string
truePagerDutyIncidentID string
bpConfigPath string
)
BeforeEach(func() {
mockCtrl = gomock.NewController(GinkgoT())
mockClient = mocks.NewMockClientInterface(mockCtrl)
mockClientWithResp = mocks.NewMockClientWithResponsesInterface(mockCtrl)
mockOcmInterface = ocmMock.NewMockOCMInterface(mockCtrl)
ocm.DefaultOCMInterface = mockOcmInterface
mockClientUtil = backplaneapiMock.NewMockClientUtils(mockCtrl)
backplaneapi.DefaultClientUtils = mockClientUtil
testClusterID = "test123"
testToken = "hello123"
trueClusterID = "trueID123"
managingClusterID = "managingID123"
serviceClusterID = "hs-sc-123456"
serviceClusterName = "hs-sc-654321"
backplaneAPIURI = "https://shard.apps"
kubeConfigPath = "filepath"
falsePagerDutyAPITkn = "token123"
// nolint:gosec truePagerDutyAPIToken refers to the Test API Token provided by https://developer.pagerduty.com/api-reference
truePagerDutyAPITkn = "y_NbAkKc66ryYTWUXYEu"
falsePagerDutyIncidentID = "incident123"
truePagerDutyIncidentID = "Q0ZNH7TDQBOO54"
mockClientWithResp.EXPECT().LoginClusterWithResponse(gomock.Any(), gomock.Any()).Return(nil, nil).Times(0)
fakeResp = &http.Response{
Body: MakeIoReader(`{"proxy_uri":"proxy", "statusCode":200, "message":"msg"}`),
Header: map[string][]string{},
StatusCode: http.StatusOK,
}
fakeResp.Header.Add("Content-Type", "json")
// Clear config file
_ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true)
clientcmd.UseModifyConfigLock = false
globalOpts.BackplaneURL = backplaneAPIURI
ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build()
mockCluster = &cmv1.Cluster{}
backplaneConfiguration = config.BackplaneConfiguration{URL: backplaneAPIURI}
loginType = LoginTypeClusterID
})
AfterEach(func() {
globalOpts.Manager = false
globalOpts.Service = false
globalOpts.BackplaneURL = ""
globalOpts.ProxyURL = ""
args.readwrite = false
_ = os.Setenv("HTTPS_PROXY", "")
_ = os.Unsetenv("BACKPLANE_CONFIG")
_ = os.Remove(bpConfigPath)
mockCtrl.Finish()
utils.RemoveTempKubeConfig()
})
Context("check ocm token", func() {
It("Should fail when failed to get OCM token", func() {
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(nil, errors.New("err")).AnyTimes()
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
err := runLogin(nil, []string{testClusterID})
Expect(err).ToNot(BeNil())
})
It("should save ocm token to kube config", func() {
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
globalOpts.ProxyURL = "https://squid.myproxy.com"
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil)
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, nil)
err = runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
cfg, err := utils.ReadKubeconfigRaw()
Expect(err).To(BeNil())
Expect(cfg.AuthInfos["anonymous"].Token).To(Equal(testToken))
})
})
Context("check BP-api and proxy connection", func() {
It("should use the specified backplane url if passed", func() {
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
globalOpts.BackplaneURL = "https://sadge.app"
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken("https://sadge.app", testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, nil)
err = runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
cfg, err := utils.ReadKubeconfigRaw()
Expect(err).To(BeNil())
Expect(cfg.CurrentContext).To(Equal("default/test123/anonymous"))
Expect(len(cfg.Contexts)).To(Equal(1))
Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterID))
Expect(cfg.Contexts["default/test123/anonymous"].Namespace).To(Equal("default"))
})
It("should use the specified proxy url if passed", func() {
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
globalOpts.ProxyURL = "https://squid.myproxy.com"
_ = os.Setenv("HTTPS_PROXY", "https://squid.myproxy.com")
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil)
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, nil)
err = runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
cfg, err := utils.ReadKubeconfigRaw()
Expect(err).To(BeNil())
Expect(cfg.CurrentContext).To(Equal("default/test123/anonymous"))
Expect(len(cfg.Contexts)).To(Equal(1))
Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterID))
Expect(cfg.Clusters[testClusterID].ProxyURL).To(Equal(globalOpts.ProxyURL))
Expect(cfg.Contexts["default/test123/anonymous"].Namespace).To(Equal("default"))
})
It("should fail if unable to create api client", func() {
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(nil, errors.New("err"))
err := runLogin(nil, []string{testClusterID})
Expect(err).ToNot(BeNil())
})
It("should fail if ocm env backplane url is empty", func() {
ocmEnv, _ = cmv1.NewEnvironment().Build()
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
err := runLogin(nil, []string{testClusterID})
Expect(err).ToNot(BeNil())
})
})
Context("check cluster login", func() {
BeforeEach(func() {
globalOpts.Manager = false
globalOpts.Service = false
args.clusterInfo = false
})
It("when display cluster info is set to true", func() {
err := utils.CreateTempKubeConfig(nil)
args.defaultNamespace = "default"
args.clusterInfo = true
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, nil)
mockOcmInterface.EXPECT().GetClusterInfoByID(gomock.Any()).Return(mockCluster, nil).Times(2)
mockOcmInterface.EXPECT().SetupOCMConnection().Return(nil, nil)
mockOcmInterface.EXPECT().IsClusterAccessProtectionEnabled(gomock.Any(), trueClusterID).Return(false, nil)
err = runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
})
It("should fail to print cluster info when is set to true and PrintClusterInfo returns an error", func() {
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
args.defaultNamespace = "default"
args.clusterInfo = true
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes()
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil).AnyTimes()
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, nil).AnyTimes()
// Mock PrintClusterInfo to return an error
mockOcmInterface.EXPECT().GetClusterInfoByID(gomock.Any()).Return(nil, errors.New("mock error"))
err = runLogin(nil, []string{testClusterID})
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to print cluster info"))
})
It("when running with a simple case should work as expected", func() {
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, nil)
err = runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
cfg, err := utils.ReadKubeconfigRaw()
Expect(err).To(BeNil())
Expect(cfg.CurrentContext).To(Equal("default/test123/anonymous"))
Expect(len(cfg.Contexts)).To(Equal(1))
Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterID))
Expect(cfg.Contexts["default/test123/anonymous"].Namespace).To(Equal("default"))
})
It("when the namespace of the context is passed as an argument", func() {
err := utils.CreateTempKubeConfig(nil)
args.defaultNamespace = "default"
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, nil)
err = runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
cfg, err := utils.ReadKubeconfigRaw()
Expect(err).To(BeNil())
Expect(cfg.CurrentContext).To(Equal("default/test123/anonymous"))
Expect(len(cfg.Contexts)).To(Equal(1))
Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal(testClusterID))
Expect(cfg.Contexts["default/test123/anonymous"].Namespace).To(Equal(args.defaultNamespace))
})
It("Should fail when trying to find a non existent cluster", func() {
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes()
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return("", "", errors.New("err"))
err := runLogin(nil, []string{testClusterID})
Expect(err).ToNot(BeNil())
})
It("should return the managing cluster if one is requested", func() {
globalOpts.Manager = true
mockOcmInterface.EXPECT().GetClusterInfoByID(gomock.Any()).Return(mockCluster, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().GetManagingCluster(trueClusterID).Return(managingClusterID, managingClusterID, true, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(managingClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(managingClusterID), gomock.Any()).Return(fakeResp, nil)
err := runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
})
It("should failed if managing cluster not exist in same env", func() {
globalOpts.Manager = true
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().GetManagingCluster(trueClusterID).Return(
managingClusterID,
managingClusterID,
false,
fmt.Errorf("failed to find management cluster for cluster %s in %s env", testClusterID, "http://test.env"),
)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(managingClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).AnyTimes()
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil).AnyTimes()
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(managingClusterID), gomock.Any()).Return(fakeResp, nil).AnyTimes()
err := runLogin(nil, []string{testClusterID})
Expect(err).NotTo(BeNil())
Expect(err.Error()).Should(ContainSubstring("failed to find management cluster for cluster test123 in http://test.env env"))
})
It("should return the service cluster if hosted cluster is given", func() {
globalOpts.Service = true
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().GetManagingCluster(trueClusterID).Return(managingClusterID, managingClusterID, true, nil).AnyTimes() // isHostedControlPlane = true
mockOcmInterface.EXPECT().GetServiceCluster(trueClusterID).Return(serviceClusterID, serviceClusterName, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(serviceClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(serviceClusterID), gomock.Any()).Return(fakeResp, nil)
err := runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
})
It("should login to current cluster if cluster id not provided", func() {
loginType = LoginTypeExistingKubeConfig
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
globalOpts.ProxyURL = "https://squid.myproxy.com"
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil)
mockOcmInterface.EXPECT().GetTargetCluster("configcluster").Return(testClusterID, "dummy_cluster", nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(testClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(testClusterID), gomock.Any()).Return(fakeResp, nil)
err = runLogin(nil, nil)
Expect(err).To(BeNil())
cfg, err := utils.ReadKubeconfigRaw()
Expect(err).To(BeNil())
Expect(cfg.Contexts["default/test123/anonymous"].Cluster).To(Equal("dummy_cluster"))
Expect(cfg.Contexts["default/test123/anonymous"].Namespace).To(Equal("default"))
})
It("should fail when a proxy or backplane url is unreachable", func() {
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, errors.New("dial tcp: lookup yourproxy.com: no such host"))
err = runLogin(nil, []string{testClusterID})
Expect(err).NotTo(BeNil())
})
It("Check KUBECONFIG when logging into multiple clusters.", func() {
globalOpts.Manager = false
args.multiCluster = true
err := utils.ModifyTempKubeConfigFileName(trueClusterID)
Expect(err).To(BeNil())
kubePath, err := os.MkdirTemp("", ".kube")
Expect(err).To(BeNil())
err = login.SetKubeConfigBasePath(kubePath)
Expect(err).To(BeNil())
_, err = login.CreateClusterKubeConfig(trueClusterID, utils.GetDefaultKubeConfig())
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).Return(fakeResp, nil)
err = runLogin(nil, []string{testClusterID})
Expect(os.Getenv("KUBECONFIG")).Should(ContainSubstring(trueClusterID))
Expect(err).To(BeNil())
})
It("should fail if specify kubeconfigpath but not in multicluster mode", func() {
globalOpts.Manager = false
args.multiCluster = false
args.kubeConfigPath = kubeConfigPath
err := login.SetKubeConfigBasePath(args.kubeConfigPath)
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil)
err = runLogin(nil, []string{testClusterID})
Expect(err.Error()).Should(ContainSubstring("can't save the kube config into a specific location if multi-cluster is not enabled"))
})
It("should fail to create PD API client and return HTTP status code 401 when unauthorized", func() {
loginType = LoginTypePagerduty
args.pd = truePagerDutyIncidentID
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
// Create a temporary JSON configuration file in the temp directory for testing purposes.
tempDir := os.TempDir()
bpConfigPath = filepath.Join(tempDir, "mock.json")
tempFile, err := os.Create(bpConfigPath) //nolint:gosec
Expect(err).To(BeNil())
testData := config.BackplaneConfiguration{
URL: backplaneAPIURI,
ProxyURL: new(string),
SessionDirectory: "",
AssumeInitialArn: "",
PagerDutyAPIKey: falsePagerDutyAPITkn,
}
// Marshal the testData into JSON format and write it to tempFile.
jsonData, err := json.Marshal(testData)
Expect(err).To(BeNil())
_, err = tempFile.Write(jsonData)
Expect(err).To(BeNil())
_ = os.Setenv("BACKPLANE_CONFIG", bpConfigPath)
err = runLogin(nil, nil)
Expect(err.Error()).Should(ContainSubstring("status code 401"))
})
It("should return error when trying to login via PD but the PD API Key is not configured", func() {
loginType = LoginTypePagerduty
args.pd = truePagerDutyIncidentID
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
// Create a temporary JSON configuration file in the temp directory for testing purposes.
tempDir := os.TempDir()
bpConfigPath = filepath.Join(tempDir, "mock.json")
tempFile, err := os.Create(bpConfigPath) //nolint:gosec
Expect(err).To(BeNil())
testData := config.BackplaneConfiguration{
URL: backplaneAPIURI,
ProxyURL: new(string),
PagerDutyAPIKey: falsePagerDutyAPITkn,
}
// Marshal the testData into JSON format and write it to tempFile.
pdTestData := testData
pdTestData.PagerDutyAPIKey = ""
jsonData, err := json.Marshal(pdTestData)
Expect(err).To(BeNil())
_, err = tempFile.Write(jsonData)
Expect(err).To(BeNil())
_ = os.Setenv("BACKPLANE_CONFIG", bpConfigPath)
err = runLogin(nil, nil)
Expect(err.Error()).Should(ContainSubstring("please make sure the PD API Key is configured correctly"))
})
It("should fail to find a non existent PD Incident and return HTTP status code 404 when the requested resource is not found", func() {
loginType = LoginTypePagerduty
args.pd = falsePagerDutyIncidentID
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
// Create a temporary JSON configuration file in the temp directory for testing purposes.
tempDir := os.TempDir()
bpConfigPath = filepath.Join(tempDir, "mock.json")
tempFile, err := os.Create(bpConfigPath) //nolint:gosec
Expect(err).To(BeNil())
testData := config.BackplaneConfiguration{
URL: backplaneAPIURI,
ProxyURL: new(string),
PagerDutyAPIKey: truePagerDutyAPITkn,
}
// Marshal the testData into JSON format and write it to tempFile.
jsonData, err := json.Marshal(testData)
Expect(err).To(BeNil())
_, err = tempFile.Write(jsonData)
Expect(err).To(BeNil())
_ = os.Setenv("BACKPLANE_CONFIG", bpConfigPath)
err = runLogin(nil, nil)
Expect(err.Error()).Should(ContainSubstring("status code 404"))
})
})
Context("check GetRestConfigAsUser", func() {
It("check config creation with username and without elevationReasons", func() {
mockOcmInterface.EXPECT().GetClusterInfoByID(testClusterID).Return(mockCluster, nil)
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(testClusterID), gomock.Any()).Return(fakeResp, nil)
username := "test-user"
config, err := GetRestConfigAsUser(backplaneConfiguration, testClusterID, username)
Expect(err).To(BeNil())
Expect(config.Impersonate.UserName).To(Equal(username))
Expect(len(config.Impersonate.Extra["reason"])).To(Equal(0))
})
It("check config creation with username and elevationReasons", func() {
mockOcmInterface.EXPECT().GetClusterInfoByID(testClusterID).Return(mockCluster, nil)
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(testClusterID), gomock.Any()).Return(fakeResp, nil)
username := "test-user"
elevationReasons := []string{"reason1", "reason2"}
config, err := GetRestConfigAsUser(backplaneConfiguration, testClusterID, username, elevationReasons...)
Expect(err).To(BeNil())
Expect(config.Impersonate.UserName).To(Equal(username))
Expect(config.Impersonate.Extra["reason"][0]).To(Equal(elevationReasons[0]))
Expect(config.Impersonate.Extra["reason"][1]).To(Equal(elevationReasons[1]))
})
})
Context("check JIRA OHSS login", func() {
var (
testOHSSID string
testIssue jira.Issue
issueFields *jira.IssueFields
)
BeforeEach(func() {
mockIssueService = jiraMock.NewMockIssueServiceInterface(mockCtrl)
ohssService = jiraClient.NewOHSSService(mockIssueService)
testOHSSID = "OHSS-1000"
})
It("should login to ohss card cluster", func() {
loginType = LoginTypeJira
args.ohss = testOHSSID
err := utils.CreateTempKubeConfig(nil)
args.kubeConfigPath = ""
Expect(err).To(BeNil())
issueFields = &jira.IssueFields{
Project: jira.Project{Key: jiraClient.JiraOHSSProjectKey},
Unknowns: tcontainer.MarshalMap{jiraClient.CustomFieldClusterID: testClusterID},
}
testIssue = jira.Issue{ID: testOHSSID, Fields: issueFields}
globalOpts.ProxyURL = "https://squid.myproxy.com"
mockIssueService.EXPECT().Get(testOHSSID, nil).Return(&testIssue, nil, nil).Times(1)
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil)
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(testClusterID, testClusterID, nil)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(testClusterID)).Return(false, nil).AnyTimes()
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(testClusterID), gomock.Any()).Return(fakeResp, nil)
err = runLogin(nil, nil)
Expect(err).To(BeNil())
})
It("should failed missing cluster id ohss cards", func() {
loginType = LoginTypeJira
args.ohss = testOHSSID
issueFields = &jira.IssueFields{
Project: jira.Project{Key: jiraClient.JiraOHSSProjectKey},
}
testIssue = jira.Issue{ID: testOHSSID, Fields: issueFields}
mockIssueService.EXPECT().Get(testOHSSID, nil).Return(&testIssue, nil, nil).Times(1)
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
err := runLogin(nil, nil)
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(Equal("clusterID cannot be detected for JIRA issue:OHSS-1000"))
})
})
Context("readonly flag functionality", func() {
BeforeEach(func() {
err := utils.CreateTempKubeConfig(nil)
Expect(err).To(BeNil())
})
It("should add readonly=true query parameter by default (when --rw flag is not set)", func() {
// Setup
args.multiCluster = false
args.readwrite = false
loginType = LoginTypeClusterID
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, trueClusterID, nil).Times(1)
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).Times(1)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).Times(1)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
// Mock LoginCluster and capture the request to verify readonly query param
var capturedURL string
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID), gomock.Any()).DoAndReturn(
func(ctx interface{}, clusterId string, reqEditors ...interface{}) (*http.Response, error) {
// Create a mock request to test the editor
req, _ := http.NewRequest("GET", backplaneAPIURI+"/backplane/login/"+clusterId, nil)
// Apply the request editors if any
for _, editor := range reqEditors {
if fn, ok := editor.(BackplaneApi.RequestEditorFn); ok {
_ = fn(nil, req)
}
}
capturedURL = req.URL.String()
return fakeResp, nil
},
)
err := runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
// Verify readonly=true query parameter is present in the URL
Expect(capturedURL).To(ContainSubstring("readonly=true"))
})
It("should not add readonly query parameter when --rw flag is set", func() {
// Setup
args.multiCluster = false
args.readwrite = true
loginType = LoginTypeClusterID
mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes()
mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, trueClusterID, nil).Times(1)
mockOcmInterface.EXPECT().GetOCMAccessToken().Return(&testToken, nil).Times(1)
mockOcmInterface.EXPECT().IsClusterHibernating(gomock.Eq(trueClusterID)).Return(false, nil).Times(1)
mockClientUtil.EXPECT().MakeRawBackplaneAPIClientWithAccessToken(backplaneAPIURI, testToken).Return(mockClient, nil)
// Mock LoginCluster and capture the request
var capturedURL string
mockClient.EXPECT().LoginCluster(gomock.Any(), gomock.Eq(trueClusterID)).DoAndReturn(
func(ctx interface{}, clusterId string, reqEditors ...interface{}) (*http.Response, error) {
// Create a mock request
req, _ := http.NewRequest("GET", backplaneAPIURI+"/backplane/login/"+clusterId, nil)
capturedURL = req.URL.String()
return fakeResp, nil
},
)
err := runLogin(nil, []string{testClusterID})
Expect(err).To(BeNil())
// Verify readonly query parameter is not present
Expect(capturedURL).NotTo(ContainSubstring("readonly"))
})
})
})