Add ICU message format support
[chromium-blink-merge.git] / extensions / browser / api / cast_channel / cast_socket_unittest.cc
bloba046bd2f26c988b6498922bb2ede73b3dcd097ef
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/browser/api/cast_channel/cast_socket.h"
7 #include <vector>
9 #include "base/memory/weak_ptr.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/run_loop.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/sys_byteorder.h"
14 #include "base/test/simple_test_tick_clock.h"
15 #include "base/timer/mock_timer.h"
16 #include "extensions/browser/api/cast_channel/cast_auth_util.h"
17 #include "extensions/browser/api/cast_channel/cast_framer.h"
18 #include "extensions/browser/api/cast_channel/cast_message_util.h"
19 #include "extensions/browser/api/cast_channel/cast_test_util.h"
20 #include "extensions/browser/api/cast_channel/cast_transport.h"
21 #include "extensions/browser/api/cast_channel/logger.h"
22 #include "extensions/common/api/cast_channel/cast_channel.pb.h"
23 #include "net/base/address_list.h"
24 #include "net/base/net_errors.h"
25 #include "net/base/net_util.h"
26 #include "net/log/test_net_log.h"
27 #include "net/socket/socket_test_util.h"
28 #include "net/socket/ssl_client_socket.h"
29 #include "net/socket/tcp_client_socket.h"
30 #include "net/ssl/ssl_info.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
34 const int64 kDistantTimeoutMillis = 100000; // 100 seconds (never hit).
36 using ::testing::_;
37 using ::testing::A;
38 using ::testing::DoAll;
39 using ::testing::Invoke;
40 using ::testing::InvokeArgument;
41 using ::testing::NotNull;
42 using ::testing::Return;
43 using ::testing::SaveArg;
45 namespace extensions {
46 namespace api {
47 namespace cast_channel {
48 const char kAuthNamespace[] = "urn:x-cast:com.google.cast.tp.deviceauth";
50 // Returns an auth challenge message inline.
51 CastMessage CreateAuthChallenge() {
52 CastMessage output;
53 CreateAuthChallengeMessage(&output);
54 return output;
57 // Returns an auth challenge response message inline.
58 CastMessage CreateAuthReply() {
59 CastMessage output;
60 output.set_protocol_version(CastMessage::CASTV2_1_0);
61 output.set_source_id("sender-0");
62 output.set_destination_id("receiver-0");
63 output.set_payload_type(CastMessage::BINARY);
64 output.set_payload_binary("abcd");
65 output.set_namespace_(kAuthNamespace);
66 return output;
69 CastMessage CreateTestMessage() {
70 CastMessage test_message;
71 test_message.set_protocol_version(CastMessage::CASTV2_1_0);
72 test_message.set_namespace_("ns");
73 test_message.set_source_id("source");
74 test_message.set_destination_id("dest");
75 test_message.set_payload_type(CastMessage::STRING);
76 test_message.set_payload_utf8("payload");
77 return test_message;
80 class MockTCPSocket : public net::TCPClientSocket {
81 public:
82 explicit MockTCPSocket(const net::MockConnect& connect_data)
83 : TCPClientSocket(net::AddressList(), nullptr, net::NetLog::Source()),
84 connect_data_(connect_data),
85 do_nothing_(false) {}
87 explicit MockTCPSocket(bool do_nothing)
88 : TCPClientSocket(net::AddressList(), nullptr, net::NetLog::Source()) {
89 CHECK(do_nothing);
90 do_nothing_ = do_nothing;
93 virtual int Connect(const net::CompletionCallback& callback) {
94 if (do_nothing_) {
95 // Stall the I/O event loop.
96 return net::ERR_IO_PENDING;
99 if (connect_data_.mode == net::ASYNC) {
100 CHECK_NE(connect_data_.result, net::ERR_IO_PENDING);
101 base::MessageLoop::current()->PostTask(
102 FROM_HERE,
103 base::Bind(callback, connect_data_.result));
104 return net::ERR_IO_PENDING;
105 } else {
106 return connect_data_.result;
110 virtual bool SetKeepAlive(bool enable, int delay) {
111 // Always return true in tests
112 return true;
115 virtual bool SetNoDelay(bool no_delay) {
116 // Always return true in tests
117 return true;
120 MOCK_METHOD3(Read,
121 int(net::IOBuffer*, int, const net::CompletionCallback&));
122 MOCK_METHOD3(Write,
123 int(net::IOBuffer*, int, const net::CompletionCallback&));
125 virtual void Disconnect() {
126 // Do nothing in tests
129 private:
130 net::MockConnect connect_data_;
131 bool do_nothing_;
133 DISALLOW_COPY_AND_ASSIGN(MockTCPSocket);
136 class MockDelegate : public CastTransport::Delegate {
137 public:
138 MockDelegate() {}
139 virtual ~MockDelegate() {}
140 MOCK_METHOD1(OnError, void(ChannelError error_state));
141 MOCK_METHOD1(OnMessage, void(const CastMessage& message));
142 MOCK_METHOD0(Start, void());
144 private:
145 DISALLOW_COPY_AND_ASSIGN(MockDelegate);
148 class CompleteHandler {
149 public:
150 CompleteHandler() {}
151 MOCK_METHOD1(OnCloseComplete, void(int result));
152 MOCK_METHOD1(OnConnectComplete, void(ChannelError error_state));
153 MOCK_METHOD1(OnWriteComplete, void(int result));
154 MOCK_METHOD1(OnReadComplete, void(int result));
156 private:
157 DISALLOW_COPY_AND_ASSIGN(CompleteHandler);
160 class TestCastSocket : public CastSocketImpl {
161 public:
162 static scoped_ptr<TestCastSocket> Create(
163 Logger* logger,
164 uint64 device_capabilities = cast_channel::CastDeviceCapability::NONE) {
165 return scoped_ptr<TestCastSocket>(
166 new TestCastSocket(CreateIPEndPointForTest(), CHANNEL_AUTH_TYPE_SSL,
167 kDistantTimeoutMillis, logger, device_capabilities));
170 static scoped_ptr<TestCastSocket> CreateSecure(
171 Logger* logger,
172 uint64 device_capabilities = cast_channel::CastDeviceCapability::NONE) {
173 return scoped_ptr<TestCastSocket>(new TestCastSocket(
174 CreateIPEndPointForTest(), CHANNEL_AUTH_TYPE_SSL_VERIFIED,
175 kDistantTimeoutMillis, logger, device_capabilities));
178 explicit TestCastSocket(const net::IPEndPoint& ip_endpoint,
179 ChannelAuthType channel_auth,
180 int64 timeout_ms,
181 Logger* logger,
182 uint64 device_capabilities)
183 : CastSocketImpl("some_extension_id",
184 ip_endpoint,
185 channel_auth,
186 &capturing_net_log_,
187 base::TimeDelta::FromMilliseconds(timeout_ms),
188 false,
189 logger,
190 device_capabilities),
191 ip_(ip_endpoint),
192 connect_index_(0),
193 extract_cert_result_(true),
194 verify_challenge_result_(true),
195 verify_challenge_disallow_(false),
196 tcp_unresponsive_(false),
197 mock_timer_(new base::MockTimer(false, false)),
198 mock_transport_(nullptr) {}
200 ~TestCastSocket() override {}
202 void SetupMockTransport() {
203 mock_transport_ = new MockCastTransport;
204 SetTransportForTesting(make_scoped_ptr(mock_transport_));
207 // Socket connection helpers.
208 void SetupTcp1Connect(net::IoMode mode, int result) {
209 tcp_connect_data_[0].reset(new net::MockConnect(mode, result));
211 void SetupTcp2Connect(net::IoMode mode, int result) {
212 tcp_connect_data_[1].reset(new net::MockConnect(mode, result));
214 void SetupSsl1Connect(net::IoMode mode, int result) {
215 ssl_connect_data_[0].reset(new net::MockConnect(mode, result));
217 void SetupSsl2Connect(net::IoMode mode, int result) {
218 ssl_connect_data_[1].reset(new net::MockConnect(mode, result));
221 // Socket I/O helpers.
222 void AddWriteResult(const net::MockWrite& write) {
223 writes_.push_back(write);
225 void AddWriteResult(net::IoMode mode, int result) {
226 AddWriteResult(net::MockWrite(mode, result));
228 void AddWriteResultForData(net::IoMode mode, const std::string& msg) {
229 AddWriteResult(mode, msg.size());
231 void AddReadResult(const net::MockRead& read) {
232 reads_.push_back(read);
234 void AddReadResult(net::IoMode mode, int result) {
235 AddReadResult(net::MockRead(mode, result));
237 void AddReadResultForData(net::IoMode mode, const std::string& data) {
238 AddReadResult(net::MockRead(mode, data.c_str(), data.size()));
241 // Helpers for modifying other connection-related behaviors.
242 void SetupTcp1ConnectUnresponsive() { tcp_unresponsive_ = true; }
244 void SetExtractCertResult(bool value) {
245 extract_cert_result_ = value;
248 void SetVerifyChallengeResult(bool value) {
249 verify_challenge_result_ = value;
252 void TriggerTimeout() {
253 mock_timer_->Fire();
256 bool TestVerifyChannelPolicyNone() {
257 AuthResult authResult;
258 return VerifyChannelPolicy(authResult);
261 bool TestVerifyChannelPolicyAudioOnly() {
262 AuthResult authResult;
263 authResult.channel_policies |= AuthResult::POLICY_AUDIO_ONLY;
264 return VerifyChannelPolicy(authResult);
267 void DisallowVerifyChallengeResult() { verify_challenge_disallow_ = true; }
269 MockCastTransport* GetMockTransport() {
270 CHECK(mock_transport_);
271 return mock_transport_;
274 private:
275 scoped_ptr<net::TCPClientSocket> CreateTcpSocket() override {
276 if (tcp_unresponsive_) {
277 return scoped_ptr<net::TCPClientSocket>(new MockTCPSocket(true));
278 } else {
279 net::MockConnect* connect_data = tcp_connect_data_[connect_index_].get();
280 connect_data->peer_addr = ip_;
281 return scoped_ptr<net::TCPClientSocket>(new MockTCPSocket(*connect_data));
285 scoped_ptr<net::SSLClientSocket> CreateSslSocket(
286 scoped_ptr<net::StreamSocket> socket) override {
287 net::MockConnect* connect_data = ssl_connect_data_[connect_index_].get();
288 connect_data->peer_addr = ip_;
289 ++connect_index_;
291 ssl_data_.reset(new net::StaticSocketDataProvider(
292 reads_.data(), reads_.size(), writes_.data(), writes_.size()));
293 ssl_data_->set_connect_data(*connect_data);
294 // NOTE: net::MockTCPClientSocket inherits from net::SSLClientSocket !!
295 return scoped_ptr<net::SSLClientSocket>(
296 new net::MockTCPClientSocket(
297 net::AddressList(), &capturing_net_log_, ssl_data_.get()));
300 bool ExtractPeerCert(std::string* cert) override {
301 if (extract_cert_result_)
302 cert->assign("dummy_test_cert");
303 return extract_cert_result_;
306 bool VerifyChallengeReply() override {
307 EXPECT_FALSE(verify_challenge_disallow_);
308 return verify_challenge_result_;
311 base::Timer* GetTimer() override { return mock_timer_.get(); }
313 net::TestNetLog capturing_net_log_;
314 net::IPEndPoint ip_;
315 // Simulated connect data
316 scoped_ptr<net::MockConnect> tcp_connect_data_[2];
317 scoped_ptr<net::MockConnect> ssl_connect_data_[2];
318 // Simulated read / write data
319 std::vector<net::MockWrite> writes_;
320 std::vector<net::MockRead> reads_;
321 scoped_ptr<net::SocketDataProvider> ssl_data_;
322 // Number of times Connect method is called
323 size_t connect_index_;
324 // Simulated result of peer cert extraction.
325 bool extract_cert_result_;
326 // Simulated result of verifying challenge reply.
327 bool verify_challenge_result_;
328 bool verify_challenge_disallow_;
329 // If true, makes TCP connection process stall. For timeout testing.
330 bool tcp_unresponsive_;
331 scoped_ptr<base::MockTimer> mock_timer_;
332 MockCastTransport* mock_transport_;
334 DISALLOW_COPY_AND_ASSIGN(TestCastSocket);
337 class CastSocketTest : public testing::Test {
338 public:
339 CastSocketTest()
340 : logger_(new Logger(
341 scoped_ptr<base::TickClock>(new base::SimpleTestTickClock),
342 base::TimeTicks())),
343 delegate_(new MockDelegate) {}
344 ~CastSocketTest() override {}
346 void SetUp() override { EXPECT_CALL(*delegate_, OnMessage(_)).Times(0); }
348 void TearDown() override {
349 if (socket_.get()) {
350 EXPECT_CALL(handler_, OnCloseComplete(net::OK));
351 socket_->Close(base::Bind(&CompleteHandler::OnCloseComplete,
352 base::Unretained(&handler_)));
356 void CreateCastSocket() { socket_ = TestCastSocket::Create(logger_); }
358 void CreateCastSocketSecure() {
359 socket_ = TestCastSocket::CreateSecure(logger_);
362 void HandleAuthHandshake() {
363 socket_->SetupMockTransport();
364 CastMessage challenge_proto = CreateAuthChallenge();
365 EXPECT_CALL(*socket_->GetMockTransport(),
366 SendMessage(EqualsProto(challenge_proto), _))
367 .WillOnce(RunCompletionCallback<1>(net::OK));
368 EXPECT_CALL(*socket_->GetMockTransport(), Start());
369 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_NONE));
370 socket_->Connect(delegate_.Pass(),
371 base::Bind(&CompleteHandler::OnConnectComplete,
372 base::Unretained(&handler_)));
373 RunPendingTasks();
374 socket_->GetMockTransport()->current_delegate()->OnMessage(
375 CreateAuthReply());
376 RunPendingTasks();
379 protected:
380 // Runs all pending tasks in the message loop.
381 void RunPendingTasks() {
382 base::RunLoop run_loop;
383 run_loop.RunUntilIdle();
386 base::MessageLoop message_loop_;
387 Logger* logger_;
388 scoped_ptr<TestCastSocket> socket_;
389 CompleteHandler handler_;
390 scoped_ptr<MockDelegate> delegate_;
392 private:
393 DISALLOW_COPY_AND_ASSIGN(CastSocketTest);
396 // Tests connecting and closing the socket.
397 TEST_F(CastSocketTest, TestConnectAndClose) {
398 CreateCastSocket();
399 socket_->SetupMockTransport();
400 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
401 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::OK);
403 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_NONE));
404 socket_->Connect(delegate_.Pass(),
405 base::Bind(&CompleteHandler::OnConnectComplete,
406 base::Unretained(&handler_)));
407 RunPendingTasks();
409 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
410 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
412 EXPECT_CALL(handler_, OnCloseComplete(net::OK));
413 socket_->Close(base::Bind(&CompleteHandler::OnCloseComplete,
414 base::Unretained(&handler_)));
415 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
416 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
419 // Tests that the following connection flow works:
420 // - TCP connection succeeds (async)
421 // - SSL connection succeeds (async)
422 TEST_F(CastSocketTest, TestConnect) {
423 CreateCastSocket();
424 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
425 socket_->SetupSsl1Connect(net::ASYNC, net::OK);
426 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
428 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_NONE));
429 socket_->Connect(delegate_.Pass(),
430 base::Bind(&CompleteHandler::OnConnectComplete,
431 base::Unretained(&handler_)));
432 RunPendingTasks();
434 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
435 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
438 // Tests that the following connection flow works:
439 // - TCP connection fails (async)
440 TEST_F(CastSocketTest, TestConnectFails) {
441 CreateCastSocket();
442 socket_->SetupTcp1Connect(net::ASYNC, net::ERR_FAILED);
444 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_CONNECT_ERROR));
445 socket_->Connect(delegate_.Pass(),
446 base::Bind(&CompleteHandler::OnConnectComplete,
447 base::Unretained(&handler_)));
448 RunPendingTasks();
450 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
451 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
452 EXPECT_EQ(proto::TCP_SOCKET_CONNECT_COMPLETE,
453 logger_->GetLastErrors(socket_->id()).event_type);
454 EXPECT_EQ(net::ERR_FAILED,
455 logger_->GetLastErrors(socket_->id()).net_return_value);
458 // Test that the following connection flow works:
459 // - TCP connection succeeds (async)
460 // - SSL connection fails with cert error (async)
461 // - Cert is extracted successfully
462 // - Second TCP connection succeeds (async)
463 // - Second SSL connection succeeds (async)
464 TEST_F(CastSocketTest, TestConnectTwoStep) {
465 CreateCastSocket();
466 socket_->SetupMockTransport();
467 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
468 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
469 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
470 socket_->SetupSsl2Connect(net::ASYNC, net::OK);
472 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_NONE));
473 socket_->Connect(delegate_.Pass(),
474 base::Bind(&CompleteHandler::OnConnectComplete,
475 base::Unretained(&handler_)));
476 RunPendingTasks();
477 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
478 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
481 // Test that the following connection flow works:
482 // - TCP connection succeeds (async)
483 // - SSL connection fails with cert error (async)
484 // - Cert is extracted successfully
485 // - Second TCP connection succeeds (async)
486 // - Second SSL connection fails (async)
487 // - The flow should NOT be tried again
488 TEST_F(CastSocketTest, TestConnectMaxTwoAttempts) {
489 CreateCastSocket();
490 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
491 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
492 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
493 socket_->SetupSsl2Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
495 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR));
496 socket_->Connect(delegate_.Pass(),
497 base::Bind(&CompleteHandler::OnConnectComplete,
498 base::Unretained(&handler_)));
499 RunPendingTasks();
501 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
502 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR,
503 socket_->error_state());
506 // Tests that the following connection flow works:
507 // - TCP connection succeeds (async)
508 // - SSL connection fails with cert error (async)
509 // - Cert is extracted successfully
510 // - Second TCP connection succeeds (async)
511 // - Second SSL connection succeeds (async)
512 // - Challenge request is sent (async)
513 // - Challenge response is received (async)
514 // - Credentials are verified successfuly
515 TEST_F(CastSocketTest, TestConnectFullSecureFlowAsync) {
516 CreateCastSocketSecure();
517 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
518 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
519 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
520 socket_->SetupSsl2Connect(net::ASYNC, net::OK);
522 HandleAuthHandshake();
524 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
525 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
528 // Tests that the following connection flow works:
529 // - TCP connection succeeds (sync)
530 // - SSL connection fails with cert error (sync)
531 // - Cert is extracted successfully
532 // - Second TCP connection succeeds (sync)
533 // - Second SSL connection succeeds (sync)
534 // - Challenge request is sent (sync)
535 // - Challenge response is received (sync)
536 // - Credentials are verified successfuly
537 TEST_F(CastSocketTest, TestConnectFullSecureFlowSync) {
538 CreateCastSocketSecure();
539 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
540 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_CERT_AUTHORITY_INVALID);
541 socket_->SetupTcp2Connect(net::SYNCHRONOUS, net::OK);
542 socket_->SetupSsl2Connect(net::SYNCHRONOUS, net::OK);
544 HandleAuthHandshake();
546 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
547 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
550 // Test that an AuthMessage with a mangled namespace triggers cancelation
551 // of the connection event loop.
552 TEST_F(CastSocketTest, TestConnectAuthMessageCorrupted) {
553 CreateCastSocketSecure();
554 socket_->SetupMockTransport();
556 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
557 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
558 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
559 socket_->SetupSsl2Connect(net::ASYNC, net::OK);
561 CastMessage challenge_proto = CreateAuthChallenge();
562 EXPECT_CALL(*socket_->GetMockTransport(),
563 SendMessage(EqualsProto(challenge_proto), _))
564 .WillOnce(RunCompletionCallback<1>(net::OK));
565 EXPECT_CALL(*socket_->GetMockTransport(), Start());
566 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_TRANSPORT_ERROR));
567 socket_->Connect(delegate_.Pass(),
568 base::Bind(&CompleteHandler::OnConnectComplete,
569 base::Unretained(&handler_)));
570 RunPendingTasks();
571 CastMessage mangled_auth_reply = CreateAuthReply();
572 mangled_auth_reply.set_namespace_("BOGUS_NAMESPACE");
574 socket_->GetMockTransport()->current_delegate()->OnMessage(
575 mangled_auth_reply);
576 RunPendingTasks();
578 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
579 EXPECT_EQ(cast_channel::CHANNEL_ERROR_TRANSPORT_ERROR,
580 socket_->error_state());
582 // Verifies that the CastSocket's resources were torn down during channel
583 // close. (see http://crbug.com/504078)
584 EXPECT_EQ(nullptr, socket_->transport());
587 // Test connection error - TCP connect fails (async)
588 TEST_F(CastSocketTest, TestConnectTcpConnectErrorAsync) {
589 CreateCastSocketSecure();
591 socket_->SetupTcp1Connect(net::ASYNC, net::ERR_FAILED);
593 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_CONNECT_ERROR));
594 socket_->Connect(delegate_.Pass(),
595 base::Bind(&CompleteHandler::OnConnectComplete,
596 base::Unretained(&handler_)));
597 RunPendingTasks();
599 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
600 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
603 // Test connection error - TCP connect fails (sync)
604 TEST_F(CastSocketTest, TestConnectTcpConnectErrorSync) {
605 CreateCastSocketSecure();
607 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::ERR_FAILED);
609 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_CONNECT_ERROR));
610 socket_->Connect(delegate_.Pass(),
611 base::Bind(&CompleteHandler::OnConnectComplete,
612 base::Unretained(&handler_)));
613 RunPendingTasks();
615 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
616 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
619 // Test connection error - timeout
620 TEST_F(CastSocketTest, TestConnectTcpTimeoutError) {
621 CreateCastSocketSecure();
622 socket_->SetupTcp1ConnectUnresponsive();
623 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_CONNECT_TIMEOUT));
624 EXPECT_CALL(*delegate_, OnError(CHANNEL_ERROR_CONNECT_TIMEOUT));
625 socket_->Connect(delegate_.Pass(),
626 base::Bind(&CompleteHandler::OnConnectComplete,
627 base::Unretained(&handler_)));
628 RunPendingTasks();
630 EXPECT_EQ(cast_channel::READY_STATE_CONNECTING, socket_->ready_state());
631 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
632 socket_->TriggerTimeout();
633 RunPendingTasks();
635 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
636 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_TIMEOUT,
637 socket_->error_state());
640 // Test connection error - TCP socket returns timeout
641 TEST_F(CastSocketTest, TestConnectTcpSocketTimeoutError) {
642 CreateCastSocketSecure();
643 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::ERR_CONNECTION_TIMED_OUT);
644 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_CONNECT_TIMEOUT));
645 EXPECT_CALL(*delegate_, OnError(CHANNEL_ERROR_CONNECT_TIMEOUT));
646 socket_->Connect(delegate_.Pass(),
647 base::Bind(&CompleteHandler::OnConnectComplete,
648 base::Unretained(&handler_)));
649 RunPendingTasks();
651 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
652 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_TIMEOUT,
653 socket_->error_state());
654 EXPECT_EQ(net::ERR_CONNECTION_TIMED_OUT,
655 logger_->GetLastErrors(socket_->id()).net_return_value);
658 // Test connection error - SSL connect fails (async)
659 TEST_F(CastSocketTest, TestConnectSslConnectErrorAsync) {
660 CreateCastSocketSecure();
662 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
663 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_FAILED);
665 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR));
666 socket_->Connect(delegate_.Pass(),
667 base::Bind(&CompleteHandler::OnConnectComplete,
668 base::Unretained(&handler_)));
669 RunPendingTasks();
671 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
672 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR,
673 socket_->error_state());
676 // Test connection error - SSL connect fails (sync)
677 TEST_F(CastSocketTest, TestConnectSslConnectErrorSync) {
678 CreateCastSocketSecure();
680 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
681 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_FAILED);
683 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR));
684 socket_->Connect(delegate_.Pass(),
685 base::Bind(&CompleteHandler::OnConnectComplete,
686 base::Unretained(&handler_)));
687 RunPendingTasks();
689 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
690 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR,
691 socket_->error_state());
692 EXPECT_EQ(net::ERR_FAILED,
693 logger_->GetLastErrors(socket_->id()).net_return_value);
696 // Test connection error - SSL connect times out (sync)
697 TEST_F(CastSocketTest, TestConnectSslConnectTimeoutSync) {
698 CreateCastSocketSecure();
700 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
701 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_CONNECTION_TIMED_OUT);
703 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_CONNECT_TIMEOUT));
704 socket_->Connect(delegate_.Pass(),
705 base::Bind(&CompleteHandler::OnConnectComplete,
706 base::Unretained(&handler_)));
707 RunPendingTasks();
709 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
710 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_TIMEOUT,
711 socket_->error_state());
712 EXPECT_EQ(net::ERR_CONNECTION_TIMED_OUT,
713 logger_->GetLastErrors(socket_->id()).net_return_value);
716 // Test connection error - SSL connect times out (async)
717 TEST_F(CastSocketTest, TestConnectSslConnectTimeoutAsync) {
718 CreateCastSocketSecure();
720 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
721 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CONNECTION_TIMED_OUT);
723 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_CONNECT_TIMEOUT));
724 socket_->Connect(delegate_.Pass(),
725 base::Bind(&CompleteHandler::OnConnectComplete,
726 base::Unretained(&handler_)));
727 RunPendingTasks();
729 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
730 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_TIMEOUT,
731 socket_->error_state());
734 // Test connection error - cert extraction error (async)
735 TEST_F(CastSocketTest, TestConnectCertExtractionErrorAsync) {
736 CreateCastSocket();
737 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
738 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
739 // Set cert extraction to fail
740 socket_->SetExtractCertResult(false);
742 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR));
743 socket_->Connect(delegate_.Pass(),
744 base::Bind(&CompleteHandler::OnConnectComplete,
745 base::Unretained(&handler_)));
746 RunPendingTasks();
748 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
749 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR,
750 socket_->error_state());
753 // Test connection error - cert extraction error (sync)
754 TEST_F(CastSocketTest, TestConnectCertExtractionErrorSync) {
755 CreateCastSocket();
756 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
757 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_CERT_AUTHORITY_INVALID);
758 // Set cert extraction to fail
759 socket_->SetExtractCertResult(false);
761 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR));
762 socket_->Connect(delegate_.Pass(),
763 base::Bind(&CompleteHandler::OnConnectComplete,
764 base::Unretained(&handler_)));
765 RunPendingTasks();
767 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
768 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR,
769 socket_->error_state());
772 // Test connection error - challenge send fails
773 TEST_F(CastSocketTest, TestConnectChallengeSendError) {
774 CreateCastSocketSecure();
775 socket_->SetupMockTransport();
777 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
778 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::OK);
779 EXPECT_CALL(*socket_->GetMockTransport(),
780 SendMessage(EqualsProto(CreateAuthChallenge()), _))
781 .WillOnce(RunCompletionCallback<1>(net::ERR_CONNECTION_RESET));
783 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_SOCKET_ERROR));
784 socket_->Connect(delegate_.Pass(),
785 base::Bind(&CompleteHandler::OnConnectComplete,
786 base::Unretained(&handler_)));
787 RunPendingTasks();
789 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
790 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR, socket_->error_state());
793 // Test connection error - challenge reply receive fails
794 TEST_F(CastSocketTest, TestConnectChallengeReplyReceiveError) {
795 CreateCastSocketSecure();
796 socket_->SetupMockTransport();
798 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
799 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::OK);
800 EXPECT_CALL(*socket_->GetMockTransport(),
801 SendMessage(EqualsProto(CreateAuthChallenge()), _))
802 .WillOnce(RunCompletionCallback<1>(net::OK));
803 socket_->AddReadResult(net::SYNCHRONOUS, net::ERR_FAILED);
804 EXPECT_CALL(*delegate_, OnError(CHANNEL_ERROR_SOCKET_ERROR));
805 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_SOCKET_ERROR));
806 EXPECT_CALL(*socket_->GetMockTransport(), Start());
807 socket_->Connect(delegate_.Pass(),
808 base::Bind(&CompleteHandler::OnConnectComplete,
809 base::Unretained(&handler_)));
810 socket_->GetMockTransport()->current_delegate()->OnError(
811 CHANNEL_ERROR_SOCKET_ERROR);
812 RunPendingTasks();
814 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
815 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR, socket_->error_state());
818 TEST_F(CastSocketTest, TestConnectChallengeVerificationFails) {
819 CreateCastSocketSecure();
820 socket_->SetupMockTransport();
821 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
822 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
823 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
824 socket_->SetupSsl2Connect(net::ASYNC, net::OK);
825 socket_->SetVerifyChallengeResult(false);
827 EXPECT_CALL(*delegate_, OnError(CHANNEL_ERROR_AUTHENTICATION_ERROR));
828 CastMessage challenge_proto = CreateAuthChallenge();
829 EXPECT_CALL(*socket_->GetMockTransport(),
830 SendMessage(EqualsProto(challenge_proto), _))
831 .WillOnce(RunCompletionCallback<1>(net::OK));
832 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR));
833 EXPECT_CALL(*socket_->GetMockTransport(), Start());
834 socket_->Connect(delegate_.Pass(),
835 base::Bind(&CompleteHandler::OnConnectComplete,
836 base::Unretained(&handler_)));
837 RunPendingTasks();
838 socket_->GetMockTransport()->current_delegate()->OnMessage(CreateAuthReply());
839 RunPendingTasks();
841 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
842 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR,
843 socket_->error_state());
846 // Sends message data through an actual non-mocked CastTransport object,
847 // testing the two components in integration.
848 TEST_F(CastSocketTest, TestConnectEndToEndWithRealTransportAsync) {
849 CreateCastSocketSecure();
850 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
851 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
852 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
853 socket_->SetupSsl2Connect(net::ASYNC, net::OK);
855 // Set low-level auth challenge expectations.
856 CastMessage challenge = CreateAuthChallenge();
857 std::string challenge_str;
858 EXPECT_TRUE(MessageFramer::Serialize(challenge, &challenge_str));
859 socket_->AddWriteResultForData(net::ASYNC, challenge_str);
861 // Set low-level auth reply expectations.
862 CastMessage reply = CreateAuthReply();
863 std::string reply_str;
864 EXPECT_TRUE(MessageFramer::Serialize(reply, &reply_str));
865 socket_->AddReadResultForData(net::ASYNC, reply_str);
866 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
868 CastMessage test_message = CreateTestMessage();
869 std::string test_message_str;
870 EXPECT_TRUE(MessageFramer::Serialize(test_message, &test_message_str));
871 socket_->AddWriteResultForData(net::ASYNC, test_message_str);
873 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_NONE));
874 socket_->Connect(delegate_.Pass(),
875 base::Bind(&CompleteHandler::OnConnectComplete,
876 base::Unretained(&handler_)));
877 RunPendingTasks();
878 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
879 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
881 // Send the test message through a real transport object.
882 EXPECT_CALL(handler_, OnWriteComplete(net::OK));
883 socket_->transport()->SendMessage(
884 test_message, base::Bind(&CompleteHandler::OnWriteComplete,
885 base::Unretained(&handler_)));
886 RunPendingTasks();
888 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
889 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
892 // Same as TestConnectEndToEndWithRealTransportAsync, except synchronous.
893 TEST_F(CastSocketTest, TestConnectEndToEndWithRealTransportSync) {
894 CreateCastSocketSecure();
895 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
896 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_CERT_AUTHORITY_INVALID);
897 socket_->SetupTcp2Connect(net::SYNCHRONOUS, net::OK);
898 socket_->SetupSsl2Connect(net::SYNCHRONOUS, net::OK);
900 // Set low-level auth challenge expectations.
901 CastMessage challenge = CreateAuthChallenge();
902 std::string challenge_str;
903 EXPECT_TRUE(MessageFramer::Serialize(challenge, &challenge_str));
904 socket_->AddWriteResultForData(net::SYNCHRONOUS, challenge_str);
906 // Set low-level auth reply expectations.
907 CastMessage reply = CreateAuthReply();
908 std::string reply_str;
909 EXPECT_TRUE(MessageFramer::Serialize(reply, &reply_str));
910 socket_->AddReadResultForData(net::SYNCHRONOUS, reply_str);
911 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
913 CastMessage test_message = CreateTestMessage();
914 std::string test_message_str;
915 EXPECT_TRUE(MessageFramer::Serialize(test_message, &test_message_str));
916 socket_->AddWriteResultForData(net::SYNCHRONOUS, test_message_str);
918 EXPECT_CALL(handler_, OnConnectComplete(CHANNEL_ERROR_NONE));
919 socket_->Connect(delegate_.Pass(),
920 base::Bind(&CompleteHandler::OnConnectComplete,
921 base::Unretained(&handler_)));
922 RunPendingTasks();
923 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
924 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
926 // Send the test message through a real transport object.
927 EXPECT_CALL(handler_, OnWriteComplete(net::OK));
928 socket_->transport()->SendMessage(
929 test_message, base::Bind(&CompleteHandler::OnWriteComplete,
930 base::Unretained(&handler_)));
931 RunPendingTasks();
933 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
934 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
937 // Tests channel policy verification for device with no capabilities.
938 TEST_F(CastSocketTest, TestChannelPolicyVerificationCapabilitiesNone) {
939 socket_ =
940 TestCastSocket::Create(logger_, cast_channel::CastDeviceCapability::NONE);
941 EXPECT_TRUE(socket_->TestVerifyChannelPolicyNone());
942 EXPECT_TRUE(socket_->TestVerifyChannelPolicyAudioOnly());
945 // Tests channel policy verification for device with video out capability.
946 TEST_F(CastSocketTest, TestChannelPolicyVerificationCapabilitiesVideoOut) {
947 socket_ = TestCastSocket::Create(
948 logger_, cast_channel::CastDeviceCapability::VIDEO_OUT);
949 EXPECT_TRUE(socket_->TestVerifyChannelPolicyNone());
950 EXPECT_FALSE(socket_->TestVerifyChannelPolicyAudioOnly());
952 } // namespace cast_channel
953 } // namespace api
954 } // namespace extensions