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