Close SSLClientSocketOpenSSL cleanly if the transport was closed.
[chromium-blink-merge.git] / net / socket / ssl_client_socket_unittest.cc
blob58e43c75f47bd91e08a6df967847d899b4fd3409
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.
5 #include "net/socket/ssl_client_socket.h"
7 #include "base/callback_helpers.h"
8 #include "base/memory/ref_counted.h"
9 #include "base/run_loop.h"
10 #include "base/time/time.h"
11 #include "net/base/address_list.h"
12 #include "net/base/io_buffer.h"
13 #include "net/base/net_errors.h"
14 #include "net/base/net_log.h"
15 #include "net/base/net_log_unittest.h"
16 #include "net/base/test_completion_callback.h"
17 #include "net/base/test_data_directory.h"
18 #include "net/cert/asn1_util.h"
19 #include "net/cert/ct_verifier.h"
20 #include "net/cert/mock_cert_verifier.h"
21 #include "net/cert/test_root_certs.h"
22 #include "net/dns/host_resolver.h"
23 #include "net/http/transport_security_state.h"
24 #include "net/socket/client_socket_factory.h"
25 #include "net/socket/client_socket_handle.h"
26 #include "net/socket/socket_test_util.h"
27 #include "net/socket/tcp_client_socket.h"
28 #include "net/ssl/channel_id_service.h"
29 #include "net/ssl/default_channel_id_store.h"
30 #include "net/ssl/ssl_cert_request_info.h"
31 #include "net/ssl/ssl_config_service.h"
32 #include "net/test/cert_test_util.h"
33 #include "net/test/spawned_test_server/spawned_test_server.h"
34 #include "testing/gmock/include/gmock/gmock.h"
35 #include "testing/gtest/include/gtest/gtest.h"
36 #include "testing/platform_test.h"
38 //-----------------------------------------------------------------------------
40 using testing::_;
41 using testing::Return;
42 using testing::Truly;
44 namespace net {
46 namespace {
48 const SSLConfig kDefaultSSLConfig;
50 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
51 // forwarding the Socket and StreamSocket interfaces to the underlying
52 // transport.
53 // This is to provide a common base class for subclasses to override specific
54 // StreamSocket methods for testing, while still communicating with a 'real'
55 // StreamSocket.
56 class WrappedStreamSocket : public StreamSocket {
57 public:
58 explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport)
59 : transport_(transport.Pass()) {}
60 virtual ~WrappedStreamSocket() {}
62 // StreamSocket implementation:
63 virtual int Connect(const CompletionCallback& callback) override {
64 return transport_->Connect(callback);
66 virtual void Disconnect() override { transport_->Disconnect(); }
67 virtual bool IsConnected() const override {
68 return transport_->IsConnected();
70 virtual bool IsConnectedAndIdle() const override {
71 return transport_->IsConnectedAndIdle();
73 virtual int GetPeerAddress(IPEndPoint* address) const override {
74 return transport_->GetPeerAddress(address);
76 virtual int GetLocalAddress(IPEndPoint* address) const override {
77 return transport_->GetLocalAddress(address);
79 virtual const BoundNetLog& NetLog() const override {
80 return transport_->NetLog();
82 virtual void SetSubresourceSpeculation() override {
83 transport_->SetSubresourceSpeculation();
85 virtual void SetOmniboxSpeculation() override {
86 transport_->SetOmniboxSpeculation();
88 virtual bool WasEverUsed() const override {
89 return transport_->WasEverUsed();
91 virtual bool UsingTCPFastOpen() const override {
92 return transport_->UsingTCPFastOpen();
94 virtual bool WasNpnNegotiated() const override {
95 return transport_->WasNpnNegotiated();
97 virtual NextProto GetNegotiatedProtocol() const override {
98 return transport_->GetNegotiatedProtocol();
100 virtual bool GetSSLInfo(SSLInfo* ssl_info) override {
101 return transport_->GetSSLInfo(ssl_info);
104 // Socket implementation:
105 virtual int Read(IOBuffer* buf,
106 int buf_len,
107 const CompletionCallback& callback) override {
108 return transport_->Read(buf, buf_len, callback);
110 virtual int Write(IOBuffer* buf,
111 int buf_len,
112 const CompletionCallback& callback) override {
113 return transport_->Write(buf, buf_len, callback);
115 virtual int SetReceiveBufferSize(int32 size) override {
116 return transport_->SetReceiveBufferSize(size);
118 virtual int SetSendBufferSize(int32 size) override {
119 return transport_->SetSendBufferSize(size);
122 protected:
123 scoped_ptr<StreamSocket> transport_;
126 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
127 // will ensure a certain amount of data is internally buffered before
128 // satisfying a Read() request. It exists to mimic OS-level internal
129 // buffering, but in a way to guarantee that X number of bytes will be
130 // returned to callers of Read(), regardless of how quickly the OS receives
131 // them from the TestServer.
132 class ReadBufferingStreamSocket : public WrappedStreamSocket {
133 public:
134 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
135 virtual ~ReadBufferingStreamSocket() {}
137 // Socket implementation:
138 virtual int Read(IOBuffer* buf,
139 int buf_len,
140 const CompletionCallback& callback) override;
142 // Sets the internal buffer to |size|. This must not be greater than
143 // the largest value supplied to Read() - that is, it does not handle
144 // having "leftovers" at the end of Read().
145 // Each call to Read() will be prevented from completion until at least
146 // |size| data has been read.
147 // Set to 0 to turn off buffering, causing Read() to transparently
148 // read via the underlying transport.
149 void SetBufferSize(int size);
151 private:
152 enum State {
153 STATE_NONE,
154 STATE_READ,
155 STATE_READ_COMPLETE,
158 int DoLoop(int result);
159 int DoRead();
160 int DoReadComplete(int result);
161 void OnReadCompleted(int result);
163 State state_;
164 scoped_refptr<GrowableIOBuffer> read_buffer_;
165 int buffer_size_;
167 scoped_refptr<IOBuffer> user_read_buf_;
168 CompletionCallback user_read_callback_;
171 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
172 scoped_ptr<StreamSocket> transport)
173 : WrappedStreamSocket(transport.Pass()),
174 read_buffer_(new GrowableIOBuffer()),
175 buffer_size_(0) {}
177 void ReadBufferingStreamSocket::SetBufferSize(int size) {
178 DCHECK(!user_read_buf_.get());
179 buffer_size_ = size;
180 read_buffer_->SetCapacity(size);
183 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
184 int buf_len,
185 const CompletionCallback& callback) {
186 if (buffer_size_ == 0)
187 return transport_->Read(buf, buf_len, callback);
189 if (buf_len < buffer_size_)
190 return ERR_UNEXPECTED;
192 state_ = STATE_READ;
193 user_read_buf_ = buf;
194 int result = DoLoop(OK);
195 if (result == ERR_IO_PENDING)
196 user_read_callback_ = callback;
197 else
198 user_read_buf_ = NULL;
199 return result;
202 int ReadBufferingStreamSocket::DoLoop(int result) {
203 int rv = result;
204 do {
205 State current_state = state_;
206 state_ = STATE_NONE;
207 switch (current_state) {
208 case STATE_READ:
209 rv = DoRead();
210 break;
211 case STATE_READ_COMPLETE:
212 rv = DoReadComplete(rv);
213 break;
214 case STATE_NONE:
215 default:
216 NOTREACHED() << "Unexpected state: " << current_state;
217 rv = ERR_UNEXPECTED;
218 break;
220 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
221 return rv;
224 int ReadBufferingStreamSocket::DoRead() {
225 state_ = STATE_READ_COMPLETE;
226 int rv =
227 transport_->Read(read_buffer_.get(),
228 read_buffer_->RemainingCapacity(),
229 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
230 base::Unretained(this)));
231 return rv;
234 int ReadBufferingStreamSocket::DoReadComplete(int result) {
235 state_ = STATE_NONE;
236 if (result <= 0)
237 return result;
239 read_buffer_->set_offset(read_buffer_->offset() + result);
240 if (read_buffer_->RemainingCapacity() > 0) {
241 state_ = STATE_READ;
242 return OK;
245 memcpy(user_read_buf_->data(),
246 read_buffer_->StartOfBuffer(),
247 read_buffer_->capacity());
248 read_buffer_->set_offset(0);
249 return read_buffer_->capacity();
252 void ReadBufferingStreamSocket::OnReadCompleted(int result) {
253 result = DoLoop(result);
254 if (result == ERR_IO_PENDING)
255 return;
257 user_read_buf_ = NULL;
258 base::ResetAndReturn(&user_read_callback_).Run(result);
261 // Simulates synchronously receiving an error during Read() or Write()
262 class SynchronousErrorStreamSocket : public WrappedStreamSocket {
263 public:
264 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
265 virtual ~SynchronousErrorStreamSocket() {}
267 // Socket implementation:
268 virtual int Read(IOBuffer* buf,
269 int buf_len,
270 const CompletionCallback& callback) override;
271 virtual int Write(IOBuffer* buf,
272 int buf_len,
273 const CompletionCallback& callback) override;
275 // Sets the next Read() call and all future calls to return |error|.
276 // If there is already a pending asynchronous read, the configured error
277 // will not be returned until that asynchronous read has completed and Read()
278 // is called again.
279 void SetNextReadError(int error) {
280 DCHECK_GE(0, error);
281 have_read_error_ = true;
282 pending_read_error_ = error;
285 // Sets the next Write() call and all future calls to return |error|.
286 // If there is already a pending asynchronous write, the configured error
287 // will not be returned until that asynchronous write has completed and
288 // Write() is called again.
289 void SetNextWriteError(int error) {
290 DCHECK_GE(0, error);
291 have_write_error_ = true;
292 pending_write_error_ = error;
295 private:
296 bool have_read_error_;
297 int pending_read_error_;
299 bool have_write_error_;
300 int pending_write_error_;
302 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket);
305 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
306 scoped_ptr<StreamSocket> transport)
307 : WrappedStreamSocket(transport.Pass()),
308 have_read_error_(false),
309 pending_read_error_(OK),
310 have_write_error_(false),
311 pending_write_error_(OK) {}
313 int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
314 int buf_len,
315 const CompletionCallback& callback) {
316 if (have_read_error_)
317 return pending_read_error_;
318 return transport_->Read(buf, buf_len, callback);
321 int SynchronousErrorStreamSocket::Write(IOBuffer* buf,
322 int buf_len,
323 const CompletionCallback& callback) {
324 if (have_write_error_)
325 return pending_write_error_;
326 return transport_->Write(buf, buf_len, callback);
329 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
330 // underlying transport needing to complete things asynchronously in a
331 // deterministic manner (e.g.: independent of the TestServer and the OS's
332 // semantics).
333 class FakeBlockingStreamSocket : public WrappedStreamSocket {
334 public:
335 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
336 virtual ~FakeBlockingStreamSocket() {}
338 // Socket implementation:
339 virtual int Read(IOBuffer* buf,
340 int buf_len,
341 const CompletionCallback& callback) override;
342 virtual int Write(IOBuffer* buf,
343 int buf_len,
344 const CompletionCallback& callback) override;
346 // Blocks read results on the socket. Reads will not complete until
347 // UnblockReadResult() has been called and a result is ready from the
348 // underlying transport. Note: if BlockReadResult() is called while there is a
349 // hanging asynchronous Read(), that Read is blocked.
350 void BlockReadResult();
351 void UnblockReadResult();
353 // Waits for the blocked Read() call to be complete at the underlying
354 // transport.
355 void WaitForReadResult();
357 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
358 // underlying transport until UnblockWrite() has been called. Note: if there
359 // is a pending asynchronous write, it is NOT blocked. For purposes of
360 // blocking writes, data is considered to have reached the underlying
361 // transport as soon as Write() is called.
362 void BlockWrite();
363 void UnblockWrite();
365 // Waits for the blocked Write() call to be scheduled.
366 void WaitForWrite();
368 // Returns the wrapped stream socket.
369 StreamSocket* transport() { return transport_.get(); }
371 private:
372 // Handles completion from the underlying transport read.
373 void OnReadCompleted(int result);
375 // True if read callbacks are blocked.
376 bool should_block_read_;
378 // The user callback for the pending read call.
379 CompletionCallback pending_read_callback_;
381 // The result for the blocked read callback, or ERR_IO_PENDING if not
382 // completed.
383 int pending_read_result_;
385 // WaitForReadResult() wait loop.
386 scoped_ptr<base::RunLoop> read_loop_;
388 // True if write calls are blocked.
389 bool should_block_write_;
391 // The buffer for the pending write, or NULL if not scheduled.
392 scoped_refptr<IOBuffer> pending_write_buf_;
394 // The callback for the pending write call.
395 CompletionCallback pending_write_callback_;
397 // The length for the pending write, or -1 if not scheduled.
398 int pending_write_len_;
400 // WaitForWrite() wait loop.
401 scoped_ptr<base::RunLoop> write_loop_;
404 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
405 scoped_ptr<StreamSocket> transport)
406 : WrappedStreamSocket(transport.Pass()),
407 should_block_read_(false),
408 pending_read_result_(ERR_IO_PENDING),
409 should_block_write_(false),
410 pending_write_len_(-1) {}
412 int FakeBlockingStreamSocket::Read(IOBuffer* buf,
413 int len,
414 const CompletionCallback& callback) {
415 DCHECK(pending_read_callback_.is_null());
416 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
417 DCHECK(!callback.is_null());
419 int rv = transport_->Read(buf, len, base::Bind(
420 &FakeBlockingStreamSocket::OnReadCompleted, base::Unretained(this)));
421 if (rv == ERR_IO_PENDING) {
422 // Save the callback to be called later.
423 pending_read_callback_ = callback;
424 } else if (should_block_read_) {
425 // Save the callback and read result to be called later.
426 pending_read_callback_ = callback;
427 OnReadCompleted(rv);
428 rv = ERR_IO_PENDING;
430 return rv;
433 int FakeBlockingStreamSocket::Write(IOBuffer* buf,
434 int len,
435 const CompletionCallback& callback) {
436 DCHECK(buf);
437 DCHECK_LE(0, len);
439 if (!should_block_write_)
440 return transport_->Write(buf, len, callback);
442 // Schedule the write, but do nothing.
443 DCHECK(!pending_write_buf_.get());
444 DCHECK_EQ(-1, pending_write_len_);
445 DCHECK(pending_write_callback_.is_null());
446 DCHECK(!callback.is_null());
447 pending_write_buf_ = buf;
448 pending_write_len_ = len;
449 pending_write_callback_ = callback;
451 // Stop the write loop, if any.
452 if (write_loop_)
453 write_loop_->Quit();
454 return ERR_IO_PENDING;
457 void FakeBlockingStreamSocket::BlockReadResult() {
458 DCHECK(!should_block_read_);
459 should_block_read_ = true;
462 void FakeBlockingStreamSocket::UnblockReadResult() {
463 DCHECK(should_block_read_);
464 should_block_read_ = false;
466 // If the operation is still pending in the underlying transport, immediately
467 // return - OnReadCompleted() will handle invoking the callback once the
468 // transport has completed.
469 if (pending_read_result_ == ERR_IO_PENDING)
470 return;
471 int result = pending_read_result_;
472 pending_read_result_ = ERR_IO_PENDING;
473 base::ResetAndReturn(&pending_read_callback_).Run(result);
476 void FakeBlockingStreamSocket::WaitForReadResult() {
477 DCHECK(should_block_read_);
478 DCHECK(!read_loop_);
480 if (pending_read_result_ != ERR_IO_PENDING)
481 return;
482 read_loop_.reset(new base::RunLoop);
483 read_loop_->Run();
484 read_loop_.reset();
485 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
488 void FakeBlockingStreamSocket::BlockWrite() {
489 DCHECK(!should_block_write_);
490 should_block_write_ = true;
493 void FakeBlockingStreamSocket::UnblockWrite() {
494 DCHECK(should_block_write_);
495 should_block_write_ = false;
497 // Do nothing if UnblockWrite() was called after BlockWrite(),
498 // without a Write() in between.
499 if (!pending_write_buf_.get())
500 return;
502 int rv = transport_->Write(
503 pending_write_buf_.get(), pending_write_len_, pending_write_callback_);
504 pending_write_buf_ = NULL;
505 pending_write_len_ = -1;
506 if (rv == ERR_IO_PENDING) {
507 pending_write_callback_.Reset();
508 } else {
509 base::ResetAndReturn(&pending_write_callback_).Run(rv);
513 void FakeBlockingStreamSocket::WaitForWrite() {
514 DCHECK(should_block_write_);
515 DCHECK(!write_loop_);
517 if (pending_write_buf_.get())
518 return;
519 write_loop_.reset(new base::RunLoop);
520 write_loop_->Run();
521 write_loop_.reset();
522 DCHECK(pending_write_buf_.get());
525 void FakeBlockingStreamSocket::OnReadCompleted(int result) {
526 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
527 DCHECK(!pending_read_callback_.is_null());
529 if (should_block_read_) {
530 // Store the result so that the callback can be invoked once Unblock() is
531 // called.
532 pending_read_result_ = result;
534 // Stop the WaitForReadResult() call if any.
535 if (read_loop_)
536 read_loop_->Quit();
537 } else {
538 // Either the Read() was never blocked or UnblockReadResult() was called
539 // before the Read() completed. Either way, run the callback.
540 base::ResetAndReturn(&pending_read_callback_).Run(result);
544 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
545 // reads and writes on the socket.
546 class CountingStreamSocket : public WrappedStreamSocket {
547 public:
548 explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport)
549 : WrappedStreamSocket(transport.Pass()),
550 read_count_(0),
551 write_count_(0) {}
552 virtual ~CountingStreamSocket() {}
554 // Socket implementation:
555 virtual int Read(IOBuffer* buf,
556 int buf_len,
557 const CompletionCallback& callback) override {
558 read_count_++;
559 return transport_->Read(buf, buf_len, callback);
561 virtual int Write(IOBuffer* buf,
562 int buf_len,
563 const CompletionCallback& callback) override {
564 write_count_++;
565 return transport_->Write(buf, buf_len, callback);
568 int read_count() const { return read_count_; }
569 int write_count() const { return write_count_; }
571 private:
572 int read_count_;
573 int write_count_;
576 // CompletionCallback that will delete the associated StreamSocket when
577 // the callback is invoked.
578 class DeleteSocketCallback : public TestCompletionCallbackBase {
579 public:
580 explicit DeleteSocketCallback(StreamSocket* socket)
581 : socket_(socket),
582 callback_(base::Bind(&DeleteSocketCallback::OnComplete,
583 base::Unretained(this))) {}
584 virtual ~DeleteSocketCallback() {}
586 const CompletionCallback& callback() const { return callback_; }
588 private:
589 void OnComplete(int result) {
590 if (socket_) {
591 delete socket_;
592 socket_ = NULL;
593 } else {
594 ADD_FAILURE() << "Deleting socket twice";
596 SetResult(result);
599 StreamSocket* socket_;
600 CompletionCallback callback_;
602 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
605 // A ChannelIDStore that always returns an error when asked for a
606 // channel id.
607 class FailingChannelIDStore : public ChannelIDStore {
608 virtual int GetChannelID(const std::string& server_identifier,
609 base::Time* expiration_time,
610 std::string* private_key_result,
611 std::string* cert_result,
612 const GetChannelIDCallback& callback) override {
613 return ERR_UNEXPECTED;
615 virtual void SetChannelID(const std::string& server_identifier,
616 base::Time creation_time,
617 base::Time expiration_time,
618 const std::string& private_key,
619 const std::string& cert) override {}
620 virtual void DeleteChannelID(const std::string& server_identifier,
621 const base::Closure& completion_callback)
622 override {}
623 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
624 base::Time delete_end,
625 const base::Closure& completion_callback)
626 override {}
627 virtual void DeleteAll(const base::Closure& completion_callback) override {}
628 virtual void GetAllChannelIDs(const GetChannelIDListCallback& callback)
629 override {}
630 virtual int GetChannelIDCount() override { return 0; }
631 virtual void SetForceKeepSessionState() override {}
634 // A ChannelIDStore that asynchronously returns an error when asked for a
635 // channel id.
636 class AsyncFailingChannelIDStore : public ChannelIDStore {
637 virtual int GetChannelID(const std::string& server_identifier,
638 base::Time* expiration_time,
639 std::string* private_key_result,
640 std::string* cert_result,
641 const GetChannelIDCallback& callback) override {
642 base::MessageLoop::current()->PostTask(
643 FROM_HERE, base::Bind(callback, ERR_UNEXPECTED,
644 server_identifier, base::Time(), "", ""));
645 return ERR_IO_PENDING;
647 virtual void SetChannelID(const std::string& server_identifier,
648 base::Time creation_time,
649 base::Time expiration_time,
650 const std::string& private_key,
651 const std::string& cert) override {}
652 virtual void DeleteChannelID(const std::string& server_identifier,
653 const base::Closure& completion_callback)
654 override {}
655 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
656 base::Time delete_end,
657 const base::Closure& completion_callback)
658 override {}
659 virtual void DeleteAll(const base::Closure& completion_callback) override {}
660 virtual void GetAllChannelIDs(const GetChannelIDListCallback& callback)
661 override {}
662 virtual int GetChannelIDCount() override { return 0; }
663 virtual void SetForceKeepSessionState() override {}
666 // A mock CTVerifier that records every call to Verify but doesn't verify
667 // anything.
668 class MockCTVerifier : public CTVerifier {
669 public:
670 MOCK_METHOD5(Verify, int(X509Certificate*,
671 const std::string&,
672 const std::string&,
673 ct::CTVerifyResult*,
674 const BoundNetLog&));
677 class SSLClientSocketTest : public PlatformTest {
678 public:
679 SSLClientSocketTest()
680 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
681 cert_verifier_(new MockCertVerifier),
682 transport_security_state_(new TransportSecurityState),
683 ran_handshake_completion_callback_(false) {
684 cert_verifier_->set_default_result(OK);
685 context_.cert_verifier = cert_verifier_.get();
686 context_.transport_security_state = transport_security_state_.get();
689 void RecordCompletedHandshake() { ran_handshake_completion_callback_ = true; }
691 protected:
692 // The address of the spawned test server, after calling StartTestServer().
693 const AddressList& addr() const { return addr_; }
695 // The SpawnedTestServer object, after calling StartTestServer().
696 const SpawnedTestServer* test_server() const { return test_server_.get(); }
698 void SetCTVerifier(CTVerifier* ct_verifier) {
699 context_.cert_transparency_verifier = ct_verifier;
702 // Starts the test server with SSL configuration |ssl_options|. Returns true
703 // on success.
704 bool StartTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
705 test_server_.reset(new SpawnedTestServer(
706 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()));
707 if (!test_server_->Start()) {
708 LOG(ERROR) << "Could not start SpawnedTestServer";
709 return false;
712 if (!test_server_->GetAddressList(&addr_)) {
713 LOG(ERROR) << "Could not get SpawnedTestServer address list";
714 return false;
716 return true;
719 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
720 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
721 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
722 if (!StartTestServer(ssl_options))
723 return false;
725 transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source()));
726 int rv = callback_.GetResult(transport_->Connect(callback_.callback()));
727 if (rv != OK) {
728 LOG(ERROR) << "Could not connect to SpawnedTestServer";
729 return false;
731 return true;
734 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
735 scoped_ptr<StreamSocket> transport_socket,
736 const HostPortPair& host_and_port,
737 const SSLConfig& ssl_config) {
738 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
739 connection->SetSocket(transport_socket.Pass());
740 return socket_factory_->CreateSSLClientSocket(
741 connection.Pass(), host_and_port, ssl_config, context_);
744 // Create an SSLClientSocket object and use it to connect to a test
745 // server, then wait for connection results. This must be called after
746 // a successful ConnectToTestServer() call.
747 // |ssl_config| the SSL configuration to use.
748 // |result| will retrieve the ::Connect() result value.
749 // Returns true on success, false otherwise. Success means that the socket
750 // could be created and its Connect() was called, not that the connection
751 // itself was a success.
752 bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) {
753 sock_ = CreateSSLClientSocket(
754 transport_.Pass(), test_server_->host_port_pair(), ssl_config);
756 if (sock_->IsConnected()) {
757 LOG(ERROR) << "SSL Socket prematurely connected";
758 return false;
761 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
762 return true;
765 ClientSocketFactory* socket_factory_;
766 scoped_ptr<MockCertVerifier> cert_verifier_;
767 scoped_ptr<TransportSecurityState> transport_security_state_;
768 SSLClientSocketContext context_;
769 scoped_ptr<SSLClientSocket> sock_;
770 CapturingNetLog log_;
771 bool ran_handshake_completion_callback_;
773 private:
774 scoped_ptr<StreamSocket> transport_;
775 scoped_ptr<SpawnedTestServer> test_server_;
776 TestCompletionCallback callback_;
777 AddressList addr_;
780 // Verifies the correctness of GetSSLCertRequestInfo.
781 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
782 protected:
783 // Creates a test server with the given SSLOptions, connects to it and returns
784 // the SSLCertRequestInfo reported by the socket.
785 scoped_refptr<SSLCertRequestInfo> GetCertRequest(
786 SpawnedTestServer::SSLOptions ssl_options) {
787 SpawnedTestServer test_server(
788 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
789 if (!test_server.Start())
790 return NULL;
792 AddressList addr;
793 if (!test_server.GetAddressList(&addr))
794 return NULL;
796 TestCompletionCallback callback;
797 CapturingNetLog log;
798 scoped_ptr<StreamSocket> transport(
799 new TCPClientSocket(addr, &log, NetLog::Source()));
800 int rv = transport->Connect(callback.callback());
801 if (rv == ERR_IO_PENDING)
802 rv = callback.WaitForResult();
803 EXPECT_EQ(OK, rv);
805 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
806 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
807 EXPECT_FALSE(sock->IsConnected());
809 rv = sock->Connect(callback.callback());
810 if (rv == ERR_IO_PENDING)
811 rv = callback.WaitForResult();
812 scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
813 sock->GetSSLCertRequestInfo(request_info.get());
814 sock->Disconnect();
815 EXPECT_FALSE(sock->IsConnected());
816 EXPECT_TRUE(
817 test_server.host_port_pair().Equals(request_info->host_and_port));
819 return request_info;
823 class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
824 public:
825 SSLClientSocketFalseStartTest()
826 : monitor_handshake_callback_(false),
827 fail_handshake_after_false_start_(false) {}
829 protected:
830 // Creates an SSLClientSocket with |client_config| attached to a
831 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
832 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
833 // so |*out_raw_transport| is a raw pointer.
835 // The client socket will begin a connect using |callback| but stop before the
836 // server's finished message is received. The finished message will be blocked
837 // in |*out_raw_transport|. To complete the handshake and successfully read
838 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
839 // the client successfully false started, |callback.WaitForResult()| will
840 // return OK without unblocking transport reads. But Read() will still block.)
842 // Must be called after StartTestServer is called.
843 void CreateAndConnectUntilServerFinishedReceived(
844 const SSLConfig& client_config,
845 TestCompletionCallback* callback,
846 FakeBlockingStreamSocket** out_raw_transport,
847 scoped_ptr<SSLClientSocket>* out_sock) {
848 CHECK(test_server());
850 scoped_ptr<StreamSocket> real_transport(scoped_ptr<StreamSocket>(
851 new TCPClientSocket(addr(), NULL, NetLog::Source())));
852 real_transport.reset(
853 new SynchronousErrorStreamSocket(real_transport.Pass()));
855 scoped_ptr<FakeBlockingStreamSocket> transport(
856 new FakeBlockingStreamSocket(real_transport.Pass()));
857 int rv = callback->GetResult(transport->Connect(callback->callback()));
858 EXPECT_EQ(OK, rv);
860 FakeBlockingStreamSocket* raw_transport = transport.get();
861 scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
862 transport.Pass(), test_server()->host_port_pair(), client_config);
864 if (monitor_handshake_callback_) {
865 sock->SetHandshakeCompletionCallback(
866 base::Bind(&SSLClientSocketTest::RecordCompletedHandshake,
867 base::Unretained(this)));
870 // Connect. Stop before the client processes the first server leg
871 // (ServerHello, etc.)
872 raw_transport->BlockReadResult();
873 rv = sock->Connect(callback->callback());
874 EXPECT_EQ(ERR_IO_PENDING, rv);
875 raw_transport->WaitForReadResult();
877 // Release the ServerHello and wait for the client to write
878 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
879 // server's leg to complete, since it may span multiple reads.)
880 EXPECT_FALSE(callback->have_result());
881 raw_transport->BlockWrite();
882 raw_transport->UnblockReadResult();
883 raw_transport->WaitForWrite();
885 if (fail_handshake_after_false_start_) {
886 SynchronousErrorStreamSocket* error_socket =
887 static_cast<SynchronousErrorStreamSocket*>(
888 raw_transport->transport());
889 error_socket->SetNextReadError(ERR_CONNECTION_RESET);
891 // And, finally, release that and block the next server leg
892 // (ChangeCipherSpec, Finished).
893 raw_transport->BlockReadResult();
894 raw_transport->UnblockWrite();
896 *out_raw_transport = raw_transport;
897 *out_sock = sock.Pass();
900 void TestFalseStart(const SpawnedTestServer::SSLOptions& server_options,
901 const SSLConfig& client_config,
902 bool expect_false_start) {
903 ASSERT_TRUE(StartTestServer(server_options));
905 TestCompletionCallback callback;
906 FakeBlockingStreamSocket* raw_transport = NULL;
907 scoped_ptr<SSLClientSocket> sock;
909 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
910 client_config, &callback, &raw_transport, &sock));
912 if (expect_false_start) {
913 // When False Starting, the handshake should complete before receiving the
914 // Change Cipher Spec and Finished messages.
916 // Note: callback.have_result() may not be true without waiting. The NSS
917 // state machine sometimes lives on a separate thread, so this thread may
918 // not yet have processed the signal that the handshake has completed.
919 int rv = callback.WaitForResult();
920 EXPECT_EQ(OK, rv);
921 EXPECT_TRUE(sock->IsConnected());
923 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
924 static const int kRequestTextSize =
925 static_cast<int>(arraysize(request_text) - 1);
926 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
927 memcpy(request_buffer->data(), request_text, kRequestTextSize);
929 // Write the request.
930 rv = callback.GetResult(sock->Write(request_buffer.get(),
931 kRequestTextSize,
932 callback.callback()));
933 EXPECT_EQ(kRequestTextSize, rv);
935 // The read will hang; it's waiting for the peer to complete the
936 // handshake, and the handshake is still blocked.
937 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
938 rv = sock->Read(buf.get(), 4096, callback.callback());
940 // After releasing reads, the connection proceeds.
941 raw_transport->UnblockReadResult();
942 rv = callback.GetResult(rv);
943 if (fail_handshake_after_false_start_)
944 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
945 else
946 EXPECT_LT(0, rv);
947 } else {
948 // False Start is not enabled, so the handshake will not complete because
949 // the server second leg is blocked.
950 base::RunLoop().RunUntilIdle();
951 EXPECT_FALSE(callback.have_result());
955 // Indicates that the socket's handshake completion callback should
956 // be monitored.
957 bool monitor_handshake_callback_;
958 // Indicates that this test's handshake should fail after the client
959 // "finished" message is sent.
960 bool fail_handshake_after_false_start_;
963 class SSLClientSocketChannelIDTest : public SSLClientSocketTest {
964 protected:
965 void EnableChannelID() {
966 channel_id_service_.reset(
967 new ChannelIDService(new DefaultChannelIDStore(NULL),
968 base::MessageLoopProxy::current()));
969 context_.channel_id_service = channel_id_service_.get();
972 void EnableFailingChannelID() {
973 channel_id_service_.reset(new ChannelIDService(
974 new FailingChannelIDStore(), base::MessageLoopProxy::current()));
975 context_.channel_id_service = channel_id_service_.get();
978 void EnableAsyncFailingChannelID() {
979 channel_id_service_.reset(new ChannelIDService(
980 new AsyncFailingChannelIDStore(),
981 base::MessageLoopProxy::current()));
982 context_.channel_id_service = channel_id_service_.get();
985 private:
986 scoped_ptr<ChannelIDService> channel_id_service_;
989 //-----------------------------------------------------------------------------
991 // LogContainsSSLConnectEndEvent returns true if the given index in the given
992 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
993 // merge the first application data record with the Finished message when false
994 // starting. However, in order to avoid the server timing out the handshake,
995 // they'll give up waiting for application data and send the Finished after a
996 // timeout. This means that an SSL connect end event may appear as a socket
997 // write.
998 static bool LogContainsSSLConnectEndEvent(
999 const CapturingNetLog::CapturedEntryList& log,
1000 int i) {
1001 return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
1002 LogContainsEvent(
1003 log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
1006 } // namespace
1008 TEST_F(SSLClientSocketTest, Connect) {
1009 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1010 SpawnedTestServer::kLocalhost,
1011 base::FilePath());
1012 ASSERT_TRUE(test_server.Start());
1014 AddressList addr;
1015 ASSERT_TRUE(test_server.GetAddressList(&addr));
1017 TestCompletionCallback callback;
1018 CapturingNetLog log;
1019 scoped_ptr<StreamSocket> transport(
1020 new TCPClientSocket(addr, &log, NetLog::Source()));
1021 int rv = transport->Connect(callback.callback());
1022 if (rv == ERR_IO_PENDING)
1023 rv = callback.WaitForResult();
1024 EXPECT_EQ(OK, rv);
1026 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1027 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1029 EXPECT_FALSE(sock->IsConnected());
1031 rv = sock->Connect(callback.callback());
1033 CapturingNetLog::CapturedEntryList entries;
1034 log.GetEntries(&entries);
1035 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1036 if (rv == ERR_IO_PENDING)
1037 rv = callback.WaitForResult();
1038 EXPECT_EQ(OK, rv);
1039 EXPECT_TRUE(sock->IsConnected());
1040 log.GetEntries(&entries);
1041 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1043 sock->Disconnect();
1044 EXPECT_FALSE(sock->IsConnected());
1047 TEST_F(SSLClientSocketTest, ConnectExpired) {
1048 SpawnedTestServer::SSLOptions ssl_options(
1049 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
1050 SpawnedTestServer test_server(
1051 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1052 ASSERT_TRUE(test_server.Start());
1054 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
1056 AddressList addr;
1057 ASSERT_TRUE(test_server.GetAddressList(&addr));
1059 TestCompletionCallback callback;
1060 CapturingNetLog log;
1061 scoped_ptr<StreamSocket> transport(
1062 new TCPClientSocket(addr, &log, NetLog::Source()));
1063 int rv = transport->Connect(callback.callback());
1064 if (rv == ERR_IO_PENDING)
1065 rv = callback.WaitForResult();
1066 EXPECT_EQ(OK, rv);
1068 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1069 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1071 EXPECT_FALSE(sock->IsConnected());
1073 rv = sock->Connect(callback.callback());
1075 CapturingNetLog::CapturedEntryList entries;
1076 log.GetEntries(&entries);
1077 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1078 if (rv == ERR_IO_PENDING)
1079 rv = callback.WaitForResult();
1081 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
1083 // Rather than testing whether or not the underlying socket is connected,
1084 // test that the handshake has finished. This is because it may be
1085 // desirable to disconnect the socket before showing a user prompt, since
1086 // the user may take indefinitely long to respond.
1087 log.GetEntries(&entries);
1088 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1091 TEST_F(SSLClientSocketTest, ConnectMismatched) {
1092 SpawnedTestServer::SSLOptions ssl_options(
1093 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
1094 SpawnedTestServer test_server(
1095 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1096 ASSERT_TRUE(test_server.Start());
1098 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
1100 AddressList addr;
1101 ASSERT_TRUE(test_server.GetAddressList(&addr));
1103 TestCompletionCallback callback;
1104 CapturingNetLog log;
1105 scoped_ptr<StreamSocket> transport(
1106 new TCPClientSocket(addr, &log, NetLog::Source()));
1107 int rv = transport->Connect(callback.callback());
1108 if (rv == ERR_IO_PENDING)
1109 rv = callback.WaitForResult();
1110 EXPECT_EQ(OK, rv);
1112 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1113 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1115 EXPECT_FALSE(sock->IsConnected());
1117 rv = sock->Connect(callback.callback());
1119 CapturingNetLog::CapturedEntryList entries;
1120 log.GetEntries(&entries);
1121 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1122 if (rv == ERR_IO_PENDING)
1123 rv = callback.WaitForResult();
1125 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
1127 // Rather than testing whether or not the underlying socket is connected,
1128 // test that the handshake has finished. This is because it may be
1129 // desirable to disconnect the socket before showing a user prompt, since
1130 // the user may take indefinitely long to respond.
1131 log.GetEntries(&entries);
1132 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1135 // Attempt to connect to a page which requests a client certificate. It should
1136 // return an error code on connect.
1137 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
1138 SpawnedTestServer::SSLOptions ssl_options;
1139 ssl_options.request_client_certificate = true;
1140 SpawnedTestServer test_server(
1141 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1142 ASSERT_TRUE(test_server.Start());
1144 AddressList addr;
1145 ASSERT_TRUE(test_server.GetAddressList(&addr));
1147 TestCompletionCallback callback;
1148 CapturingNetLog log;
1149 scoped_ptr<StreamSocket> transport(
1150 new TCPClientSocket(addr, &log, NetLog::Source()));
1151 int rv = transport->Connect(callback.callback());
1152 if (rv == ERR_IO_PENDING)
1153 rv = callback.WaitForResult();
1154 EXPECT_EQ(OK, rv);
1156 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1157 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1159 EXPECT_FALSE(sock->IsConnected());
1161 rv = sock->Connect(callback.callback());
1163 CapturingNetLog::CapturedEntryList entries;
1164 log.GetEntries(&entries);
1165 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1166 if (rv == ERR_IO_PENDING)
1167 rv = callback.WaitForResult();
1169 log.GetEntries(&entries);
1170 // Because we prematurely kill the handshake at CertificateRequest,
1171 // the server may still send data (notably the ServerHelloDone)
1172 // after the error is returned. As a result, the SSL_CONNECT may not
1173 // be the last entry. See http://crbug.com/54445. We use
1174 // ExpectLogContainsSomewhere instead of
1175 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1176 // extra read instead of two. This occurs before the handshake ends,
1177 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1178 // necessary.
1180 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1181 // fixed and we can respond to the first CertificateRequest
1182 // without closing the socket, add a unit test for sending the
1183 // certificate. This test may still be useful as we'll want to close
1184 // the socket on a timeout if the user takes a long time to pick a
1185 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1186 ExpectLogContainsSomewhere(
1187 entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END);
1188 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
1189 EXPECT_FALSE(sock->IsConnected());
1192 // Connect to a server requesting optional client authentication. Send it a
1193 // null certificate. It should allow the connection.
1195 // TODO(davidben): Also test providing an actual certificate.
1196 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
1197 SpawnedTestServer::SSLOptions ssl_options;
1198 ssl_options.request_client_certificate = true;
1199 SpawnedTestServer test_server(
1200 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1201 ASSERT_TRUE(test_server.Start());
1203 AddressList addr;
1204 ASSERT_TRUE(test_server.GetAddressList(&addr));
1206 TestCompletionCallback callback;
1207 CapturingNetLog log;
1208 scoped_ptr<StreamSocket> transport(
1209 new TCPClientSocket(addr, &log, NetLog::Source()));
1210 int rv = transport->Connect(callback.callback());
1211 if (rv == ERR_IO_PENDING)
1212 rv = callback.WaitForResult();
1213 EXPECT_EQ(OK, rv);
1215 SSLConfig ssl_config = kDefaultSSLConfig;
1216 ssl_config.send_client_cert = true;
1217 ssl_config.client_cert = NULL;
1219 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1220 transport.Pass(), test_server.host_port_pair(), ssl_config));
1222 EXPECT_FALSE(sock->IsConnected());
1224 // Our test server accepts certificate-less connections.
1225 // TODO(davidben): Add a test which requires them and verify the error.
1226 rv = sock->Connect(callback.callback());
1228 CapturingNetLog::CapturedEntryList entries;
1229 log.GetEntries(&entries);
1230 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1231 if (rv == ERR_IO_PENDING)
1232 rv = callback.WaitForResult();
1234 EXPECT_EQ(OK, rv);
1235 EXPECT_TRUE(sock->IsConnected());
1236 log.GetEntries(&entries);
1237 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1239 // We responded to the server's certificate request with a Certificate
1240 // message with no client certificate in it. ssl_info.client_cert_sent
1241 // should be false in this case.
1242 SSLInfo ssl_info;
1243 sock->GetSSLInfo(&ssl_info);
1244 EXPECT_FALSE(ssl_info.client_cert_sent);
1246 sock->Disconnect();
1247 EXPECT_FALSE(sock->IsConnected());
1250 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1251 // - Server closes an SSL connection (with a close_notify alert message).
1252 // - Server closes the underlying TCP connection directly.
1253 // - Server sends data unexpectedly.
1255 TEST_F(SSLClientSocketTest, Read) {
1256 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1257 SpawnedTestServer::kLocalhost,
1258 base::FilePath());
1259 ASSERT_TRUE(test_server.Start());
1261 AddressList addr;
1262 ASSERT_TRUE(test_server.GetAddressList(&addr));
1264 TestCompletionCallback callback;
1265 scoped_ptr<StreamSocket> transport(
1266 new TCPClientSocket(addr, NULL, NetLog::Source()));
1267 int rv = transport->Connect(callback.callback());
1268 if (rv == ERR_IO_PENDING)
1269 rv = callback.WaitForResult();
1270 EXPECT_EQ(OK, rv);
1272 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1273 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1275 rv = sock->Connect(callback.callback());
1276 if (rv == ERR_IO_PENDING)
1277 rv = callback.WaitForResult();
1278 EXPECT_EQ(OK, rv);
1279 EXPECT_TRUE(sock->IsConnected());
1281 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1282 scoped_refptr<IOBuffer> request_buffer(
1283 new IOBuffer(arraysize(request_text) - 1));
1284 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1286 rv = sock->Write(
1287 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1288 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1290 if (rv == ERR_IO_PENDING)
1291 rv = callback.WaitForResult();
1292 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1294 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1295 for (;;) {
1296 rv = sock->Read(buf.get(), 4096, callback.callback());
1297 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1299 if (rv == ERR_IO_PENDING)
1300 rv = callback.WaitForResult();
1302 EXPECT_GE(rv, 0);
1303 if (rv <= 0)
1304 break;
1308 // Tests that SSLClientSocket properly handles when the underlying transport
1309 // synchronously fails a transport read in during the handshake. The error code
1310 // should be preserved so SSLv3 fallback logic can condition on it.
1311 TEST_F(SSLClientSocketTest, Connect_WithSynchronousError) {
1312 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1313 SpawnedTestServer::kLocalhost,
1314 base::FilePath());
1315 ASSERT_TRUE(test_server.Start());
1317 AddressList addr;
1318 ASSERT_TRUE(test_server.GetAddressList(&addr));
1320 TestCompletionCallback callback;
1321 scoped_ptr<StreamSocket> real_transport(
1322 new TCPClientSocket(addr, NULL, NetLog::Source()));
1323 scoped_ptr<SynchronousErrorStreamSocket> transport(
1324 new SynchronousErrorStreamSocket(real_transport.Pass()));
1325 int rv = callback.GetResult(transport->Connect(callback.callback()));
1326 EXPECT_EQ(OK, rv);
1328 // Disable TLS False Start to avoid handshake non-determinism.
1329 SSLConfig ssl_config;
1330 ssl_config.false_start_enabled = false;
1332 SynchronousErrorStreamSocket* raw_transport = transport.get();
1333 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1334 transport.Pass(), test_server.host_port_pair(), ssl_config));
1336 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
1338 rv = callback.GetResult(sock->Connect(callback.callback()));
1339 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1340 EXPECT_FALSE(sock->IsConnected());
1343 // Tests that the SSLClientSocket properly handles when the underlying transport
1344 // synchronously returns an error code - such as if an intermediary terminates
1345 // the socket connection uncleanly.
1346 // This is a regression test for http://crbug.com/238536
1347 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
1348 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1349 SpawnedTestServer::kLocalhost,
1350 base::FilePath());
1351 ASSERT_TRUE(test_server.Start());
1353 AddressList addr;
1354 ASSERT_TRUE(test_server.GetAddressList(&addr));
1356 TestCompletionCallback callback;
1357 scoped_ptr<StreamSocket> real_transport(
1358 new TCPClientSocket(addr, NULL, NetLog::Source()));
1359 scoped_ptr<SynchronousErrorStreamSocket> transport(
1360 new SynchronousErrorStreamSocket(real_transport.Pass()));
1361 int rv = callback.GetResult(transport->Connect(callback.callback()));
1362 EXPECT_EQ(OK, rv);
1364 // Disable TLS False Start to avoid handshake non-determinism.
1365 SSLConfig ssl_config;
1366 ssl_config.false_start_enabled = false;
1368 SynchronousErrorStreamSocket* raw_transport = transport.get();
1369 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1370 transport.Pass(), test_server.host_port_pair(), ssl_config));
1372 rv = callback.GetResult(sock->Connect(callback.callback()));
1373 EXPECT_EQ(OK, rv);
1374 EXPECT_TRUE(sock->IsConnected());
1376 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1377 static const int kRequestTextSize =
1378 static_cast<int>(arraysize(request_text) - 1);
1379 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1380 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1382 rv = callback.GetResult(
1383 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1384 EXPECT_EQ(kRequestTextSize, rv);
1386 // Simulate an unclean/forcible shutdown.
1387 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
1389 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1391 // Note: This test will hang if this bug has regressed. Simply checking that
1392 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1393 // result when using a dedicated task runner for NSS.
1394 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1395 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1398 // Tests that the SSLClientSocket properly handles when the underlying transport
1399 // asynchronously returns an error code while writing data - such as if an
1400 // intermediary terminates the socket connection uncleanly.
1401 // This is a regression test for http://crbug.com/249848
1402 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
1403 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1404 SpawnedTestServer::kLocalhost,
1405 base::FilePath());
1406 ASSERT_TRUE(test_server.Start());
1408 AddressList addr;
1409 ASSERT_TRUE(test_server.GetAddressList(&addr));
1411 TestCompletionCallback callback;
1412 scoped_ptr<StreamSocket> real_transport(
1413 new TCPClientSocket(addr, NULL, NetLog::Source()));
1414 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1415 // is retained in order to configure additional errors.
1416 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1417 new SynchronousErrorStreamSocket(real_transport.Pass()));
1418 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1419 scoped_ptr<FakeBlockingStreamSocket> transport(
1420 new FakeBlockingStreamSocket(error_socket.Pass()));
1421 FakeBlockingStreamSocket* raw_transport = transport.get();
1422 int rv = callback.GetResult(transport->Connect(callback.callback()));
1423 EXPECT_EQ(OK, rv);
1425 // Disable TLS False Start to avoid handshake non-determinism.
1426 SSLConfig ssl_config;
1427 ssl_config.false_start_enabled = false;
1429 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1430 transport.Pass(), test_server.host_port_pair(), ssl_config));
1432 rv = callback.GetResult(sock->Connect(callback.callback()));
1433 EXPECT_EQ(OK, rv);
1434 EXPECT_TRUE(sock->IsConnected());
1436 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1437 static const int kRequestTextSize =
1438 static_cast<int>(arraysize(request_text) - 1);
1439 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1440 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1442 // Simulate an unclean/forcible shutdown on the underlying socket.
1443 // However, simulate this error asynchronously.
1444 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1445 raw_transport->BlockWrite();
1447 // This write should complete synchronously, because the TLS ciphertext
1448 // can be created and placed into the outgoing buffers independent of the
1449 // underlying transport.
1450 rv = callback.GetResult(
1451 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1452 EXPECT_EQ(kRequestTextSize, rv);
1454 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1456 rv = sock->Read(buf.get(), 4096, callback.callback());
1457 EXPECT_EQ(ERR_IO_PENDING, rv);
1459 // Now unblock the outgoing request, having it fail with the connection
1460 // being reset.
1461 raw_transport->UnblockWrite();
1463 // Note: This will cause an inifite loop if this bug has regressed. Simply
1464 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1465 // is a legitimate result when using a dedicated task runner for NSS.
1466 rv = callback.GetResult(rv);
1467 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1470 // If there is a Write failure at the transport with no follow-up Read, although
1471 // the write error will not be returned to the client until a future Read or
1472 // Write operation, SSLClientSocket should not spin attempting to re-write on
1473 // the socket. This is a regression test for part of https://crbug.com/381160.
1474 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) {
1475 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1476 SpawnedTestServer::kLocalhost,
1477 base::FilePath());
1478 ASSERT_TRUE(test_server.Start());
1480 AddressList addr;
1481 ASSERT_TRUE(test_server.GetAddressList(&addr));
1483 TestCompletionCallback callback;
1484 scoped_ptr<StreamSocket> real_transport(
1485 new TCPClientSocket(addr, NULL, NetLog::Source()));
1486 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1487 // is retained in order to query them.
1488 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1489 new SynchronousErrorStreamSocket(real_transport.Pass()));
1490 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1491 scoped_ptr<CountingStreamSocket> counting_socket(
1492 new CountingStreamSocket(error_socket.Pass()));
1493 CountingStreamSocket* raw_counting_socket = counting_socket.get();
1494 int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
1495 ASSERT_EQ(OK, rv);
1497 // Disable TLS False Start to avoid handshake non-determinism.
1498 SSLConfig ssl_config;
1499 ssl_config.false_start_enabled = false;
1501 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1502 counting_socket.Pass(), test_server.host_port_pair(), ssl_config));
1504 rv = callback.GetResult(sock->Connect(callback.callback()));
1505 ASSERT_EQ(OK, rv);
1506 ASSERT_TRUE(sock->IsConnected());
1508 // Simulate an unclean/forcible shutdown on the underlying socket.
1509 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1511 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1512 static const int kRequestTextSize =
1513 static_cast<int>(arraysize(request_text) - 1);
1514 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1515 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1517 // This write should complete synchronously, because the TLS ciphertext
1518 // can be created and placed into the outgoing buffers independent of the
1519 // underlying transport.
1520 rv = callback.GetResult(
1521 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1522 ASSERT_EQ(kRequestTextSize, rv);
1524 // Let the event loop spin for a little bit of time. Even on platforms where
1525 // pumping the state machine involve thread hops, there should be no further
1526 // writes on the transport socket.
1528 // TODO(davidben): Avoid the arbitrary timeout?
1529 int old_write_count = raw_counting_socket->write_count();
1530 base::RunLoop loop;
1531 base::MessageLoop::current()->PostDelayedTask(
1532 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1533 loop.Run();
1534 EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
1537 // Test the full duplex mode, with Read and Write pending at the same time.
1538 // This test also serves as a regression test for http://crbug.com/29815.
1539 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1540 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1541 SpawnedTestServer::kLocalhost,
1542 base::FilePath());
1543 ASSERT_TRUE(test_server.Start());
1545 AddressList addr;
1546 ASSERT_TRUE(test_server.GetAddressList(&addr));
1548 TestCompletionCallback callback; // Used for everything except Write.
1550 scoped_ptr<StreamSocket> transport(
1551 new TCPClientSocket(addr, NULL, NetLog::Source()));
1552 int rv = transport->Connect(callback.callback());
1553 if (rv == ERR_IO_PENDING)
1554 rv = callback.WaitForResult();
1555 EXPECT_EQ(OK, rv);
1557 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1558 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1560 rv = sock->Connect(callback.callback());
1561 if (rv == ERR_IO_PENDING)
1562 rv = callback.WaitForResult();
1563 EXPECT_EQ(OK, rv);
1564 EXPECT_TRUE(sock->IsConnected());
1566 // Issue a "hanging" Read first.
1567 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1568 rv = sock->Read(buf.get(), 4096, callback.callback());
1569 // We haven't written the request, so there should be no response yet.
1570 ASSERT_EQ(ERR_IO_PENDING, rv);
1572 // Write the request.
1573 // The request is padded with a User-Agent header to a size that causes the
1574 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1575 // This tests the fix for http://crbug.com/29815.
1576 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1577 for (int i = 0; i < 3770; ++i)
1578 request_text.push_back('*');
1579 request_text.append("\r\n\r\n");
1580 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1582 TestCompletionCallback callback2; // Used for Write only.
1583 rv = sock->Write(
1584 request_buffer.get(), request_text.size(), callback2.callback());
1585 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1587 if (rv == ERR_IO_PENDING)
1588 rv = callback2.WaitForResult();
1589 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1591 // Now get the Read result.
1592 rv = callback.WaitForResult();
1593 EXPECT_GT(rv, 0);
1596 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1597 // mode when the underlying transport is blocked on sending data. When the
1598 // underlying transport completes due to an error, it should invoke both the
1599 // Read() and Write() callbacks. If the socket is deleted by the Read()
1600 // callback, the Write() callback should not be invoked.
1601 // Regression test for http://crbug.com/232633
1602 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1603 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1604 SpawnedTestServer::kLocalhost,
1605 base::FilePath());
1606 ASSERT_TRUE(test_server.Start());
1608 AddressList addr;
1609 ASSERT_TRUE(test_server.GetAddressList(&addr));
1611 TestCompletionCallback callback;
1612 scoped_ptr<StreamSocket> real_transport(
1613 new TCPClientSocket(addr, NULL, NetLog::Source()));
1614 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1615 // is retained in order to configure additional errors.
1616 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1617 new SynchronousErrorStreamSocket(real_transport.Pass()));
1618 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1619 scoped_ptr<FakeBlockingStreamSocket> transport(
1620 new FakeBlockingStreamSocket(error_socket.Pass()));
1621 FakeBlockingStreamSocket* raw_transport = transport.get();
1623 int rv = callback.GetResult(transport->Connect(callback.callback()));
1624 EXPECT_EQ(OK, rv);
1626 // Disable TLS False Start to avoid handshake non-determinism.
1627 SSLConfig ssl_config;
1628 ssl_config.false_start_enabled = false;
1630 scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
1631 transport.Pass(), test_server.host_port_pair(), ssl_config);
1633 rv = callback.GetResult(sock->Connect(callback.callback()));
1634 EXPECT_EQ(OK, rv);
1635 EXPECT_TRUE(sock->IsConnected());
1637 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1638 request_text.append(20 * 1024, '*');
1639 request_text.append("\r\n\r\n");
1640 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1641 new StringIOBuffer(request_text), request_text.size()));
1643 // Simulate errors being returned from the underlying Read() and Write() ...
1644 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1645 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1646 // ... but have those errors returned asynchronously. Because the Write() will
1647 // return first, this will trigger the error.
1648 raw_transport->BlockReadResult();
1649 raw_transport->BlockWrite();
1651 // Enqueue a Read() before calling Write(), which should "hang" due to
1652 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1653 SSLClientSocket* raw_sock = sock.get();
1654 DeleteSocketCallback read_callback(sock.release());
1655 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1656 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1658 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1659 ASSERT_EQ(ERR_IO_PENDING, rv);
1660 ASSERT_FALSE(read_callback.have_result());
1662 #if !defined(USE_OPENSSL)
1663 // NSS follows a pattern where a call to PR_Write will only consume as
1664 // much data as it can encode into application data records before the
1665 // internal memio buffer is full, which should only fill if writing a large
1666 // amount of data and the underlying transport is blocked. Once this happens,
1667 // NSS will return (total size of all application data records it wrote) - 1,
1668 // with the caller expected to resume with the remaining unsent data.
1670 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1671 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1672 // get the socket in the state needed for the test below.
1674 // This is not needed for OpenSSL, because for OpenSSL,
1675 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1676 // SSLClientSocketOpenSSL::Write() will not return until all of
1677 // |request_buffer| has been written to the underlying BIO (although not
1678 // necessarily the underlying transport).
1679 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1680 request_buffer->BytesRemaining(),
1681 callback.callback()));
1682 ASSERT_LT(0, rv);
1683 request_buffer->DidConsume(rv);
1685 // Guard to ensure that |request_buffer| was larger than all of the internal
1686 // buffers (transport, memio, NSS) along the way - otherwise the next call
1687 // to Write() will crash with an invalid buffer.
1688 ASSERT_LT(0, request_buffer->BytesRemaining());
1689 #endif
1691 // Attempt to write the remaining data. NSS will not be able to consume the
1692 // application data because the internal buffers are full, while OpenSSL will
1693 // return that its blocked because the underlying transport is blocked.
1694 rv = raw_sock->Write(request_buffer.get(),
1695 request_buffer->BytesRemaining(),
1696 callback.callback());
1697 ASSERT_EQ(ERR_IO_PENDING, rv);
1698 ASSERT_FALSE(callback.have_result());
1700 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1701 // call the Read() callback, deleting the socket and thus aborting calling
1702 // the Write() callback.
1703 raw_transport->UnblockWrite();
1705 rv = read_callback.WaitForResult();
1706 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1708 // The Write callback should not have been called.
1709 EXPECT_FALSE(callback.have_result());
1712 // Tests that the SSLClientSocket does not crash if data is received on the
1713 // transport socket after a failing write. This can occur if we have a Write
1714 // error in a SPDY socket.
1715 // Regression test for http://crbug.com/335557
1716 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1717 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1718 SpawnedTestServer::kLocalhost,
1719 base::FilePath());
1720 ASSERT_TRUE(test_server.Start());
1722 AddressList addr;
1723 ASSERT_TRUE(test_server.GetAddressList(&addr));
1725 TestCompletionCallback callback;
1726 scoped_ptr<StreamSocket> real_transport(
1727 new TCPClientSocket(addr, NULL, NetLog::Source()));
1728 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1729 // is retained in order to configure additional errors.
1730 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1731 new SynchronousErrorStreamSocket(real_transport.Pass()));
1732 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1733 scoped_ptr<FakeBlockingStreamSocket> transport(
1734 new FakeBlockingStreamSocket(error_socket.Pass()));
1735 FakeBlockingStreamSocket* raw_transport = transport.get();
1737 int rv = callback.GetResult(transport->Connect(callback.callback()));
1738 EXPECT_EQ(OK, rv);
1740 // Disable TLS False Start to avoid handshake non-determinism.
1741 SSLConfig ssl_config;
1742 ssl_config.false_start_enabled = false;
1744 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1745 transport.Pass(), test_server.host_port_pair(), ssl_config));
1747 rv = callback.GetResult(sock->Connect(callback.callback()));
1748 EXPECT_EQ(OK, rv);
1749 EXPECT_TRUE(sock->IsConnected());
1751 // Send a request so there is something to read from the socket.
1752 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1753 static const int kRequestTextSize =
1754 static_cast<int>(arraysize(request_text) - 1);
1755 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1756 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1758 rv = callback.GetResult(
1759 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1760 EXPECT_EQ(kRequestTextSize, rv);
1762 // Start a hanging read.
1763 TestCompletionCallback read_callback;
1764 raw_transport->BlockReadResult();
1765 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1766 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1767 EXPECT_EQ(ERR_IO_PENDING, rv);
1769 // Perform another write, but have it fail. Write a request larger than the
1770 // internal socket buffers so that the request hits the underlying transport
1771 // socket and detects the error.
1772 std::string long_request_text =
1773 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1774 long_request_text.append(20 * 1024, '*');
1775 long_request_text.append("\r\n\r\n");
1776 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1777 new StringIOBuffer(long_request_text), long_request_text.size()));
1779 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1781 // Write as much data as possible until hitting an error. This is necessary
1782 // for NSS. PR_Write will only consume as much data as it can encode into
1783 // application data records before the internal memio buffer is full, which
1784 // should only fill if writing a large amount of data and the underlying
1785 // transport is blocked. Once this happens, NSS will return (total size of all
1786 // application data records it wrote) - 1, with the caller expected to resume
1787 // with the remaining unsent data.
1788 do {
1789 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1790 long_request_buffer->BytesRemaining(),
1791 callback.callback()));
1792 if (rv > 0) {
1793 long_request_buffer->DidConsume(rv);
1794 // Abort if the entire buffer is ever consumed.
1795 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1797 } while (rv > 0);
1799 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1801 // Release the read.
1802 raw_transport->UnblockReadResult();
1803 rv = read_callback.WaitForResult();
1805 #if defined(USE_OPENSSL)
1806 // Should still read bytes despite the write error.
1807 EXPECT_LT(0, rv);
1808 #else
1809 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1810 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1811 // the write error stops future reads.
1812 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1813 #endif
1816 // Tests that SSLClientSocket fails the handshake if the underlying
1817 // transport is cleanly closed.
1818 TEST_F(SSLClientSocketTest, Connect_WithZeroReturn) {
1819 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1820 SpawnedTestServer::kLocalhost,
1821 base::FilePath());
1822 ASSERT_TRUE(test_server.Start());
1824 AddressList addr;
1825 ASSERT_TRUE(test_server.GetAddressList(&addr));
1827 TestCompletionCallback callback;
1828 scoped_ptr<StreamSocket> real_transport(
1829 new TCPClientSocket(addr, NULL, NetLog::Source()));
1830 scoped_ptr<SynchronousErrorStreamSocket> transport(
1831 new SynchronousErrorStreamSocket(real_transport.Pass()));
1832 int rv = callback.GetResult(transport->Connect(callback.callback()));
1833 EXPECT_EQ(OK, rv);
1835 SynchronousErrorStreamSocket* raw_transport = transport.get();
1836 scoped_ptr<SSLClientSocket> sock(
1837 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1838 test_server.host_port_pair(),
1839 kDefaultSSLConfig));
1841 raw_transport->SetNextReadError(0);
1843 rv = callback.GetResult(sock->Connect(callback.callback()));
1844 EXPECT_EQ(ERR_CONNECTION_CLOSED, rv);
1845 EXPECT_FALSE(sock->IsConnected());
1848 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1849 // underlying socket is cleanly closed.
1850 // This is a regression test for https://crbug.com/422246
1851 TEST_F(SSLClientSocketTest, Read_WithZeroReturn) {
1852 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1853 SpawnedTestServer::kLocalhost,
1854 base::FilePath());
1855 ASSERT_TRUE(test_server.Start());
1857 AddressList addr;
1858 ASSERT_TRUE(test_server.GetAddressList(&addr));
1860 TestCompletionCallback callback;
1861 scoped_ptr<StreamSocket> real_transport(
1862 new TCPClientSocket(addr, NULL, NetLog::Source()));
1863 scoped_ptr<SynchronousErrorStreamSocket> transport(
1864 new SynchronousErrorStreamSocket(real_transport.Pass()));
1865 int rv = callback.GetResult(transport->Connect(callback.callback()));
1866 EXPECT_EQ(OK, rv);
1868 // Disable TLS False Start to ensure the handshake has completed.
1869 SSLConfig ssl_config;
1870 ssl_config.false_start_enabled = false;
1872 SynchronousErrorStreamSocket* raw_transport = transport.get();
1873 scoped_ptr<SSLClientSocket> sock(
1874 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1875 test_server.host_port_pair(),
1876 ssl_config));
1878 rv = callback.GetResult(sock->Connect(callback.callback()));
1879 EXPECT_EQ(OK, rv);
1880 EXPECT_TRUE(sock->IsConnected());
1882 raw_transport->SetNextReadError(0);
1883 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1884 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1885 EXPECT_EQ(0, rv);
1888 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1889 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1890 SpawnedTestServer::kLocalhost,
1891 base::FilePath());
1892 ASSERT_TRUE(test_server.Start());
1894 AddressList addr;
1895 ASSERT_TRUE(test_server.GetAddressList(&addr));
1897 TestCompletionCallback callback;
1898 scoped_ptr<StreamSocket> transport(
1899 new TCPClientSocket(addr, NULL, NetLog::Source()));
1900 int rv = transport->Connect(callback.callback());
1901 if (rv == ERR_IO_PENDING)
1902 rv = callback.WaitForResult();
1903 EXPECT_EQ(OK, rv);
1905 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1906 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1908 rv = sock->Connect(callback.callback());
1909 if (rv == ERR_IO_PENDING)
1910 rv = callback.WaitForResult();
1911 EXPECT_EQ(OK, rv);
1913 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1914 scoped_refptr<IOBuffer> request_buffer(
1915 new IOBuffer(arraysize(request_text) - 1));
1916 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1918 rv = sock->Write(
1919 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1920 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1922 if (rv == ERR_IO_PENDING)
1923 rv = callback.WaitForResult();
1924 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1926 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1927 for (;;) {
1928 rv = sock->Read(buf.get(), 1, callback.callback());
1929 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1931 if (rv == ERR_IO_PENDING)
1932 rv = callback.WaitForResult();
1934 EXPECT_GE(rv, 0);
1935 if (rv <= 0)
1936 break;
1940 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1941 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1942 SpawnedTestServer::kLocalhost,
1943 base::FilePath());
1944 ASSERT_TRUE(test_server.Start());
1946 AddressList addr;
1947 ASSERT_TRUE(test_server.GetAddressList(&addr));
1949 TestCompletionCallback callback;
1951 scoped_ptr<StreamSocket> real_transport(
1952 new TCPClientSocket(addr, NULL, NetLog::Source()));
1953 scoped_ptr<ReadBufferingStreamSocket> transport(
1954 new ReadBufferingStreamSocket(real_transport.Pass()));
1955 ReadBufferingStreamSocket* raw_transport = transport.get();
1956 int rv = callback.GetResult(transport->Connect(callback.callback()));
1957 ASSERT_EQ(OK, rv);
1959 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1960 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1962 rv = callback.GetResult(sock->Connect(callback.callback()));
1963 ASSERT_EQ(OK, rv);
1964 ASSERT_TRUE(sock->IsConnected());
1966 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1967 scoped_refptr<IOBuffer> request_buffer(
1968 new IOBuffer(arraysize(request_text) - 1));
1969 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1971 rv = callback.GetResult(sock->Write(
1972 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
1973 ASSERT_GT(rv, 0);
1974 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1976 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
1977 // data (the max SSL record size) at a time. Ensure that at least 15K worth
1978 // of SSL data is buffered first. The 15K of buffered data is made up of
1979 // many smaller SSL records (the TestServer writes along 1350 byte
1980 // plaintext boundaries), although there may also be a few records that are
1981 // smaller or larger, due to timing and SSL False Start.
1982 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
1983 // the SSLClientSocket implementation, and larger than the minimum amount
1984 // of ciphertext necessary to contain the 8K of plaintext requested below.
1985 raw_transport->SetBufferSize(15000);
1987 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
1988 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
1989 ASSERT_EQ(rv, 8192);
1992 TEST_F(SSLClientSocketTest, Read_Interrupted) {
1993 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1994 SpawnedTestServer::kLocalhost,
1995 base::FilePath());
1996 ASSERT_TRUE(test_server.Start());
1998 AddressList addr;
1999 ASSERT_TRUE(test_server.GetAddressList(&addr));
2001 TestCompletionCallback callback;
2002 scoped_ptr<StreamSocket> transport(
2003 new TCPClientSocket(addr, NULL, NetLog::Source()));
2004 int rv = transport->Connect(callback.callback());
2005 if (rv == ERR_IO_PENDING)
2006 rv = callback.WaitForResult();
2007 EXPECT_EQ(OK, rv);
2009 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2010 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2012 rv = sock->Connect(callback.callback());
2013 if (rv == ERR_IO_PENDING)
2014 rv = callback.WaitForResult();
2015 EXPECT_EQ(OK, rv);
2017 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2018 scoped_refptr<IOBuffer> request_buffer(
2019 new IOBuffer(arraysize(request_text) - 1));
2020 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2022 rv = sock->Write(
2023 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2024 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2026 if (rv == ERR_IO_PENDING)
2027 rv = callback.WaitForResult();
2028 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2030 // Do a partial read and then exit. This test should not crash!
2031 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
2032 rv = sock->Read(buf.get(), 512, callback.callback());
2033 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
2035 if (rv == ERR_IO_PENDING)
2036 rv = callback.WaitForResult();
2038 EXPECT_GT(rv, 0);
2041 TEST_F(SSLClientSocketTest, Read_FullLogging) {
2042 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2043 SpawnedTestServer::kLocalhost,
2044 base::FilePath());
2045 ASSERT_TRUE(test_server.Start());
2047 AddressList addr;
2048 ASSERT_TRUE(test_server.GetAddressList(&addr));
2050 TestCompletionCallback callback;
2051 CapturingNetLog log;
2052 log.SetLogLevel(NetLog::LOG_ALL);
2053 scoped_ptr<StreamSocket> transport(
2054 new TCPClientSocket(addr, &log, NetLog::Source()));
2055 int rv = transport->Connect(callback.callback());
2056 if (rv == ERR_IO_PENDING)
2057 rv = callback.WaitForResult();
2058 EXPECT_EQ(OK, rv);
2060 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2061 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2063 rv = sock->Connect(callback.callback());
2064 if (rv == ERR_IO_PENDING)
2065 rv = callback.WaitForResult();
2066 EXPECT_EQ(OK, rv);
2067 EXPECT_TRUE(sock->IsConnected());
2069 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2070 scoped_refptr<IOBuffer> request_buffer(
2071 new IOBuffer(arraysize(request_text) - 1));
2072 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2074 rv = sock->Write(
2075 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2076 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2078 if (rv == ERR_IO_PENDING)
2079 rv = callback.WaitForResult();
2080 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2082 CapturingNetLog::CapturedEntryList entries;
2083 log.GetEntries(&entries);
2084 size_t last_index = ExpectLogContainsSomewhereAfter(
2085 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
2087 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
2088 for (;;) {
2089 rv = sock->Read(buf.get(), 4096, callback.callback());
2090 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2092 if (rv == ERR_IO_PENDING)
2093 rv = callback.WaitForResult();
2095 EXPECT_GE(rv, 0);
2096 if (rv <= 0)
2097 break;
2099 log.GetEntries(&entries);
2100 last_index =
2101 ExpectLogContainsSomewhereAfter(entries,
2102 last_index + 1,
2103 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
2104 NetLog::PHASE_NONE);
2108 // Regression test for http://crbug.com/42538
2109 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
2110 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2111 SpawnedTestServer::kLocalhost,
2112 base::FilePath());
2113 ASSERT_TRUE(test_server.Start());
2115 AddressList addr;
2116 TestCompletionCallback callback;
2118 static const unsigned char application_data[] = {
2119 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2120 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2121 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2122 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2123 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2124 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2125 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2126 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2127 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2128 0x0a};
2130 // All reads and writes complete synchronously (async=false).
2131 MockRead data_reads[] = {
2132 MockRead(SYNCHRONOUS,
2133 reinterpret_cast<const char*>(application_data),
2134 arraysize(application_data)),
2135 MockRead(SYNCHRONOUS, OK), };
2137 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
2139 scoped_ptr<StreamSocket> transport(
2140 new MockTCPClientSocket(addr, NULL, &data));
2141 int rv = transport->Connect(callback.callback());
2142 if (rv == ERR_IO_PENDING)
2143 rv = callback.WaitForResult();
2144 EXPECT_EQ(OK, rv);
2146 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2147 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2149 rv = sock->Connect(callback.callback());
2150 if (rv == ERR_IO_PENDING)
2151 rv = callback.WaitForResult();
2152 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
2155 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
2156 // Rather than exhaustively disabling every RC4 ciphersuite defined at
2157 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
2158 // only disabling those cipher suites that the test server actually
2159 // implements.
2160 const uint16 kCiphersToDisable[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
2163 SpawnedTestServer::SSLOptions ssl_options;
2164 // Enable only RC4 on the test server.
2165 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
2166 SpawnedTestServer test_server(
2167 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2168 ASSERT_TRUE(test_server.Start());
2170 AddressList addr;
2171 ASSERT_TRUE(test_server.GetAddressList(&addr));
2173 TestCompletionCallback callback;
2174 CapturingNetLog log;
2175 scoped_ptr<StreamSocket> transport(
2176 new TCPClientSocket(addr, &log, NetLog::Source()));
2177 int rv = transport->Connect(callback.callback());
2178 if (rv == ERR_IO_PENDING)
2179 rv = callback.WaitForResult();
2180 EXPECT_EQ(OK, rv);
2182 SSLConfig ssl_config;
2183 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
2184 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
2186 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2187 transport.Pass(), test_server.host_port_pair(), ssl_config));
2189 EXPECT_FALSE(sock->IsConnected());
2191 rv = sock->Connect(callback.callback());
2192 CapturingNetLog::CapturedEntryList entries;
2193 log.GetEntries(&entries);
2194 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2196 // NSS has special handling that maps a handshake_failure alert received
2197 // immediately after a client_hello to be a mismatched cipher suite error,
2198 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
2199 // Secure Transport (OS X), the handshake_failure is bubbled up without any
2200 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
2201 // indicates that no cipher suite was negotiated with the test server.
2202 if (rv == ERR_IO_PENDING)
2203 rv = callback.WaitForResult();
2204 EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH ||
2205 rv == ERR_SSL_PROTOCOL_ERROR);
2206 // The exact ordering differs between SSLClientSocketNSS (which issues an
2207 // extra read) and SSLClientSocketMac (which does not). Just make sure the
2208 // error appears somewhere in the log.
2209 log.GetEntries(&entries);
2210 ExpectLogContainsSomewhere(
2211 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
2213 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2214 // the socket when it encounters an error, whereas other implementations
2215 // leave it connected.
2216 // Because this an error that the test server is mutually aware of, as opposed
2217 // to being an error such as a certificate name mismatch, which is
2218 // client-only, the exact index of the SSL connect end depends on how
2219 // quickly the test server closes the underlying socket. If the test server
2220 // closes before the IO message loop pumps messages, there may be a 0-byte
2221 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2222 // result, the SSL connect end event will be the second-to-last entry,
2223 // rather than the last entry.
2224 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) ||
2225 LogContainsSSLConnectEndEvent(entries, -2));
2228 // When creating an SSLClientSocket, it is allowed to pass in a
2229 // ClientSocketHandle that is not obtained from a client socket pool.
2230 // Here we verify that such a simple ClientSocketHandle, not associated with any
2231 // client socket pool, can be destroyed safely.
2232 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
2233 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2234 SpawnedTestServer::kLocalhost,
2235 base::FilePath());
2236 ASSERT_TRUE(test_server.Start());
2238 AddressList addr;
2239 ASSERT_TRUE(test_server.GetAddressList(&addr));
2241 TestCompletionCallback callback;
2242 scoped_ptr<StreamSocket> transport(
2243 new TCPClientSocket(addr, NULL, NetLog::Source()));
2244 int rv = transport->Connect(callback.callback());
2245 if (rv == ERR_IO_PENDING)
2246 rv = callback.WaitForResult();
2247 EXPECT_EQ(OK, rv);
2249 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
2250 socket_handle->SetSocket(transport.Pass());
2252 scoped_ptr<SSLClientSocket> sock(
2253 socket_factory_->CreateSSLClientSocket(socket_handle.Pass(),
2254 test_server.host_port_pair(),
2255 kDefaultSSLConfig,
2256 context_));
2258 EXPECT_FALSE(sock->IsConnected());
2259 rv = sock->Connect(callback.callback());
2260 if (rv == ERR_IO_PENDING)
2261 rv = callback.WaitForResult();
2262 EXPECT_EQ(OK, rv);
2265 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2266 // code and different keying label results in different keying material.
2267 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
2268 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2269 SpawnedTestServer::kLocalhost,
2270 base::FilePath());
2271 ASSERT_TRUE(test_server.Start());
2273 AddressList addr;
2274 ASSERT_TRUE(test_server.GetAddressList(&addr));
2276 TestCompletionCallback callback;
2278 scoped_ptr<StreamSocket> transport(
2279 new TCPClientSocket(addr, NULL, NetLog::Source()));
2280 int rv = transport->Connect(callback.callback());
2281 if (rv == ERR_IO_PENDING)
2282 rv = callback.WaitForResult();
2283 EXPECT_EQ(OK, rv);
2285 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2286 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2288 rv = sock->Connect(callback.callback());
2289 if (rv == ERR_IO_PENDING)
2290 rv = callback.WaitForResult();
2291 EXPECT_EQ(OK, rv);
2292 EXPECT_TRUE(sock->IsConnected());
2294 const int kKeyingMaterialSize = 32;
2295 const char* kKeyingLabel1 = "client-socket-test-1";
2296 const char* kKeyingContext = "";
2297 unsigned char client_out1[kKeyingMaterialSize];
2298 memset(client_out1, 0, sizeof(client_out1));
2299 rv = sock->ExportKeyingMaterial(
2300 kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1));
2301 EXPECT_EQ(rv, OK);
2303 const char* kKeyingLabel2 = "client-socket-test-2";
2304 unsigned char client_out2[kKeyingMaterialSize];
2305 memset(client_out2, 0, sizeof(client_out2));
2306 rv = sock->ExportKeyingMaterial(
2307 kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2));
2308 EXPECT_EQ(rv, OK);
2309 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2312 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2313 // explicit NSS initialization.
2314 TEST(SSLClientSocket, ClearSessionCache) {
2315 SSLClientSocket::ClearSessionCache();
2318 // Test that the server certificates are properly retrieved from the underlying
2319 // SSL stack.
2320 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
2321 // The connection does not have to be successful.
2322 cert_verifier_->set_default_result(ERR_CERT_INVALID);
2324 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2325 // This makes the server present redundant-server-chain.pem, which contains
2326 // intermediate certificates.
2327 SpawnedTestServer::SSLOptions ssl_options(
2328 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2329 SpawnedTestServer test_server(
2330 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2331 ASSERT_TRUE(test_server.Start());
2333 AddressList addr;
2334 ASSERT_TRUE(test_server.GetAddressList(&addr));
2336 TestCompletionCallback callback;
2337 scoped_ptr<StreamSocket> transport(
2338 new TCPClientSocket(addr, NULL, NetLog::Source()));
2339 int rv = transport->Connect(callback.callback());
2340 rv = callback.GetResult(rv);
2341 EXPECT_EQ(OK, rv);
2343 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2344 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2345 EXPECT_FALSE(sock->IsConnected());
2346 rv = sock->Connect(callback.callback());
2347 rv = callback.GetResult(rv);
2349 EXPECT_EQ(ERR_CERT_INVALID, rv);
2350 EXPECT_TRUE(sock->IsConnected());
2352 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2353 // certs from redundant-server-chain.pem.
2354 CertificateList server_certs =
2355 CreateCertificateListFromFile(GetTestCertsDirectory(),
2356 "redundant-server-chain.pem",
2357 X509Certificate::FORMAT_AUTO);
2359 // Get the server certificate as received client side.
2360 scoped_refptr<X509Certificate> server_certificate =
2361 sock->GetUnverifiedServerCertificateChain();
2363 // Get the intermediates as received client side.
2364 const X509Certificate::OSCertHandles& server_intermediates =
2365 server_certificate->GetIntermediateCertificates();
2367 // Check that the unverified server certificate chain is properly retrieved
2368 // from the underlying ssl stack.
2369 ASSERT_EQ(4U, server_certs.size());
2371 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2372 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
2374 ASSERT_EQ(3U, server_intermediates.size());
2376 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
2377 server_certs[1]->os_cert_handle()));
2378 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
2379 server_certs[2]->os_cert_handle()));
2380 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
2381 server_certs[3]->os_cert_handle()));
2383 sock->Disconnect();
2384 EXPECT_FALSE(sock->IsConnected());
2387 // This tests that SSLInfo contains a properly re-constructed certificate
2388 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2389 // verified, not the chain as served by the server. (They may be different.)
2391 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2392 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2393 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2394 // a self-signed root. Such a situation can occur when a new root (C2) is
2395 // cross-certified by an old root (D) and has two different versions of its
2396 // floating around. Servers may supply C2 as an intermediate, but the
2397 // SSLClientSocket should return the chain that was verified, from
2398 // verify_result, instead.
2399 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
2400 // By default, cause the CertVerifier to treat all certificates as
2401 // expired.
2402 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
2404 // We will expect SSLInfo to ultimately contain this chain.
2405 CertificateList certs =
2406 CreateCertificateListFromFile(GetTestCertsDirectory(),
2407 "redundant-validated-chain.pem",
2408 X509Certificate::FORMAT_AUTO);
2409 ASSERT_EQ(3U, certs.size());
2411 X509Certificate::OSCertHandles temp_intermediates;
2412 temp_intermediates.push_back(certs[1]->os_cert_handle());
2413 temp_intermediates.push_back(certs[2]->os_cert_handle());
2415 CertVerifyResult verify_result;
2416 verify_result.verified_cert = X509Certificate::CreateFromHandle(
2417 certs[0]->os_cert_handle(), temp_intermediates);
2419 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2420 // rather than A->B->C.
2421 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
2423 // Load and install the root for the validated chain.
2424 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
2425 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2426 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
2427 ScopedTestRoot scoped_root(root_cert.get());
2429 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2430 SpawnedTestServer::SSLOptions ssl_options(
2431 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2432 SpawnedTestServer test_server(
2433 SpawnedTestServer::TYPE_HTTPS,
2434 ssl_options,
2435 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2436 ASSERT_TRUE(test_server.Start());
2438 AddressList addr;
2439 ASSERT_TRUE(test_server.GetAddressList(&addr));
2441 TestCompletionCallback callback;
2442 CapturingNetLog log;
2443 scoped_ptr<StreamSocket> transport(
2444 new TCPClientSocket(addr, &log, NetLog::Source()));
2445 int rv = transport->Connect(callback.callback());
2446 if (rv == ERR_IO_PENDING)
2447 rv = callback.WaitForResult();
2448 EXPECT_EQ(OK, rv);
2450 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2451 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2452 EXPECT_FALSE(sock->IsConnected());
2453 rv = sock->Connect(callback.callback());
2455 CapturingNetLog::CapturedEntryList entries;
2456 log.GetEntries(&entries);
2457 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2458 if (rv == ERR_IO_PENDING)
2459 rv = callback.WaitForResult();
2461 EXPECT_EQ(OK, rv);
2462 EXPECT_TRUE(sock->IsConnected());
2463 log.GetEntries(&entries);
2464 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2466 SSLInfo ssl_info;
2467 sock->GetSSLInfo(&ssl_info);
2469 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2470 // -> C2.
2471 const X509Certificate::OSCertHandles& intermediates =
2472 ssl_info.cert->GetIntermediateCertificates();
2473 ASSERT_EQ(2U, intermediates.size());
2474 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
2475 certs[0]->os_cert_handle()));
2476 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
2477 certs[1]->os_cert_handle()));
2478 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
2479 certs[2]->os_cert_handle()));
2481 sock->Disconnect();
2482 EXPECT_FALSE(sock->IsConnected());
2485 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
2486 SpawnedTestServer::SSLOptions ssl_options;
2487 ssl_options.request_client_certificate = true;
2488 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2489 ASSERT_TRUE(request_info.get());
2490 EXPECT_EQ(0u, request_info->cert_authorities.size());
2493 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
2494 const base::FilePath::CharType kThawteFile[] =
2495 FILE_PATH_LITERAL("thawte.single.pem");
2496 const unsigned char kThawteDN[] = {
2497 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2498 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2499 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2500 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2501 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2502 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2503 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2504 const size_t kThawteLen = sizeof(kThawteDN);
2506 const base::FilePath::CharType kDiginotarFile[] =
2507 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2508 const unsigned char kDiginotarDN[] = {
2509 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2510 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2511 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2512 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2513 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2514 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2515 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2516 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2517 0x6c};
2518 const size_t kDiginotarLen = sizeof(kDiginotarDN);
2520 SpawnedTestServer::SSLOptions ssl_options;
2521 ssl_options.request_client_certificate = true;
2522 ssl_options.client_authorities.push_back(
2523 GetTestClientCertsDirectory().Append(kThawteFile));
2524 ssl_options.client_authorities.push_back(
2525 GetTestClientCertsDirectory().Append(kDiginotarFile));
2526 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2527 ASSERT_TRUE(request_info.get());
2528 ASSERT_EQ(2u, request_info->cert_authorities.size());
2529 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
2530 request_info->cert_authorities[0]);
2531 EXPECT_EQ(
2532 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
2533 request_info->cert_authorities[1]);
2536 // cert_key_types is currently only populated on OpenSSL.
2537 #if defined(USE_OPENSSL)
2538 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
2539 SpawnedTestServer::SSLOptions ssl_options;
2540 ssl_options.request_client_certificate = true;
2541 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN);
2542 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2543 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2544 ASSERT_TRUE(request_info.get());
2545 ASSERT_EQ(2u, request_info->cert_key_types.size());
2546 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]);
2547 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]);
2549 #endif // defined(USE_OPENSSL)
2551 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
2552 SpawnedTestServer::SSLOptions ssl_options;
2553 ssl_options.signed_cert_timestamps_tls_ext = "test";
2555 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2556 ssl_options,
2557 base::FilePath());
2558 ASSERT_TRUE(test_server.Start());
2560 AddressList addr;
2561 ASSERT_TRUE(test_server.GetAddressList(&addr));
2563 TestCompletionCallback callback;
2564 scoped_ptr<StreamSocket> transport(
2565 new TCPClientSocket(addr, &log_, NetLog::Source()));
2566 int rv = callback.GetResult(transport->Connect(callback.callback()));
2567 EXPECT_EQ(OK, rv);
2569 SSLConfig ssl_config;
2570 ssl_config.signed_cert_timestamps_enabled = true;
2572 MockCTVerifier ct_verifier;
2573 SetCTVerifier(&ct_verifier);
2575 // Check that the SCT list is extracted as expected.
2576 EXPECT_CALL(ct_verifier, Verify(_, "", "test", _, _)).WillRepeatedly(
2577 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2579 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2580 transport.Pass(), test_server.host_port_pair(), ssl_config));
2581 rv = callback.GetResult(sock->Connect(callback.callback()));
2582 EXPECT_EQ(OK, rv);
2584 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2587 namespace {
2589 bool IsValidOCSPResponse(const base::StringPiece& input) {
2590 base::StringPiece ocsp_response = input;
2591 base::StringPiece sequence, response_status, response_bytes;
2592 return asn1::GetElement(&ocsp_response, asn1::kSEQUENCE, &sequence) &&
2593 ocsp_response.empty() &&
2594 asn1::GetElement(&sequence, asn1::kENUMERATED, &response_status) &&
2595 asn1::GetElement(&sequence,
2596 asn1::kContextSpecific | asn1::kConstructed | 0,
2597 &response_status) &&
2598 sequence.empty();
2601 } // namespace
2603 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2604 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2605 SpawnedTestServer::SSLOptions ssl_options;
2606 ssl_options.staple_ocsp_response = true;
2607 // The test server currently only knows how to generate OCSP responses
2608 // for a freshly minted certificate.
2609 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2611 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2612 ssl_options,
2613 base::FilePath());
2614 ASSERT_TRUE(test_server.Start());
2616 AddressList addr;
2617 ASSERT_TRUE(test_server.GetAddressList(&addr));
2619 TestCompletionCallback callback;
2620 scoped_ptr<StreamSocket> transport(
2621 new TCPClientSocket(addr, &log_, NetLog::Source()));
2622 int rv = callback.GetResult(transport->Connect(callback.callback()));
2623 EXPECT_EQ(OK, rv);
2625 SSLConfig ssl_config;
2626 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2627 // Certificate Transparency verification regardless of whether the platform
2628 // is able to process the OCSP status itself.
2629 ssl_config.signed_cert_timestamps_enabled = true;
2631 MockCTVerifier ct_verifier;
2632 SetCTVerifier(&ct_verifier);
2634 // Check that the OCSP response is extracted and well-formed. It should be the
2635 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2636 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2637 // particular, it should not include the overall two-byte length prefix from
2638 // TLS.
2639 EXPECT_CALL(ct_verifier,
2640 Verify(_, Truly(IsValidOCSPResponse), "", _, _)).WillRepeatedly(
2641 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2643 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2644 transport.Pass(), test_server.host_port_pair(), ssl_config));
2645 rv = callback.GetResult(sock->Connect(callback.callback()));
2646 EXPECT_EQ(OK, rv);
2648 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2651 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2652 SpawnedTestServer::SSLOptions ssl_options;
2653 ssl_options.signed_cert_timestamps_tls_ext = "test";
2655 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2656 ssl_options,
2657 base::FilePath());
2658 ASSERT_TRUE(test_server.Start());
2660 AddressList addr;
2661 ASSERT_TRUE(test_server.GetAddressList(&addr));
2663 TestCompletionCallback callback;
2664 scoped_ptr<StreamSocket> transport(
2665 new TCPClientSocket(addr, &log_, NetLog::Source()));
2666 int rv = callback.GetResult(transport->Connect(callback.callback()));
2667 EXPECT_EQ(OK, rv);
2669 SSLConfig ssl_config;
2670 ssl_config.signed_cert_timestamps_enabled = false;
2672 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2673 transport.Pass(), test_server.host_port_pair(), ssl_config));
2674 rv = callback.GetResult(sock->Connect(callback.callback()));
2675 EXPECT_EQ(OK, rv);
2677 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2680 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2681 TEST_F(SSLClientSocketTest, ReuseStates) {
2682 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2683 SpawnedTestServer::kLocalhost,
2684 base::FilePath());
2685 ASSERT_TRUE(test_server.Start());
2687 AddressList addr;
2688 ASSERT_TRUE(test_server.GetAddressList(&addr));
2690 TestCompletionCallback callback;
2691 scoped_ptr<StreamSocket> transport(
2692 new TCPClientSocket(addr, NULL, NetLog::Source()));
2693 int rv = transport->Connect(callback.callback());
2694 if (rv == ERR_IO_PENDING)
2695 rv = callback.WaitForResult();
2696 EXPECT_EQ(OK, rv);
2698 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2699 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2701 rv = sock->Connect(callback.callback());
2702 if (rv == ERR_IO_PENDING)
2703 rv = callback.WaitForResult();
2704 EXPECT_EQ(OK, rv);
2706 // The socket was just connected. It should be idle because it is speaking
2707 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2708 // returns false.
2709 EXPECT_TRUE(sock->IsConnected());
2710 EXPECT_TRUE(sock->IsConnectedAndIdle());
2711 EXPECT_FALSE(sock->WasEverUsed());
2713 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2714 const size_t kRequestLen = arraysize(kRequestText) - 1;
2715 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2716 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2718 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2719 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2721 if (rv == ERR_IO_PENDING)
2722 rv = callback.WaitForResult();
2723 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2725 // The socket has now been used.
2726 EXPECT_TRUE(sock->WasEverUsed());
2728 // TODO(davidben): Read one byte to ensure the test server has responded and
2729 // then assert IsConnectedAndIdle is false. This currently doesn't work
2730 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2731 // SSL implementation's internal buffers. Either call PR_Available and
2732 // SSL_pending, although the former isn't actually implemented or perhaps
2733 // attempt to read one byte extra.
2736 #if defined(USE_OPENSSL)
2738 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithFailure) {
2739 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2740 SpawnedTestServer::kLocalhost,
2741 base::FilePath());
2742 ASSERT_TRUE(test_server.Start());
2744 AddressList addr;
2745 ASSERT_TRUE(test_server.GetAddressList(&addr));
2747 TestCompletionCallback callback;
2748 scoped_ptr<StreamSocket> real_transport(
2749 new TCPClientSocket(addr, NULL, NetLog::Source()));
2750 scoped_ptr<SynchronousErrorStreamSocket> transport(
2751 new SynchronousErrorStreamSocket(real_transport.Pass()));
2752 int rv = callback.GetResult(transport->Connect(callback.callback()));
2753 EXPECT_EQ(OK, rv);
2755 // Disable TLS False Start to avoid handshake non-determinism.
2756 SSLConfig ssl_config;
2757 ssl_config.false_start_enabled = false;
2759 SynchronousErrorStreamSocket* raw_transport = transport.get();
2760 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2761 transport.Pass(), test_server.host_port_pair(), ssl_config));
2763 sock->SetHandshakeCompletionCallback(base::Bind(
2764 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2766 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
2768 rv = callback.GetResult(sock->Connect(callback.callback()));
2769 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
2770 EXPECT_FALSE(sock->IsConnected());
2772 EXPECT_TRUE(ran_handshake_completion_callback_);
2775 // Tests that the completion callback is run when an SSL connection
2776 // completes successfully.
2777 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithSuccess) {
2778 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2779 SpawnedTestServer::kLocalhost,
2780 base::FilePath());
2781 ASSERT_TRUE(test_server.Start());
2783 AddressList addr;
2784 ASSERT_TRUE(test_server.GetAddressList(&addr));
2786 scoped_ptr<StreamSocket> transport(
2787 new TCPClientSocket(addr, NULL, NetLog::Source()));
2789 TestCompletionCallback callback;
2790 int rv = transport->Connect(callback.callback());
2791 if (rv == ERR_IO_PENDING)
2792 rv = callback.WaitForResult();
2793 EXPECT_EQ(OK, rv);
2795 SSLConfig ssl_config = kDefaultSSLConfig;
2796 ssl_config.false_start_enabled = false;
2798 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2799 transport.Pass(), test_server.host_port_pair(), ssl_config));
2801 sock->SetHandshakeCompletionCallback(base::Bind(
2802 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2804 rv = callback.GetResult(sock->Connect(callback.callback()));
2806 EXPECT_EQ(OK, rv);
2807 EXPECT_TRUE(sock->IsConnected());
2808 EXPECT_TRUE(ran_handshake_completion_callback_);
2811 // Tests that the completion callback is run with a server that doesn't cache
2812 // sessions.
2813 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithDisabledSessionCache) {
2814 SpawnedTestServer::SSLOptions ssl_options;
2815 ssl_options.disable_session_cache = true;
2816 SpawnedTestServer test_server(
2817 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2818 ASSERT_TRUE(test_server.Start());
2820 AddressList addr;
2821 ASSERT_TRUE(test_server.GetAddressList(&addr));
2823 scoped_ptr<StreamSocket> transport(
2824 new TCPClientSocket(addr, NULL, NetLog::Source()));
2826 TestCompletionCallback callback;
2827 int rv = transport->Connect(callback.callback());
2828 if (rv == ERR_IO_PENDING)
2829 rv = callback.WaitForResult();
2830 EXPECT_EQ(OK, rv);
2832 SSLConfig ssl_config = kDefaultSSLConfig;
2833 ssl_config.false_start_enabled = false;
2835 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2836 transport.Pass(), test_server.host_port_pair(), ssl_config));
2838 sock->SetHandshakeCompletionCallback(base::Bind(
2839 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2841 rv = callback.GetResult(sock->Connect(callback.callback()));
2843 EXPECT_EQ(OK, rv);
2844 EXPECT_TRUE(sock->IsConnected());
2845 EXPECT_TRUE(ran_handshake_completion_callback_);
2848 TEST_F(SSLClientSocketFalseStartTest,
2849 HandshakeCallbackIsRun_WithFalseStartFailure) {
2850 // False Start requires NPN and a forward-secret cipher suite.
2851 SpawnedTestServer::SSLOptions server_options;
2852 server_options.key_exchanges =
2853 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2854 server_options.enable_npn = true;
2855 SSLConfig client_config;
2856 client_config.next_protos.push_back("http/1.1");
2857 monitor_handshake_callback_ = true;
2858 fail_handshake_after_false_start_ = true;
2859 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, true));
2860 ASSERT_TRUE(ran_handshake_completion_callback_);
2863 TEST_F(SSLClientSocketFalseStartTest,
2864 HandshakeCallbackIsRun_WithFalseStartSuccess) {
2865 // False Start requires NPN and a forward-secret cipher suite.
2866 SpawnedTestServer::SSLOptions server_options;
2867 server_options.key_exchanges =
2868 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2869 server_options.enable_npn = true;
2870 SSLConfig client_config;
2871 client_config.next_protos.push_back("http/1.1");
2872 monitor_handshake_callback_ = true;
2873 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, true));
2874 ASSERT_TRUE(ran_handshake_completion_callback_);
2876 #endif // defined(USE_OPENSSL)
2878 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
2879 // False Start requires NPN and a forward-secret cipher suite.
2880 SpawnedTestServer::SSLOptions server_options;
2881 server_options.key_exchanges =
2882 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2883 server_options.enable_npn = true;
2884 SSLConfig client_config;
2885 client_config.next_protos.push_back("http/1.1");
2886 ASSERT_NO_FATAL_FAILURE(
2887 TestFalseStart(server_options, client_config, true));
2890 // Test that False Start is disabled without NPN.
2891 TEST_F(SSLClientSocketFalseStartTest, NoNPN) {
2892 SpawnedTestServer::SSLOptions server_options;
2893 server_options.key_exchanges =
2894 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2895 SSLConfig client_config;
2896 client_config.next_protos.clear();
2897 ASSERT_NO_FATAL_FAILURE(
2898 TestFalseStart(server_options, client_config, false));
2901 // Test that False Start is disabled without a forward-secret cipher suite.
2902 TEST_F(SSLClientSocketFalseStartTest, NoForwardSecrecy) {
2903 SpawnedTestServer::SSLOptions server_options;
2904 server_options.key_exchanges =
2905 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
2906 server_options.enable_npn = true;
2907 SSLConfig client_config;
2908 client_config.next_protos.push_back("http/1.1");
2909 ASSERT_NO_FATAL_FAILURE(
2910 TestFalseStart(server_options, client_config, false));
2913 // Test that sessions are resumable after receiving the server Finished message.
2914 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
2915 // Start a server.
2916 SpawnedTestServer::SSLOptions server_options;
2917 server_options.key_exchanges =
2918 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2919 server_options.enable_npn = true;
2920 SSLConfig client_config;
2921 client_config.next_protos.push_back("http/1.1");
2923 // Let a full handshake complete with False Start.
2924 ASSERT_NO_FATAL_FAILURE(
2925 TestFalseStart(server_options, client_config, true));
2927 // Make a second connection.
2928 TestCompletionCallback callback;
2929 scoped_ptr<StreamSocket> transport2(
2930 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2931 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2932 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2933 transport2.Pass(), test_server()->host_port_pair(), client_config);
2934 ASSERT_TRUE(sock2.get());
2935 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
2937 // It should resume the session.
2938 SSLInfo ssl_info;
2939 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
2940 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
2943 // Test that sessions are not resumable before receiving the server Finished
2944 // message.
2945 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinish) {
2946 // Start a server.
2947 SpawnedTestServer::SSLOptions server_options;
2948 server_options.key_exchanges =
2949 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2950 server_options.enable_npn = true;
2951 ASSERT_TRUE(StartTestServer(server_options));
2953 SSLConfig client_config;
2954 client_config.next_protos.push_back("http/1.1");
2956 // Start a handshake up to the server Finished message.
2957 TestCompletionCallback callback;
2958 FakeBlockingStreamSocket* raw_transport1;
2959 scoped_ptr<SSLClientSocket> sock1;
2960 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
2961 client_config, &callback, &raw_transport1, &sock1));
2962 // Although raw_transport1 has the server Finished blocked, the handshake
2963 // still completes.
2964 EXPECT_EQ(OK, callback.WaitForResult());
2966 // Drop the old socket. This is needed because the Python test server can't
2967 // service two sockets in parallel.
2968 sock1.reset();
2970 // Start a second connection.
2971 scoped_ptr<StreamSocket> transport2(
2972 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2973 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2974 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2975 transport2.Pass(), test_server()->host_port_pair(), client_config);
2976 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
2978 // No session resumption because the first connection never received a server
2979 // Finished message.
2980 SSLInfo ssl_info;
2981 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
2982 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2985 // Connect to a server using channel id. It should allow the connection.
2986 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) {
2987 SpawnedTestServer::SSLOptions ssl_options;
2989 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2991 EnableChannelID();
2992 SSLConfig ssl_config = kDefaultSSLConfig;
2993 ssl_config.channel_id_enabled = true;
2995 int rv;
2996 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2998 EXPECT_EQ(OK, rv);
2999 EXPECT_TRUE(sock_->IsConnected());
3000 EXPECT_TRUE(sock_->WasChannelIDSent());
3002 sock_->Disconnect();
3003 EXPECT_FALSE(sock_->IsConnected());
3006 // Connect to a server using Channel ID but failing to look up the Channel
3007 // ID. It should fail.
3008 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) {
3009 SpawnedTestServer::SSLOptions ssl_options;
3011 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3013 EnableFailingChannelID();
3014 SSLConfig ssl_config = kDefaultSSLConfig;
3015 ssl_config.channel_id_enabled = true;
3017 int rv;
3018 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3020 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3021 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3022 // error codes for now.
3023 // http://crbug.com/373670
3024 EXPECT_NE(OK, rv);
3025 EXPECT_FALSE(sock_->IsConnected());
3028 // Connect to a server using Channel ID but asynchronously failing to look up
3029 // the Channel ID. It should fail.
3030 TEST_F(SSLClientSocketChannelIDTest, FailingChannelIDAsync) {
3031 SpawnedTestServer::SSLOptions ssl_options;
3033 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3035 EnableAsyncFailingChannelID();
3036 SSLConfig ssl_config = kDefaultSSLConfig;
3037 ssl_config.channel_id_enabled = true;
3039 int rv;
3040 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3042 EXPECT_EQ(ERR_UNEXPECTED, rv);
3043 EXPECT_FALSE(sock_->IsConnected());
3046 } // namespace net