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
|
/*
*
* Copyright 2020 gRPC authors.
*
* 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
*
* http://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 xds
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"os"
"strings"
"testing"
"time"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/tls/certprovider"
icredentials "google.golang.org/grpc/internal/credentials"
xdsinternal "google.golang.org/grpc/internal/credentials/xds"
"google.golang.org/grpc/internal/grpctest"
"google.golang.org/grpc/internal/testutils"
"google.golang.org/grpc/internal/xds/matcher"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/testdata"
)
const (
defaultTestTimeout = 1 * time.Second
defaultTestShortTimeout = 10 * time.Millisecond
defaultTestCertSAN = "abc.test.example.com"
authority = "authority"
)
type s struct {
grpctest.Tester
}
func Test(t *testing.T) {
grpctest.RunSubTests(t, s{})
}
// Helper function to create a real TLS client credentials which is used as
// fallback credentials from multiple tests.
func makeFallbackClientCreds(t *testing.T) credentials.TransportCredentials {
creds, err := credentials.NewClientTLSFromFile(testdata.Path("x509/server_ca_cert.pem"), "x.test.example.com")
if err != nil {
t.Fatal(err)
}
return creds
}
// testServer is a no-op server which listens on a local TCP port for incoming
// connections, and performs a manual TLS handshake on the received raw
// connection using a user specified handshake function. It then makes the
// result of the handshake operation available through a channel for tests to
// inspect. Tests should stop the testServer as part of their cleanup.
type testServer struct {
lis net.Listener
address string // Listening address of the test server.
handshakeFunc testHandshakeFunc // Test specified handshake function.
hsResult *testutils.Channel // Channel to deliver handshake results.
}
// handshakeResult wraps the result of the handshake operation on the test
// server. It consists of TLS connection state and an error, if the handshake
// failed. This result is delivered on the `hsResult` channel on the testServer.
type handshakeResult struct {
connState tls.ConnectionState
err error
}
// Configurable handshake function for the testServer. Tests can set this to
// simulate different conditions like handshake success, failure, timeout etc.
type testHandshakeFunc func(net.Conn) handshakeResult
// newTestServerWithHandshakeFunc starts a new testServer which listens for
// connections on a local TCP port, and uses the provided custom handshake
// function to perform TLS handshake.
func newTestServerWithHandshakeFunc(f testHandshakeFunc) *testServer {
ts := &testServer{
handshakeFunc: f,
hsResult: testutils.NewChannel(),
}
ts.start()
return ts
}
// starts actually starts listening on a local TCP port, and spawns a goroutine
// to handle new connections.
func (ts *testServer) start() error {
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
return err
}
ts.lis = lis
ts.address = lis.Addr().String()
go ts.handleConn()
return nil
}
// handleconn accepts a new raw connection, and invokes the test provided
// handshake function to perform TLS handshake, and returns the result on the
// `hsResult` channel.
func (ts *testServer) handleConn() {
for {
rawConn, err := ts.lis.Accept()
if err != nil {
// Once the listeners closed, Accept() will return with an error.
return
}
hsr := ts.handshakeFunc(rawConn)
ts.hsResult.Send(hsr)
}
}
// stop closes the associated listener which causes the connection handling
// goroutine to exit.
func (ts *testServer) stop() {
ts.lis.Close()
}
// A handshake function which simulates a successful handshake without client
// authentication (server does not request for client certificate during the
// handshake here).
func testServerTLSHandshake(rawConn net.Conn) handshakeResult {
cert, err := tls.LoadX509KeyPair(testdata.Path("x509/server1_cert.pem"), testdata.Path("x509/server1_key.pem"))
if err != nil {
return handshakeResult{err: err}
}
cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
conn := tls.Server(rawConn, cfg)
if err := conn.Handshake(); err != nil {
return handshakeResult{err: err}
}
return handshakeResult{connState: conn.ConnectionState()}
}
// A handshake function which simulates a successful handshake with mutual
// authentication.
func testServerMutualTLSHandshake(rawConn net.Conn) handshakeResult {
cert, err := tls.LoadX509KeyPair(testdata.Path("x509/server1_cert.pem"), testdata.Path("x509/server1_key.pem"))
if err != nil {
return handshakeResult{err: err}
}
pemData, err := os.ReadFile(testdata.Path("x509/client_ca_cert.pem"))
if err != nil {
return handshakeResult{err: err}
}
roots := x509.NewCertPool()
roots.AppendCertsFromPEM(pemData)
cfg := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: roots,
}
conn := tls.Server(rawConn, cfg)
if err := conn.Handshake(); err != nil {
return handshakeResult{err: err}
}
return handshakeResult{connState: conn.ConnectionState()}
}
// fakeProvider is an implementation of the certprovider.Provider interface
// which returns the configured key material and error in calls to
// KeyMaterial().
type fakeProvider struct {
km *certprovider.KeyMaterial
err error
}
func (f *fakeProvider) KeyMaterial(ctx context.Context) (*certprovider.KeyMaterial, error) {
return f.km, f.err
}
func (f *fakeProvider) Close() {}
// makeIdentityProvider creates a new instance of the fakeProvider returning the
// identity key material specified in the provider file paths.
func makeIdentityProvider(t *testing.T, certPath, keyPath string) certprovider.Provider {
t.Helper()
cert, err := tls.LoadX509KeyPair(testdata.Path(certPath), testdata.Path(keyPath))
if err != nil {
t.Fatal(err)
}
return &fakeProvider{km: &certprovider.KeyMaterial{Certs: []tls.Certificate{cert}}}
}
// makeRootProvider creates a new instance of the fakeProvider returning the
// root key material specified in the provider file paths.
func makeRootProvider(t *testing.T, caPath string) *fakeProvider {
pemData, err := os.ReadFile(testdata.Path(caPath))
if err != nil {
t.Fatal(err)
}
roots := x509.NewCertPool()
roots.AppendCertsFromPEM(pemData)
return &fakeProvider{km: &certprovider.KeyMaterial{Roots: roots}}
}
// newTestContextWithHandshakeInfo returns a copy of parent with HandshakeInfo
// context value added to it.
func newTestContextWithHandshakeInfo(parent context.Context, root, identity certprovider.Provider, sanExactMatch string) context.Context {
// Creating the HandshakeInfo and adding it to the attributes is very
// similar to what the CDS balancer would do when it intercepts calls to
// NewSubConn().
info := xdsinternal.NewHandshakeInfo(root, identity)
if sanExactMatch != "" {
info.SetSANMatchers([]matcher.StringMatcher{matcher.StringMatcherForTesting(newStringP(sanExactMatch), nil, nil, nil, nil, false)})
}
addr := xdsinternal.SetHandshakeInfo(resolver.Address{}, info)
// Moving the attributes from the resolver.Address to the context passed to
// the handshaker is done in the transport layer. Since we directly call the
// handshaker in these tests, we need to do the same here.
return icredentials.NewClientHandshakeInfoContext(parent, credentials.ClientHandshakeInfo{Attributes: addr.Attributes})
}
// compareAuthInfo compares the AuthInfo received on the client side after a
// successful handshake with the authInfo available on the testServer.
func compareAuthInfo(ctx context.Context, ts *testServer, ai credentials.AuthInfo) error {
if ai.AuthType() != "tls" {
return fmt.Errorf("ClientHandshake returned authType %q, want %q", ai.AuthType(), "tls")
}
info, ok := ai.(credentials.TLSInfo)
if !ok {
return fmt.Errorf("ClientHandshake returned authInfo of type %T, want %T", ai, credentials.TLSInfo{})
}
gotState := info.State
// Read the handshake result from the testServer which contains the TLS
// connection state and compare it with the one received on the client-side.
val, err := ts.hsResult.Receive(ctx)
if err != nil {
return fmt.Errorf("testServer failed to return handshake result: %v", err)
}
hsr := val.(handshakeResult)
if hsr.err != nil {
return fmt.Errorf("testServer handshake failure: %v", hsr.err)
}
// AuthInfo contains a variety of information. We only verify a subset here.
// This is the same subset which is verified in TLS credentials tests.
if err := compareConnState(gotState, hsr.connState); err != nil {
return err
}
return nil
}
func compareConnState(got, want tls.ConnectionState) error {
switch {
case got.Version != want.Version:
return fmt.Errorf("TLS.ConnectionState got Version: %v, want: %v", got.Version, want.Version)
case got.HandshakeComplete != want.HandshakeComplete:
return fmt.Errorf("TLS.ConnectionState got HandshakeComplete: %v, want: %v", got.HandshakeComplete, want.HandshakeComplete)
case got.CipherSuite != want.CipherSuite:
return fmt.Errorf("TLS.ConnectionState got CipherSuite: %v, want: %v", got.CipherSuite, want.CipherSuite)
case got.NegotiatedProtocol != want.NegotiatedProtocol:
return fmt.Errorf("TLS.ConnectionState got NegotiatedProtocol: %v, want: %v", got.NegotiatedProtocol, want.NegotiatedProtocol)
}
return nil
}
// TestClientCredsWithoutFallback verifies that the call to
// NewClientCredentials() fails when no fallback is specified.
func (s) TestClientCredsWithoutFallback(t *testing.T) {
if _, err := NewClientCredentials(ClientOptions{}); err == nil {
t.Fatal("NewClientCredentials() succeeded without specifying fallback")
}
}
// TestClientCredsInvalidHandshakeInfo verifies scenarios where the passed in
// HandshakeInfo is invalid because it does not contain the expected certificate
// providers.
func (s) TestClientCredsInvalidHandshakeInfo(t *testing.T) {
opts := ClientOptions{FallbackCreds: makeFallbackClientCreds(t)}
creds, err := NewClientCredentials(opts)
if err != nil {
t.Fatalf("NewClientCredentials(%v) failed: %v", opts, err)
}
pCtx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
ctx := newTestContextWithHandshakeInfo(pCtx, nil, &fakeProvider{}, "")
if _, _, err := creds.ClientHandshake(ctx, authority, nil); err == nil {
t.Fatal("ClientHandshake succeeded without root certificate provider in HandshakeInfo")
}
}
// TestClientCredsProviderFailure verifies the cases where an expected
// certificate provider is missing in the HandshakeInfo value in the context.
func (s) TestClientCredsProviderFailure(t *testing.T) {
opts := ClientOptions{FallbackCreds: makeFallbackClientCreds(t)}
creds, err := NewClientCredentials(opts)
if err != nil {
t.Fatalf("NewClientCredentials(%v) failed: %v", opts, err)
}
tests := []struct {
desc string
rootProvider certprovider.Provider
identityProvider certprovider.Provider
wantErr string
}{
{
desc: "erroring root provider",
rootProvider: &fakeProvider{err: errors.New("root provider error")},
wantErr: "root provider error",
},
{
desc: "erroring identity provider",
rootProvider: &fakeProvider{km: &certprovider.KeyMaterial{}},
identityProvider: &fakeProvider{err: errors.New("identity provider error")},
wantErr: "identity provider error",
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
ctx = newTestContextWithHandshakeInfo(ctx, test.rootProvider, test.identityProvider, "")
if _, _, err := creds.ClientHandshake(ctx, authority, nil); err == nil || !strings.Contains(err.Error(), test.wantErr) {
t.Fatalf("ClientHandshake() returned error: %q, wantErr: %q", err, test.wantErr)
}
})
}
}
// TestClientCredsSuccess verifies successful client handshake cases.
func (s) TestClientCredsSuccess(t *testing.T) {
tests := []struct {
desc string
handshakeFunc testHandshakeFunc
handshakeInfoCtx func(ctx context.Context) context.Context
}{
{
desc: "fallback",
handshakeFunc: testServerTLSHandshake,
handshakeInfoCtx: func(ctx context.Context) context.Context {
// Since we don't add a HandshakeInfo to the context, the
// ClientHandshake() method will delegate to the fallback.
return ctx
},
},
{
desc: "TLS",
handshakeFunc: testServerTLSHandshake,
handshakeInfoCtx: func(ctx context.Context) context.Context {
return newTestContextWithHandshakeInfo(ctx, makeRootProvider(t, "x509/server_ca_cert.pem"), nil, defaultTestCertSAN)
},
},
{
desc: "mTLS",
handshakeFunc: testServerMutualTLSHandshake,
handshakeInfoCtx: func(ctx context.Context) context.Context {
return newTestContextWithHandshakeInfo(ctx, makeRootProvider(t, "x509/server_ca_cert.pem"), makeIdentityProvider(t, "x509/server1_cert.pem", "x509/server1_key.pem"), defaultTestCertSAN)
},
},
{
desc: "mTLS with no acceptedSANs specified",
handshakeFunc: testServerMutualTLSHandshake,
handshakeInfoCtx: func(ctx context.Context) context.Context {
return newTestContextWithHandshakeInfo(ctx, makeRootProvider(t, "x509/server_ca_cert.pem"), makeIdentityProvider(t, "x509/server1_cert.pem", "x509/server1_key.pem"), "")
},
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
ts := newTestServerWithHandshakeFunc(test.handshakeFunc)
defer ts.stop()
opts := ClientOptions{FallbackCreds: makeFallbackClientCreds(t)}
creds, err := NewClientCredentials(opts)
if err != nil {
t.Fatalf("NewClientCredentials(%v) failed: %v", opts, err)
}
conn, err := net.Dial("tcp", ts.address)
if err != nil {
t.Fatalf("net.Dial(%s) failed: %v", ts.address, err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
_, ai, err := creds.ClientHandshake(test.handshakeInfoCtx(ctx), authority, conn)
if err != nil {
t.Fatalf("ClientHandshake() returned failed: %q", err)
}
if err := compareAuthInfo(ctx, ts, ai); err != nil {
t.Fatal(err)
}
})
}
}
func (s) TestClientCredsHandshakeTimeout(t *testing.T) {
clientDone := make(chan struct{})
// A handshake function which simulates a handshake timeout from the
// server-side by simply blocking on the client-side handshake to timeout
// and not writing any handshake data.
hErr := errors.New("server handshake error")
ts := newTestServerWithHandshakeFunc(func(rawConn net.Conn) handshakeResult {
<-clientDone
return handshakeResult{err: hErr}
})
defer ts.stop()
opts := ClientOptions{FallbackCreds: makeFallbackClientCreds(t)}
creds, err := NewClientCredentials(opts)
if err != nil {
t.Fatalf("NewClientCredentials(%v) failed: %v", opts, err)
}
conn, err := net.Dial("tcp", ts.address)
if err != nil {
t.Fatalf("net.Dial(%s) failed: %v", ts.address, err)
}
defer conn.Close()
sCtx, sCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)
defer sCancel()
ctx := newTestContextWithHandshakeInfo(sCtx, makeRootProvider(t, "x509/server_ca_cert.pem"), nil, defaultTestCertSAN)
if _, _, err := creds.ClientHandshake(ctx, authority, conn); err == nil {
t.Fatal("ClientHandshake() succeeded when expected to timeout")
}
close(clientDone)
// Read the handshake result from the testServer and make sure the expected
// error is returned.
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
val, err := ts.hsResult.Receive(ctx)
if err != nil {
t.Fatalf("testServer failed to return handshake result: %v", err)
}
hsr := val.(handshakeResult)
if hsr.err != hErr {
t.Fatalf("testServer handshake returned error: %v, want: %v", hsr.err, hErr)
}
}
// TestClientCredsHandshakeFailure verifies different handshake failure cases.
func (s) TestClientCredsHandshakeFailure(t *testing.T) {
tests := []struct {
desc string
handshakeFunc testHandshakeFunc
rootProvider certprovider.Provider
san string
wantErr string
}{
{
desc: "cert validation failure",
handshakeFunc: testServerTLSHandshake,
rootProvider: makeRootProvider(t, "x509/client_ca_cert.pem"),
san: defaultTestCertSAN,
wantErr: "x509: certificate signed by unknown authority",
},
{
desc: "SAN mismatch",
handshakeFunc: testServerTLSHandshake,
rootProvider: makeRootProvider(t, "x509/server_ca_cert.pem"),
san: "bad-san",
wantErr: "do not match any of the accepted SANs",
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
ts := newTestServerWithHandshakeFunc(test.handshakeFunc)
defer ts.stop()
opts := ClientOptions{FallbackCreds: makeFallbackClientCreds(t)}
creds, err := NewClientCredentials(opts)
if err != nil {
t.Fatalf("NewClientCredentials(%v) failed: %v", opts, err)
}
conn, err := net.Dial("tcp", ts.address)
if err != nil {
t.Fatalf("net.Dial(%s) failed: %v", ts.address, err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
ctx = newTestContextWithHandshakeInfo(ctx, test.rootProvider, nil, test.san)
if _, _, err := creds.ClientHandshake(ctx, authority, conn); err == nil || !strings.Contains(err.Error(), test.wantErr) {
t.Fatalf("ClientHandshake() returned %q, wantErr %q", err, test.wantErr)
}
})
}
}
// TestClientCredsProviderSwitch verifies the case where the first attempt of
// ClientHandshake fails because of a handshake failure. Then we update the
// certificate provider and the second attempt succeeds. This is an
// approximation of the flow of events when the control plane specifies new
// security config which results in new certificate providers being used.
func (s) TestClientCredsProviderSwitch(t *testing.T) {
ts := newTestServerWithHandshakeFunc(testServerTLSHandshake)
defer ts.stop()
opts := ClientOptions{FallbackCreds: makeFallbackClientCreds(t)}
creds, err := NewClientCredentials(opts)
if err != nil {
t.Fatalf("NewClientCredentials(%v) failed: %v", opts, err)
}
conn, err := net.Dial("tcp", ts.address)
if err != nil {
t.Fatalf("net.Dial(%s) failed: %v", ts.address, err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
// Create a root provider which will fail the handshake because it does not
// use the correct trust roots.
root1 := makeRootProvider(t, "x509/client_ca_cert.pem")
handshakeInfo := xdsinternal.NewHandshakeInfo(root1, nil)
handshakeInfo.SetSANMatchers([]matcher.StringMatcher{matcher.StringMatcherForTesting(newStringP(defaultTestCertSAN), nil, nil, nil, nil, false)})
// We need to repeat most of what newTestContextWithHandshakeInfo() does
// here because we need access to the underlying HandshakeInfo so that we
// can update it before the next call to ClientHandshake().
addr := xdsinternal.SetHandshakeInfo(resolver.Address{}, handshakeInfo)
ctx = icredentials.NewClientHandshakeInfoContext(ctx, credentials.ClientHandshakeInfo{Attributes: addr.Attributes})
if _, _, err := creds.ClientHandshake(ctx, authority, conn); err == nil {
t.Fatal("ClientHandshake() succeeded when expected to fail")
}
// Drain the result channel on the test server so that we can inspect the
// result for the next handshake.
_, err = ts.hsResult.Receive(ctx)
if err != nil {
t.Errorf("testServer failed to return handshake result: %v", err)
}
conn, err = net.Dial("tcp", ts.address)
if err != nil {
t.Fatalf("net.Dial(%s) failed: %v", ts.address, err)
}
defer conn.Close()
// Create a new root provider which uses the correct trust roots. And update
// the HandshakeInfo with the new provider.
root2 := makeRootProvider(t, "x509/server_ca_cert.pem")
handshakeInfo.SetRootCertProvider(root2)
_, ai, err := creds.ClientHandshake(ctx, authority, conn)
if err != nil {
t.Fatalf("ClientHandshake() returned failed: %q", err)
}
if err := compareAuthInfo(ctx, ts, ai); err != nil {
t.Fatal(err)
}
}
// TestClientClone verifies the Clone() method on client credentials.
func (s) TestClientClone(t *testing.T) {
opts := ClientOptions{FallbackCreds: makeFallbackClientCreds(t)}
orig, err := NewClientCredentials(opts)
if err != nil {
t.Fatalf("NewClientCredentials(%v) failed: %v", opts, err)
}
// The credsImpl does not have any exported fields, and it does not make
// sense to use any cmp options to look deep into. So, all we make sure here
// is that the cloned object points to a different location in memory.
if clone := orig.Clone(); clone == orig {
t.Fatal("return value from Clone() doesn't point to new credentials instance")
}
}
func newStringP(s string) *string {
return &s
}
|