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/file_util.h"
8 #include "base/files/file_path.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 "testing/gmock/include/gmock/gmock.h"
47 #include "testing/gtest/include/gtest/gtest.h"
50 #if defined(OS_CHROMEOS)
51 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
52 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
53 #include "chromeos/chromeos_paths.h"
54 #include "chromeos/dbus/cryptohome_client.h"
55 #include "chromeos/login/user_names.h"
57 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
58 #include "chrome/browser/signin/signin_manager_factory.h"
59 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
60 #include "components/signin/core/browser/signin_manager.h"
63 using testing::AnyNumber;
64 using testing::InvokeWithoutArgs;
66 using testing::Return;
73 namespace em = enterprise_management;
79 KeyedService* BuildFakeProfileInvalidationProvider(
80 content::BrowserContext* context) {
81 return new invalidation::ProfileInvalidationProvider(
82 scoped_ptr<invalidation::InvalidationService>(
83 new invalidation::FakeInvalidationService));
86 const char* GetTestUser() {
87 #if defined(OS_CHROMEOS)
88 return chromeos::login::kStubUser;
90 return "user@example.com";
94 std::string GetEmptyPolicy() {
95 const char kEmptyPolicy[] =
99 " \"recommended\": {}"
101 " \"managed_users\": [ \"*\" ],"
102 " \"policy_user\": \"%s\","
103 " \"current_key_index\": 0"
106 return base::StringPrintf(
107 kEmptyPolicy, dm_protocol::kChromeUserPolicyType, GetTestUser());
110 std::string GetTestPolicy(const char* homepage, int key_version) {
111 const char kTestPolicy[] =
115 " \"ShowHomeButton\": true,"
116 " \"RestoreOnStartup\": 4,"
117 " \"URLBlacklist\": [ \"dev.chromium.org\", \"youtube.com\" ],"
118 " \"MaxInvalidationFetchDelay\": 1000"
120 " \"recommended\": {"
121 " \"HomepageLocation\": \"%s\""
124 " \"managed_users\": [ \"*\" ],"
125 " \"policy_user\": \"%s\","
126 " \"current_key_index\": %d,"
127 " \"invalidation_source\": 16,"
128 " \"invalidation_name\": \"test_policy\""
131 return base::StringPrintf(kTestPolicy,
132 dm_protocol::kChromeUserPolicyType,
138 void GetExpectedDefaultPolicy(PolicyMap* policy_map) {
139 #if defined(OS_CHROMEOS)
140 policy_map->Set(key::kChromeOsMultiProfileUserBehavior,
141 POLICY_LEVEL_MANDATORY,
143 new base::StringValue("primary-only"),
148 void GetExpectedTestPolicy(PolicyMap* expected, const char* homepage) {
149 expected->Set(key::kShowHomeButton,
150 POLICY_LEVEL_MANDATORY,
152 new base::FundamentalValue(true),
154 expected->Set(key::kRestoreOnStartup,
155 POLICY_LEVEL_MANDATORY,
157 new base::FundamentalValue(4),
159 base::ListValue list;
160 list.AppendString("dev.chromium.org");
161 list.AppendString("youtube.com");
163 key::kURLBlacklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
164 list.DeepCopy(), NULL);
165 expected->Set(key::kMaxInvalidationFetchDelay,
166 POLICY_LEVEL_MANDATORY,
168 new base::FundamentalValue(1000),
170 expected->Set(key::kHomepageLocation,
171 POLICY_LEVEL_RECOMMENDED,
173 new base::StringValue(homepage),
175 #if defined(OS_CHROMEOS)
176 expected->Set(key::kChromeOsMultiProfileUserBehavior,
177 POLICY_LEVEL_MANDATORY,
179 new base::StringValue("primary-only"),
186 // Tests the cloud policy stack(s).
187 class CloudPolicyTest : public InProcessBrowserTest,
188 public PolicyService::Observer {
191 virtual ~CloudPolicyTest() {}
193 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
194 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
195 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetEmptyPolicy()));
197 test_server_.reset(new LocalPolicyTestServer(policy_file_path()));
198 ASSERT_TRUE(test_server_->Start());
200 std::string url = test_server_->GetServiceURL().spec();
202 CommandLine* command_line = CommandLine::ForCurrentProcess();
203 command_line->AppendSwitchASCII(switches::kDeviceManagementUrl, url);
205 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
206 RegisterTestingFactory(BuildFakeProfileInvalidationProvider);
209 virtual void SetUpOnMainThread() OVERRIDE {
210 ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process->policy_service()))
211 << "Pre-existing policies in this machine will make this test fail.";
213 BrowserPolicyConnector* connector =
214 g_browser_process->browser_policy_connector();
215 connector->ScheduleServiceInitialization(0);
217 #if defined(OS_CHROMEOS)
218 UserCloudPolicyManagerChromeOS* policy_manager =
219 UserCloudPolicyManagerFactoryChromeOS::GetForProfile(
220 browser()->profile());
221 ASSERT_TRUE(policy_manager);
223 // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
224 // the username to the UserCloudPolicyValidator.
225 SigninManager* signin_manager =
226 SigninManagerFactory::GetForProfile(browser()->profile());
227 ASSERT_TRUE(signin_manager);
228 signin_manager->SetAuthenticatedUsername(GetTestUser());
230 UserCloudPolicyManager* policy_manager =
231 UserCloudPolicyManagerFactory::GetForBrowserContext(
232 browser()->profile());
233 ASSERT_TRUE(policy_manager);
234 policy_manager->Connect(
235 g_browser_process->local_state(),
236 g_browser_process->system_request_context(),
237 UserCloudPolicyManager::CreateCloudPolicyClient(
238 connector->device_management_service(),
239 g_browser_process->system_request_context()).Pass());
240 #endif // defined(OS_CHROMEOS)
242 ASSERT_TRUE(policy_manager->core()->client());
243 base::RunLoop run_loop;
244 MockCloudPolicyClientObserver observer;
245 EXPECT_CALL(observer, OnRegistrationStateChanged(_)).WillOnce(
246 InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
247 policy_manager->core()->client()->AddObserver(&observer);
249 // Give a bogus OAuth token to the |policy_manager|. This should make its
250 // CloudPolicyClient fetch the DMToken.
251 ASSERT_FALSE(policy_manager->core()->client()->is_registered());
252 em::DeviceRegisterRequest::Type registration_type =
253 #if defined(OS_CHROMEOS)
254 em::DeviceRegisterRequest::USER;
256 em::DeviceRegisterRequest::BROWSER;
258 policy_manager->core()->client()->Register(
259 registration_type, "bogus", std::string(), false, std::string(),
262 Mock::VerifyAndClearExpectations(&observer);
263 policy_manager->core()->client()->RemoveObserver(&observer);
264 EXPECT_TRUE(policy_manager->core()->client()->is_registered());
266 #if defined(OS_CHROMEOS)
267 // Get the path to the user policy key file.
268 base::FilePath user_policy_key_dir;
270 PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_policy_key_dir));
271 std::string sanitized_username =
272 chromeos::CryptohomeClient::GetStubSanitizedUsername(GetTestUser());
273 user_policy_key_file_ = user_policy_key_dir.AppendASCII(sanitized_username)
274 .AppendASCII("policy.pub");
278 PolicyService* GetPolicyService() {
279 ProfilePolicyConnector* profile_connector =
280 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile());
281 return profile_connector->policy_service();
284 invalidation::FakeInvalidationService* GetInvalidationService() {
285 return static_cast<invalidation::FakeInvalidationService*>(
286 static_cast<invalidation::ProfileInvalidationProvider*>(
287 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
288 GetForProfile(browser()->profile()))->GetInvalidationService());
291 void SetServerPolicy(const std::string& policy) {
292 int result = base::WriteFile(policy_file_path(), policy.data(),
294 ASSERT_EQ(static_cast<int>(policy.size()), result);
297 base::FilePath policy_file_path() const {
298 return temp_dir_.path().AppendASCII("policy.json");
301 virtual void OnPolicyUpdated(const PolicyNamespace& ns,
302 const PolicyMap& previous,
303 const PolicyMap& current) OVERRIDE {
304 if (!on_policy_updated_.is_null()) {
305 on_policy_updated_.Run();
306 on_policy_updated_.Reset();
310 virtual void OnPolicyServiceInitialized(PolicyDomain domain) OVERRIDE {}
312 base::ScopedTempDir temp_dir_;
313 scoped_ptr<LocalPolicyTestServer> test_server_;
314 base::FilePath user_policy_key_file_;
315 base::Closure on_policy_updated_;
318 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicy) {
319 PolicyService* policy_service = GetPolicyService();
321 base::RunLoop run_loop;
322 // This does the initial fetch and stores the initial key.
323 policy_service->RefreshPolicies(run_loop.QuitClosure());
327 PolicyMap default_policy;
328 GetExpectedDefaultPolicy(&default_policy);
329 EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
330 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
332 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
334 GetExpectedTestPolicy(&expected, "google.com");
336 base::RunLoop run_loop;
337 // This fetches the new policies, using the same key.
338 policy_service->RefreshPolicies(run_loop.QuitClosure());
341 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
342 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
345 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, InvalidatePolicy) {
346 PolicyService* policy_service = GetPolicyService();
347 policy_service->AddObserver(POLICY_DOMAIN_CHROME, this);
349 // Perform the initial fetch.
350 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
352 base::RunLoop run_loop;
353 policy_service->RefreshPolicies(run_loop.QuitClosure());
357 // Update the homepage in the policy and trigger an invalidation.
358 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("youtube.com", 0)));
359 base::TimeDelta now =
360 base::Time::NowFromSystemTime() - base::Time::UnixEpoch();
361 GetInvalidationService()->EmitInvalidationForTest(
362 syncer::Invalidation::Init(
363 invalidation::ObjectId(16, "test_policy"),
364 now.InMicroseconds() /* version */,
367 base::RunLoop run_loop;
368 on_policy_updated_ = run_loop.QuitClosure();
372 // Check that the updated policy was fetched.
374 GetExpectedTestPolicy(&expected, "youtube.com");
375 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
376 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
378 policy_service->RemoveObserver(POLICY_DOMAIN_CHROME, this);
381 #if defined(OS_CHROMEOS)
382 IN_PROC_BROWSER_TEST_F(CloudPolicyTest, FetchPolicyWithRotatedKey) {
383 PolicyService* policy_service = GetPolicyService();
385 base::RunLoop run_loop;
386 // This does the initial fetch and stores the initial key.
387 policy_service->RefreshPolicies(run_loop.QuitClosure());
391 // Read the initial key.
392 std::string initial_key;
393 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &initial_key));
395 PolicyMap default_policy;
396 GetExpectedDefaultPolicy(&default_policy);
397 EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
398 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
400 // Set the new policies and a new key at the server.
401 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 1)));
403 GetExpectedTestPolicy(&expected, "google.com");
405 base::RunLoop run_loop;
406 // This fetches the new policies and does a key rotation.
407 policy_service->RefreshPolicies(run_loop.QuitClosure());
410 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
411 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
413 // Verify that the key was rotated.
414 std::string rotated_key;
415 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &rotated_key));
416 EXPECT_NE(rotated_key, initial_key);
418 // Another refresh using the same key won't rotate it again.
420 base::RunLoop run_loop;
421 policy_service->RefreshPolicies(run_loop.QuitClosure());
424 EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
425 PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
426 std::string current_key;
427 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, ¤t_key));
428 EXPECT_EQ(rotated_key, current_key);
432 TEST(CloudPolicyProtoTest, VerifyProtobufEquivalence) {
433 // There are 2 protobufs that can be used for user cloud policy:
434 // cloud_policy.proto and chrome_settings.proto. chrome_settings.proto is the
435 // version used by the server, but generates one proto message per policy; to
436 // save binary size on the client, the other version shares proto messages for
437 // policies of the same type. They generate the same bytes on the wire though,
438 // so they are compatible. This test verifies that that stays true.
440 // Build a ChromeSettingsProto message with one policy of each supported type.
441 em::ChromeSettingsProto chrome_settings;
442 chrome_settings.mutable_homepagelocation()->set_homepagelocation(
444 chrome_settings.mutable_showhomebutton()->set_showhomebutton(true);
445 chrome_settings.mutable_restoreonstartup()->set_restoreonstartup(4);
446 em::StringList* list =
447 chrome_settings.mutable_disabledschemes()->mutable_disabledschemes();
448 list->add_entries("ftp");
449 list->add_entries("mailto");
450 // Try explicitly setting a policy mode too.
451 chrome_settings.mutable_disablespdy()->set_disablespdy(false);
452 chrome_settings.mutable_disablespdy()->mutable_policy_options()->set_mode(
453 em::PolicyOptions::MANDATORY);
454 chrome_settings.mutable_syncdisabled()->set_syncdisabled(true);
455 chrome_settings.mutable_syncdisabled()->mutable_policy_options()->set_mode(
456 em::PolicyOptions::RECOMMENDED);
458 // Build an equivalent CloudPolicySettings message.
459 em::CloudPolicySettings cloud_policy;
460 cloud_policy.mutable_homepagelocation()->set_value("chromium.org");
461 cloud_policy.mutable_showhomebutton()->set_value(true);
462 cloud_policy.mutable_restoreonstartup()->set_value(4);
463 list = cloud_policy.mutable_disabledschemes()->mutable_value();
464 list->add_entries("ftp");
465 list->add_entries("mailto");
466 cloud_policy.mutable_disablespdy()->set_value(false);
467 cloud_policy.mutable_disablespdy()->mutable_policy_options()->set_mode(
468 em::PolicyOptions::MANDATORY);
469 cloud_policy.mutable_syncdisabled()->set_value(true);
470 cloud_policy.mutable_syncdisabled()->mutable_policy_options()->set_mode(
471 em::PolicyOptions::RECOMMENDED);
473 // They should now serialize to the same bytes.
474 std::string chrome_settings_serialized;
475 std::string cloud_policy_serialized;
476 ASSERT_TRUE(chrome_settings.SerializeToString(&chrome_settings_serialized));
477 ASSERT_TRUE(cloud_policy.SerializeToString(&cloud_policy_serialized));
478 EXPECT_EQ(chrome_settings_serialized, cloud_policy_serialized);
481 } // namespace policy