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"
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"
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"
64 using testing::AnyNumber
;
65 using testing::InvokeWithoutArgs
;
67 using testing::Return
;
74 namespace em
= enterprise_management
;
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
;
91 return "user@example.com";
95 std::string
GetEmptyPolicy() {
96 const char kEmptyPolicy
[] =
100 " \"recommended\": {}"
102 " \"managed_users\": [ \"*\" ],"
103 " \"policy_user\": \"%s\","
104 " \"current_key_index\": 0"
107 return base::StringPrintf(
108 kEmptyPolicy
, dm_protocol::kChromeUserPolicyType
, GetTestUser());
111 std::string
GetTestPolicy(const char* homepage
, int key_version
) {
112 const char kTestPolicy
[] =
116 " \"ShowHomeButton\": true,"
117 " \"RestoreOnStartup\": 4,"
118 " \"URLBlacklist\": [ \"dev.chromium.org\", \"youtube.com\" ],"
119 " \"MaxInvalidationFetchDelay\": 1000"
121 " \"recommended\": {"
122 " \"HomepageLocation\": \"%s\""
125 " \"managed_users\": [ \"*\" ],"
126 " \"policy_user\": \"%s\","
127 " \"current_key_index\": %d,"
128 " \"invalidation_source\": 16,"
129 " \"invalidation_name\": \"test_policy\""
132 return base::StringPrintf(kTestPolicy
,
133 dm_protocol::kChromeUserPolicyType
,
139 void GetExpectedDefaultPolicy(PolicyMap
* policy_map
) {
140 #if defined(OS_CHROMEOS)
141 policy_map
->Set(key::kChromeOsMultiProfileUserBehavior
,
142 POLICY_LEVEL_MANDATORY
,
144 new base::StringValue("primary-only"),
146 policy_map
->Set(key::kEasyUnlockAllowed
,
147 POLICY_LEVEL_MANDATORY
,
149 new base::FundamentalValue(false),
151 policy_map
->Set(key::kCaptivePortalAuthenticationIgnoresProxy
,
152 POLICY_LEVEL_MANDATORY
,
154 new base::FundamentalValue(false),
159 void GetExpectedTestPolicy(PolicyMap
* expected
, const char* homepage
) {
160 expected
->Set(key::kShowHomeButton
,
161 POLICY_LEVEL_MANDATORY
,
163 new base::FundamentalValue(true),
165 expected
->Set(key::kRestoreOnStartup
,
166 POLICY_LEVEL_MANDATORY
,
168 new base::FundamentalValue(4),
170 base::ListValue list
;
171 list
.AppendString("dev.chromium.org");
172 list
.AppendString("youtube.com");
174 key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
175 list
.DeepCopy(), NULL
);
176 expected
->Set(key::kMaxInvalidationFetchDelay
,
177 POLICY_LEVEL_MANDATORY
,
179 new base::FundamentalValue(1000),
181 expected
->Set(key::kHomepageLocation
,
182 POLICY_LEVEL_RECOMMENDED
,
184 new base::StringValue(homepage
),
186 #if defined(OS_CHROMEOS)
187 expected
->Set(key::kChromeOsMultiProfileUserBehavior
,
188 POLICY_LEVEL_MANDATORY
,
190 new base::StringValue("primary-only"),
192 expected
->Set(key::kEasyUnlockAllowed
,
193 POLICY_LEVEL_MANDATORY
,
195 new base::FundamentalValue(false),
197 expected
->Set(key::kCaptivePortalAuthenticationIgnoresProxy
,
198 POLICY_LEVEL_MANDATORY
,
200 new base::FundamentalValue(false),
207 // Tests the cloud policy stack(s).
208 class CloudPolicyTest
: public InProcessBrowserTest
,
209 public PolicyService::Observer
{
212 ~CloudPolicyTest() override
{}
214 void SetUpInProcessBrowserTestFixture() override
{
215 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
216 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetEmptyPolicy()));
218 test_server_
.reset(new LocalPolicyTestServer(policy_file_path()));
219 ASSERT_TRUE(test_server_
->Start());
221 std::string url
= test_server_
->GetServiceURL().spec();
223 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
224 command_line
->AppendSwitchASCII(switches::kDeviceManagementUrl
, url
);
226 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
227 RegisterTestingFactory(BuildFakeProfileInvalidationProvider
);
230 void SetUpOnMainThread() override
{
231 ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process
->policy_service()))
232 << "Pre-existing policies in this machine will make this test fail.";
234 BrowserPolicyConnector
* connector
=
235 g_browser_process
->browser_policy_connector();
236 connector
->ScheduleServiceInitialization(0);
238 #if defined(OS_CHROMEOS)
239 UserCloudPolicyManagerChromeOS
* policy_manager
=
240 UserCloudPolicyManagerFactoryChromeOS::GetForProfile(
241 browser()->profile());
242 ASSERT_TRUE(policy_manager
);
244 // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
245 // the username to the UserCloudPolicyValidator.
246 SigninManager
* signin_manager
=
247 SigninManagerFactory::GetForProfile(browser()->profile());
248 ASSERT_TRUE(signin_manager
);
249 signin_manager
->SetAuthenticatedUsername(GetTestUser());
251 UserCloudPolicyManager
* policy_manager
=
252 UserCloudPolicyManagerFactory::GetForBrowserContext(
253 browser()->profile());
254 ASSERT_TRUE(policy_manager
);
255 policy_manager
->Connect(
256 g_browser_process
->local_state(),
257 g_browser_process
->system_request_context(),
258 UserCloudPolicyManager::CreateCloudPolicyClient(
259 connector
->device_management_service(),
260 g_browser_process
->system_request_context()).Pass());
261 #endif // defined(OS_CHROMEOS)
263 ASSERT_TRUE(policy_manager
->core()->client());
264 base::RunLoop run_loop
;
265 MockCloudPolicyClientObserver observer
;
266 EXPECT_CALL(observer
, OnRegistrationStateChanged(_
)).WillOnce(
267 InvokeWithoutArgs(&run_loop
, &base::RunLoop::Quit
));
268 policy_manager
->core()->client()->AddObserver(&observer
);
270 // Give a bogus OAuth token to the |policy_manager|. This should make its
271 // CloudPolicyClient fetch the DMToken.
272 ASSERT_FALSE(policy_manager
->core()->client()->is_registered());
273 em::DeviceRegisterRequest::Type registration_type
=
274 #if defined(OS_CHROMEOS)
275 em::DeviceRegisterRequest::USER
;
277 em::DeviceRegisterRequest::BROWSER
;
279 policy_manager
->core()->client()->Register(
280 registration_type
, em::DeviceRegisterRequest::FLAVOR_USER_REGISTRATION
,
281 "bogus", std::string(), std::string(), std::string());
283 Mock::VerifyAndClearExpectations(&observer
);
284 policy_manager
->core()->client()->RemoveObserver(&observer
);
285 EXPECT_TRUE(policy_manager
->core()->client()->is_registered());
287 #if defined(OS_CHROMEOS)
288 // Get the path to the user policy key file.
289 base::FilePath user_policy_key_dir
;
291 PathService::Get(chromeos::DIR_USER_POLICY_KEYS
, &user_policy_key_dir
));
292 std::string sanitized_username
=
293 chromeos::CryptohomeClient::GetStubSanitizedUsername(GetTestUser());
294 user_policy_key_file_
= user_policy_key_dir
.AppendASCII(sanitized_username
)
295 .AppendASCII("policy.pub");
299 PolicyService
* GetPolicyService() {
300 ProfilePolicyConnector
* profile_connector
=
301 ProfilePolicyConnectorFactory::GetForBrowserContext(
302 browser()->profile());
303 return profile_connector
->policy_service();
306 invalidation::FakeInvalidationService
* GetInvalidationService() {
307 return static_cast<invalidation::FakeInvalidationService
*>(
308 static_cast<invalidation::ProfileInvalidationProvider
*>(
309 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
310 GetForProfile(browser()->profile()))->GetInvalidationService());
313 void SetServerPolicy(const std::string
& policy
) {
314 int result
= base::WriteFile(policy_file_path(), policy
.data(),
316 ASSERT_EQ(static_cast<int>(policy
.size()), result
);
319 base::FilePath
policy_file_path() const {
320 return temp_dir_
.path().AppendASCII("policy.json");
323 void OnPolicyUpdated(const PolicyNamespace
& ns
,
324 const PolicyMap
& previous
,
325 const PolicyMap
& current
) override
{
326 if (!on_policy_updated_
.is_null()) {
327 on_policy_updated_
.Run();
328 on_policy_updated_
.Reset();
332 void OnPolicyServiceInitialized(PolicyDomain domain
) override
{}
334 base::ScopedTempDir temp_dir_
;
335 scoped_ptr
<LocalPolicyTestServer
> test_server_
;
336 base::FilePath user_policy_key_file_
;
337 base::Closure on_policy_updated_
;
340 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, FetchPolicy
) {
341 PolicyService
* policy_service
= GetPolicyService();
343 base::RunLoop run_loop
;
344 // This does the initial fetch and stores the initial key.
345 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
349 PolicyMap default_policy
;
350 GetExpectedDefaultPolicy(&default_policy
);
351 EXPECT_TRUE(default_policy
.Equals(policy_service
->GetPolicies(
352 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
354 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
356 GetExpectedTestPolicy(&expected
, "google.com");
358 base::RunLoop run_loop
;
359 // This fetches the new policies, using the same key.
360 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
363 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
364 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
367 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, InvalidatePolicy
) {
368 PolicyService
* policy_service
= GetPolicyService();
369 policy_service
->AddObserver(POLICY_DOMAIN_CHROME
, this);
371 // Perform the initial fetch.
372 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
374 base::RunLoop run_loop
;
375 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
379 // Update the homepage in the policy and trigger an invalidation.
380 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("youtube.com", 0)));
381 base::TimeDelta now
=
382 base::Time::NowFromSystemTime() - base::Time::UnixEpoch();
383 GetInvalidationService()->EmitInvalidationForTest(
384 syncer::Invalidation::Init(
385 invalidation::ObjectId(16, "test_policy"),
386 now
.InMicroseconds() /* version */,
389 base::RunLoop run_loop
;
390 on_policy_updated_
= run_loop
.QuitClosure();
394 // Check that the updated policy was fetched.
396 GetExpectedTestPolicy(&expected
, "youtube.com");
397 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
398 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
400 policy_service
->RemoveObserver(POLICY_DOMAIN_CHROME
, this);
403 #if defined(OS_CHROMEOS)
404 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, FetchPolicyWithRotatedKey
) {
405 PolicyService
* policy_service
= GetPolicyService();
407 base::RunLoop run_loop
;
408 // This does the initial fetch and stores the initial key.
409 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
413 // Read the initial key.
414 std::string initial_key
;
415 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, &initial_key
));
417 PolicyMap default_policy
;
418 GetExpectedDefaultPolicy(&default_policy
);
419 EXPECT_TRUE(default_policy
.Equals(policy_service
->GetPolicies(
420 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
422 // Set the new policies and a new key at the server.
423 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 1)));
425 GetExpectedTestPolicy(&expected
, "google.com");
427 base::RunLoop run_loop
;
428 // This fetches the new policies and does a key rotation.
429 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
432 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
433 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
435 // Verify that the key was rotated.
436 std::string rotated_key
;
437 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, &rotated_key
));
438 EXPECT_NE(rotated_key
, initial_key
);
440 // Another refresh using the same key won't rotate it again.
442 base::RunLoop run_loop
;
443 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
446 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
447 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
448 std::string current_key
;
449 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, ¤t_key
));
450 EXPECT_EQ(rotated_key
, current_key
);
454 TEST(CloudPolicyProtoTest
, VerifyProtobufEquivalence
) {
455 // There are 2 protobufs that can be used for user cloud policy:
456 // cloud_policy.proto and chrome_settings.proto. chrome_settings.proto is the
457 // version used by the server, but generates one proto message per policy; to
458 // save binary size on the client, the other version shares proto messages for
459 // policies of the same type. They generate the same bytes on the wire though,
460 // so they are compatible. This test verifies that that stays true.
462 // Build a ChromeSettingsProto message with one policy of each supported type.
463 em::ChromeSettingsProto chrome_settings
;
464 chrome_settings
.mutable_homepagelocation()->set_homepagelocation(
466 chrome_settings
.mutable_showhomebutton()->set_showhomebutton(true);
467 chrome_settings
.mutable_restoreonstartup()->set_restoreonstartup(4);
468 em::StringList
* list
=
469 chrome_settings
.mutable_disabledschemes()->mutable_disabledschemes();
470 list
->add_entries("ftp");
471 list
->add_entries("mailto");
472 // Try explicitly setting a policy mode too.
473 chrome_settings
.mutable_disablespdy()->set_disablespdy(false);
474 chrome_settings
.mutable_disablespdy()->mutable_policy_options()->set_mode(
475 em::PolicyOptions::MANDATORY
);
476 chrome_settings
.mutable_syncdisabled()->set_syncdisabled(true);
477 chrome_settings
.mutable_syncdisabled()->mutable_policy_options()->set_mode(
478 em::PolicyOptions::RECOMMENDED
);
480 // Build an equivalent CloudPolicySettings message.
481 em::CloudPolicySettings cloud_policy
;
482 cloud_policy
.mutable_homepagelocation()->set_value("chromium.org");
483 cloud_policy
.mutable_showhomebutton()->set_value(true);
484 cloud_policy
.mutable_restoreonstartup()->set_value(4);
485 list
= cloud_policy
.mutable_disabledschemes()->mutable_value();
486 list
->add_entries("ftp");
487 list
->add_entries("mailto");
488 cloud_policy
.mutable_disablespdy()->set_value(false);
489 cloud_policy
.mutable_disablespdy()->mutable_policy_options()->set_mode(
490 em::PolicyOptions::MANDATORY
);
491 cloud_policy
.mutable_syncdisabled()->set_value(true);
492 cloud_policy
.mutable_syncdisabled()->mutable_policy_options()->set_mode(
493 em::PolicyOptions::RECOMMENDED
);
495 // They should now serialize to the same bytes.
496 std::string chrome_settings_serialized
;
497 std::string cloud_policy_serialized
;
498 ASSERT_TRUE(chrome_settings
.SerializeToString(&chrome_settings_serialized
));
499 ASSERT_TRUE(cloud_policy
.SerializeToString(&cloud_policy_serialized
));
500 EXPECT_EQ(chrome_settings_serialized
, cloud_policy_serialized
);
503 } // namespace policy