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 "components/policy/core/common/policy_types.h"
40 #include "content/public/browser/notification_service.h"
41 #include "content/public/browser/notification_source.h"
42 #include "content/public/test/test_utils.h"
43 #include "net/url_request/url_request_context_getter.h"
44 #include "policy/policy_constants.h"
45 #include "policy/proto/chrome_settings.pb.h"
46 #include "policy/proto/cloud_policy.pb.h"
47 #include "policy/proto/device_management_backend.pb.h"
48 #include "testing/gmock/include/gmock/gmock.h"
49 #include "testing/gtest/include/gtest/gtest.h"
52 #if defined(OS_CHROMEOS)
53 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
54 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
55 #include "chromeos/chromeos_paths.h"
56 #include "chromeos/dbus/cryptohome_client.h"
57 #include "chromeos/login/user_names.h"
59 #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
60 #include "chrome/browser/signin/signin_manager_factory.h"
61 #include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
62 #include "components/signin/core/browser/signin_manager.h"
65 using testing::AnyNumber
;
66 using testing::InvokeWithoutArgs
;
68 using testing::Return
;
75 namespace em
= enterprise_management
;
81 scoped_ptr
<KeyedService
> BuildFakeProfileInvalidationProvider(
82 content::BrowserContext
* context
) {
83 return make_scoped_ptr(new invalidation::ProfileInvalidationProvider(
84 scoped_ptr
<invalidation::InvalidationService
>(
85 new invalidation::FakeInvalidationService
)));
88 #if !defined(OS_CHROMEOS)
89 const char* GetTestGaiaId() {
90 return "gaia-id-user@example.com";
94 const char* GetTestUser() {
95 #if defined(OS_CHROMEOS)
96 return chromeos::login::kStubUser
;
98 return "user@example.com";
102 std::string
GetEmptyPolicy() {
103 const char kEmptyPolicy
[] =
106 " \"mandatory\": {},"
107 " \"recommended\": {}"
109 " \"managed_users\": [ \"*\" ],"
110 " \"policy_user\": \"%s\","
111 " \"current_key_index\": 0"
114 return base::StringPrintf(
115 kEmptyPolicy
, dm_protocol::kChromeUserPolicyType
, GetTestUser());
118 std::string
GetTestPolicy(const char* homepage
, int key_version
) {
119 const char kTestPolicy
[] =
123 " \"ShowHomeButton\": true,"
124 " \"RestoreOnStartup\": 4,"
125 " \"URLBlacklist\": [ \"dev.chromium.org\", \"youtube.com\" ],"
126 " \"MaxInvalidationFetchDelay\": 1000"
128 " \"recommended\": {"
129 " \"HomepageLocation\": \"%s\""
132 " \"managed_users\": [ \"*\" ],"
133 " \"policy_user\": \"%s\","
134 " \"current_key_index\": %d,"
135 " \"invalidation_source\": 16,"
136 " \"invalidation_name\": \"test_policy\""
139 return base::StringPrintf(kTestPolicy
,
140 dm_protocol::kChromeUserPolicyType
,
146 void GetExpectedDefaultPolicy(PolicyMap
* policy_map
) {
147 #if defined(OS_CHROMEOS)
148 policy_map
->Set(key::kChromeOsMultiProfileUserBehavior
,
149 POLICY_LEVEL_MANDATORY
,
151 POLICY_SOURCE_ENTERPRISE_DEFAULT
,
152 new base::StringValue("primary-only"),
154 policy_map
->Set(key::kEasyUnlockAllowed
,
155 POLICY_LEVEL_MANDATORY
,
157 POLICY_SOURCE_ENTERPRISE_DEFAULT
,
158 new base::FundamentalValue(false),
160 policy_map
->Set(key::kCaptivePortalAuthenticationIgnoresProxy
,
161 POLICY_LEVEL_MANDATORY
,
163 POLICY_SOURCE_ENTERPRISE_DEFAULT
,
164 new base::FundamentalValue(false),
169 void GetExpectedTestPolicy(PolicyMap
* expected
, const char* homepage
) {
170 expected
->Set(key::kShowHomeButton
,
171 POLICY_LEVEL_MANDATORY
,
174 new base::FundamentalValue(true),
176 expected
->Set(key::kRestoreOnStartup
,
177 POLICY_LEVEL_MANDATORY
,
180 new base::FundamentalValue(4),
182 base::ListValue list
;
183 list
.AppendString("dev.chromium.org");
184 list
.AppendString("youtube.com");
185 expected
->Set(key::kURLBlacklist
,
186 POLICY_LEVEL_MANDATORY
,
191 expected
->Set(key::kMaxInvalidationFetchDelay
,
192 POLICY_LEVEL_MANDATORY
,
195 new base::FundamentalValue(1000),
197 expected
->Set(key::kHomepageLocation
,
198 POLICY_LEVEL_RECOMMENDED
,
201 new base::StringValue(homepage
),
203 #if defined(OS_CHROMEOS)
204 expected
->Set(key::kChromeOsMultiProfileUserBehavior
,
205 POLICY_LEVEL_MANDATORY
,
207 POLICY_SOURCE_ENTERPRISE_DEFAULT
,
208 new base::StringValue("primary-only"),
210 expected
->Set(key::kEasyUnlockAllowed
,
211 POLICY_LEVEL_MANDATORY
,
213 POLICY_SOURCE_ENTERPRISE_DEFAULT
,
214 new base::FundamentalValue(false),
216 expected
->Set(key::kCaptivePortalAuthenticationIgnoresProxy
,
217 POLICY_LEVEL_MANDATORY
,
219 POLICY_SOURCE_ENTERPRISE_DEFAULT
,
220 new base::FundamentalValue(false),
227 // Tests the cloud policy stack(s).
228 class CloudPolicyTest
: public InProcessBrowserTest
,
229 public PolicyService::Observer
{
232 ~CloudPolicyTest() override
{}
234 void SetUpInProcessBrowserTestFixture() override
{
235 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
236 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetEmptyPolicy()));
238 test_server_
.reset(new LocalPolicyTestServer(policy_file_path()));
239 ASSERT_TRUE(test_server_
->Start());
241 std::string url
= test_server_
->GetServiceURL().spec();
243 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
244 command_line
->AppendSwitchASCII(switches::kDeviceManagementUrl
, url
);
246 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
247 RegisterTestingFactory(BuildFakeProfileInvalidationProvider
);
250 void SetUpOnMainThread() override
{
251 ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process
->policy_service()))
252 << "Pre-existing policies in this machine will make this test fail.";
254 BrowserPolicyConnector
* connector
=
255 g_browser_process
->browser_policy_connector();
256 connector
->ScheduleServiceInitialization(0);
258 #if defined(OS_CHROMEOS)
259 UserCloudPolicyManagerChromeOS
* policy_manager
=
260 UserCloudPolicyManagerFactoryChromeOS::GetForProfile(
261 browser()->profile());
262 ASSERT_TRUE(policy_manager
);
264 // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
265 // the username to the UserCloudPolicyValidator.
266 SigninManager
* signin_manager
=
267 SigninManagerFactory::GetForProfile(browser()->profile());
268 ASSERT_TRUE(signin_manager
);
269 signin_manager
->SetAuthenticatedAccountInfo(GetTestGaiaId(), GetTestUser());
271 UserCloudPolicyManager
* policy_manager
=
272 UserCloudPolicyManagerFactory::GetForBrowserContext(
273 browser()->profile());
274 ASSERT_TRUE(policy_manager
);
275 policy_manager
->Connect(
276 g_browser_process
->local_state(),
277 g_browser_process
->system_request_context(),
278 UserCloudPolicyManager::CreateCloudPolicyClient(
279 connector
->device_management_service(),
280 g_browser_process
->system_request_context()).Pass());
281 #endif // defined(OS_CHROMEOS)
283 ASSERT_TRUE(policy_manager
->core()->client());
284 base::RunLoop run_loop
;
285 MockCloudPolicyClientObserver observer
;
286 EXPECT_CALL(observer
, OnRegistrationStateChanged(_
)).WillOnce(
287 InvokeWithoutArgs(&run_loop
, &base::RunLoop::Quit
));
288 policy_manager
->core()->client()->AddObserver(&observer
);
290 // Give a bogus OAuth token to the |policy_manager|. This should make its
291 // CloudPolicyClient fetch the DMToken.
292 ASSERT_FALSE(policy_manager
->core()->client()->is_registered());
293 em::DeviceRegisterRequest::Type registration_type
=
294 #if defined(OS_CHROMEOS)
295 em::DeviceRegisterRequest::USER
;
297 em::DeviceRegisterRequest::BROWSER
;
299 policy_manager
->core()->client()->Register(
300 registration_type
, em::DeviceRegisterRequest::FLAVOR_USER_REGISTRATION
,
301 "bogus", std::string(), std::string(), std::string());
303 Mock::VerifyAndClearExpectations(&observer
);
304 policy_manager
->core()->client()->RemoveObserver(&observer
);
305 EXPECT_TRUE(policy_manager
->core()->client()->is_registered());
307 #if defined(OS_CHROMEOS)
308 // Get the path to the user policy key file.
309 base::FilePath user_policy_key_dir
;
311 PathService::Get(chromeos::DIR_USER_POLICY_KEYS
, &user_policy_key_dir
));
312 std::string sanitized_username
=
313 chromeos::CryptohomeClient::GetStubSanitizedUsername(GetTestUser());
314 user_policy_key_file_
= user_policy_key_dir
.AppendASCII(sanitized_username
)
315 .AppendASCII("policy.pub");
319 PolicyService
* GetPolicyService() {
320 ProfilePolicyConnector
* profile_connector
=
321 ProfilePolicyConnectorFactory::GetForBrowserContext(
322 browser()->profile());
323 return profile_connector
->policy_service();
326 invalidation::FakeInvalidationService
* GetInvalidationService() {
327 return static_cast<invalidation::FakeInvalidationService
*>(
328 static_cast<invalidation::ProfileInvalidationProvider
*>(
329 invalidation::ProfileInvalidationProviderFactory::GetInstance()->
330 GetForProfile(browser()->profile()))->GetInvalidationService());
333 void SetServerPolicy(const std::string
& policy
) {
334 int result
= base::WriteFile(policy_file_path(), policy
.data(),
336 ASSERT_EQ(static_cast<int>(policy
.size()), result
);
339 base::FilePath
policy_file_path() const {
340 return temp_dir_
.path().AppendASCII("policy.json");
343 void OnPolicyUpdated(const PolicyNamespace
& ns
,
344 const PolicyMap
& previous
,
345 const PolicyMap
& current
) override
{
346 if (!on_policy_updated_
.is_null()) {
347 on_policy_updated_
.Run();
348 on_policy_updated_
.Reset();
352 void OnPolicyServiceInitialized(PolicyDomain domain
) override
{}
354 base::ScopedTempDir temp_dir_
;
355 scoped_ptr
<LocalPolicyTestServer
> test_server_
;
356 base::FilePath user_policy_key_file_
;
357 base::Closure on_policy_updated_
;
360 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, FetchPolicy
) {
361 PolicyService
* policy_service
= GetPolicyService();
363 base::RunLoop run_loop
;
364 // This does the initial fetch and stores the initial key.
365 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
369 PolicyMap default_policy
;
370 GetExpectedDefaultPolicy(&default_policy
);
371 EXPECT_TRUE(default_policy
.Equals(policy_service
->GetPolicies(
372 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
374 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
376 GetExpectedTestPolicy(&expected
, "google.com");
378 base::RunLoop run_loop
;
379 // This fetches the new policies, using the same key.
380 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
383 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
384 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
387 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, InvalidatePolicy
) {
388 PolicyService
* policy_service
= GetPolicyService();
389 policy_service
->AddObserver(POLICY_DOMAIN_CHROME
, this);
391 // Perform the initial fetch.
392 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 0)));
394 base::RunLoop run_loop
;
395 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
399 // Update the homepage in the policy and trigger an invalidation.
400 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("youtube.com", 0)));
401 base::TimeDelta now
=
402 base::Time::NowFromSystemTime() - base::Time::UnixEpoch();
403 GetInvalidationService()->EmitInvalidationForTest(
404 syncer::Invalidation::Init(
405 invalidation::ObjectId(16, "test_policy"),
406 now
.InMicroseconds() /* version */,
409 base::RunLoop run_loop
;
410 on_policy_updated_
= run_loop
.QuitClosure();
414 // Check that the updated policy was fetched.
416 GetExpectedTestPolicy(&expected
, "youtube.com");
417 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
418 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
420 policy_service
->RemoveObserver(POLICY_DOMAIN_CHROME
, this);
423 #if defined(OS_CHROMEOS)
424 IN_PROC_BROWSER_TEST_F(CloudPolicyTest
, FetchPolicyWithRotatedKey
) {
425 PolicyService
* policy_service
= GetPolicyService();
427 base::RunLoop run_loop
;
428 // This does the initial fetch and stores the initial key.
429 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
433 // Read the initial key.
434 std::string initial_key
;
435 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, &initial_key
));
437 PolicyMap default_policy
;
438 GetExpectedDefaultPolicy(&default_policy
);
439 EXPECT_TRUE(default_policy
.Equals(policy_service
->GetPolicies(
440 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
442 // Set the new policies and a new key at the server.
443 ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com", 1)));
445 GetExpectedTestPolicy(&expected
, "google.com");
447 base::RunLoop run_loop
;
448 // This fetches the new policies and does a key rotation.
449 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
452 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
453 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
455 // Verify that the key was rotated.
456 std::string rotated_key
;
457 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, &rotated_key
));
458 EXPECT_NE(rotated_key
, initial_key
);
460 // Another refresh using the same key won't rotate it again.
462 base::RunLoop run_loop
;
463 policy_service
->RefreshPolicies(run_loop
.QuitClosure());
466 EXPECT_TRUE(expected
.Equals(policy_service
->GetPolicies(
467 PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()))));
468 std::string current_key
;
469 ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_
, ¤t_key
));
470 EXPECT_EQ(rotated_key
, current_key
);
474 TEST(CloudPolicyProtoTest
, VerifyProtobufEquivalence
) {
475 // There are 2 protobufs that can be used for user cloud policy:
476 // cloud_policy.proto and chrome_settings.proto. chrome_settings.proto is the
477 // version used by the server, but generates one proto message per policy; to
478 // save binary size on the client, the other version shares proto messages for
479 // policies of the same type. They generate the same bytes on the wire though,
480 // so they are compatible. This test verifies that that stays true.
482 // Build a ChromeSettingsProto message with one policy of each supported type.
483 em::ChromeSettingsProto chrome_settings
;
484 chrome_settings
.mutable_homepagelocation()->set_homepagelocation(
486 chrome_settings
.mutable_showhomebutton()->set_showhomebutton(true);
487 chrome_settings
.mutable_restoreonstartup()->set_restoreonstartup(4);
488 em::StringList
* list
=
489 chrome_settings
.mutable_disabledschemes()->mutable_disabledschemes();
490 list
->add_entries("ftp");
491 list
->add_entries("mailto");
492 // Try explicitly setting a policy mode too.
493 chrome_settings
.mutable_disablespdy()->set_disablespdy(false);
494 chrome_settings
.mutable_disablespdy()->mutable_policy_options()->set_mode(
495 em::PolicyOptions::MANDATORY
);
496 chrome_settings
.mutable_syncdisabled()->set_syncdisabled(true);
497 chrome_settings
.mutable_syncdisabled()->mutable_policy_options()->set_mode(
498 em::PolicyOptions::RECOMMENDED
);
500 // Build an equivalent CloudPolicySettings message.
501 em::CloudPolicySettings cloud_policy
;
502 cloud_policy
.mutable_homepagelocation()->set_value("chromium.org");
503 cloud_policy
.mutable_showhomebutton()->set_value(true);
504 cloud_policy
.mutable_restoreonstartup()->set_value(4);
505 list
= cloud_policy
.mutable_disabledschemes()->mutable_value();
506 list
->add_entries("ftp");
507 list
->add_entries("mailto");
508 cloud_policy
.mutable_disablespdy()->set_value(false);
509 cloud_policy
.mutable_disablespdy()->mutable_policy_options()->set_mode(
510 em::PolicyOptions::MANDATORY
);
511 cloud_policy
.mutable_syncdisabled()->set_value(true);
512 cloud_policy
.mutable_syncdisabled()->mutable_policy_options()->set_mode(
513 em::PolicyOptions::RECOMMENDED
);
515 // They should now serialize to the same bytes.
516 std::string chrome_settings_serialized
;
517 std::string cloud_policy_serialized
;
518 ASSERT_TRUE(chrome_settings
.SerializeToString(&chrome_settings_serialized
));
519 ASSERT_TRUE(cloud_policy
.SerializeToString(&cloud_policy_serialized
));
520 EXPECT_EQ(chrome_settings_serialized
, cloud_policy_serialized
);
523 } // namespace policy