Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / policy / network_configuration_updater_unittest.cc
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 "base/bind.h"
6 #include "base/bind_helpers.h"
7 #include "base/callback.h"
8 #include "base/files/file_path.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/run_loop.h"
11 #include "base/values.h"
12 #include "chrome/browser/chromeos/policy/device_network_configuration_updater.h"
13 #include "chrome/browser/chromeos/policy/user_network_configuration_updater.h"
14 #include "chrome/browser/chromeos/settings/cros_settings.h"
15 #include "chrome/browser/chromeos/settings/device_settings_service.h"
16 #include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h"
17 #include "chrome/test/base/testing_profile.h"
18 #include "chromeos/network/fake_network_device_handler.h"
19 #include "chromeos/network/mock_managed_network_configuration_handler.h"
20 #include "chromeos/network/onc/mock_certificate_importer.h"
21 #include "chromeos/network/onc/onc_test_utils.h"
22 #include "chromeos/network/onc/onc_utils.h"
23 #include "components/onc/onc_constants.h"
24 #include "components/policy/core/common/external_data_fetcher.h"
25 #include "components/policy/core/common/mock_configuration_policy_provider.h"
26 #include "components/policy/core/common/policy_map.h"
27 #include "components/policy/core/common/policy_service_impl.h"
28 #include "components/user_manager/user.h"
29 #include "components/user_manager/user_type.h"
30 #include "content/public/test/test_browser_thread_bundle.h"
31 #include "content/public/test/test_utils.h"
32 #include "net/base/test_data_directory.h"
33 #include "net/cert/x509_certificate.h"
34 #include "net/test/cert_test_util.h"
35 #include "policy/policy_constants.h"
36 #include "testing/gmock/include/gmock/gmock.h"
37 #include "testing/gtest/include/gtest/gtest.h"
38
39 using testing::AnyNumber;
40 using testing::AtLeast;
41 using testing::Mock;
42 using testing::Ne;
43 using testing::Return;
44 using testing::StrictMock;
45 using testing::_;
46
47 namespace policy {
48
49 namespace {
50
51 const char kFakeUserEmail[] = "fake email";
52 const char kFakeUsernameHash[] = "fake hash";
53
54 class FakeUser : public user_manager::User {
55  public:
56   FakeUser() : User(kFakeUserEmail) {
57     set_display_email(kFakeUserEmail);
58     set_username_hash(kFakeUsernameHash);
59   }
60   virtual ~FakeUser() {}
61
62   // User overrides
63   virtual user_manager::UserType GetType() const OVERRIDE {
64     return user_manager::USER_TYPE_REGULAR;
65   }
66
67  private:
68   DISALLOW_COPY_AND_ASSIGN(FakeUser);
69 };
70
71 class FakeWebTrustedCertsObserver
72     : public UserNetworkConfigurationUpdater::WebTrustedCertsObserver {
73  public:
74   virtual void OnTrustAnchorsChanged(
75       const net::CertificateList& trust_anchors) OVERRIDE {
76     trust_anchors_ = trust_anchors;
77   }
78   net::CertificateList trust_anchors_;
79 };
80
81 class FakeNetworkDeviceHandler : public chromeos::FakeNetworkDeviceHandler {
82   public:
83    FakeNetworkDeviceHandler() : allow_roaming_(false) {}
84
85    virtual void SetCellularAllowRoaming(bool allow_roaming) OVERRIDE {
86      allow_roaming_ = allow_roaming;
87    }
88
89    bool allow_roaming_;
90 };
91
92 const char kFakeONC[] =
93     "{ \"NetworkConfigurations\": ["
94     "    { \"GUID\": \"{485d6076-dd44-6b6d-69787465725f5040}\","
95     "      \"Type\": \"WiFi\","
96     "      \"Name\": \"My WiFi Network\","
97     "      \"WiFi\": {"
98     "        \"SSID\": \"ssid-none\","
99     "        \"Security\": \"None\" }"
100     "    }"
101     "  ],"
102     "  \"GlobalNetworkConfiguration\": {"
103     "    \"AllowOnlyPolicyNetworksToAutoconnect\": true,"
104     "  },"
105     "  \"Certificates\": ["
106     "    { \"GUID\": \"{f998f760-272b-6939-4c2beffe428697ac}\","
107     "      \"PKCS12\": \"abc\","
108     "       \"Type\": \"Client\" }"
109     "  ],"
110     "  \"Type\": \"UnencryptedConfiguration\""
111     "}";
112
113 std::string ValueToString(const base::Value& value) {
114   std::stringstream str;
115   str << value;
116   return str.str();
117 }
118
119 void AppendAll(const base::ListValue& from, base::ListValue* to) {
120   for (base::ListValue::const_iterator it = from.begin(); it != from.end();
121        ++it) {
122     to->Append((*it)->DeepCopy());
123   }
124 }
125
126 // Matcher to match base::Value.
127 MATCHER_P(IsEqualTo,
128           value,
129           std::string(negation ? "isn't" : "is") + " equal to " +
130               ValueToString(*value)) {
131   return value->Equals(&arg);
132 }
133
134 MATCHER(IsEmpty, std::string(negation ? "isn't" : "is") + " empty.") {
135   return arg.empty();
136 }
137
138 ACTION_P(SetCertificateList, list) {
139   if (arg2)
140     *arg2 = list;
141   return true;
142 }
143
144 }  // namespace
145
146 class NetworkConfigurationUpdaterTest : public testing::Test {
147  protected:
148   NetworkConfigurationUpdaterTest() {
149   }
150
151   virtual void SetUp() OVERRIDE {
152     EXPECT_CALL(provider_, IsInitializationComplete(_))
153         .WillRepeatedly(Return(false));
154     provider_.Init();
155     PolicyServiceImpl::Providers providers;
156     providers.push_back(&provider_);
157     policy_service_.reset(new PolicyServiceImpl(providers));
158
159     scoped_ptr<base::DictionaryValue> fake_toplevel_onc =
160         chromeos::onc::ReadDictionaryFromJson(kFakeONC);
161
162     base::ListValue* network_configs = NULL;
163     fake_toplevel_onc->GetListWithoutPathExpansion(
164         onc::toplevel_config::kNetworkConfigurations, &network_configs);
165     AppendAll(*network_configs, &fake_network_configs_);
166
167     base::DictionaryValue* global_config = NULL;
168     fake_toplevel_onc->GetDictionaryWithoutPathExpansion(
169         onc::toplevel_config::kGlobalNetworkConfiguration, &global_config);
170     fake_global_network_config_.MergeDictionary(global_config);
171
172     base::ListValue* certs = NULL;
173     fake_toplevel_onc->GetListWithoutPathExpansion(
174         onc::toplevel_config::kCertificates, &certs);
175     AppendAll(*certs, &fake_certificates_);
176
177     certificate_importer_ =
178         new StrictMock<chromeos::onc::MockCertificateImporter>();
179     certificate_importer_owned_.reset(certificate_importer_);
180   }
181
182   virtual void TearDown() OVERRIDE {
183     network_configuration_updater_.reset();
184     provider_.Shutdown();
185     base::RunLoop().RunUntilIdle();
186   }
187
188   void MarkPolicyProviderInitialized() {
189     Mock::VerifyAndClearExpectations(&provider_);
190     EXPECT_CALL(provider_, IsInitializationComplete(_))
191         .WillRepeatedly(Return(true));
192     provider_.SetAutoRefresh();
193     provider_.RefreshPolicies();
194     base::RunLoop().RunUntilIdle();
195   }
196
197   void UpdateProviderPolicy(const PolicyMap& policy) {
198     provider_.UpdateChromePolicy(policy);
199     base::RunLoop().RunUntilIdle();
200   }
201
202   UserNetworkConfigurationUpdater*
203   CreateNetworkConfigurationUpdaterForUserPolicy(
204       bool allow_trusted_certs_from_policy,
205       bool set_cert_importer) {
206     UserNetworkConfigurationUpdater* updater =
207         UserNetworkConfigurationUpdater::CreateForUserPolicy(
208             &profile_,
209             allow_trusted_certs_from_policy,
210             fake_user_,
211             policy_service_.get(),
212             &network_config_handler_).release();
213     if (set_cert_importer) {
214       EXPECT_TRUE(certificate_importer_owned_);
215       updater->SetCertificateImporterForTest(
216           certificate_importer_owned_.Pass());
217     }
218     network_configuration_updater_.reset(updater);
219     return updater;
220   }
221
222   void CreateNetworkConfigurationUpdaterForDevicePolicy() {
223     network_configuration_updater_ =
224         DeviceNetworkConfigurationUpdater::CreateForDevicePolicy(
225             policy_service_.get(),
226             &network_config_handler_,
227             &network_device_handler_,
228             chromeos::CrosSettings::Get());
229   }
230
231   base::ListValue fake_network_configs_;
232   base::DictionaryValue fake_global_network_config_;
233   base::ListValue fake_certificates_;
234   StrictMock<chromeos::MockManagedNetworkConfigurationHandler>
235       network_config_handler_;
236   FakeNetworkDeviceHandler network_device_handler_;
237
238   // Not used directly. Required for CrosSettings.
239   chromeos::ScopedTestDeviceSettingsService scoped_device_settings_service_;
240   chromeos::ScopedTestCrosSettings scoped_cros_settings_;
241
242   // Ownership of certificate_importer_owned_ is passed to the
243   // NetworkConfigurationUpdater. When that happens, |certificate_importer_|
244   // continues to point to that instance but |certificate_importer_owned_| is
245   // released.
246   StrictMock<chromeos::onc::MockCertificateImporter>* certificate_importer_;
247   scoped_ptr<chromeos::onc::CertificateImporter> certificate_importer_owned_;
248
249   StrictMock<MockConfigurationPolicyProvider> provider_;
250   scoped_ptr<PolicyServiceImpl> policy_service_;
251   FakeUser fake_user_;
252
253   TestingProfile profile_;
254
255   scoped_ptr<NetworkConfigurationUpdater> network_configuration_updater_;
256   content::TestBrowserThreadBundle thread_bundle_;
257 };
258
259 TEST_F(NetworkConfigurationUpdaterTest, CellularAllowRoaming) {
260   // Ignore network config updates.
261   EXPECT_CALL(network_config_handler_, SetPolicy(_, _, _, _)).Times(AtLeast(1));
262
263   // Setup the DataRoaming device setting.
264   chromeos::CrosSettings* cros_settings = chromeos::CrosSettings::Get();
265   chromeos::CrosSettingsProvider* device_settings_provider =
266       cros_settings->GetProvider(chromeos::kSignedDataRoamingEnabled);
267   cros_settings->RemoveSettingsProvider(device_settings_provider);
268   delete device_settings_provider;
269   chromeos::StubCrosSettingsProvider* stub_settings_provider =
270       new chromeos::StubCrosSettingsProvider;
271   cros_settings->AddSettingsProvider(stub_settings_provider);
272
273   chromeos::CrosSettings::Get()->Set(chromeos::kSignedDataRoamingEnabled,
274                                      base::FundamentalValue(false));
275   EXPECT_FALSE(network_device_handler_.allow_roaming_);
276
277   CreateNetworkConfigurationUpdaterForDevicePolicy();
278   MarkPolicyProviderInitialized();
279   chromeos::CrosSettings::Get()->Set(chromeos::kSignedDataRoamingEnabled,
280                                      base::FundamentalValue(true));
281   EXPECT_TRUE(network_device_handler_.allow_roaming_);
282
283   chromeos::CrosSettings::Get()->Set(chromeos::kSignedDataRoamingEnabled,
284                                      base::FundamentalValue(false));
285   EXPECT_FALSE(network_device_handler_.allow_roaming_);
286 }
287
288 TEST_F(NetworkConfigurationUpdaterTest, PolicyIsValidatedAndRepaired) {
289   scoped_ptr<base::DictionaryValue> onc_repaired =
290       chromeos::onc::test_utils::ReadTestDictionary(
291           "repaired_toplevel_partially_invalid.onc");
292
293   base::ListValue* network_configs_repaired = NULL;
294   onc_repaired->GetListWithoutPathExpansion(
295       onc::toplevel_config::kNetworkConfigurations, &network_configs_repaired);
296   ASSERT_TRUE(network_configs_repaired);
297
298   base::DictionaryValue* global_config_repaired = NULL;
299   onc_repaired->GetDictionaryWithoutPathExpansion(
300       onc::toplevel_config::kGlobalNetworkConfiguration,
301       &global_config_repaired);
302   ASSERT_TRUE(global_config_repaired);
303
304   std::string onc_policy =
305       chromeos::onc::test_utils::ReadTestData("toplevel_partially_invalid.onc");
306   PolicyMap policy;
307   policy.Set(key::kOpenNetworkConfiguration,
308              POLICY_LEVEL_MANDATORY,
309              POLICY_SCOPE_USER,
310              new base::StringValue(onc_policy),
311              NULL);
312   UpdateProviderPolicy(policy);
313
314   EXPECT_CALL(network_config_handler_,
315               SetPolicy(onc::ONC_SOURCE_USER_POLICY,
316                         _,
317                         IsEqualTo(network_configs_repaired),
318                         IsEqualTo(global_config_repaired)));
319   EXPECT_CALL(*certificate_importer_,
320               ImportCertificates(_, onc::ONC_SOURCE_USER_POLICY,  _));
321
322   CreateNetworkConfigurationUpdaterForUserPolicy(
323       false /* do not allow trusted certs from policy */,
324       true /* set certificate importer */);
325   MarkPolicyProviderInitialized();
326 }
327
328 TEST_F(NetworkConfigurationUpdaterTest,
329        DoNotAllowTrustedCertificatesFromPolicy) {
330   net::CertificateList cert_list;
331   cert_list =
332       net::CreateCertificateListFromFile(net::GetTestCertsDirectory(),
333                                          "ok_cert.pem",
334                                          net::X509Certificate::FORMAT_AUTO);
335   ASSERT_EQ(1u, cert_list.size());
336
337   EXPECT_CALL(network_config_handler_,
338               SetPolicy(onc::ONC_SOURCE_USER_POLICY, _, _, _));
339   EXPECT_CALL(*certificate_importer_, ImportCertificates(_, _, _))
340       .WillRepeatedly(SetCertificateList(cert_list));
341
342   UserNetworkConfigurationUpdater* updater =
343       CreateNetworkConfigurationUpdaterForUserPolicy(
344           false /* do not allow trusted certs from policy */,
345           true /* set certificate importer */);
346   MarkPolicyProviderInitialized();
347
348   // Certificates with the "Web" trust flag set should not be forwarded to
349   // observers.
350   FakeWebTrustedCertsObserver observer;
351   updater->AddTrustedCertsObserver(&observer);
352
353   base::RunLoop().RunUntilIdle();
354
355   net::CertificateList trust_anchors;
356   updater->GetWebTrustedCertificates(&trust_anchors);
357   EXPECT_TRUE(trust_anchors.empty());
358
359   EXPECT_TRUE(observer.trust_anchors_.empty());
360   updater->RemoveTrustedCertsObserver(&observer);
361 }
362
363 TEST_F(NetworkConfigurationUpdaterTest,
364        AllowTrustedCertificatesFromPolicyInitially) {
365   // Ignore network configuration changes.
366   EXPECT_CALL(network_config_handler_, SetPolicy(_, _, _, _))
367       .Times(AnyNumber());
368
369   net::CertificateList cert_list;
370   cert_list =
371       net::CreateCertificateListFromFile(net::GetTestCertsDirectory(),
372                                          "ok_cert.pem",
373                                          net::X509Certificate::FORMAT_AUTO);
374   ASSERT_EQ(1u, cert_list.size());
375
376   EXPECT_CALL(*certificate_importer_,
377               ImportCertificates(_, onc::ONC_SOURCE_USER_POLICY, _))
378       .WillRepeatedly(SetCertificateList(cert_list));
379
380   UserNetworkConfigurationUpdater* updater =
381       CreateNetworkConfigurationUpdaterForUserPolicy(
382           true /* allow trusted certs from policy */,
383           true /* set certificate importer */);
384   MarkPolicyProviderInitialized();
385
386   base::RunLoop().RunUntilIdle();
387
388   // Certificates with the "Web" trust flag set will be returned.
389   net::CertificateList trust_anchors;
390   updater->GetWebTrustedCertificates(&trust_anchors);
391   EXPECT_EQ(1u, trust_anchors.size());
392 }
393
394 TEST_F(NetworkConfigurationUpdaterTest,
395        AllowTrustedCertificatesFromPolicyOnUpdate) {
396   // Ignore network configuration changes.
397   EXPECT_CALL(network_config_handler_, SetPolicy(_, _, _, _))
398       .Times(AnyNumber());
399
400   // Start with an empty certificate list.
401   EXPECT_CALL(*certificate_importer_,
402               ImportCertificates(_, onc::ONC_SOURCE_USER_POLICY, _))
403       .WillRepeatedly(SetCertificateList(net::CertificateList()));
404
405   UserNetworkConfigurationUpdater* updater =
406       CreateNetworkConfigurationUpdaterForUserPolicy(
407           true /* allow trusted certs from policy */,
408           true /* set certificate importer */);
409   MarkPolicyProviderInitialized();
410
411   FakeWebTrustedCertsObserver observer;
412   updater->AddTrustedCertsObserver(&observer);
413
414   base::RunLoop().RunUntilIdle();
415
416   // Verify that the returned certificate list is empty.
417   Mock::VerifyAndClearExpectations(certificate_importer_);
418   {
419     net::CertificateList trust_anchors;
420     updater->GetWebTrustedCertificates(&trust_anchors);
421     EXPECT_TRUE(trust_anchors.empty());
422   }
423   EXPECT_TRUE(observer.trust_anchors_.empty());
424
425   // Now use a non-empty certificate list to test the observer notification.
426   net::CertificateList cert_list;
427   cert_list =
428       net::CreateCertificateListFromFile(net::GetTestCertsDirectory(),
429                                          "ok_cert.pem",
430                                          net::X509Certificate::FORMAT_AUTO);
431   ASSERT_EQ(1u, cert_list.size());
432
433   EXPECT_CALL(*certificate_importer_,
434               ImportCertificates(_, onc::ONC_SOURCE_USER_POLICY, _))
435       .WillOnce(SetCertificateList(cert_list));
436
437   // Change to any non-empty policy, so that updates are triggered. The actual
438   // content of the policy is irrelevant.
439   PolicyMap policy;
440   policy.Set(key::kOpenNetworkConfiguration,
441              POLICY_LEVEL_MANDATORY,
442              POLICY_SCOPE_USER,
443              new base::StringValue(kFakeONC),
444              NULL);
445   UpdateProviderPolicy(policy);
446   base::RunLoop().RunUntilIdle();
447
448   // Certificates with the "Web" trust flag set will be returned and forwarded
449   // to observers.
450   {
451     net::CertificateList trust_anchors;
452     updater->GetWebTrustedCertificates(&trust_anchors);
453     EXPECT_EQ(1u, trust_anchors.size());
454   }
455   EXPECT_EQ(1u, observer.trust_anchors_.size());
456
457   updater->RemoveTrustedCertsObserver(&observer);
458 }
459
460 TEST_F(NetworkConfigurationUpdaterTest,
461        DontImportCertificateBeforeCertificateImporterSet) {
462   PolicyMap policy;
463   policy.Set(key::kOpenNetworkConfiguration, POLICY_LEVEL_MANDATORY,
464              POLICY_SCOPE_USER, new base::StringValue(kFakeONC), NULL);
465   UpdateProviderPolicy(policy);
466
467   EXPECT_CALL(network_config_handler_,
468               SetPolicy(onc::ONC_SOURCE_USER_POLICY,
469                         kFakeUsernameHash,
470                         IsEqualTo(&fake_network_configs_),
471                         IsEqualTo(&fake_global_network_config_)));
472   EXPECT_CALL(*certificate_importer_, ImportCertificates(_, _ , _)).Times(0);
473
474   UserNetworkConfigurationUpdater* updater =
475       CreateNetworkConfigurationUpdaterForUserPolicy(
476           true /* allow trusted certs from policy */,
477           false /* do not set certificate importer */);
478   MarkPolicyProviderInitialized();
479
480   Mock::VerifyAndClearExpectations(&network_config_handler_);
481   Mock::VerifyAndClearExpectations(certificate_importer_);
482
483   EXPECT_CALL(network_config_handler_,
484               SetPolicy(onc::ONC_SOURCE_USER_POLICY,
485                         kFakeUsernameHash,
486                         IsEqualTo(&fake_network_configs_),
487                         IsEqualTo(&fake_global_network_config_)))
488       .Times(0);
489   EXPECT_CALL(*certificate_importer_,
490               ImportCertificates(IsEqualTo(&fake_certificates_),
491                                  onc::ONC_SOURCE_USER_POLICY,
492                                   _));
493
494   ASSERT_TRUE(certificate_importer_owned_);
495   updater->SetCertificateImporterForTest(certificate_importer_owned_.Pass());
496 }
497
498 class NetworkConfigurationUpdaterTestWithParam
499     : public NetworkConfigurationUpdaterTest,
500       public testing::WithParamInterface<const char*> {
501  protected:
502   // Returns the currently tested ONC source.
503   onc::ONCSource CurrentONCSource() {
504     if (GetParam() == key::kOpenNetworkConfiguration)
505       return onc::ONC_SOURCE_USER_POLICY;
506     DCHECK(GetParam() == key::kDeviceOpenNetworkConfiguration);
507     return onc::ONC_SOURCE_DEVICE_POLICY;
508   }
509
510   // Returns the expected username hash to push policies to
511   // ManagedNetworkConfigurationHandler.
512   std::string ExpectedUsernameHash() {
513     if (GetParam() == key::kOpenNetworkConfiguration)
514       return kFakeUsernameHash;
515     return std::string();
516   }
517
518   size_t ExpectedImportCertificatesCallCount() {
519     if (GetParam() == key::kOpenNetworkConfiguration)
520       return 1u;
521     return 0u;
522   }
523
524   void CreateNetworkConfigurationUpdater() {
525     if (GetParam() == key::kOpenNetworkConfiguration) {
526       CreateNetworkConfigurationUpdaterForUserPolicy(
527           false /* do not allow trusted certs from policy */,
528           true /* set certificate importer */);
529     } else {
530       CreateNetworkConfigurationUpdaterForDevicePolicy();
531     }
532   }
533 };
534
535 TEST_P(NetworkConfigurationUpdaterTestWithParam, InitialUpdates) {
536   PolicyMap policy;
537   policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
538              new base::StringValue(kFakeONC), NULL);
539   UpdateProviderPolicy(policy);
540
541   EXPECT_CALL(network_config_handler_,
542               SetPolicy(CurrentONCSource(),
543                         ExpectedUsernameHash(),
544                         IsEqualTo(&fake_network_configs_),
545                         IsEqualTo(&fake_global_network_config_)));
546   EXPECT_CALL(*certificate_importer_,
547               ImportCertificates(IsEqualTo(&fake_certificates_),
548                                  CurrentONCSource(),
549                                   _))
550       .Times(ExpectedImportCertificatesCallCount());
551
552   CreateNetworkConfigurationUpdater();
553   MarkPolicyProviderInitialized();
554 }
555
556 TEST_P(NetworkConfigurationUpdaterTestWithParam,
557        PolicyNotSetBeforePolicyProviderInitialized) {
558   PolicyMap policy;
559   policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
560              new base::StringValue(kFakeONC), NULL);
561   UpdateProviderPolicy(policy);
562
563   EXPECT_CALL(network_config_handler_,
564               SetPolicy(CurrentONCSource(),
565                         ExpectedUsernameHash(),
566                         IsEqualTo(&fake_network_configs_),
567                         IsEqualTo(&fake_global_network_config_)))
568       .Times(0);
569   EXPECT_CALL(*certificate_importer_,
570               ImportCertificates(IsEqualTo(&fake_certificates_),
571                                  CurrentONCSource(),
572                                   _))
573       .Times(0);
574
575   CreateNetworkConfigurationUpdater();
576
577   Mock::VerifyAndClearExpectations(&network_config_handler_);
578   Mock::VerifyAndClearExpectations(certificate_importer_);
579
580   EXPECT_CALL(network_config_handler_,
581               SetPolicy(CurrentONCSource(),
582                         ExpectedUsernameHash(),
583                         IsEqualTo(&fake_network_configs_),
584                         IsEqualTo(&fake_global_network_config_)));
585   EXPECT_CALL(*certificate_importer_,
586               ImportCertificates(IsEqualTo(&fake_certificates_),
587                                  CurrentONCSource(),
588                                   _))
589       .Times(ExpectedImportCertificatesCallCount());
590
591   MarkPolicyProviderInitialized();
592 }
593
594 TEST_P(NetworkConfigurationUpdaterTestWithParam,
595        PolicyAppliedImmediatelyIfProvidersInitialized) {
596   MarkPolicyProviderInitialized();
597
598   PolicyMap policy;
599   policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
600              new base::StringValue(kFakeONC), NULL);
601   UpdateProviderPolicy(policy);
602
603   EXPECT_CALL(network_config_handler_,
604               SetPolicy(CurrentONCSource(),
605                         ExpectedUsernameHash(),
606                         IsEqualTo(&fake_network_configs_),
607                         IsEqualTo(&fake_global_network_config_)));
608   EXPECT_CALL(*certificate_importer_,
609               ImportCertificates(IsEqualTo(&fake_certificates_),
610                                  CurrentONCSource(),
611                                   _))
612       .Times(ExpectedImportCertificatesCallCount());
613
614   CreateNetworkConfigurationUpdater();
615 }
616
617 TEST_P(NetworkConfigurationUpdaterTestWithParam, PolicyChange) {
618   // Ignore the initial updates.
619   EXPECT_CALL(network_config_handler_, SetPolicy(_, _, _, _)).Times(AtLeast(1));
620   EXPECT_CALL(*certificate_importer_, ImportCertificates(_, _, _))
621       .Times(AtLeast(ExpectedImportCertificatesCallCount()));
622
623   CreateNetworkConfigurationUpdater();
624   MarkPolicyProviderInitialized();
625
626   Mock::VerifyAndClearExpectations(&network_config_handler_);
627   Mock::VerifyAndClearExpectations(certificate_importer_);
628
629   // The Updater should update if policy changes.
630   EXPECT_CALL(network_config_handler_,
631               SetPolicy(CurrentONCSource(),
632                         _,
633                         IsEqualTo(&fake_network_configs_),
634                         IsEqualTo(&fake_global_network_config_)));
635   EXPECT_CALL(*certificate_importer_,
636               ImportCertificates(IsEqualTo(&fake_certificates_),
637                                  CurrentONCSource(),
638                                   _))
639       .Times(ExpectedImportCertificatesCallCount());
640
641   PolicyMap policy;
642   policy.Set(GetParam(), POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
643              new base::StringValue(kFakeONC), NULL);
644   UpdateProviderPolicy(policy);
645   Mock::VerifyAndClearExpectations(&network_config_handler_);
646   Mock::VerifyAndClearExpectations(certificate_importer_);
647
648   // Another update is expected if the policy goes away.
649   EXPECT_CALL(network_config_handler_,
650               SetPolicy(CurrentONCSource(), _, IsEmpty(), IsEmpty()));
651   EXPECT_CALL(*certificate_importer_,
652               ImportCertificates(IsEmpty(), CurrentONCSource(), _))
653       .Times(ExpectedImportCertificatesCallCount());
654
655   policy.Erase(GetParam());
656   UpdateProviderPolicy(policy);
657 }
658
659 INSTANTIATE_TEST_CASE_P(NetworkConfigurationUpdaterTestWithParamInstance,
660                         NetworkConfigurationUpdaterTestWithParam,
661                         testing::Values(key::kDeviceOpenNetworkConfiguration,
662                                         key::kOpenNetworkConfiguration));
663
664 }  // namespace policy