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/invalidation_service_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/policy/core/browser/browser_policy_connector.h"
27 #include "components/policy/core/common/cloud/cloud_policy_client.h"
28 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
29 #include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
30 #include "components/policy/core/common/external_data_fetcher.h"
31 #include "components/policy/core/common/policy_map.h"
32 #include "components/policy/core/common/policy_service.h"
33 #include "components/policy/core/common/policy_switches.h"
34 #include "components/policy/core/common/policy_test_utils.h"
35 #include "content/public/browser/notification_service.h"
36 #include "content/public/browser/notification_source.h"
37 #include "content/public/test/test_utils.h"
38 #include "net/url_request/url_request_context_getter.h"
39 #include "policy/policy_constants.h"
40 #include "policy/proto/chrome_settings.pb.h"
41 #include "policy/proto/cloud_policy.pb.h"
42 #include "sync/internal_api/public/base/invalidation.h"
43 #include "testing/gmock/include/gmock/gmock.h"
44 #include "testing/gtest/include/gtest/gtest.h"
47 #if defined(OS_CHROMEOS)
48 #include "chrome/browser/chromeos/login/user_manager.h"
49 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
50 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
51 #include "chromeos/chromeos_paths.h"
52 #include "chromeos/dbus/cryptohome_client.h"
54 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
55 #include "chrome/browser/signin/signin_manager_factory.h"
56 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
57 #include "components/signin/core/browser/signin_manager.h"
60 using testing::AnyNumber
;
61 using testing::InvokeWithoutArgs
;
63 using testing::Return
;
66 namespace em
= enterprise_management
;
72 const char* GetTestUser() {
73 #if defined(OS_CHROMEOS)
74 return chromeos::UserManager::kStubUser
;
76 return "user@example.com";
80 std::string
GetEmptyPolicy() {
81 const char kEmptyPolicy
[] =
85 " \"recommended\": {}"
87 " \"managed_users\": [ \"*\" ],"
88 " \"policy_user\": \"%s\","
89 " \"current_key_index\": 0"
92 return base::StringPrintf(
93 kEmptyPolicy
, dm_protocol::kChromeUserPolicyType
, GetTestUser());
96 std::string
GetTestPolicy(const char* homepage
, int key_version
) {
97 const char kTestPolicy
[] =
101 " \"ShowHomeButton\": true,"
102 " \"RestoreOnStartup\": 4,"
103 " \"URLBlacklist\": [ \"dev.chromium.org\", \"youtube.com\" ],"
104 " \"MaxInvalidationFetchDelay\": 1000"
106 " \"recommended\": {"
107 " \"HomepageLocation\": \"%s\""
110 " \"managed_users\": [ \"*\" ],"
111 " \"policy_user\": \"%s\","
112 " \"current_key_index\": %d,"
113 " \"invalidation_source\": 16,"
114 " \"invalidation_name\": \"test_policy\""
117 return base::StringPrintf(kTestPolicy
,
118 dm_protocol::kChromeUserPolicyType
,
124 void GetExpectedDefaultPolicy(PolicyMap
* policy_map
) {
125 #if defined(OS_CHROMEOS)
127 key::kChromeOsMultiProfileUserBehavior
, POLICY_LEVEL_MANDATORY
,
128 POLICY_SCOPE_USER
, base::Value::CreateStringValue("primary-only"), NULL
);
132 void GetExpectedTestPolicy(PolicyMap
* expected
, const char* homepage
) {
133 expected
->Set(key::kShowHomeButton
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
134 base::Value::CreateBooleanValue(true), NULL
);
135 expected
->Set(key::kRestoreOnStartup
, POLICY_LEVEL_MANDATORY
,
136 POLICY_SCOPE_USER
, base::Value::CreateIntegerValue(4), NULL
);
137 base::ListValue list
;
138 list
.AppendString("dev.chromium.org");
139 list
.AppendString("youtube.com");
141 key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
142 list
.DeepCopy(), NULL
);
144 key::kMaxInvalidationFetchDelay
, POLICY_LEVEL_MANDATORY
,
145 POLICY_SCOPE_USER
, base::Value::CreateIntegerValue(1000), NULL
);
147 key::kHomepageLocation
, POLICY_LEVEL_RECOMMENDED
,
148 POLICY_SCOPE_USER
, base::Value::CreateStringValue(homepage
), NULL
);
149 #if defined(OS_CHROMEOS)
151 key::kChromeOsMultiProfileUserBehavior
, POLICY_LEVEL_MANDATORY
,
152 POLICY_SCOPE_USER
, base::Value::CreateStringValue("primary-only"), NULL
);
158 // Tests the cloud policy stack(s).
159 class CloudPolicyTest
: public InProcessBrowserTest
,
160 public PolicyService::Observer
{
163 virtual ~CloudPolicyTest() {}
165 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE
{
166 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
167 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetEmptyPolicy()));
169 test_server_
.reset(new LocalPolicyTestServer(policy_file_path()));
170 ASSERT_TRUE(test_server_
->Start());
172 std::string url
= test_server_
->GetServiceURL().spec();
174 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
175 command_line
->AppendSwitchASCII(switches::kDeviceManagementUrl
, url
);
177 invalidation::InvalidationServiceFactory::GetInstance()->
178 RegisterTestingFactory(invalidation::FakeInvalidationService::Build
);
181 virtual void SetUpOnMainThread() OVERRIDE
{
182 ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process
->policy_service()))
183 << "Pre-existing policies in this machine will make this test fail.";
185 BrowserPolicyConnector
* connector
=
186 g_browser_process
->browser_policy_connector();
187 connector
->ScheduleServiceInitialization(0);
189 #if defined(OS_CHROMEOS)
190 UserCloudPolicyManagerChromeOS
* policy_manager
=
191 UserCloudPolicyManagerFactoryChromeOS::GetForProfile(
192 browser()->profile());
193 ASSERT_TRUE(policy_manager
);
195 // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
196 // the username to the UserCloudPolicyValidator.
197 SigninManager
* signin_manager
=
198 SigninManagerFactory::GetForProfile(browser()->profile());
199 ASSERT_TRUE(signin_manager
);
200 signin_manager
->SetAuthenticatedUsername(GetTestUser());
202 UserCloudPolicyManager
* policy_manager
=
203 UserCloudPolicyManagerFactory::GetForBrowserContext(
204 browser()->profile());
205 ASSERT_TRUE(policy_manager
);
206 policy_manager
->Connect(
207 g_browser_process
->local_state(),
208 g_browser_process
->system_request_context(),
209 UserCloudPolicyManager::CreateCloudPolicyClient(
210 connector
->device_management_service(),
211 g_browser_process
->system_request_context()).Pass());
212 #endif // defined(OS_CHROMEOS)
214 ASSERT_TRUE(policy_manager
->core()->client());
215 base::RunLoop run_loop
;
216 MockCloudPolicyClientObserver observer
;
217 EXPECT_CALL(observer
, OnRegistrationStateChanged(_
)).WillOnce(
218 InvokeWithoutArgs(&run_loop
, &base::RunLoop::Quit
));
219 policy_manager
->core()->client()->AddObserver(&observer
);
221 // Give a bogus OAuth token to the |policy_manager|. This should make its
222 // CloudPolicyClient fetch the DMToken.
223 ASSERT_FALSE(policy_manager
->core()->client()->is_registered());
224 em::DeviceRegisterRequest::Type registration_type
=
225 #if defined(OS_CHROMEOS)
226 em::DeviceRegisterRequest::USER
;
228 em::DeviceRegisterRequest::BROWSER
;
230 policy_manager
->core()->client()->Register(
231 registration_type
, "bogus", std::string(), false, std::string(),
234 Mock::VerifyAndClearExpectations(&observer
);
235 policy_manager
->core()->client()->RemoveObserver(&observer
);
236 EXPECT_TRUE(policy_manager
->core()->client()->is_registered());
238 #if defined(OS_CHROMEOS)
239 // Get the path to the user policy key file.
240 base::FilePath user_policy_key_dir
;
242 PathService::Get(chromeos::DIR_USER_POLICY_KEYS
, &user_policy_key_dir
));
243 std::string sanitized_username
=
244 chromeos::CryptohomeClient::GetStubSanitizedUsername(GetTestUser());
245 user_policy_key_file_
= user_policy_key_dir
.AppendASCII(sanitized_username
)
246 .AppendASCII("policy.pub");
250 PolicyService
* GetPolicyService() {
251 ProfilePolicyConnector
* profile_connector
=
252 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile());
253 return profile_connector
->policy_service();
256 invalidation::FakeInvalidationService
* GetInvalidationService() {
257 return static_cast<invalidation::FakeInvalidationService
*>(
258 invalidation::InvalidationServiceFactory::GetForProfile(
259 browser()->profile()));
262 void SetServerPolicy(const std::string
& policy
) {
263 int result
= base::WriteFile(policy_file_path(), policy
.data(),
265 ASSERT_EQ(static_cast<int>(policy
.size()), result
);
268 base::FilePath
policy_file_path() const {
269 return temp_dir_
.path().AppendASCII("policy.json");
272 virtual void OnPolicyUpdated(const PolicyNamespace
& ns
,
273 const PolicyMap
& previous
,
274 const PolicyMap
& current
) OVERRIDE
{
275 if (!on_policy_updated_
.is_null()) {
276 on_policy_updated_
.Run();
277 on_policy_updated_
.Reset();
281 virtual void OnPolicyServiceInitialized(PolicyDomain domain
) OVERRIDE
{}
283 base::ScopedTempDir temp_dir_
;
284 scoped_ptr
<LocalPolicyTestServer
> test_server_
;
285 base::FilePath user_policy_key_file_
;
286 base::Closure on_policy_updated_
;
289 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, FetchPolicy
) {
290 PolicyService
* policy_service
= GetPolicyService();
292 base::RunLoop run_loop
;
293 // This does the initial fetch and stores the initial key.
294 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
298 PolicyMap default_policy
;
299 GetExpectedDefaultPolicy(&default_policy
);
300 EXPECT_TRUE(default_policy
.Equals(policy_service
->GetPolicies(
301 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
303 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
305 GetExpectedTestPolicy(&expected
, "google.com");
307 base::RunLoop run_loop
;
308 // This fetches the new policies, using the same key.
309 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
312 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
313 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
316 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, InvalidatePolicy
) {
317 PolicyService
* policy_service
= GetPolicyService();
318 policy_service
->AddObserver(POLICY_DOMAIN_CHROME
, this);
320 // Perform the initial fetch.
321 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
323 base::RunLoop run_loop
;
324 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
328 // Update the homepage in the policy and trigger an invalidation.
329 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("youtube.com", 0)));
330 base::TimeDelta now
=
331 base::Time::NowFromSystemTime() - base::Time::UnixEpoch();
332 GetInvalidationService()->EmitInvalidationForTest(
333 syncer::Invalidation::Init(
334 invalidation::ObjectId(16, "test_policy"),
335 now
.InMicroseconds() /* version */,
338 base::RunLoop run_loop
;
339 on_policy_updated_
= run_loop
.QuitClosure();
343 // Check that the updated policy was fetched.
345 GetExpectedTestPolicy(&expected
, "youtube.com");
346 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
347 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
349 policy_service
->RemoveObserver(POLICY_DOMAIN_CHROME
, this);
352 #if defined(OS_CHROMEOS)
353 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, FetchPolicyWithRotatedKey
) {
354 PolicyService
* policy_service
= GetPolicyService();
356 base::RunLoop run_loop
;
357 // This does the initial fetch and stores the initial key.
358 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
362 // Read the initial key.
363 std::string initial_key
;
364 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, &initial_key
));
366 PolicyMap default_policy
;
367 GetExpectedDefaultPolicy(&default_policy
);
368 EXPECT_TRUE(default_policy
.Equals(policy_service
->GetPolicies(
369 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
371 // Set the new policies and a new key at the server.
372 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 1)));
374 GetExpectedTestPolicy(&expected
, "google.com");
376 base::RunLoop run_loop
;
377 // This fetches the new policies and does a key rotation.
378 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
381 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
382 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
384 // Verify that the key was rotated.
385 std::string rotated_key
;
386 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, &rotated_key
));
387 EXPECT_NE(rotated_key
, initial_key
);
389 // Another refresh using the same key won't rotate it again.
391 base::RunLoop run_loop
;
392 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
395 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
396 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
397 std::string current_key
;
398 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, ¤t_key
));
399 EXPECT_EQ(rotated_key
, current_key
);
403 TEST(CloudPolicyProtoTest
, VerifyProtobufEquivalence
) {
404 // There are 2 protobufs that can be used for user cloud policy:
405 // cloud_policy.proto and chrome_settings.proto. chrome_settings.proto is the
406 // version used by the server, but generates one proto message per policy; to
407 // save binary size on the client, the other version shares proto messages for
408 // policies of the same type. They generate the same bytes on the wire though,
409 // so they are compatible. This test verifies that that stays true.
411 // Build a ChromeSettingsProto message with one policy of each supported type.
412 em::ChromeSettingsProto chrome_settings
;
413 chrome_settings
.mutable_homepagelocation()->set_homepagelocation(
415 chrome_settings
.mutable_showhomebutton()->set_showhomebutton(true);
416 chrome_settings
.mutable_restoreonstartup()->set_restoreonstartup(4);
417 em::StringList
* list
=
418 chrome_settings
.mutable_disabledschemes()->mutable_disabledschemes();
419 list
->add_entries("ftp");
420 list
->add_entries("mailto");
421 // Try explicitly setting a policy mode too.
422 chrome_settings
.mutable_disablespdy()->set_disablespdy(false);
423 chrome_settings
.mutable_disablespdy()->mutable_policy_options()->set_mode(
424 em::PolicyOptions::MANDATORY
);
425 chrome_settings
.mutable_syncdisabled()->set_syncdisabled(true);
426 chrome_settings
.mutable_syncdisabled()->mutable_policy_options()->set_mode(
427 em::PolicyOptions::RECOMMENDED
);
429 // Build an equivalent CloudPolicySettings message.
430 em::CloudPolicySettings cloud_policy
;
431 cloud_policy
.mutable_homepagelocation()->set_value("chromium.org");
432 cloud_policy
.mutable_showhomebutton()->set_value(true);
433 cloud_policy
.mutable_restoreonstartup()->set_value(4);
434 list
= cloud_policy
.mutable_disabledschemes()->mutable_value();
435 list
->add_entries("ftp");
436 list
->add_entries("mailto");
437 cloud_policy
.mutable_disablespdy()->set_value(false);
438 cloud_policy
.mutable_disablespdy()->mutable_policy_options()->set_mode(
439 em::PolicyOptions::MANDATORY
);
440 cloud_policy
.mutable_syncdisabled()->set_value(true);
441 cloud_policy
.mutable_syncdisabled()->mutable_policy_options()->set_mode(
442 em::PolicyOptions::RECOMMENDED
);
444 // They should now serialize to the same bytes.
445 std::string chrome_settings_serialized
;
446 std::string cloud_policy_serialized
;
447 ASSERT_TRUE(chrome_settings
.SerializeToString(&chrome_settings_serialized
));
448 ASSERT_TRUE(cloud_policy
.SerializeToString(&cloud_policy_serialized
));
449 EXPECT_EQ(chrome_settings_serialized
, cloud_policy_serialized
);
452 } // namespace policy