xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/core/tls_server_handshaker_test.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "quiche/quic/core/tls_server_handshaker.h"
6 
7 #include <memory>
8 #include <utility>
9 #include <vector>
10 
11 #include "absl/base/macros.h"
12 #include "absl/strings/string_view.h"
13 #include "quiche/quic/core/crypto/certificate_util.h"
14 #include "quiche/quic/core/crypto/client_proof_source.h"
15 #include "quiche/quic/core/crypto/proof_source.h"
16 #include "quiche/quic/core/crypto/quic_random.h"
17 #include "quiche/quic/core/quic_connection_id.h"
18 #include "quiche/quic/core/quic_crypto_client_stream.h"
19 #include "quiche/quic/core/quic_session.h"
20 #include "quiche/quic/core/quic_types.h"
21 #include "quiche/quic/core/quic_utils.h"
22 #include "quiche/quic/core/quic_versions.h"
23 #include "quiche/quic/core/tls_client_handshaker.h"
24 #include "quiche/quic/platform/api/quic_flags.h"
25 #include "quiche/quic/platform/api/quic_logging.h"
26 #include "quiche/quic/platform/api/quic_test.h"
27 #include "quiche/quic/test_tools/crypto_test_utils.h"
28 #include "quiche/quic/test_tools/failing_proof_source.h"
29 #include "quiche/quic/test_tools/fake_proof_source.h"
30 #include "quiche/quic/test_tools/fake_proof_source_handle.h"
31 #include "quiche/quic/test_tools/quic_config_peer.h"
32 #include "quiche/quic/test_tools/quic_test_utils.h"
33 #include "quiche/quic/test_tools/simple_session_cache.h"
34 #include "quiche/quic/test_tools/test_certificates.h"
35 #include "quiche/quic/test_tools/test_ticket_crypter.h"
36 
37 namespace quic {
38 class QuicConnection;
39 class QuicStream;
40 }  // namespace quic
41 
42 using testing::_;
43 using testing::NiceMock;
44 using testing::Return;
45 
46 namespace quic {
47 namespace test {
48 
49 namespace {
50 
51 const char kServerHostname[] = "test.example.com";
52 const uint16_t kServerPort = 443;
53 
54 struct TestParams {
55   ParsedQuicVersion version;
56   bool disable_resumption;
57 };
58 
59 // Used by ::testing::PrintToStringParamName().
PrintToString(const TestParams & p)60 std::string PrintToString(const TestParams& p) {
61   return absl::StrCat(
62       ParsedQuicVersionToString(p.version), "_",
63       (p.disable_resumption ? "ResumptionDisabled" : "ResumptionEnabled"));
64 }
65 
66 // Constructs test permutations.
GetTestParams()67 std::vector<TestParams> GetTestParams() {
68   std::vector<TestParams> params;
69   for (const auto& version : AllSupportedVersionsWithTls()) {
70     for (bool disable_resumption : {false, true}) {
71       params.push_back(TestParams{version, disable_resumption});
72     }
73   }
74   return params;
75 }
76 
77 class TestTlsServerHandshaker : public TlsServerHandshaker {
78  public:
79   static constexpr TransportParameters::TransportParameterId
80       kFailHandshakeParam{0xFFEACA};
81 
TestTlsServerHandshaker(QuicSession * session,const QuicCryptoServerConfig * crypto_config)82   TestTlsServerHandshaker(QuicSession* session,
83                           const QuicCryptoServerConfig* crypto_config)
84       : TlsServerHandshaker(session, crypto_config),
85         proof_source_(crypto_config->proof_source()) {
86     ON_CALL(*this, MaybeCreateProofSourceHandle())
87         .WillByDefault(testing::Invoke(
88             this, &TestTlsServerHandshaker::RealMaybeCreateProofSourceHandle));
89 
90     ON_CALL(*this, OverrideQuicConfigDefaults(_))
91         .WillByDefault(testing::Invoke(
92             this, &TestTlsServerHandshaker::RealOverrideQuicConfigDefaults));
93   }
94 
95   MOCK_METHOD(std::unique_ptr<ProofSourceHandle>, MaybeCreateProofSourceHandle,
96               (), (override));
97 
98   MOCK_METHOD(void, OverrideQuicConfigDefaults, (QuicConfig * config),
99               (override));
100 
SetupProofSourceHandle(FakeProofSourceHandle::Action select_cert_action,FakeProofSourceHandle::Action compute_signature_action,QuicDelayedSSLConfig dealyed_ssl_config=QuicDelayedSSLConfig ())101   void SetupProofSourceHandle(
102       FakeProofSourceHandle::Action select_cert_action,
103       FakeProofSourceHandle::Action compute_signature_action,
104       QuicDelayedSSLConfig dealyed_ssl_config = QuicDelayedSSLConfig()) {
105     EXPECT_CALL(*this, MaybeCreateProofSourceHandle())
106         .WillOnce(
107             testing::Invoke([this, select_cert_action, compute_signature_action,
108                              dealyed_ssl_config]() {
109               auto handle = std::make_unique<FakeProofSourceHandle>(
110                   proof_source_, this, select_cert_action,
111                   compute_signature_action, dealyed_ssl_config);
112               fake_proof_source_handle_ = handle.get();
113               return handle;
114             }));
115   }
116 
fake_proof_source_handle()117   FakeProofSourceHandle* fake_proof_source_handle() {
118     return fake_proof_source_handle_;
119   }
120 
received_client_cert() const121   bool received_client_cert() const { return received_client_cert_; }
122 
123   using TlsServerHandshaker::AdvanceHandshake;
124   using TlsServerHandshaker::expected_ssl_error;
125 
126  protected:
VerifyCertChain(const std::vector<std::string> & certs,std::string * error_details,std::unique_ptr<ProofVerifyDetails> * details,uint8_t * out_alert,std::unique_ptr<ProofVerifierCallback> callback)127   QuicAsyncStatus VerifyCertChain(
128       const std::vector<std::string>& certs, std::string* error_details,
129       std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert,
130       std::unique_ptr<ProofVerifierCallback> callback) override {
131     received_client_cert_ = true;
132     return TlsServerHandshaker::VerifyCertChain(certs, error_details, details,
133                                                 out_alert, std::move(callback));
134   }
135 
ProcessAdditionalTransportParameters(const TransportParameters & params)136   bool ProcessAdditionalTransportParameters(
137       const TransportParameters& params) override {
138     return !params.custom_parameters.contains(kFailHandshakeParam);
139   }
140 
141  private:
RealMaybeCreateProofSourceHandle()142   std::unique_ptr<ProofSourceHandle> RealMaybeCreateProofSourceHandle() {
143     return TlsServerHandshaker::MaybeCreateProofSourceHandle();
144   }
145 
RealOverrideQuicConfigDefaults(QuicConfig * config)146   void RealOverrideQuicConfigDefaults(QuicConfig* config) {
147     return TlsServerHandshaker::OverrideQuicConfigDefaults(config);
148   }
149 
150   // Owned by TlsServerHandshaker.
151   FakeProofSourceHandle* fake_proof_source_handle_ = nullptr;
152   ProofSource* proof_source_ = nullptr;
153   bool received_client_cert_ = false;
154 };
155 
156 class TlsServerHandshakerTestSession : public TestQuicSpdyServerSession {
157  public:
158   using TestQuicSpdyServerSession::TestQuicSpdyServerSession;
159 
CreateQuicCryptoServerStream(const QuicCryptoServerConfig * crypto_config,QuicCompressedCertsCache *)160   std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream(
161       const QuicCryptoServerConfig* crypto_config,
162       QuicCompressedCertsCache* /*compressed_certs_cache*/) override {
163     if (connection()->version().handshake_protocol == PROTOCOL_TLS1_3) {
164       return std::make_unique<NiceMock<TestTlsServerHandshaker>>(this,
165                                                                  crypto_config);
166     }
167 
168     QUICHE_CHECK(false) << "Unsupported handshake protocol: "
169                         << connection()->version().handshake_protocol;
170     return nullptr;
171   }
172 };
173 
174 class TlsServerHandshakerTest : public QuicTestWithParam<TestParams> {
175  public:
TlsServerHandshakerTest()176   TlsServerHandshakerTest()
177       : server_compressed_certs_cache_(
178             QuicCompressedCertsCache::kQuicCompressedCertsCacheSize),
179         server_id_(kServerHostname, kServerPort, false),
180         supported_versions_({GetParam().version}) {
181     SetQuicFlag(quic_disable_server_tls_resumption,
182                 GetParam().disable_resumption);
183     client_crypto_config_ = std::make_unique<QuicCryptoClientConfig>(
184         crypto_test_utils::ProofVerifierForTesting(),
185         std::make_unique<test::SimpleSessionCache>());
186     InitializeServerConfig();
187     InitializeServer();
188     InitializeFakeClient();
189   }
190 
~TlsServerHandshakerTest()191   ~TlsServerHandshakerTest() override {
192     // Ensure that anything that might reference |helpers_| is destroyed before
193     // |helpers_| is destroyed.
194     server_session_.reset();
195     client_session_.reset();
196     helpers_.clear();
197     alarm_factories_.clear();
198   }
199 
InitializeServerConfig()200   void InitializeServerConfig() {
201     auto ticket_crypter = std::make_unique<TestTicketCrypter>();
202     ticket_crypter_ = ticket_crypter.get();
203     auto proof_source = std::make_unique<FakeProofSource>();
204     proof_source_ = proof_source.get();
205     proof_source_->SetTicketCrypter(std::move(ticket_crypter));
206     server_crypto_config_ = std::make_unique<QuicCryptoServerConfig>(
207         QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(),
208         std::move(proof_source), KeyExchangeSource::Default());
209   }
210 
InitializeServerConfigWithFailingProofSource()211   void InitializeServerConfigWithFailingProofSource() {
212     server_crypto_config_ = std::make_unique<QuicCryptoServerConfig>(
213         QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(),
214         std::make_unique<FailingProofSource>(), KeyExchangeSource::Default());
215   }
216 
CreateTlsServerHandshakerTestSession(MockQuicConnectionHelper * helper,MockAlarmFactory * alarm_factory)217   void CreateTlsServerHandshakerTestSession(MockQuicConnectionHelper* helper,
218                                             MockAlarmFactory* alarm_factory) {
219     server_connection_ = new PacketSavingConnection(
220         helper, alarm_factory, Perspective::IS_SERVER,
221         ParsedVersionOfIndex(supported_versions_, 0));
222 
223     TlsServerHandshakerTestSession* server_session =
224         new TlsServerHandshakerTestSession(
225             server_connection_, DefaultQuicConfig(), supported_versions_,
226             server_crypto_config_.get(), &server_compressed_certs_cache_);
227     server_session->set_client_cert_mode(initial_client_cert_mode_);
228     server_session->Initialize();
229 
230     // We advance the clock initially because the default time is zero and the
231     // strike register worries that we've just overflowed a uint32_t time.
232     server_connection_->AdvanceTime(QuicTime::Delta::FromSeconds(100000));
233 
234     QUICHE_CHECK(server_session);
235     server_session_.reset(server_session);
236   }
237 
InitializeServerWithFakeProofSourceHandle()238   void InitializeServerWithFakeProofSourceHandle() {
239     helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>());
240     alarm_factories_.push_back(std::make_unique<MockAlarmFactory>());
241     CreateTlsServerHandshakerTestSession(helpers_.back().get(),
242                                          alarm_factories_.back().get());
243     server_handshaker_ = static_cast<NiceMock<TestTlsServerHandshaker>*>(
244         server_session_->GetMutableCryptoStream());
245     EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _))
246         .Times(testing::AnyNumber());
247     EXPECT_CALL(*server_session_, SelectAlpn(_))
248         .WillRepeatedly([this](const std::vector<absl::string_view>& alpns) {
249           return std::find(
250               alpns.cbegin(), alpns.cend(),
251               AlpnForVersion(server_session_->connection()->version()));
252         });
253     crypto_test_utils::SetupCryptoServerConfigForTest(
254         server_connection_->clock(), server_connection_->random_generator(),
255         server_crypto_config_.get());
256   }
257 
258   // Initializes the crypto server stream state for testing.  May be
259   // called multiple times.
InitializeServer()260   void InitializeServer() {
261     TestQuicSpdyServerSession* server_session = nullptr;
262     helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>());
263     alarm_factories_.push_back(std::make_unique<MockAlarmFactory>());
264     CreateServerSessionForTest(
265         server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_,
266         helpers_.back().get(), alarm_factories_.back().get(),
267         server_crypto_config_.get(), &server_compressed_certs_cache_,
268         &server_connection_, &server_session);
269     QUICHE_CHECK(server_session);
270     server_session_.reset(server_session);
271     server_handshaker_ = nullptr;
272     EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _))
273         .Times(testing::AnyNumber());
274     EXPECT_CALL(*server_session_, SelectAlpn(_))
275         .WillRepeatedly([this](const std::vector<absl::string_view>& alpns) {
276           return std::find(
277               alpns.cbegin(), alpns.cend(),
278               AlpnForVersion(server_session_->connection()->version()));
279         });
280     crypto_test_utils::SetupCryptoServerConfigForTest(
281         server_connection_->clock(), server_connection_->random_generator(),
282         server_crypto_config_.get());
283   }
284 
server_stream()285   QuicCryptoServerStreamBase* server_stream() {
286     return server_session_->GetMutableCryptoStream();
287   }
288 
client_stream()289   QuicCryptoClientStream* client_stream() {
290     return client_session_->GetMutableCryptoStream();
291   }
292 
293   // Initializes a fake client, and all its associated state, for
294   // testing.  May be called multiple times.
InitializeFakeClient()295   void InitializeFakeClient() {
296     TestQuicSpdyClientSession* client_session = nullptr;
297     helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>());
298     alarm_factories_.push_back(std::make_unique<MockAlarmFactory>());
299     CreateClientSessionForTest(
300         server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_,
301         helpers_.back().get(), alarm_factories_.back().get(),
302         client_crypto_config_.get(), &client_connection_, &client_session);
303     const std::string default_alpn =
304         AlpnForVersion(client_connection_->version());
305     ON_CALL(*client_session, GetAlpnsToOffer())
306         .WillByDefault(Return(std::vector<std::string>({default_alpn})));
307     QUICHE_CHECK(client_session);
308     client_session_.reset(client_session);
309     moved_messages_counts_ = {0, 0};
310   }
311 
CompleteCryptoHandshake()312   void CompleteCryptoHandshake() {
313     while (!client_stream()->one_rtt_keys_available() ||
314            !server_stream()->one_rtt_keys_available()) {
315       auto previous_moved_messages_counts = moved_messages_counts_;
316       AdvanceHandshakeWithFakeClient();
317       // Check that the handshake has made forward progress
318       ASSERT_NE(previous_moved_messages_counts, moved_messages_counts_);
319     }
320   }
321 
322   // Performs a single round of handshake message-exchange between the
323   // client and server.
AdvanceHandshakeWithFakeClient()324   void AdvanceHandshakeWithFakeClient() {
325     QUICHE_CHECK(server_connection_);
326     QUICHE_CHECK(client_session_ != nullptr);
327 
328     EXPECT_CALL(*client_session_, OnProofValid(_)).Times(testing::AnyNumber());
329     EXPECT_CALL(*client_session_, OnProofVerifyDetailsAvailable(_))
330         .Times(testing::AnyNumber());
331     EXPECT_CALL(*client_connection_, OnCanWrite()).Times(testing::AnyNumber());
332     EXPECT_CALL(*server_connection_, OnCanWrite()).Times(testing::AnyNumber());
333     // Call CryptoConnect if we haven't moved any client messages yet.
334     if (moved_messages_counts_.first == 0) {
335       client_stream()->CryptoConnect();
336     }
337     moved_messages_counts_ = crypto_test_utils::AdvanceHandshake(
338         client_connection_, client_stream(), moved_messages_counts_.first,
339         server_connection_, server_stream(), moved_messages_counts_.second);
340   }
341 
ExpectHandshakeSuccessful()342   void ExpectHandshakeSuccessful() {
343     EXPECT_TRUE(client_stream()->one_rtt_keys_available());
344     EXPECT_TRUE(client_stream()->encryption_established());
345     EXPECT_TRUE(server_stream()->one_rtt_keys_available());
346     EXPECT_TRUE(server_stream()->encryption_established());
347     EXPECT_EQ(HANDSHAKE_COMPLETE, client_stream()->GetHandshakeState());
348     EXPECT_EQ(HANDSHAKE_CONFIRMED, server_stream()->GetHandshakeState());
349 
350     const auto& client_crypto_params =
351         client_stream()->crypto_negotiated_params();
352     const auto& server_crypto_params =
353         server_stream()->crypto_negotiated_params();
354     // The TLS params should be filled in on the client.
355     EXPECT_NE(0, client_crypto_params.cipher_suite);
356     EXPECT_NE(0, client_crypto_params.key_exchange_group);
357     EXPECT_NE(0, client_crypto_params.peer_signature_algorithm);
358 
359     // The cipher suite and key exchange group should match on the client and
360     // server.
361     EXPECT_EQ(client_crypto_params.cipher_suite,
362               server_crypto_params.cipher_suite);
363     EXPECT_EQ(client_crypto_params.key_exchange_group,
364               server_crypto_params.key_exchange_group);
365     // We don't support client certs on the server (yet), so the server
366     // shouldn't have a peer signature algorithm to report.
367     EXPECT_EQ(0, server_crypto_params.peer_signature_algorithm);
368   }
369 
370   // Should only be called when using FakeProofSourceHandle.
last_select_cert_args() const371   FakeProofSourceHandle::SelectCertArgs last_select_cert_args() const {
372     QUICHE_CHECK(server_handshaker_ &&
373                  server_handshaker_->fake_proof_source_handle());
374     QUICHE_CHECK(!server_handshaker_->fake_proof_source_handle()
375                       ->all_select_cert_args()
376                       .empty());
377     return server_handshaker_->fake_proof_source_handle()
378         ->all_select_cert_args()
379         .back();
380   }
381 
382   // Should only be called when using FakeProofSourceHandle.
last_compute_signature_args() const383   FakeProofSourceHandle::ComputeSignatureArgs last_compute_signature_args()
384       const {
385     QUICHE_CHECK(server_handshaker_ &&
386                  server_handshaker_->fake_proof_source_handle());
387     QUICHE_CHECK(!server_handshaker_->fake_proof_source_handle()
388                       ->all_compute_signature_args()
389                       .empty());
390     return server_handshaker_->fake_proof_source_handle()
391         ->all_compute_signature_args()
392         .back();
393   }
394 
395  protected:
396   // Setup the client to send a (self-signed) client cert to the server, if
397   // requested. InitializeFakeClient() must be called after this to take effect.
SetupClientCert()398   bool SetupClientCert() {
399     auto client_proof_source = std::make_unique<DefaultClientProofSource>();
400 
401     CertificatePrivateKey client_cert_key(
402         MakeKeyPairForSelfSignedCertificate());
403 
404     CertificateOptions options;
405     options.subject = "CN=subject";
406     options.serial_number = 0x12345678;
407     options.validity_start = {2020, 1, 1, 0, 0, 0};
408     options.validity_end = {2049, 12, 31, 0, 0, 0};
409     std::string der_cert =
410         CreateSelfSignedCertificate(*client_cert_key.private_key(), options);
411 
412     quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>
413         client_cert_chain(new ClientProofSource::Chain({der_cert}));
414 
415     if (!client_proof_source->AddCertAndKey({"*"}, client_cert_chain,
416                                             std::move(client_cert_key))) {
417       return false;
418     }
419 
420     client_crypto_config_->set_proof_source(std::move(client_proof_source));
421     return true;
422   }
423 
424   // Every connection gets its own MockQuicConnectionHelper and
425   // MockAlarmFactory, tracked separately from the server and client state so
426   // their lifetimes persist through the whole test.
427   std::vector<std::unique_ptr<MockQuicConnectionHelper>> helpers_;
428   std::vector<std::unique_ptr<MockAlarmFactory>> alarm_factories_;
429 
430   // Server state.
431   PacketSavingConnection* server_connection_;
432   std::unique_ptr<TestQuicSpdyServerSession> server_session_;
433   // Only set when initialized with InitializeServerWithFakeProofSourceHandle.
434   NiceMock<TestTlsServerHandshaker>* server_handshaker_ = nullptr;
435   TestTicketCrypter* ticket_crypter_;  // owned by proof_source_
436   FakeProofSource* proof_source_;      // owned by server_crypto_config_
437   std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_;
438   QuicCompressedCertsCache server_compressed_certs_cache_;
439   QuicServerId server_id_;
440   ClientCertMode initial_client_cert_mode_ = ClientCertMode::kNone;
441 
442   // Client state.
443   PacketSavingConnection* client_connection_;
444   std::unique_ptr<QuicCryptoClientConfig> client_crypto_config_;
445   std::unique_ptr<TestQuicSpdyClientSession> client_session_;
446 
447   crypto_test_utils::FakeClientOptions client_options_;
448   // How many handshake messages have been moved from client to server and
449   // server to client.
450   std::pair<size_t, size_t> moved_messages_counts_ = {0, 0};
451 
452   // Which QUIC versions the client and server support.
453   ParsedQuicVersionVector supported_versions_;
454 };
455 
456 INSTANTIATE_TEST_SUITE_P(TlsServerHandshakerTests, TlsServerHandshakerTest,
457                          ::testing::ValuesIn(GetTestParams()),
458                          ::testing::PrintToStringParamName());
459 
TEST_P(TlsServerHandshakerTest,NotInitiallyConected)460 TEST_P(TlsServerHandshakerTest, NotInitiallyConected) {
461   EXPECT_FALSE(server_stream()->encryption_established());
462   EXPECT_FALSE(server_stream()->one_rtt_keys_available());
463 }
464 
TEST_P(TlsServerHandshakerTest,ConnectedAfterTlsHandshake)465 TEST_P(TlsServerHandshakerTest, ConnectedAfterTlsHandshake) {
466   CompleteCryptoHandshake();
467   EXPECT_EQ(PROTOCOL_TLS1_3, server_stream()->handshake_protocol());
468   ExpectHandshakeSuccessful();
469 }
470 
TEST_P(TlsServerHandshakerTest,HandshakeWithAsyncSelectCertSuccess)471 TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertSuccess) {
472   InitializeServerWithFakeProofSourceHandle();
473   server_handshaker_->SetupProofSourceHandle(
474       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
475       /*compute_signature_action=*/FakeProofSourceHandle::Action::
476           DELEGATE_SYNC);
477 
478   EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0);
479   EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0);
480 
481   // Start handshake.
482   AdvanceHandshakeWithFakeClient();
483 
484   ASSERT_TRUE(
485       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
486   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
487 
488   CompleteCryptoHandshake();
489 
490   ExpectHandshakeSuccessful();
491 }
492 
TEST_P(TlsServerHandshakerTest,HandshakeWithAsyncSelectCertFailure)493 TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertFailure) {
494   InitializeServerWithFakeProofSourceHandle();
495   server_handshaker_->SetupProofSourceHandle(
496       /*select_cert_action=*/FakeProofSourceHandle::Action::FAIL_ASYNC,
497       /*compute_signature_action=*/FakeProofSourceHandle::Action::
498           DELEGATE_SYNC);
499 
500   // Start handshake.
501   AdvanceHandshakeWithFakeClient();
502 
503   ASSERT_TRUE(
504       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
505   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
506 
507   // Check that the server didn't send any handshake messages, because it failed
508   // to handshake.
509   EXPECT_EQ(moved_messages_counts_.second, 0u);
510 }
511 
TEST_P(TlsServerHandshakerTest,HandshakeWithAsyncSelectCertAndSignature)512 TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertAndSignature) {
513   InitializeServerWithFakeProofSourceHandle();
514   server_handshaker_->SetupProofSourceHandle(
515       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
516       /*compute_signature_action=*/FakeProofSourceHandle::Action::
517           DELEGATE_ASYNC);
518 
519   EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0);
520   EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0);
521 
522   // Start handshake.
523   AdvanceHandshakeWithFakeClient();
524 
525   // A select cert operation is now pending.
526   ASSERT_TRUE(
527       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
528   EXPECT_EQ(server_handshaker_->expected_ssl_error(),
529             SSL_ERROR_PENDING_CERTIFICATE);
530 
531   // Complete the pending select cert. It should advance the handshake to
532   // compute a signature, which will also be saved as a pending operation.
533   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
534 
535   // A compute signature operation is now pending.
536   ASSERT_TRUE(
537       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
538   EXPECT_EQ(server_handshaker_->expected_ssl_error(),
539             SSL_ERROR_WANT_PRIVATE_KEY_OPERATION);
540 
541   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
542 
543   CompleteCryptoHandshake();
544 
545   ExpectHandshakeSuccessful();
546 }
547 
TEST_P(TlsServerHandshakerTest,HandshakeWithAsyncSignature)548 TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSignature) {
549   EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0);
550   EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0);
551   // Enable FakeProofSource to capture call to ComputeTlsSignature and run it
552   // asynchronously.
553   proof_source_->Activate();
554 
555   // Start handshake.
556   AdvanceHandshakeWithFakeClient();
557 
558   ASSERT_EQ(proof_source_->NumPendingCallbacks(), 1);
559   proof_source_->InvokePendingCallback(0);
560 
561   CompleteCryptoHandshake();
562 
563   ExpectHandshakeSuccessful();
564 }
565 
TEST_P(TlsServerHandshakerTest,CancelPendingSelectCert)566 TEST_P(TlsServerHandshakerTest, CancelPendingSelectCert) {
567   InitializeServerWithFakeProofSourceHandle();
568   server_handshaker_->SetupProofSourceHandle(
569       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
570       /*compute_signature_action=*/FakeProofSourceHandle::Action::
571           DELEGATE_SYNC);
572 
573   EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0);
574   EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0);
575 
576   // Start handshake.
577   AdvanceHandshakeWithFakeClient();
578 
579   ASSERT_TRUE(
580       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
581   server_handshaker_->CancelOutstandingCallbacks();
582   ASSERT_FALSE(
583       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
584   // CompletePendingOperation should be noop.
585   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
586 }
587 
TEST_P(TlsServerHandshakerTest,CancelPendingSignature)588 TEST_P(TlsServerHandshakerTest, CancelPendingSignature) {
589   EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0);
590   EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0);
591   // Enable FakeProofSource to capture call to ComputeTlsSignature and run it
592   // asynchronously.
593   proof_source_->Activate();
594 
595   // Start handshake.
596   AdvanceHandshakeWithFakeClient();
597 
598   ASSERT_EQ(proof_source_->NumPendingCallbacks(), 1);
599   server_session_ = nullptr;
600 
601   proof_source_->InvokePendingCallback(0);
602 }
603 
TEST_P(TlsServerHandshakerTest,ExtractSNI)604 TEST_P(TlsServerHandshakerTest, ExtractSNI) {
605   CompleteCryptoHandshake();
606   ExpectHandshakeSuccessful();
607 
608   EXPECT_EQ(server_stream()->crypto_negotiated_params().sni,
609             "test.example.com");
610 }
611 
TEST_P(TlsServerHandshakerTest,ServerConnectionIdPassedToSelectCert)612 TEST_P(TlsServerHandshakerTest, ServerConnectionIdPassedToSelectCert) {
613   InitializeServerWithFakeProofSourceHandle();
614 
615   // Disable early data.
616   server_session_->set_early_data_enabled(false);
617 
618   server_handshaker_->SetupProofSourceHandle(
619       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
620       /*compute_signature_action=*/FakeProofSourceHandle::Action::
621           DELEGATE_SYNC);
622   InitializeFakeClient();
623   CompleteCryptoHandshake();
624   ExpectHandshakeSuccessful();
625 
626   EXPECT_EQ(last_select_cert_args().original_connection_id, TestConnectionId());
627 }
628 
TEST_P(TlsServerHandshakerTest,HostnameForCertSelectionAndComputeSignature)629 TEST_P(TlsServerHandshakerTest, HostnameForCertSelectionAndComputeSignature) {
630   // Client uses upper case letters in hostname. It is considered valid by
631   // QuicHostnameUtils::IsValidSNI, but it should be normalized for cert
632   // selection.
633   server_id_ = QuicServerId("tEsT.EXAMPLE.CoM", kServerPort, false);
634   InitializeServerWithFakeProofSourceHandle();
635   server_handshaker_->SetupProofSourceHandle(
636       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
637       /*compute_signature_action=*/FakeProofSourceHandle::Action::
638           DELEGATE_SYNC);
639   InitializeFakeClient();
640   CompleteCryptoHandshake();
641   ExpectHandshakeSuccessful();
642 
643   EXPECT_EQ(server_stream()->crypto_negotiated_params().sni,
644             "test.example.com");
645 
646   EXPECT_EQ(last_select_cert_args().hostname, "test.example.com");
647   EXPECT_EQ(last_compute_signature_args().hostname, "test.example.com");
648 }
649 
TEST_P(TlsServerHandshakerTest,SSLConfigForCertSelection)650 TEST_P(TlsServerHandshakerTest, SSLConfigForCertSelection) {
651   InitializeServerWithFakeProofSourceHandle();
652 
653   // Disable early data.
654   server_session_->set_early_data_enabled(false);
655 
656   server_handshaker_->SetupProofSourceHandle(
657       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
658       /*compute_signature_action=*/FakeProofSourceHandle::Action::
659           DELEGATE_SYNC);
660   InitializeFakeClient();
661   CompleteCryptoHandshake();
662   ExpectHandshakeSuccessful();
663 
664   EXPECT_FALSE(last_select_cert_args().ssl_config.early_data_enabled);
665 }
666 
TEST_P(TlsServerHandshakerTest,ConnectionClosedOnTlsError)667 TEST_P(TlsServerHandshakerTest, ConnectionClosedOnTlsError) {
668   EXPECT_CALL(*server_connection_,
669               CloseConnection(QUIC_HANDSHAKE_FAILED, _, _, _));
670 
671   // Send a zero-length ClientHello from client to server.
672   char bogus_handshake_message[] = {
673       // Handshake struct (RFC 8446 appendix B.3)
674       1,        // HandshakeType client_hello
675       0, 0, 0,  // uint24 length
676   };
677 
678   // Install a packet flusher such that the packets generated by
679   // |server_connection_| in response to this handshake message are more likely
680   // to be coalesced and/or batched in the writer.
681   //
682   // This is required by TlsServerHandshaker because without the flusher, it
683   // tends to generate many small, uncoalesced packets, one per
684   // TlsHandshaker::WriteMessage.
685   QuicConnection::ScopedPacketFlusher flusher(server_connection_);
686   server_stream()->crypto_message_parser()->ProcessInput(
687       absl::string_view(bogus_handshake_message,
688                         ABSL_ARRAYSIZE(bogus_handshake_message)),
689       ENCRYPTION_INITIAL);
690 
691   EXPECT_FALSE(server_stream()->one_rtt_keys_available());
692 }
693 
TEST_P(TlsServerHandshakerTest,ClientSendingBadALPN)694 TEST_P(TlsServerHandshakerTest, ClientSendingBadALPN) {
695   const std::string kTestBadClientAlpn = "bad-client-alpn";
696   EXPECT_CALL(*client_session_, GetAlpnsToOffer())
697       .WillOnce(Return(std::vector<std::string>({kTestBadClientAlpn})));
698 
699   EXPECT_CALL(*server_connection_,
700               CloseConnection(QUIC_HANDSHAKE_FAILED,
701                               static_cast<QuicIetfTransportErrorCodes>(
702                                   CRYPTO_ERROR_FIRST + 120),
703                               "TLS handshake failure (ENCRYPTION_INITIAL) 120: "
704                               "no application protocol",
705                               _));
706 
707   AdvanceHandshakeWithFakeClient();
708 
709   EXPECT_FALSE(client_stream()->one_rtt_keys_available());
710   EXPECT_FALSE(client_stream()->encryption_established());
711   EXPECT_FALSE(server_stream()->one_rtt_keys_available());
712   EXPECT_FALSE(server_stream()->encryption_established());
713 }
714 
TEST_P(TlsServerHandshakerTest,CustomALPNNegotiation)715 TEST_P(TlsServerHandshakerTest, CustomALPNNegotiation) {
716   EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0);
717   EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0);
718 
719   const std::string kTestAlpn = "A Custom ALPN Value";
720   const std::vector<std::string> kTestAlpns(
721       {"foo", "bar", kTestAlpn, "something else"});
722   EXPECT_CALL(*client_session_, GetAlpnsToOffer())
723       .WillRepeatedly(Return(kTestAlpns));
724   EXPECT_CALL(*server_session_, SelectAlpn(_))
725       .WillOnce(
726           [kTestAlpn, kTestAlpns](const std::vector<absl::string_view>& alpns) {
727             EXPECT_THAT(alpns, testing::ElementsAreArray(kTestAlpns));
728             return std::find(alpns.cbegin(), alpns.cend(), kTestAlpn);
729           });
730   EXPECT_CALL(*client_session_, OnAlpnSelected(absl::string_view(kTestAlpn)));
731   EXPECT_CALL(*server_session_, OnAlpnSelected(absl::string_view(kTestAlpn)));
732 
733   CompleteCryptoHandshake();
734   ExpectHandshakeSuccessful();
735 }
736 
TEST_P(TlsServerHandshakerTest,RejectInvalidSNI)737 TEST_P(TlsServerHandshakerTest, RejectInvalidSNI) {
738   server_id_ = QuicServerId("invalid!.example.com", kServerPort, false);
739   InitializeFakeClient();
740   static_cast<TlsClientHandshaker*>(
741       QuicCryptoClientStreamPeer::GetHandshaker(client_stream()))
742       ->AllowInvalidSNIForTests();
743 
744   // Run the handshake and expect it to fail.
745   AdvanceHandshakeWithFakeClient();
746   EXPECT_FALSE(server_stream()->encryption_established());
747   EXPECT_FALSE(server_stream()->one_rtt_keys_available());
748 }
749 
TEST_P(TlsServerHandshakerTest,Resumption)750 TEST_P(TlsServerHandshakerTest, Resumption) {
751   // Do the first handshake
752   InitializeFakeClient();
753   CompleteCryptoHandshake();
754   ExpectHandshakeSuccessful();
755   EXPECT_FALSE(client_stream()->IsResumption());
756   EXPECT_FALSE(server_stream()->IsResumption());
757   EXPECT_FALSE(server_stream()->ResumptionAttempted());
758 
759   // Now do another handshake
760   InitializeServer();
761   InitializeFakeClient();
762   CompleteCryptoHandshake();
763   ExpectHandshakeSuccessful();
764   EXPECT_NE(client_stream()->IsResumption(), GetParam().disable_resumption);
765   EXPECT_NE(server_stream()->IsResumption(), GetParam().disable_resumption);
766   EXPECT_NE(server_stream()->ResumptionAttempted(),
767             GetParam().disable_resumption);
768 }
769 
TEST_P(TlsServerHandshakerTest,ResumptionWithAsyncDecryptCallback)770 TEST_P(TlsServerHandshakerTest, ResumptionWithAsyncDecryptCallback) {
771   // Do the first handshake
772   InitializeFakeClient();
773   CompleteCryptoHandshake();
774   ExpectHandshakeSuccessful();
775 
776   ticket_crypter_->SetRunCallbacksAsync(true);
777   // Now do another handshake
778   InitializeServer();
779   InitializeFakeClient();
780 
781   AdvanceHandshakeWithFakeClient();
782   if (GetParam().disable_resumption) {
783     ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 0u);
784     return;
785   }
786   // Test that the DecryptCallback will be run asynchronously, and then run it.
787   ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 1u);
788   ticket_crypter_->RunPendingCallback(0);
789 
790   CompleteCryptoHandshake();
791   ExpectHandshakeSuccessful();
792   EXPECT_TRUE(client_stream()->IsResumption());
793   EXPECT_TRUE(server_stream()->IsResumption());
794   EXPECT_TRUE(server_stream()->ResumptionAttempted());
795 }
796 
TEST_P(TlsServerHandshakerTest,ResumptionWithPlaceholderTicket)797 TEST_P(TlsServerHandshakerTest, ResumptionWithPlaceholderTicket) {
798   // Do the first handshake
799   InitializeFakeClient();
800 
801   ticket_crypter_->set_fail_encrypt(true);
802   CompleteCryptoHandshake();
803   ExpectHandshakeSuccessful();
804   EXPECT_FALSE(client_stream()->IsResumption());
805   EXPECT_FALSE(server_stream()->IsResumption());
806   EXPECT_FALSE(server_stream()->ResumptionAttempted());
807 
808   // Now do another handshake. It should end up with a full handshake because
809   // the placeholder ticket is undecryptable.
810   InitializeServer();
811   InitializeFakeClient();
812   CompleteCryptoHandshake();
813   ExpectHandshakeSuccessful();
814   EXPECT_FALSE(client_stream()->IsResumption());
815   EXPECT_FALSE(server_stream()->IsResumption());
816   EXPECT_NE(server_stream()->ResumptionAttempted(),
817             GetParam().disable_resumption);
818 }
819 
TEST_P(TlsServerHandshakerTest,AdvanceHandshakeDuringAsyncDecryptCallback)820 TEST_P(TlsServerHandshakerTest, AdvanceHandshakeDuringAsyncDecryptCallback) {
821   if (GetParam().disable_resumption) {
822     return;
823   }
824 
825   // Do the first handshake
826   InitializeFakeClient();
827   CompleteCryptoHandshake();
828   ExpectHandshakeSuccessful();
829 
830   ticket_crypter_->SetRunCallbacksAsync(true);
831   // Now do another handshake
832   InitializeServerWithFakeProofSourceHandle();
833   server_handshaker_->SetupProofSourceHandle(
834       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
835       /*compute_signature_action=*/FakeProofSourceHandle::Action::
836           DELEGATE_SYNC);
837   InitializeFakeClient();
838 
839   AdvanceHandshakeWithFakeClient();
840 
841   // Ensure an async DecryptCallback is now pending.
842   ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 1u);
843 
844   {
845     QuicConnection::ScopedPacketFlusher flusher(server_connection_);
846     server_handshaker_->AdvanceHandshake();
847   }
848 
849   // This will delete |server_handshaker_|.
850   server_session_ = nullptr;
851 
852   ticket_crypter_->RunPendingCallback(0);  // Should not crash.
853 }
854 
TEST_P(TlsServerHandshakerTest,ResumptionWithFailingDecryptCallback)855 TEST_P(TlsServerHandshakerTest, ResumptionWithFailingDecryptCallback) {
856   if (GetParam().disable_resumption) {
857     return;
858   }
859 
860   // Do the first handshake
861   InitializeFakeClient();
862   CompleteCryptoHandshake();
863   ExpectHandshakeSuccessful();
864 
865   ticket_crypter_->set_fail_decrypt(true);
866   // Now do another handshake
867   InitializeServer();
868   InitializeFakeClient();
869   CompleteCryptoHandshake();
870   ExpectHandshakeSuccessful();
871   EXPECT_FALSE(client_stream()->IsResumption());
872   EXPECT_FALSE(server_stream()->IsResumption());
873   EXPECT_TRUE(server_stream()->ResumptionAttempted());
874 }
875 
TEST_P(TlsServerHandshakerTest,ResumptionWithFailingAsyncDecryptCallback)876 TEST_P(TlsServerHandshakerTest, ResumptionWithFailingAsyncDecryptCallback) {
877   if (GetParam().disable_resumption) {
878     return;
879   }
880 
881   // Do the first handshake
882   InitializeFakeClient();
883   CompleteCryptoHandshake();
884   ExpectHandshakeSuccessful();
885 
886   ticket_crypter_->set_fail_decrypt(true);
887   ticket_crypter_->SetRunCallbacksAsync(true);
888   // Now do another handshake
889   InitializeServer();
890   InitializeFakeClient();
891 
892   AdvanceHandshakeWithFakeClient();
893   // Test that the DecryptCallback will be run asynchronously, and then run it.
894   ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 1u);
895   ticket_crypter_->RunPendingCallback(0);
896 
897   CompleteCryptoHandshake();
898   ExpectHandshakeSuccessful();
899   EXPECT_FALSE(client_stream()->IsResumption());
900   EXPECT_FALSE(server_stream()->IsResumption());
901   EXPECT_TRUE(server_stream()->ResumptionAttempted());
902 }
903 
TEST_P(TlsServerHandshakerTest,HandshakeFailsWithFailingProofSource)904 TEST_P(TlsServerHandshakerTest, HandshakeFailsWithFailingProofSource) {
905   InitializeServerConfigWithFailingProofSource();
906   InitializeServer();
907   InitializeFakeClient();
908 
909   // Attempt handshake.
910   AdvanceHandshakeWithFakeClient();
911   // Check that the server didn't send any handshake messages, because it failed
912   // to handshake.
913   EXPECT_EQ(moved_messages_counts_.second, 0u);
914 }
915 
TEST_P(TlsServerHandshakerTest,ZeroRttResumption)916 TEST_P(TlsServerHandshakerTest, ZeroRttResumption) {
917   std::vector<uint8_t> application_state = {0, 1, 2, 3};
918 
919   // Do the first handshake
920   server_stream()->SetServerApplicationStateForResumption(
921       std::make_unique<ApplicationState>(application_state));
922   InitializeFakeClient();
923   CompleteCryptoHandshake();
924   ExpectHandshakeSuccessful();
925   EXPECT_FALSE(client_stream()->IsResumption());
926   EXPECT_FALSE(server_stream()->IsZeroRtt());
927 
928   // Now do another handshake
929   InitializeServer();
930   server_stream()->SetServerApplicationStateForResumption(
931       std::make_unique<ApplicationState>(application_state));
932   InitializeFakeClient();
933   CompleteCryptoHandshake();
934   ExpectHandshakeSuccessful();
935   EXPECT_NE(client_stream()->IsResumption(), GetParam().disable_resumption);
936   EXPECT_NE(server_stream()->IsZeroRtt(), GetParam().disable_resumption);
937 }
938 
TEST_P(TlsServerHandshakerTest,ZeroRttRejectOnApplicationStateChange)939 TEST_P(TlsServerHandshakerTest, ZeroRttRejectOnApplicationStateChange) {
940   std::vector<uint8_t> original_application_state = {1, 2};
941   std::vector<uint8_t> new_application_state = {3, 4};
942 
943   // Do the first handshake
944   server_stream()->SetServerApplicationStateForResumption(
945       std::make_unique<ApplicationState>(original_application_state));
946   InitializeFakeClient();
947   CompleteCryptoHandshake();
948   ExpectHandshakeSuccessful();
949   EXPECT_FALSE(client_stream()->IsResumption());
950   EXPECT_FALSE(server_stream()->IsZeroRtt());
951 
952   // Do another handshake, but change the application state
953   InitializeServer();
954   server_stream()->SetServerApplicationStateForResumption(
955       std::make_unique<ApplicationState>(new_application_state));
956   InitializeFakeClient();
957   CompleteCryptoHandshake();
958   ExpectHandshakeSuccessful();
959   EXPECT_NE(client_stream()->IsResumption(), GetParam().disable_resumption);
960   EXPECT_FALSE(server_stream()->IsZeroRtt());
961 }
962 
TEST_P(TlsServerHandshakerTest,RequestClientCert)963 TEST_P(TlsServerHandshakerTest, RequestClientCert) {
964   ASSERT_TRUE(SetupClientCert());
965   InitializeFakeClient();
966 
967   initial_client_cert_mode_ = ClientCertMode::kRequest;
968   InitializeServerWithFakeProofSourceHandle();
969   server_handshaker_->SetupProofSourceHandle(
970       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
971       /*compute_signature_action=*/FakeProofSourceHandle::Action::
972           DELEGATE_SYNC);
973 
974   CompleteCryptoHandshake();
975   ExpectHandshakeSuccessful();
976   EXPECT_TRUE(server_handshaker_->received_client_cert());
977 }
978 
TEST_P(TlsServerHandshakerTest,SetInvalidServerTransportParamsByDelayedSslConfig)979 TEST_P(TlsServerHandshakerTest,
980        SetInvalidServerTransportParamsByDelayedSslConfig) {
981   ASSERT_TRUE(SetupClientCert());
982   InitializeFakeClient();
983 
984   QuicDelayedSSLConfig delayed_ssl_config;
985   delayed_ssl_config.quic_transport_parameters = {1, 2, 3};
986   InitializeServerWithFakeProofSourceHandle();
987   server_handshaker_->SetupProofSourceHandle(
988       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
989       /*compute_signature_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
990       delayed_ssl_config);
991 
992   AdvanceHandshakeWithFakeClient();
993   ASSERT_TRUE(
994       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
995   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
996 
997   CompleteCryptoHandshake();
998   ExpectHandshakeSuccessful();
999   EXPECT_FALSE(server_handshaker_->fake_proof_source_handle()
1000                    ->all_compute_signature_args()
1001                    .empty());
1002 }
1003 
TEST_P(TlsServerHandshakerTest,SetValidServerTransportParamsByDelayedSslConfig)1004 TEST_P(TlsServerHandshakerTest,
1005        SetValidServerTransportParamsByDelayedSslConfig) {
1006   ParsedQuicVersion version = GetParam().version;
1007 
1008   TransportParameters server_params;
1009   std::string error_details;
1010   server_params.perspective = quic::Perspective::IS_SERVER;
1011   server_params.legacy_version_information =
1012       TransportParameters::LegacyVersionInformation();
1013   server_params.legacy_version_information.value().supported_versions =
1014       quic::CreateQuicVersionLabelVector(
1015           quic::ParsedQuicVersionVector{version});
1016   server_params.legacy_version_information.value().version =
1017       quic::CreateQuicVersionLabel(version);
1018   server_params.version_information = TransportParameters::VersionInformation();
1019   server_params.version_information.value().chosen_version =
1020       quic::CreateQuicVersionLabel(version);
1021   server_params.version_information.value().other_versions =
1022       quic::CreateQuicVersionLabelVector(
1023           quic::ParsedQuicVersionVector{version});
1024 
1025   ASSERT_TRUE(server_params.AreValid(&error_details)) << error_details;
1026 
1027   std::vector<uint8_t> server_params_bytes;
1028   ASSERT_TRUE(
1029       SerializeTransportParameters(server_params, &server_params_bytes));
1030 
1031   ASSERT_TRUE(SetupClientCert());
1032   InitializeFakeClient();
1033 
1034   QuicDelayedSSLConfig delayed_ssl_config;
1035   delayed_ssl_config.quic_transport_parameters = server_params_bytes;
1036   InitializeServerWithFakeProofSourceHandle();
1037   server_handshaker_->SetupProofSourceHandle(
1038       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
1039       /*compute_signature_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
1040       delayed_ssl_config);
1041 
1042   AdvanceHandshakeWithFakeClient();
1043   ASSERT_TRUE(
1044       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
1045   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
1046 
1047   CompleteCryptoHandshake();
1048   ExpectHandshakeSuccessful();
1049   EXPECT_FALSE(server_handshaker_->fake_proof_source_handle()
1050                    ->all_compute_signature_args()
1051                    .empty());
1052 }
1053 
TEST_P(TlsServerHandshakerTest,RequestClientCertByDelayedSslConfig)1054 TEST_P(TlsServerHandshakerTest, RequestClientCertByDelayedSslConfig) {
1055   ASSERT_TRUE(SetupClientCert());
1056   InitializeFakeClient();
1057 
1058   QuicDelayedSSLConfig delayed_ssl_config;
1059   delayed_ssl_config.client_cert_mode = ClientCertMode::kRequest;
1060   InitializeServerWithFakeProofSourceHandle();
1061   server_handshaker_->SetupProofSourceHandle(
1062       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
1063       /*compute_signature_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
1064       delayed_ssl_config);
1065 
1066   AdvanceHandshakeWithFakeClient();
1067   ASSERT_TRUE(
1068       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
1069   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
1070 
1071   CompleteCryptoHandshake();
1072   ExpectHandshakeSuccessful();
1073   EXPECT_TRUE(server_handshaker_->received_client_cert());
1074 }
1075 
TEST_P(TlsServerHandshakerTest,RequestClientCert_NoCert)1076 TEST_P(TlsServerHandshakerTest, RequestClientCert_NoCert) {
1077   initial_client_cert_mode_ = ClientCertMode::kRequest;
1078   InitializeServerWithFakeProofSourceHandle();
1079   server_handshaker_->SetupProofSourceHandle(
1080       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
1081       /*compute_signature_action=*/FakeProofSourceHandle::Action::
1082           DELEGATE_SYNC);
1083 
1084   CompleteCryptoHandshake();
1085   ExpectHandshakeSuccessful();
1086   EXPECT_FALSE(server_handshaker_->received_client_cert());
1087 }
1088 
TEST_P(TlsServerHandshakerTest,RequestAndRequireClientCert)1089 TEST_P(TlsServerHandshakerTest, RequestAndRequireClientCert) {
1090   ASSERT_TRUE(SetupClientCert());
1091   InitializeFakeClient();
1092 
1093   initial_client_cert_mode_ = ClientCertMode::kRequire;
1094   InitializeServerWithFakeProofSourceHandle();
1095   server_handshaker_->SetupProofSourceHandle(
1096       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
1097       /*compute_signature_action=*/FakeProofSourceHandle::Action::
1098           DELEGATE_SYNC);
1099 
1100   CompleteCryptoHandshake();
1101   ExpectHandshakeSuccessful();
1102   EXPECT_TRUE(server_handshaker_->received_client_cert());
1103 }
1104 
TEST_P(TlsServerHandshakerTest,RequestAndRequireClientCertByDelayedSslConfig)1105 TEST_P(TlsServerHandshakerTest, RequestAndRequireClientCertByDelayedSslConfig) {
1106   ASSERT_TRUE(SetupClientCert());
1107   InitializeFakeClient();
1108 
1109   QuicDelayedSSLConfig delayed_ssl_config;
1110   delayed_ssl_config.client_cert_mode = ClientCertMode::kRequire;
1111   InitializeServerWithFakeProofSourceHandle();
1112   server_handshaker_->SetupProofSourceHandle(
1113       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
1114       /*compute_signature_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
1115       delayed_ssl_config);
1116 
1117   AdvanceHandshakeWithFakeClient();
1118   ASSERT_TRUE(
1119       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
1120   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
1121 
1122   CompleteCryptoHandshake();
1123   ExpectHandshakeSuccessful();
1124   EXPECT_TRUE(server_handshaker_->received_client_cert());
1125 }
1126 
TEST_P(TlsServerHandshakerTest,RequestAndRequireClientCert_NoCert)1127 TEST_P(TlsServerHandshakerTest, RequestAndRequireClientCert_NoCert) {
1128   initial_client_cert_mode_ = ClientCertMode::kRequire;
1129   InitializeServerWithFakeProofSourceHandle();
1130   server_handshaker_->SetupProofSourceHandle(
1131       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
1132       /*compute_signature_action=*/FakeProofSourceHandle::Action::
1133           DELEGATE_SYNC);
1134 
1135   EXPECT_CALL(*server_connection_,
1136               CloseConnection(QUIC_TLS_CERTIFICATE_REQUIRED, _, _, _));
1137 
1138   AdvanceHandshakeWithFakeClient();
1139   AdvanceHandshakeWithFakeClient();
1140   EXPECT_FALSE(server_handshaker_->received_client_cert());
1141 }
1142 
TEST_P(TlsServerHandshakerTest,CloseConnectionBeforeSelectCert)1143 TEST_P(TlsServerHandshakerTest, CloseConnectionBeforeSelectCert) {
1144   InitializeServerWithFakeProofSourceHandle();
1145   server_handshaker_->SetupProofSourceHandle(
1146       /*select_cert_action=*/FakeProofSourceHandle::Action::
1147           FAIL_SYNC_DO_NOT_CHECK_CLOSED,
1148       /*compute_signature_action=*/FakeProofSourceHandle::Action::
1149           FAIL_SYNC_DO_NOT_CHECK_CLOSED);
1150 
1151   EXPECT_CALL(*server_handshaker_, OverrideQuicConfigDefaults(_))
1152       .WillOnce(testing::Invoke([](QuicConfig* config) {
1153         QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(config,
1154                                                             /*max_streams=*/0);
1155       }));
1156 
1157   EXPECT_CALL(*server_connection_,
1158               CloseConnection(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, _, _))
1159       .WillOnce(testing::Invoke(
1160           [this](QuicErrorCode error, const std::string& details,
1161                  ConnectionCloseBehavior connection_close_behavior) {
1162             server_connection_->ReallyCloseConnection(
1163                 error, details, connection_close_behavior);
1164             ASSERT_FALSE(server_connection_->connected());
1165           }));
1166 
1167   AdvanceHandshakeWithFakeClient();
1168 
1169   EXPECT_TRUE(server_handshaker_->fake_proof_source_handle()
1170                   ->all_select_cert_args()
1171                   .empty());
1172 }
1173 
TEST_P(TlsServerHandshakerTest,FailUponCustomTranportParam)1174 TEST_P(TlsServerHandshakerTest, FailUponCustomTranportParam) {
1175   client_session_->config()->custom_transport_parameters_to_send().emplace(
1176       TestTlsServerHandshaker::kFailHandshakeParam,
1177       "Fail handshake upon seeing this.");
1178 
1179   InitializeServerWithFakeProofSourceHandle();
1180   server_handshaker_->SetupProofSourceHandle(
1181       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
1182       /*compute_signature_action=*/FakeProofSourceHandle::Action::
1183           DELEGATE_SYNC);
1184   EXPECT_CALL(
1185       *server_connection_,
1186       CloseConnection(QUIC_HANDSHAKE_FAILED,
1187                       "Failed to process additional transport parameters", _));
1188 
1189   // Start handshake.
1190   AdvanceHandshakeWithFakeClient();
1191 }
1192 
TEST_P(TlsServerHandshakerTest,SuccessWithCustomTranportParam)1193 TEST_P(TlsServerHandshakerTest, SuccessWithCustomTranportParam) {
1194   client_session_->config()->custom_transport_parameters_to_send().emplace(
1195       TransportParameters::TransportParameterId{0xFFEADD},
1196       "Continue upon seeing this.");
1197 
1198   InitializeServerWithFakeProofSourceHandle();
1199   server_handshaker_->SetupProofSourceHandle(
1200       /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_ASYNC,
1201       /*compute_signature_action=*/FakeProofSourceHandle::Action::
1202           DELEGATE_SYNC);
1203   EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0);
1204 
1205   // Start handshake.
1206   AdvanceHandshakeWithFakeClient();
1207   ASSERT_TRUE(
1208       server_handshaker_->fake_proof_source_handle()->HasPendingOperation());
1209   server_handshaker_->fake_proof_source_handle()->CompletePendingOperation();
1210 
1211   CompleteCryptoHandshake();
1212 
1213   ExpectHandshakeSuccessful();
1214 }
1215 
1216 #if BORINGSSL_API_VERSION >= 22
TEST_P(TlsServerHandshakerTest,EnableKyber)1217 TEST_P(TlsServerHandshakerTest, EnableKyber) {
1218   server_crypto_config_->set_preferred_groups(
1219       {SSL_GROUP_X25519_KYBER768_DRAFT00});
1220   client_crypto_config_->set_preferred_groups(
1221       {SSL_GROUP_X25519_KYBER768_DRAFT00, SSL_GROUP_X25519, SSL_GROUP_SECP256R1,
1222        SSL_GROUP_SECP384R1});
1223 
1224   InitializeServer();
1225   InitializeFakeClient();
1226   CompleteCryptoHandshake();
1227   ExpectHandshakeSuccessful();
1228   EXPECT_EQ(PROTOCOL_TLS1_3, server_stream()->handshake_protocol());
1229   EXPECT_EQ(SSL_GROUP_X25519_KYBER768_DRAFT00,
1230             SSL_get_group_id(server_stream()->GetSsl()));
1231 }
1232 #endif  // BORINGSSL_API_VERSION
1233 
1234 #if BORINGSSL_API_VERSION >= 27
TEST_P(TlsServerHandshakerTest,AlpsUseNewCodepoint)1235 TEST_P(TlsServerHandshakerTest, AlpsUseNewCodepoint) {
1236   const struct {
1237     bool client_use_alps_new_codepoint;
1238     bool server_allow_alps_new_codepoint;
1239   } tests[] = {
1240       // The intent of this test is to demonstrate different combinations of
1241       // ALPS codepoint settings works well for both client and server.
1242       {true, true},
1243       {false, true},
1244       {false, false},
1245       {true, true},
1246   };
1247   for (size_t i = 0; i < ABSL_ARRAYSIZE(tests); i++) {
1248     SCOPED_TRACE(absl::StrCat("Test #", i));
1249     const auto& test = tests[i];
1250     client_crypto_config_->set_alps_use_new_codepoint(
1251         test.client_use_alps_new_codepoint);
1252     SetQuicReloadableFlag(quic_gfe_allow_alps_new_codepoint,
1253                           test.server_allow_alps_new_codepoint);
1254 
1255     ASSERT_TRUE(SetupClientCert());
1256     InitializeFakeClient();
1257 
1258     InitializeServerWithFakeProofSourceHandle();
1259     server_handshaker_->SetupProofSourceHandle(
1260         /*select_cert_action=*/FakeProofSourceHandle::Action::DELEGATE_SYNC,
1261         /*compute_signature_action=*/FakeProofSourceHandle::Action::
1262             DELEGATE_SYNC);
1263 
1264     // Start handshake.
1265     AdvanceHandshakeWithFakeClient();
1266     EXPECT_EQ(test.client_use_alps_new_codepoint,
1267               server_handshaker_->UseAlpsNewCodepoint());
1268 
1269     CompleteCryptoHandshake();
1270     ExpectHandshakeSuccessful();
1271     EXPECT_EQ(PROTOCOL_TLS1_3, server_stream()->handshake_protocol());
1272   }
1273 }
1274 #endif  // BORINGSSL_API_VERSION
1275 
1276 }  // namespace
1277 }  // namespace test
1278 }  // namespace quic
1279