Removed affiliation from chrome and tests.
[chromium-blink-merge.git] / components / policy / core / common / cloud / cloud_policy_client.h
blob41e87f7341b39dfb9b1dbec9887d6f01f2fe28dd
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 #ifndef COMPONENTS_POLICY_CORE_COMMON_CLOUD_CLOUD_POLICY_CLIENT_H_
6 #define COMPONENTS_POLICY_CORE_COMMON_CLOUD_CLOUD_POLICY_CLIENT_H_
8 #include <map>
9 #include <set>
10 #include <string>
11 #include <utility>
12 #include <vector>
14 #include "base/basictypes.h"
15 #include "base/callback.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/scoped_vector.h"
18 #include "base/observer_list.h"
19 #include "base/time/time.h"
20 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
21 #include "components/policy/core/common/remote_commands/remote_command_job.h"
22 #include "components/policy/policy_export.h"
23 #include "policy/proto/device_management_backend.pb.h"
25 namespace net {
26 class URLRequestContextGetter;
29 namespace policy {
31 class DeviceManagementRequestJob;
32 class DeviceManagementService;
34 // Implements the core logic required to talk to the device management service.
35 // Also keeps track of the current state of the association with the service,
36 // such as whether there is a valid registration (DMToken is present in that
37 // case) and whether and what errors occurred in the latest request.
39 // Note that CloudPolicyClient doesn't do any validation of policy responses
40 // such as signature and time stamp checks. These happen once the policy gets
41 // installed in the cloud policy cache.
42 class POLICY_EXPORT CloudPolicyClient {
43 public:
44 // Maps a (policy type, settings entity ID) pair to its corresponding
45 // PolicyFetchResponse.
46 using ResponseMap = std::map<std::pair<std::string, std::string>,
47 enterprise_management::PolicyFetchResponse*>;
49 // A callback which receives boolean status of an operation. If the operation
50 // succeeded, |status| is true.
51 using StatusCallback = base::Callback<void(bool status)>;
53 // A callback which receives fetched remote commands.
54 using RemoteCommandCallback = base::Callback<void(
55 DeviceManagementStatus,
56 const std::vector<enterprise_management::RemoteCommand>&)>;
58 // Observer interface for state and policy changes.
59 class POLICY_EXPORT Observer {
60 public:
61 virtual ~Observer();
63 // Called when a policy fetch completes successfully. If a policy fetch
64 // triggers an error, OnClientError() will fire.
65 virtual void OnPolicyFetched(CloudPolicyClient* client) = 0;
67 // Called upon registration state changes. This callback is invoked for
68 // successful completion of registration and unregistration requests.
69 virtual void OnRegistrationStateChanged(CloudPolicyClient* client) = 0;
71 // Called when a request for device robot OAuth2 authorization tokens
72 // returns successfully. Only occurs during enrollment. Optional
73 // (default implementation is a noop).
74 virtual void OnRobotAuthCodesFetched(CloudPolicyClient* client);
76 // Indicates there's been an error in a previously-issued request.
77 virtual void OnClientError(CloudPolicyClient* client) = 0;
80 // |provider| and |service| are weak pointers and it's the caller's
81 // responsibility to keep them valid for the lifetime of CloudPolicyClient.
82 // |verification_key_hash| contains an identifier telling the DMServer which
83 // verification key to use.
84 CloudPolicyClient(
85 const std::string& machine_id,
86 const std::string& machine_model,
87 const std::string& verification_key_hash,
88 DeviceManagementService* service,
89 scoped_refptr<net::URLRequestContextGetter> request_context);
90 virtual ~CloudPolicyClient();
92 // Sets the DMToken, thereby establishing a registration with the server. A
93 // policy fetch is not automatically issued but can be requested by calling
94 // FetchPolicy().
95 virtual void SetupRegistration(const std::string& dm_token,
96 const std::string& client_id);
98 // Attempts to register with the device management service. Results in a
99 // registration change or error notification.
100 virtual void Register(
101 enterprise_management::DeviceRegisterRequest::Type registration_type,
102 enterprise_management::DeviceRegisterRequest::Flavor flavor,
103 const std::string& auth_token,
104 const std::string& client_id,
105 const std::string& requisition,
106 const std::string& current_state_key);
108 // Sets information about a policy invalidation. Subsequent fetch operations
109 // will use the given info, and callers can use fetched_invalidation_version
110 // to determine which version of policy was fetched.
111 void SetInvalidationInfo(int64 version, const std::string& payload);
113 // Requests a policy fetch. The client being registered is a prerequisite to
114 // this operation and this call will CHECK if the client is not in registered
115 // state. FetchPolicy() triggers a policy fetch from the cloud. A policy
116 // change notification is reported to the observers and the new policy blob
117 // can be retrieved once the policy fetch operation completes. In case of
118 // multiple requests to fetch policy, new requests will cancel any pending
119 // requests and the latest request will eventually trigger notifications.
120 virtual void FetchPolicy();
122 // Requests OAuth2 auth codes for the device robot account. The client being
123 // registered is a prerequisite to this operation and this call will CHECK if
124 // the client is not in registered state.
125 virtual void FetchRobotAuthCodes(const std::string& auth_token);
127 // Sends an unregistration request to the server.
128 virtual void Unregister();
130 // Upload a device certificate to the server. Like FetchPolicy, this method
131 // requires that the client is in a registered state. |certificate_data| must
132 // hold the X.509 certificate data to be sent to the server. The |callback|
133 // will be called when the operation completes.
134 virtual void UploadCertificate(const std::string& certificate_data,
135 const StatusCallback& callback);
137 // Uploads device/session status to the server. As above, the client must be
138 // in a registered state. If non-null, |device_status| and |session_status|
139 // will be included in the upload status request. The |callback| will be
140 // called when the operation completes.
141 virtual void UploadDeviceStatus(
142 const enterprise_management::DeviceStatusReportRequest* device_status,
143 const enterprise_management::SessionStatusReportRequest* session_status,
144 const StatusCallback& callback);
146 // Attempts to fetch remote commands, with |last_command_id| being the ID of
147 // the last command that finished execution and |command_results| being
148 // results for previous commands which have not been reported yet. The
149 // |callback| will be called when the operation completes.
150 // Note that sending |last_command_id| will acknowledge this command and any
151 // previous commands. A nullptr indicates that no commands have finished
152 // execution.
153 virtual void FetchRemoteCommands(
154 scoped_ptr<RemoteCommandJob::UniqueIDType> last_command_id,
155 const std::vector<enterprise_management::RemoteCommandResult>&
156 command_results,
157 const RemoteCommandCallback& callback);
159 // Sends a device attribute update permission request to the server, uses
160 // OAuth2 token |auth_token| to identify user who requests a permission to
161 // name a device, calls a |callback| from the enrollment screen to indicate
162 // whether the device naming prompt should be shown.
163 void GetDeviceAttributeUpdatePermission(const std::string& auth_token,
164 const StatusCallback& callback);
166 // Sends a device naming information (Asset Id and Location) to the
167 // device management server, uses OAuth2 token |auth_token| to identify user
168 // who names a device, the |callback| will be called when the operation
169 // completes.
170 void UpdateDeviceAttributes(const std::string& auth_token,
171 const std::string& asset_id,
172 const std::string& location,
173 const StatusCallback& callback);
175 // Adds an observer to be called back upon policy and state changes.
176 void AddObserver(Observer* observer);
178 // Removes the specified observer.
179 void RemoveObserver(Observer* observer);
181 void set_submit_machine_id(bool submit_machine_id) {
182 submit_machine_id_ = submit_machine_id;
185 void set_last_policy_timestamp(const base::Time& timestamp) {
186 last_policy_timestamp_ = timestamp;
189 void set_public_key_version(int public_key_version) {
190 public_key_version_ = public_key_version;
191 public_key_version_valid_ = true;
194 void clear_public_key_version() {
195 public_key_version_valid_ = false;
198 // FetchPolicy() calls will request this policy type.
199 // If |settings_entity_id| is empty then it won't be set in the
200 // PolicyFetchRequest.
201 void AddPolicyTypeToFetch(const std::string& policy_type,
202 const std::string& settings_entity_id);
204 // FetchPolicy() calls won't request the given policy type and optional
205 // |settings_entity_id| anymore.
206 void RemovePolicyTypeToFetch(const std::string& policy_type,
207 const std::string& settings_entity_id);
209 // Configures a set of device state keys to transfer to the server in the next
210 // policy fetch. If the fetch is successful, the keys will be cleared so they
211 // are only uploaded once.
212 void SetStateKeysToUpload(const std::vector<std::string>& keys);
214 // Whether the client is registered with the device management service.
215 bool is_registered() const { return !dm_token_.empty(); }
217 const std::string& dm_token() const { return dm_token_; }
218 const std::string& client_id() const { return client_id_; }
220 // The device mode as received in the registration request.
221 DeviceMode device_mode() const { return device_mode_; }
223 // The policy responses as obtained by the last request to the cloud. These
224 // policies haven't gone through verification, so their contents cannot be
225 // trusted. Use CloudPolicyStore::policy() and CloudPolicyStore::policy_map()
226 // instead for making policy decisions.
227 const ResponseMap& responses() const {
228 return responses_;
231 // Returns the policy response for the (|policy_type|, |settings_entity_id|)
232 // pair if found in |responses()|. Otherwise returns nullptr.
233 const enterprise_management::PolicyFetchResponse* GetPolicyFor(
234 const std::string& policy_type,
235 const std::string& settings_entity_id) const;
237 DeviceManagementStatus status() const {
238 return status_;
241 const std::string& robot_api_auth_code() const {
242 return robot_api_auth_code_;
245 // Returns the invalidation version that was used for the last FetchPolicy.
246 // Observers can call this method from their OnPolicyFetched method to
247 // determine which at which invalidation version the policy was fetched.
248 int64 fetched_invalidation_version() const {
249 return fetched_invalidation_version_;
252 scoped_refptr<net::URLRequestContextGetter> GetRequestContext();
254 // Returns the number of active requests.
255 int GetActiveRequestCountForTest() const;
257 protected:
258 // A set of (policy type, settings entity ID) pairs to fetch.
259 typedef std::set<std::pair<std::string, std::string>> PolicyTypeSet;
261 // Callback for retries of registration requests.
262 void OnRetryRegister(DeviceManagementRequestJob* job);
264 // Callback for registration requests.
265 void OnRegisterCompleted(
266 DeviceManagementStatus status,
267 int net_error,
268 const enterprise_management::DeviceManagementResponse& response);
270 // Callback for policy fetch requests.
271 void OnPolicyFetchCompleted(
272 DeviceManagementStatus status,
273 int net_error,
274 const enterprise_management::DeviceManagementResponse& response);
276 // Callback for robot account api authorization requests.
277 void OnFetchRobotAuthCodesCompleted(
278 DeviceManagementStatus status,
279 int net_error,
280 const enterprise_management::DeviceManagementResponse& response);
282 // Callback for unregistration requests.
283 void OnUnregisterCompleted(
284 DeviceManagementStatus status,
285 int net_error,
286 const enterprise_management::DeviceManagementResponse& response);
288 // Callback for certificate upload requests.
289 void OnCertificateUploadCompleted(
290 const DeviceManagementRequestJob* job,
291 const StatusCallback& callback,
292 DeviceManagementStatus status,
293 int net_error,
294 const enterprise_management::DeviceManagementResponse& response);
296 // Callback for status upload requests.
297 void OnStatusUploadCompleted(
298 const DeviceManagementRequestJob* job,
299 const StatusCallback& callback,
300 DeviceManagementStatus status,
301 int net_error,
302 const enterprise_management::DeviceManagementResponse& response);
304 // Callback for remote command fetch requests.
305 void OnRemoteCommandsFetched(
306 const DeviceManagementRequestJob* job,
307 const RemoteCommandCallback& callback,
308 DeviceManagementStatus status,
309 int net_error,
310 const enterprise_management::DeviceManagementResponse& response);
312 // Callback for device attribute update permission requests.
313 void OnDeviceAttributeUpdatePermissionCompleted(
314 const DeviceManagementRequestJob* job,
315 const StatusCallback& callback,
316 DeviceManagementStatus status,
317 int net_error,
318 const enterprise_management::DeviceManagementResponse& response);
320 // Callback for device attribute update requests.
321 void OnDeviceAttributeUpdated(
322 const DeviceManagementRequestJob* job,
323 const StatusCallback& callback,
324 DeviceManagementStatus status,
325 int net_error,
326 const enterprise_management::DeviceManagementResponse& response);
328 // Helper to remove a job from request_jobs_.
329 void RemoveJob(const DeviceManagementRequestJob* job);
331 // Observer notification helpers.
332 void NotifyPolicyFetched();
333 void NotifyRegistrationStateChanged();
334 void NotifyRobotAuthCodesFetched();
335 void NotifyClientError();
337 // Data necessary for constructing policy requests.
338 const std::string machine_id_;
339 const std::string machine_model_;
340 const std::string verification_key_hash_;
341 PolicyTypeSet types_to_fetch_;
342 std::vector<std::string> state_keys_to_upload_;
344 std::string dm_token_;
345 DeviceMode device_mode_;
346 std::string client_id_;
347 bool submit_machine_id_;
348 base::Time last_policy_timestamp_;
349 int public_key_version_;
350 bool public_key_version_valid_;
351 std::string robot_api_auth_code_;
353 // Information for the latest policy invalidation received.
354 int64 invalidation_version_;
355 std::string invalidation_payload_;
357 // The invalidation version used for the most recent fetch operation.
358 int64 fetched_invalidation_version_;
360 // Used for issuing requests to the cloud.
361 DeviceManagementService* service_;
363 // Only one outstanding policy fetch is allowed, so this is tracked in
364 // its own member variable.
365 scoped_ptr<DeviceManagementRequestJob> policy_fetch_request_job_;
367 // All of the outstanding non-policy-fetch request jobs. These jobs are
368 // silently cancelled if Unregister() is called.
369 ScopedVector<DeviceManagementRequestJob> request_jobs_;
371 // The policy responses returned by the last policy fetch operation.
372 ResponseMap responses_;
373 DeviceManagementStatus status_;
375 base::ObserverList<Observer, true> observers_;
376 scoped_refptr<net::URLRequestContextGetter> request_context_;
378 private:
379 DISALLOW_COPY_AND_ASSIGN(CloudPolicyClient);
382 } // namespace policy
384 #endif // COMPONENTS_POLICY_CORE_COMMON_CLOUD_CLOUD_POLICY_CLIENT_H_