Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1326)

Side by Side Diff: chrome/browser/extensions/api/socket/tls_socket_unittest.cc

Issue 76403004: An implementation of chrome.socket.secure(). (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Stop using Profile and move completely to URLRequestContext. Created 6 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright 2013 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 "extensions/browser/api/socket/tls_socket.h"
6
7 #include <deque>
8 #include <utility>
9
10 #include "base/memory/scoped_ptr.h"
11 #include "base/strings/string_piece.h"
12 #include "net/base/address_list.h"
13 #include "net/base/completion_callback.h"
14 #include "net/base/io_buffer.h"
15 #include "net/base/net_errors.h"
16 #include "net/base/rand_callback.h"
17 #include "net/socket/ssl_client_socket.h"
18 #include "net/socket/tcp_client_socket.h"
19 #include "testing/gmock/include/gmock/gmock.h"
20
21 using testing::_;
22 using testing::DoAll;
23 using testing::Invoke;
24 using testing::Gt;
25 using testing::Return;
26 using testing::SaveArg;
27 using testing::WithArgs;
28 using base::StringPiece;
29
30 namespace net {
31 class ServerBoundCertService;
32 }
33
34 namespace extensions {
35
36 class MockSSLClientSocket : public net::SSLClientSocket {
37 public:
38 MockSSLClientSocket() {}
39 MOCK_METHOD0(Disconnect, void());
40 MOCK_METHOD3(Read,
41 int(net::IOBuffer* buf,
42 int buf_len,
43 const net::CompletionCallback& callback));
44 MOCK_METHOD3(Write,
45 int(net::IOBuffer* buf,
46 int buf_len,
47 const net::CompletionCallback& callback));
48 MOCK_METHOD1(SetReceiveBufferSize, bool(int32));
49 MOCK_METHOD1(SetSendBufferSize, bool(int32));
50 MOCK_METHOD1(Connect, int(const CompletionCallback&));
51 MOCK_CONST_METHOD0(IsConnectedAndIdle, bool());
52 MOCK_CONST_METHOD1(GetPeerAddress, int(net::IPEndPoint*));
53 MOCK_CONST_METHOD1(GetLocalAddress, int(net::IPEndPoint*));
54 MOCK_CONST_METHOD0(NetLog, const net::BoundNetLog&());
55 MOCK_METHOD0(SetSubresourceSpeculation, void());
56 MOCK_METHOD0(SetOmniboxSpeculation, void());
57 MOCK_CONST_METHOD0(WasEverUsed, bool());
58 MOCK_CONST_METHOD0(UsingTCPFastOpen, bool());
59 MOCK_METHOD1(GetSSLInfo, bool(net::SSLInfo*));
60 MOCK_METHOD5(ExportKeyingMaterial,
61 int(const StringPiece&,
62 bool,
63 const StringPiece&,
64 unsigned char*,
65 unsigned int));
66 MOCK_METHOD1(GetTLSUniqueChannelBinding, int(std::string*));
67 MOCK_METHOD1(GetSSLCertRequestInfo, void(net::SSLCertRequestInfo*));
68 MOCK_METHOD2(GetNextProto,
69 net::SSLClientSocket::NextProtoStatus(std::string*,
70 std::string*));
71 MOCK_CONST_METHOD0(GetServerBoundCertService, net::ServerBoundCertService*());
72 MOCK_CONST_METHOD0(GetUnverifiedServerCertificateChain,
73 scoped_refptr<net::X509Certificate>());
74 virtual bool IsConnected() const OVERRIDE { return true; }
75
76 private:
77 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket);
78 };
79
80 class MockTCPSocket : public net::TCPClientSocket {
81 public:
82 explicit MockTCPSocket(const net::AddressList& address_list)
83 : net::TCPClientSocket(address_list, NULL, net::NetLog::Source()) {}
84
85 MOCK_METHOD3(Read,
86 int(net::IOBuffer* buf,
87 int buf_len,
88 const net::CompletionCallback& callback));
89 MOCK_METHOD3(Write,
90 int(net::IOBuffer* buf,
91 int buf_len,
92 const net::CompletionCallback& callback));
93 MOCK_METHOD2(SetKeepAlive, bool(bool enable, int delay));
94 MOCK_METHOD1(SetNoDelay, bool(bool no_delay));
95
96 virtual bool IsConnected() const OVERRIDE { return true; }
97
98 private:
99 DISALLOW_COPY_AND_ASSIGN(MockTCPSocket);
100 };
101
102 class CompleteHandler {
103 public:
104 CompleteHandler() {}
105 MOCK_METHOD1(OnComplete, void(int result_code));
106 MOCK_METHOD2(OnReadComplete,
107 void(int result_code, scoped_refptr<net::IOBuffer> io_buffer));
108 MOCK_METHOD2(OnAccept, void(int, net::TCPClientSocket*));
109
110 private:
111 DISALLOW_COPY_AND_ASSIGN(CompleteHandler);
112 };
113
114 static const char FAKE_ID[] = "faktetesttlssocketunittest";
115
116 class TLSSocketTest : public ::testing::Test {
117 public:
118 TLSSocketTest() {}
119
120 virtual void SetUp() {
121 net::AddressList address_list;
122 // |ssl_socket_| is owned by |socket_|. TLSSocketTest keeps a pointer to
123 // it to expect invocations from TLSSocket to |ssl_socket_|.
124 scoped_ptr<MockSSLClientSocket> ssl_sock(new MockSSLClientSocket);
125 ssl_socket_ = ssl_sock.get();
126 socket_.reset(new TLSSocket(ssl_sock.PassAs<net::StreamSocket>(),
127 "test_extension_id"));
128 EXPECT_CALL(*ssl_socket_, Disconnect()).Times(1);
129 };
130
131 virtual void TearDown() {
132 ssl_socket_ = NULL;
133 socket_.reset();
134 };
135
136 protected:
137 MockSSLClientSocket* ssl_socket_;
138 scoped_ptr<TLSSocket> socket_;
139 };
140
141 // Verify that a Read() on TLSSocket will pass through into a Read() on
142 // |ssl_socket_| and invoke its completion callback.
143 TEST_F(TLSSocketTest, TestTLSSocketRead) {
144 CompleteHandler handler;
145
146 EXPECT_CALL(*ssl_socket_, Read(_, _, _)).Times(1);
147 EXPECT_CALL(handler, OnReadComplete(_, _)).Times(1);
148
149 const int count = 512;
150 socket_->Read(
151 count,
152 base::Bind(&CompleteHandler::OnReadComplete, base::Unretained(&handler)));
153 }
154
155 // Verify that a Write() on a TLSSocket will pass through to Write()
156 // invocations on |ssl_socket_|, handling partial writes correctly, and calls
157 // the completion callback correctly.
158 TEST_F(TLSSocketTest, TestTLSSocketWrite) {
159 CompleteHandler handler;
160 net::CompletionCallback callback;
161
162 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(2).WillRepeatedly(
163 DoAll(SaveArg<2>(&callback), Return(128)));
164 EXPECT_CALL(handler, OnComplete(_)).Times(1);
165
166 scoped_refptr<net::IOBufferWithSize> io_buffer(
167 new net::IOBufferWithSize(256));
168 socket_->Write(
169 io_buffer.get(),
170 io_buffer->size(),
171 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
172 }
173
174 // Simulate a blocked Write, and verify that, when simulating the Write going
175 // through, the callback gets invoked.
176 TEST_F(TLSSocketTest, TestTLSSocketBlockedWrite) {
177 CompleteHandler handler;
178 net::CompletionCallback callback;
179
180 // Return ERR_IO_PENDING to say the Write()'s blocked. Save the |callback|
181 // Write()'s passed.
182 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(2).WillRepeatedly(
183 DoAll(SaveArg<2>(&callback), Return(net::ERR_IO_PENDING)));
184
185 scoped_refptr<net::IOBufferWithSize> io_buffer(new net::IOBufferWithSize(42));
186 socket_->Write(
187 io_buffer.get(),
188 io_buffer->size(),
189 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
190
191 // After the simulated asynchronous writes come back (via calls to
192 // callback.Run()), hander's OnComplete() should get invoked with the total
193 // amount written.
194 EXPECT_CALL(handler, OnComplete(42)).Times(1);
195 callback.Run(40);
196 callback.Run(2);
197 }
198
199 // Simulate multiple blocked Write()s.
200 TEST_F(TLSSocketTest, TestTLSSocketBlockedWriteReentry) {
201 const int kNumIOs = 5;
202 CompleteHandler handlers[kNumIOs];
203 net::CompletionCallback callback;
204 scoped_refptr<net::IOBufferWithSize> io_buffers[kNumIOs];
205
206 // The implementation of TLSSocket::Write() is inherited from
207 // Socket::Write(), which implements an internal write queue that wraps
208 // TLSSocket::WriteImpl(). Each call from TLSSocket::WriteImpl() will invoke
209 // |ssl_socket_|'s Write() (mocked here). Save the |callback| (assume they
210 // will all be equivalent), and return ERR_IO_PENDING, to indicate a blocked
211 // request. The mocked SSLClientSocket::Write() will get one request per
212 // TLSSocket::Write() request invoked on |socket_| below.
213 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(kNumIOs).WillRepeatedly(
214 DoAll(SaveArg<2>(&callback), Return(net::ERR_IO_PENDING)));
215
216 // Send out |kNuMIOs| requests, each with a different size.
217 for (int i = 0; i < kNumIOs; i++) {
218 io_buffers[i] = new net::IOBufferWithSize(128 + i * 50);
219 socket_->Write(io_buffers[i].get(),
220 io_buffers[i]->size(),
221 base::Bind(&CompleteHandler::OnComplete,
222 base::Unretained(&handlers[i])));
223
224 // Set up expectations on all |kNumIOs| handlers.
225 EXPECT_CALL(handlers[i], OnComplete(io_buffers[i]->size())).Times(1);
226 }
227
228 // Finish each pending I/O. This should satisfy the expectations on the
229 // handlers.
230 for (int i = 0; i < kNumIOs; i++) {
231 callback.Run(128 + i * 50);
232 }
233 }
234
235 typedef std::pair<net::CompletionCallback, int> PendingCallback;
236
237 class CallbackList : public std::deque<PendingCallback> {
238 public:
239 void append(const net::CompletionCallback& cb, int arg) {
240 push_back(std::make_pair(cb, arg));
241 }
242 };
243
244 // Simulate Write()s above and below a SSLClientSocket size limit.
245 TEST_F(TLSSocketTest, TestTLSSocketLargeWrites) {
246 const int kSizeIncrement = 4096;
247 const int kNumIncrements = 10;
248 const int kFragmentIncrement = 4;
249 const int kSizeLimit = kSizeIncrement * kFragmentIncrement;
250 net::CompletionCallback callback;
251 CompleteHandler handler;
252 scoped_refptr<net::IOBufferWithSize> io_buffers[kNumIncrements];
253 CallbackList pending_callbacks;
254 size_t total_bytes_requested = 0;
255 size_t total_bytes_written = 0;
256
257 // Some implementations of SSLClientSocket may have write-size limits (e.g,
258 // max 1 TLS record, which is 16k). This test mocks a size limit at
259 // |kSizeIncrement| and calls Write() above and below that limit. It
260 // simulates SSLClientSocket::Write() behavior in only writing up to the size
261 // limit, requiring additional calls for the remaining data to be sent.
262 // Socket::Write() (and supporting methods) execute the additional calls as
263 // needed. This test verifies that this inherited implementation does
264 // properly issue additional calls, and that the total amount returned from
265 // all mocked SSLClientSocket::Write() calls is the same as originally
266 // requested.
267
268 // |ssl_socket_|'s Write() will write at most |kSizeLimit| bytes. The
269 // inherited Socket::Write() will repeatedly call |ssl_socket_|'s Write()
270 // until the entire original request is sent. Socket::Write() will queue any
271 // additional write requests until the current request is complete. A
272 // request is complete when the callback passed to Socket::WriteImpl() is
273 // invoked with an argument equal to the original number of bytes requested
274 // from Socket::Write(). If the callback is invoked with a smaller number,
275 // Socket::WriteImpl() will get repeatedly invoked until the sum of the
276 // callbacks' arguments is equal to the original requested amount.
277 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).WillRepeatedly(
278 DoAll(WithArgs<2, 1>(Invoke(&pending_callbacks, &CallbackList::append)),
279 Return(net::ERR_IO_PENDING)));
280
281 // Observe what comes back from Socket::Write() here.
282 EXPECT_CALL(handler, OnComplete(Gt(0))).Times(kNumIncrements);
283
284 // Send out |kNumIncrements| requests, each with a different size. The
285 // last request is the same size as the first, and the ones in the middle
286 // are monotonically increasing from the first.
287 for (int i = 0; i < kNumIncrements; i++) {
288 const bool last = i == (kNumIncrements - 1);
289 io_buffers[i] = new net::IOBufferWithSize(last ? kSizeIncrement
290 : kSizeIncrement * (i + 1));
291 total_bytes_requested += io_buffers[i]->size();
292
293 // Invoke Socket::Write(). This will invoke |ssl_socket_|'s Write(), which
294 // this test mocks out. That mocked Write() is in an asynchronous waiting
295 // state until the passed callback (saved in the EXPECT_CALL for
296 // |ssl_socket_|'s Write()) is invoked.
297 socket_->Write(
298 io_buffers[i].get(),
299 io_buffers[i]->size(),
300 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
301 }
302
303 // Invoke callbacks for pending I/Os. These can synchronously invoke more of
304 // |ssl_socket_|'s Write() as needed. The callback checks how much is left
305 // in the request, and then starts issuing any queued Socket::Write()
306 // invocations.
307 while (!pending_callbacks.empty()) {
308 PendingCallback cb = pending_callbacks.front();
309 pending_callbacks.pop_front();
310
311 int amount_written_invocation = std::min(kSizeLimit, cb.second);
312 total_bytes_written += amount_written_invocation;
313 cb.first.Run(amount_written_invocation);
314 }
315
316 ASSERT_EQ(total_bytes_requested, total_bytes_written)
317 << "There should be exactly as many bytes written as originally "
318 << "requested to Write().";
319 }
320
321 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698