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