browser_policy_connector_chromeos.cc revision 6e8cce623b6e4fe0c9e4af605d675dd9d0338c38
1// Copyright 2014 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 "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
6
7#include <string>
8#include "base/bind.h"
9#include "base/bind_helpers.h"
10#include "base/command_line.h"
11#include "base/files/file_path.h"
12#include "base/location.h"
13#include "base/logging.h"
14#include "base/message_loop/message_loop.h"
15#include "base/message_loop/message_loop_proxy.h"
16#include "base/path_service.h"
17#include "base/prefs/pref_registry_simple.h"
18#include "base/sequenced_task_runner.h"
19#include "base/strings/utf_string_conversions.h"
20#include "base/threading/sequenced_worker_pool.h"
21#include "chrome/browser/chromeos/policy/app_pack_updater.h"
22#include "chrome/browser/chromeos/policy/consumer_management_service.h"
23#include "chrome/browser/chromeos/policy/device_cloud_policy_initializer.h"
24#include "chrome/browser/chromeos/policy/device_cloud_policy_invalidator.h"
25#include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
26#include "chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h"
27#include "chrome/browser/chromeos/policy/device_local_account.h"
28#include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
29#include "chrome/browser/chromeos/policy/device_network_configuration_updater.h"
30#include "chrome/browser/chromeos/policy/enterprise_install_attributes.h"
31#include "chrome/browser/chromeos/policy/server_backed_state_keys_broker.h"
32#include "chrome/browser/chromeos/settings/cros_settings.h"
33#include "chrome/browser/chromeos/settings/device_settings_service.h"
34#include "chrome/browser/policy/device_management_service_configuration.h"
35#include "chrome/common/pref_names.h"
36#include "chromeos/chromeos_paths.h"
37#include "chromeos/chromeos_switches.h"
38#include "chromeos/cryptohome/system_salt_getter.h"
39#include "chromeos/dbus/cryptohome_client.h"
40#include "chromeos/dbus/dbus_thread_manager.h"
41#include "chromeos/network/network_handler.h"
42#include "chromeos/network/onc/onc_certificate_importer_impl.h"
43#include "chromeos/settings/cros_settings_names.h"
44#include "chromeos/settings/cros_settings_provider.h"
45#include "chromeos/settings/timezone_settings.h"
46#include "components/policy/core/common/cloud/cloud_policy_client.h"
47#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h"
48#include "components/policy/core/common/proxy_policy_provider.h"
49#include "content/public/browser/browser_thread.h"
50#include "google_apis/gaia/gaia_auth_util.h"
51#include "net/url_request/url_request_context_getter.h"
52
53using content::BrowserThread;
54
55namespace policy {
56
57namespace {
58
59// TODO(davidyu): Update the URL to the real one once it is ready.
60// http://crbug.com/366491.
61//
62// The URL for the consumer device management server.
63const char kDefaultConsumerDeviceManagementServerUrl[] =
64    "https://m.google.com/devicemanagement/data/api";
65
66// Install attributes for tests.
67EnterpriseInstallAttributes* g_testing_install_attributes = NULL;
68
69// Helper that returns a new SequencedTaskRunner backed by the blocking pool.
70// Each SequencedTaskRunner returned is independent from the others.
71scoped_refptr<base::SequencedTaskRunner> GetBackgroundTaskRunner() {
72  base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
73  CHECK(pool);
74  return pool->GetSequencedTaskRunnerWithShutdownBehavior(
75      pool->GetSequenceToken(), base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
76}
77
78std::string GetDeviceManagementServerUrlForConsumer() {
79  const CommandLine* command_line = CommandLine::ForCurrentProcess();
80  if (command_line->HasSwitch(
81          chromeos::switches::kConsumerDeviceManagementUrl)) {
82    return command_line->GetSwitchValueASCII(
83        chromeos::switches::kConsumerDeviceManagementUrl);
84  }
85  return kDefaultConsumerDeviceManagementServerUrl;
86}
87
88}  // namespace
89
90BrowserPolicyConnectorChromeOS::BrowserPolicyConnectorChromeOS()
91    : device_cloud_policy_manager_(NULL),
92      global_user_cloud_policy_provider_(NULL),
93      weak_ptr_factory_(this) {
94  if (g_testing_install_attributes) {
95    install_attributes_.reset(g_testing_install_attributes);
96    g_testing_install_attributes = NULL;
97  }
98
99  // SystemSaltGetter or DBusThreadManager may be uninitialized on unit tests.
100
101  // TODO(satorux): Remove SystemSaltGetter::IsInitialized() when it's ready
102  // (removing it now breaks tests). crbug.com/141016.
103  if (chromeos::SystemSaltGetter::IsInitialized() &&
104      chromeos::DBusThreadManager::IsInitialized()) {
105    state_keys_broker_.reset(new ServerBackedStateKeysBroker(
106        chromeos::DBusThreadManager::Get()->GetSessionManagerClient(),
107        base::MessageLoopProxy::current()));
108
109    chromeos::CryptohomeClient* cryptohome_client =
110        chromeos::DBusThreadManager::Get()->GetCryptohomeClient();
111    if (!install_attributes_) {
112      install_attributes_.reset(
113          new EnterpriseInstallAttributes(cryptohome_client));
114    }
115    base::FilePath install_attrs_file;
116    CHECK(PathService::Get(chromeos::FILE_INSTALL_ATTRIBUTES,
117                           &install_attrs_file));
118    install_attributes_->ReadCacheFile(install_attrs_file);
119
120    scoped_ptr<DeviceCloudPolicyStoreChromeOS> device_cloud_policy_store(
121        new DeviceCloudPolicyStoreChromeOS(
122            chromeos::DeviceSettingsService::Get(),
123            install_attributes_.get(),
124            GetBackgroundTaskRunner()));
125    device_cloud_policy_manager_ =
126        new DeviceCloudPolicyManagerChromeOS(device_cloud_policy_store.Pass(),
127                                             base::MessageLoopProxy::current(),
128                                             state_keys_broker_.get());
129    AddPolicyProvider(
130        scoped_ptr<ConfigurationPolicyProvider>(device_cloud_policy_manager_));
131  }
132
133  global_user_cloud_policy_provider_ = new ProxyPolicyProvider();
134  AddPolicyProvider(scoped_ptr<ConfigurationPolicyProvider>(
135      global_user_cloud_policy_provider_));
136}
137
138BrowserPolicyConnectorChromeOS::~BrowserPolicyConnectorChromeOS() {}
139
140void BrowserPolicyConnectorChromeOS::Init(
141    PrefService* local_state,
142    scoped_refptr<net::URLRequestContextGetter> request_context) {
143  ChromeBrowserPolicyConnector::Init(local_state, request_context);
144
145  scoped_ptr<DeviceManagementService::Configuration> configuration(
146      new DeviceManagementServiceConfiguration(
147          GetDeviceManagementServerUrlForConsumer()));
148  consumer_device_management_service_.reset(
149      new DeviceManagementService(configuration.Pass()));
150  consumer_device_management_service_->ScheduleInitialization(
151      kServiceInitializationStartupDelay);
152
153  const CommandLine* command_line = CommandLine::ForCurrentProcess();
154  if (command_line->HasSwitch(chromeos::switches::kEnableConsumerManagement)) {
155    chromeos::CryptohomeClient* cryptohome_client =
156        chromeos::DBusThreadManager::Get()->GetCryptohomeClient();
157    consumer_management_service_.reset(
158        new ConsumerManagementService(cryptohome_client));
159  }
160
161  if (device_cloud_policy_manager_) {
162    // Note: for now the |device_cloud_policy_manager_| is using the global
163    // schema registry. Eventually it will have its own registry, once device
164    // cloud policy for extensions is introduced. That means it'd have to be
165    // initialized from here instead of BrowserPolicyConnector::Init().
166
167    device_cloud_policy_manager_->Initialize(local_state);
168
169    device_cloud_policy_initializer_.reset(
170        new DeviceCloudPolicyInitializer(
171            local_state,
172            device_management_service(),
173            GetDeviceManagementServiceForConsumer(),
174            GetBackgroundTaskRunner(),
175            install_attributes_.get(),
176            state_keys_broker_.get(),
177            device_cloud_policy_manager_->device_store(),
178            device_cloud_policy_manager_,
179            chromeos::DeviceSettingsService::Get(),
180            base::Bind(&BrowserPolicyConnectorChromeOS::
181                           OnDeviceCloudPolicyManagerConnected,
182                       base::Unretained(this))));
183  }
184
185  device_local_account_policy_service_.reset(
186      new DeviceLocalAccountPolicyService(
187          chromeos::DBusThreadManager::Get()->GetSessionManagerClient(),
188          chromeos::DeviceSettingsService::Get(),
189          chromeos::CrosSettings::Get(),
190          GetBackgroundTaskRunner(),
191          GetBackgroundTaskRunner(),
192          GetBackgroundTaskRunner(),
193          content::BrowserThread::GetMessageLoopProxyForThread(
194              content::BrowserThread::IO),
195          request_context));
196  device_local_account_policy_service_->Connect(device_management_service());
197  device_cloud_policy_invalidator_.reset(new DeviceCloudPolicyInvalidator);
198
199  // request_context is NULL in unit tests.
200  if (request_context && install_attributes_) {
201    app_pack_updater_.reset(
202        new AppPackUpdater(request_context, install_attributes_.get()));
203  }
204
205  SetTimezoneIfPolicyAvailable();
206
207  network_configuration_updater_ =
208      DeviceNetworkConfigurationUpdater::CreateForDevicePolicy(
209          GetPolicyService(),
210          chromeos::NetworkHandler::Get()
211              ->managed_network_configuration_handler(),
212          chromeos::NetworkHandler::Get()->network_device_handler(),
213          chromeos::CrosSettings::Get());
214}
215
216void BrowserPolicyConnectorChromeOS::ShutdownInvalidator() {
217  device_cloud_policy_invalidator_.reset();
218}
219
220void BrowserPolicyConnectorChromeOS::Shutdown() {
221  // Verify that ShutdownInvalidator() has been called first.
222  DCHECK(!device_cloud_policy_invalidator_);
223
224  // The AppPackUpdater may be observing the |device_cloud_policy_manager_|.
225  // Delete it first.
226  app_pack_updater_.reset();
227
228  network_configuration_updater_.reset();
229
230  if (device_local_account_policy_service_)
231    device_local_account_policy_service_->Shutdown();
232
233  if (device_cloud_policy_initializer_)
234    device_cloud_policy_initializer_->Shutdown();
235
236  ChromeBrowserPolicyConnector::Shutdown();
237}
238
239bool BrowserPolicyConnectorChromeOS::IsEnterpriseManaged() {
240  return install_attributes_ && install_attributes_->IsEnterpriseDevice();
241}
242
243std::string BrowserPolicyConnectorChromeOS::GetEnterpriseDomain() {
244  return install_attributes_ ? install_attributes_->GetDomain() : std::string();
245}
246
247DeviceMode BrowserPolicyConnectorChromeOS::GetDeviceMode() {
248  return install_attributes_ ? install_attributes_->GetMode()
249                             : DEVICE_MODE_NOT_SET;
250}
251
252UserAffiliation BrowserPolicyConnectorChromeOS::GetUserAffiliation(
253    const std::string& user_name) {
254  // An empty username means incognito user in case of ChromiumOS and
255  // no logged-in user in case of Chromium (SigninService). Many tests use
256  // nonsense email addresses (e.g. 'test') so treat those as non-enterprise
257  // users.
258  if (user_name.empty() || user_name.find('@') == std::string::npos)
259    return USER_AFFILIATION_NONE;
260
261  if (install_attributes_ &&
262      (gaia::ExtractDomainName(gaia::CanonicalizeEmail(user_name)) ==
263           install_attributes_->GetDomain() ||
264       policy::IsDeviceLocalAccountUser(user_name, NULL))) {
265    return USER_AFFILIATION_MANAGED;
266  }
267
268  return USER_AFFILIATION_NONE;
269}
270
271AppPackUpdater* BrowserPolicyConnectorChromeOS::GetAppPackUpdater() {
272  return app_pack_updater_.get();
273}
274
275void BrowserPolicyConnectorChromeOS::SetUserPolicyDelegate(
276    ConfigurationPolicyProvider* user_policy_provider) {
277  global_user_cloud_policy_provider_->SetDelegate(user_policy_provider);
278}
279
280void BrowserPolicyConnectorChromeOS::SetInstallAttributesForTesting(
281    EnterpriseInstallAttributes* attributes) {
282  DCHECK(!g_testing_install_attributes);
283  g_testing_install_attributes = attributes;
284}
285
286void BrowserPolicyConnectorChromeOS::RemoveInstallAttributesForTesting() {
287  if (g_testing_install_attributes) {
288    delete g_testing_install_attributes;
289    g_testing_install_attributes = NULL;
290  }
291}
292
293// static
294void BrowserPolicyConnectorChromeOS::RegisterPrefs(
295    PrefRegistrySimple* registry) {
296  registry->RegisterIntegerPref(
297      prefs::kDevicePolicyRefreshRate,
298      CloudPolicyRefreshScheduler::kDefaultRefreshDelayMs);
299}
300
301void BrowserPolicyConnectorChromeOS::SetTimezoneIfPolicyAvailable() {
302  typedef chromeos::CrosSettingsProvider Provider;
303  Provider::TrustedStatus result =
304      chromeos::CrosSettings::Get()->PrepareTrustedValues(base::Bind(
305          &BrowserPolicyConnectorChromeOS::SetTimezoneIfPolicyAvailable,
306          weak_ptr_factory_.GetWeakPtr()));
307
308  if (result != Provider::TRUSTED)
309    return;
310
311  std::string timezone;
312  if (chromeos::CrosSettings::Get()->GetString(chromeos::kSystemTimezonePolicy,
313                                               &timezone) &&
314      !timezone.empty()) {
315    chromeos::system::TimezoneSettings::GetInstance()->SetTimezoneFromID(
316        base::UTF8ToUTF16(timezone));
317  }
318}
319
320void BrowserPolicyConnectorChromeOS::OnDeviceCloudPolicyManagerConnected() {
321  // This function is invoked by DCPInitializer, so we should release the
322  // initializer after this function returns.
323  if (device_cloud_policy_initializer_) {
324    device_cloud_policy_initializer_->Shutdown();
325    base::MessageLoop::current()->DeleteSoon(
326        FROM_HERE, device_cloud_policy_initializer_.release());
327  }
328}
329
330}  // namespace policy
331