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

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: Morning LKGR Rebase. 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
« no previous file with comments | « no previous file | chrome/browser/extensions/api/sockets_tcp/sockets_tcp_apitest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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, int(int32));
49 MOCK_METHOD1(SetSendBufferSize, int(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 MOCK_CONST_METHOD0(GetChannelIDService, net::ChannelIDService*());
75 virtual bool IsConnected() const OVERRIDE { return true; }
76
77 private:
78 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket);
79 };
80
81 class MockTCPSocket : public net::TCPClientSocket {
82 public:
83 explicit MockTCPSocket(const net::AddressList& address_list)
84 : net::TCPClientSocket(address_list, NULL, net::NetLog::Source()) {}
85
86 MOCK_METHOD3(Read,
87 int(net::IOBuffer* buf,
88 int buf_len,
89 const net::CompletionCallback& callback));
90 MOCK_METHOD3(Write,
91 int(net::IOBuffer* buf,
92 int buf_len,
93 const net::CompletionCallback& callback));
94 MOCK_METHOD2(SetKeepAlive, bool(bool enable, int delay));
95 MOCK_METHOD1(SetNoDelay, bool(bool no_delay));
96
97 virtual bool IsConnected() const OVERRIDE { return true; }
98
99 private:
100 DISALLOW_COPY_AND_ASSIGN(MockTCPSocket);
101 };
102
103 class CompleteHandler {
104 public:
105 CompleteHandler() {}
106 MOCK_METHOD1(OnComplete, void(int result_code));
107 MOCK_METHOD2(OnReadComplete,
108 void(int result_code, scoped_refptr<net::IOBuffer> io_buffer));
109 MOCK_METHOD2(OnAccept, void(int, net::TCPClientSocket*));
110
111 private:
112 DISALLOW_COPY_AND_ASSIGN(CompleteHandler);
113 };
114
115 class TLSSocketTest : public ::testing::Test {
116 public:
117 TLSSocketTest() {}
118
119 virtual void SetUp() {
120 net::AddressList address_list;
121 // |ssl_socket_| is owned by |socket_|. TLSSocketTest keeps a pointer to
122 // it to expect invocations from TLSSocket to |ssl_socket_|.
123 scoped_ptr<MockSSLClientSocket> ssl_sock(new MockSSLClientSocket);
124 ssl_socket_ = ssl_sock.get();
125 socket_.reset(new TLSSocket(ssl_sock.PassAs<net::StreamSocket>(),
126 "test_extension_id"));
127 EXPECT_CALL(*ssl_socket_, Disconnect()).Times(1);
128 };
129
130 virtual void TearDown() {
131 ssl_socket_ = NULL;
132 socket_.reset();
133 };
134
135 protected:
136 MockSSLClientSocket* ssl_socket_;
137 scoped_ptr<TLSSocket> socket_;
138 };
139
140 // Verify that a Read() on TLSSocket will pass through into a Read() on
141 // |ssl_socket_| and invoke its completion callback.
142 TEST_F(TLSSocketTest, TestTLSSocketRead) {
143 CompleteHandler handler;
144
145 EXPECT_CALL(*ssl_socket_, Read(_, _, _)).Times(1);
146 EXPECT_CALL(handler, OnReadComplete(_, _)).Times(1);
147
148 const int count = 512;
149 socket_->Read(
150 count,
151 base::Bind(&CompleteHandler::OnReadComplete, base::Unretained(&handler)));
152 }
153
154 // Verify that a Write() on a TLSSocket will pass through to Write()
155 // invocations on |ssl_socket_|, handling partial writes correctly, and calls
156 // the completion callback correctly.
157 TEST_F(TLSSocketTest, TestTLSSocketWrite) {
158 CompleteHandler handler;
159 net::CompletionCallback callback;
160
161 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(2).WillRepeatedly(
162 DoAll(SaveArg<2>(&callback), Return(128)));
163 EXPECT_CALL(handler, OnComplete(_)).Times(1);
164
165 scoped_refptr<net::IOBufferWithSize> io_buffer(
166 new net::IOBufferWithSize(256));
167 socket_->Write(
168 io_buffer.get(),
169 io_buffer->size(),
170 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
171 }
172
173 // Simulate a blocked Write, and verify that, when simulating the Write going
174 // through, the callback gets invoked.
175 TEST_F(TLSSocketTest, TestTLSSocketBlockedWrite) {
176 CompleteHandler handler;
177 net::CompletionCallback callback;
178
179 // Return ERR_IO_PENDING to say the Write()'s blocked. Save the |callback|
180 // Write()'s passed.
181 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(2).WillRepeatedly(
182 DoAll(SaveArg<2>(&callback), Return(net::ERR_IO_PENDING)));
183
184 scoped_refptr<net::IOBufferWithSize> io_buffer(new net::IOBufferWithSize(42));
185 socket_->Write(
186 io_buffer.get(),
187 io_buffer->size(),
188 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
189
190 // After the simulated asynchronous writes come back (via calls to
191 // callback.Run()), hander's OnComplete() should get invoked with the total
192 // amount written.
193 EXPECT_CALL(handler, OnComplete(42)).Times(1);
194 callback.Run(40);
195 callback.Run(2);
196 }
197
198 // Simulate multiple blocked Write()s.
199 TEST_F(TLSSocketTest, TestTLSSocketBlockedWriteReentry) {
200 const int kNumIOs = 5;
201 CompleteHandler handlers[kNumIOs];
202 net::CompletionCallback callback;
203 scoped_refptr<net::IOBufferWithSize> io_buffers[kNumIOs];
204
205 // The implementation of TLSSocket::Write() is inherited from
206 // Socket::Write(), which implements an internal write queue that wraps
207 // TLSSocket::WriteImpl(). Each call from TLSSocket::WriteImpl() will invoke
208 // |ssl_socket_|'s Write() (mocked here). Save the |callback| (assume they
209 // will all be equivalent), and return ERR_IO_PENDING, to indicate a blocked
210 // request. The mocked SSLClientSocket::Write() will get one request per
211 // TLSSocket::Write() request invoked on |socket_| below.
212 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).Times(kNumIOs).WillRepeatedly(
213 DoAll(SaveArg<2>(&callback), Return(net::ERR_IO_PENDING)));
214
215 // Send out |kNuMIOs| requests, each with a different size.
216 for (int i = 0; i < kNumIOs; i++) {
217 io_buffers[i] = new net::IOBufferWithSize(128 + i * 50);
218 socket_->Write(io_buffers[i].get(),
219 io_buffers[i]->size(),
220 base::Bind(&CompleteHandler::OnComplete,
221 base::Unretained(&handlers[i])));
222
223 // Set up expectations on all |kNumIOs| handlers.
224 EXPECT_CALL(handlers[i], OnComplete(io_buffers[i]->size())).Times(1);
225 }
226
227 // Finish each pending I/O. This should satisfy the expectations on the
228 // handlers.
229 for (int i = 0; i < kNumIOs; i++) {
230 callback.Run(128 + i * 50);
231 }
232 }
233
234 typedef std::pair<net::CompletionCallback, int> PendingCallback;
235
236 class CallbackList : public std::deque<PendingCallback> {
237 public:
238 void append(const net::CompletionCallback& cb, int arg) {
239 push_back(std::make_pair(cb, arg));
240 }
241 };
242
243 // Simulate Write()s above and below a SSLClientSocket size limit.
244 TEST_F(TLSSocketTest, TestTLSSocketLargeWrites) {
245 const int kSizeIncrement = 4096;
246 const int kNumIncrements = 10;
247 const int kFragmentIncrement = 4;
248 const int kSizeLimit = kSizeIncrement * kFragmentIncrement;
249 net::CompletionCallback callback;
250 CompleteHandler handler;
251 scoped_refptr<net::IOBufferWithSize> io_buffers[kNumIncrements];
252 CallbackList pending_callbacks;
253 size_t total_bytes_requested = 0;
254 size_t total_bytes_written = 0;
255
256 // Some implementations of SSLClientSocket may have write-size limits (e.g,
257 // max 1 TLS record, which is 16k). This test mocks a size limit at
258 // |kSizeIncrement| and calls Write() above and below that limit. It
259 // simulates SSLClientSocket::Write() behavior in only writing up to the size
260 // limit, requiring additional calls for the remaining data to be sent.
261 // Socket::Write() (and supporting methods) execute the additional calls as
262 // needed. This test verifies that this inherited implementation does
263 // properly issue additional calls, and that the total amount returned from
264 // all mocked SSLClientSocket::Write() calls is the same as originally
265 // requested.
266
267 // |ssl_socket_|'s Write() will write at most |kSizeLimit| bytes. The
268 // inherited Socket::Write() will repeatedly call |ssl_socket_|'s Write()
269 // until the entire original request is sent. Socket::Write() will queue any
270 // additional write requests until the current request is complete. A
271 // request is complete when the callback passed to Socket::WriteImpl() is
272 // invoked with an argument equal to the original number of bytes requested
273 // from Socket::Write(). If the callback is invoked with a smaller number,
274 // Socket::WriteImpl() will get repeatedly invoked until the sum of the
275 // callbacks' arguments is equal to the original requested amount.
276 EXPECT_CALL(*ssl_socket_, Write(_, _, _)).WillRepeatedly(
277 DoAll(WithArgs<2, 1>(Invoke(&pending_callbacks, &CallbackList::append)),
278 Return(net::ERR_IO_PENDING)));
279
280 // Observe what comes back from Socket::Write() here.
281 EXPECT_CALL(handler, OnComplete(Gt(0))).Times(kNumIncrements);
282
283 // Send out |kNumIncrements| requests, each with a different size. The
284 // last request is the same size as the first, and the ones in the middle
285 // are monotonically increasing from the first.
286 for (int i = 0; i < kNumIncrements; i++) {
287 const bool last = i == (kNumIncrements - 1);
288 io_buffers[i] = new net::IOBufferWithSize(last ? kSizeIncrement
289 : kSizeIncrement * (i + 1));
290 total_bytes_requested += io_buffers[i]->size();
291
292 // Invoke Socket::Write(). This will invoke |ssl_socket_|'s Write(), which
293 // this test mocks out. That mocked Write() is in an asynchronous waiting
294 // state until the passed callback (saved in the EXPECT_CALL for
295 // |ssl_socket_|'s Write()) is invoked.
296 socket_->Write(
297 io_buffers[i].get(),
298 io_buffers[i]->size(),
299 base::Bind(&CompleteHandler::OnComplete, base::Unretained(&handler)));
300 }
301
302 // Invoke callbacks for pending I/Os. These can synchronously invoke more of
303 // |ssl_socket_|'s Write() as needed. The callback checks how much is left
304 // in the request, and then starts issuing any queued Socket::Write()
305 // invocations.
306 while (!pending_callbacks.empty()) {
307 PendingCallback cb = pending_callbacks.front();
308 pending_callbacks.pop_front();
309
310 int amount_written_invocation = std::min(kSizeLimit, cb.second);
311 total_bytes_written += amount_written_invocation;
312 cb.first.Run(amount_written_invocation);
313 }
314
315 ASSERT_EQ(total_bytes_requested, total_bytes_written)
316 << "There should be exactly as many bytes written as originally "
317 << "requested to Write().";
318 }
319
320 } // namespace extensions
OLDNEW
« no previous file with comments | « no previous file | chrome/browser/extensions/api/sockets_tcp/sockets_tcp_apitest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698