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