-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
validation_test.go
1120 lines (1035 loc) · 44 KB
/
validation_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
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gcp
import (
"context"
"fmt"
"net"
"net/http"
"strings"
"testing"
"github.com/golang/mock/gomock"
logrusTest "github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
googleoauth "golang.org/x/oauth2/google"
"google.golang.org/api/cloudresourcemanager/v3"
compute "google.golang.org/api/compute/v1"
dns "google.golang.org/api/dns/v1"
"google.golang.org/api/googleapi"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/openshift/installer/pkg/asset/installconfig/gcp/mock"
"github.com/openshift/installer/pkg/ipnet"
"github.com/openshift/installer/pkg/types"
"github.com/openshift/installer/pkg/types/gcp"
)
type editFunctions []func(ic *types.InstallConfig)
var (
validNetworkName = "valid-vpc"
validProjectName = "valid-project"
invalidProjectName = "invalid-project"
validRegion = "us-east1"
invalidRegion = "us-east4"
validZone = "us-east1-b"
validComputeSubnet = "valid-compute-subnet"
validCPSubnet = "valid-controlplane-subnet"
validCIDR = "10.0.0.0/16"
validClusterName = "valid-cluster"
validPrivateZone = "valid-short-private-zone"
validPublicZone = "valid-short-public-zone"
invalidPublicZone = "invalid-short-public-zone"
validBaseDomain = "example.installer.domain."
validXpnSA = "valid-example-sa@gcloud.serviceaccount.com"
invalidXpnSA = "invalid-example-sa@gcloud.serviceaccount.com"
// #nosec G101
fakeCreds = `{
"client_id": "fake.apps.googleusercontent.com",
"client_secret": "fake-secret",
"quota_project_id": "openshift-installer-fake",
"refresh_token": "fake_token",
"type": "authorized_user"
}`
validPrivateDNSZone = dns.ManagedZone{
Name: validPrivateZone,
DnsName: fmt.Sprintf("%s.%s", validClusterName, strings.TrimSuffix(validBaseDomain, ".")),
}
validPublicDNSZone = dns.ManagedZone{
Name: validPublicZone,
DnsName: validBaseDomain,
}
invalidateMachineCIDR = func(ic *types.InstallConfig) {
_, newCidr, _ := net.ParseCIDR("192.168.111.0/24")
ic.MachineNetwork = []types.MachineNetworkEntry{
{CIDR: ipnet.IPNet{IPNet: *newCidr}},
}
}
validMachineTypes = func(ic *types.InstallConfig) {
ic.Platform.GCP.DefaultMachinePlatform.InstanceType = "n1-standard-2"
ic.ControlPlane.Platform.GCP.InstanceType = "n1-standard-4"
ic.Compute[0].Platform.GCP.InstanceType = "n1-standard-2"
}
invalidateDefaultMachineTypes = func(ic *types.InstallConfig) {
ic.Platform.GCP.DefaultMachinePlatform.InstanceType = "n1-standard-1"
}
invalidateControlPlaneMachineTypes = func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.InstanceType = "n1-standard-1"
}
invalidateComputeMachineTypes = func(ic *types.InstallConfig) {
ic.Compute[0].Platform.GCP.InstanceType = "n1-standard-1"
}
undefinedDefaultMachineTypes = func(ic *types.InstallConfig) {
ic.Platform.GCP.DefaultMachinePlatform.InstanceType = "n1-dne-1"
}
invalidateControlPlaneDiskTypes = func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.DiskType = "pd-standard"
}
invalidateNetwork = func(ic *types.InstallConfig) { ic.GCP.Network = "invalid-vpc" }
invalidateComputeSubnet = func(ic *types.InstallConfig) { ic.GCP.ComputeSubnet = "invalid-compute-subnet" }
invalidateCPSubnet = func(ic *types.InstallConfig) { ic.GCP.ControlPlaneSubnet = "invalid-cp-subnet" }
invalidateRegion = func(ic *types.InstallConfig) { ic.GCP.Region = invalidRegion }
invalidateProject = func(ic *types.InstallConfig) { ic.GCP.ProjectID = invalidProjectName }
invalidateNetworkProject = func(ic *types.InstallConfig) { ic.GCP.NetworkProjectID = invalidProjectName }
removeVPC = func(ic *types.InstallConfig) { ic.GCP.Network = "" }
removeSubnets = func(ic *types.InstallConfig) { ic.GCP.ComputeSubnet, ic.GCP.ControlPlaneSubnet = "", "" }
invalidClusterName = func(ic *types.InstallConfig) { ic.ObjectMeta.Name = "testgoogletest" }
validNetworkProject = func(ic *types.InstallConfig) { ic.GCP.NetworkProjectID = validProjectName }
validateXpnSA = func(ic *types.InstallConfig) { ic.ControlPlane.Platform.GCP.ServiceAccount = validXpnSA }
invalidateXpnSA = func(ic *types.InstallConfig) { ic.ControlPlane.Platform.GCP.ServiceAccount = invalidXpnSA }
machineTypeAPIResult = map[string]*compute.MachineType{
"n1-standard-1": {GuestCpus: 1, MemoryMb: 3840},
"n1-standard-2": {GuestCpus: 2, MemoryMb: 7680},
"n1-standard-4": {GuestCpus: 4, MemoryMb: 15360},
"n2-standard-1": {GuestCpus: 1, MemoryMb: 8192},
"n2-standard-2": {GuestCpus: 2, MemoryMb: 16384},
"n2-standard-4": {GuestCpus: 4, MemoryMb: 32768},
"n4-standard-4": {GuestCpus: 4, MemoryMb: 32768},
"t2a-standard-4": {GuestCpus: 4, MemoryMb: 16384},
"n4-custom-4-16384": {GuestCpus: 4, MemoryMb: 16384}, // custom machine type
"custom-4-16384": {GuestCpus: 4, MemoryMb: 16384}, // custom machine type - default type
}
subnetAPIResult = []*compute.Subnetwork{
{
Name: validCPSubnet,
IpCidrRange: validCIDR,
},
{
Name: validComputeSubnet,
IpCidrRange: validCIDR,
},
}
)
func validInstallConfig() *types.InstallConfig {
return &types.InstallConfig{
BaseDomain: validBaseDomain,
ObjectMeta: metav1.ObjectMeta{
Name: validClusterName,
},
Networking: &types.Networking{
MachineNetwork: []types.MachineNetworkEntry{
{CIDR: *ipnet.MustParseCIDR(validCIDR)},
},
},
Platform: types.Platform{
GCP: &gcp.Platform{
DefaultMachinePlatform: &gcp.MachinePool{},
ProjectID: validProjectName,
Region: validRegion,
Network: validNetworkName,
ComputeSubnet: validComputeSubnet,
ControlPlaneSubnet: validCPSubnet,
},
},
ControlPlane: &types.MachinePool{
Architecture: types.ArchitectureAMD64,
Platform: types.MachinePoolPlatform{
GCP: &gcp.MachinePool{},
},
},
Compute: []types.MachinePool{{
Architecture: types.ArchitectureAMD64,
Platform: types.MachinePoolPlatform{
GCP: &gcp.MachinePool{},
},
}},
// Setting to manual for testing the ValidateCredentials
CredentialsMode: types.ManualCredentialsMode,
}
}
func TestGCPInstallConfigValidation(t *testing.T) {
cases := []struct {
name string
edits editFunctions
expectedError bool
expectedErrMsg string
}{
{
name: "Valid network & subnets",
edits: editFunctions{},
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid ClusterName",
edits: editFunctions{invalidClusterName},
expectedError: true,
expectedErrMsg: `clusterName: Invalid value: "testgoogletest": cluster name must not start with "goog" or contain variations of "google"`,
},
{
name: "Valid install config without network & subnets",
edits: editFunctions{removeVPC, removeSubnets},
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid subnet range",
edits: editFunctions{invalidateMachineCIDR},
expectedError: true,
expectedErrMsg: "computeSubnet: Invalid value.*subnet CIDR range start 10.0.0.0 is outside of the specified machine networks",
},
{
name: "Invalid network",
edits: editFunctions{invalidateNetwork},
expectedError: true,
expectedErrMsg: "network: Invalid value",
},
{
name: "Invalid compute subnet",
edits: editFunctions{invalidateComputeSubnet},
expectedError: true,
expectedErrMsg: "computeSubnet: Invalid value",
},
{
name: "Invalid control plane subnet",
edits: editFunctions{invalidateCPSubnet},
expectedError: true,
expectedErrMsg: "controlPlaneSubnet: Invalid value",
},
{
name: "Invalid both subnets",
edits: editFunctions{invalidateCPSubnet, invalidateComputeSubnet},
expectedError: true,
expectedErrMsg: "computeSubnet: Invalid value.*controlPlaneSubnet: Invalid value",
},
{
name: "Valid machine types",
edits: editFunctions{validMachineTypes},
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid default machine type",
edits: editFunctions{invalidateDefaultMachineTypes},
expectedError: true,
expectedErrMsg: `\[platform.gcp.defaultMachinePlatform.type: Invalid value: "n1-standard-1": instance type does not meet minimum resource requirements of 4 vCPUs, platform.gcp.defaultMachinePlatform.type: Invalid value: "n1-standard-1": instance type does not meet minimum resource requirements of 15360 MB Memory, controlPlane.platform.gcp.type: Invalid value: "n1-standard-1": instance type does not meet minimum resource requirements of 4 vCPUs, controlPlane.platform.gcp.type: Invalid value: "n1-standard-1": instance type does not meet minimum resource requirements of 15360 MB Memory, compute\[0\].platform.gcp.type: Invalid value: "n1-standard-1": instance type does not meet minimum resource requirements of 2 vCPUs, compute\[0\].platform.gcp.type: Invalid value: "n1-standard-1": instance type does not meet minimum resource requirements of 7680 MB Memory\]`,
},
{
name: "Invalid control plane machine disk types",
edits: editFunctions{validMachineTypes, invalidateControlPlaneDiskTypes},
expectedError: true,
expectedErrMsg: `controlPlane.type: Unsupported value: "pd-standard": supported values: "hyperdisk-balanced", "pd-balanced", "pd-ssd"`,
},
{
name: "Invalid control plane machine types",
edits: editFunctions{invalidateControlPlaneMachineTypes},
expectedError: true,
expectedErrMsg: `[controlPlane.platform.gcp.type: Invalid value: "n1\-standard\-1": instance type does not meet minimum resource requirements of 4 vCPUs, controlPlane.platform.gcp.type: Invalid value: "n1\-standard\-1": instance type does not meet minimum resource requirements of 15361 MB Memory]`,
},
{
name: "Invalid compute machine types",
edits: editFunctions{invalidateComputeMachineTypes},
expectedError: true,
expectedErrMsg: `\[compute\[0\].platform.gcp.type: Invalid value: "n1-standard-1": instance type does not meet minimum resource requirements of 2 vCPUs, compute\[0\].platform.gcp.type: Invalid value: "n1-standard-1": instance type does not meet minimum resource requirements of 7680 MB Memory\]`,
},
{
name: "Undefined default machine types",
edits: editFunctions{undefinedDefaultMachineTypes},
expectedError: true,
expectedErrMsg: `Internal error: 404`,
},
{
name: "Invalid region",
edits: editFunctions{invalidateRegion},
expectedError: true,
expectedErrMsg: "could not find subnet valid-compute-subnet in network valid-vpc and region us-east4",
},
{
name: "Invalid project",
edits: editFunctions{invalidateProject},
expectedError: true,
expectedErrMsg: "network: Invalid value",
},
{
name: "Invalid project & region",
edits: editFunctions{invalidateRegion, invalidateProject},
expectedError: true,
expectedErrMsg: "network: Invalid value",
},
{
name: "Invalid project ID",
edits: editFunctions{invalidateProject, removeSubnets, removeVPC},
expectedError: true,
expectedErrMsg: "platform.gcp.project: Invalid value: \"invalid-project\": invalid project ID",
},
{
name: "Invalid network project ID",
edits: editFunctions{invalidateNetworkProject},
expectedError: true,
expectedErrMsg: "platform.gcp.networkProjectID: Invalid value: \"invalid-project\": invalid project ID",
},
{
name: "Valid Region",
edits: editFunctions{},
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid region not found",
edits: editFunctions{invalidateRegion, invalidateProject},
expectedError: true,
expectedErrMsg: "platform.gcp.project: Invalid value: \"invalid-project\": invalid project ID",
},
{
name: "Region not validated",
edits: editFunctions{invalidateRegion},
expectedError: true,
expectedErrMsg: "platform.gcp.region: Invalid value: \"us-east4\": invalid region",
},
{
name: "Valid XPN Service Account",
edits: editFunctions{validNetworkProject, validateXpnSA},
expectedError: false,
},
{
name: "Invalid XPN Service Account",
edits: editFunctions{validNetworkProject, invalidateXpnSA},
expectedError: true,
expectedErrMsg: "controlPlane.platform.gcp.serviceAccount: Internal error\"",
},
}
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
gcpClient := mock.NewMockAPI(mockCtrl)
errNotFound := &googleapi.Error{Code: http.StatusNotFound}
// Should get the list of projects.
gcpClient.EXPECT().GetProjects(gomock.Any()).Return(map[string]string{"valid-project": "valid-project"}, nil).AnyTimes()
gcpClient.EXPECT().GetProjectByID(gomock.Any(), "valid-project").Return(&cloudresourcemanager.Project{}, nil).AnyTimes()
gcpClient.EXPECT().GetProjectByID(gomock.Any(), "invalid-project").Return(nil, errNotFound).AnyTimes()
gcpClient.EXPECT().GetProjectByID(gomock.Any(), gomock.Any()).Return(nil, fmt.Errorf("error")).AnyTimes()
// Should get the list of zones.
gcpClient.EXPECT().GetZones(gomock.Any(), gomock.Any(), gomock.Any()).Return([]*compute.Zone{{Name: validZone}}, nil).AnyTimes()
// When passed an invalid project, no regions will be returned
gcpClient.EXPECT().GetRegions(gomock.Any(), invalidProjectName).Return(nil, fmt.Errorf("failed to get regions for project")).AnyTimes()
// When passed a project that is valid but the region is not contained, an error should still occur
gcpClient.EXPECT().GetRegions(gomock.Any(), validProjectName).Return([]string{validRegion}, nil).AnyTimes()
// Should return the machine type as specified.
for key, value := range machineTypeAPIResult {
gcpClient.EXPECT().GetMachineTypeWithZones(gomock.Any(), gomock.Any(), gomock.Any(), key).Return(value, sets.New(validZone), nil).AnyTimes()
}
// When passed incorrect machine type, the API returns nil.
gcpClient.EXPECT().GetMachineTypeWithZones(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, fmt.Errorf("404")).AnyTimes()
// When passed the correct network & project, return an empty network, which should be enough to validate ok.
gcpClient.EXPECT().GetNetwork(gomock.Any(), validNetworkName, validProjectName).Return(&compute.Network{}, nil).AnyTimes()
// When passed an incorrect network or incorrect project, the API returns nil
gcpClient.EXPECT().GetNetwork(gomock.Any(), gomock.Not(validNetworkName), gomock.Any()).Return(nil, fmt.Errorf("404")).AnyTimes()
gcpClient.EXPECT().GetNetwork(gomock.Any(), gomock.Any(), gomock.Not(validProjectName)).Return(nil, fmt.Errorf("404")).AnyTimes()
// When passed a correct network, project, & region, returns valid subnets.
// We will test incorrect subnets, by changing the install config.
gcpClient.EXPECT().GetSubnetworks(gomock.Any(), validNetworkName, validProjectName, validRegion).Return(subnetAPIResult, nil).AnyTimes()
// When passed an incorrect network, project or region, return empty list.
gcpClient.EXPECT().GetSubnetworks(gomock.Any(), gomock.Not(validNetworkName), gomock.Any(), gomock.Any()).Return([]*compute.Subnetwork{}, nil).AnyTimes()
gcpClient.EXPECT().GetSubnetworks(gomock.Any(), gomock.Any(), gomock.Not(validProjectName), gomock.Any()).Return([]*compute.Subnetwork{}, nil).AnyTimes()
gcpClient.EXPECT().GetSubnetworks(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Not(validRegion)).Return([]*compute.Subnetwork{}, nil).AnyTimes()
// Return fake credentials when asked
gcpClient.EXPECT().GetCredentials().Return(&googleoauth.Credentials{JSON: []byte(fakeCreds)}).AnyTimes()
// Expected results for the managed zone tests
gcpClient.EXPECT().GetDNSZoneByName(gomock.Any(), gomock.Any(), validPublicZone).Return(&validPublicDNSZone, nil).AnyTimes()
gcpClient.EXPECT().GetDNSZoneByName(gomock.Any(), gomock.Any(), validPrivateZone).Return(&validPrivateDNSZone, nil).AnyTimes()
gcpClient.EXPECT().GetDNSZoneByName(gomock.Any(), gomock.Any(), invalidPublicZone).Return(nil, fmt.Errorf("no matching DNS Zone found")).AnyTimes()
gcpClient.EXPECT().GetServiceAccount(gomock.Any(), validProjectName, validXpnSA).Return(validXpnSA, nil).AnyTimes()
gcpClient.EXPECT().GetServiceAccount(gomock.Any(), validProjectName, invalidXpnSA).Return("", fmt.Errorf("controlPlane.platform.gcp.serviceAccount: Internal error\"")).AnyTimes()
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
editedInstallConfig := validInstallConfig()
for _, edit := range tc.edits {
edit(editedInstallConfig)
}
errs := Validate(gcpClient, editedInstallConfig)
if tc.expectedError {
assert.Regexp(t, tc.expectedErrMsg, errs)
} else {
assert.Empty(t, errs)
}
})
}
}
func TestValidatePreExistingPublicDNS(t *testing.T) {
cases := []struct {
name string
records []*dns.ResourceRecordSet
err string
}{{
name: "no pre-existing",
records: nil,
}, {
name: "no pre-existing",
records: []*dns.ResourceRecordSet{{Name: "api.another-cluster-name.base-domain."}},
}, {
name: "pre-existing",
records: []*dns.ResourceRecordSet{{Name: "api.cluster-name.base-domain."}},
err: `^metadata\.name: Invalid value: "cluster-name": record\(s\) \["api\.cluster-name\.base-domain\."\] already exists in DNS Zone \(project-id/zone-name\) and might be in use by another cluster, please remove it to continue$`,
}, {
name: "pre-existing",
records: []*dns.ResourceRecordSet{{Name: "api.cluster-name.base-domain."}, {Name: "api.cluster-name.base-domain."}},
err: `^metadata\.name: Invalid value: "cluster-name": record\(s\) \["api\.cluster-name\.base-domain\."\] already exists in DNS Zone \(project-id/zone-name\) and might be in use by another cluster, please remove it to continue$`,
}}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
gcpClient := mock.NewMockAPI(mockCtrl)
gcpClient.EXPECT().GetDNSZone(gomock.Any(), "project-id", "base-domain", true).Return(&dns.ManagedZone{Name: "zone-name"}, nil).AnyTimes()
gcpClient.EXPECT().GetRecordSets(gomock.Any(), gomock.Eq("project-id"), gomock.Eq("zone-name")).Return(test.records, nil).AnyTimes()
err := ValidatePreExistingPublicDNS(gcpClient, &types.InstallConfig{
ObjectMeta: metav1.ObjectMeta{Name: "cluster-name"},
BaseDomain: "base-domain",
Platform: types.Platform{GCP: &gcp.Platform{ProjectID: "project-id"}},
})
if test.err == "" {
assert.True(t, err == nil)
} else {
assert.Regexp(t, test.err, err)
}
})
}
}
func TestValidatePrivateDNSZone(t *testing.T) {
cases := []struct {
name string
records []*dns.ResourceRecordSet
err string
}{{
name: "no pre-existing",
records: nil,
}, {
name: "no pre-existing",
records: []*dns.ResourceRecordSet{{Name: "api.another-cluster-name.base-domain."}},
}, {
name: "pre-existing",
records: []*dns.ResourceRecordSet{{Name: "api.cluster-name.base-domain."}},
err: `^metadata\.name: Invalid value: "cluster-name": record\(s\) \["api\.cluster-name\.base-domain\."\] already exists in DNS Zone \(project-id/zone-name\) and might be in use by another cluster, please remove it to continue$`,
}, {
name: "pre-existing",
records: []*dns.ResourceRecordSet{{Name: "api.cluster-name.base-domain."}, {Name: "api.cluster-name.base-domain."}},
err: `^metadata\.name: Invalid value: "cluster-name": record\(s\) \["api\.cluster-name\.base-domain\."\] already exists in DNS Zone \(project-id/zone-name\) and might be in use by another cluster, please remove it to continue$`,
}}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
gcpClient := mock.NewMockAPI(mockCtrl)
gcpClient.EXPECT().GetDNSZone(gomock.Any(), "project-id", "cluster-name.base-domain", false).Return(&dns.ManagedZone{Name: "zone-name"}, nil).AnyTimes()
gcpClient.EXPECT().GetRecordSets(gomock.Any(), gomock.Eq("project-id"), gomock.Eq("zone-name")).Return(test.records, nil).AnyTimes()
err := ValidatePrivateDNSZone(gcpClient, &types.InstallConfig{
ObjectMeta: metav1.ObjectMeta{Name: "cluster-name"},
BaseDomain: "base-domain",
Platform: types.Platform{GCP: &gcp.Platform{ProjectID: "project-id", Network: "shared-vpc", NetworkProjectID: "test-network-project"}},
})
if test.err == "" {
assert.True(t, err == nil)
} else {
assert.Regexp(t, test.err, err)
}
})
}
}
func TestGCPEnabledServicesList(t *testing.T) {
cases := []struct {
name string
services []string
err string
}{{
name: "No services present",
services: nil,
err: "unable to fetch enabled services for project. Make sure 'serviceusage.googleapis.com' is enabled",
}, {
name: "Service Usage missing",
services: []string{"compute.googleapis.com"},
err: "unable to fetch enabled services for project. Make sure 'serviceusage.googleapis.com' is enabled",
}, {
name: "All pre-existing",
services: []string{
"compute.googleapis.com",
"cloudresourcemanager.googleapis.com", "dns.googleapis.com",
"iam.googleapis.com", "iamcredentials.googleapis.com", "serviceusage.googleapis.com",
"deploymentmanager.googleapis.com",
},
}, {
name: "Some services present",
services: []string{"compute.googleapis.com", "serviceusage.googleapis.com"},
err: "the following required services are not enabled in this project: cloudresourcemanager.googleapis.com,dns.googleapis.com,iam.googleapis.com,iamcredentials.googleapis.com",
}}
errForbidden := &googleapi.Error{Code: http.StatusForbidden}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
gcpClient := mock.NewMockAPI(mockCtrl)
if !sets.NewString(test.services...).Has("serviceusage.googleapis.com") {
gcpClient.EXPECT().GetEnabledServices(gomock.Any(), gomock.Any()).Return(nil, errForbidden).AnyTimes()
} else {
gcpClient.EXPECT().GetEnabledServices(gomock.Any(), gomock.Any()).Return(test.services, nil).AnyTimes()
}
err := ValidateEnabledServices(context.TODO(), gcpClient, "")
if test.err == "" {
assert.NoError(t, err)
} else {
assert.Regexp(t, test.err, err)
}
})
}
}
func TestValidateCredentialMode(t *testing.T) {
cases := []struct {
name string
creds types.CredentialsMode
emptyCreds bool
err string
}{{
name: "missing json with manual creds",
creds: types.ManualCredentialsMode,
emptyCreds: true,
}, {
name: "missing json without manual creds",
creds: types.PassthroughCredentialsMode,
emptyCreds: true,
err: "credentialsMode: Forbidden: Manual credentials mode needs to be enabled to use environmental authentication",
}, {
name: "supplied json with manual creds",
creds: types.ManualCredentialsMode,
emptyCreds: false,
}, {
name: "supplied json without manual creds",
creds: types.PassthroughCredentialsMode,
emptyCreds: false,
err: "credentialsMode: Forbidden: environmental authentication is only supported with Manual credentials mode",
}}
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
// Client where the creds are empty
gcpClientEmptyCreds := mock.NewMockAPI(mockCtrl)
gcpClientEmptyCreds.EXPECT().GetCredentials().Return(&googleoauth.Credentials{JSON: nil}).AnyTimes()
// Client that contains creds
gcpClientWithCreds := mock.NewMockAPI(mockCtrl)
gcpClientWithCreds.EXPECT().GetCredentials().Return(&googleoauth.Credentials{JSON: []byte(fakeCreds)}).AnyTimes()
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
ic := types.InstallConfig{
ObjectMeta: metav1.ObjectMeta{Name: "cluster-name"},
BaseDomain: "base-domain",
Platform: types.Platform{GCP: &gcp.Platform{ProjectID: "project-id"}},
CredentialsMode: test.creds,
}
var err error
if test.emptyCreds {
err = ValidateCredentialMode(gcpClientEmptyCreds, &ic).ToAggregate()
} else {
err = ValidateCredentialMode(gcpClientWithCreds, &ic).ToAggregate()
}
if test.err == "" {
assert.Nil(t, err)
} else {
assert.Regexp(t, test.err, err)
}
})
}
}
func TestValidateServiceAccountPresent(t *testing.T) {
cases := []struct {
name string
creds *googleoauth.Credentials
serviceAccount string
networkProjectID string
expectedError string
}{
{
name: "Test no network project ID",
creds: &googleoauth.Credentials{},
},
{
name: "Test network project ID with service account",
creds: &googleoauth.Credentials{},
serviceAccount: "test-service-account",
networkProjectID: "test-network-project",
},
{
name: "Test network project ID service account and creds",
creds: &googleoauth.Credentials{JSON: []byte("{}")},
serviceAccount: "test-service-account",
networkProjectID: "test-network-project",
},
{
name: "Test network project ID no creds",
creds: &googleoauth.Credentials{JSON: nil},
networkProjectID: "test-network-project",
expectedError: "controlPlane.platform.gcp.serviceAccount: Required value: service account must be provided when authentication credentials do not provide a service account",
},
}
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
for _, test := range cases {
gcpClient := mock.NewMockAPI(mockCtrl)
if test.networkProjectID != "" {
gcpClient.EXPECT().GetCredentials().Return(test.creds)
}
t.Run(test.name, func(t *testing.T) {
ic := types.InstallConfig{
ObjectMeta: metav1.ObjectMeta{Name: "cluster-name"},
BaseDomain: "base-domain",
Platform: types.Platform{GCP: &gcp.Platform{ProjectID: "project-id", NetworkProjectID: test.networkProjectID}},
CredentialsMode: types.PassthroughCredentialsMode,
ControlPlane: &types.MachinePool{
Platform: types.MachinePoolPlatform{
GCP: &gcp.MachinePool{
ServiceAccount: test.serviceAccount,
},
},
},
}
errorList := validateServiceAccountPresent(gcpClient, &ic)
if errorList == nil && test.expectedError == "" {
assert.NoError(t, errorList.ToAggregate())
} else {
assert.Regexp(t, test.expectedError, errorList.ToAggregate())
}
})
}
}
func TestValidateZones(t *testing.T) {
validZonesDefaultMachine := func(ic *types.InstallConfig) {
ic.Platform.GCP.DefaultMachinePlatform.Zones = []string{"us-central1-a", "us-central1-c"}
}
validZonesControlPlane := func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.Zones = []string{"us-central1-a", "us-central1-b"}
}
validZonesCompute := func(ic *types.InstallConfig) {
ic.Compute[0].Platform.GCP.Zones = []string{"us-central1-b", "us-central1-c", "us-central1-d"}
}
invalidZonesDefaultMachine := func(ic *types.InstallConfig) {
ic.Platform.GCP.DefaultMachinePlatform.Zones = []string{"us-central1-a", "us-central1-x", "us-central1-y"}
}
invalidZonesControlPlane := func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.Zones = []string{"us-central1-d", "us-central1-x", "us-central1-y"}
}
invalidZonesCompute := func(ic *types.InstallConfig) {
ic.Compute[0].Platform.GCP.Zones = []string{"us-central1-y", "us-central1-z", "us-central1-w"}
}
cases := []struct {
name string
edits editFunctions
expectedError bool
expectedErrMsg string
}{
{
name: "Valid zones for defaultMachine",
edits: editFunctions{validZonesDefaultMachine},
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid zones for defaultMachine",
edits: editFunctions{invalidZonesDefaultMachine},
expectedError: true,
expectedErrMsg: `^\[platform.gcp.defaultMachinePlatform.zones: Invalid value: \[\]string\{"us\-central1\-x", "us\-central1\-y"\}: zone\(s\) not found in region\]$`,
},
{
name: "Valid zones for controlPlane",
edits: editFunctions{validZonesControlPlane},
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid zones for controlPlane",
edits: editFunctions{invalidZonesControlPlane},
expectedError: true,
expectedErrMsg: `^\[controlPlane.platform.gcp.zones: Invalid value: \[\]string\{"us\-central1\-x", "us\-central1\-y"\}: zone\(s\) not found in region\]$`,
},
{
name: "Valid zones for compute",
edits: editFunctions{validZonesCompute},
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid zones for compute",
edits: editFunctions{invalidZonesCompute},
expectedError: true,
expectedErrMsg: `^\[compute\[0\].platform.gcp.zones: Invalid value: \[\]string\{"us\-central1\-w", "us\-central1\-y", "us\-central1\-z"\}: zone\(s\) not found in region\]$`,
},
}
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
gcpClient := mock.NewMockAPI(mockCtrl)
validZones := []*compute.Zone{
{Name: "us-central1-a"},
{Name: "us-central1-b"},
{Name: "us-central1-c"},
{Name: "us-central1-d"},
}
// Should get the list of zones.
gcpClient.EXPECT().GetZones(gomock.Any(), gomock.Any(), gomock.Any()).Return(validZones, nil).AnyTimes()
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
editedInstallConfig := validInstallConfig()
for _, edit := range tc.edits {
edit(editedInstallConfig)
}
errs := validateZones(gcpClient, editedInstallConfig)
if tc.expectedError {
assert.Regexp(t, tc.expectedErrMsg, errs)
} else {
assert.Empty(t, errs)
}
})
}
}
func TestValidateInstanceType(t *testing.T) {
cases := []struct {
name string
zones []string
diskType string
instanceType string
arch string
expectedError bool
expectedErrMsg string
}{
{
name: "Valid instance type with min requirements and no zones specified",
zones: []string{},
instanceType: "n1-standard-4",
diskType: "pd-ssd",
expectedError: false,
expectedErrMsg: "",
},
{
name: "Valid instance type with min requirements and valid zones specified",
zones: []string{"a", "b"},
instanceType: "n1-standard-4",
diskType: "pd-ssd",
arch: "amd64",
expectedError: false,
expectedErrMsg: "",
},
{
name: "Valid instance type with min requirements and invalid zones specified",
zones: []string{"a", "b", "d", "x", "y"},
instanceType: "n1-standard-4",
diskType: "pd-ssd",
expectedError: true,
expectedErrMsg: `\[instance.type: Invalid value: "n1\-standard\-4": instance type not available in zones: \[x y\]\]$`,
},
{
name: "Valid instance fails min requirements and no zones specified",
zones: []string{},
instanceType: "n1-standard-2",
diskType: "pd-ssd",
expectedError: true,
expectedErrMsg: `^\[instance.type: Invalid value: "n1\-standard\-2": instance type does not meet minimum resource requirements of 4 vCPUs instance.type: Invalid value: "n1\-standard\-2": instance type does not meet minimum resource requirements of 15360 MB Memory\]$`,
},
{
name: "Valid instance fails min requirements and valid zones specified",
zones: []string{"a", "b"},
instanceType: "n1-standard-1",
diskType: "pd-ssd",
expectedError: true,
expectedErrMsg: ``,
},
{
name: "Valid instance fails min requirements and invalid zones specified",
zones: []string{"a", "x", "y"},
diskType: "pd-ssd",
expectedError: true,
expectedErrMsg: ``,
},
{
name: "Invalid instance and no zones specified",
zones: []string{},
instanceType: "invalid-instance-1",
diskType: "pd-ssd",
expectedError: true,
expectedErrMsg: `^\[<nil>: Internal error: 404\]$`,
},
{
name: "Invalid instance and valid zones specified",
zones: []string{"a", "b"},
instanceType: "invalid-instance-1",
diskType: "pd-ssd",
expectedError: true,
expectedErrMsg: `^\[<nil>: Internal error: 404\]$`,
},
{
name: "Invalid instance and invalid zones specified",
zones: []string{"a", "x", "y", "z"},
instanceType: "invalid-instance-1",
diskType: "pd-ssd",
expectedError: true,
expectedErrMsg: `^\[<nil>: Internal error: 404\]$`,
},
{
name: "Invalid instance architecture",
zones: []string{"a", "b"},
instanceType: "t2a-standard-4",
diskType: "pd-ssd",
arch: "amd64",
expectedError: true,
expectedErrMsg: `^\[instance.type: Invalid value: "t2a\-standard\-4": instance type architecture arm64 does not match specified architecture amd64\]$`,
},
{
name: "Valid special instance type with min requirements",
zones: []string{"a"},
instanceType: "n4-standard-4",
diskType: "hyperdisk-balanced",
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid special instance type with min requirements",
zones: []string{"a"},
instanceType: "n2-standard-4",
diskType: "hyperdisk-balanced",
expectedError: true,
expectedErrMsg: `^\[instance.diskType: Invalid value: "hyperdisk\-balanced": n2\-standard\-4 instance requires one of the following disk types: \[pd\-standard pd\-ssd pd\-balanced\]\]$`,
},
{
name: "Valid custom instance type",
zones: []string{"a"},
instanceType: "n4-custom-4-16384",
diskType: "hyperdisk-balanced",
expectedError: false,
expectedErrMsg: "",
},
{
name: "Valid custom instance type invalid disk type",
zones: []string{"a"},
instanceType: "n4-custom-4-16384",
diskType: "pd-ssd",
expectedError: true,
expectedErrMsg: `^\[instance.diskType: Invalid value: "pd\-ssd": n4\-custom\-4\-16384 instance requires one of the following disk types: \[hyperdisk\-balanced\]\]$`,
},
{
name: "Valid custom default instance type",
zones: []string{"a"},
instanceType: "custom-4-16384",
diskType: "pd-ssd",
expectedError: false,
expectedErrMsg: "",
},
{
name: "Invalid disk type custom default instance type",
zones: []string{"a"},
instanceType: "custom-4-16384",
diskType: "hyperdisk-balanced",
expectedError: true,
expectedErrMsg: `^\[instance.diskType: Invalid value: "hyperdisk\-balanced": custom\-4\-16384 instance requires one of the following disk types: \[pd\-standard pd\-ssd pd\-balanced\]\]$`,
},
}
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
gcpClient := mock.NewMockAPI(mockCtrl)
// Should return the machine type as specified
for key, value := range machineTypeAPIResult {
gcpClient.EXPECT().GetMachineTypeWithZones(gomock.Any(), gomock.Any(), gomock.Any(), key).Return(value, sets.New("a", "b", "c", "d"), nil).AnyTimes()
}
// When passed incorrect machine type, the API returns nil.
gcpClient.EXPECT().GetMachineTypeWithZones(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, fmt.Errorf("404")).AnyTimes()
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
errs := ValidateInstanceType(gcpClient, field.NewPath("instance"), "project-id", "region", test.zones, test.diskType, test.instanceType, controlPlaneReq, test.arch)
if test.expectedError {
assert.Regexp(t, test.expectedErrMsg, errs)
} else {
assert.Empty(t, errs)
}
})
}
}
func TestValidateMarketplaceImages(t *testing.T) {
var (
validImage = "valid-image"
projectID = "project-id"
invalidImage = "invalid-image"
mismatchedArch = "mismatched-arch"
osImage = &gcp.OSImage{}
validDefaultMachineImage = func(ic *types.InstallConfig) {
ic.Platform.GCP.DefaultMachinePlatform.OSImage = osImage
ic.Platform.GCP.DefaultMachinePlatform.OSImage.Name = validImage
ic.Platform.GCP.DefaultMachinePlatform.OSImage.Project = projectID
}
validControlPlaneImage = func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.OSImage = osImage
ic.ControlPlane.Platform.GCP.OSImage.Name = validImage
ic.ControlPlane.Platform.GCP.OSImage.Project = projectID
}
validComputeImage = func(ic *types.InstallConfig) {
ic.Compute[0].Platform.GCP.OSImage = osImage
ic.Compute[0].Platform.GCP.OSImage.Name = validImage
ic.Compute[0].Platform.GCP.OSImage.Project = projectID
}
invalidDefaultMachineImage = func(ic *types.InstallConfig) {
ic.Platform.GCP.DefaultMachinePlatform.OSImage = osImage
ic.Platform.GCP.DefaultMachinePlatform.OSImage.Name = invalidImage
ic.Platform.GCP.DefaultMachinePlatform.OSImage.Project = projectID
}
invalidControlPlaneImage = func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.OSImage = osImage
ic.ControlPlane.Platform.GCP.OSImage.Name = invalidImage
ic.ControlPlane.Platform.GCP.OSImage.Project = projectID
}
invalidComputeImage = func(ic *types.InstallConfig) {
ic.Compute[0].Platform.GCP.OSImage = osImage
ic.Compute[0].Platform.GCP.OSImage.Name = invalidImage
ic.Compute[0].Platform.GCP.OSImage.Project = projectID
}
mismatchedDefaultMachineImageArchitecture = func(ic *types.InstallConfig) {
ic.Platform.GCP.DefaultMachinePlatform.OSImage = osImage
ic.Platform.GCP.DefaultMachinePlatform.OSImage.Name = mismatchedArch
ic.Platform.GCP.DefaultMachinePlatform.OSImage.Project = projectID
ic.ControlPlane.Architecture = types.ArchitectureARM64
ic.Compute[0].Architecture = types.ArchitectureARM64
}
mismatchedControlPlaneImageArchitecture = func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.OSImage = osImage
ic.ControlPlane.Platform.GCP.OSImage.Name = mismatchedArch
ic.ControlPlane.Platform.GCP.OSImage.Project = projectID
ic.ControlPlane.Architecture = types.ArchitectureARM64
}
mismatchedComputeImageArchitecture = func(ic *types.InstallConfig) {
ic.Compute[0].Platform.GCP.OSImage = osImage
ic.Compute[0].Platform.GCP.OSImage.Name = mismatchedArch
ic.Compute[0].Platform.GCP.OSImage.Project = projectID
ic.Compute[0].Architecture = types.ArchitectureARM64
}
unspecifiedImageArchitecture = func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.OSImage = osImage
ic.ControlPlane.Platform.GCP.OSImage.Name = "unspecified-arch"
ic.ControlPlane.Platform.GCP.OSImage.Project = projectID
}
missingImageArchitecture = func(ic *types.InstallConfig) {
ic.ControlPlane.Platform.GCP.OSImage = osImage
ic.ControlPlane.Platform.GCP.OSImage.Name = "missing-arch"
ic.ControlPlane.Platform.GCP.OSImage.Project = projectID
}
marketplaceImageAPIResult = &compute.Image{
Architecture: "X86_64",
}
unspecifiedMarketplaceImageAPIResult = &compute.Image{
Architecture: "ARCHITECTURE_UNSPECIFIED",