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"
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).
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
{
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() {
53 CreateAuthChallengeMessage(&output
);
57 // Returns an auth challenge response message inline.
58 CastMessage
CreateAuthReply() {
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
);
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");
80 class MockTCPSocket
: public net::TCPClientSocket
{
82 explicit MockTCPSocket(const net::MockConnect
& connect_data
)
83 : TCPClientSocket(net::AddressList(), nullptr, net::NetLog::Source()),
84 connect_data_(connect_data
),
87 explicit MockTCPSocket(bool do_nothing
)
88 : TCPClientSocket(net::AddressList(), nullptr, net::NetLog::Source()) {
90 do_nothing_
= do_nothing
;
93 virtual int Connect(const net::CompletionCallback
& callback
) {
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(
103 base::Bind(callback
, connect_data_
.result
));
104 return net::ERR_IO_PENDING
;
106 return connect_data_
.result
;
110 virtual bool SetKeepAlive(bool enable
, int delay
) {
111 // Always return true in tests
115 virtual bool SetNoDelay(bool no_delay
) {
116 // Always return true in tests
121 int(net::IOBuffer
*, int, const net::CompletionCallback
&));
123 int(net::IOBuffer
*, int, const net::CompletionCallback
&));
125 virtual void Disconnect() {
126 // Do nothing in tests
130 net::MockConnect connect_data_
;
133 DISALLOW_COPY_AND_ASSIGN(MockTCPSocket
);
136 class MockDelegate
: public CastTransport::Delegate
{
139 virtual ~MockDelegate() {}
140 MOCK_METHOD1(OnError
, void(ChannelError error_state
));
141 MOCK_METHOD1(OnMessage
, void(const CastMessage
& message
));
142 MOCK_METHOD0(Start
, void());
145 DISALLOW_COPY_AND_ASSIGN(MockDelegate
);
148 class 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
));
157 DISALLOW_COPY_AND_ASSIGN(CompleteHandler
);
160 class TestCastSocket
: public CastSocketImpl
{
162 static scoped_ptr
<TestCastSocket
> Create(
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(
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
,
182 uint64 device_capabilities
)
183 : CastSocketImpl("some_extension_id",
187 base::TimeDelta::FromMilliseconds(timeout_ms
),
190 device_capabilities
),
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() {
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_
;
275 scoped_ptr
<net::TCPClientSocket
> CreateTcpSocket() override
{
276 if (tcp_unresponsive_
) {
277 return scoped_ptr
<net::TCPClientSocket
>(new MockTCPSocket(true));
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_
;
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_
;
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
{
340 : logger_(new Logger(
341 scoped_ptr
<base::TickClock
>(new base::SimpleTestTickClock
),
343 delegate_(new MockDelegate
) {}
344 ~CastSocketTest() override
{}
346 void SetUp() override
{ EXPECT_CALL(*delegate_
, OnMessage(_
)).Times(0); }
348 void TearDown() override
{
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_
)));
374 socket_
->GetMockTransport()->current_delegate()->OnMessage(
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_
;
388 scoped_ptr
<TestCastSocket
> socket_
;
389 CompleteHandler handler_
;
390 scoped_ptr
<MockDelegate
> delegate_
;
393 DISALLOW_COPY_AND_ASSIGN(CastSocketTest
);
396 // Tests connecting and closing the socket.
397 TEST_F(CastSocketTest
, TestConnectAndClose
) {
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_
)));
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
) {
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_
)));
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
) {
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_
)));
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
) {
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_
)));
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
) {
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_
)));
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_
)));
571 CastMessage mangled_auth_reply
= CreateAuthReply();
572 mangled_auth_reply
.set_namespace_("BOGUS_NAMESPACE");
574 socket_
->GetMockTransport()->current_delegate()->OnMessage(
578 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
579 EXPECT_EQ(cast_channel::CHANNEL_ERROR_TRANSPORT_ERROR
,
580 socket_
->error_state());
583 // Test connection error - TCP connect fails (async)
584 TEST_F(CastSocketTest
, TestConnectTcpConnectErrorAsync
) {
585 CreateCastSocketSecure();
587 socket_
->SetupTcp1Connect(net::ASYNC
, net::ERR_FAILED
);
589 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_CONNECT_ERROR
));
590 socket_
->Connect(delegate_
.Pass(),
591 base::Bind(&CompleteHandler::OnConnectComplete
,
592 base::Unretained(&handler_
)));
595 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
596 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR
, socket_
->error_state());
599 // Test connection error - TCP connect fails (sync)
600 TEST_F(CastSocketTest
, TestConnectTcpConnectErrorSync
) {
601 CreateCastSocketSecure();
603 socket_
->SetupTcp1Connect(net::SYNCHRONOUS
, net::ERR_FAILED
);
605 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_CONNECT_ERROR
));
606 socket_
->Connect(delegate_
.Pass(),
607 base::Bind(&CompleteHandler::OnConnectComplete
,
608 base::Unretained(&handler_
)));
611 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
612 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR
, socket_
->error_state());
615 // Test connection error - timeout
616 TEST_F(CastSocketTest
, TestConnectTcpTimeoutError
) {
617 CreateCastSocketSecure();
618 socket_
->SetupTcp1ConnectUnresponsive();
619 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_CONNECT_TIMEOUT
));
620 EXPECT_CALL(*delegate_
, OnError(CHANNEL_ERROR_CONNECT_TIMEOUT
));
621 socket_
->Connect(delegate_
.Pass(),
622 base::Bind(&CompleteHandler::OnConnectComplete
,
623 base::Unretained(&handler_
)));
626 EXPECT_EQ(cast_channel::READY_STATE_CONNECTING
, socket_
->ready_state());
627 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE
, socket_
->error_state());
628 socket_
->TriggerTimeout();
631 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
632 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_TIMEOUT
,
633 socket_
->error_state());
636 // Test connection error - SSL connect fails (async)
637 TEST_F(CastSocketTest
, TestConnectSslConnectErrorAsync
) {
638 CreateCastSocketSecure();
640 socket_
->SetupTcp1Connect(net::SYNCHRONOUS
, net::OK
);
641 socket_
->SetupSsl1Connect(net::SYNCHRONOUS
, net::ERR_FAILED
);
643 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR
));
644 socket_
->Connect(delegate_
.Pass(),
645 base::Bind(&CompleteHandler::OnConnectComplete
,
646 base::Unretained(&handler_
)));
649 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
650 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR
,
651 socket_
->error_state());
654 // Test connection error - SSL connect fails (sync)
655 TEST_F(CastSocketTest
, TestConnectSslConnectErrorSync
) {
656 CreateCastSocketSecure();
658 socket_
->SetupTcp1Connect(net::SYNCHRONOUS
, net::OK
);
659 socket_
->SetupSsl1Connect(net::ASYNC
, net::ERR_FAILED
);
661 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR
));
662 socket_
->Connect(delegate_
.Pass(),
663 base::Bind(&CompleteHandler::OnConnectComplete
,
664 base::Unretained(&handler_
)));
667 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
668 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR
,
669 socket_
->error_state());
672 // Test connection error - cert extraction error (async)
673 TEST_F(CastSocketTest
, TestConnectCertExtractionErrorAsync
) {
675 socket_
->SetupTcp1Connect(net::ASYNC
, net::OK
);
676 socket_
->SetupSsl1Connect(net::ASYNC
, net::ERR_CERT_AUTHORITY_INVALID
);
677 // Set cert extraction to fail
678 socket_
->SetExtractCertResult(false);
680 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR
));
681 socket_
->Connect(delegate_
.Pass(),
682 base::Bind(&CompleteHandler::OnConnectComplete
,
683 base::Unretained(&handler_
)));
686 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
687 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR
,
688 socket_
->error_state());
691 // Test connection error - cert extraction error (sync)
692 TEST_F(CastSocketTest
, TestConnectCertExtractionErrorSync
) {
694 socket_
->SetupTcp1Connect(net::SYNCHRONOUS
, net::OK
);
695 socket_
->SetupSsl1Connect(net::SYNCHRONOUS
, net::ERR_CERT_AUTHORITY_INVALID
);
696 // Set cert extraction to fail
697 socket_
->SetExtractCertResult(false);
699 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR
));
700 socket_
->Connect(delegate_
.Pass(),
701 base::Bind(&CompleteHandler::OnConnectComplete
,
702 base::Unretained(&handler_
)));
705 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
706 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR
,
707 socket_
->error_state());
710 // Test connection error - challenge send fails
711 TEST_F(CastSocketTest
, TestConnectChallengeSendError
) {
712 CreateCastSocketSecure();
713 socket_
->SetupMockTransport();
715 socket_
->SetupTcp1Connect(net::SYNCHRONOUS
, net::OK
);
716 socket_
->SetupSsl1Connect(net::SYNCHRONOUS
, net::OK
);
717 EXPECT_CALL(*socket_
->GetMockTransport(),
718 SendMessage(EqualsProto(CreateAuthChallenge()), _
))
719 .WillOnce(RunCompletionCallback
<1>(net::ERR_CONNECTION_RESET
));
721 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_SOCKET_ERROR
));
722 socket_
->Connect(delegate_
.Pass(),
723 base::Bind(&CompleteHandler::OnConnectComplete
,
724 base::Unretained(&handler_
)));
727 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
728 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR
, socket_
->error_state());
731 // Test connection error - challenge reply receive fails
732 TEST_F(CastSocketTest
, TestConnectChallengeReplyReceiveError
) {
733 CreateCastSocketSecure();
734 socket_
->SetupMockTransport();
736 socket_
->SetupTcp1Connect(net::SYNCHRONOUS
, net::OK
);
737 socket_
->SetupSsl1Connect(net::SYNCHRONOUS
, net::OK
);
738 EXPECT_CALL(*socket_
->GetMockTransport(),
739 SendMessage(EqualsProto(CreateAuthChallenge()), _
))
740 .WillOnce(RunCompletionCallback
<1>(net::OK
));
741 socket_
->AddReadResult(net::SYNCHRONOUS
, net::ERR_FAILED
);
742 EXPECT_CALL(*delegate_
, OnError(CHANNEL_ERROR_SOCKET_ERROR
));
743 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_SOCKET_ERROR
));
744 EXPECT_CALL(*socket_
->GetMockTransport(), Start());
745 socket_
->Connect(delegate_
.Pass(),
746 base::Bind(&CompleteHandler::OnConnectComplete
,
747 base::Unretained(&handler_
)));
748 socket_
->GetMockTransport()->current_delegate()->OnError(
749 CHANNEL_ERROR_SOCKET_ERROR
);
752 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
753 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR
, socket_
->error_state());
756 TEST_F(CastSocketTest
, TestConnectChallengeVerificationFails
) {
757 CreateCastSocketSecure();
758 socket_
->SetupMockTransport();
759 socket_
->SetupTcp1Connect(net::ASYNC
, net::OK
);
760 socket_
->SetupSsl1Connect(net::ASYNC
, net::ERR_CERT_AUTHORITY_INVALID
);
761 socket_
->SetupTcp2Connect(net::ASYNC
, net::OK
);
762 socket_
->SetupSsl2Connect(net::ASYNC
, net::OK
);
763 socket_
->SetVerifyChallengeResult(false);
765 EXPECT_CALL(*delegate_
, OnError(CHANNEL_ERROR_AUTHENTICATION_ERROR
));
766 CastMessage challenge_proto
= CreateAuthChallenge();
767 EXPECT_CALL(*socket_
->GetMockTransport(),
768 SendMessage(EqualsProto(challenge_proto
), _
))
769 .WillOnce(RunCompletionCallback
<1>(net::OK
));
770 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_AUTHENTICATION_ERROR
));
771 EXPECT_CALL(*socket_
->GetMockTransport(), Start());
772 socket_
->Connect(delegate_
.Pass(),
773 base::Bind(&CompleteHandler::OnConnectComplete
,
774 base::Unretained(&handler_
)));
776 socket_
->GetMockTransport()->current_delegate()->OnMessage(CreateAuthReply());
779 EXPECT_EQ(cast_channel::READY_STATE_CLOSED
, socket_
->ready_state());
780 EXPECT_EQ(cast_channel::CHANNEL_ERROR_AUTHENTICATION_ERROR
,
781 socket_
->error_state());
784 // Sends message data through an actual non-mocked CastTransport object,
785 // testing the two components in integration.
786 TEST_F(CastSocketTest
, TestConnectEndToEndWithRealTransportAsync
) {
787 CreateCastSocketSecure();
788 socket_
->SetupTcp1Connect(net::ASYNC
, net::OK
);
789 socket_
->SetupSsl1Connect(net::ASYNC
, net::ERR_CERT_AUTHORITY_INVALID
);
790 socket_
->SetupTcp2Connect(net::ASYNC
, net::OK
);
791 socket_
->SetupSsl2Connect(net::ASYNC
, net::OK
);
793 // Set low-level auth challenge expectations.
794 CastMessage challenge
= CreateAuthChallenge();
795 std::string challenge_str
;
796 EXPECT_TRUE(MessageFramer::Serialize(challenge
, &challenge_str
));
797 socket_
->AddWriteResultForData(net::ASYNC
, challenge_str
);
799 // Set low-level auth reply expectations.
800 CastMessage reply
= CreateAuthReply();
801 std::string reply_str
;
802 EXPECT_TRUE(MessageFramer::Serialize(reply
, &reply_str
));
803 socket_
->AddReadResultForData(net::ASYNC
, reply_str
);
804 socket_
->AddReadResult(net::ASYNC
, net::ERR_IO_PENDING
);
806 CastMessage test_message
= CreateTestMessage();
807 std::string test_message_str
;
808 EXPECT_TRUE(MessageFramer::Serialize(test_message
, &test_message_str
));
809 socket_
->AddWriteResultForData(net::ASYNC
, test_message_str
);
811 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_NONE
));
812 socket_
->Connect(delegate_
.Pass(),
813 base::Bind(&CompleteHandler::OnConnectComplete
,
814 base::Unretained(&handler_
)));
816 EXPECT_EQ(cast_channel::READY_STATE_OPEN
, socket_
->ready_state());
817 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE
, socket_
->error_state());
819 // Send the test message through a real transport object.
820 EXPECT_CALL(handler_
, OnWriteComplete(net::OK
));
821 socket_
->transport()->SendMessage(
822 test_message
, base::Bind(&CompleteHandler::OnWriteComplete
,
823 base::Unretained(&handler_
)));
826 EXPECT_EQ(cast_channel::READY_STATE_OPEN
, socket_
->ready_state());
827 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE
, socket_
->error_state());
830 // Same as TestConnectEndToEndWithRealTransportAsync, except synchronous.
831 TEST_F(CastSocketTest
, TestConnectEndToEndWithRealTransportSync
) {
832 CreateCastSocketSecure();
833 socket_
->SetupTcp1Connect(net::SYNCHRONOUS
, net::OK
);
834 socket_
->SetupSsl1Connect(net::SYNCHRONOUS
, net::ERR_CERT_AUTHORITY_INVALID
);
835 socket_
->SetupTcp2Connect(net::SYNCHRONOUS
, net::OK
);
836 socket_
->SetupSsl2Connect(net::SYNCHRONOUS
, net::OK
);
838 // Set low-level auth challenge expectations.
839 CastMessage challenge
= CreateAuthChallenge();
840 std::string challenge_str
;
841 EXPECT_TRUE(MessageFramer::Serialize(challenge
, &challenge_str
));
842 socket_
->AddWriteResultForData(net::SYNCHRONOUS
, challenge_str
);
844 // Set low-level auth reply expectations.
845 CastMessage reply
= CreateAuthReply();
846 std::string reply_str
;
847 EXPECT_TRUE(MessageFramer::Serialize(reply
, &reply_str
));
848 socket_
->AddReadResultForData(net::SYNCHRONOUS
, reply_str
);
849 socket_
->AddReadResult(net::ASYNC
, net::ERR_IO_PENDING
);
851 CastMessage test_message
= CreateTestMessage();
852 std::string test_message_str
;
853 EXPECT_TRUE(MessageFramer::Serialize(test_message
, &test_message_str
));
854 socket_
->AddWriteResultForData(net::SYNCHRONOUS
, test_message_str
);
856 EXPECT_CALL(handler_
, OnConnectComplete(CHANNEL_ERROR_NONE
));
857 socket_
->Connect(delegate_
.Pass(),
858 base::Bind(&CompleteHandler::OnConnectComplete
,
859 base::Unretained(&handler_
)));
861 EXPECT_EQ(cast_channel::READY_STATE_OPEN
, socket_
->ready_state());
862 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE
, socket_
->error_state());
864 // Send the test message through a real transport object.
865 EXPECT_CALL(handler_
, OnWriteComplete(net::OK
));
866 socket_
->transport()->SendMessage(
867 test_message
, base::Bind(&CompleteHandler::OnWriteComplete
,
868 base::Unretained(&handler_
)));
871 EXPECT_EQ(cast_channel::READY_STATE_OPEN
, socket_
->ready_state());
872 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE
, socket_
->error_state());
875 // Tests channel policy verification for device with no capabilities.
876 TEST_F(CastSocketTest
, TestChannelPolicyVerificationCapabilitiesNone
) {
878 TestCastSocket::Create(logger_
, cast_channel::CastDeviceCapability::NONE
);
879 EXPECT_TRUE(socket_
->TestVerifyChannelPolicyNone());
880 EXPECT_TRUE(socket_
->TestVerifyChannelPolicyAudioOnly());
883 // Tests channel policy verification for device with video out capability.
884 TEST_F(CastSocketTest
, TestChannelPolicyVerificationCapabilitiesVideoOut
) {
885 socket_
= TestCastSocket::Create(
886 logger_
, cast_channel::CastDeviceCapability::VIDEO_OUT
);
887 EXPECT_TRUE(socket_
->TestVerifyChannelPolicyNone());
888 EXPECT_FALSE(socket_
->TestVerifyChannelPolicyAudioOnly());
890 } // namespace cast_channel
891 } // namespace core_api
892 } // namespace extensions