Source file src/crypto/tls/quic_test.go

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"crypto/tls/internal/fips140tls"
    11  	"errors"
    12  	"fmt"
    13  	"net"
    14  	"reflect"
    15  	"strings"
    16  	"sync"
    17  	"testing"
    18  )
    19  
    20  type testQUICConn struct {
    21  	t                 *testing.T
    22  	conn              *QUICConn
    23  	readSecret        map[QUICEncryptionLevel]suiteSecret
    24  	writeSecret       map[QUICEncryptionLevel]suiteSecret
    25  	ticketOpts        QUICSessionTicketOptions
    26  	onResumeSession   func(*SessionState)
    27  	gotParams         []byte
    28  	gotError          error
    29  	earlyDataRejected bool
    30  	complete          bool
    31  }
    32  
    33  func newTestQUICClient(t *testing.T, config *QUICConfig) *testQUICConn {
    34  	q := &testQUICConn{
    35  		t:    t,
    36  		conn: QUICClient(config),
    37  	}
    38  	t.Cleanup(func() {
    39  		q.conn.Close()
    40  	})
    41  	return q
    42  }
    43  
    44  func newTestQUICServer(t *testing.T, config *QUICConfig) *testQUICConn {
    45  	q := &testQUICConn{
    46  		t:    t,
    47  		conn: QUICServer(config),
    48  	}
    49  	t.Cleanup(func() {
    50  		q.conn.Close()
    51  	})
    52  	return q
    53  }
    54  
    55  type suiteSecret struct {
    56  	suite  uint16
    57  	secret []byte
    58  }
    59  
    60  func (q *testQUICConn) setReadSecret(level QUICEncryptionLevel, suite uint16, secret []byte) {
    61  	if _, ok := q.writeSecret[level]; !ok && level != QUICEncryptionLevelEarly {
    62  		q.t.Errorf("SetReadSecret for level %v called before SetWriteSecret", level)
    63  	}
    64  	if level == QUICEncryptionLevelApplication && !q.complete {
    65  		q.t.Errorf("SetReadSecret for level %v called before HandshakeComplete", level)
    66  	}
    67  	if _, ok := q.readSecret[level]; ok {
    68  		q.t.Errorf("SetReadSecret for level %v called twice", level)
    69  	}
    70  	if q.readSecret == nil {
    71  		q.readSecret = map[QUICEncryptionLevel]suiteSecret{}
    72  	}
    73  	switch level {
    74  	case QUICEncryptionLevelHandshake,
    75  		QUICEncryptionLevelEarly,
    76  		QUICEncryptionLevelApplication:
    77  		q.readSecret[level] = suiteSecret{suite, secret}
    78  	default:
    79  		q.t.Errorf("SetReadSecret for unexpected level %v", level)
    80  	}
    81  }
    82  
    83  func (q *testQUICConn) setWriteSecret(level QUICEncryptionLevel, suite uint16, secret []byte) {
    84  	if _, ok := q.writeSecret[level]; ok {
    85  		q.t.Errorf("SetWriteSecret for level %v called twice", level)
    86  	}
    87  	if q.writeSecret == nil {
    88  		q.writeSecret = map[QUICEncryptionLevel]suiteSecret{}
    89  	}
    90  	switch level {
    91  	case QUICEncryptionLevelHandshake,
    92  		QUICEncryptionLevelEarly,
    93  		QUICEncryptionLevelApplication:
    94  		q.writeSecret[level] = suiteSecret{suite, secret}
    95  	default:
    96  		q.t.Errorf("SetWriteSecret for unexpected level %v", level)
    97  	}
    98  }
    99  
   100  var errTransportParametersRequired = errors.New("transport parameters required")
   101  
   102  func runTestQUICConnection(ctx context.Context, cli, srv *testQUICConn, onEvent func(e QUICEvent, src, dst *testQUICConn) bool) error {
   103  	a, b := cli, srv
   104  	for _, c := range []*testQUICConn{a, b} {
   105  		if !c.conn.conn.quic.started {
   106  			if err := c.conn.Start(ctx); err != nil {
   107  				return err
   108  			}
   109  		}
   110  	}
   111  	idleCount := 0
   112  	for {
   113  		e := a.conn.NextEvent()
   114  		if onEvent != nil && onEvent(e, a, b) {
   115  			continue
   116  		}
   117  		if a.gotError != nil && e.Kind != QUICNoEvent {
   118  			return fmt.Errorf("unexpected event %v after QUICErrorEvent", e.Kind)
   119  		}
   120  		switch e.Kind {
   121  		case QUICNoEvent:
   122  			idleCount++
   123  			if idleCount == 2 {
   124  				if !a.complete || !b.complete {
   125  					return errors.New("handshake incomplete")
   126  				}
   127  				return nil
   128  			}
   129  			a, b = b, a
   130  		case QUICSetReadSecret:
   131  			a.setReadSecret(e.Level, e.Suite, e.Data)
   132  		case QUICSetWriteSecret:
   133  			a.setWriteSecret(e.Level, e.Suite, e.Data)
   134  		case QUICWriteData:
   135  			if err := b.conn.HandleData(e.Level, e.Data); err != nil {
   136  				return err
   137  			}
   138  		case QUICTransportParameters:
   139  			a.gotParams = e.Data
   140  			if a.gotParams == nil {
   141  				a.gotParams = []byte{}
   142  			}
   143  		case QUICTransportParametersRequired:
   144  			return errTransportParametersRequired
   145  		case QUICHandshakeDone:
   146  			a.complete = true
   147  			if a == srv {
   148  				if err := srv.conn.SendSessionTicket(srv.ticketOpts); err != nil {
   149  					return err
   150  				}
   151  			}
   152  		case QUICStoreSession:
   153  			if a != cli {
   154  				return errors.New("unexpected QUICStoreSession event received by server")
   155  			}
   156  			a.conn.StoreSession(e.SessionState)
   157  		case QUICResumeSession:
   158  			if a.onResumeSession != nil {
   159  				a.onResumeSession(e.SessionState)
   160  			}
   161  		case QUICRejectedEarlyData:
   162  			a.earlyDataRejected = true
   163  		case QUICErrorEvent:
   164  			if e.Err == nil {
   165  				return errors.New("unexpected QUICErrorEvent with no Err")
   166  			}
   167  			a.gotError = e.Err
   168  		}
   169  		if e.Kind != QUICNoEvent {
   170  			idleCount = 0
   171  		}
   172  	}
   173  }
   174  
   175  func TestQUICConnection(t *testing.T) {
   176  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   177  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   178  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   179  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   180  
   181  	cli := newTestQUICClient(t, clientConfig)
   182  	cli.conn.SetTransportParameters(nil)
   183  
   184  	srv := newTestQUICServer(t, serverConfig)
   185  	srv.conn.SetTransportParameters(nil)
   186  
   187  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   188  		t.Fatalf("error during connection handshake: %v", err)
   189  	}
   190  
   191  	if _, ok := cli.readSecret[QUICEncryptionLevelHandshake]; !ok {
   192  		t.Errorf("client has no Handshake secret")
   193  	}
   194  	if _, ok := cli.readSecret[QUICEncryptionLevelApplication]; !ok {
   195  		t.Errorf("client has no Application secret")
   196  	}
   197  	if _, ok := srv.readSecret[QUICEncryptionLevelHandshake]; !ok {
   198  		t.Errorf("server has no Handshake secret")
   199  	}
   200  	if _, ok := srv.readSecret[QUICEncryptionLevelApplication]; !ok {
   201  		t.Errorf("server has no Application secret")
   202  	}
   203  	for _, level := range []QUICEncryptionLevel{QUICEncryptionLevelHandshake, QUICEncryptionLevelApplication} {
   204  		if _, ok := cli.readSecret[level]; !ok {
   205  			t.Errorf("client has no %v read secret", level)
   206  		}
   207  		if _, ok := srv.readSecret[level]; !ok {
   208  			t.Errorf("server has no %v read secret", level)
   209  		}
   210  		if !reflect.DeepEqual(cli.readSecret[level], srv.writeSecret[level]) {
   211  			t.Errorf("client read secret does not match server write secret for level %v", level)
   212  		}
   213  		if !reflect.DeepEqual(cli.writeSecret[level], srv.readSecret[level]) {
   214  			t.Errorf("client write secret does not match server read secret for level %v", level)
   215  		}
   216  	}
   217  }
   218  
   219  func TestQUICVersions(t *testing.T) {
   220  	for _, tc := range []struct {
   221  		name      string
   222  		clientMin uint16
   223  		clientMax uint16
   224  		serverMin uint16
   225  		serverMax uint16
   226  		wantErr   bool
   227  	}{
   228  		{
   229  			name: "defaults",
   230  		},
   231  		{
   232  			name:      "MinVersion TLS 1.2",
   233  			clientMin: VersionTLS12,
   234  			serverMin: VersionTLS12,
   235  		},
   236  		{
   237  			name:      "MinVersion TLS 1.3",
   238  			clientMin: VersionTLS13,
   239  			serverMin: VersionTLS13,
   240  		},
   241  		{
   242  			name:      "client MaxVersion TLS 1.2",
   243  			clientMax: VersionTLS12,
   244  			wantErr:   true,
   245  		},
   246  		{
   247  			name:      "server MaxVersion TLS 1.2",
   248  			serverMax: VersionTLS12,
   249  			wantErr:   true,
   250  		},
   251  	} {
   252  		t.Run(tc.name, func(t *testing.T) {
   253  			client := testConfigClient()
   254  			client.MinVersion = tc.clientMin
   255  			client.MaxVersion = tc.clientMax
   256  			server := testConfigServer()
   257  			server.MinVersion = tc.serverMin
   258  			server.MaxVersion = tc.serverMax
   259  
   260  			cli := newTestQUICClient(t, &QUICConfig{TLSConfig: client})
   261  			cli.conn.SetTransportParameters(nil)
   262  			srv := newTestQUICServer(t, &QUICConfig{TLSConfig: server})
   263  			srv.conn.SetTransportParameters(nil)
   264  			err := runTestQUICConnection(context.Background(), cli, srv, nil)
   265  			if tc.wantErr == (err == nil) {
   266  				t.Errorf("got err=%v, wantErr=%v", err, tc.wantErr)
   267  			}
   268  		})
   269  	}
   270  }
   271  
   272  func TestQUICSessionResumption(t *testing.T) {
   273  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   274  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   275  	clientConfig.TLSConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   276  
   277  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   278  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   279  
   280  	cli := newTestQUICClient(t, clientConfig)
   281  	cli.conn.SetTransportParameters(nil)
   282  	srv := newTestQUICServer(t, serverConfig)
   283  	srv.conn.SetTransportParameters(nil)
   284  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   285  		t.Fatalf("error during first connection handshake: %v", err)
   286  	}
   287  	if cli.conn.ConnectionState().DidResume {
   288  		t.Errorf("first connection unexpectedly used session resumption")
   289  	}
   290  
   291  	cli2 := newTestQUICClient(t, clientConfig)
   292  	cli2.conn.SetTransportParameters(nil)
   293  	srv2 := newTestQUICServer(t, serverConfig)
   294  	srv2.conn.SetTransportParameters(nil)
   295  	if err := runTestQUICConnection(context.Background(), cli2, srv2, nil); err != nil {
   296  		t.Fatalf("error during second connection handshake: %v", err)
   297  	}
   298  	if !cli2.conn.ConnectionState().DidResume {
   299  		t.Errorf("second connection did not use session resumption")
   300  	}
   301  
   302  	clientConfig.TLSConfig.SessionTicketsDisabled = true
   303  	cli3 := newTestQUICClient(t, clientConfig)
   304  	cli3.conn.SetTransportParameters(nil)
   305  	srv3 := newTestQUICServer(t, serverConfig)
   306  	srv3.conn.SetTransportParameters(nil)
   307  	if err := runTestQUICConnection(context.Background(), cli3, srv3, nil); err != nil {
   308  		t.Fatalf("error during third connection handshake: %v", err)
   309  	}
   310  	if cli3.conn.ConnectionState().DidResume {
   311  		t.Errorf("third connection unexpectedly used session resumption")
   312  	}
   313  }
   314  
   315  func TestQUICFragmentaryData(t *testing.T) {
   316  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   317  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   318  	clientConfig.TLSConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   319  
   320  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   321  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   322  
   323  	cli := newTestQUICClient(t, clientConfig)
   324  	cli.conn.SetTransportParameters(nil)
   325  	srv := newTestQUICServer(t, serverConfig)
   326  	srv.conn.SetTransportParameters(nil)
   327  	onEvent := func(e QUICEvent, src, dst *testQUICConn) bool {
   328  		if e.Kind == QUICWriteData {
   329  			// Provide the data one byte at a time.
   330  			for i := range e.Data {
   331  				if err := dst.conn.HandleData(e.Level, e.Data[i:i+1]); err != nil {
   332  					t.Errorf("HandleData: %v", err)
   333  					break
   334  				}
   335  			}
   336  			return true
   337  		}
   338  		return false
   339  	}
   340  	if err := runTestQUICConnection(context.Background(), cli, srv, onEvent); err != nil {
   341  		t.Fatalf("error during first connection handshake: %v", err)
   342  	}
   343  }
   344  
   345  func TestQUICPostHandshakeClientAuthentication(t *testing.T) {
   346  	// RFC 9001, Section 4.4.
   347  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   348  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   349  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   350  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   351  	cli := newTestQUICClient(t, clientConfig)
   352  	cli.conn.SetTransportParameters(nil)
   353  	srv := newTestQUICServer(t, serverConfig)
   354  	srv.conn.SetTransportParameters(nil)
   355  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   356  		t.Fatalf("error during connection handshake: %v", err)
   357  	}
   358  
   359  	certReq := new(certificateRequestMsgTLS13)
   360  	certReq.ocspStapling = true
   361  	certReq.scts = true
   362  	certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms(VersionTLS13, VersionTLS13, fips140tls.Required())
   363  	certReqBytes, err := certReq.marshal()
   364  	if err != nil {
   365  		t.Fatal(err)
   366  	}
   367  	if err := cli.conn.HandleData(QUICEncryptionLevelApplication, append([]byte{
   368  		byte(typeCertificateRequest),
   369  		byte(0), byte(0), byte(len(certReqBytes)),
   370  	}, certReqBytes...)); err == nil {
   371  		t.Fatalf("post-handshake authentication request: got no error, want one")
   372  	}
   373  }
   374  
   375  func TestQUICPostHandshakeKeyUpdate(t *testing.T) {
   376  	// RFC 9001, Section 6.
   377  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   378  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   379  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   380  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   381  	cli := newTestQUICClient(t, clientConfig)
   382  	cli.conn.SetTransportParameters(nil)
   383  	srv := newTestQUICServer(t, serverConfig)
   384  	srv.conn.SetTransportParameters(nil)
   385  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   386  		t.Fatalf("error during connection handshake: %v", err)
   387  	}
   388  
   389  	keyUpdate := new(keyUpdateMsg)
   390  	keyUpdateBytes, err := keyUpdate.marshal()
   391  	if err != nil {
   392  		t.Fatal(err)
   393  	}
   394  	expectedErr := "unexpected key update message"
   395  	if err = cli.conn.HandleData(QUICEncryptionLevelApplication, keyUpdateBytes); err == nil {
   396  		t.Fatalf("key update request: expected error from post-handshake key update, got nil")
   397  	} else if !strings.Contains(err.Error(), expectedErr) {
   398  		t.Fatalf("key update request: got error %v, expected substring %q", err, expectedErr)
   399  	}
   400  }
   401  
   402  func TestQUICPostHandshakeMessageTooLarge(t *testing.T) {
   403  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   404  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   405  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   406  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   407  	cli := newTestQUICClient(t, clientConfig)
   408  	cli.conn.SetTransportParameters(nil)
   409  	srv := newTestQUICServer(t, serverConfig)
   410  	srv.conn.SetTransportParameters(nil)
   411  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   412  		t.Fatalf("error during connection handshake: %v", err)
   413  	}
   414  
   415  	size := maxHandshake + 1
   416  	if err := cli.conn.HandleData(QUICEncryptionLevelApplication, []byte{
   417  		byte(typeNewSessionTicket),
   418  		byte(size >> 16),
   419  		byte(size >> 8),
   420  		byte(size),
   421  	}); err == nil {
   422  		t.Fatalf("%v-byte post-handshake message: got no error, want one", size)
   423  	}
   424  }
   425  
   426  func TestQUICHandshakeError(t *testing.T) {
   427  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   428  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   429  	clientConfig.TLSConfig.InsecureSkipVerify = false
   430  	clientConfig.TLSConfig.ServerName = "name"
   431  
   432  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   433  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   434  
   435  	cli := newTestQUICClient(t, clientConfig)
   436  	cli.conn.SetTransportParameters(nil)
   437  	srv := newTestQUICServer(t, serverConfig)
   438  	srv.conn.SetTransportParameters(nil)
   439  	err := runTestQUICConnection(context.Background(), cli, srv, nil)
   440  	if !errors.Is(err, AlertError(alertBadCertificate)) {
   441  		t.Errorf("connection handshake terminated with error %q, want alertBadCertificate", err)
   442  	}
   443  	if _, ok := errors.AsType[*CertificateVerificationError](err); !ok {
   444  		t.Errorf("connection handshake terminated with error %q, want CertificateVerificationError", err)
   445  	}
   446  
   447  	ev := cli.conn.NextEvent()
   448  	if ev.Kind != QUICErrorEvent {
   449  		t.Errorf("client.NextEvent: no QUICErrorEvent, want one")
   450  	}
   451  	if ev.Err != err {
   452  		t.Errorf("client.NextEvent: want same error returned by Start, got %v", ev.Err)
   453  	}
   454  }
   455  
   456  // Test that we can report an error produced by the GetEncryptedClientHelloKeys function.
   457  func TestQUICECHKeyError(t *testing.T) {
   458  	getECHKeysError := errors.New("error returned by GetEncryptedClientHelloKeys")
   459  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   460  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   461  	clientConfig.TLSConfig.NextProtos = []string{"h3"}
   462  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   463  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   464  	serverConfig.TLSConfig.NextProtos = []string{"h3"}
   465  	serverConfig.TLSConfig.GetEncryptedClientHelloKeys = func(*ClientHelloInfo) ([]EncryptedClientHelloKey, error) {
   466  		return nil, getECHKeysError
   467  	}
   468  	cli := newTestQUICClient(t, clientConfig)
   469  	cli.conn.SetTransportParameters(nil)
   470  	srv := newTestQUICServer(t, serverConfig)
   471  	srv.conn.SetTransportParameters(nil)
   472  	// Since adding ECH GREASE the client sends a GREASE'd ECH extension on every
   473  	// TLS 1.3 ClientHello, so the server invokes GetEncryptedClientHelloKeys
   474  	// during readClientHello and aborts before EncryptedExtensions are built.
   475  	//
   476  	// runTestQUICConnection short-circuits the event loop when HandleData errors,
   477  	// so the server-side gotError is never polled. Instead, we assert against
   478  	// the returned error directly (it is wrapped with AlertError by quicError).
   479  	//
   480  	// Ordering against transport-parameter signalling is covered by
   481  	// TestQUICDelayedTransportParameters.
   482  	err := runTestQUICConnection(context.Background(), cli, srv, nil)
   483  	if err == nil {
   484  		t.Fatalf("handshake with GetEncryptedClientHelloKeys errors: nil, want error")
   485  	}
   486  	if _, ok := errors.AsType[AlertError](err); !ok {
   487  		t.Errorf("connection handshake terminated with error %T (%v), want AlertError", err, err)
   488  	}
   489  	if !errors.Is(err, getECHKeysError) {
   490  		t.Errorf("connection handshake terminated with error %v, want error returned by GetEncryptedClientHelloKeys", err)
   491  	}
   492  }
   493  
   494  // Test that QUICConn.ConnectionState can be used during the handshake,
   495  // and that it reports the application protocol as soon as it has been
   496  // negotiated.
   497  func TestQUICConnectionState(t *testing.T) {
   498  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   499  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   500  	clientConfig.TLSConfig.NextProtos = []string{"h3"}
   501  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   502  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   503  	serverConfig.TLSConfig.NextProtos = []string{"h3"}
   504  	cli := newTestQUICClient(t, clientConfig)
   505  	cli.conn.SetTransportParameters(nil)
   506  	srv := newTestQUICServer(t, serverConfig)
   507  	srv.conn.SetTransportParameters(nil)
   508  	onEvent := func(e QUICEvent, src, dst *testQUICConn) bool {
   509  		cliCS := cli.conn.ConnectionState()
   510  		if _, ok := cli.readSecret[QUICEncryptionLevelApplication]; ok {
   511  			if want, got := cliCS.NegotiatedProtocol, "h3"; want != got {
   512  				t.Errorf("cli.ConnectionState().NegotiatedProtocol = %q, want %q", want, got)
   513  			}
   514  		}
   515  		srvCS := srv.conn.ConnectionState()
   516  		if _, ok := srv.readSecret[QUICEncryptionLevelHandshake]; ok {
   517  			if want, got := srvCS.NegotiatedProtocol, "h3"; want != got {
   518  				t.Errorf("srv.ConnectionState().NegotiatedProtocol = %q, want %q", want, got)
   519  			}
   520  		}
   521  		return false
   522  	}
   523  	if err := runTestQUICConnection(context.Background(), cli, srv, onEvent); err != nil {
   524  		t.Fatalf("error during connection handshake: %v", err)
   525  	}
   526  }
   527  
   528  func TestQUICStartContextPropagation(t *testing.T) {
   529  	const key = "key"
   530  	const value = "value"
   531  	ctx := context.WithValue(context.Background(), key, value)
   532  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   533  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   534  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   535  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   536  	calls := 0
   537  	serverConfig.TLSConfig.GetConfigForClient = func(info *ClientHelloInfo) (*Config, error) {
   538  		calls++
   539  		got, _ := info.Context().Value(key).(string)
   540  		if got != value {
   541  			t.Errorf("GetConfigForClient context key %q has value %q, want %q", key, got, value)
   542  		}
   543  		return nil, nil
   544  	}
   545  	cli := newTestQUICClient(t, clientConfig)
   546  	cli.conn.SetTransportParameters(nil)
   547  	srv := newTestQUICServer(t, serverConfig)
   548  	srv.conn.SetTransportParameters(nil)
   549  	if err := runTestQUICConnection(ctx, cli, srv, nil); err != nil {
   550  		t.Fatalf("error during connection handshake: %v", err)
   551  	}
   552  	if calls != 1 {
   553  		t.Errorf("GetConfigForClient called %v times, want 1", calls)
   554  	}
   555  }
   556  
   557  func TestQUICClientHelloInfoConn(t *testing.T) {
   558  	clientHelloInfoConn, peerConn := net.Pipe()
   559  	t.Cleanup(func() {
   560  		clientHelloInfoConn.Close()
   561  		peerConn.Close()
   562  	})
   563  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   564  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   565  	serverConfig := &QUICConfig{
   566  		TLSConfig:           testConfigServer(),
   567  		ClientHelloInfoConn: clientHelloInfoConn,
   568  	}
   569  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   570  	var called bool
   571  	serverConfig.TLSConfig.GetConfigForClient = func(info *ClientHelloInfo) (*Config, error) {
   572  		called = true
   573  		if info.Conn != clientHelloInfoConn {
   574  			t.Errorf("ClientHelloInfo.Conn = %v, want %v", info.Conn, clientHelloInfoConn)
   575  		}
   576  		return nil, nil
   577  	}
   578  	cli := newTestQUICClient(t, clientConfig)
   579  	cli.conn.SetTransportParameters(nil)
   580  	srv := newTestQUICServer(t, serverConfig)
   581  	srv.conn.SetTransportParameters(nil)
   582  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   583  		t.Fatalf("error during connection handshake: %v", err)
   584  	}
   585  	if !called {
   586  		t.Fatal("GetConfigForClient was not called")
   587  	}
   588  }
   589  
   590  func TestQUICContextCancelation(t *testing.T) {
   591  	ctx, cancel := context.WithCancel(context.Background())
   592  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   593  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   594  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   595  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   596  	cli := newTestQUICClient(t, clientConfig)
   597  	cli.conn.SetTransportParameters(nil)
   598  	srv := newTestQUICServer(t, serverConfig)
   599  	srv.conn.SetTransportParameters(nil)
   600  	// Verify that canceling the connection context concurrently does not cause any races.
   601  	// See https://go.dev/issue/77274.
   602  	var wg sync.WaitGroup
   603  	wg.Go(func() {
   604  		_ = runTestQUICConnection(ctx, cli, srv, nil)
   605  	})
   606  	wg.Go(cancel)
   607  	wg.Wait()
   608  }
   609  
   610  func TestQUICDelayedTransportParameters(t *testing.T) {
   611  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   612  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   613  	clientConfig.TLSConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   614  
   615  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   616  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   617  
   618  	cliParams := "client params"
   619  	srvParams := "server params"
   620  
   621  	cli := newTestQUICClient(t, clientConfig)
   622  	srv := newTestQUICServer(t, serverConfig)
   623  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != errTransportParametersRequired {
   624  		t.Fatalf("handshake with no client parameters: %v; want errTransportParametersRequired", err)
   625  	}
   626  	cli.conn.SetTransportParameters([]byte(cliParams))
   627  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != errTransportParametersRequired {
   628  		t.Fatalf("handshake with no server parameters: %v; want errTransportParametersRequired", err)
   629  	}
   630  	srv.conn.SetTransportParameters([]byte(srvParams))
   631  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   632  		t.Fatalf("error during connection handshake: %v", err)
   633  	}
   634  
   635  	if got, want := string(cli.gotParams), srvParams; got != want {
   636  		t.Errorf("client got transport params: %q, want %q", got, want)
   637  	}
   638  	if got, want := string(srv.gotParams), cliParams; got != want {
   639  		t.Errorf("server got transport params: %q, want %q", got, want)
   640  	}
   641  }
   642  
   643  func TestQUICEmptyTransportParameters(t *testing.T) {
   644  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   645  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   646  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   647  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   648  
   649  	cli := newTestQUICClient(t, clientConfig)
   650  	cli.conn.SetTransportParameters(nil)
   651  	srv := newTestQUICServer(t, serverConfig)
   652  	srv.conn.SetTransportParameters(nil)
   653  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   654  		t.Fatalf("error during connection handshake: %v", err)
   655  	}
   656  
   657  	if cli.gotParams == nil {
   658  		t.Errorf("client did not get transport params")
   659  	}
   660  	if srv.gotParams == nil {
   661  		t.Errorf("server did not get transport params")
   662  	}
   663  	if len(cli.gotParams) != 0 {
   664  		t.Errorf("client got transport params: %v, want empty", cli.gotParams)
   665  	}
   666  	if len(srv.gotParams) != 0 {
   667  		t.Errorf("server got transport params: %v, want empty", srv.gotParams)
   668  	}
   669  }
   670  
   671  func TestQUICCanceledWaitingForData(t *testing.T) {
   672  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   673  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   674  	cli := newTestQUICClient(t, clientConfig)
   675  	cli.conn.SetTransportParameters(nil)
   676  	cli.conn.Start(context.Background())
   677  	for cli.conn.NextEvent().Kind != QUICNoEvent {
   678  	}
   679  	err := cli.conn.Close()
   680  	if !errors.Is(err, alertCloseNotify) {
   681  		t.Errorf("conn.Close() = %v, want alertCloseNotify", err)
   682  	}
   683  }
   684  
   685  func TestQUICCanceledWaitingForTransportParams(t *testing.T) {
   686  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   687  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   688  	cli := newTestQUICClient(t, clientConfig)
   689  	cli.conn.Start(context.Background())
   690  	for cli.conn.NextEvent().Kind != QUICTransportParametersRequired {
   691  	}
   692  	err := cli.conn.Close()
   693  	if !errors.Is(err, alertCloseNotify) {
   694  		t.Errorf("conn.Close() = %v, want alertCloseNotify", err)
   695  	}
   696  }
   697  
   698  func TestQUICEarlyData(t *testing.T) {
   699  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   700  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   701  	clientConfig.TLSConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   702  	clientConfig.TLSConfig.NextProtos = []string{"h3"}
   703  
   704  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   705  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   706  	serverConfig.TLSConfig.NextProtos = []string{"h3"}
   707  
   708  	cli := newTestQUICClient(t, clientConfig)
   709  	cli.conn.SetTransportParameters(nil)
   710  	srv := newTestQUICServer(t, serverConfig)
   711  	srv.conn.SetTransportParameters(nil)
   712  	srv.ticketOpts.EarlyData = true
   713  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   714  		t.Fatalf("error during first connection handshake: %v", err)
   715  	}
   716  	if cli.conn.ConnectionState().DidResume {
   717  		t.Errorf("first connection unexpectedly used session resumption")
   718  	}
   719  
   720  	cli2 := newTestQUICClient(t, clientConfig)
   721  	cli2.conn.SetTransportParameters(nil)
   722  	srv2 := newTestQUICServer(t, serverConfig)
   723  	srv2.conn.SetTransportParameters(nil)
   724  	onEvent := func(e QUICEvent, src, dst *testQUICConn) bool {
   725  		switch e.Kind {
   726  		case QUICStoreSession, QUICResumeSession:
   727  			t.Errorf("with EnableSessionEvents=false, got unexpected event %v", e.Kind)
   728  		}
   729  		return false
   730  	}
   731  	if err := runTestQUICConnection(context.Background(), cli2, srv2, onEvent); err != nil {
   732  		t.Fatalf("error during second connection handshake: %v", err)
   733  	}
   734  	if !cli2.conn.ConnectionState().DidResume {
   735  		t.Errorf("second connection did not use session resumption")
   736  	}
   737  	cliSecret := cli2.writeSecret[QUICEncryptionLevelEarly]
   738  	if cliSecret.secret == nil {
   739  		t.Errorf("client did not receive early data write secret")
   740  	}
   741  	srvSecret := srv2.readSecret[QUICEncryptionLevelEarly]
   742  	if srvSecret.secret == nil {
   743  		t.Errorf("server did not receive early data read secret")
   744  	}
   745  	if cliSecret.suite != srvSecret.suite || !bytes.Equal(cliSecret.secret, srvSecret.secret) {
   746  		t.Errorf("client early data secret does not match server")
   747  	}
   748  }
   749  
   750  func TestQUICEarlyDataDeclined(t *testing.T) {
   751  	t.Run("server", func(t *testing.T) {
   752  		testQUICEarlyDataDeclined(t, true)
   753  	})
   754  	t.Run("client", func(t *testing.T) {
   755  		testQUICEarlyDataDeclined(t, false)
   756  	})
   757  }
   758  
   759  func testQUICEarlyDataDeclined(t *testing.T, server bool) {
   760  	clientConfig := &QUICConfig{TLSConfig: testConfigClient()}
   761  	clientConfig.EnableSessionEvents = true
   762  	clientConfig.TLSConfig.MinVersion = VersionTLS13
   763  	clientConfig.TLSConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   764  	clientConfig.TLSConfig.NextProtos = []string{"h3"}
   765  
   766  	serverConfig := &QUICConfig{TLSConfig: testConfigServer()}
   767  	serverConfig.EnableSessionEvents = true
   768  	serverConfig.TLSConfig.MinVersion = VersionTLS13
   769  	serverConfig.TLSConfig.NextProtos = []string{"h3"}
   770  
   771  	cli := newTestQUICClient(t, clientConfig)
   772  	cli.conn.SetTransportParameters(nil)
   773  	srv := newTestQUICServer(t, serverConfig)
   774  	srv.conn.SetTransportParameters(nil)
   775  	srv.ticketOpts.EarlyData = true
   776  	if err := runTestQUICConnection(context.Background(), cli, srv, nil); err != nil {
   777  		t.Fatalf("error during first connection handshake: %v", err)
   778  	}
   779  	if cli.conn.ConnectionState().DidResume {
   780  		t.Errorf("first connection unexpectedly used session resumption")
   781  	}
   782  
   783  	cli2 := newTestQUICClient(t, clientConfig)
   784  	cli2.conn.SetTransportParameters(nil)
   785  	srv2 := newTestQUICServer(t, serverConfig)
   786  	srv2.conn.SetTransportParameters(nil)
   787  	declineEarlyData := func(state *SessionState) {
   788  		state.EarlyData = false
   789  	}
   790  	if server {
   791  		srv2.onResumeSession = declineEarlyData
   792  	} else {
   793  		cli2.onResumeSession = declineEarlyData
   794  	}
   795  	if err := runTestQUICConnection(context.Background(), cli2, srv2, nil); err != nil {
   796  		t.Fatalf("error during second connection handshake: %v", err)
   797  	}
   798  	if !cli2.conn.ConnectionState().DidResume {
   799  		t.Errorf("second connection did not use session resumption")
   800  	}
   801  	_, cliEarlyData := cli2.writeSecret[QUICEncryptionLevelEarly]
   802  	if server {
   803  		if !cliEarlyData {
   804  			t.Errorf("client did not receive early data write secret")
   805  		}
   806  		if !cli2.earlyDataRejected {
   807  			t.Errorf("client did not receive QUICEarlyDataRejected")
   808  		}
   809  	}
   810  	if _, srvEarlyData := srv2.readSecret[QUICEncryptionLevelEarly]; srvEarlyData {
   811  		t.Errorf("server received early data read secret")
   812  	}
   813  }
   814  

View as plain text