Switch global error menu icon to vectorized MD asset
[chromium-blink-merge.git] / chrome / browser / policy / cloud / cloud_policy_browsertest.cc
blob946f11934e0ecba20ac01f5a41bb0a5897767c34
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 "base/callback.h"
6 #include "base/command_line.h"
7 #include "base/files/file_path.h"
8 #include "base/files/file_util.h"
9 #include "base/files/scoped_temp_dir.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/path_service.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/run_loop.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/time/time.h"
16 #include "chrome/browser/browser_process.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/invalidation/fake_invalidation_service.h"
19 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
20 #include "chrome/browser/policy/profile_policy_connector.h"
21 #include "chrome/browser/policy/profile_policy_connector_factory.h"
22 #include "chrome/browser/policy/test/local_policy_test_server.h"
23 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/ui/browser.h"
25 #include "chrome/test/base/in_process_browser_test.h"
26 #include "components/invalidation/impl/profile_invalidation_provider.h"
27 #include "components/invalidation/public/invalidation.h"
28 #include "components/invalidation/public/invalidation_service.h"
29 #include "components/keyed_service/core/keyed_service.h"
30 #include "components/policy/core/browser/browser_policy_connector.h"
31 #include "components/policy/core/common/cloud/cloud_policy_client.h"
32 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
33 #include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
34 #include "components/policy/core/common/external_data_fetcher.h"
35 #include "components/policy/core/common/policy_map.h"
36 #include "components/policy/core/common/policy_service.h"
37 #include "components/policy/core/common/policy_switches.h"
38 #include "components/policy/core/common/policy_test_utils.h"
39 #include "content/public/browser/notification_service.h"
40 #include "content/public/browser/notification_source.h"
41 #include "content/public/test/test_utils.h"
42 #include "net/url_request/url_request_context_getter.h"
43 #include "policy/policy_constants.h"
44 #include "policy/proto/chrome_settings.pb.h"
45 #include "policy/proto/cloud_policy.pb.h"
46 #include "policy/proto/device_management_backend.pb.h"
47 #include "testing/gmock/include/gmock/gmock.h"
48 #include "testing/gtest/include/gtest/gtest.h"
49 #include "url/gurl.h"
51 #if defined(OS_CHROMEOS)
52 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
53 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
54 #include "chromeos/chromeos_paths.h"
55 #include "chromeos/dbus/cryptohome_client.h"
56 #include "chromeos/login/user_names.h"
57 #else
58 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
59 #include "chrome/browser/signin/signin_manager_factory.h"
60 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
61 #include "components/signin/core/browser/signin_manager.h"
62 #endif
64 using testing::AnyNumber;
65 using testing::InvokeWithoutArgs;
66 using testing::Mock;
67 using testing::Return;
68 using testing::_;
70 namespace content {
71 class BrowserContext;
74 namespace em = enterprise_management;
76 namespace policy {
78 namespace {
80 scoped_ptr<KeyedService> BuildFakeProfileInvalidationProvider(
81 content::BrowserContext* context) {
82 return make_scoped_ptr(new invalidation::ProfileInvalidationProvider(
83 scoped_ptr<invalidation::InvalidationService>(
84 new invalidation::FakeInvalidationService)));
87 #if !defined(OS_CHROMEOS)
88 const char* GetTestGaiaId() {
89 return "gaia-id-user@example.com";
91 #endif
93 const char* GetTestUser() {
94 #if defined(OS_CHROMEOS)
95 return chromeos::login::kStubUser;
96 #else
97 return "user@example.com";
98 #endif
101 std::string GetEmptyPolicy() {
102 const char kEmptyPolicy[] =
104 " \"%s\": {"
105 " \"mandatory\": {},"
106 " \"recommended\": {}"
107 " },"
108 " \"managed_users\": [ \"*\" ],"
109 " \"policy_user\": \"%s\","
110 " \"current_key_index\": 0"
111 "}";
113 return base::StringPrintf(
114 kEmptyPolicy, dm_protocol::kChromeUserPolicyType, GetTestUser());
117 std::string GetTestPolicy(const char* homepage, int key_version) {
118 const char kTestPolicy[] =
120 " \"%s\": {"
121 " \"mandatory\": {"
122 " \"ShowHomeButton\": true,"
123 " \"RestoreOnStartup\": 4,"
124 " \"URLBlacklist\": [ \"dev.chromium.org\", \"youtube.com\" ],"
125 " \"MaxInvalidationFetchDelay\": 1000"
126 " },"
127 " \"recommended\": {"
128 " \"HomepageLocation\": \"%s\""
129 " }"
130 " },"
131 " \"managed_users\": [ \"*\" ],"
132 " \"policy_user\": \"%s\","
133 " \"current_key_index\": %d,"
134 " \"invalidation_source\": 16,"
135 " \"invalidation_name\": \"test_policy\""
136 "}";
138 return base::StringPrintf(kTestPolicy,
139 dm_protocol::kChromeUserPolicyType,
140 homepage,
141 GetTestUser(),
142 key_version);
145 void GetExpectedDefaultPolicy(PolicyMap* policy_map) {
146 #if defined(OS_CHROMEOS)
147 policy_map->Set(key::kChromeOsMultiProfileUserBehavior,
148 POLICY_LEVEL_MANDATORY,
149 POLICY_SCOPE_USER,
150 new base::StringValue("primary-only"),
151 NULL);
152 policy_map->Set(key::kEasyUnlockAllowed,
153 POLICY_LEVEL_MANDATORY,
154 POLICY_SCOPE_USER,
155 new base::FundamentalValue(false),
156 NULL);
157 policy_map->Set(key::kCaptivePortalAuthenticationIgnoresProxy,
158 POLICY_LEVEL_MANDATORY,
159 POLICY_SCOPE_USER,
160 new base::FundamentalValue(false),
161 NULL);
162 #endif
165 void GetExpectedTestPolicy(PolicyMap* expected, const char* homepage) {
166 expected->Set(key::kShowHomeButton,
167 POLICY_LEVEL_MANDATORY,
168 POLICY_SCOPE_USER,
169 new base::FundamentalValue(true),
170 NULL);
171 expected->Set(key::kRestoreOnStartup,
172 POLICY_LEVEL_MANDATORY,
173 POLICY_SCOPE_USER,
174 new base::FundamentalValue(4),
175 NULL);
176 base::ListValue list;
177 list.AppendString("dev.chromium.org");
178 list.AppendString("youtube.com");
179 expected->Set(
180 key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
181 list.DeepCopy(), NULL);
182 expected->Set(key::kMaxInvalidationFetchDelay,
183 POLICY_LEVEL_MANDATORY,
184 POLICY_SCOPE_USER,
185 new base::FundamentalValue(1000),
186 NULL);
187 expected->Set(key::kHomepageLocation,
188 POLICY_LEVEL_RECOMMENDED,
189 POLICY_SCOPE_USER,
190 new base::StringValue(homepage),
191 NULL);
192 #if defined(OS_CHROMEOS)
193 expected->Set(key::kChromeOsMultiProfileUserBehavior,
194 POLICY_LEVEL_MANDATORY,
195 POLICY_SCOPE_USER,
196 new base::StringValue("primary-only"),
197 NULL);
198 expected->Set(key::kEasyUnlockAllowed,
199 POLICY_LEVEL_MANDATORY,
200 POLICY_SCOPE_USER,
201 new base::FundamentalValue(false),
202 NULL);
203 expected->Set(key::kCaptivePortalAuthenticationIgnoresProxy,
204 POLICY_LEVEL_MANDATORY,
205 POLICY_SCOPE_USER,
206 new base::FundamentalValue(false),
207 NULL);
208 #endif
211 } // namespace
213 // Tests the cloud policy stack(s).
214 class CloudPolicyTest : public InProcessBrowserTest,
215 public PolicyService::Observer {
216 protected:
217 CloudPolicyTest() {}
218 ~CloudPolicyTest() override {}
220 void SetUpInProcessBrowserTestFixture() override {
221 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
222 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetEmptyPolicy()));
224 test_server_.reset(new LocalPolicyTestServer(policy_file_path()));
225 ASSERT_TRUE(test_server_->Start());
227 std::string url = test_server_->GetServiceURL().spec();
229 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
230 command_line->AppendSwitchASCII(switches::kDeviceManagementUrl, url);
232 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
233 RegisterTestingFactory(BuildFakeProfileInvalidationProvider);
236 void SetUpOnMainThread() override {
237 ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process->policy_service()))
238 << "Pre-existing policies in this machine will make this test fail.";
240 BrowserPolicyConnector* connector =
241 g_browser_process->browser_policy_connector();
242 connector->ScheduleServiceInitialization(0);
244 #if defined(OS_CHROMEOS)
245 UserCloudPolicyManagerChromeOS* policy_manager =
246 UserCloudPolicyManagerFactoryChromeOS::GetForProfile(
247 browser()->profile());
248 ASSERT_TRUE(policy_manager);
249 #else
250 // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
251 // the username to the UserCloudPolicyValidator.
252 SigninManager* signin_manager =
253 SigninManagerFactory::GetForProfile(browser()->profile());
254 ASSERT_TRUE(signin_manager);
255 signin_manager->SetAuthenticatedAccountInfo(GetTestGaiaId(), GetTestUser());
257 UserCloudPolicyManager* policy_manager =
258 UserCloudPolicyManagerFactory::GetForBrowserContext(
259 browser()->profile());
260 ASSERT_TRUE(policy_manager);
261 policy_manager->Connect(
262 g_browser_process->local_state(),
263 g_browser_process->system_request_context(),
264 UserCloudPolicyManager::CreateCloudPolicyClient(
265 connector->device_management_service(),
266 g_browser_process->system_request_context()).Pass());
267 #endif // defined(OS_CHROMEOS)
269 ASSERT_TRUE(policy_manager->core()->client());
270 base::RunLoop run_loop;
271 MockCloudPolicyClientObserver observer;
272 EXPECT_CALL(observer, OnRegistrationStateChanged(_)).WillOnce(
273 InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
274 policy_manager->core()->client()->AddObserver(&observer);
276 // Give a bogus OAuth token to the |policy_manager|. This should make its
277 // CloudPolicyClient fetch the DMToken.
278 ASSERT_FALSE(policy_manager->core()->client()->is_registered());
279 em::DeviceRegisterRequest::Type registration_type =
280 #if defined(OS_CHROMEOS)
281 em::DeviceRegisterRequest::USER;
282 #else
283 em::DeviceRegisterRequest::BROWSER;
284 #endif
285 policy_manager->core()->client()->Register(
286 registration_type, em::DeviceRegisterRequest::FLAVOR_USER_REGISTRATION,
287 "bogus", std::string(), std::string(), std::string());
288 run_loop.Run();
289 Mock::VerifyAndClearExpectations(&observer);
290 policy_manager->core()->client()->RemoveObserver(&observer);
291 EXPECT_TRUE(policy_manager->core()->client()->is_registered());
293 #if defined(OS_CHROMEOS)
294 // Get the path to the user policy key file.
295 base::FilePath user_policy_key_dir;
296 ASSERT_TRUE(
297 PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_policy_key_dir));
298 std::string sanitized_username =
299 chromeos::CryptohomeClient::GetStubSanitizedUsername(GetTestUser());
300 user_policy_key_file_ = user_policy_key_dir.AppendASCII(sanitized_username)
301 .AppendASCII("policy.pub");
302 #endif
305 PolicyService* GetPolicyService() {
306 ProfilePolicyConnector* profile_connector =
307 ProfilePolicyConnectorFactory::GetForBrowserContext(
308 browser()->profile());
309 return profile_connector->policy_service();
312 invalidation::FakeInvalidationService* GetInvalidationService() {
313 return static_cast<invalidation::FakeInvalidationService*>(
314 static_cast<invalidation::ProfileInvalidationProvider*>(
315 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
316 GetForProfile(browser()->profile()))->GetInvalidationService());
319 void SetServerPolicy(const std::string& policy) {
320 int result = base::WriteFile(policy_file_path(), policy.data(),
321 policy.size());
322 ASSERT_EQ(static_cast<int>(policy.size()), result);
325 base::FilePath policy_file_path() const {
326 return temp_dir_.path().AppendASCII("policy.json");
329 void OnPolicyUpdated(const PolicyNamespace& ns,
330 const PolicyMap& previous,
331 const PolicyMap& current) override {
332 if (!on_policy_updated_.is_null()) {
333 on_policy_updated_.Run();
334 on_policy_updated_.Reset();
338 void OnPolicyServiceInitialized(PolicyDomain domain) override {}
340 base::ScopedTempDir temp_dir_;
341 scoped_ptr<LocalPolicyTestServer> test_server_;
342 base::FilePath user_policy_key_file_;
343 base::Closure on_policy_updated_;
346 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicy) {
347 PolicyService* policy_service = GetPolicyService();
349 base::RunLoop run_loop;
350 // This does the initial fetch and stores the initial key.
351 policy_service->RefreshPolicies(run_loop.QuitClosure());
352 run_loop.Run();
355 PolicyMap default_policy;
356 GetExpectedDefaultPolicy(&default_policy);
357 EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
358 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
360 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
361 PolicyMap expected;
362 GetExpectedTestPolicy(&expected, "google.com");
364 base::RunLoop run_loop;
365 // This fetches the new policies, using the same key.
366 policy_service->RefreshPolicies(run_loop.QuitClosure());
367 run_loop.Run();
369 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
370 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
373 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, InvalidatePolicy) {
374 PolicyService* policy_service = GetPolicyService();
375 policy_service->AddObserver(POLICY_DOMAIN_CHROME, this);
377 // Perform the initial fetch.
378 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
380 base::RunLoop run_loop;
381 policy_service->RefreshPolicies(run_loop.QuitClosure());
382 run_loop.Run();
385 // Update the homepage in the policy and trigger an invalidation.
386 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("youtube.com", 0)));
387 base::TimeDelta now =
388 base::Time::NowFromSystemTime() - base::Time::UnixEpoch();
389 GetInvalidationService()->EmitInvalidationForTest(
390 syncer::Invalidation::Init(
391 invalidation::ObjectId(16, "test_policy"),
392 now.InMicroseconds() /* version */,
393 "payload"));
395 base::RunLoop run_loop;
396 on_policy_updated_ = run_loop.QuitClosure();
397 run_loop.Run();
400 // Check that the updated policy was fetched.
401 PolicyMap expected;
402 GetExpectedTestPolicy(&expected, "youtube.com");
403 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
404 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
406 policy_service->RemoveObserver(POLICY_DOMAIN_CHROME, this);
409 #if defined(OS_CHROMEOS)
410 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicyWithRotatedKey) {
411 PolicyService* policy_service = GetPolicyService();
413 base::RunLoop run_loop;
414 // This does the initial fetch and stores the initial key.
415 policy_service->RefreshPolicies(run_loop.QuitClosure());
416 run_loop.Run();
419 // Read the initial key.
420 std::string initial_key;
421 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &initial_key));
423 PolicyMap default_policy;
424 GetExpectedDefaultPolicy(&default_policy);
425 EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
426 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
428 // Set the new policies and a new key at the server.
429 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 1)));
430 PolicyMap expected;
431 GetExpectedTestPolicy(&expected, "google.com");
433 base::RunLoop run_loop;
434 // This fetches the new policies and does a key rotation.
435 policy_service->RefreshPolicies(run_loop.QuitClosure());
436 run_loop.Run();
438 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
439 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
441 // Verify that the key was rotated.
442 std::string rotated_key;
443 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &rotated_key));
444 EXPECT_NE(rotated_key, initial_key);
446 // Another refresh using the same key won't rotate it again.
448 base::RunLoop run_loop;
449 policy_service->RefreshPolicies(run_loop.QuitClosure());
450 run_loop.Run();
452 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
453 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
454 std::string current_key;
455 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &current_key));
456 EXPECT_EQ(rotated_key, current_key);
458 #endif
460 TEST(CloudPolicyProtoTest, VerifyProtobufEquivalence) {
461 // There are 2 protobufs that can be used for user cloud policy:
462 // cloud_policy.proto and chrome_settings.proto. chrome_settings.proto is the
463 // version used by the server, but generates one proto message per policy; to
464 // save binary size on the client, the other version shares proto messages for
465 // policies of the same type. They generate the same bytes on the wire though,
466 // so they are compatible. This test verifies that that stays true.
468 // Build a ChromeSettingsProto message with one policy of each supported type.
469 em::ChromeSettingsProto chrome_settings;
470 chrome_settings.mutable_homepagelocation()->set_homepagelocation(
471 "chromium.org");
472 chrome_settings.mutable_showhomebutton()->set_showhomebutton(true);
473 chrome_settings.mutable_restoreonstartup()->set_restoreonstartup(4);
474 em::StringList* list =
475 chrome_settings.mutable_disabledschemes()->mutable_disabledschemes();
476 list->add_entries("ftp");
477 list->add_entries("mailto");
478 // Try explicitly setting a policy mode too.
479 chrome_settings.mutable_disablespdy()->set_disablespdy(false);
480 chrome_settings.mutable_disablespdy()->mutable_policy_options()->set_mode(
481 em::PolicyOptions::MANDATORY);
482 chrome_settings.mutable_syncdisabled()->set_syncdisabled(true);
483 chrome_settings.mutable_syncdisabled()->mutable_policy_options()->set_mode(
484 em::PolicyOptions::RECOMMENDED);
486 // Build an equivalent CloudPolicySettings message.
487 em::CloudPolicySettings cloud_policy;
488 cloud_policy.mutable_homepagelocation()->set_value("chromium.org");
489 cloud_policy.mutable_showhomebutton()->set_value(true);
490 cloud_policy.mutable_restoreonstartup()->set_value(4);
491 list = cloud_policy.mutable_disabledschemes()->mutable_value();
492 list->add_entries("ftp");
493 list->add_entries("mailto");
494 cloud_policy.mutable_disablespdy()->set_value(false);
495 cloud_policy.mutable_disablespdy()->mutable_policy_options()->set_mode(
496 em::PolicyOptions::MANDATORY);
497 cloud_policy.mutable_syncdisabled()->set_value(true);
498 cloud_policy.mutable_syncdisabled()->mutable_policy_options()->set_mode(
499 em::PolicyOptions::RECOMMENDED);
501 // They should now serialize to the same bytes.
502 std::string chrome_settings_serialized;
503 std::string cloud_policy_serialized;
504 ASSERT_TRUE(chrome_settings.SerializeToString(&chrome_settings_serialized));
505 ASSERT_TRUE(cloud_policy.SerializeToString(&cloud_policy_serialized));
506 EXPECT_EQ(chrome_settings_serialized, cloud_policy_serialized);
509 } // namespace policy