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/quic_crypto_stream.h"
6
7 #include <cstdint>
8 #include <memory>
9 #include <string>
10 #include <utility>
11 #include <vector>
12
13 #include "quiche/quic/core/crypto/crypto_handshake.h"
14 #include "quiche/quic/core/crypto/crypto_protocol.h"
15 #include "quiche/quic/core/crypto/null_encrypter.h"
16 #include "quiche/quic/core/quic_error_codes.h"
17 #include "quiche/quic/core/quic_types.h"
18 #include "quiche/quic/core/quic_utils.h"
19 #include "quiche/quic/platform/api/quic_expect_bug.h"
20 #include "quiche/quic/platform/api/quic_flags.h"
21 #include "quiche/quic/platform/api/quic_socket_address.h"
22 #include "quiche/quic/platform/api/quic_test.h"
23 #include "quiche/quic/test_tools/crypto_test_utils.h"
24 #include "quiche/quic/test_tools/quic_connection_peer.h"
25 #include "quiche/quic/test_tools/quic_stream_peer.h"
26 #include "quiche/quic/test_tools/quic_test_utils.h"
27
28 using testing::_;
29 using testing::InSequence;
30 using testing::Invoke;
31 using testing::InvokeWithoutArgs;
32 using testing::Return;
33
34 namespace quic {
35 namespace test {
36 namespace {
37
38 class MockQuicCryptoStream : public QuicCryptoStream,
39 public QuicCryptoHandshaker {
40 public:
MockQuicCryptoStream(QuicSession * session)41 explicit MockQuicCryptoStream(QuicSession* session)
42 : QuicCryptoStream(session),
43 QuicCryptoHandshaker(this, session),
44 params_(new QuicCryptoNegotiatedParameters) {}
45 MockQuicCryptoStream(const MockQuicCryptoStream&) = delete;
46 MockQuicCryptoStream& operator=(const MockQuicCryptoStream&) = delete;
47
OnHandshakeMessage(const CryptoHandshakeMessage & message)48 void OnHandshakeMessage(const CryptoHandshakeMessage& message) override {
49 messages_.push_back(message);
50 }
51
messages()52 std::vector<CryptoHandshakeMessage>* messages() { return &messages_; }
53
EarlyDataReason() const54 ssl_early_data_reason_t EarlyDataReason() const override {
55 return ssl_early_data_unknown;
56 }
encryption_established() const57 bool encryption_established() const override { return false; }
one_rtt_keys_available() const58 bool one_rtt_keys_available() const override { return false; }
59
crypto_negotiated_params() const60 const QuicCryptoNegotiatedParameters& crypto_negotiated_params()
61 const override {
62 return *params_;
63 }
crypto_message_parser()64 CryptoMessageParser* crypto_message_parser() override {
65 return QuicCryptoHandshaker::crypto_message_parser();
66 }
OnPacketDecrypted(EncryptionLevel)67 void OnPacketDecrypted(EncryptionLevel /*level*/) override {}
OnOneRttPacketAcknowledged()68 void OnOneRttPacketAcknowledged() override {}
OnHandshakePacketSent()69 void OnHandshakePacketSent() override {}
OnHandshakeDoneReceived()70 void OnHandshakeDoneReceived() override {}
OnNewTokenReceived(absl::string_view)71 void OnNewTokenReceived(absl::string_view /*token*/) override {}
GetAddressToken(const CachedNetworkParameters *) const72 std::string GetAddressToken(
73 const CachedNetworkParameters* /*cached_network_parameters*/)
74 const override {
75 return "";
76 }
ValidateAddressToken(absl::string_view) const77 bool ValidateAddressToken(absl::string_view /*token*/) const override {
78 return true;
79 }
PreviousCachedNetworkParams() const80 const CachedNetworkParameters* PreviousCachedNetworkParams() const override {
81 return nullptr;
82 }
SetPreviousCachedNetworkParams(CachedNetworkParameters)83 void SetPreviousCachedNetworkParams(
84 CachedNetworkParameters /*cached_network_params*/) override {}
GetHandshakeState() const85 HandshakeState GetHandshakeState() const override { return HANDSHAKE_START; }
SetServerApplicationStateForResumption(std::unique_ptr<ApplicationState>)86 void SetServerApplicationStateForResumption(
87 std::unique_ptr<ApplicationState> /*application_state*/) override {}
AdvanceKeysAndCreateCurrentOneRttDecrypter()88 std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter()
89 override {
90 return nullptr;
91 }
CreateCurrentOneRttEncrypter()92 std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override {
93 return nullptr;
94 }
ExportKeyingMaterial(absl::string_view,absl::string_view,size_t,std::string *)95 bool ExportKeyingMaterial(absl::string_view /*label*/,
96 absl::string_view /*context*/,
97 size_t /*result_len*/,
98 std::string* /*result*/) override {
99 return false;
100 }
GetSsl() const101 SSL* GetSsl() const override { return nullptr; }
102
IsCryptoFrameExpectedForEncryptionLevel(EncryptionLevel level) const103 bool IsCryptoFrameExpectedForEncryptionLevel(
104 EncryptionLevel level) const override {
105 return level != ENCRYPTION_ZERO_RTT;
106 }
107
GetEncryptionLevelToSendCryptoDataOfSpace(PacketNumberSpace space) const108 EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace(
109 PacketNumberSpace space) const override {
110 switch (space) {
111 case INITIAL_DATA:
112 return ENCRYPTION_INITIAL;
113 case HANDSHAKE_DATA:
114 return ENCRYPTION_HANDSHAKE;
115 case APPLICATION_DATA:
116 return QuicCryptoStream::session()
117 ->GetEncryptionLevelToSendApplicationData();
118 default:
119 QUICHE_DCHECK(false);
120 return NUM_ENCRYPTION_LEVELS;
121 }
122 }
123
124 private:
125 quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_;
126 std::vector<CryptoHandshakeMessage> messages_;
127 };
128
129 class QuicCryptoStreamTest : public QuicTest {
130 public:
QuicCryptoStreamTest()131 QuicCryptoStreamTest()
132 : connection_(new MockQuicConnection(&helper_, &alarm_factory_,
133 Perspective::IS_CLIENT)),
134 session_(connection_, /*create_mock_crypto_stream=*/false) {
135 EXPECT_CALL(*static_cast<MockPacketWriter*>(connection_->writer()),
136 WritePacket(_, _, _, _, _, _))
137 .WillRepeatedly(Return(WriteResult(WRITE_STATUS_OK, 0)));
138 stream_ = new MockQuicCryptoStream(&session_);
139 session_.SetCryptoStream(stream_);
140 session_.Initialize();
141 message_.set_tag(kSHLO);
142 message_.SetStringPiece(1, "abc");
143 message_.SetStringPiece(2, "def");
144 ConstructHandshakeMessage();
145 }
146 QuicCryptoStreamTest(const QuicCryptoStreamTest&) = delete;
147 QuicCryptoStreamTest& operator=(const QuicCryptoStreamTest&) = delete;
148
ConstructHandshakeMessage()149 void ConstructHandshakeMessage() {
150 CryptoFramer framer;
151 message_data_ = framer.ConstructHandshakeMessage(message_);
152 }
153
154 protected:
155 MockQuicConnectionHelper helper_;
156 MockAlarmFactory alarm_factory_;
157 MockQuicConnection* connection_;
158 MockQuicSpdySession session_;
159 MockQuicCryptoStream* stream_;
160 CryptoHandshakeMessage message_;
161 std::unique_ptr<QuicData> message_data_;
162 };
163
TEST_F(QuicCryptoStreamTest,NotInitiallyConected)164 TEST_F(QuicCryptoStreamTest, NotInitiallyConected) {
165 EXPECT_FALSE(stream_->encryption_established());
166 EXPECT_FALSE(stream_->one_rtt_keys_available());
167 }
168
TEST_F(QuicCryptoStreamTest,ProcessRawData)169 TEST_F(QuicCryptoStreamTest, ProcessRawData) {
170 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
171 stream_->OnStreamFrame(QuicStreamFrame(
172 QuicUtils::GetCryptoStreamId(connection_->transport_version()),
173 /*fin=*/false,
174 /*offset=*/0, message_data_->AsStringPiece()));
175 } else {
176 stream_->OnCryptoFrame(QuicCryptoFrame(ENCRYPTION_INITIAL, /*offset*/ 0,
177 message_data_->AsStringPiece()));
178 }
179 ASSERT_EQ(1u, stream_->messages()->size());
180 const CryptoHandshakeMessage& message = (*stream_->messages())[0];
181 EXPECT_EQ(kSHLO, message.tag());
182 EXPECT_EQ(2u, message.tag_value_map().size());
183 EXPECT_EQ("abc", crypto_test_utils::GetValueForTag(message, 1));
184 EXPECT_EQ("def", crypto_test_utils::GetValueForTag(message, 2));
185 }
186
TEST_F(QuicCryptoStreamTest,ProcessBadData)187 TEST_F(QuicCryptoStreamTest, ProcessBadData) {
188 std::string bad(message_data_->data(), message_data_->length());
189 const int kFirstTagIndex = sizeof(uint32_t) + // message tag
190 sizeof(uint16_t) + // number of tag-value pairs
191 sizeof(uint16_t); // padding
192 EXPECT_EQ(1, bad[kFirstTagIndex]);
193 bad[kFirstTagIndex] = 0x7F; // out of order tag
194
195 EXPECT_CALL(*connection_, CloseConnection(QUIC_CRYPTO_TAGS_OUT_OF_ORDER,
196 testing::_, testing::_));
197 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
198 stream_->OnStreamFrame(QuicStreamFrame(
199 QuicUtils::GetCryptoStreamId(connection_->transport_version()),
200 /*fin=*/false, /*offset=*/0, bad));
201 } else {
202 stream_->OnCryptoFrame(
203 QuicCryptoFrame(ENCRYPTION_INITIAL, /*offset*/ 0, bad));
204 }
205 }
206
TEST_F(QuicCryptoStreamTest,NoConnectionLevelFlowControl)207 TEST_F(QuicCryptoStreamTest, NoConnectionLevelFlowControl) {
208 EXPECT_FALSE(
209 QuicStreamPeer::StreamContributesToConnectionFlowControl(stream_));
210 }
211
TEST_F(QuicCryptoStreamTest,RetransmitCryptoData)212 TEST_F(QuicCryptoStreamTest, RetransmitCryptoData) {
213 if (QuicVersionUsesCryptoFrames(connection_->transport_version())) {
214 return;
215 }
216 InSequence s;
217 // Send [0, 1350) in ENCRYPTION_INITIAL.
218 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
219 std::string data(1350, 'a');
220 EXPECT_CALL(
221 session_,
222 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
223 1350, 0, _, _, _))
224 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
225 stream_->WriteOrBufferData(data, false, nullptr);
226 // Send [1350, 2700) in ENCRYPTION_ZERO_RTT.
227 connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
228 EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level());
229 EXPECT_CALL(
230 session_,
231 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
232 1350, 1350, _, _, _))
233 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
234 stream_->WriteOrBufferData(data, false, nullptr);
235 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
236 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
237
238 // Lost [0, 1000).
239 stream_->OnStreamFrameLost(0, 1000, false);
240 EXPECT_TRUE(stream_->HasPendingRetransmission());
241 // Lost [1200, 2000).
242 stream_->OnStreamFrameLost(1200, 800, false);
243 EXPECT_CALL(
244 session_,
245 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
246 1000, 0, _, _, _))
247 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
248 // Verify [1200, 2000) are sent in [1200, 1350) and [1350, 2000) because of
249 // they are in different encryption levels.
250 EXPECT_CALL(
251 session_,
252 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
253 150, 1200, _, _, _))
254 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
255 EXPECT_CALL(
256 session_,
257 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
258 650, 1350, _, _, _))
259 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
260 stream_->OnCanWrite();
261 EXPECT_FALSE(stream_->HasPendingRetransmission());
262 // Verify connection's encryption level has restored.
263 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
264 }
265
TEST_F(QuicCryptoStreamTest,RetransmitCryptoDataInCryptoFrames)266 TEST_F(QuicCryptoStreamTest, RetransmitCryptoDataInCryptoFrames) {
267 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
268 return;
269 }
270 EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
271 InSequence s;
272 // Send [0, 1350) in ENCRYPTION_INITIAL.
273 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
274 std::string data(1350, 'a');
275 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
276 .WillOnce(Invoke(connection_,
277 &MockQuicConnection::QuicConnection_SendCryptoData));
278 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data);
279 // Send [1350, 2700) in ENCRYPTION_ZERO_RTT.
280 std::unique_ptr<NullEncrypter> encrypter =
281 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT);
282 connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter));
283 connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
284 EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level());
285 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0))
286 .WillOnce(Invoke(connection_,
287 &MockQuicConnection::QuicConnection_SendCryptoData));
288 stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data);
289
290 // Before encryption moves to ENCRYPTION_FORWARD_SECURE, ZERO RTT data are
291 // retranmitted at ENCRYPTION_ZERO_RTT.
292 QuicCryptoFrame lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650);
293 stream_->OnCryptoFrameLost(&lost_frame);
294
295 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 650, 0))
296 .WillOnce(Invoke(connection_,
297 &MockQuicConnection::QuicConnection_SendCryptoData));
298 stream_->WritePendingCryptoRetransmission();
299
300 connection_->SetEncrypter(
301 ENCRYPTION_FORWARD_SECURE,
302 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT));
303 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
304 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
305
306 // Lost [0, 1000).
307 lost_frame = QuicCryptoFrame(ENCRYPTION_INITIAL, 0, 1000);
308 stream_->OnCryptoFrameLost(&lost_frame);
309 EXPECT_TRUE(stream_->HasPendingCryptoRetransmission());
310 // Lost [1200, 2000).
311 lost_frame = QuicCryptoFrame(ENCRYPTION_INITIAL, 1200, 150);
312 stream_->OnCryptoFrameLost(&lost_frame);
313 lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650);
314 stream_->OnCryptoFrameLost(&lost_frame);
315 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0))
316 .WillOnce(Invoke(connection_,
317 &MockQuicConnection::QuicConnection_SendCryptoData));
318 // Verify [1200, 2000) are sent in [1200, 1350) and [1350, 2000) because of
319 // they are in different encryption levels.
320 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 150, 1200))
321 .WillOnce(Invoke(connection_,
322 &MockQuicConnection::QuicConnection_SendCryptoData));
323 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 650, 0))
324 .WillOnce(Invoke(connection_,
325 &MockQuicConnection::QuicConnection_SendCryptoData));
326 stream_->WritePendingCryptoRetransmission();
327 EXPECT_FALSE(stream_->HasPendingCryptoRetransmission());
328 // Verify connection's encryption level has restored.
329 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
330 }
331
332 // Regression test for handling the missing ENCRYPTION_HANDSHAKE in
333 // quic_crypto_stream.cc. This test is essentially the same as
334 // RetransmitCryptoDataInCryptoFrames, except it uses ENCRYPTION_HANDSHAKE in
335 // place of ENCRYPTION_ZERO_RTT.
TEST_F(QuicCryptoStreamTest,RetransmitEncryptionHandshakeLevelCryptoFrames)336 TEST_F(QuicCryptoStreamTest, RetransmitEncryptionHandshakeLevelCryptoFrames) {
337 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
338 return;
339 }
340 EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
341 InSequence s;
342 // Send [0, 1000) in ENCRYPTION_INITIAL.
343 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
344 std::string data(1000, 'a');
345 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0))
346 .WillOnce(Invoke(connection_,
347 &MockQuicConnection::QuicConnection_SendCryptoData));
348 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data);
349 // Send [1000, 2000) in ENCRYPTION_HANDSHAKE.
350 std::unique_ptr<NullEncrypter> encrypter =
351 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT);
352 connection_->SetEncrypter(ENCRYPTION_HANDSHAKE, std::move(encrypter));
353 connection_->SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
354 EXPECT_EQ(ENCRYPTION_HANDSHAKE, connection_->encryption_level());
355 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_HANDSHAKE, 1000, 0))
356 .WillOnce(Invoke(connection_,
357 &MockQuicConnection::QuicConnection_SendCryptoData));
358 stream_->WriteCryptoData(ENCRYPTION_HANDSHAKE, data);
359 connection_->SetEncrypter(
360 ENCRYPTION_FORWARD_SECURE,
361 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT));
362 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
363 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
364
365 // Lost [1000, 1200).
366 QuicCryptoFrame lost_frame(ENCRYPTION_HANDSHAKE, 0, 200);
367 stream_->OnCryptoFrameLost(&lost_frame);
368 EXPECT_TRUE(stream_->HasPendingCryptoRetransmission());
369 // Verify [1000, 1200) is sent.
370 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_HANDSHAKE, 200, 0))
371 .WillOnce(Invoke(connection_,
372 &MockQuicConnection::QuicConnection_SendCryptoData));
373 stream_->WritePendingCryptoRetransmission();
374 EXPECT_FALSE(stream_->HasPendingCryptoRetransmission());
375 }
376
TEST_F(QuicCryptoStreamTest,NeuterUnencryptedStreamData)377 TEST_F(QuicCryptoStreamTest, NeuterUnencryptedStreamData) {
378 if (QuicVersionUsesCryptoFrames(connection_->transport_version())) {
379 return;
380 }
381 // Send [0, 1350) in ENCRYPTION_INITIAL.
382 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
383 std::string data(1350, 'a');
384 EXPECT_CALL(
385 session_,
386 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
387 1350, 0, _, _, _))
388 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
389 stream_->WriteOrBufferData(data, false, nullptr);
390 // Send [1350, 2700) in ENCRYPTION_ZERO_RTT.
391 connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
392 EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level());
393 EXPECT_CALL(
394 session_,
395 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
396 1350, 1350, _, _, _))
397 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
398 stream_->WriteOrBufferData(data, false, nullptr);
399
400 // Lost [0, 1350).
401 stream_->OnStreamFrameLost(0, 1350, false);
402 EXPECT_TRUE(stream_->HasPendingRetransmission());
403 // Neuters [0, 1350).
404 stream_->NeuterUnencryptedStreamData();
405 EXPECT_FALSE(stream_->HasPendingRetransmission());
406 // Lost [0, 1350) again.
407 stream_->OnStreamFrameLost(0, 1350, false);
408 EXPECT_FALSE(stream_->HasPendingRetransmission());
409
410 // Lost [1350, 2000).
411 stream_->OnStreamFrameLost(1350, 650, false);
412 EXPECT_TRUE(stream_->HasPendingRetransmission());
413 stream_->NeuterUnencryptedStreamData();
414 EXPECT_TRUE(stream_->HasPendingRetransmission());
415 }
416
TEST_F(QuicCryptoStreamTest,NeuterUnencryptedCryptoData)417 TEST_F(QuicCryptoStreamTest, NeuterUnencryptedCryptoData) {
418 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
419 return;
420 }
421 // Send [0, 1350) in ENCRYPTION_INITIAL.
422 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
423 std::string data(1350, 'a');
424 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
425 .WillOnce(Invoke(connection_,
426 &MockQuicConnection::QuicConnection_SendCryptoData));
427 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data);
428 // Send [1350, 2700) in ENCRYPTION_ZERO_RTT.
429 connection_->SetEncrypter(
430 ENCRYPTION_ZERO_RTT,
431 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT));
432 connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
433 std::unique_ptr<NullEncrypter> encrypter =
434 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT);
435 connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter));
436 EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level());
437 EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
438 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0))
439 .WillOnce(Invoke(connection_,
440 &MockQuicConnection::QuicConnection_SendCryptoData));
441 stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data);
442
443 // Lost [0, 1350).
444 QuicCryptoFrame lost_frame(ENCRYPTION_INITIAL, 0, 1350);
445 stream_->OnCryptoFrameLost(&lost_frame);
446 EXPECT_TRUE(stream_->HasPendingCryptoRetransmission());
447 // Neuters [0, 1350).
448 stream_->NeuterUnencryptedStreamData();
449 EXPECT_FALSE(stream_->HasPendingCryptoRetransmission());
450 // Lost [0, 1350) again.
451 stream_->OnCryptoFrameLost(&lost_frame);
452 EXPECT_FALSE(stream_->HasPendingCryptoRetransmission());
453
454 // Lost [1350, 2000), which starts at offset 0 at the ENCRYPTION_ZERO_RTT
455 // level.
456 lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650);
457 stream_->OnCryptoFrameLost(&lost_frame);
458 EXPECT_TRUE(stream_->HasPendingCryptoRetransmission());
459 stream_->NeuterUnencryptedStreamData();
460 EXPECT_TRUE(stream_->HasPendingCryptoRetransmission());
461 }
462
TEST_F(QuicCryptoStreamTest,RetransmitStreamData)463 TEST_F(QuicCryptoStreamTest, RetransmitStreamData) {
464 if (QuicVersionUsesCryptoFrames(connection_->transport_version())) {
465 return;
466 }
467 InSequence s;
468 // Send [0, 1350) in ENCRYPTION_INITIAL.
469 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
470 std::string data(1350, 'a');
471 EXPECT_CALL(
472 session_,
473 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
474 1350, 0, _, _, _))
475 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
476 stream_->WriteOrBufferData(data, false, nullptr);
477 // Send [1350, 2700) in ENCRYPTION_ZERO_RTT.
478 connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
479 EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level());
480 EXPECT_CALL(
481 session_,
482 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
483 1350, 1350, _, _, _))
484 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
485 stream_->WriteOrBufferData(data, false, nullptr);
486 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
487 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
488
489 // Ack [2000, 2500).
490 QuicByteCount newly_acked_length = 0;
491 stream_->OnStreamFrameAcked(2000, 500, false, QuicTime::Delta::Zero(),
492 QuicTime::Zero(), &newly_acked_length);
493 EXPECT_EQ(500u, newly_acked_length);
494
495 // Force crypto stream to send [1350, 2700) and only [1350, 1500) is consumed.
496 EXPECT_CALL(
497 session_,
498 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
499 650, 1350, _, _, _))
500 .WillOnce(InvokeWithoutArgs([this]() {
501 return session_.ConsumeData(
502 QuicUtils::GetCryptoStreamId(connection_->transport_version()), 150,
503 1350, NO_FIN, HANDSHAKE_RETRANSMISSION, std::nullopt);
504 }));
505
506 EXPECT_FALSE(stream_->RetransmitStreamData(1350, 1350, false,
507 HANDSHAKE_RETRANSMISSION));
508 // Verify connection's encryption level has restored.
509 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
510
511 // Force session to send [1350, 1500) again and all data is consumed.
512 EXPECT_CALL(
513 session_,
514 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
515 650, 1350, _, _, _))
516 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
517 EXPECT_CALL(
518 session_,
519 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
520 200, 2500, _, _, _))
521 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
522 EXPECT_TRUE(stream_->RetransmitStreamData(1350, 1350, false,
523 HANDSHAKE_RETRANSMISSION));
524 // Verify connection's encryption level has restored.
525 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
526
527 EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)).Times(0);
528 // Force to send an empty frame.
529 EXPECT_TRUE(
530 stream_->RetransmitStreamData(0, 0, false, HANDSHAKE_RETRANSMISSION));
531 }
532
TEST_F(QuicCryptoStreamTest,RetransmitStreamDataWithCryptoFrames)533 TEST_F(QuicCryptoStreamTest, RetransmitStreamDataWithCryptoFrames) {
534 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
535 return;
536 }
537 InSequence s;
538 // Send [0, 1350) in ENCRYPTION_INITIAL.
539 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
540 std::string data(1350, 'a');
541 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
542 .WillOnce(Invoke(connection_,
543 &MockQuicConnection::QuicConnection_SendCryptoData));
544 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data);
545 // Send [1350, 2700) in ENCRYPTION_ZERO_RTT.
546 std::unique_ptr<NullEncrypter> encrypter =
547 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT);
548 connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter));
549 connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
550 EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level());
551 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0))
552 .WillOnce(Invoke(connection_,
553 &MockQuicConnection::QuicConnection_SendCryptoData));
554 stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data);
555 connection_->SetEncrypter(
556 ENCRYPTION_FORWARD_SECURE,
557 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT));
558 connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
559 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
560
561 // Ack [2000, 2500).
562 QuicCryptoFrame acked_frame(ENCRYPTION_ZERO_RTT, 650, 500);
563 EXPECT_TRUE(
564 stream_->OnCryptoFrameAcked(acked_frame, QuicTime::Delta::Zero()));
565
566 // Retransmit only [1350, 1500).
567 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 150, 0))
568 .WillOnce(Invoke(connection_,
569 &MockQuicConnection::QuicConnection_SendCryptoData));
570 QuicCryptoFrame frame_to_retransmit(ENCRYPTION_ZERO_RTT, 0, 150);
571 stream_->RetransmitData(&frame_to_retransmit, HANDSHAKE_RETRANSMISSION);
572
573 // Verify connection's encryption level has restored.
574 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
575
576 // Retransmit [1350, 2700) again and all data is sent.
577 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 650, 0))
578 .WillOnce(Invoke(connection_,
579 &MockQuicConnection::QuicConnection_SendCryptoData));
580 EXPECT_CALL(*connection_,
581 SendCryptoData(ENCRYPTION_FORWARD_SECURE, 200, 1150))
582 .WillOnce(Invoke(connection_,
583 &MockQuicConnection::QuicConnection_SendCryptoData));
584 frame_to_retransmit = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 1350);
585 stream_->RetransmitData(&frame_to_retransmit, HANDSHAKE_RETRANSMISSION);
586 // Verify connection's encryption level has restored.
587 EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level());
588
589 EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
590 // Force to send an empty frame.
591 QuicCryptoFrame empty_frame(ENCRYPTION_FORWARD_SECURE, 0, 0);
592 stream_->RetransmitData(&empty_frame, HANDSHAKE_RETRANSMISSION);
593 }
594
595 // Regression test for b/115926584.
TEST_F(QuicCryptoStreamTest,HasUnackedCryptoData)596 TEST_F(QuicCryptoStreamTest, HasUnackedCryptoData) {
597 if (QuicVersionUsesCryptoFrames(connection_->transport_version())) {
598 return;
599 }
600 std::string data(1350, 'a');
601 EXPECT_CALL(
602 session_,
603 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
604 1350, 0, _, _, _))
605 .WillOnce(testing::Return(QuicConsumedData(0, false)));
606 stream_->WriteOrBufferData(data, false, nullptr);
607 EXPECT_FALSE(stream_->IsWaitingForAcks());
608 // Although there is no outstanding data, verify session has pending crypto
609 // data.
610 EXPECT_TRUE(session_.HasUnackedCryptoData());
611
612 EXPECT_CALL(
613 session_,
614 WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()),
615 1350, 0, _, _, _))
616 .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
617 stream_->OnCanWrite();
618 EXPECT_TRUE(stream_->IsWaitingForAcks());
619 EXPECT_TRUE(session_.HasUnackedCryptoData());
620 }
621
TEST_F(QuicCryptoStreamTest,HasUnackedCryptoDataWithCryptoFrames)622 TEST_F(QuicCryptoStreamTest, HasUnackedCryptoDataWithCryptoFrames) {
623 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
624 return;
625 }
626 // Send [0, 1350) in ENCRYPTION_INITIAL.
627 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
628 std::string data(1350, 'a');
629 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
630 .WillOnce(Invoke(connection_,
631 &MockQuicConnection::QuicConnection_SendCryptoData));
632 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data);
633 EXPECT_TRUE(stream_->IsWaitingForAcks());
634 EXPECT_TRUE(session_.HasUnackedCryptoData());
635 }
636
637 // Regression test for bugfix of GetPacketHeaderSize.
TEST_F(QuicCryptoStreamTest,CryptoMessageFramingOverhead)638 TEST_F(QuicCryptoStreamTest, CryptoMessageFramingOverhead) {
639 for (const ParsedQuicVersion& version :
640 AllSupportedVersionsWithQuicCrypto()) {
641 SCOPED_TRACE(version);
642 QuicByteCount expected_overhead = 52;
643 if (version.HasLongHeaderLengths()) {
644 expected_overhead += 3;
645 }
646 if (version.HasLengthPrefixedConnectionIds()) {
647 expected_overhead += 1;
648 }
649 EXPECT_EQ(expected_overhead,
650 QuicCryptoStream::CryptoMessageFramingOverhead(
651 version.transport_version, TestConnectionId()));
652 }
653 }
654
TEST_F(QuicCryptoStreamTest,WriteCryptoDataExceedsSendBufferLimit)655 TEST_F(QuicCryptoStreamTest, WriteCryptoDataExceedsSendBufferLimit) {
656 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
657 return;
658 }
659 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
660 int32_t buffer_limit = GetQuicFlag(quic_max_buffered_crypto_bytes);
661
662 // Write data larger than the buffer limit, when there is no existing data in
663 // the buffer. Data is sent rather than closing the connection.
664 EXPECT_FALSE(stream_->HasBufferedCryptoFrames());
665 int32_t over_limit = buffer_limit + 1;
666 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, over_limit, 0))
667 // All the data is sent, no resulting buffer.
668 .WillOnce(Return(over_limit));
669 std::string large_data(over_limit, 'a');
670 stream_->WriteCryptoData(ENCRYPTION_INITIAL, large_data);
671
672 // Write data to the buffer up to the limit. One byte gets sent.
673 EXPECT_FALSE(stream_->HasBufferedCryptoFrames());
674 EXPECT_CALL(*connection_,
675 SendCryptoData(ENCRYPTION_INITIAL, buffer_limit, over_limit))
676 .WillOnce(Return(1));
677 std::string data(buffer_limit, 'a');
678 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data);
679 EXPECT_TRUE(stream_->HasBufferedCryptoFrames());
680
681 // Write another byte that is not sent (due to there already being data in the
682 // buffer); send buffer is now full.
683 EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
684 std::string data2(1, 'a');
685 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data2);
686 EXPECT_TRUE(stream_->HasBufferedCryptoFrames());
687
688 // Writing an additional byte to the send buffer closes the connection.
689 if (GetQuicFlag(quic_bounded_crypto_send_buffer)) {
690 EXPECT_CALL(*connection_, CloseConnection(QUIC_INTERNAL_ERROR, _, _));
691 EXPECT_QUIC_BUG(
692 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data2),
693 "Too much data for crypto send buffer with level: ENCRYPTION_INITIAL, "
694 "current_buffer_size: 16384, data length: 1");
695 }
696 }
697
TEST_F(QuicCryptoStreamTest,WriteBufferedCryptoFrames)698 TEST_F(QuicCryptoStreamTest, WriteBufferedCryptoFrames) {
699 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
700 return;
701 }
702 EXPECT_FALSE(stream_->HasBufferedCryptoFrames());
703 InSequence s;
704 // Send [0, 1350) in ENCRYPTION_INITIAL.
705 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
706 std::string data(1350, 'a');
707 // Only consumed 1000 bytes.
708 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
709 .WillOnce(Return(1000));
710 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data);
711 EXPECT_TRUE(stream_->HasBufferedCryptoFrames());
712
713 // Send [1350, 2700) in ENCRYPTION_ZERO_RTT and verify no write is attempted
714 // because there is buffered data.
715 EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
716 connection_->SetEncrypter(
717 ENCRYPTION_ZERO_RTT,
718 std::make_unique<NullEncrypter>(Perspective::IS_CLIENT));
719 connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
720 stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data);
721 EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level());
722
723 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 350, 1000))
724 .WillOnce(Return(350));
725 // Partial write of ENCRYPTION_ZERO_RTT data.
726 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0))
727 .WillOnce(Return(1000));
728 stream_->WriteBufferedCryptoFrames();
729 EXPECT_TRUE(stream_->HasBufferedCryptoFrames());
730 EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level());
731
732 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 350, 1000))
733 .WillOnce(Return(350));
734 stream_->WriteBufferedCryptoFrames();
735 EXPECT_FALSE(stream_->HasBufferedCryptoFrames());
736 }
737
TEST_F(QuicCryptoStreamTest,LimitBufferedCryptoData)738 TEST_F(QuicCryptoStreamTest, LimitBufferedCryptoData) {
739 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
740 return;
741 }
742
743 EXPECT_CALL(*connection_,
744 CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _));
745 std::string large_frame(2 * GetQuicFlag(quic_max_buffered_crypto_bytes), 'a');
746
747 // Set offset to 1 so that we guarantee the data gets buffered instead of
748 // immediately processed.
749 QuicStreamOffset offset = 1;
750 stream_->OnCryptoFrame(
751 QuicCryptoFrame(ENCRYPTION_INITIAL, offset, large_frame));
752 }
753
TEST_F(QuicCryptoStreamTest,CloseConnectionWithZeroRttCryptoFrame)754 TEST_F(QuicCryptoStreamTest, CloseConnectionWithZeroRttCryptoFrame) {
755 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
756 return;
757 }
758
759 EXPECT_CALL(*connection_,
760 CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, _, _));
761
762 test::QuicConnectionPeer::SetLastDecryptedLevel(connection_,
763 ENCRYPTION_ZERO_RTT);
764 QuicStreamOffset offset = 1;
765 stream_->OnCryptoFrame(QuicCryptoFrame(ENCRYPTION_ZERO_RTT, offset, "data"));
766 }
767
TEST_F(QuicCryptoStreamTest,RetransmitCryptoFramesAndPartialWrite)768 TEST_F(QuicCryptoStreamTest, RetransmitCryptoFramesAndPartialWrite) {
769 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
770 return;
771 }
772
773 EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0);
774 InSequence s;
775 // Send [0, 1350) in ENCRYPTION_INITIAL.
776 EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level());
777 std::string data(1350, 'a');
778 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0))
779 .WillOnce(Invoke(connection_,
780 &MockQuicConnection::QuicConnection_SendCryptoData));
781 stream_->WriteCryptoData(ENCRYPTION_INITIAL, data);
782
783 // Lost [0, 1000).
784 QuicCryptoFrame lost_frame(ENCRYPTION_INITIAL, 0, 1000);
785 stream_->OnCryptoFrameLost(&lost_frame);
786 EXPECT_TRUE(stream_->HasPendingCryptoRetransmission());
787 // Simulate connection is constrained by amplification restriction.
788 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0))
789 .WillOnce(Return(0));
790 stream_->WritePendingCryptoRetransmission();
791 EXPECT_TRUE(stream_->HasPendingCryptoRetransmission());
792 // Connection gets unblocked.
793 EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0))
794 .WillOnce(Invoke(connection_,
795 &MockQuicConnection::QuicConnection_SendCryptoData));
796 stream_->WritePendingCryptoRetransmission();
797 EXPECT_FALSE(stream_->HasPendingCryptoRetransmission());
798 }
799
800 // Regression test for b/203199510
TEST_F(QuicCryptoStreamTest,EmptyCryptoFrame)801 TEST_F(QuicCryptoStreamTest, EmptyCryptoFrame) {
802 if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) {
803 return;
804 }
805 EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
806 QuicCryptoFrame empty_crypto_frame(ENCRYPTION_INITIAL, 0, nullptr, 0);
807 stream_->OnCryptoFrame(empty_crypto_frame);
808 }
809
810 } // namespace
811 } // namespace test
812 } // namespace quic
813