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