Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / settings / device_settings_service.h
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 #ifndef CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_SETTINGS_SERVICE_H_
6 #define CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_SETTINGS_SERVICE_H_
7
8 #include <deque>
9 #include <string>
10 #include <vector>
11
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/observer_list.h"
18 #include "base/stl_util.h"
19 #include "chromeos/dbus/session_manager_client.h"
20 #include "chromeos/tpm_token_loader.h"
21 #include "components/policy/core/common/cloud/cloud_policy_validator.h"
22
23 namespace crypto {
24 class RSAPrivateKey;
25 }
26
27 namespace enterprise_management {
28 class ChromeDeviceSettingsProto;
29 class PolicyData;
30 class PolicyFetchResponse;
31 }
32
33 namespace chromeos {
34
35 class OwnerKeyUtil;
36 class SessionManagerOperation;
37
38 // Keeps the public and private halves of the owner key. Both may be missing,
39 // but if the private key is present, the public half will be as well. This
40 // class is immutable and refcounted in order to allow safe access from any
41 // thread.
42 class OwnerKey : public base::RefCountedThreadSafe<OwnerKey> {
43  public:
44   OwnerKey(scoped_ptr<std::vector<uint8> > public_key,
45            scoped_ptr<crypto::RSAPrivateKey> private_key);
46
47   const std::vector<uint8>* public_key() {
48     return public_key_.get();
49   }
50
51   std::string public_key_as_string() {
52     return std::string(reinterpret_cast<const char*>(
53         vector_as_array(public_key_.get())), public_key_->size());
54   }
55
56   crypto::RSAPrivateKey* private_key() {
57     return private_key_.get();
58   }
59
60  private:
61   friend class base::RefCountedThreadSafe<OwnerKey>;
62   ~OwnerKey();
63
64   scoped_ptr<std::vector<uint8> > public_key_;
65   scoped_ptr<crypto::RSAPrivateKey> private_key_;
66
67   DISALLOW_COPY_AND_ASSIGN(OwnerKey);
68 };
69
70 // Deals with the low-level interface to Chromium OS device settings. Device
71 // settings are stored in a protobuf that's protected by a cryptographic
72 // signature generated by a key in the device owner's possession. Key and
73 // settings are brokered by the session_manager daemon.
74 //
75 // The purpose of DeviceSettingsService is to keep track of the current key and
76 // settings blob. For reading and writing device settings, use CrosSettings
77 // instead, which provides a high-level interface that allows for manipulation
78 // of individual settings.
79 //
80 // DeviceSettingsService generates notifications for key and policy update
81 // events so interested parties can reload state as appropriate.
82 class DeviceSettingsService : public SessionManagerClient::Observer,
83                               public TPMTokenLoader::Observer {
84  public:
85   // Indicates ownership status of the device.
86   enum OwnershipStatus {
87     // Listed in upgrade order.
88     OWNERSHIP_UNKNOWN = 0,
89     OWNERSHIP_NONE,
90     OWNERSHIP_TAKEN
91   };
92
93   typedef base::Callback<void(OwnershipStatus)> OwnershipStatusCallback;
94   typedef base::Callback<void(bool)> IsCurrentUserOwnerCallback;
95
96   // Status codes for Store().
97   enum Status {
98     STORE_SUCCESS,
99     STORE_KEY_UNAVAILABLE,       // Owner key not yet configured.
100     STORE_POLICY_ERROR,          // Failure constructing the settings blob.
101     STORE_OPERATION_FAILED,      // IPC to session_manager daemon failed.
102     STORE_NO_POLICY,             // No settings blob present.
103     STORE_INVALID_POLICY,        // Invalid settings blob.
104     STORE_VALIDATION_ERROR,      // Unrecoverable policy validation failure.
105     STORE_TEMP_VALIDATION_ERROR, // Temporary policy validation failure.
106   };
107
108   // Observer interface.
109   class Observer {
110    public:
111     virtual ~Observer();
112
113     // Indicates device ownership status changes.
114     virtual void OwnershipStatusChanged() = 0;
115
116     // Gets call after updates to the device settings.
117     virtual void DeviceSettingsUpdated() = 0;
118   };
119
120   // Manage singleton instance.
121   static void Initialize();
122   static bool IsInitialized();
123   static void Shutdown();
124   static DeviceSettingsService* Get();
125
126   // Creates a device settings service instance. This is meant for unit tests,
127   // production code uses the singleton returned by Get() above.
128   DeviceSettingsService();
129   virtual ~DeviceSettingsService();
130
131   // To be called on startup once threads are initialized and DBus is ready.
132   void SetSessionManager(SessionManagerClient* session_manager_client,
133                          scoped_refptr<OwnerKeyUtil> owner_key_util);
134
135   // Prevents the service from making further calls to session_manager_client
136   // and stops any pending operations.
137   void UnsetSessionManager();
138
139   // Returns the currently active device settings. Returns NULL if the device
140   // settings have not been retrieved from session_manager yet.
141   const enterprise_management::PolicyData* policy_data() {
142     return policy_data_.get();
143   }
144   const enterprise_management::ChromeDeviceSettingsProto*
145       device_settings() const {
146     return device_settings_.get();
147   }
148
149   // Returns the currently used owner key.
150   scoped_refptr<OwnerKey> GetOwnerKey();
151
152   // Returns the status generated by the last operation.
153   Status status() {
154     return store_status_;
155   }
156
157   // Triggers an attempt to pull the public half of the owner key from disk and
158   // load the device settings.
159   void Load();
160
161   // Signs |settings| with the private half of the owner key and sends the
162   // resulting policy blob to session manager for storage. The result of the
163   // operation is reported through |callback|. If successful, the updated device
164   // settings are present in policy_data() and device_settings() when the
165   // callback runs.
166   void SignAndStore(
167       scoped_ptr<enterprise_management::ChromeDeviceSettingsProto> new_settings,
168       const base::Closure& callback);
169
170   // Stores a policy blob to session_manager. The result of the operation is
171   // reported through |callback|. If successful, the updated device settings are
172   // present in policy_data() and device_settings() when the callback runs.
173   void Store(scoped_ptr<enterprise_management::PolicyFetchResponse> policy,
174              const base::Closure& callback);
175
176   // Returns the ownership status. May return OWNERSHIP_UNKNOWN if the disk
177   // hasn't been checked yet.
178   OwnershipStatus GetOwnershipStatus();
179
180   // Determines the ownership status and reports the result to |callback|. This
181   // is guaranteed to never return OWNERSHIP_UNKNOWN.
182   void GetOwnershipStatusAsync(const OwnershipStatusCallback& callback);
183
184   // Checks whether we have the private owner key.
185   bool HasPrivateOwnerKey();
186
187   // Determines whether the current user is the owner. The callback is
188   // guaranteed not to be called before it is possible to determine if the
189   // current user is the owner (by testing existence of the private owner key).
190   void IsCurrentUserOwnerAsync(const IsCurrentUserOwnerCallback& callback);
191
192   // Sets the identity of the user that's interacting with the service. This is
193   // relevant only for writing settings through SignAndStore().
194   void SetUsername(const std::string& username);
195   const std::string& GetUsername() const;
196
197   // Adds an observer.
198   void AddObserver(Observer* observer);
199   // Removes an observer.
200   void RemoveObserver(Observer* observer);
201
202   // SessionManagerClient::Observer:
203   virtual void OwnerKeySet(bool success) OVERRIDE;
204   virtual void PropertyChangeComplete(bool success) OVERRIDE;
205
206   // TPMTokenLoader::Observer:
207   virtual void OnTPMTokenReady() OVERRIDE;
208
209  private:
210   // Enqueues a new operation. Takes ownership of |operation| and starts it
211   // right away if there is no active operation currently.
212   void Enqueue(SessionManagerOperation* operation);
213
214   // Enqueues a load operation.
215   void EnqueueLoad(bool force_key_load);
216
217   // Makes sure there's a reload operation so changes to the settings (and key,
218   // in case force_key_load is set) are getting picked up.
219   void EnsureReload(bool force_key_load);
220
221   // Runs the next pending operation.
222   void StartNextOperation();
223
224   // Updates status, policy data and owner key from a finished operation.
225   // Starts the next pending operation if available.
226   void HandleCompletedOperation(const base::Closure& callback,
227                                 SessionManagerOperation* operation,
228                                 Status status);
229
230   SessionManagerClient* session_manager_client_;
231   scoped_refptr<OwnerKeyUtil> owner_key_util_;
232
233   Status store_status_;
234
235   std::vector<OwnershipStatusCallback> pending_ownership_status_callbacks_;
236   std::vector<IsCurrentUserOwnerCallback>
237       pending_is_current_user_owner_callbacks_;
238
239   std::string username_;
240   scoped_refptr<OwnerKey> owner_key_;
241   // Whether TPM token still needs to be initialized.
242   bool waiting_for_tpm_token_;
243   // Whether TPM token was ready when the current owner key was set.
244   // Implies that the current user is owner iff the private owner key is set.
245   bool owner_key_loaded_with_tpm_token_;
246
247   scoped_ptr<enterprise_management::PolicyData> policy_data_;
248   scoped_ptr<enterprise_management::ChromeDeviceSettingsProto> device_settings_;
249
250   // The queue of pending operations. The first operation on the queue is
251   // currently active; it gets removed and destroyed once it completes.
252   std::deque<SessionManagerOperation*> pending_operations_;
253
254   ObserverList<Observer, true> observers_;
255
256   // For recoverable load errors how many retries are left before we give up.
257   int load_retries_left_;
258
259   base::WeakPtrFactory<DeviceSettingsService> weak_factory_;
260
261   DISALLOW_COPY_AND_ASSIGN(DeviceSettingsService);
262 };
263
264 // Helper class for tests. Initializes the DeviceSettingsService singleton on
265 // construction and tears it down again on destruction.
266 class ScopedTestDeviceSettingsService {
267  public:
268   ScopedTestDeviceSettingsService();
269   ~ScopedTestDeviceSettingsService();
270
271  private:
272   DISALLOW_COPY_AND_ASSIGN(ScopedTestDeviceSettingsService);
273 };
274
275 }  // namespace chromeos
276
277 #endif  // CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_SETTINGS_SERVICE_H_