QUIC - enable persisting of QUICServerInfo (server config) to disk
[chromium-blink-merge.git] / net / socket / ssl_client_socket_unittest.cc
blob3aa445a72f8795eac9bd305e20c203ab41595d64
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/mock_cert_verifier.h"
19 #include "net/cert/test_root_certs.h"
20 #include "net/dns/host_resolver.h"
21 #include "net/http/transport_security_state.h"
22 #include "net/socket/client_socket_factory.h"
23 #include "net/socket/client_socket_handle.h"
24 #include "net/socket/socket_test_util.h"
25 #include "net/socket/tcp_client_socket.h"
26 #include "net/ssl/channel_id_service.h"
27 #include "net/ssl/default_channel_id_store.h"
28 #include "net/ssl/ssl_cert_request_info.h"
29 #include "net/ssl/ssl_config_service.h"
30 #include "net/test/cert_test_util.h"
31 #include "net/test/spawned_test_server/spawned_test_server.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33 #include "testing/platform_test.h"
35 //-----------------------------------------------------------------------------
37 namespace net {
39 namespace {
41 const SSLConfig kDefaultSSLConfig;
43 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
44 // forwarding the Socket and StreamSocket interfaces to the underlying
45 // transport.
46 // This is to provide a common base class for subclasses to override specific
47 // StreamSocket methods for testing, while still communicating with a 'real'
48 // StreamSocket.
49 class WrappedStreamSocket : public StreamSocket {
50 public:
51 explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport)
52 : transport_(transport.Pass()) {}
53 virtual ~WrappedStreamSocket() {}
55 // StreamSocket implementation:
56 virtual int Connect(const CompletionCallback& callback) OVERRIDE {
57 return transport_->Connect(callback);
59 virtual void Disconnect() OVERRIDE { transport_->Disconnect(); }
60 virtual bool IsConnected() const OVERRIDE {
61 return transport_->IsConnected();
63 virtual bool IsConnectedAndIdle() const OVERRIDE {
64 return transport_->IsConnectedAndIdle();
66 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
67 return transport_->GetPeerAddress(address);
69 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
70 return transport_->GetLocalAddress(address);
72 virtual const BoundNetLog& NetLog() const OVERRIDE {
73 return transport_->NetLog();
75 virtual void SetSubresourceSpeculation() OVERRIDE {
76 transport_->SetSubresourceSpeculation();
78 virtual void SetOmniboxSpeculation() OVERRIDE {
79 transport_->SetOmniboxSpeculation();
81 virtual bool WasEverUsed() const OVERRIDE {
82 return transport_->WasEverUsed();
84 virtual bool UsingTCPFastOpen() const OVERRIDE {
85 return transport_->UsingTCPFastOpen();
87 virtual bool WasNpnNegotiated() const OVERRIDE {
88 return transport_->WasNpnNegotiated();
90 virtual NextProto GetNegotiatedProtocol() const OVERRIDE {
91 return transport_->GetNegotiatedProtocol();
93 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE {
94 return transport_->GetSSLInfo(ssl_info);
97 // Socket implementation:
98 virtual int Read(IOBuffer* buf,
99 int buf_len,
100 const CompletionCallback& callback) OVERRIDE {
101 return transport_->Read(buf, buf_len, callback);
103 virtual int Write(IOBuffer* buf,
104 int buf_len,
105 const CompletionCallback& callback) OVERRIDE {
106 return transport_->Write(buf, buf_len, callback);
108 virtual int SetReceiveBufferSize(int32 size) OVERRIDE {
109 return transport_->SetReceiveBufferSize(size);
111 virtual int SetSendBufferSize(int32 size) OVERRIDE {
112 return transport_->SetSendBufferSize(size);
115 protected:
116 scoped_ptr<StreamSocket> transport_;
119 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
120 // will ensure a certain amount of data is internally buffered before
121 // satisfying a Read() request. It exists to mimic OS-level internal
122 // buffering, but in a way to guarantee that X number of bytes will be
123 // returned to callers of Read(), regardless of how quickly the OS receives
124 // them from the TestServer.
125 class ReadBufferingStreamSocket : public WrappedStreamSocket {
126 public:
127 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
128 virtual ~ReadBufferingStreamSocket() {}
130 // Socket implementation:
131 virtual int Read(IOBuffer* buf,
132 int buf_len,
133 const CompletionCallback& callback) OVERRIDE;
135 // Sets the internal buffer to |size|. This must not be greater than
136 // the largest value supplied to Read() - that is, it does not handle
137 // having "leftovers" at the end of Read().
138 // Each call to Read() will be prevented from completion until at least
139 // |size| data has been read.
140 // Set to 0 to turn off buffering, causing Read() to transparently
141 // read via the underlying transport.
142 void SetBufferSize(int size);
144 private:
145 enum State {
146 STATE_NONE,
147 STATE_READ,
148 STATE_READ_COMPLETE,
151 int DoLoop(int result);
152 int DoRead();
153 int DoReadComplete(int result);
154 void OnReadCompleted(int result);
156 State state_;
157 scoped_refptr<GrowableIOBuffer> read_buffer_;
158 int buffer_size_;
160 scoped_refptr<IOBuffer> user_read_buf_;
161 CompletionCallback user_read_callback_;
164 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
165 scoped_ptr<StreamSocket> transport)
166 : WrappedStreamSocket(transport.Pass()),
167 read_buffer_(new GrowableIOBuffer()),
168 buffer_size_(0) {}
170 void ReadBufferingStreamSocket::SetBufferSize(int size) {
171 DCHECK(!user_read_buf_.get());
172 buffer_size_ = size;
173 read_buffer_->SetCapacity(size);
176 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
177 int buf_len,
178 const CompletionCallback& callback) {
179 if (buffer_size_ == 0)
180 return transport_->Read(buf, buf_len, callback);
182 if (buf_len < buffer_size_)
183 return ERR_UNEXPECTED;
185 state_ = STATE_READ;
186 user_read_buf_ = buf;
187 int result = DoLoop(OK);
188 if (result == ERR_IO_PENDING)
189 user_read_callback_ = callback;
190 else
191 user_read_buf_ = NULL;
192 return result;
195 int ReadBufferingStreamSocket::DoLoop(int result) {
196 int rv = result;
197 do {
198 State current_state = state_;
199 state_ = STATE_NONE;
200 switch (current_state) {
201 case STATE_READ:
202 rv = DoRead();
203 break;
204 case STATE_READ_COMPLETE:
205 rv = DoReadComplete(rv);
206 break;
207 case STATE_NONE:
208 default:
209 NOTREACHED() << "Unexpected state: " << current_state;
210 rv = ERR_UNEXPECTED;
211 break;
213 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
214 return rv;
217 int ReadBufferingStreamSocket::DoRead() {
218 state_ = STATE_READ_COMPLETE;
219 int rv =
220 transport_->Read(read_buffer_.get(),
221 read_buffer_->RemainingCapacity(),
222 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
223 base::Unretained(this)));
224 return rv;
227 int ReadBufferingStreamSocket::DoReadComplete(int result) {
228 state_ = STATE_NONE;
229 if (result <= 0)
230 return result;
232 read_buffer_->set_offset(read_buffer_->offset() + result);
233 if (read_buffer_->RemainingCapacity() > 0) {
234 state_ = STATE_READ;
235 return OK;
238 memcpy(user_read_buf_->data(),
239 read_buffer_->StartOfBuffer(),
240 read_buffer_->capacity());
241 read_buffer_->set_offset(0);
242 return read_buffer_->capacity();
245 void ReadBufferingStreamSocket::OnReadCompleted(int result) {
246 result = DoLoop(result);
247 if (result == ERR_IO_PENDING)
248 return;
250 user_read_buf_ = NULL;
251 base::ResetAndReturn(&user_read_callback_).Run(result);
254 // Simulates synchronously receiving an error during Read() or Write()
255 class SynchronousErrorStreamSocket : public WrappedStreamSocket {
256 public:
257 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
258 virtual ~SynchronousErrorStreamSocket() {}
260 // Socket implementation:
261 virtual int Read(IOBuffer* buf,
262 int buf_len,
263 const CompletionCallback& callback) OVERRIDE;
264 virtual int Write(IOBuffer* buf,
265 int buf_len,
266 const CompletionCallback& callback) OVERRIDE;
268 // Sets the next Read() call and all future calls to return |error|.
269 // If there is already a pending asynchronous read, the configured error
270 // will not be returned until that asynchronous read has completed and Read()
271 // is called again.
272 void SetNextReadError(Error error) {
273 DCHECK_GE(0, error);
274 have_read_error_ = true;
275 pending_read_error_ = error;
278 // Sets the next Write() call and all future calls to return |error|.
279 // If there is already a pending asynchronous write, the configured error
280 // will not be returned until that asynchronous write has completed and
281 // Write() is called again.
282 void SetNextWriteError(Error error) {
283 DCHECK_GE(0, error);
284 have_write_error_ = true;
285 pending_write_error_ = error;
288 private:
289 bool have_read_error_;
290 int pending_read_error_;
292 bool have_write_error_;
293 int pending_write_error_;
295 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket);
298 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
299 scoped_ptr<StreamSocket> transport)
300 : WrappedStreamSocket(transport.Pass()),
301 have_read_error_(false),
302 pending_read_error_(OK),
303 have_write_error_(false),
304 pending_write_error_(OK) {}
306 int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
307 int buf_len,
308 const CompletionCallback& callback) {
309 if (have_read_error_)
310 return pending_read_error_;
311 return transport_->Read(buf, buf_len, callback);
314 int SynchronousErrorStreamSocket::Write(IOBuffer* buf,
315 int buf_len,
316 const CompletionCallback& callback) {
317 if (have_write_error_)
318 return pending_write_error_;
319 return transport_->Write(buf, buf_len, callback);
322 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
323 // underlying transport needing to complete things asynchronously in a
324 // deterministic manner (e.g.: independent of the TestServer and the OS's
325 // semantics).
326 class FakeBlockingStreamSocket : public WrappedStreamSocket {
327 public:
328 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
329 virtual ~FakeBlockingStreamSocket() {}
331 // Socket implementation:
332 virtual int Read(IOBuffer* buf,
333 int buf_len,
334 const CompletionCallback& callback) OVERRIDE;
335 virtual int Write(IOBuffer* buf,
336 int buf_len,
337 const CompletionCallback& callback) OVERRIDE;
339 // Blocks read results on the socket. Reads will not complete until
340 // UnblockReadResult() has been called and a result is ready from the
341 // underlying transport. Note: if BlockReadResult() is called while there is a
342 // hanging asynchronous Read(), that Read is blocked.
343 void BlockReadResult();
344 void UnblockReadResult();
346 // Waits for the blocked Read() call to be complete at the underlying
347 // transport.
348 void WaitForReadResult();
350 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
351 // underlying transport until UnblockWrite() has been called. Note: if there
352 // is a pending asynchronous write, it is NOT blocked. For purposes of
353 // blocking writes, data is considered to have reached the underlying
354 // transport as soon as Write() is called.
355 void BlockWrite();
356 void UnblockWrite();
358 // Waits for the blocked Write() call to be scheduled.
359 void WaitForWrite();
361 private:
362 // Handles completion from the underlying transport read.
363 void OnReadCompleted(int result);
365 // True if read callbacks are blocked.
366 bool should_block_read_;
368 // The user callback for the pending read call.
369 CompletionCallback pending_read_callback_;
371 // The result for the blocked read callback, or ERR_IO_PENDING if not
372 // completed.
373 int pending_read_result_;
375 // WaitForReadResult() wait loop.
376 scoped_ptr<base::RunLoop> read_loop_;
378 // True if write calls are blocked.
379 bool should_block_write_;
381 // The buffer for the pending write, or NULL if not scheduled.
382 scoped_refptr<IOBuffer> pending_write_buf_;
384 // The callback for the pending write call.
385 CompletionCallback pending_write_callback_;
387 // The length for the pending write, or -1 if not scheduled.
388 int pending_write_len_;
390 // WaitForWrite() wait loop.
391 scoped_ptr<base::RunLoop> write_loop_;
394 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
395 scoped_ptr<StreamSocket> transport)
396 : WrappedStreamSocket(transport.Pass()),
397 should_block_read_(false),
398 pending_read_result_(ERR_IO_PENDING),
399 should_block_write_(false),
400 pending_write_len_(-1) {}
402 int FakeBlockingStreamSocket::Read(IOBuffer* buf,
403 int len,
404 const CompletionCallback& callback) {
405 DCHECK(pending_read_callback_.is_null());
406 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
407 DCHECK(!callback.is_null());
409 int rv = transport_->Read(buf, len, base::Bind(
410 &FakeBlockingStreamSocket::OnReadCompleted, base::Unretained(this)));
411 if (rv == ERR_IO_PENDING) {
412 // Save the callback to be called later.
413 pending_read_callback_ = callback;
414 } else if (should_block_read_) {
415 // Save the callback and read result to be called later.
416 pending_read_callback_ = callback;
417 OnReadCompleted(rv);
418 rv = ERR_IO_PENDING;
420 return rv;
423 int FakeBlockingStreamSocket::Write(IOBuffer* buf,
424 int len,
425 const CompletionCallback& callback) {
426 DCHECK(buf);
427 DCHECK_LE(0, len);
429 if (!should_block_write_)
430 return transport_->Write(buf, len, callback);
432 // Schedule the write, but do nothing.
433 DCHECK(!pending_write_buf_);
434 DCHECK_EQ(-1, pending_write_len_);
435 DCHECK(pending_write_callback_.is_null());
436 DCHECK(!callback.is_null());
437 pending_write_buf_ = buf;
438 pending_write_len_ = len;
439 pending_write_callback_ = callback;
441 // Stop the write loop, if any.
442 if (write_loop_)
443 write_loop_->Quit();
444 return ERR_IO_PENDING;
447 void FakeBlockingStreamSocket::BlockReadResult() {
448 DCHECK(!should_block_read_);
449 should_block_read_ = true;
452 void FakeBlockingStreamSocket::UnblockReadResult() {
453 DCHECK(should_block_read_);
454 should_block_read_ = false;
456 // If the operation is still pending in the underlying transport, immediately
457 // return - OnReadCompleted() will handle invoking the callback once the
458 // transport has completed.
459 if (pending_read_result_ == ERR_IO_PENDING)
460 return;
461 int result = pending_read_result_;
462 pending_read_result_ = ERR_IO_PENDING;
463 base::ResetAndReturn(&pending_read_callback_).Run(result);
466 void FakeBlockingStreamSocket::WaitForReadResult() {
467 DCHECK(should_block_read_);
468 DCHECK(!read_loop_);
470 if (pending_read_result_ != ERR_IO_PENDING)
471 return;
472 read_loop_.reset(new base::RunLoop);
473 read_loop_->Run();
474 read_loop_.reset();
475 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
478 void FakeBlockingStreamSocket::BlockWrite() {
479 DCHECK(!should_block_write_);
480 should_block_write_ = true;
483 void FakeBlockingStreamSocket::UnblockWrite() {
484 DCHECK(should_block_write_);
485 should_block_write_ = false;
487 // Do nothing if UnblockWrite() was called after BlockWrite(),
488 // without a Write() in between.
489 if (!pending_write_buf_)
490 return;
492 int rv = transport_->Write(pending_write_buf_, pending_write_len_,
493 pending_write_callback_);
494 pending_write_buf_ = NULL;
495 pending_write_len_ = -1;
496 if (rv == ERR_IO_PENDING) {
497 pending_write_callback_.Reset();
498 } else {
499 base::ResetAndReturn(&pending_write_callback_).Run(rv);
503 void FakeBlockingStreamSocket::WaitForWrite() {
504 DCHECK(should_block_write_);
505 DCHECK(!write_loop_);
507 if (pending_write_buf_)
508 return;
509 write_loop_.reset(new base::RunLoop);
510 write_loop_->Run();
511 write_loop_.reset();
512 DCHECK(pending_write_buf_);
515 void FakeBlockingStreamSocket::OnReadCompleted(int result) {
516 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
517 DCHECK(!pending_read_callback_.is_null());
519 if (should_block_read_) {
520 // Store the result so that the callback can be invoked once Unblock() is
521 // called.
522 pending_read_result_ = result;
524 // Stop the WaitForReadResult() call if any.
525 if (read_loop_)
526 read_loop_->Quit();
527 } else {
528 // Either the Read() was never blocked or UnblockReadResult() was called
529 // before the Read() completed. Either way, run the callback.
530 base::ResetAndReturn(&pending_read_callback_).Run(result);
534 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
535 // reads and writes on the socket.
536 class CountingStreamSocket : public WrappedStreamSocket {
537 public:
538 explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport)
539 : WrappedStreamSocket(transport.Pass()),
540 read_count_(0),
541 write_count_(0) {}
542 virtual ~CountingStreamSocket() {}
544 // Socket implementation:
545 virtual int Read(IOBuffer* buf,
546 int buf_len,
547 const CompletionCallback& callback) OVERRIDE {
548 read_count_++;
549 return transport_->Read(buf, buf_len, callback);
551 virtual int Write(IOBuffer* buf,
552 int buf_len,
553 const CompletionCallback& callback) OVERRIDE {
554 write_count_++;
555 return transport_->Write(buf, buf_len, callback);
558 int read_count() const { return read_count_; }
559 int write_count() const { return write_count_; }
561 private:
562 int read_count_;
563 int write_count_;
566 // CompletionCallback that will delete the associated StreamSocket when
567 // the callback is invoked.
568 class DeleteSocketCallback : public TestCompletionCallbackBase {
569 public:
570 explicit DeleteSocketCallback(StreamSocket* socket)
571 : socket_(socket),
572 callback_(base::Bind(&DeleteSocketCallback::OnComplete,
573 base::Unretained(this))) {}
574 virtual ~DeleteSocketCallback() {}
576 const CompletionCallback& callback() const { return callback_; }
578 private:
579 void OnComplete(int result) {
580 if (socket_) {
581 delete socket_;
582 socket_ = NULL;
583 } else {
584 ADD_FAILURE() << "Deleting socket twice";
586 SetResult(result);
589 StreamSocket* socket_;
590 CompletionCallback callback_;
592 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
595 // A ChannelIDStore that always returns an error when asked for a
596 // channel id.
597 class FailingChannelIDStore : public ChannelIDStore {
598 virtual int GetChannelID(const std::string& server_identifier,
599 base::Time* expiration_time,
600 std::string* private_key_result,
601 std::string* cert_result,
602 const GetChannelIDCallback& callback) OVERRIDE {
603 return ERR_UNEXPECTED;
605 virtual void SetChannelID(const std::string& server_identifier,
606 base::Time creation_time,
607 base::Time expiration_time,
608 const std::string& private_key,
609 const std::string& cert) OVERRIDE {}
610 virtual void DeleteChannelID(const std::string& server_identifier,
611 const base::Closure& completion_callback)
612 OVERRIDE {}
613 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
614 base::Time delete_end,
615 const base::Closure& completion_callback)
616 OVERRIDE {}
617 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
618 virtual void GetAllChannelIDs(const GetChannelIDListCallback& callback)
619 OVERRIDE {}
620 virtual int GetChannelIDCount() OVERRIDE { return 0; }
621 virtual void SetForceKeepSessionState() OVERRIDE {}
624 // A ChannelIDStore that asynchronously returns an error when asked for a
625 // channel id.
626 class AsyncFailingChannelIDStore : public ChannelIDStore {
627 virtual int GetChannelID(const std::string& server_identifier,
628 base::Time* expiration_time,
629 std::string* private_key_result,
630 std::string* cert_result,
631 const GetChannelIDCallback& callback) OVERRIDE {
632 base::MessageLoop::current()->PostTask(
633 FROM_HERE, base::Bind(callback, ERR_UNEXPECTED,
634 server_identifier, base::Time(), "", ""));
635 return ERR_IO_PENDING;
637 virtual void SetChannelID(const std::string& server_identifier,
638 base::Time creation_time,
639 base::Time expiration_time,
640 const std::string& private_key,
641 const std::string& cert) OVERRIDE {}
642 virtual void DeleteChannelID(const std::string& server_identifier,
643 const base::Closure& completion_callback)
644 OVERRIDE {}
645 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
646 base::Time delete_end,
647 const base::Closure& completion_callback)
648 OVERRIDE {}
649 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
650 virtual void GetAllChannelIDs(const GetChannelIDListCallback& callback)
651 OVERRIDE {}
652 virtual int GetChannelIDCount() OVERRIDE { return 0; }
653 virtual void SetForceKeepSessionState() OVERRIDE {}
656 class SSLClientSocketTest : public PlatformTest {
657 public:
658 SSLClientSocketTest()
659 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
660 cert_verifier_(new MockCertVerifier),
661 transport_security_state_(new TransportSecurityState) {
662 cert_verifier_->set_default_result(OK);
663 context_.cert_verifier = cert_verifier_.get();
664 context_.transport_security_state = transport_security_state_.get();
667 protected:
668 // The address of the spawned test server, after calling StartTestServer().
669 const AddressList& addr() const { return addr_; }
671 // The SpawnedTestServer object, after calling StartTestServer().
672 const SpawnedTestServer* test_server() const { return test_server_.get(); }
674 // Starts the test server with SSL configuration |ssl_options|. Returns true
675 // on success.
676 bool StartTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
677 test_server_.reset(new SpawnedTestServer(
678 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()));
679 if (!test_server_->Start()) {
680 LOG(ERROR) << "Could not start SpawnedTestServer";
681 return false;
684 if (!test_server_->GetAddressList(&addr_)) {
685 LOG(ERROR) << "Could not get SpawnedTestServer address list";
686 return false;
688 return true;
691 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
692 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
693 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
694 if (!StartTestServer(ssl_options))
695 return false;
697 transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source()));
698 int rv = callback_.GetResult(transport_->Connect(callback_.callback()));
699 if (rv != OK) {
700 LOG(ERROR) << "Could not connect to SpawnedTestServer";
701 return false;
703 return true;
706 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
707 scoped_ptr<StreamSocket> transport_socket,
708 const HostPortPair& host_and_port,
709 const SSLConfig& ssl_config) {
710 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
711 connection->SetSocket(transport_socket.Pass());
712 return socket_factory_->CreateSSLClientSocket(
713 connection.Pass(), host_and_port, ssl_config, context_);
716 // Create an SSLClientSocket object and use it to connect to a test
717 // server, then wait for connection results. This must be called after
718 // a successful ConnectToTestServer() call.
719 // |ssl_config| the SSL configuration to use.
720 // |result| will retrieve the ::Connect() result value.
721 // Returns true on success, false otherwise. Success means that the socket
722 // could be created and its Connect() was called, not that the connection
723 // itself was a success.
724 bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) {
725 sock_ = CreateSSLClientSocket(
726 transport_.Pass(), test_server_->host_port_pair(), ssl_config);
728 if (sock_->IsConnected()) {
729 LOG(ERROR) << "SSL Socket prematurely connected";
730 return false;
733 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
734 return true;
737 ClientSocketFactory* socket_factory_;
738 scoped_ptr<MockCertVerifier> cert_verifier_;
739 scoped_ptr<TransportSecurityState> transport_security_state_;
740 SSLClientSocketContext context_;
741 scoped_ptr<SSLClientSocket> sock_;
742 CapturingNetLog log_;
744 private:
745 scoped_ptr<StreamSocket> transport_;
746 scoped_ptr<SpawnedTestServer> test_server_;
747 TestCompletionCallback callback_;
748 AddressList addr_;
751 // Verifies the correctness of GetSSLCertRequestInfo.
752 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
753 protected:
754 // Creates a test server with the given SSLOptions, connects to it and returns
755 // the SSLCertRequestInfo reported by the socket.
756 scoped_refptr<SSLCertRequestInfo> GetCertRequest(
757 SpawnedTestServer::SSLOptions ssl_options) {
758 SpawnedTestServer test_server(
759 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
760 if (!test_server.Start())
761 return NULL;
763 AddressList addr;
764 if (!test_server.GetAddressList(&addr))
765 return NULL;
767 TestCompletionCallback callback;
768 CapturingNetLog log;
769 scoped_ptr<StreamSocket> transport(
770 new TCPClientSocket(addr, &log, NetLog::Source()));
771 int rv = transport->Connect(callback.callback());
772 if (rv == ERR_IO_PENDING)
773 rv = callback.WaitForResult();
774 EXPECT_EQ(OK, rv);
776 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
777 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
778 EXPECT_FALSE(sock->IsConnected());
780 rv = sock->Connect(callback.callback());
781 if (rv == ERR_IO_PENDING)
782 rv = callback.WaitForResult();
783 scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
784 sock->GetSSLCertRequestInfo(request_info.get());
785 sock->Disconnect();
786 EXPECT_FALSE(sock->IsConnected());
787 EXPECT_TRUE(
788 test_server.host_port_pair().Equals(request_info->host_and_port));
790 return request_info;
794 class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
795 protected:
796 // Creates an SSLClientSocket with |client_config| attached to a
797 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
798 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
799 // so |*out_raw_transport| is a raw pointer.
801 // The client socket will begin a connect using |callback| but stop before the
802 // server's finished message is received. The finished message will be blocked
803 // in |*out_raw_transport|. To complete the handshake and successfully read
804 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
805 // the client successfully false started, |callback.WaitForResult()| will
806 // return OK without unblocking transport reads. But Read() will still block.)
808 // Must be called after StartTestServer is called.
809 void CreateAndConnectUntilServerFinishedReceived(
810 const SSLConfig& client_config,
811 TestCompletionCallback* callback,
812 FakeBlockingStreamSocket** out_raw_transport,
813 scoped_ptr<SSLClientSocket>* out_sock) {
814 CHECK(test_server());
816 scoped_ptr<StreamSocket> real_transport(
817 new TCPClientSocket(addr(), NULL, NetLog::Source()));
818 scoped_ptr<FakeBlockingStreamSocket> transport(
819 new FakeBlockingStreamSocket(real_transport.Pass()));
820 int rv = callback->GetResult(transport->Connect(callback->callback()));
821 EXPECT_EQ(OK, rv);
823 FakeBlockingStreamSocket* raw_transport = transport.get();
824 scoped_ptr<SSLClientSocket> sock =
825 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
826 test_server()->host_port_pair(),
827 client_config);
829 // Connect. Stop before the client processes the first server leg
830 // (ServerHello, etc.)
831 raw_transport->BlockReadResult();
832 rv = sock->Connect(callback->callback());
833 EXPECT_EQ(ERR_IO_PENDING, rv);
834 raw_transport->WaitForReadResult();
836 // Release the ServerHello and wait for the client to write
837 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
838 // server's leg to complete, since it may span multiple reads.)
839 EXPECT_FALSE(callback->have_result());
840 raw_transport->BlockWrite();
841 raw_transport->UnblockReadResult();
842 raw_transport->WaitForWrite();
844 // And, finally, release that and block the next server leg
845 // (ChangeCipherSpec, Finished).
846 raw_transport->BlockReadResult();
847 raw_transport->UnblockWrite();
849 *out_raw_transport = raw_transport;
850 *out_sock = sock.Pass();
853 void TestFalseStart(const SpawnedTestServer::SSLOptions& server_options,
854 const SSLConfig& client_config,
855 bool expect_false_start) {
856 ASSERT_TRUE(StartTestServer(server_options));
858 TestCompletionCallback callback;
859 FakeBlockingStreamSocket* raw_transport = NULL;
860 scoped_ptr<SSLClientSocket> sock;
861 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
862 client_config, &callback, &raw_transport, &sock));
864 if (expect_false_start) {
865 // When False Starting, the handshake should complete before receiving the
866 // Change Cipher Spec and Finished messages.
868 // Note: callback.have_result() may not be true without waiting. The NSS
869 // state machine sometimes lives on a separate thread, so this thread may
870 // not yet have processed the signal that the handshake has completed.
871 int rv = callback.WaitForResult();
872 EXPECT_EQ(OK, rv);
873 EXPECT_TRUE(sock->IsConnected());
875 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
876 static const int kRequestTextSize =
877 static_cast<int>(arraysize(request_text) - 1);
878 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
879 memcpy(request_buffer->data(), request_text, kRequestTextSize);
881 // Write the request.
882 rv = callback.GetResult(sock->Write(request_buffer.get(),
883 kRequestTextSize,
884 callback.callback()));
885 EXPECT_EQ(kRequestTextSize, rv);
887 // The read will hang; it's waiting for the peer to complete the
888 // handshake, and the handshake is still blocked.
889 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
890 rv = sock->Read(buf.get(), 4096, callback.callback());
892 // After releasing reads, the connection proceeds.
893 raw_transport->UnblockReadResult();
894 rv = callback.GetResult(rv);
895 EXPECT_LT(0, rv);
896 } else {
897 // False Start is not enabled, so the handshake will not complete because
898 // the server second leg is blocked.
899 base::RunLoop().RunUntilIdle();
900 EXPECT_FALSE(callback.have_result());
905 class SSLClientSocketChannelIDTest : public SSLClientSocketTest {
906 protected:
907 void EnableChannelID() {
908 channel_id_service_.reset(
909 new ChannelIDService(new DefaultChannelIDStore(NULL),
910 base::MessageLoopProxy::current()));
911 context_.channel_id_service = channel_id_service_.get();
914 void EnableFailingChannelID() {
915 channel_id_service_.reset(new ChannelIDService(
916 new FailingChannelIDStore(), base::MessageLoopProxy::current()));
917 context_.channel_id_service = channel_id_service_.get();
920 void EnableAsyncFailingChannelID() {
921 channel_id_service_.reset(new ChannelIDService(
922 new AsyncFailingChannelIDStore(),
923 base::MessageLoopProxy::current()));
924 context_.channel_id_service = channel_id_service_.get();
927 private:
928 scoped_ptr<ChannelIDService> channel_id_service_;
931 //-----------------------------------------------------------------------------
933 // LogContainsSSLConnectEndEvent returns true if the given index in the given
934 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
935 // merge the first application data record with the Finished message when false
936 // starting. However, in order to avoid the server timing out the handshake,
937 // they'll give up waiting for application data and send the Finished after a
938 // timeout. This means that an SSL connect end event may appear as a socket
939 // write.
940 static bool LogContainsSSLConnectEndEvent(
941 const CapturingNetLog::CapturedEntryList& log,
942 int i) {
943 return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
944 LogContainsEvent(
945 log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
948 } // namespace
950 TEST_F(SSLClientSocketTest, Connect) {
951 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
952 SpawnedTestServer::kLocalhost,
953 base::FilePath());
954 ASSERT_TRUE(test_server.Start());
956 AddressList addr;
957 ASSERT_TRUE(test_server.GetAddressList(&addr));
959 TestCompletionCallback callback;
960 CapturingNetLog log;
961 scoped_ptr<StreamSocket> transport(
962 new TCPClientSocket(addr, &log, NetLog::Source()));
963 int rv = transport->Connect(callback.callback());
964 if (rv == ERR_IO_PENDING)
965 rv = callback.WaitForResult();
966 EXPECT_EQ(OK, rv);
968 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
969 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
971 EXPECT_FALSE(sock->IsConnected());
973 rv = sock->Connect(callback.callback());
975 CapturingNetLog::CapturedEntryList entries;
976 log.GetEntries(&entries);
977 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
978 if (rv == ERR_IO_PENDING)
979 rv = callback.WaitForResult();
980 EXPECT_EQ(OK, rv);
981 EXPECT_TRUE(sock->IsConnected());
982 log.GetEntries(&entries);
983 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
985 sock->Disconnect();
986 EXPECT_FALSE(sock->IsConnected());
989 TEST_F(SSLClientSocketTest, ConnectExpired) {
990 SpawnedTestServer::SSLOptions ssl_options(
991 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
992 SpawnedTestServer test_server(
993 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
994 ASSERT_TRUE(test_server.Start());
996 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
998 AddressList addr;
999 ASSERT_TRUE(test_server.GetAddressList(&addr));
1001 TestCompletionCallback callback;
1002 CapturingNetLog log;
1003 scoped_ptr<StreamSocket> transport(
1004 new TCPClientSocket(addr, &log, NetLog::Source()));
1005 int rv = transport->Connect(callback.callback());
1006 if (rv == ERR_IO_PENDING)
1007 rv = callback.WaitForResult();
1008 EXPECT_EQ(OK, rv);
1010 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1011 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1013 EXPECT_FALSE(sock->IsConnected());
1015 rv = sock->Connect(callback.callback());
1017 CapturingNetLog::CapturedEntryList entries;
1018 log.GetEntries(&entries);
1019 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1020 if (rv == ERR_IO_PENDING)
1021 rv = callback.WaitForResult();
1023 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
1025 // Rather than testing whether or not the underlying socket is connected,
1026 // test that the handshake has finished. This is because it may be
1027 // desirable to disconnect the socket before showing a user prompt, since
1028 // the user may take indefinitely long to respond.
1029 log.GetEntries(&entries);
1030 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1033 TEST_F(SSLClientSocketTest, ConnectMismatched) {
1034 SpawnedTestServer::SSLOptions ssl_options(
1035 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
1036 SpawnedTestServer test_server(
1037 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1038 ASSERT_TRUE(test_server.Start());
1040 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
1042 AddressList addr;
1043 ASSERT_TRUE(test_server.GetAddressList(&addr));
1045 TestCompletionCallback callback;
1046 CapturingNetLog log;
1047 scoped_ptr<StreamSocket> transport(
1048 new TCPClientSocket(addr, &log, NetLog::Source()));
1049 int rv = transport->Connect(callback.callback());
1050 if (rv == ERR_IO_PENDING)
1051 rv = callback.WaitForResult();
1052 EXPECT_EQ(OK, rv);
1054 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1055 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1057 EXPECT_FALSE(sock->IsConnected());
1059 rv = sock->Connect(callback.callback());
1061 CapturingNetLog::CapturedEntryList entries;
1062 log.GetEntries(&entries);
1063 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1064 if (rv == ERR_IO_PENDING)
1065 rv = callback.WaitForResult();
1067 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
1069 // Rather than testing whether or not the underlying socket is connected,
1070 // test that the handshake has finished. This is because it may be
1071 // desirable to disconnect the socket before showing a user prompt, since
1072 // the user may take indefinitely long to respond.
1073 log.GetEntries(&entries);
1074 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1077 // Attempt to connect to a page which requests a client certificate. It should
1078 // return an error code on connect.
1079 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
1080 SpawnedTestServer::SSLOptions ssl_options;
1081 ssl_options.request_client_certificate = true;
1082 SpawnedTestServer test_server(
1083 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1084 ASSERT_TRUE(test_server.Start());
1086 AddressList addr;
1087 ASSERT_TRUE(test_server.GetAddressList(&addr));
1089 TestCompletionCallback callback;
1090 CapturingNetLog log;
1091 scoped_ptr<StreamSocket> transport(
1092 new TCPClientSocket(addr, &log, NetLog::Source()));
1093 int rv = transport->Connect(callback.callback());
1094 if (rv == ERR_IO_PENDING)
1095 rv = callback.WaitForResult();
1096 EXPECT_EQ(OK, rv);
1098 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1099 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1101 EXPECT_FALSE(sock->IsConnected());
1103 rv = sock->Connect(callback.callback());
1105 CapturingNetLog::CapturedEntryList entries;
1106 log.GetEntries(&entries);
1107 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1108 if (rv == ERR_IO_PENDING)
1109 rv = callback.WaitForResult();
1111 log.GetEntries(&entries);
1112 // Because we prematurely kill the handshake at CertificateRequest,
1113 // the server may still send data (notably the ServerHelloDone)
1114 // after the error is returned. As a result, the SSL_CONNECT may not
1115 // be the last entry. See http://crbug.com/54445. We use
1116 // ExpectLogContainsSomewhere instead of
1117 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1118 // extra read instead of two. This occurs before the handshake ends,
1119 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1120 // necessary.
1122 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1123 // fixed and we can respond to the first CertificateRequest
1124 // without closing the socket, add a unit test for sending the
1125 // certificate. This test may still be useful as we'll want to close
1126 // the socket on a timeout if the user takes a long time to pick a
1127 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1128 ExpectLogContainsSomewhere(
1129 entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END);
1130 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
1131 EXPECT_FALSE(sock->IsConnected());
1134 // Connect to a server requesting optional client authentication. Send it a
1135 // null certificate. It should allow the connection.
1137 // TODO(davidben): Also test providing an actual certificate.
1138 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
1139 SpawnedTestServer::SSLOptions ssl_options;
1140 ssl_options.request_client_certificate = true;
1141 SpawnedTestServer test_server(
1142 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1143 ASSERT_TRUE(test_server.Start());
1145 AddressList addr;
1146 ASSERT_TRUE(test_server.GetAddressList(&addr));
1148 TestCompletionCallback callback;
1149 CapturingNetLog log;
1150 scoped_ptr<StreamSocket> transport(
1151 new TCPClientSocket(addr, &log, NetLog::Source()));
1152 int rv = transport->Connect(callback.callback());
1153 if (rv == ERR_IO_PENDING)
1154 rv = callback.WaitForResult();
1155 EXPECT_EQ(OK, rv);
1157 SSLConfig ssl_config = kDefaultSSLConfig;
1158 ssl_config.send_client_cert = true;
1159 ssl_config.client_cert = NULL;
1161 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1162 transport.Pass(), test_server.host_port_pair(), ssl_config));
1164 EXPECT_FALSE(sock->IsConnected());
1166 // Our test server accepts certificate-less connections.
1167 // TODO(davidben): Add a test which requires them and verify the error.
1168 rv = sock->Connect(callback.callback());
1170 CapturingNetLog::CapturedEntryList entries;
1171 log.GetEntries(&entries);
1172 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1173 if (rv == ERR_IO_PENDING)
1174 rv = callback.WaitForResult();
1176 EXPECT_EQ(OK, rv);
1177 EXPECT_TRUE(sock->IsConnected());
1178 log.GetEntries(&entries);
1179 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1181 // We responded to the server's certificate request with a Certificate
1182 // message with no client certificate in it. ssl_info.client_cert_sent
1183 // should be false in this case.
1184 SSLInfo ssl_info;
1185 sock->GetSSLInfo(&ssl_info);
1186 EXPECT_FALSE(ssl_info.client_cert_sent);
1188 sock->Disconnect();
1189 EXPECT_FALSE(sock->IsConnected());
1192 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1193 // - Server closes an SSL connection (with a close_notify alert message).
1194 // - Server closes the underlying TCP connection directly.
1195 // - Server sends data unexpectedly.
1197 TEST_F(SSLClientSocketTest, Read) {
1198 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1199 SpawnedTestServer::kLocalhost,
1200 base::FilePath());
1201 ASSERT_TRUE(test_server.Start());
1203 AddressList addr;
1204 ASSERT_TRUE(test_server.GetAddressList(&addr));
1206 TestCompletionCallback callback;
1207 scoped_ptr<StreamSocket> transport(
1208 new TCPClientSocket(addr, NULL, NetLog::Source()));
1209 int rv = transport->Connect(callback.callback());
1210 if (rv == ERR_IO_PENDING)
1211 rv = callback.WaitForResult();
1212 EXPECT_EQ(OK, rv);
1214 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1215 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1217 rv = sock->Connect(callback.callback());
1218 if (rv == ERR_IO_PENDING)
1219 rv = callback.WaitForResult();
1220 EXPECT_EQ(OK, rv);
1221 EXPECT_TRUE(sock->IsConnected());
1223 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1224 scoped_refptr<IOBuffer> request_buffer(
1225 new IOBuffer(arraysize(request_text) - 1));
1226 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1228 rv = sock->Write(
1229 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1230 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1232 if (rv == ERR_IO_PENDING)
1233 rv = callback.WaitForResult();
1234 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1236 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1237 for (;;) {
1238 rv = sock->Read(buf.get(), 4096, callback.callback());
1239 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1241 if (rv == ERR_IO_PENDING)
1242 rv = callback.WaitForResult();
1244 EXPECT_GE(rv, 0);
1245 if (rv <= 0)
1246 break;
1250 // Tests that SSLClientSocket properly handles when the underlying transport
1251 // synchronously fails a transport read in during the handshake. The error code
1252 // should be preserved so SSLv3 fallback logic can condition on it.
1253 TEST_F(SSLClientSocketTest, Connect_WithSynchronousError) {
1254 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1255 SpawnedTestServer::kLocalhost,
1256 base::FilePath());
1257 ASSERT_TRUE(test_server.Start());
1259 AddressList addr;
1260 ASSERT_TRUE(test_server.GetAddressList(&addr));
1262 TestCompletionCallback callback;
1263 scoped_ptr<StreamSocket> real_transport(
1264 new TCPClientSocket(addr, NULL, NetLog::Source()));
1265 scoped_ptr<SynchronousErrorStreamSocket> transport(
1266 new SynchronousErrorStreamSocket(real_transport.Pass()));
1267 int rv = callback.GetResult(transport->Connect(callback.callback()));
1268 EXPECT_EQ(OK, rv);
1270 // Disable TLS False Start to avoid handshake non-determinism.
1271 SSLConfig ssl_config;
1272 ssl_config.false_start_enabled = false;
1274 SynchronousErrorStreamSocket* raw_transport = transport.get();
1275 scoped_ptr<SSLClientSocket> sock(
1276 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1277 test_server.host_port_pair(),
1278 ssl_config));
1280 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
1282 rv = callback.GetResult(sock->Connect(callback.callback()));
1283 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1284 EXPECT_FALSE(sock->IsConnected());
1287 // Tests that the SSLClientSocket properly handles when the underlying transport
1288 // synchronously returns an error code - such as if an intermediary terminates
1289 // the socket connection uncleanly.
1290 // This is a regression test for http://crbug.com/238536
1291 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
1292 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1293 SpawnedTestServer::kLocalhost,
1294 base::FilePath());
1295 ASSERT_TRUE(test_server.Start());
1297 AddressList addr;
1298 ASSERT_TRUE(test_server.GetAddressList(&addr));
1300 TestCompletionCallback callback;
1301 scoped_ptr<StreamSocket> real_transport(
1302 new TCPClientSocket(addr, NULL, NetLog::Source()));
1303 scoped_ptr<SynchronousErrorStreamSocket> transport(
1304 new SynchronousErrorStreamSocket(real_transport.Pass()));
1305 int rv = callback.GetResult(transport->Connect(callback.callback()));
1306 EXPECT_EQ(OK, rv);
1308 // Disable TLS False Start to avoid handshake non-determinism.
1309 SSLConfig ssl_config;
1310 ssl_config.false_start_enabled = false;
1312 SynchronousErrorStreamSocket* raw_transport = transport.get();
1313 scoped_ptr<SSLClientSocket> sock(
1314 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1315 test_server.host_port_pair(),
1316 ssl_config));
1318 rv = callback.GetResult(sock->Connect(callback.callback()));
1319 EXPECT_EQ(OK, rv);
1320 EXPECT_TRUE(sock->IsConnected());
1322 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1323 static const int kRequestTextSize =
1324 static_cast<int>(arraysize(request_text) - 1);
1325 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1326 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1328 rv = callback.GetResult(
1329 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1330 EXPECT_EQ(kRequestTextSize, rv);
1332 // Simulate an unclean/forcible shutdown.
1333 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
1335 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1337 // Note: This test will hang if this bug has regressed. Simply checking that
1338 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1339 // result when using a dedicated task runner for NSS.
1340 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1341 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1344 // Tests that the SSLClientSocket properly handles when the underlying transport
1345 // asynchronously returns an error code while writing data - such as if an
1346 // intermediary terminates the socket connection uncleanly.
1347 // This is a regression test for http://crbug.com/249848
1348 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
1349 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1350 SpawnedTestServer::kLocalhost,
1351 base::FilePath());
1352 ASSERT_TRUE(test_server.Start());
1354 AddressList addr;
1355 ASSERT_TRUE(test_server.GetAddressList(&addr));
1357 TestCompletionCallback callback;
1358 scoped_ptr<StreamSocket> real_transport(
1359 new TCPClientSocket(addr, NULL, NetLog::Source()));
1360 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1361 // is retained in order to configure additional errors.
1362 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1363 new SynchronousErrorStreamSocket(real_transport.Pass()));
1364 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1365 scoped_ptr<FakeBlockingStreamSocket> transport(
1366 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1367 FakeBlockingStreamSocket* raw_transport = transport.get();
1368 int rv = callback.GetResult(transport->Connect(callback.callback()));
1369 EXPECT_EQ(OK, rv);
1371 // Disable TLS False Start to avoid handshake non-determinism.
1372 SSLConfig ssl_config;
1373 ssl_config.false_start_enabled = false;
1375 scoped_ptr<SSLClientSocket> sock(
1376 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1377 test_server.host_port_pair(),
1378 ssl_config));
1380 rv = callback.GetResult(sock->Connect(callback.callback()));
1381 EXPECT_EQ(OK, rv);
1382 EXPECT_TRUE(sock->IsConnected());
1384 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1385 static const int kRequestTextSize =
1386 static_cast<int>(arraysize(request_text) - 1);
1387 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1388 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1390 // Simulate an unclean/forcible shutdown on the underlying socket.
1391 // However, simulate this error asynchronously.
1392 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1393 raw_transport->BlockWrite();
1395 // This write should complete synchronously, because the TLS ciphertext
1396 // can be created and placed into the outgoing buffers independent of the
1397 // underlying transport.
1398 rv = callback.GetResult(
1399 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1400 EXPECT_EQ(kRequestTextSize, rv);
1402 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1404 rv = sock->Read(buf.get(), 4096, callback.callback());
1405 EXPECT_EQ(ERR_IO_PENDING, rv);
1407 // Now unblock the outgoing request, having it fail with the connection
1408 // being reset.
1409 raw_transport->UnblockWrite();
1411 // Note: This will cause an inifite loop if this bug has regressed. Simply
1412 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1413 // is a legitimate result when using a dedicated task runner for NSS.
1414 rv = callback.GetResult(rv);
1415 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1418 // If there is a Write failure at the transport with no follow-up Read, although
1419 // the write error will not be returned to the client until a future Read or
1420 // Write operation, SSLClientSocket should not spin attempting to re-write on
1421 // the socket. This is a regression test for part of https://crbug.com/381160.
1422 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) {
1423 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1424 SpawnedTestServer::kLocalhost,
1425 base::FilePath());
1426 ASSERT_TRUE(test_server.Start());
1428 AddressList addr;
1429 ASSERT_TRUE(test_server.GetAddressList(&addr));
1431 TestCompletionCallback callback;
1432 scoped_ptr<StreamSocket> real_transport(
1433 new TCPClientSocket(addr, NULL, NetLog::Source()));
1434 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1435 // is retained in order to query them.
1436 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1437 new SynchronousErrorStreamSocket(real_transport.Pass()));
1438 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1439 scoped_ptr<CountingStreamSocket> counting_socket(
1440 new CountingStreamSocket(error_socket.PassAs<StreamSocket>()));
1441 CountingStreamSocket* raw_counting_socket = counting_socket.get();
1442 int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
1443 ASSERT_EQ(OK, rv);
1445 // Disable TLS False Start to avoid handshake non-determinism.
1446 SSLConfig ssl_config;
1447 ssl_config.false_start_enabled = false;
1449 scoped_ptr<SSLClientSocket> sock(
1450 CreateSSLClientSocket(counting_socket.PassAs<StreamSocket>(),
1451 test_server.host_port_pair(),
1452 ssl_config));
1454 rv = callback.GetResult(sock->Connect(callback.callback()));
1455 ASSERT_EQ(OK, rv);
1456 ASSERT_TRUE(sock->IsConnected());
1458 // Simulate an unclean/forcible shutdown on the underlying socket.
1459 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1461 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1462 static const int kRequestTextSize =
1463 static_cast<int>(arraysize(request_text) - 1);
1464 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1465 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1467 // This write should complete synchronously, because the TLS ciphertext
1468 // can be created and placed into the outgoing buffers independent of the
1469 // underlying transport.
1470 rv = callback.GetResult(
1471 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1472 ASSERT_EQ(kRequestTextSize, rv);
1474 // Let the event loop spin for a little bit of time. Even on platforms where
1475 // pumping the state machine involve thread hops, there should be no further
1476 // writes on the transport socket.
1478 // TODO(davidben): Avoid the arbitrary timeout?
1479 int old_write_count = raw_counting_socket->write_count();
1480 base::RunLoop loop;
1481 base::MessageLoop::current()->PostDelayedTask(
1482 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1483 loop.Run();
1484 EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
1487 // Test the full duplex mode, with Read and Write pending at the same time.
1488 // This test also serves as a regression test for http://crbug.com/29815.
1489 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1490 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1491 SpawnedTestServer::kLocalhost,
1492 base::FilePath());
1493 ASSERT_TRUE(test_server.Start());
1495 AddressList addr;
1496 ASSERT_TRUE(test_server.GetAddressList(&addr));
1498 TestCompletionCallback callback; // Used for everything except Write.
1500 scoped_ptr<StreamSocket> transport(
1501 new TCPClientSocket(addr, NULL, NetLog::Source()));
1502 int rv = transport->Connect(callback.callback());
1503 if (rv == ERR_IO_PENDING)
1504 rv = callback.WaitForResult();
1505 EXPECT_EQ(OK, rv);
1507 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1508 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1510 rv = sock->Connect(callback.callback());
1511 if (rv == ERR_IO_PENDING)
1512 rv = callback.WaitForResult();
1513 EXPECT_EQ(OK, rv);
1514 EXPECT_TRUE(sock->IsConnected());
1516 // Issue a "hanging" Read first.
1517 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1518 rv = sock->Read(buf.get(), 4096, callback.callback());
1519 // We haven't written the request, so there should be no response yet.
1520 ASSERT_EQ(ERR_IO_PENDING, rv);
1522 // Write the request.
1523 // The request is padded with a User-Agent header to a size that causes the
1524 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1525 // This tests the fix for http://crbug.com/29815.
1526 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1527 for (int i = 0; i < 3770; ++i)
1528 request_text.push_back('*');
1529 request_text.append("\r\n\r\n");
1530 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1532 TestCompletionCallback callback2; // Used for Write only.
1533 rv = sock->Write(
1534 request_buffer.get(), request_text.size(), callback2.callback());
1535 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1537 if (rv == ERR_IO_PENDING)
1538 rv = callback2.WaitForResult();
1539 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1541 // Now get the Read result.
1542 rv = callback.WaitForResult();
1543 EXPECT_GT(rv, 0);
1546 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1547 // mode when the underlying transport is blocked on sending data. When the
1548 // underlying transport completes due to an error, it should invoke both the
1549 // Read() and Write() callbacks. If the socket is deleted by the Read()
1550 // callback, the Write() callback should not be invoked.
1551 // Regression test for http://crbug.com/232633
1552 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1553 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1554 SpawnedTestServer::kLocalhost,
1555 base::FilePath());
1556 ASSERT_TRUE(test_server.Start());
1558 AddressList addr;
1559 ASSERT_TRUE(test_server.GetAddressList(&addr));
1561 TestCompletionCallback callback;
1562 scoped_ptr<StreamSocket> real_transport(
1563 new TCPClientSocket(addr, NULL, NetLog::Source()));
1564 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1565 // is retained in order to configure additional errors.
1566 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1567 new SynchronousErrorStreamSocket(real_transport.Pass()));
1568 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1569 scoped_ptr<FakeBlockingStreamSocket> transport(
1570 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1571 FakeBlockingStreamSocket* raw_transport = transport.get();
1573 int rv = callback.GetResult(transport->Connect(callback.callback()));
1574 EXPECT_EQ(OK, rv);
1576 // Disable TLS False Start to avoid handshake non-determinism.
1577 SSLConfig ssl_config;
1578 ssl_config.false_start_enabled = false;
1580 scoped_ptr<SSLClientSocket> sock =
1581 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1582 test_server.host_port_pair(),
1583 ssl_config);
1585 rv = callback.GetResult(sock->Connect(callback.callback()));
1586 EXPECT_EQ(OK, rv);
1587 EXPECT_TRUE(sock->IsConnected());
1589 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1590 request_text.append(20 * 1024, '*');
1591 request_text.append("\r\n\r\n");
1592 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1593 new StringIOBuffer(request_text), request_text.size()));
1595 // Simulate errors being returned from the underlying Read() and Write() ...
1596 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1597 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1598 // ... but have those errors returned asynchronously. Because the Write() will
1599 // return first, this will trigger the error.
1600 raw_transport->BlockReadResult();
1601 raw_transport->BlockWrite();
1603 // Enqueue a Read() before calling Write(), which should "hang" due to
1604 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1605 SSLClientSocket* raw_sock = sock.get();
1606 DeleteSocketCallback read_callback(sock.release());
1607 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1608 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1610 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1611 ASSERT_EQ(ERR_IO_PENDING, rv);
1612 ASSERT_FALSE(read_callback.have_result());
1614 #if !defined(USE_OPENSSL)
1615 // NSS follows a pattern where a call to PR_Write will only consume as
1616 // much data as it can encode into application data records before the
1617 // internal memio buffer is full, which should only fill if writing a large
1618 // amount of data and the underlying transport is blocked. Once this happens,
1619 // NSS will return (total size of all application data records it wrote) - 1,
1620 // with the caller expected to resume with the remaining unsent data.
1622 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1623 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1624 // get the socket in the state needed for the test below.
1626 // This is not needed for OpenSSL, because for OpenSSL,
1627 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1628 // SSLClientSocketOpenSSL::Write() will not return until all of
1629 // |request_buffer| has been written to the underlying BIO (although not
1630 // necessarily the underlying transport).
1631 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1632 request_buffer->BytesRemaining(),
1633 callback.callback()));
1634 ASSERT_LT(0, rv);
1635 request_buffer->DidConsume(rv);
1637 // Guard to ensure that |request_buffer| was larger than all of the internal
1638 // buffers (transport, memio, NSS) along the way - otherwise the next call
1639 // to Write() will crash with an invalid buffer.
1640 ASSERT_LT(0, request_buffer->BytesRemaining());
1641 #endif
1643 // Attempt to write the remaining data. NSS will not be able to consume the
1644 // application data because the internal buffers are full, while OpenSSL will
1645 // return that its blocked because the underlying transport is blocked.
1646 rv = raw_sock->Write(request_buffer.get(),
1647 request_buffer->BytesRemaining(),
1648 callback.callback());
1649 ASSERT_EQ(ERR_IO_PENDING, rv);
1650 ASSERT_FALSE(callback.have_result());
1652 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1653 // call the Read() callback, deleting the socket and thus aborting calling
1654 // the Write() callback.
1655 raw_transport->UnblockWrite();
1657 rv = read_callback.WaitForResult();
1658 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1660 // The Write callback should not have been called.
1661 EXPECT_FALSE(callback.have_result());
1664 // Tests that the SSLClientSocket does not crash if data is received on the
1665 // transport socket after a failing write. This can occur if we have a Write
1666 // error in a SPDY socket.
1667 // Regression test for http://crbug.com/335557
1668 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1669 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1670 SpawnedTestServer::kLocalhost,
1671 base::FilePath());
1672 ASSERT_TRUE(test_server.Start());
1674 AddressList addr;
1675 ASSERT_TRUE(test_server.GetAddressList(&addr));
1677 TestCompletionCallback callback;
1678 scoped_ptr<StreamSocket> real_transport(
1679 new TCPClientSocket(addr, NULL, NetLog::Source()));
1680 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1681 // is retained in order to configure additional errors.
1682 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1683 new SynchronousErrorStreamSocket(real_transport.Pass()));
1684 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1685 scoped_ptr<FakeBlockingStreamSocket> transport(
1686 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1687 FakeBlockingStreamSocket* raw_transport = transport.get();
1689 int rv = callback.GetResult(transport->Connect(callback.callback()));
1690 EXPECT_EQ(OK, rv);
1692 // Disable TLS False Start to avoid handshake non-determinism.
1693 SSLConfig ssl_config;
1694 ssl_config.false_start_enabled = false;
1696 scoped_ptr<SSLClientSocket> sock(
1697 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1698 test_server.host_port_pair(),
1699 ssl_config));
1701 rv = callback.GetResult(sock->Connect(callback.callback()));
1702 EXPECT_EQ(OK, rv);
1703 EXPECT_TRUE(sock->IsConnected());
1705 // Send a request so there is something to read from the socket.
1706 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1707 static const int kRequestTextSize =
1708 static_cast<int>(arraysize(request_text) - 1);
1709 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1710 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1712 rv = callback.GetResult(
1713 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1714 EXPECT_EQ(kRequestTextSize, rv);
1716 // Start a hanging read.
1717 TestCompletionCallback read_callback;
1718 raw_transport->BlockReadResult();
1719 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1720 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1721 EXPECT_EQ(ERR_IO_PENDING, rv);
1723 // Perform another write, but have it fail. Write a request larger than the
1724 // internal socket buffers so that the request hits the underlying transport
1725 // socket and detects the error.
1726 std::string long_request_text =
1727 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1728 long_request_text.append(20 * 1024, '*');
1729 long_request_text.append("\r\n\r\n");
1730 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1731 new StringIOBuffer(long_request_text), long_request_text.size()));
1733 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1735 // Write as much data as possible until hitting an error. This is necessary
1736 // for NSS. PR_Write will only consume as much data as it can encode into
1737 // application data records before the internal memio buffer is full, which
1738 // should only fill if writing a large amount of data and the underlying
1739 // transport is blocked. Once this happens, NSS will return (total size of all
1740 // application data records it wrote) - 1, with the caller expected to resume
1741 // with the remaining unsent data.
1742 do {
1743 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1744 long_request_buffer->BytesRemaining(),
1745 callback.callback()));
1746 if (rv > 0) {
1747 long_request_buffer->DidConsume(rv);
1748 // Abort if the entire buffer is ever consumed.
1749 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1751 } while (rv > 0);
1753 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1755 // Release the read.
1756 raw_transport->UnblockReadResult();
1757 rv = read_callback.WaitForResult();
1759 #if defined(USE_OPENSSL)
1760 // Should still read bytes despite the write error.
1761 EXPECT_LT(0, rv);
1762 #else
1763 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1764 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1765 // the write error stops future reads.
1766 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1767 #endif
1770 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1771 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1772 SpawnedTestServer::kLocalhost,
1773 base::FilePath());
1774 ASSERT_TRUE(test_server.Start());
1776 AddressList addr;
1777 ASSERT_TRUE(test_server.GetAddressList(&addr));
1779 TestCompletionCallback callback;
1780 scoped_ptr<StreamSocket> transport(
1781 new TCPClientSocket(addr, NULL, NetLog::Source()));
1782 int rv = transport->Connect(callback.callback());
1783 if (rv == ERR_IO_PENDING)
1784 rv = callback.WaitForResult();
1785 EXPECT_EQ(OK, rv);
1787 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1788 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1790 rv = sock->Connect(callback.callback());
1791 if (rv == ERR_IO_PENDING)
1792 rv = callback.WaitForResult();
1793 EXPECT_EQ(OK, rv);
1795 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1796 scoped_refptr<IOBuffer> request_buffer(
1797 new IOBuffer(arraysize(request_text) - 1));
1798 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1800 rv = sock->Write(
1801 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1802 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1804 if (rv == ERR_IO_PENDING)
1805 rv = callback.WaitForResult();
1806 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1808 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1809 for (;;) {
1810 rv = sock->Read(buf.get(), 1, callback.callback());
1811 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1813 if (rv == ERR_IO_PENDING)
1814 rv = callback.WaitForResult();
1816 EXPECT_GE(rv, 0);
1817 if (rv <= 0)
1818 break;
1822 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1823 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1824 SpawnedTestServer::kLocalhost,
1825 base::FilePath());
1826 ASSERT_TRUE(test_server.Start());
1828 AddressList addr;
1829 ASSERT_TRUE(test_server.GetAddressList(&addr));
1831 TestCompletionCallback callback;
1833 scoped_ptr<StreamSocket> real_transport(
1834 new TCPClientSocket(addr, NULL, NetLog::Source()));
1835 scoped_ptr<ReadBufferingStreamSocket> transport(
1836 new ReadBufferingStreamSocket(real_transport.Pass()));
1837 ReadBufferingStreamSocket* raw_transport = transport.get();
1838 int rv = callback.GetResult(transport->Connect(callback.callback()));
1839 ASSERT_EQ(OK, rv);
1841 scoped_ptr<SSLClientSocket> sock(
1842 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1843 test_server.host_port_pair(),
1844 kDefaultSSLConfig));
1846 rv = callback.GetResult(sock->Connect(callback.callback()));
1847 ASSERT_EQ(OK, rv);
1848 ASSERT_TRUE(sock->IsConnected());
1850 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1851 scoped_refptr<IOBuffer> request_buffer(
1852 new IOBuffer(arraysize(request_text) - 1));
1853 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1855 rv = callback.GetResult(sock->Write(
1856 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
1857 ASSERT_GT(rv, 0);
1858 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1860 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
1861 // data (the max SSL record size) at a time. Ensure that at least 15K worth
1862 // of SSL data is buffered first. The 15K of buffered data is made up of
1863 // many smaller SSL records (the TestServer writes along 1350 byte
1864 // plaintext boundaries), although there may also be a few records that are
1865 // smaller or larger, due to timing and SSL False Start.
1866 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
1867 // the SSLClientSocket implementation, and larger than the minimum amount
1868 // of ciphertext necessary to contain the 8K of plaintext requested below.
1869 raw_transport->SetBufferSize(15000);
1871 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
1872 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
1873 ASSERT_EQ(rv, 8192);
1876 TEST_F(SSLClientSocketTest, Read_Interrupted) {
1877 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1878 SpawnedTestServer::kLocalhost,
1879 base::FilePath());
1880 ASSERT_TRUE(test_server.Start());
1882 AddressList addr;
1883 ASSERT_TRUE(test_server.GetAddressList(&addr));
1885 TestCompletionCallback callback;
1886 scoped_ptr<StreamSocket> transport(
1887 new TCPClientSocket(addr, NULL, NetLog::Source()));
1888 int rv = transport->Connect(callback.callback());
1889 if (rv == ERR_IO_PENDING)
1890 rv = callback.WaitForResult();
1891 EXPECT_EQ(OK, rv);
1893 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1894 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1896 rv = sock->Connect(callback.callback());
1897 if (rv == ERR_IO_PENDING)
1898 rv = callback.WaitForResult();
1899 EXPECT_EQ(OK, rv);
1901 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1902 scoped_refptr<IOBuffer> request_buffer(
1903 new IOBuffer(arraysize(request_text) - 1));
1904 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1906 rv = sock->Write(
1907 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1908 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1910 if (rv == ERR_IO_PENDING)
1911 rv = callback.WaitForResult();
1912 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1914 // Do a partial read and then exit. This test should not crash!
1915 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
1916 rv = sock->Read(buf.get(), 512, callback.callback());
1917 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
1919 if (rv == ERR_IO_PENDING)
1920 rv = callback.WaitForResult();
1922 EXPECT_GT(rv, 0);
1925 TEST_F(SSLClientSocketTest, Read_FullLogging) {
1926 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1927 SpawnedTestServer::kLocalhost,
1928 base::FilePath());
1929 ASSERT_TRUE(test_server.Start());
1931 AddressList addr;
1932 ASSERT_TRUE(test_server.GetAddressList(&addr));
1934 TestCompletionCallback callback;
1935 CapturingNetLog log;
1936 log.SetLogLevel(NetLog::LOG_ALL);
1937 scoped_ptr<StreamSocket> transport(
1938 new TCPClientSocket(addr, &log, NetLog::Source()));
1939 int rv = transport->Connect(callback.callback());
1940 if (rv == ERR_IO_PENDING)
1941 rv = callback.WaitForResult();
1942 EXPECT_EQ(OK, rv);
1944 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1945 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1947 rv = sock->Connect(callback.callback());
1948 if (rv == ERR_IO_PENDING)
1949 rv = callback.WaitForResult();
1950 EXPECT_EQ(OK, rv);
1951 EXPECT_TRUE(sock->IsConnected());
1953 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1954 scoped_refptr<IOBuffer> request_buffer(
1955 new IOBuffer(arraysize(request_text) - 1));
1956 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1958 rv = sock->Write(
1959 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1960 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1962 if (rv == ERR_IO_PENDING)
1963 rv = callback.WaitForResult();
1964 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1966 CapturingNetLog::CapturedEntryList entries;
1967 log.GetEntries(&entries);
1968 size_t last_index = ExpectLogContainsSomewhereAfter(
1969 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
1971 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1972 for (;;) {
1973 rv = sock->Read(buf.get(), 4096, callback.callback());
1974 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1976 if (rv == ERR_IO_PENDING)
1977 rv = callback.WaitForResult();
1979 EXPECT_GE(rv, 0);
1980 if (rv <= 0)
1981 break;
1983 log.GetEntries(&entries);
1984 last_index =
1985 ExpectLogContainsSomewhereAfter(entries,
1986 last_index + 1,
1987 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1988 NetLog::PHASE_NONE);
1992 // Regression test for http://crbug.com/42538
1993 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
1994 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1995 SpawnedTestServer::kLocalhost,
1996 base::FilePath());
1997 ASSERT_TRUE(test_server.Start());
1999 AddressList addr;
2000 TestCompletionCallback callback;
2002 static const unsigned char application_data[] = {
2003 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2004 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2005 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2006 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2007 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2008 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2009 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2010 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2011 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2012 0x0a};
2014 // All reads and writes complete synchronously (async=false).
2015 MockRead data_reads[] = {
2016 MockRead(SYNCHRONOUS,
2017 reinterpret_cast<const char*>(application_data),
2018 arraysize(application_data)),
2019 MockRead(SYNCHRONOUS, OK), };
2021 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
2023 scoped_ptr<StreamSocket> transport(
2024 new MockTCPClientSocket(addr, NULL, &data));
2025 int rv = transport->Connect(callback.callback());
2026 if (rv == ERR_IO_PENDING)
2027 rv = callback.WaitForResult();
2028 EXPECT_EQ(OK, rv);
2030 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2031 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2033 rv = sock->Connect(callback.callback());
2034 if (rv == ERR_IO_PENDING)
2035 rv = callback.WaitForResult();
2036 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
2039 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
2040 // Rather than exhaustively disabling every RC4 ciphersuite defined at
2041 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
2042 // only disabling those cipher suites that the test server actually
2043 // implements.
2044 const uint16 kCiphersToDisable[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
2047 SpawnedTestServer::SSLOptions ssl_options;
2048 // Enable only RC4 on the test server.
2049 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
2050 SpawnedTestServer test_server(
2051 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2052 ASSERT_TRUE(test_server.Start());
2054 AddressList addr;
2055 ASSERT_TRUE(test_server.GetAddressList(&addr));
2057 TestCompletionCallback callback;
2058 CapturingNetLog log;
2059 scoped_ptr<StreamSocket> transport(
2060 new TCPClientSocket(addr, &log, NetLog::Source()));
2061 int rv = transport->Connect(callback.callback());
2062 if (rv == ERR_IO_PENDING)
2063 rv = callback.WaitForResult();
2064 EXPECT_EQ(OK, rv);
2066 SSLConfig ssl_config;
2067 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
2068 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
2070 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2071 transport.Pass(), test_server.host_port_pair(), ssl_config));
2073 EXPECT_FALSE(sock->IsConnected());
2075 rv = sock->Connect(callback.callback());
2076 CapturingNetLog::CapturedEntryList entries;
2077 log.GetEntries(&entries);
2078 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2080 // NSS has special handling that maps a handshake_failure alert received
2081 // immediately after a client_hello to be a mismatched cipher suite error,
2082 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
2083 // Secure Transport (OS X), the handshake_failure is bubbled up without any
2084 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
2085 // indicates that no cipher suite was negotiated with the test server.
2086 if (rv == ERR_IO_PENDING)
2087 rv = callback.WaitForResult();
2088 EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH ||
2089 rv == ERR_SSL_PROTOCOL_ERROR);
2090 // The exact ordering differs between SSLClientSocketNSS (which issues an
2091 // extra read) and SSLClientSocketMac (which does not). Just make sure the
2092 // error appears somewhere in the log.
2093 log.GetEntries(&entries);
2094 ExpectLogContainsSomewhere(
2095 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
2097 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2098 // the socket when it encounters an error, whereas other implementations
2099 // leave it connected.
2100 // Because this an error that the test server is mutually aware of, as opposed
2101 // to being an error such as a certificate name mismatch, which is
2102 // client-only, the exact index of the SSL connect end depends on how
2103 // quickly the test server closes the underlying socket. If the test server
2104 // closes before the IO message loop pumps messages, there may be a 0-byte
2105 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2106 // result, the SSL connect end event will be the second-to-last entry,
2107 // rather than the last entry.
2108 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) ||
2109 LogContainsSSLConnectEndEvent(entries, -2));
2112 // When creating an SSLClientSocket, it is allowed to pass in a
2113 // ClientSocketHandle that is not obtained from a client socket pool.
2114 // Here we verify that such a simple ClientSocketHandle, not associated with any
2115 // client socket pool, can be destroyed safely.
2116 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
2117 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2118 SpawnedTestServer::kLocalhost,
2119 base::FilePath());
2120 ASSERT_TRUE(test_server.Start());
2122 AddressList addr;
2123 ASSERT_TRUE(test_server.GetAddressList(&addr));
2125 TestCompletionCallback callback;
2126 scoped_ptr<StreamSocket> transport(
2127 new TCPClientSocket(addr, NULL, NetLog::Source()));
2128 int rv = transport->Connect(callback.callback());
2129 if (rv == ERR_IO_PENDING)
2130 rv = callback.WaitForResult();
2131 EXPECT_EQ(OK, rv);
2133 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
2134 socket_handle->SetSocket(transport.Pass());
2136 scoped_ptr<SSLClientSocket> sock(
2137 socket_factory_->CreateSSLClientSocket(socket_handle.Pass(),
2138 test_server.host_port_pair(),
2139 kDefaultSSLConfig,
2140 context_));
2142 EXPECT_FALSE(sock->IsConnected());
2143 rv = sock->Connect(callback.callback());
2144 if (rv == ERR_IO_PENDING)
2145 rv = callback.WaitForResult();
2146 EXPECT_EQ(OK, rv);
2149 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2150 // code and different keying label results in different keying material.
2151 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
2152 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2153 SpawnedTestServer::kLocalhost,
2154 base::FilePath());
2155 ASSERT_TRUE(test_server.Start());
2157 AddressList addr;
2158 ASSERT_TRUE(test_server.GetAddressList(&addr));
2160 TestCompletionCallback callback;
2162 scoped_ptr<StreamSocket> transport(
2163 new TCPClientSocket(addr, NULL, NetLog::Source()));
2164 int rv = transport->Connect(callback.callback());
2165 if (rv == ERR_IO_PENDING)
2166 rv = callback.WaitForResult();
2167 EXPECT_EQ(OK, rv);
2169 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2170 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2172 rv = sock->Connect(callback.callback());
2173 if (rv == ERR_IO_PENDING)
2174 rv = callback.WaitForResult();
2175 EXPECT_EQ(OK, rv);
2176 EXPECT_TRUE(sock->IsConnected());
2178 const int kKeyingMaterialSize = 32;
2179 const char* kKeyingLabel1 = "client-socket-test-1";
2180 const char* kKeyingContext = "";
2181 unsigned char client_out1[kKeyingMaterialSize];
2182 memset(client_out1, 0, sizeof(client_out1));
2183 rv = sock->ExportKeyingMaterial(
2184 kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1));
2185 EXPECT_EQ(rv, OK);
2187 const char* kKeyingLabel2 = "client-socket-test-2";
2188 unsigned char client_out2[kKeyingMaterialSize];
2189 memset(client_out2, 0, sizeof(client_out2));
2190 rv = sock->ExportKeyingMaterial(
2191 kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2));
2192 EXPECT_EQ(rv, OK);
2193 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2196 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2197 // explicit NSS initialization.
2198 TEST(SSLClientSocket, ClearSessionCache) {
2199 SSLClientSocket::ClearSessionCache();
2202 // Test that the server certificates are properly retrieved from the underlying
2203 // SSL stack.
2204 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
2205 // The connection does not have to be successful.
2206 cert_verifier_->set_default_result(ERR_CERT_INVALID);
2208 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2209 // This makes the server present redundant-server-chain.pem, which contains
2210 // intermediate certificates.
2211 SpawnedTestServer::SSLOptions ssl_options(
2212 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2213 SpawnedTestServer test_server(
2214 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2215 ASSERT_TRUE(test_server.Start());
2217 AddressList addr;
2218 ASSERT_TRUE(test_server.GetAddressList(&addr));
2220 TestCompletionCallback callback;
2221 scoped_ptr<StreamSocket> transport(
2222 new TCPClientSocket(addr, NULL, NetLog::Source()));
2223 int rv = transport->Connect(callback.callback());
2224 rv = callback.GetResult(rv);
2225 EXPECT_EQ(OK, rv);
2227 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2228 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2229 EXPECT_FALSE(sock->IsConnected());
2230 rv = sock->Connect(callback.callback());
2231 rv = callback.GetResult(rv);
2233 EXPECT_EQ(ERR_CERT_INVALID, rv);
2234 EXPECT_TRUE(sock->IsConnected());
2236 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2237 // certs from redundant-server-chain.pem.
2238 CertificateList server_certs =
2239 CreateCertificateListFromFile(GetTestCertsDirectory(),
2240 "redundant-server-chain.pem",
2241 X509Certificate::FORMAT_AUTO);
2243 // Get the server certificate as received client side.
2244 scoped_refptr<X509Certificate> server_certificate =
2245 sock->GetUnverifiedServerCertificateChain();
2247 // Get the intermediates as received client side.
2248 const X509Certificate::OSCertHandles& server_intermediates =
2249 server_certificate->GetIntermediateCertificates();
2251 // Check that the unverified server certificate chain is properly retrieved
2252 // from the underlying ssl stack.
2253 ASSERT_EQ(4U, server_certs.size());
2255 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2256 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
2258 ASSERT_EQ(3U, server_intermediates.size());
2260 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
2261 server_certs[1]->os_cert_handle()));
2262 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
2263 server_certs[2]->os_cert_handle()));
2264 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
2265 server_certs[3]->os_cert_handle()));
2267 sock->Disconnect();
2268 EXPECT_FALSE(sock->IsConnected());
2271 // This tests that SSLInfo contains a properly re-constructed certificate
2272 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2273 // verified, not the chain as served by the server. (They may be different.)
2275 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2276 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2277 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2278 // a self-signed root. Such a situation can occur when a new root (C2) is
2279 // cross-certified by an old root (D) and has two different versions of its
2280 // floating around. Servers may supply C2 as an intermediate, but the
2281 // SSLClientSocket should return the chain that was verified, from
2282 // verify_result, instead.
2283 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
2284 // By default, cause the CertVerifier to treat all certificates as
2285 // expired.
2286 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
2288 // We will expect SSLInfo to ultimately contain this chain.
2289 CertificateList certs =
2290 CreateCertificateListFromFile(GetTestCertsDirectory(),
2291 "redundant-validated-chain.pem",
2292 X509Certificate::FORMAT_AUTO);
2293 ASSERT_EQ(3U, certs.size());
2295 X509Certificate::OSCertHandles temp_intermediates;
2296 temp_intermediates.push_back(certs[1]->os_cert_handle());
2297 temp_intermediates.push_back(certs[2]->os_cert_handle());
2299 CertVerifyResult verify_result;
2300 verify_result.verified_cert = X509Certificate::CreateFromHandle(
2301 certs[0]->os_cert_handle(), temp_intermediates);
2303 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2304 // rather than A->B->C.
2305 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
2307 // Load and install the root for the validated chain.
2308 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
2309 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2310 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert);
2311 ScopedTestRoot scoped_root(root_cert.get());
2313 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2314 SpawnedTestServer::SSLOptions ssl_options(
2315 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2316 SpawnedTestServer test_server(
2317 SpawnedTestServer::TYPE_HTTPS,
2318 ssl_options,
2319 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2320 ASSERT_TRUE(test_server.Start());
2322 AddressList addr;
2323 ASSERT_TRUE(test_server.GetAddressList(&addr));
2325 TestCompletionCallback callback;
2326 CapturingNetLog log;
2327 scoped_ptr<StreamSocket> transport(
2328 new TCPClientSocket(addr, &log, NetLog::Source()));
2329 int rv = transport->Connect(callback.callback());
2330 if (rv == ERR_IO_PENDING)
2331 rv = callback.WaitForResult();
2332 EXPECT_EQ(OK, rv);
2334 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2335 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2336 EXPECT_FALSE(sock->IsConnected());
2337 rv = sock->Connect(callback.callback());
2339 CapturingNetLog::CapturedEntryList entries;
2340 log.GetEntries(&entries);
2341 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2342 if (rv == ERR_IO_PENDING)
2343 rv = callback.WaitForResult();
2345 EXPECT_EQ(OK, rv);
2346 EXPECT_TRUE(sock->IsConnected());
2347 log.GetEntries(&entries);
2348 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2350 SSLInfo ssl_info;
2351 sock->GetSSLInfo(&ssl_info);
2353 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2354 // -> C2.
2355 const X509Certificate::OSCertHandles& intermediates =
2356 ssl_info.cert->GetIntermediateCertificates();
2357 ASSERT_EQ(2U, intermediates.size());
2358 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
2359 certs[0]->os_cert_handle()));
2360 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
2361 certs[1]->os_cert_handle()));
2362 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
2363 certs[2]->os_cert_handle()));
2365 sock->Disconnect();
2366 EXPECT_FALSE(sock->IsConnected());
2369 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
2370 SpawnedTestServer::SSLOptions ssl_options;
2371 ssl_options.request_client_certificate = true;
2372 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2373 ASSERT_TRUE(request_info.get());
2374 EXPECT_EQ(0u, request_info->cert_authorities.size());
2377 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
2378 const base::FilePath::CharType kThawteFile[] =
2379 FILE_PATH_LITERAL("thawte.single.pem");
2380 const unsigned char kThawteDN[] = {
2381 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2382 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2383 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2384 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2385 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2386 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2387 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2388 const size_t kThawteLen = sizeof(kThawteDN);
2390 const base::FilePath::CharType kDiginotarFile[] =
2391 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2392 const unsigned char kDiginotarDN[] = {
2393 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2394 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2395 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2396 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2397 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2398 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2399 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2400 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2401 0x6c};
2402 const size_t kDiginotarLen = sizeof(kDiginotarDN);
2404 SpawnedTestServer::SSLOptions ssl_options;
2405 ssl_options.request_client_certificate = true;
2406 ssl_options.client_authorities.push_back(
2407 GetTestClientCertsDirectory().Append(kThawteFile));
2408 ssl_options.client_authorities.push_back(
2409 GetTestClientCertsDirectory().Append(kDiginotarFile));
2410 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2411 ASSERT_TRUE(request_info.get());
2412 ASSERT_EQ(2u, request_info->cert_authorities.size());
2413 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
2414 request_info->cert_authorities[0]);
2415 EXPECT_EQ(
2416 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
2417 request_info->cert_authorities[1]);
2420 // cert_key_types is currently only populated on OpenSSL.
2421 #if defined(USE_OPENSSL)
2422 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
2423 SpawnedTestServer::SSLOptions ssl_options;
2424 ssl_options.request_client_certificate = true;
2425 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN);
2426 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2427 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2428 ASSERT_TRUE(request_info.get());
2429 ASSERT_EQ(2u, request_info->cert_key_types.size());
2430 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]);
2431 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]);
2433 #endif // defined(USE_OPENSSL)
2435 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
2436 SpawnedTestServer::SSLOptions ssl_options;
2437 ssl_options.signed_cert_timestamps_tls_ext = "test";
2439 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2440 ssl_options,
2441 base::FilePath());
2442 ASSERT_TRUE(test_server.Start());
2444 AddressList addr;
2445 ASSERT_TRUE(test_server.GetAddressList(&addr));
2447 TestCompletionCallback callback;
2448 CapturingNetLog log;
2449 scoped_ptr<StreamSocket> transport(
2450 new TCPClientSocket(addr, &log, NetLog::Source()));
2451 int rv = transport->Connect(callback.callback());
2452 if (rv == ERR_IO_PENDING)
2453 rv = callback.WaitForResult();
2454 EXPECT_EQ(OK, rv);
2456 SSLConfig ssl_config;
2457 ssl_config.signed_cert_timestamps_enabled = true;
2459 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2460 transport.Pass(), test_server.host_port_pair(), ssl_config));
2462 EXPECT_FALSE(sock->IsConnected());
2464 rv = sock->Connect(callback.callback());
2466 CapturingNetLog::CapturedEntryList entries;
2467 log.GetEntries(&entries);
2468 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2469 if (rv == ERR_IO_PENDING)
2470 rv = callback.WaitForResult();
2471 EXPECT_EQ(OK, rv);
2472 EXPECT_TRUE(sock->IsConnected());
2473 log.GetEntries(&entries);
2474 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2476 #if !defined(USE_OPENSSL)
2477 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2478 #else
2479 // Enabling CT for OpenSSL is currently a noop.
2480 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2481 #endif
2483 sock->Disconnect();
2484 EXPECT_FALSE(sock->IsConnected());
2487 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2488 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2489 SpawnedTestServer::SSLOptions ssl_options;
2490 ssl_options.staple_ocsp_response = true;
2491 // The test server currently only knows how to generate OCSP responses
2492 // for a freshly minted certificate.
2493 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2495 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2496 ssl_options,
2497 base::FilePath());
2498 ASSERT_TRUE(test_server.Start());
2500 AddressList addr;
2501 ASSERT_TRUE(test_server.GetAddressList(&addr));
2503 TestCompletionCallback callback;
2504 CapturingNetLog log;
2505 scoped_ptr<StreamSocket> transport(
2506 new TCPClientSocket(addr, &log, NetLog::Source()));
2507 int rv = transport->Connect(callback.callback());
2508 if (rv == ERR_IO_PENDING)
2509 rv = callback.WaitForResult();
2510 EXPECT_EQ(OK, rv);
2512 SSLConfig ssl_config;
2513 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2514 // Certificate Transparency verification regardless of whether the platform
2515 // is able to process the OCSP status itself.
2516 ssl_config.signed_cert_timestamps_enabled = true;
2518 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2519 transport.Pass(), test_server.host_port_pair(), ssl_config));
2521 EXPECT_FALSE(sock->IsConnected());
2523 rv = sock->Connect(callback.callback());
2525 CapturingNetLog::CapturedEntryList entries;
2526 log.GetEntries(&entries);
2527 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2528 if (rv == ERR_IO_PENDING)
2529 rv = callback.WaitForResult();
2530 EXPECT_EQ(OK, rv);
2531 EXPECT_TRUE(sock->IsConnected());
2532 log.GetEntries(&entries);
2533 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2535 #if !defined(USE_OPENSSL)
2536 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2537 #else
2538 // OCSP stapling isn't currently supported in the OpenSSL socket.
2539 EXPECT_FALSE(sock->stapled_ocsp_response_received_);
2540 #endif
2542 sock->Disconnect();
2543 EXPECT_FALSE(sock->IsConnected());
2546 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2547 SpawnedTestServer::SSLOptions ssl_options;
2548 ssl_options.signed_cert_timestamps_tls_ext = "test";
2550 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2551 ssl_options,
2552 base::FilePath());
2553 ASSERT_TRUE(test_server.Start());
2555 AddressList addr;
2556 ASSERT_TRUE(test_server.GetAddressList(&addr));
2558 TestCompletionCallback callback;
2559 CapturingNetLog log;
2560 scoped_ptr<StreamSocket> transport(
2561 new TCPClientSocket(addr, &log, NetLog::Source()));
2562 int rv = transport->Connect(callback.callback());
2563 if (rv == ERR_IO_PENDING)
2564 rv = callback.WaitForResult();
2565 EXPECT_EQ(OK, rv);
2567 SSLConfig ssl_config;
2568 ssl_config.signed_cert_timestamps_enabled = false;
2570 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2571 transport.Pass(), test_server.host_port_pair(), ssl_config));
2573 EXPECT_FALSE(sock->IsConnected());
2575 rv = sock->Connect(callback.callback());
2577 CapturingNetLog::CapturedEntryList entries;
2578 log.GetEntries(&entries);
2579 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2580 if (rv == ERR_IO_PENDING)
2581 rv = callback.WaitForResult();
2582 EXPECT_EQ(OK, rv);
2583 EXPECT_TRUE(sock->IsConnected());
2584 log.GetEntries(&entries);
2585 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2587 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2589 sock->Disconnect();
2590 EXPECT_FALSE(sock->IsConnected());
2593 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2594 TEST_F(SSLClientSocketTest, ReuseStates) {
2595 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2596 SpawnedTestServer::kLocalhost,
2597 base::FilePath());
2598 ASSERT_TRUE(test_server.Start());
2600 AddressList addr;
2601 ASSERT_TRUE(test_server.GetAddressList(&addr));
2603 TestCompletionCallback callback;
2604 scoped_ptr<StreamSocket> transport(
2605 new TCPClientSocket(addr, NULL, NetLog::Source()));
2606 int rv = transport->Connect(callback.callback());
2607 if (rv == ERR_IO_PENDING)
2608 rv = callback.WaitForResult();
2609 EXPECT_EQ(OK, rv);
2611 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2612 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2614 rv = sock->Connect(callback.callback());
2615 if (rv == ERR_IO_PENDING)
2616 rv = callback.WaitForResult();
2617 EXPECT_EQ(OK, rv);
2619 // The socket was just connected. It should be idle because it is speaking
2620 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2621 // returns false.
2622 EXPECT_TRUE(sock->IsConnected());
2623 EXPECT_TRUE(sock->IsConnectedAndIdle());
2624 EXPECT_FALSE(sock->WasEverUsed());
2626 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2627 const size_t kRequestLen = arraysize(kRequestText) - 1;
2628 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2629 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2631 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2632 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2634 if (rv == ERR_IO_PENDING)
2635 rv = callback.WaitForResult();
2636 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2638 // The socket has now been used.
2639 EXPECT_TRUE(sock->WasEverUsed());
2641 // TODO(davidben): Read one byte to ensure the test server has responded and
2642 // then assert IsConnectedAndIdle is false. This currently doesn't work
2643 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2644 // SSL implementation's internal buffers. Either call PR_Available and
2645 // SSL_pending, although the former isn't actually implemented or perhaps
2646 // attempt to read one byte extra.
2649 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
2650 // False Start requires NPN and a forward-secret cipher suite.
2651 SpawnedTestServer::SSLOptions server_options;
2652 server_options.key_exchanges =
2653 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2654 server_options.enable_npn = true;
2655 SSLConfig client_config;
2656 client_config.next_protos.push_back("http/1.1");
2657 ASSERT_NO_FATAL_FAILURE(
2658 TestFalseStart(server_options, client_config, true));
2661 // Test that False Start is disabled without NPN.
2662 TEST_F(SSLClientSocketFalseStartTest, NoNPN) {
2663 SpawnedTestServer::SSLOptions server_options;
2664 server_options.key_exchanges =
2665 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2666 SSLConfig client_config;
2667 client_config.next_protos.clear();
2668 ASSERT_NO_FATAL_FAILURE(
2669 TestFalseStart(server_options, client_config, false));
2672 // Test that False Start is disabled without a forward-secret cipher suite.
2673 TEST_F(SSLClientSocketFalseStartTest, NoForwardSecrecy) {
2674 SpawnedTestServer::SSLOptions server_options;
2675 server_options.key_exchanges =
2676 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
2677 server_options.enable_npn = true;
2678 SSLConfig client_config;
2679 client_config.next_protos.push_back("http/1.1");
2680 ASSERT_NO_FATAL_FAILURE(
2681 TestFalseStart(server_options, client_config, false));
2684 // Test that sessions are resumable after receiving the server Finished message.
2685 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
2686 // Start a server.
2687 SpawnedTestServer::SSLOptions server_options;
2688 server_options.key_exchanges =
2689 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2690 server_options.enable_npn = true;
2691 SSLConfig client_config;
2692 client_config.next_protos.push_back("http/1.1");
2694 // Let a full handshake complete with False Start.
2695 ASSERT_NO_FATAL_FAILURE(
2696 TestFalseStart(server_options, client_config, true));
2698 // Make a second connection.
2699 TestCompletionCallback callback;
2700 scoped_ptr<StreamSocket> transport2(
2701 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2702 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2703 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2704 transport2.Pass(), test_server()->host_port_pair(), client_config);
2705 ASSERT_TRUE(sock2.get());
2706 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
2708 // It should resume the session.
2709 SSLInfo ssl_info;
2710 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
2711 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
2714 // Test that sessions are not resumable before receiving the server Finished
2715 // message.
2716 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinish) {
2717 // Start a server.
2718 SpawnedTestServer::SSLOptions server_options;
2719 server_options.key_exchanges =
2720 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2721 server_options.enable_npn = true;
2722 ASSERT_TRUE(StartTestServer(server_options));
2724 SSLConfig client_config;
2725 client_config.next_protos.push_back("http/1.1");
2727 // Start a handshake up to the server Finished message.
2728 TestCompletionCallback callback;
2729 FakeBlockingStreamSocket* raw_transport1;
2730 scoped_ptr<SSLClientSocket> sock1;
2731 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
2732 client_config, &callback, &raw_transport1, &sock1));
2733 // Although raw_transport1 has the server Finished blocked, the handshake
2734 // still completes.
2735 EXPECT_EQ(OK, callback.WaitForResult());
2737 // Drop the old socket. This is needed because the Python test server can't
2738 // service two sockets in parallel.
2739 sock1.reset();
2741 // Start a second connection.
2742 scoped_ptr<StreamSocket> transport2(
2743 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2744 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2745 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2746 transport2.Pass(), test_server()->host_port_pair(), client_config);
2747 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
2749 // No session resumption because the first connection never received a server
2750 // Finished message.
2751 SSLInfo ssl_info;
2752 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
2753 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2756 // Connect to a server using channel id. It should allow the connection.
2757 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) {
2758 SpawnedTestServer::SSLOptions ssl_options;
2760 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2762 EnableChannelID();
2763 SSLConfig ssl_config = kDefaultSSLConfig;
2764 ssl_config.channel_id_enabled = true;
2766 int rv;
2767 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2769 EXPECT_EQ(OK, rv);
2770 EXPECT_TRUE(sock_->IsConnected());
2771 EXPECT_TRUE(sock_->WasChannelIDSent());
2773 sock_->Disconnect();
2774 EXPECT_FALSE(sock_->IsConnected());
2777 // Connect to a server using Channel ID but failing to look up the Channel
2778 // ID. It should fail.
2779 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) {
2780 SpawnedTestServer::SSLOptions ssl_options;
2782 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2784 EnableFailingChannelID();
2785 SSLConfig ssl_config = kDefaultSSLConfig;
2786 ssl_config.channel_id_enabled = true;
2788 int rv;
2789 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2791 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
2792 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
2793 // error codes for now.
2794 // http://crbug.com/373670
2795 EXPECT_NE(OK, rv);
2796 EXPECT_FALSE(sock_->IsConnected());
2799 // Connect to a server using Channel ID but asynchronously failing to look up
2800 // the Channel ID. It should fail.
2801 TEST_F(SSLClientSocketChannelIDTest, FailingChannelIDAsync) {
2802 SpawnedTestServer::SSLOptions ssl_options;
2804 ASSERT_TRUE(ConnectToTestServer(ssl_options));
2806 EnableAsyncFailingChannelID();
2807 SSLConfig ssl_config = kDefaultSSLConfig;
2808 ssl_config.channel_id_enabled = true;
2810 int rv;
2811 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
2813 EXPECT_EQ(ERR_UNEXPECTED, rv);
2814 EXPECT_FALSE(sock_->IsConnected());
2817 } // namespace net