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

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

Powered by Google App Engine
This is Rietveld 408576698