-
Notifications
You must be signed in to change notification settings - Fork 30
/
dialer_test.go
1169 lines (1065 loc) · 30.5 KB
/
dialer_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
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cloudsqlconn
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"cloud.google.com/go/cloudsqlconn/errtype"
"cloud.google.com/go/cloudsqlconn/instance"
"cloud.google.com/go/cloudsqlconn/internal/cloudsql"
"cloud.google.com/go/cloudsqlconn/internal/mock"
"golang.org/x/oauth2"
)
// testSuccessfulDial uses the provided dialer to dial the specified instance
// and verifies the connection works end to end.
func testSuccessfulDial(
ctx context.Context, t *testing.T, d *Dialer, icn string, opts ...DialOption,
) {
testSucessfulDialWithInstanceName(ctx, t, d, icn, "my-instance", opts...)
}
// testSuccessfulDial uses the provided dialer to dial the specified instance
// and verifies the connection works end to end.
func testSucessfulDialWithInstanceName(
ctx context.Context, t *testing.T, d *Dialer, icn string, instanceName string, opts ...DialOption,
) {
conn, err := d.Dial(ctx, icn, opts...)
if err != nil {
t.Fatalf("expected Dial to succeed, but got error: %v", err)
}
defer func() { _ = conn.Close() }()
data, err := io.ReadAll(conn)
if err != nil {
t.Fatalf("expected ReadAll to succeed, got error %v", err)
}
if string(data) != instanceName {
t.Fatalf(
"expected known response from the server, but got %v",
string(data),
)
}
}
// setupConfig holds all the configuration to use when setting up a dialer.
type setupConfig struct {
testInstance mock.FakeCSQLInstance
skipServer bool
skipVerify bool
reqs []*mock.Request
dialerOptions []Option
}
// setupDialer configures a Dialer with an HTTP client configured to point at a
// mock SQL Admin API. Use setupConfig to configure the expected requests.
func setupDialer(t *testing.T, c setupConfig) *Dialer {
svc, cleanup, err := mock.NewSQLAdminService(
context.Background(),
c.reqs...,
)
if err != nil {
t.Fatalf("failed to init SQLAdminService: %v", err)
}
stop := func() {}
if !c.skipServer {
stop = mock.StartServerProxy(t, c.testInstance)
}
t.Cleanup(func() {
stop()
err := cleanup()
if !c.skipVerify && err != nil {
t.Fatalf("%v", err)
}
})
opts := []Option{
WithTokenSource(mock.EmptyTokenSource{}),
// give refresh plenty of time to complete in slower CI builds
WithRefreshTimeout(time.Minute),
}
if c.dialerOptions != nil {
opts = c.dialerOptions
}
d, err := NewDialer(context.Background(), opts...)
if err != nil {
t.Fatalf("expected NewDialer to succeed, but got error: %v", err)
}
d.sqladmin = svc
return d
}
func TestDialerCanConnectToInstance(t *testing.T) {
inst := mock.NewFakeCSQLInstance(
"my-project", "my-region", "my-instance",
)
d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
})
testSuccessfulDial(
context.Background(), t, d,
inst.String(),
)
}
func TestDialWithAdminAPIErrors(t *testing.T) {
inst := mock.NewFakeCSQLInstance(
"my-project", "my-region", "my-instance",
)
// API server will respond with 40x's
d := setupDialer(t, setupConfig{testInstance: inst})
_, err := d.Dial(
context.Background(), inst.String(),
)
var wantErr *errtype.RefreshError
if !errors.As(err, &wantErr) {
t.Fatalf("when API call fails, want = %T, got = %v", wantErr, err)
}
}
func TestDialWithConfigurationErrors(t *testing.T) {
inst := mock.NewFakeCSQLInstance(
"my-project", "my-region", "my-instance",
)
d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: []*mock.Request{
mock.InstanceGetSuccess(inst, 3),
mock.CreateEphemeralSuccess(inst, 3),
},
skipVerify: true,
skipServer: true,
})
_, err := d.Dial(
context.Background(),
// Try private IP of a public IP-only instance
inst.String(), WithPrivateIP(),
)
if err == nil {
t.Fatal("when IP type is invalid, want = error, got = nil")
}
_, err = d.Dial(
context.Background(), inst.String(),
)
if err == nil {
t.Fatal("when server proxy socket is unavailable, want = error, got = nil")
}
}
func TestDialWithExpiredCertificate(t *testing.T) {
inst := mock.NewFakeCSQLInstance(
"my-project", "my-region", "my-instance",
// Server certificate is expired
mock.WithCertExpiry(time.Now().Add(-time.Hour)),
)
d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: []*mock.Request{
mock.InstanceGetSuccess(inst, 3),
mock.CreateEphemeralSuccess(inst, 3),
},
skipVerify: true,
skipServer: true,
})
_, err := d.Dial(context.Background(), inst.String())
if err == nil {
t.Fatal("when TLS handshake fails, want = error, got = nil")
}
}
func fakeServiceAccount(ud string) []byte {
sa := `
"type": "service_account",
"project_id": "a-project-id",
"private_key_id": "a-private-key-id",
"private_key": "a-private-key",
"client_email": "[email protected]",
"client_id": "12345",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/email%40example.com"
`
if ud != "" {
sa = sa + fmt.Sprintf(`, "universe_domain": "%s"`, ud)
}
return []byte(fmt.Sprintf(`{ %s }`, sa))
}
func TestIAMAuthn(t *testing.T) {
tcs := []struct {
desc string
opts Option
wantIAMAuthN bool
}{
{
desc: "When Credentials are provided with IAM Authn ENABLED",
opts: WithOptions(
WithIAMAuthN(),
WithCredentialsJSON(fakeServiceAccount("")),
),
wantIAMAuthN: true,
},
{
desc: "When Credentials are provided with IAM Authn DISABLED",
opts: WithCredentialsJSON(fakeServiceAccount("")),
wantIAMAuthN: false,
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
d, err := NewDialer(context.Background(), tc.opts)
if err != nil {
t.Fatalf("NewDialer failed with error = %v", err)
}
if gotIAMAuthN := d.defaultDialConfig.useIAMAuthN; gotIAMAuthN != tc.wantIAMAuthN {
t.Fatalf("want = %v, got = %v", tc.wantIAMAuthN, gotIAMAuthN)
}
})
}
}
func TestSQLServerFailsOnIAMAuthN(t *testing.T) {
inst := mock.NewFakeCSQLInstance("proj", "region", "inst",
mock.WithEngineVersion("SQLSERVER"),
)
d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
dialerOptions: []Option{
WithIAMAuthNTokenSources(
mock.EmptyTokenSource{},
mock.EmptyTokenSource{},
), WithIAMAuthN(),
},
skipVerify: true,
})
_, err := d.Dial(context.Background(), inst.String())
if err == nil {
t.Fatalf("version = %v, want error, got nil", "SQLSERVER")
}
}
func TestUniverseDomain(t *testing.T) {
tcs := []struct {
desc string
opts Option
}{
{
desc: "When universe domain matches GDU",
opts: WithOptions(
WithUniverseDomain("googleapis.com"),
WithCredentialsJSON(fakeServiceAccount("")),
),
},
{
desc: "When TPC universe matches TPC credential domain",
opts: WithOptions(
WithUniverseDomain("test-universe.test"),
WithCredentialsJSON(fakeServiceAccount("test-universe.test")),
),
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
_, err := NewDialer(context.Background(), tc.opts)
if err != nil {
t.Fatalf("NewDialer failed with error = %v", err)
}
})
}
}
func TestUniverseDomainErrors(t *testing.T) {
tcs := []struct {
desc string
opts Option
}{
{
desc: "When universe domain does not match ADC credentials from GDU",
opts: WithOptions(WithUniverseDomain("test-universe.test")),
},
{
desc: "When GDU does not match credential domain",
opts: WithOptions(WithCredentialsJSON(
fakeServiceAccount("test-universe.test"),
)),
},
{
desc: "WithUniverseDomain used alongside WithAdminAPIEndpoint",
opts: WithOptions(
WithUniverseDomain("googleapis.com"),
WithAdminAPIEndpoint("https://sqladmin.googleapis.com"),
),
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
_, err := NewDialer(context.Background(), tc.opts)
t.Log(err)
if err == nil {
t.Fatalf("Wanted universe domain mismatch, want error, got nil")
}
})
}
}
func TestDialerWithCustomDialFunc(t *testing.T) {
inst := mock.NewFakeCSQLInstance("proj", "region", "inst",
mock.WithEngineVersion("SQLSERVER"),
)
d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
dialerOptions: []Option{
WithTokenSource(mock.EmptyTokenSource{}),
WithDialFunc(func(context.Context, string, string) (net.Conn, error) {
return nil, errors.New("sentinel error")
}),
},
})
_, err := d.Dial(context.Background(), inst.String())
if !strings.Contains(err.Error(), "sentinel error") {
t.Fatalf("want = sentinel error, got = %v", err)
}
}
func TestDialerEngineVersion(t *testing.T) {
tests := []string{
"MYSQL_5_7", "POSTGRES_14", "SQLSERVER_2019_STANDARD", "MYSQL_8_0_18",
}
for _, wantEV := range tests {
t.Run(wantEV, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
inst := mock.NewFakeCSQLInstance(
"my-project", "my-region", "my-instance",
mock.WithEngineVersion(wantEV),
)
d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
dialerOptions: []Option{
WithTokenSource(mock.EmptyTokenSource{}),
},
})
gotEV, err := d.EngineVersion(ctx, inst.String())
if err != nil {
t.Fatalf("failed to retrieve engine version: %v", err)
}
if wantEV != gotEV {
t.Errorf(
"InstanceEngineVersion(%s) failed: want %v, got %v",
wantEV, gotEV, err,
)
}
})
}
}
// When Auto IAM AuthN is enabled, EngineVersion should warm the cache with a
// client certificate with Auto IAM AuthN enabled.
func TestEngineVersionAvoidsDuplicateRefreshWithIAMAuthN(t *testing.T) {
inst := mock.NewFakeCSQLInstance(
"my-project", "my-region", "my-instance",
)
d := setupDialer(t, setupConfig{
testInstance: inst,
dialerOptions: []Option{
WithIAMAuthN(), WithIAMAuthNTokenSources(
mock.EmptyTokenSource{},
mock.EmptyTokenSource{},
),
},
reqs: []*mock.Request{
// There should only be two API requests
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
})
_, err := d.EngineVersion(context.Background(), inst.String())
if err != nil {
t.Fatal(err)
}
testSuccessfulDial(
context.Background(), t, d,
inst.String(),
)
}
func TestEngineVersionRemovesInvalidInstancesFromCache(t *testing.T) {
// When a dialer attempts to call EngineVersion for a
// non-existent instance, it should delete the instance from
// the cache and ensure no background refresh happens (which would be
// wasted cycles).
d, err := NewDialer(
context.Background(),
WithTokenSource(mock.EmptyTokenSource{}),
)
if err != nil {
t.Fatalf("expected NewDialer to succeed, but got error: %v", err)
}
// Populate instance map with connection info cache that will always fail
// This allows the test to verify the error case path invoking close.
badInstanceConnectionName := "doesntexist:us-central1:doesntexist"
tcs := []struct {
desc string
icn string
resp connectionInfoResp
opts []DialOption
}{
{
desc: "EngineVersion on a bad instance URI",
icn: badInstanceConnectionName,
resp: connectionInfoResp{
err: errors.New("connect info failed"),
},
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
// Manually populate the internal cache with a spy
inst, _ := instance.ParseConnName(tc.icn)
spy := &spyConnectionInfoCache{
connectInfoCalls: []connectionInfoResp{tc.resp},
}
d.cache[createKey(inst)] = newMonitoredCache(nil, spy, inst, 0, nil, nil)
_, err = d.EngineVersion(context.Background(), tc.icn)
if err == nil {
t.Fatal("expected EngineVersion to return error")
}
// Verify that the connection info cache was closed (to prevent
// further failed refresh operations)
if got, want := spy.closeWasCalled(), true; got != want {
t.Fatal("Close was not called")
}
// Now verify that bad connection name has been deleted from map.
d.lock.RLock()
_, ok := d.cache[createKey(inst)]
d.lock.RUnlock()
if ok {
t.Fatal("connection info was not removed from cache")
}
})
}
}
func TestDialerUserAgent(t *testing.T) {
data, err := os.ReadFile("version.txt")
if err != nil {
t.Fatalf("failed to read version.txt: %v", err)
}
ver := strings.TrimSpace(string(data))
want := "cloud-sql-go-connector/" + ver
if want != userAgent {
t.Errorf("embed version mismatched: want %q, got %q", want, userAgent)
}
}
func TestWarmup(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
inst := mock.NewFakeCSQLInstance("my-project", "my-region", "my-instance")
tests := []struct {
desc string
warmupOpts []DialOption
dialOpts []DialOption
expectedCalls []*mock.Request
}{
{
desc: "Warmup and Dial both use IAM AuthN",
warmupOpts: []DialOption{WithDialIAMAuthN(true)},
dialOpts: []DialOption{WithDialIAMAuthN(true)},
expectedCalls: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
},
{
desc: "Warmup uses IAM Authn, Dial does not",
warmupOpts: []DialOption{WithDialIAMAuthN(true)},
dialOpts: []DialOption{WithDialIAMAuthN(false)},
expectedCalls: []*mock.Request{
mock.InstanceGetSuccess(inst, 2),
mock.CreateEphemeralSuccess(inst, 2),
},
},
{
desc: "Warmup uses IAM AuthN, Dial uses global setting",
warmupOpts: []DialOption{WithDialIAMAuthN(true)},
dialOpts: []DialOption{},
expectedCalls: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
d := setupDialer(t, setupConfig{
dialerOptions: []Option{
WithIAMAuthN(),
WithIAMAuthNTokenSources(
mock.EmptyTokenSource{},
mock.EmptyTokenSource{},
),
},
testInstance: inst,
reqs: test.expectedCalls,
})
// Warmup once with the "default" options
err := d.Warmup(ctx, inst.String(), test.warmupOpts...)
if err != nil {
t.Fatalf("Warmup failed: %v", err)
}
// Call EngineVersion to make sure we block until both API calls
// are completed.
_, err = d.EngineVersion(ctx, inst.String())
if err != nil {
t.Fatalf("Warmup failed: %v", err)
}
// Dial once with the "dial" options
testSuccessfulDial(
ctx, t, d,
inst.String(),
test.dialOpts...,
)
})
}
}
func TestWarmupRemovesInvalidInstancesFromCache(t *testing.T) {
// When a dialer attempts to Warmup for a non-existent instance,
// it should delete the instance from the cache and ensure no background
// refresh happens (which would be wasted cycles).
d, err := NewDialer(
context.Background(),
WithTokenSource(mock.EmptyTokenSource{}),
)
if err != nil {
t.Fatalf("expected NewDialer to succeed, but got error: %v", err)
}
// Populate instance map with connection info cache that will always fail
// This allows the test to verify the error case path invoking close.
badInstanceConnectionName := "doesntexist:us-central1:doesntexist"
tcs := []struct {
desc string
icn string
resp connectionInfoResp
opts []DialOption
}{
{
desc: "warmup a bad instance URI",
icn: badInstanceConnectionName,
resp: connectionInfoResp{
err: errors.New("connect info failed"),
},
opts: []DialOption{WithDialIAMAuthN(true)},
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
// Manually populate the internal cache with a spy
inst, _ := instance.ParseConnName(tc.icn)
spy := &spyConnectionInfoCache{
connectInfoCalls: []connectionInfoResp{tc.resp},
}
d.cache[createKey(inst)] = newMonitoredCache(nil, spy, inst, 0, nil, nil)
err = d.Warmup(context.Background(), tc.icn, tc.opts...)
if err == nil {
t.Fatal("expected Warmup to return error")
}
// Verify that the connection info cache was closed (to prevent
// further failed refresh operations)
if got, want := spy.closeWasCalled(), true; got != want {
t.Fatal("Close was not called")
}
// Now verify that bad connection name has been deleted from map.
d.lock.RLock()
_, ok := d.cache[createKey(inst)]
d.lock.RUnlock()
if ok {
t.Fatal("connection info was not removed from cache")
}
})
}
}
func TestDialDialerOptsConflicts(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
inst := mock.NewFakeCSQLInstance("my-project", "my-region", "my-instance")
tests := []struct {
desc string
dialerOpts []Option
dialOpts []DialOption
expectedCalls []*mock.Request
}{
{
desc: "dialer opts set and dial uses default",
dialerOpts: []Option{WithIAMAuthN()},
dialOpts: []DialOption{},
expectedCalls: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
},
{
desc: "dialer and dial opts are the same",
dialerOpts: []Option{WithIAMAuthN()},
dialOpts: []DialOption{WithDialIAMAuthN(true)},
expectedCalls: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},
},
{
desc: "dialer and dial opts are different",
dialerOpts: []Option{WithIAMAuthN()},
dialOpts: []DialOption{WithDialIAMAuthN(false)},
expectedCalls: []*mock.Request{
mock.InstanceGetSuccess(inst, 2),
mock.CreateEphemeralSuccess(inst, 2),
},
},
}
for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: tc.expectedCalls,
dialerOptions: append(
tc.dialerOpts,
WithIAMAuthNTokenSources(
mock.EmptyTokenSource{}, mock.EmptyTokenSource{},
),
),
})
// Dial once with the "default" options
testSuccessfulDial(ctx, t, d, inst.String())
// Dial once with the "dial" options
testSuccessfulDial(ctx, t, d, inst.String(), tc.dialOpts...)
})
}
}
func TestTokenSourceWithIAMAuthN(t *testing.T) {
ts := oauth2.StaticTokenSource(&oauth2.Token{})
tcs := []struct {
desc string
opts []Option
wantErr bool
}{
{
desc: "when token source is set with IAM AuthN",
opts: []Option{WithTokenSource(ts), WithIAMAuthN()},
wantErr: true,
},
{
desc: "when IAM AuthN token source is set without IAM AuthN",
opts: []Option{WithIAMAuthNTokenSources(ts, ts)},
wantErr: true,
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
_, err := NewDialer(context.Background(), tc.opts...)
gotErr := err != nil
if tc.wantErr != gotErr {
t.Fatalf("err: want = %v, got = %v", tc.wantErr, gotErr)
}
})
}
}
func TestDialerRemovesInvalidInstancesFromCache(t *testing.T) {
// When a dialer attempts to retrieve connection info for a
// non-existent instance, it should delete the instance from
// the cache and ensure no background refresh happens (which would be
// wasted cycles).
d, err := NewDialer(
context.Background(),
WithTokenSource(mock.EmptyTokenSource{}),
)
if err != nil {
t.Fatalf("expected NewDialer to succeed, but got error: %v", err)
}
// Populate instance map with connection info cache that will always fail
// This allows the test to verify the error case path invoking close.
badInstanceConnectionName := "doesntexist:us-central1:doesntexist"
tcs := []struct {
desc string
icn string
resp connectionInfoResp
opts []DialOption
}{
{
desc: "dialing a bad instance URI",
icn: badInstanceConnectionName,
resp: connectionInfoResp{
err: errors.New("connect info failed"),
},
},
{
desc: "specifying an invalid IP type",
icn: "myproject:myregion:myinstance",
resp: connectionInfoResp{
info: cloudsql.NewConnectionInfo(
instance.ConnName{},
"",
"GOOGLE_MANAGED_INTERNAL_CA",
"",
map[string]string{
// no public IP
cloudsql.PrivateIP: "10.0.0.1",
},
nil,
tls.Certificate{Leaf: &x509.Certificate{
NotAfter: time.Now().Add(time.Hour),
}},
),
},
opts: []DialOption{WithPublicIP()},
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
// Manually populate the internal cache with a spy
inst, _ := instance.ParseConnName(tc.icn)
spy := &spyConnectionInfoCache{
connectInfoCalls: []connectionInfoResp{tc.resp},
}
d.cache[createKey(inst)] = newMonitoredCache(nil, spy, inst, 0, nil, nil)
_, err = d.Dial(context.Background(), tc.icn, tc.opts...)
if err == nil {
t.Fatal("expected Dial to return error")
}
// Verify that the connection info cache was closed (to prevent
// further failed refresh operations)
if got, want := spy.closeWasCalled(), true; got != want {
t.Fatal("Close was not called")
}
// Now verify that bad connection name has been deleted from map.
d.lock.RLock()
_, ok := d.cache[createKey(inst)]
d.lock.RUnlock()
if ok {
t.Fatal("connection info was not removed from cache")
}
})
}
}
func TestDialRefreshesExpiredCertificates(t *testing.T) {
d, err := NewDialer(context.Background(),
WithTokenSource(mock.EmptyTokenSource{}),
)
if err != nil {
t.Fatalf("expected NewDialer to succeed, but got error: %v", err)
}
sentinel := errors.New("connect info failed")
icn := "project:region:instance"
cn, _ := instance.ParseConnName(icn)
spy := &spyConnectionInfoCache{
connectInfoCalls: []connectionInfoResp{
// First call returns expired certificate
{
// Certificate expired 10 hours ago.
info: cloudsql.ConnectionInfo{
Expiration: time.Now().Add(-10 * time.Hour),
},
},
// Second call errors to validate error path
{
err: sentinel,
},
},
}
d.cache[createKey(cn)] = newMonitoredCache(nil, spy, cn, 0, nil, nil)
_, err = d.Dial(context.Background(), icn)
if !errors.Is(err, sentinel) {
t.Fatalf("expected Dial to return sentinel error, instead got = %v", err)
}
// Verify that the cache was refreshed
if got, want := spy.forceRefreshWasCalled(), true; got != want {
t.Fatal("ForceRefresh was not called")
}
// Verify that the connection info cache was closed (to prevent
// further failed refresh operations)
if got, want := spy.closeWasCalled(), true; got != want {
t.Fatal("Close was not called")
}
// Now verify that bad connection name has been deleted from map.
d.lock.RLock()
_, ok := d.cache[createKey(cn)]
d.lock.RUnlock()
if ok {
t.Fatal("bad instance was not removed from the cache")
}
}
type connectionInfoResp struct {
info cloudsql.ConnectionInfo
err error
}
type spyConnectionInfoCache struct {
mu sync.Mutex
connectInfoIndex int
connectInfoCalls []connectionInfoResp
closed bool
forceRefreshed bool
// embed interface to avoid having to implement irrelevant methods
connectionInfoCache
}
func (s *spyConnectionInfoCache) ConnectionInfo(
context.Context,
) (cloudsql.ConnectionInfo, error) {
s.mu.Lock()
defer s.mu.Unlock()
res := s.connectInfoCalls[s.connectInfoIndex]
s.connectInfoIndex++
return res.info, res.err
}
func (s *spyConnectionInfoCache) ForceRefresh() {
s.mu.Lock()
defer s.mu.Unlock()
s.forceRefreshed = true
}
func (s *spyConnectionInfoCache) UpdateRefresh(*bool) {}
func (s *spyConnectionInfoCache) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
s.closed = true
return nil
}
func (s *spyConnectionInfoCache) closeWasCalled() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed
}
func (s *spyConnectionInfoCache) forceRefreshWasCalled() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.forceRefreshed
}
func TestDialerSupportsOneOffDialFunction(t *testing.T) {
ctx := context.Background()
inst := mock.NewFakeCSQLInstance("p", "r", "i")
svc, cleanup, err := mock.NewSQLAdminService(
context.Background(),
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
)
if err != nil {
t.Fatalf("failed to init SQLAdminService: %v", err)
}
d, err := NewDialer(ctx, WithTokenSource(mock.EmptyTokenSource{}))
if err != nil {
t.Fatal(err)
}
d.sqladmin = svc
defer func() {
if err := d.Close(); err != nil {
t.Log(err)
}
_ = cleanup()
}()
sentinelErr := errors.New("dial func was called")
f := func(context.Context, string, string) (net.Conn, error) {
return nil, sentinelErr
}
if _, err := d.Dial(ctx, "p:r:i", WithOneOffDialFunc(f)); !errors.Is(err, sentinelErr) {
t.Fatal("one-off dial func was not called")
}
}
func TestDialerCloseReportsFriendlyError(t *testing.T) {
d, err := NewDialer(
context.Background(),
WithTokenSource(mock.EmptyTokenSource{}),
)
if err != nil {
t.Fatal(err)
}
_ = d.Close()
_, err = d.Dial(context.Background(), "p:r:i")
if !errors.Is(err, ErrDialerClosed) {
t.Fatalf("want = %v, got = %v", ErrDialerClosed, err)
}
// Ensure multiple calls to close don't panic
_ = d.Close()
_, err = d.Dial(context.Background(), "p:r:i")
if !errors.Is(err, ErrDialerClosed) {
t.Fatalf("want = %v, got = %v", ErrDialerClosed, err)
}
}
func TestDialerInitializesLazyCache(t *testing.T) {
cn, _ := instance.ParseConnName("my-project:my-region:my-instance")
inst := mock.NewFakeCSQLInstance(
cn.Project(), cn.Region(), cn.Name(),
)
d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},