1 // Copyright (c) 2012 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 "chromeos/network/network_connection_handler.h"
8 #include "base/callback.h"
9 #include "base/file_util.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/run_loop.h"
13 #include "base/strings/stringprintf.h"
14 #include "chromeos/cert_loader.h"
15 #include "chromeos/dbus/dbus_thread_manager.h"
16 #include "chromeos/dbus/shill_manager_client.h"
17 #include "chromeos/dbus/shill_service_client.h"
18 #include "chromeos/network/network_configuration_handler.h"
19 #include "chromeos/network/network_state_handler.h"
20 #include "chromeos/network/onc/onc_utils.h"
21 #include "chromeos/tpm_token_loader.h"
22 #include "crypto/nss_util.h"
23 #include "crypto/nss_util_internal.h"
24 #include "net/base/net_errors.h"
25 #include "net/base/test_data_directory.h"
26 #include "net/cert/nss_cert_database_chromeos.h"
27 #include "net/cert/x509_certificate.h"
28 #include "net/test/cert_test_util.h"
29 #include "testing/gtest/include/gtest/gtest.h"
30 #include "third_party/cros_system_api/dbus/service_constants.h"
34 const char* kSuccessResult = "success";
36 void ConfigureCallback(const dbus::ObjectPath& result) {
39 void ConfigureErrorCallback(const std::string& error_name,
40 const std::string& error_message) {
47 class NetworkConnectionHandlerTest : public testing::Test {
49 NetworkConnectionHandlerTest() : user_("userhash") {
51 virtual ~NetworkConnectionHandlerTest() {
54 virtual void SetUp() OVERRIDE {
55 ASSERT_TRUE(user_.constructed_successfully());
58 test_nssdb_.reset(new net::NSSCertDatabaseChromeOS(
59 crypto::GetPublicSlotForChromeOSUser(user_.username_hash()),
60 crypto::GetPrivateSlotForChromeOSUser(
61 user_.username_hash(),
62 base::Callback<void(crypto::ScopedPK11Slot)>())));
63 test_nssdb_->SetSlowTaskRunnerForTest(message_loop_.message_loop_proxy());
65 TPMTokenLoader::InitializeForTest();
67 CertLoader::Initialize();
68 CertLoader* cert_loader = CertLoader::Get();
69 cert_loader->force_hardware_backed_for_test();
71 // Initialize DBusThreadManager with a stub implementation.
72 DBusThreadManager::InitializeWithStub();
73 base::RunLoop().RunUntilIdle();
74 DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface()
76 base::RunLoop().RunUntilIdle();
77 LoginState::Initialize();
78 network_state_handler_.reset(NetworkStateHandler::InitializeForTest());
79 network_configuration_handler_.reset(
80 NetworkConfigurationHandler::InitializeForTest(
81 network_state_handler_.get()));
83 network_connection_handler_.reset(new NetworkConnectionHandler);
84 network_connection_handler_->Init(network_state_handler_.get(),
85 network_configuration_handler_.get());
88 virtual void TearDown() OVERRIDE {
89 network_connection_handler_.reset();
90 network_configuration_handler_.reset();
91 network_state_handler_.reset();
92 CertLoader::Shutdown();
93 TPMTokenLoader::Shutdown();
94 LoginState::Shutdown();
95 DBusThreadManager::Shutdown();
99 bool Configure(const std::string& json_string) {
100 scoped_ptr<base::DictionaryValue> json_dict =
101 onc::ReadDictionaryFromJson(json_string);
103 LOG(ERROR) << "Error parsing json: " << json_string;
106 DBusThreadManager::Get()->GetShillManagerClient()->ConfigureService(
108 base::Bind(&ConfigureCallback),
109 base::Bind(&ConfigureErrorCallback));
110 base::RunLoop().RunUntilIdle();
114 void Connect(const std::string& service_path) {
115 const bool check_error_state = true;
116 network_connection_handler_->ConnectToNetwork(
118 base::Bind(&NetworkConnectionHandlerTest::SuccessCallback,
119 base::Unretained(this)),
120 base::Bind(&NetworkConnectionHandlerTest::ErrorCallback,
121 base::Unretained(this)),
123 base::RunLoop().RunUntilIdle();
126 void Disconnect(const std::string& service_path) {
127 network_connection_handler_->DisconnectNetwork(
129 base::Bind(&NetworkConnectionHandlerTest::SuccessCallback,
130 base::Unretained(this)),
131 base::Bind(&NetworkConnectionHandlerTest::ErrorCallback,
132 base::Unretained(this)));
133 base::RunLoop().RunUntilIdle();
136 void SuccessCallback() {
137 result_ = kSuccessResult;
140 void ErrorCallback(const std::string& error_name,
141 scoped_ptr<base::DictionaryValue> error_data) {
142 result_ = error_name;
145 std::string GetResultAndReset() {
147 result.swap(result_);
151 std::string GetServiceStringProperty(const std::string& service_path,
152 const std::string& key) {
154 const base::DictionaryValue* properties =
155 DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface()->
156 GetServiceProperties(service_path);
158 properties->GetStringWithoutPathExpansion(key, &result);
162 void StartCertLoader() {
163 CertLoader::Get()->StartWithNSSDB(test_nssdb_.get());
164 base::RunLoop().RunUntilIdle();
167 void ImportClientCertAndKey(const std::string& pkcs12_file,
168 net::NSSCertDatabase* nssdb,
169 net::CertificateList* loaded_certs) {
170 std::string pkcs12_data;
171 base::FilePath pkcs12_path =
172 net::GetTestCertsDirectory().Append(pkcs12_file);
173 ASSERT_TRUE(base::ReadFileToString(pkcs12_path, &pkcs12_data));
175 scoped_refptr<net::CryptoModule> module(
176 net::CryptoModule::CreateFromHandle(nssdb->GetPrivateSlot().get()));
179 nssdb->ImportFromPKCS12(module, pkcs12_data, base::string16(), false,
181 ASSERT_EQ(1U, loaded_certs->size());
184 scoped_ptr<NetworkStateHandler> network_state_handler_;
185 scoped_ptr<NetworkConfigurationHandler> network_configuration_handler_;
186 scoped_ptr<NetworkConnectionHandler> network_connection_handler_;
187 crypto::ScopedTestNSSChromeOSUser user_;
188 scoped_ptr<net::NSSCertDatabaseChromeOS> test_nssdb_;
189 base::MessageLoopForUI message_loop_;
193 DISALLOW_COPY_AND_ASSIGN(NetworkConnectionHandlerTest);
198 const char* kConfigConnectable =
199 "{ \"GUID\": \"wifi0\", \"Type\": \"wifi\", \"State\": \"idle\", "
200 " \"Connectable\": true }";
201 const char* kConfigConnected =
202 "{ \"GUID\": \"wifi1\", \"Type\": \"wifi\", \"State\": \"online\" }";
203 const char* kConfigConnecting =
204 "{ \"GUID\": \"wifi2\", \"Type\": \"wifi\", \"State\": \"association\" }";
205 const char* kConfigRequiresPassphrase =
206 "{ \"GUID\": \"wifi3\", \"Type\": \"wifi\", "
207 " \"PassphraseRequired\": true }";
208 const char* kConfigRequiresActivation =
209 "{ \"GUID\": \"cellular1\", \"Type\": \"cellular\","
210 " \"Cellular.ActivationState\": \"not-activated\" }";
214 TEST_F(NetworkConnectionHandlerTest, NetworkConnectionHandlerConnectSuccess) {
215 EXPECT_TRUE(Configure(kConfigConnectable));
217 EXPECT_EQ(kSuccessResult, GetResultAndReset());
218 EXPECT_EQ(shill::kStateOnline,
219 GetServiceStringProperty("wifi0", shill::kStateProperty));
222 // Handles basic failure cases.
223 TEST_F(NetworkConnectionHandlerTest, NetworkConnectionHandlerConnectFailure) {
224 Connect("no-network");
225 EXPECT_EQ(NetworkConnectionHandler::kErrorConfigureFailed,
226 GetResultAndReset());
228 EXPECT_TRUE(Configure(kConfigConnected));
230 EXPECT_EQ(NetworkConnectionHandler::kErrorConnected, GetResultAndReset());
232 EXPECT_TRUE(Configure(kConfigConnecting));
234 EXPECT_EQ(NetworkConnectionHandler::kErrorConnecting, GetResultAndReset());
236 EXPECT_TRUE(Configure(kConfigRequiresPassphrase));
238 EXPECT_EQ(NetworkConnectionHandler::kErrorPassphraseRequired,
239 GetResultAndReset());
241 EXPECT_TRUE(Configure(kConfigRequiresActivation));
242 Connect("cellular1");
243 EXPECT_EQ(NetworkConnectionHandler::kErrorActivationRequired,
244 GetResultAndReset());
249 const char* kConfigRequiresCertificateTemplate =
250 "{ \"GUID\": \"wifi4\", \"Type\": \"wifi\", \"Connectable\": false,"
251 " \"Security\": \"802_1x\","
253 " \\\"certificate_type\\\": \\\"pattern\\\","
254 " \\\"certificate_pattern\\\": {"
255 " \\\"Subject\\\": {\\\"CommonName\\\": \\\"%s\\\" }"
260 // Handle certificates.
261 TEST_F(NetworkConnectionHandlerTest, ConnectCertificateMissing) {
264 EXPECT_TRUE(Configure(
265 base::StringPrintf(kConfigRequiresCertificateTemplate, "unknown")));
267 EXPECT_EQ(NetworkConnectionHandler::kErrorCertificateRequired,
268 GetResultAndReset());
271 TEST_F(NetworkConnectionHandlerTest, ConnectWithCertificateSuccess) {
274 net::CertificateList certs;
275 ImportClientCertAndKey("websocket_client_cert.p12",
279 EXPECT_TRUE(Configure(
280 base::StringPrintf(kConfigRequiresCertificateTemplate,
281 certs[0]->subject().common_name.c_str())));
284 EXPECT_EQ(kSuccessResult, GetResultAndReset());
287 TEST_F(NetworkConnectionHandlerTest,
288 ConnectWithCertificateRequestedBeforeCertsAreLoaded) {
289 net::CertificateList certs;
290 ImportClientCertAndKey("websocket_client_cert.p12",
294 EXPECT_TRUE(Configure(
295 base::StringPrintf(kConfigRequiresCertificateTemplate,
296 certs[0]->subject().common_name.c_str())));
300 // Connect request came before the cert loader loaded certificates, so the
301 // connect request should have been throttled until the certificates are
303 EXPECT_EQ("", GetResultAndReset());
307 // |StartCertLoader| should have triggered certificate loading.
308 // When the certificates got loaded, the connection request should have
309 // proceeded and eventually succeeded.
310 EXPECT_EQ(kSuccessResult, GetResultAndReset());
313 TEST_F(NetworkConnectionHandlerTest,
314 NetworkConnectionHandlerDisconnectSuccess) {
315 EXPECT_TRUE(Configure(kConfigConnected));
317 EXPECT_EQ(kSuccessResult, GetResultAndReset());
320 TEST_F(NetworkConnectionHandlerTest,
321 NetworkConnectionHandlerDisconnectFailure) {
322 Connect("no-network");
323 EXPECT_EQ(NetworkConnectionHandler::kErrorConfigureFailed,
324 GetResultAndReset());
326 EXPECT_TRUE(Configure(kConfigConnectable));
328 EXPECT_EQ(NetworkConnectionHandler::kErrorNotConnected, GetResultAndReset());
331 } // namespace chromeos