ProfilePolicyConnectorFactory: Refactoring from Profile to BrowserContext.
[chromium-blink-merge.git] / chrome / browser / policy / cloud / cloud_policy_browsertest.cc
blob5224eca8139319287e8b463c7aeba25c5f5d0958
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/invalidation.h"
27 #include "components/invalidation/invalidation_service.h"
28 #include "components/invalidation/profile_invalidation_provider.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 KeyedService* BuildFakeProfileInvalidationProvider(
81 content::BrowserContext* context) {
82 return new invalidation::ProfileInvalidationProvider(
83 scoped_ptr<invalidation::InvalidationService>(
84 new invalidation::FakeInvalidationService));
87 const char* GetTestUser() {
88 #if defined(OS_CHROMEOS)
89 return chromeos::login::kStubUser;
90 #else
91 return "user@example.com";
92 #endif
95 std::string GetEmptyPolicy() {
96 const char kEmptyPolicy[] =
97 "{"
98 " \"%s\": {"
99 " \"mandatory\": {},"
100 " \"recommended\": {}"
101 " },"
102 " \"managed_users\": [ \"*\" ],"
103 " \"policy_user\": \"%s\","
104 " \"current_key_index\": 0"
105 "}";
107 return base::StringPrintf(
108 kEmptyPolicy, dm_protocol::kChromeUserPolicyType, GetTestUser());
111 std::string GetTestPolicy(const char* homepage, int key_version) {
112 const char kTestPolicy[] =
114 " \"%s\": {"
115 " \"mandatory\": {"
116 " \"ShowHomeButton\": true,"
117 " \"RestoreOnStartup\": 4,"
118 " \"URLBlacklist\": [ \"dev.chromium.org\", \"youtube.com\" ],"
119 " \"MaxInvalidationFetchDelay\": 1000"
120 " },"
121 " \"recommended\": {"
122 " \"HomepageLocation\": \"%s\""
123 " }"
124 " },"
125 " \"managed_users\": [ \"*\" ],"
126 " \"policy_user\": \"%s\","
127 " \"current_key_index\": %d,"
128 " \"invalidation_source\": 16,"
129 " \"invalidation_name\": \"test_policy\""
130 "}";
132 return base::StringPrintf(kTestPolicy,
133 dm_protocol::kChromeUserPolicyType,
134 homepage,
135 GetTestUser(),
136 key_version);
139 void GetExpectedDefaultPolicy(PolicyMap* policy_map) {
140 #if defined(OS_CHROMEOS)
141 policy_map->Set(key::kChromeOsMultiProfileUserBehavior,
142 POLICY_LEVEL_MANDATORY,
143 POLICY_SCOPE_USER,
144 new base::StringValue("primary-only"),
145 NULL);
146 policy_map->Set(key::kEasyUnlockAllowed,
147 POLICY_LEVEL_MANDATORY,
148 POLICY_SCOPE_USER,
149 new base::FundamentalValue(false),
150 NULL);
151 #endif
154 void GetExpectedTestPolicy(PolicyMap* expected, const char* homepage) {
155 expected->Set(key::kShowHomeButton,
156 POLICY_LEVEL_MANDATORY,
157 POLICY_SCOPE_USER,
158 new base::FundamentalValue(true),
159 NULL);
160 expected->Set(key::kRestoreOnStartup,
161 POLICY_LEVEL_MANDATORY,
162 POLICY_SCOPE_USER,
163 new base::FundamentalValue(4),
164 NULL);
165 base::ListValue list;
166 list.AppendString("dev.chromium.org");
167 list.AppendString("youtube.com");
168 expected->Set(
169 key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
170 list.DeepCopy(), NULL);
171 expected->Set(key::kMaxInvalidationFetchDelay,
172 POLICY_LEVEL_MANDATORY,
173 POLICY_SCOPE_USER,
174 new base::FundamentalValue(1000),
175 NULL);
176 expected->Set(key::kHomepageLocation,
177 POLICY_LEVEL_RECOMMENDED,
178 POLICY_SCOPE_USER,
179 new base::StringValue(homepage),
180 NULL);
181 #if defined(OS_CHROMEOS)
182 expected->Set(key::kChromeOsMultiProfileUserBehavior,
183 POLICY_LEVEL_MANDATORY,
184 POLICY_SCOPE_USER,
185 new base::StringValue("primary-only"),
186 NULL);
187 expected->Set(key::kEasyUnlockAllowed,
188 POLICY_LEVEL_MANDATORY,
189 POLICY_SCOPE_USER,
190 new base::FundamentalValue(false),
191 NULL);
192 #endif
195 } // namespace
197 // Tests the cloud policy stack(s).
198 class CloudPolicyTest : public InProcessBrowserTest,
199 public PolicyService::Observer {
200 protected:
201 CloudPolicyTest() {}
202 ~CloudPolicyTest() override {}
204 void SetUpInProcessBrowserTestFixture() override {
205 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
206 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetEmptyPolicy()));
208 test_server_.reset(new LocalPolicyTestServer(policy_file_path()));
209 ASSERT_TRUE(test_server_->Start());
211 std::string url = test_server_->GetServiceURL().spec();
213 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
214 command_line->AppendSwitchASCII(switches::kDeviceManagementUrl, url);
216 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
217 RegisterTestingFactory(BuildFakeProfileInvalidationProvider);
220 void SetUpOnMainThread() override {
221 ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process->policy_service()))
222 << "Pre-existing policies in this machine will make this test fail.";
224 BrowserPolicyConnector* connector =
225 g_browser_process->browser_policy_connector();
226 connector->ScheduleServiceInitialization(0);
228 #if defined(OS_CHROMEOS)
229 UserCloudPolicyManagerChromeOS* policy_manager =
230 UserCloudPolicyManagerFactoryChromeOS::GetForProfile(
231 browser()->profile());
232 ASSERT_TRUE(policy_manager);
233 #else
234 // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
235 // the username to the UserCloudPolicyValidator.
236 SigninManager* signin_manager =
237 SigninManagerFactory::GetForProfile(browser()->profile());
238 ASSERT_TRUE(signin_manager);
239 signin_manager->SetAuthenticatedUsername(GetTestUser());
241 UserCloudPolicyManager* policy_manager =
242 UserCloudPolicyManagerFactory::GetForBrowserContext(
243 browser()->profile());
244 ASSERT_TRUE(policy_manager);
245 policy_manager->Connect(
246 g_browser_process->local_state(),
247 g_browser_process->system_request_context(),
248 UserCloudPolicyManager::CreateCloudPolicyClient(
249 connector->device_management_service(),
250 g_browser_process->system_request_context()).Pass());
251 #endif // defined(OS_CHROMEOS)
253 ASSERT_TRUE(policy_manager->core()->client());
254 base::RunLoop run_loop;
255 MockCloudPolicyClientObserver observer;
256 EXPECT_CALL(observer, OnRegistrationStateChanged(_)).WillOnce(
257 InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
258 policy_manager->core()->client()->AddObserver(&observer);
260 // Give a bogus OAuth token to the |policy_manager|. This should make its
261 // CloudPolicyClient fetch the DMToken.
262 ASSERT_FALSE(policy_manager->core()->client()->is_registered());
263 em::DeviceRegisterRequest::Type registration_type =
264 #if defined(OS_CHROMEOS)
265 em::DeviceRegisterRequest::USER;
266 #else
267 em::DeviceRegisterRequest::BROWSER;
268 #endif
269 policy_manager->core()->client()->Register(
270 registration_type, em::DeviceRegisterRequest::FLAVOR_USER_REGISTRATION,
271 "bogus", std::string(), std::string(), std::string());
272 run_loop.Run();
273 Mock::VerifyAndClearExpectations(&observer);
274 policy_manager->core()->client()->RemoveObserver(&observer);
275 EXPECT_TRUE(policy_manager->core()->client()->is_registered());
277 #if defined(OS_CHROMEOS)
278 // Get the path to the user policy key file.
279 base::FilePath user_policy_key_dir;
280 ASSERT_TRUE(
281 PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_policy_key_dir));
282 std::string sanitized_username =
283 chromeos::CryptohomeClient::GetStubSanitizedUsername(GetTestUser());
284 user_policy_key_file_ = user_policy_key_dir.AppendASCII(sanitized_username)
285 .AppendASCII("policy.pub");
286 #endif
289 PolicyService* GetPolicyService() {
290 ProfilePolicyConnector* profile_connector =
291 ProfilePolicyConnectorFactory::GetForBrowserContext(
292 browser()->profile());
293 return profile_connector->policy_service();
296 invalidation::FakeInvalidationService* GetInvalidationService() {
297 return static_cast<invalidation::FakeInvalidationService*>(
298 static_cast<invalidation::ProfileInvalidationProvider*>(
299 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
300 GetForProfile(browser()->profile()))->GetInvalidationService());
303 void SetServerPolicy(const std::string& policy) {
304 int result = base::WriteFile(policy_file_path(), policy.data(),
305 policy.size());
306 ASSERT_EQ(static_cast<int>(policy.size()), result);
309 base::FilePath policy_file_path() const {
310 return temp_dir_.path().AppendASCII("policy.json");
313 void OnPolicyUpdated(const PolicyNamespace& ns,
314 const PolicyMap& previous,
315 const PolicyMap& current) override {
316 if (!on_policy_updated_.is_null()) {
317 on_policy_updated_.Run();
318 on_policy_updated_.Reset();
322 void OnPolicyServiceInitialized(PolicyDomain domain) override {}
324 base::ScopedTempDir temp_dir_;
325 scoped_ptr<LocalPolicyTestServer> test_server_;
326 base::FilePath user_policy_key_file_;
327 base::Closure on_policy_updated_;
330 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicy) {
331 PolicyService* policy_service = GetPolicyService();
333 base::RunLoop run_loop;
334 // This does the initial fetch and stores the initial key.
335 policy_service->RefreshPolicies(run_loop.QuitClosure());
336 run_loop.Run();
339 PolicyMap default_policy;
340 GetExpectedDefaultPolicy(&default_policy);
341 EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
342 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
344 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
345 PolicyMap expected;
346 GetExpectedTestPolicy(&expected, "google.com");
348 base::RunLoop run_loop;
349 // This fetches the new policies, using the same key.
350 policy_service->RefreshPolicies(run_loop.QuitClosure());
351 run_loop.Run();
353 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
354 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
357 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, InvalidatePolicy) {
358 PolicyService* policy_service = GetPolicyService();
359 policy_service->AddObserver(POLICY_DOMAIN_CHROME, this);
361 // Perform the initial fetch.
362 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
364 base::RunLoop run_loop;
365 policy_service->RefreshPolicies(run_loop.QuitClosure());
366 run_loop.Run();
369 // Update the homepage in the policy and trigger an invalidation.
370 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("youtube.com", 0)));
371 base::TimeDelta now =
372 base::Time::NowFromSystemTime() - base::Time::UnixEpoch();
373 GetInvalidationService()->EmitInvalidationForTest(
374 syncer::Invalidation::Init(
375 invalidation::ObjectId(16, "test_policy"),
376 now.InMicroseconds() /* version */,
377 "payload"));
379 base::RunLoop run_loop;
380 on_policy_updated_ = run_loop.QuitClosure();
381 run_loop.Run();
384 // Check that the updated policy was fetched.
385 PolicyMap expected;
386 GetExpectedTestPolicy(&expected, "youtube.com");
387 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
388 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
390 policy_service->RemoveObserver(POLICY_DOMAIN_CHROME, this);
393 #if defined(OS_CHROMEOS)
394 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicyWithRotatedKey) {
395 PolicyService* policy_service = GetPolicyService();
397 base::RunLoop run_loop;
398 // This does the initial fetch and stores the initial key.
399 policy_service->RefreshPolicies(run_loop.QuitClosure());
400 run_loop.Run();
403 // Read the initial key.
404 std::string initial_key;
405 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &initial_key));
407 PolicyMap default_policy;
408 GetExpectedDefaultPolicy(&default_policy);
409 EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
410 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
412 // Set the new policies and a new key at the server.
413 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 1)));
414 PolicyMap expected;
415 GetExpectedTestPolicy(&expected, "google.com");
417 base::RunLoop run_loop;
418 // This fetches the new policies and does a key rotation.
419 policy_service->RefreshPolicies(run_loop.QuitClosure());
420 run_loop.Run();
422 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
423 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
425 // Verify that the key was rotated.
426 std::string rotated_key;
427 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &rotated_key));
428 EXPECT_NE(rotated_key, initial_key);
430 // Another refresh using the same key won't rotate it again.
432 base::RunLoop run_loop;
433 policy_service->RefreshPolicies(run_loop.QuitClosure());
434 run_loop.Run();
436 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
437 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
438 std::string current_key;
439 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &current_key));
440 EXPECT_EQ(rotated_key, current_key);
442 #endif
444 TEST(CloudPolicyProtoTest, VerifyProtobufEquivalence) {
445 // There are 2 protobufs that can be used for user cloud policy:
446 // cloud_policy.proto and chrome_settings.proto. chrome_settings.proto is the
447 // version used by the server, but generates one proto message per policy; to
448 // save binary size on the client, the other version shares proto messages for
449 // policies of the same type. They generate the same bytes on the wire though,
450 // so they are compatible. This test verifies that that stays true.
452 // Build a ChromeSettingsProto message with one policy of each supported type.
453 em::ChromeSettingsProto chrome_settings;
454 chrome_settings.mutable_homepagelocation()->set_homepagelocation(
455 "chromium.org");
456 chrome_settings.mutable_showhomebutton()->set_showhomebutton(true);
457 chrome_settings.mutable_restoreonstartup()->set_restoreonstartup(4);
458 em::StringList* list =
459 chrome_settings.mutable_disabledschemes()->mutable_disabledschemes();
460 list->add_entries("ftp");
461 list->add_entries("mailto");
462 // Try explicitly setting a policy mode too.
463 chrome_settings.mutable_disablespdy()->set_disablespdy(false);
464 chrome_settings.mutable_disablespdy()->mutable_policy_options()->set_mode(
465 em::PolicyOptions::MANDATORY);
466 chrome_settings.mutable_syncdisabled()->set_syncdisabled(true);
467 chrome_settings.mutable_syncdisabled()->mutable_policy_options()->set_mode(
468 em::PolicyOptions::RECOMMENDED);
470 // Build an equivalent CloudPolicySettings message.
471 em::CloudPolicySettings cloud_policy;
472 cloud_policy.mutable_homepagelocation()->set_value("chromium.org");
473 cloud_policy.mutable_showhomebutton()->set_value(true);
474 cloud_policy.mutable_restoreonstartup()->set_value(4);
475 list = cloud_policy.mutable_disabledschemes()->mutable_value();
476 list->add_entries("ftp");
477 list->add_entries("mailto");
478 cloud_policy.mutable_disablespdy()->set_value(false);
479 cloud_policy.mutable_disablespdy()->mutable_policy_options()->set_mode(
480 em::PolicyOptions::MANDATORY);
481 cloud_policy.mutable_syncdisabled()->set_value(true);
482 cloud_policy.mutable_syncdisabled()->mutable_policy_options()->set_mode(
483 em::PolicyOptions::RECOMMENDED);
485 // They should now serialize to the same bytes.
486 std::string chrome_settings_serialized;
487 std::string cloud_policy_serialized;
488 ASSERT_TRUE(chrome_settings.SerializeToString(&chrome_settings_serialized));
489 ASSERT_TRUE(cloud_policy.SerializeToString(&cloud_policy_serialized));
490 EXPECT_EQ(chrome_settings_serialized, cloud_policy_serialized);
493 } // namespace policy