forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiclient_test.go
1434 lines (1308 loc) · 40.9 KB
/
apiclient_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 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package api_test
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/juju/clock"
"github.com/juju/clock/testclock"
"github.com/juju/errors"
proxyutils "github.com/juju/proxy"
"github.com/juju/testing"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/api"
apitesting "github.com/juju/juju/api/testing"
"github.com/juju/juju/apiserver/params"
apiservertesting "github.com/juju/juju/apiserver/testing"
"github.com/juju/juju/controller"
jjtesting "github.com/juju/juju/juju/testing"
"github.com/juju/juju/network"
"github.com/juju/juju/rpc"
"github.com/juju/juju/rpc/jsoncodec"
jtesting "github.com/juju/juju/testing"
"github.com/juju/juju/utils/proxy"
jujuversion "github.com/juju/juju/version"
)
type apiclientSuite struct {
jjtesting.JujuConnSuite
}
var _ = gc.Suite(&apiclientSuite{})
func (s *apiclientSuite) TestDialAPIToModel(c *gc.C) {
info := s.APIInfo(c)
conn, location, err := api.DialAPI(info, api.DialOpts{})
c.Assert(err, jc.ErrorIsNil)
defer conn.Close()
assertConnAddrForModel(c, location, info.Addrs[0], s.State.ModelUUID())
}
func (s *apiclientSuite) TestDialAPIToRoot(c *gc.C) {
info := s.APIInfo(c)
info.ModelTag = names.NewModelTag("")
conn, location, err := api.DialAPI(info, api.DialOpts{})
c.Assert(err, jc.ErrorIsNil)
defer conn.Close()
assertConnAddrForRoot(c, location, info.Addrs[0])
}
func (s *apiclientSuite) TestDialAPIMultiple(c *gc.C) {
// Create a socket that proxies to the API server.
info := s.APIInfo(c)
serverAddr := info.Addrs[0]
proxy := testing.NewTCPProxy(c, serverAddr)
defer proxy.Close()
// Check that we can use the proxy to connect.
info.Addrs = []string{proxy.Addr()}
conn, location, err := api.DialAPI(info, api.DialOpts{})
c.Assert(err, jc.ErrorIsNil)
conn.Close()
assertConnAddrForModel(c, location, proxy.Addr(), s.State.ModelUUID())
// Now break Addrs[0], and ensure that Addrs[1]
// is successfully connected to.
proxy.Close()
info.Addrs = []string{proxy.Addr(), serverAddr}
conn, location, err = api.DialAPI(info, api.DialOpts{})
c.Assert(err, jc.ErrorIsNil)
conn.Close()
assertConnAddrForModel(c, location, serverAddr, s.State.ModelUUID())
}
func (s *apiclientSuite) TestDialAPIWithProxy(c *gc.C) {
info := s.APIInfo(c)
opts := api.DialOpts{IPAddrResolver: apitesting.IPAddrResolverMap{
"testing.invalid": {"0.1.1.1"},
}}
fakeAddr := "testing.invalid:1234"
// Confirm that the proxy configuration is used. See:
// https://bugs.launchpad.net/juju/+bug/1698989
//
// TODO(axw) use github.com/elazarl/goproxy set up a real
// forward proxy, and confirm that we can dial a successful
// connection.
handler := func(w http.ResponseWriter, r *http.Request) {
if r.Method != "CONNECT" {
http.Error(w, fmt.Sprintf("invalid method %s", r.Method), http.StatusMethodNotAllowed)
return
}
if r.URL.Host != fakeAddr {
http.Error(w, fmt.Sprintf("unexpected host %s", r.URL.Host), http.StatusBadRequest)
return
}
http.Error(w, "🍵", http.StatusTeapot)
}
proxyServer := httptest.NewServer(http.HandlerFunc(handler))
defer proxyServer.Close()
err := proxy.DefaultConfig.Set(proxyutils.Settings{
Https: proxyServer.Listener.Addr().String(),
})
c.Assert(err, jc.ErrorIsNil)
defer proxy.DefaultConfig.Set(proxyutils.Settings{})
// Check that we can use the proxy to connect.
info.Addrs = []string{fakeAddr}
_, _, err = api.DialAPI(info, opts)
c.Assert(err, gc.ErrorMatches, "unable to connect to API: I'm a teapot")
}
func (s *apiclientSuite) TestDialAPIMultipleError(c *gc.C) {
var addrs []string
// count holds the number of times we've accepted a connection.
var count int32
for i := 0; i < 3; i++ {
listener, err := net.Listen("tcp", "127.0.0.1:0")
c.Assert(err, jc.ErrorIsNil)
defer listener.Close()
addrs = append(addrs, listener.Addr().String())
go func() {
for {
client, err := listener.Accept()
if err != nil {
return
}
atomic.AddInt32(&count, 1)
client.Close()
}
}()
}
info := s.APIInfo(c)
info.Addrs = addrs
_, _, err := api.DialAPI(info, api.DialOpts{})
c.Assert(err, gc.ErrorMatches, `unable to connect to API: .*`)
c.Assert(atomic.LoadInt32(&count), gc.Equals, int32(3))
}
func (s *apiclientSuite) TestVerifyCA(c *gc.C) {
decodedCACert, _ := pem.Decode([]byte(jtesting.CACert))
serverCertWithoutCA, _ := tls.X509KeyPair([]byte(jtesting.ServerCert), []byte(jtesting.ServerKey))
serverCertWithSelfSignedCA, _ := tls.X509KeyPair([]byte(jtesting.ServerCert), []byte(jtesting.ServerKey))
serverCertWithSelfSignedCA.Certificate = append(serverCertWithSelfSignedCA.Certificate, decodedCACert.Bytes)
specs := []struct {
descr string
serverCert tls.Certificate
verifyCA func(host, endpoint string, caCert *x509.Certificate) error
expConnCount int32
errRegex string
}{
{
descr: "VerifyCA provided but server does not present a CA cert",
serverCert: serverCertWithoutCA,
verifyCA: func(host, endpoint string, caCert *x509.Certificate) error {
return errors.New("VerifyCA should not be called")
},
// Dial tries to fetch CAs, doesn't find any and
// proceeds with the connection to the servers. This
// would be the case where we connect to an older juju
// controller.
expConnCount: 2,
errRegex: `unable to connect to API: .*`,
},
{
descr: "no VerifyCA provided",
serverCert: serverCertWithSelfSignedCA,
// Dial connects to all servers
expConnCount: 1,
errRegex: `unable to connect to API: .*`,
},
{
descr: "VerifyCA that always rejects certs",
serverCert: serverCertWithSelfSignedCA,
verifyCA: func(host, endpoint string, caCert *x509.Certificate) error {
return errors.New("CA not trusted")
},
// Dial aborts after fetching CAs
expConnCount: 1,
errRegex: "CA not trusted",
},
{
descr: "VerifyCA that always accepts certs",
serverCert: serverCertWithSelfSignedCA,
verifyCA: func(host, endpoint string, caCert *x509.Certificate) error {
return nil
},
// Dial fetches CAs and then proceeds with the connection to the servers
expConnCount: 2,
errRegex: `unable to connect to API: .*`,
},
}
info := s.APIInfo(c)
for specIndex, spec := range specs {
c.Logf("test %d: %s", specIndex, spec.descr)
// connCount holds the number of times we've accepted a connection.
var connCount int32
tlsConf := &tls.Config{
Certificates: []tls.Certificate{spec.serverCert},
}
listener, err := tls.Listen("tcp", "127.0.0.1:0", tlsConf)
c.Assert(err, jc.ErrorIsNil)
defer listener.Close()
go func() {
buf := make([]byte, 4)
for {
client, err := listener.Accept()
if err != nil {
return
}
atomic.AddInt32(&connCount, 1)
// Do a dummy read to prevent the connection from
// closing before the client can access the certs.
_, _ = client.Read(buf)
_ = client.Close()
}
}()
atomic.StoreInt32(&connCount, 0)
info.Addrs = []string{listener.Addr().String()}
_, _, err = api.DialAPI(info, api.DialOpts{
VerifyCA: spec.verifyCA,
})
c.Assert(err, gc.ErrorMatches, spec.errRegex)
c.Assert(atomic.LoadInt32(&connCount), gc.Equals, spec.expConnCount)
}
}
func (s *apiclientSuite) TestOpen(c *gc.C) {
info := s.APIInfo(c)
st, err := api.Open(info, api.DialOpts{})
c.Assert(err, jc.ErrorIsNil)
defer st.Close()
c.Assert(st.Addr(), gc.Equals, info.Addrs[0])
modelTag, ok := st.ModelTag()
c.Assert(ok, jc.IsTrue)
c.Assert(modelTag, gc.Equals, s.Model.ModelTag())
remoteVersion, versionSet := st.ServerVersion()
c.Assert(versionSet, jc.IsTrue)
c.Assert(remoteVersion, gc.Equals, jujuversion.Current)
}
func (s *apiclientSuite) TestOpenHonorsModelTag(c *gc.C) {
info := s.APIInfo(c)
// TODO(jam): 2014-06-05 http://pad.lv/1326802
// we want to test this eventually, but for now s.APIInfo uses
// conn.StateInfo() which doesn't know about ModelTag.
// c.Check(info.ModelTag, gc.Equals, model.Tag())
// c.Assert(info.ModelTag, gc.Not(gc.Equals), "")
// We start by ensuring we have an invalid tag, and Open should fail.
info.ModelTag = names.NewModelTag("0b501e7e-cafe-f00d-ba1d-b1a570c0e199")
_, err := api.Open(info, api.DialOpts{})
c.Assert(errors.Cause(err), gc.DeepEquals, &rpc.RequestError{
Message: `unknown model: "0b501e7e-cafe-f00d-ba1d-b1a570c0e199"`,
Code: "model not found",
})
c.Check(params.ErrCode(err), gc.Equals, params.CodeModelNotFound)
// Now set it to the right tag, and we should succeed.
info.ModelTag = s.Model.ModelTag()
st, err := api.Open(info, api.DialOpts{})
c.Assert(err, jc.ErrorIsNil)
st.Close()
// Backwards compatibility, we should succeed if we do not set an
// model tag
info.ModelTag = names.NewModelTag("")
st, err = api.Open(info, api.DialOpts{})
c.Assert(err, jc.ErrorIsNil)
st.Close()
}
func (s *apiclientSuite) TestServerRoot(c *gc.C) {
url := api.ServerRoot(s.APIState.Client())
c.Assert(url, gc.Matches, "https://localhost:[0-9]+")
}
func (s *apiclientSuite) TestDialWebsocketStopsOtherDialAttempts(c *gc.C) {
// Try to open the API with two addresses.
// Wait for connection attempts to both.
// Let one succeed.
// Wait for the other to be canceled.
type dialResponse struct {
conn jsoncodec.JSONConn
}
type dialInfo struct {
ctx context.Context
location string
replyc chan<- dialResponse
}
dialed := make(chan dialInfo)
fakeDialer := func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error) {
reply := make(chan dialResponse)
dialed <- dialInfo{
ctx: ctx,
location: urlStr,
replyc: reply,
}
r := <-reply
return r.conn, nil
}
conn0 := fakeConn{}
clock := testclock.NewClock(time.Now())
openDone := make(chan struct{})
const dialAddressInterval = 50 * time.Millisecond
go func() {
defer close(openDone)
conn, err := api.Open(&api.Info{
Addrs: []string{
"place1.example:1234",
"place2.example:1234",
},
SkipLogin: true,
CACert: jtesting.CACert,
}, api.DialOpts{
Timeout: 5 * time.Second,
RetryDelay: 1 * time.Second,
DialAddressInterval: dialAddressInterval,
DialWebsocket: fakeDialer,
Clock: clock,
IPAddrResolver: apitesting.IPAddrResolverMap{
"place1.example": {"0.1.1.1"},
"place2.example": {"0.2.2.2"},
},
})
c.Check(api.UnderlyingConn(conn), gc.Equals, conn0)
c.Check(err, jc.ErrorIsNil)
}()
place1 := "wss://place1.example:1234/api"
place2 := "wss://place2.example:1234/api"
// Wait for first connection, but don't
// reply immediately because we want
// to wait for the second connection before
// letting the first one succeed.
var info0 dialInfo
select {
case info0 = <-dialed:
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for dial")
}
this := place1
other := place2
if info0.location != place1 {
// We now randomly order what we will connect to. So we check
// whether we first tried to connect to place1 or place2.
// However, we should still be able to interrupt a second dial by
// having the first one succeed.
this = place2
other = place1
}
c.Assert(info0.location, gc.Equals, this)
var info1 dialInfo
// Wait for the next dial to be made. Note that we wait for two
// waiters because ContextWithTimeout as created by the
// outer level of api.Open also waits.
err := clock.WaitAdvance(dialAddressInterval, time.Second, 2)
c.Assert(err, jc.ErrorIsNil)
select {
case info1 = <-dialed:
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for dial")
}
c.Assert(info1.location, gc.Equals, other)
// Allow the first dial to succeed.
info0.replyc <- dialResponse{
conn: conn0,
}
// The Open returns immediately without waiting
// for the second dial to complete.
select {
case <-openDone:
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for connection")
}
// The second dial's context is canceled to tell
// it to stop.
select {
case <-info1.ctx.Done():
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for context to be closed")
}
conn1 := fakeConn{
closed: make(chan struct{}),
}
// Allow the second dial to succeed.
info1.replyc <- dialResponse{
conn: conn1,
}
// Check that the connection it returns is closed.
select {
case <-conn1.closed:
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for connection to be closed")
}
}
type apiDialInfo struct {
location string
hasRootCAs bool
serverName string
}
var openWithSNIHostnameTests = []struct {
about string
info *api.Info
expectDial apiDialInfo
}{{
about: "no cert; DNS name - use SNI hostname",
info: &api.Info{
Addrs: []string{"foo.com:1234"},
SNIHostName: "foo.com",
SkipLogin: true,
},
expectDial: apiDialInfo{
location: "wss://foo.com:1234/api",
hasRootCAs: false,
serverName: "foo.com",
},
}, {
about: "no cert; numeric IP address - use SNI hostname",
info: &api.Info{
Addrs: []string{"0.1.2.3:1234"},
SNIHostName: "foo.com",
SkipLogin: true,
},
expectDial: apiDialInfo{
location: "wss://0.1.2.3:1234/api",
hasRootCAs: false,
serverName: "foo.com",
},
}, {
about: "with cert; DNS name - use cert",
info: &api.Info{
Addrs: []string{"0.1.1.1:1234"},
SNIHostName: "foo.com",
SkipLogin: true,
CACert: jtesting.CACert,
},
expectDial: apiDialInfo{
location: "wss://0.1.1.1:1234/api",
hasRootCAs: true,
serverName: "juju-apiserver",
},
}, {
about: "with cert; numeric IP address - use cert",
info: &api.Info{
Addrs: []string{"0.1.2.3:1234"},
SNIHostName: "foo.com",
SkipLogin: true,
CACert: jtesting.CACert,
},
expectDial: apiDialInfo{
location: "wss://0.1.2.3:1234/api",
hasRootCAs: true,
serverName: "juju-apiserver",
},
}}
func (s *apiclientSuite) TestOpenWithSNIHostname(c *gc.C) {
for i, test := range openWithSNIHostnameTests {
c.Logf("test %d: %v", i, test.about)
s.testOpenDialError(c, dialTest{
apiInfo: test.info,
expectOpenError: `unable to connect to API: nope`,
expectDials: []dialAttempt{{
check: func(info dialInfo) {
c.Check(info.location, gc.Equals, test.expectDial.location)
c.Assert(info.tlsConfig, gc.NotNil)
c.Check(info.tlsConfig.RootCAs != nil, gc.Equals, test.expectDial.hasRootCAs)
c.Check(info.tlsConfig.ServerName, gc.Equals, test.expectDial.serverName)
},
returnError: errors.New("nope"),
}},
allowMoreDials: true,
})
}
}
func (s *apiclientSuite) TestFallbackToSNIHostnameOnCertErrorAndNonNumericHostname(c *gc.C) {
s.testOpenDialError(c, dialTest{
apiInfo: &api.Info{
Addrs: []string{"x.com:1234"},
CACert: jtesting.CACert,
SNIHostName: "foo.com",
},
// go 1.9 says "is not authorized to sign for this name"
// go 1.10 says "is not authorized to sign for this domain"
expectOpenError: `unable to connect to API: x509: a root or intermediate certificate is not authorized to sign.*`,
expectDials: []dialAttempt{{
// The first dial attempt should use the private CA cert.
check: func(info dialInfo) {
c.Assert(info.tlsConfig, gc.NotNil)
c.Check(info.tlsConfig.RootCAs.Subjects(), gc.HasLen, 1)
c.Check(info.tlsConfig.ServerName, gc.Equals, "juju-apiserver")
},
returnError: x509.CertificateInvalidError{
Reason: x509.CANotAuthorizedForThisName,
},
}, {
// The second dial attempt should fall back to using the
// SNI hostname.
check: func(info dialInfo) {
c.Assert(info.tlsConfig, gc.NotNil)
c.Check(info.tlsConfig.RootCAs, gc.IsNil)
c.Check(info.tlsConfig.ServerName, gc.Equals, "foo.com")
},
// Note: we return another certificate error so that
// the Open logic returns immediately rather than waiting
// for the timeout.
returnError: x509.SystemRootsError{},
}},
})
}
func (s *apiclientSuite) TestFailImmediatelyOnCertErrorAndNumericHostname(c *gc.C) {
s.testOpenDialError(c, dialTest{
apiInfo: &api.Info{
Addrs: []string{"0.1.2.3:1234"},
CACert: jtesting.CACert,
},
// go 1.9 says "is not authorized to sign for this name"
// go 1.10 says "is not authorized to sign for this domain"
expectOpenError: `unable to connect to API: x509: a root or intermediate certificate is not authorized to sign.*`,
expectDials: []dialAttempt{{
// The first dial attempt should use the private CA cert.
check: func(info dialInfo) {
c.Assert(info.tlsConfig, gc.NotNil)
c.Check(info.tlsConfig.RootCAs.Subjects(), gc.HasLen, 1)
c.Check(info.tlsConfig.ServerName, gc.Equals, "juju-apiserver")
},
returnError: x509.CertificateInvalidError{
Reason: x509.CANotAuthorizedForThisName,
},
}},
})
}
type dialTest struct {
apiInfo *api.Info
// expectDials holds an entry for each dial
// attempt that's expected to be made.
// If allowMoreDials is true, any number of
// attempts will be allowed and the last entry
// of expectDials will be used when the
// number exceeds
expectDials []dialAttempt
allowMoreDials bool
expectOpenError string
}
type dialAttempt struct {
check func(info dialInfo)
returnError error
}
type dialInfo struct {
location string
tlsConfig *tls.Config
errc chan<- error
}
func (s *apiclientSuite) testOpenDialError(c *gc.C, t dialTest) {
dialed := make(chan dialInfo)
fakeDialer := func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error) {
reply := make(chan error)
dialed <- dialInfo{
location: urlStr,
tlsConfig: tlsConfig,
errc: reply,
}
return nil, <-reply
}
done := make(chan struct{})
go func() {
defer close(done)
conn, err := api.Open(t.apiInfo, api.DialOpts{
DialWebsocket: fakeDialer,
IPAddrResolver: seqResolver(t.apiInfo.Addrs...),
Clock: &fakeClock{},
})
c.Check(conn, gc.Equals, nil)
c.Check(err, gc.ErrorMatches, t.expectOpenError)
}()
for i := 0; t.allowMoreDials || i < len(t.expectDials); i++ {
c.Logf("attempt %d", i)
var attempt dialAttempt
if i < len(t.expectDials) {
attempt = t.expectDials[i]
} else if t.allowMoreDials {
attempt = t.expectDials[len(t.expectDials)-1]
} else {
break
}
select {
case info := <-dialed:
attempt.check(info)
info.errc <- attempt.returnError
case <-done:
if i < len(t.expectDials) {
c.Fatalf("Open returned early - expected dials not made")
}
return
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for dial")
}
}
select {
case <-done:
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for API open")
}
}
func (s *apiclientSuite) TestOpenWithNoCACert(c *gc.C) {
// This is hard to test as we have no way of affecting the system roots,
// so instead we check that the error that we get implies that
// we're using the system roots.
info := s.APIInfo(c)
info.CACert = ""
// This test used to use a long timeout so that we can check that the retry
// logic doesn't retry, but that got all messed up with dualstack IPs.
// The api server was only listening on IPv4, but localhost resolved to both
// IPv4 and IPv6. The IPv4 didn't retry, but the IPv6 one did, because it was
// retrying the dial. The parallel try doesn't have a fatal error type yet.
_, err := api.Open(info, api.DialOpts{
Timeout: 2 * time.Second,
RetryDelay: 200 * time.Millisecond,
})
c.Assert(err, gc.ErrorMatches, `unable to connect to API: x509: certificate signed by unknown authority`)
}
func (s *apiclientSuite) TestOpenWithRedirect(c *gc.C) {
redirectToHosts := []string{"0.1.2.3:1234", "0.1.2.4:1235"}
redirectToCACert := "fake CA cert"
srv := apiservertesting.NewAPIServer(func(modelUUID string) interface{} {
return &redirectAPI{
modelUUID: modelUUID,
redirectToHosts: redirectToHosts,
redirectToCACert: redirectToCACert,
}
})
defer srv.Close()
_, err := api.Open(&api.Info{
Addrs: srv.Addrs,
CACert: jtesting.CACert,
ModelTag: names.NewModelTag("beef1beef1-0000-0000-000011112222"),
}, api.DialOpts{})
c.Assert(err, gc.ErrorMatches, `redirection to alternative server required`)
hps, _ := network.ParseHostPorts(redirectToHosts...)
c.Assert(errors.Cause(err), jc.DeepEquals, &api.RedirectError{
Servers: [][]network.HostPort{hps},
CACert: redirectToCACert,
FollowRedirect: true,
})
}
func (s *apiclientSuite) TestOpenCachesDNS(c *gc.C) {
fakeDialer := func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error) {
return fakeConn{}, nil
}
dnsCache := make(dnsCacheMap)
conn, err := api.Open(&api.Info{
Addrs: []string{
"place1.example:1234",
},
SkipLogin: true,
CACert: jtesting.CACert,
}, api.DialOpts{
DialWebsocket: fakeDialer,
IPAddrResolver: apitesting.IPAddrResolverMap{
"place1.example": {"0.1.1.1"},
},
DNSCache: dnsCache,
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(conn, gc.NotNil)
c.Assert(dnsCache.Lookup("place1.example"), jc.DeepEquals, []string{"0.1.1.1"})
}
func (s *apiclientSuite) TestDNSCacheUsed(c *gc.C) {
var dialed string
fakeDialer := func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error) {
dialed = ipAddr
return fakeConn{}, nil
}
conn, err := api.Open(&api.Info{
Addrs: []string{
"place1.example:1234",
},
SkipLogin: true,
CACert: jtesting.CACert,
}, api.DialOpts{
DialWebsocket: fakeDialer,
// Note: don't resolve any addresses. If we resolve one,
// then there's a possibility that the resolving will
// happen and a second dial attempt will happen before
// the Open returns, giving rise to a race.
IPAddrResolver: apitesting.IPAddrResolverMap{},
DNSCache: dnsCacheMap{
"place1.example": {"0.1.1.1"},
},
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(conn, gc.NotNil)
// The dialed IP address should have come from the cache, not the IP address
// resolver.
c.Assert(dialed, gc.Equals, "0.1.1.1:1234")
c.Assert(conn.IPAddr(), gc.Equals, "0.1.1.1:1234")
}
func (s *apiclientSuite) TestNumericAddressIsNotAddedToCache(c *gc.C) {
fakeDialer := func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error) {
return fakeConn{}, nil
}
dnsCache := make(dnsCacheMap)
conn, err := api.Open(&api.Info{
Addrs: []string{
"0.1.2.3:1234",
},
SkipLogin: true,
CACert: jtesting.CACert,
}, api.DialOpts{
DialWebsocket: fakeDialer,
IPAddrResolver: apitesting.IPAddrResolverMap{},
DNSCache: dnsCache,
})
c.Assert(err, jc.ErrorIsNil)
c.Assert(conn, gc.NotNil)
c.Assert(conn.Addr(), gc.Equals, "0.1.2.3:1234")
c.Assert(conn.IPAddr(), gc.Equals, "0.1.2.3:1234")
c.Assert(dnsCache, gc.HasLen, 0)
}
func (s *apiclientSuite) TestFallbackToIPLookupWhenCacheOutOfDate(c *gc.C) {
dialc := make(chan string)
start := make(chan struct{})
fakeDialer := func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error) {
dialc <- ipAddr
<-start
if ipAddr == "0.2.2.2:1234" {
return fakeConn{}, nil
}
return nil, errors.Errorf("bad address")
}
dnsCache := dnsCacheMap{
"place1.example": {"0.1.1.1"},
}
type openResult struct {
conn api.Connection
err error
}
openc := make(chan openResult)
go func() {
conn, err := api.Open(&api.Info{
Addrs: []string{
"place1.example:1234",
},
SkipLogin: true,
CACert: jtesting.CACert,
}, api.DialOpts{
// Note: zero timeout means each address attempt
// will only try once only.
DialWebsocket: fakeDialer,
IPAddrResolver: apitesting.IPAddrResolverMap{
"place1.example": {"0.2.2.2"},
},
DNSCache: dnsCache,
})
openc <- openResult{conn, err}
}()
// Wait for both dial attempts to happen.
// If we don't, then the second attempt might
// happen before the first one and the first
// attempt might then never happen.
dialed := make(map[string]bool)
for i := 0; i < 2; i++ {
select {
case hostPort := <-dialc:
dialed[hostPort] = true
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for dial attempt")
}
}
// Allow the dial attempts to return.
close(start)
// Check that no more dial attempts happen.
select {
case hostPort := <-dialc:
c.Fatalf("unexpected dial attempt to %q; existing attempts: %v", hostPort, dialed)
case <-time.After(jtesting.ShortWait):
}
r := <-openc
c.Assert(r.err, jc.ErrorIsNil)
c.Assert(r.conn, gc.NotNil)
c.Assert(r.conn.Addr(), gc.Equals, "place1.example:1234")
c.Assert(r.conn.IPAddr(), gc.Equals, "0.2.2.2:1234")
c.Assert(dialed, jc.DeepEquals, map[string]bool{
"0.2.2.2:1234": true,
"0.1.1.1:1234": true,
})
c.Assert(dnsCache.Lookup("place1.example"), jc.DeepEquals, []string{"0.2.2.2"})
}
func (s *apiclientSuite) TestOpenTimesOutOnLogin(c *gc.C) {
unblock := make(chan chan struct{})
srv := apiservertesting.NewAPIServer(func(modelUUID string) interface{} {
return &loginTimeoutAPI{
unblock: unblock,
}
})
defer srv.Close()
defer close(unblock)
clk := testclock.NewClock(time.Now())
done := make(chan error, 1)
go func() {
_, err := api.Open(&api.Info{
Addrs: srv.Addrs,
CACert: jtesting.CACert,
ModelTag: names.NewModelTag("beef1beef1-0000-0000-000011112222"),
}, api.DialOpts{
Clock: clk,
Timeout: 5 * time.Second,
})
done <- err
}()
// Wait for Login to be entered before we advance the clock. Note that we don't actually unblock the request,
// we just ensure that the other side has gotten to the point where it wants to be blocked. Otherwise we might
// advance the clock before we even get the api.Dial to finish or before TLS handshaking finishes.
unblocked := make(chan struct{})
defer close(unblocked)
select {
case unblock <- unblocked:
case <-time.After(jtesting.LongWait):
c.Fatalf("timed out waiting for Login to be called")
}
err := clk.WaitAdvance(5*time.Second, time.Second, 1)
c.Assert(err, jc.ErrorIsNil)
select {
case err := <-done:
c.Assert(err, gc.ErrorMatches, `cannot log in: context deadline exceeded`)
case <-time.After(time.Second):
c.Fatalf("timed out waiting for api.Open timeout")
}
}
func (s *apiclientSuite) TestOpenTimeoutAffectsDial(c *gc.C) {
sync := make(chan struct{})
fakeDialer := func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error) {
close(sync)
<-ctx.Done()
return nil, ctx.Err()
}
clk := testclock.NewClock(time.Now())
done := make(chan error, 1)
go func() {
_, err := api.Open(&api.Info{
Addrs: []string{"127.0.0.1:1234"},
CACert: jtesting.CACert,
ModelTag: names.NewModelTag("beef1beef1-0000-0000-000011112222"),
SkipLogin: true,
}, api.DialOpts{
Clock: clk,
Timeout: 5 * time.Second,
DialWebsocket: fakeDialer,
})
done <- err
}()
// Before we advance time, ensure that the parallel try mechanism
// has entered the dial function.
select {
case <-sync:
case <-time.After(testing.LongWait):
c.Errorf("didn't enter dial")
}
err := clk.WaitAdvance(5*time.Second, time.Second, 1)
c.Assert(err, jc.ErrorIsNil)
select {
case err := <-done:
c.Assert(err, gc.ErrorMatches, `unable to connect to API: context deadline exceeded`)
case <-time.After(time.Second):
c.Fatalf("timed out waiting for api.Open timeout")
}
}
func (s *apiclientSuite) TestOpenDialTimeoutAffectsDial(c *gc.C) {
sync := make(chan struct{})
fakeDialer := func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error) {
close(sync)
<-ctx.Done()
return nil, ctx.Err()
}
clk := testclock.NewClock(time.Now())
done := make(chan error, 1)
go func() {
_, err := api.Open(&api.Info{
Addrs: []string{"127.0.0.1:1234"},
CACert: jtesting.CACert,
ModelTag: names.NewModelTag("beef1beef1-0000-0000-000011112222"),
SkipLogin: true,
}, api.DialOpts{
Clock: clk,
Timeout: 5 * time.Second,
DialTimeout: 3 * time.Second,
DialWebsocket: fakeDialer,
})
done <- err
}()
// Before we advance time, ensure that the parallel try mechanism
// has entered the dial function.
select {
case <-sync:
case <-time.After(testing.LongWait):
c.Errorf("didn't enter dial")
}
err := clk.WaitAdvance(3*time.Second, time.Second, 2) // Timeout & DialTimeout
c.Assert(err, jc.ErrorIsNil)
select {
case err := <-done:
c.Assert(err, gc.ErrorMatches, `unable to connect to API: context deadline exceeded`)
case <-time.After(time.Second):
c.Fatalf("timed out waiting for api.Open timeout")
}
}
func (s *apiclientSuite) TestOpenDialTimeoutDoesNotAffectLogin(c *gc.C) {
unblock := make(chan chan struct{})
srv := apiservertesting.NewAPIServer(func(modelUUID string) interface{} {
return &loginTimeoutAPI{
unblock: unblock,
}
})
defer srv.Close()
defer close(unblock)
clk := testclock.NewClock(time.Now())
done := make(chan error, 1)
go func() {
_, err := api.Open(&api.Info{
Addrs: srv.Addrs,
CACert: jtesting.CACert,
ModelTag: names.NewModelTag("beef1beef1-0000-0000-000011112222"),
}, api.DialOpts{
Clock: clk,
DialTimeout: 5 * time.Second,
})
done <- err
}()
// We should not get a response from api.Open until we
// unblock the login.
unblocked := make(chan struct{})
select {
case unblock <- unblocked:
// We are now in the Login method of the loginTimeoutAPI.
case <-time.After(jtesting.LongWait):
c.Fatalf("didn't enter Login")