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_POLICY_CLOUD_CLOUD_POLICY_CLIENT_H_
6#define CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CLIENT_H_
7
8#include <map>
9#include <set>
10#include <string>
11
12#include "base/basictypes.h"
13#include "base/callback.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/observer_list.h"
16#include "base/time/time.h"
17#include "chrome/browser/policy/cloud/cloud_policy_constants.h"
18#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h"
19
20namespace policy {
21
22class DeviceManagementRequestJob;
23class DeviceManagementService;
24
25// Implements the core logic required to talk to the device management service.
26// Also keeps track of the current state of the association with the service,
27// such as whether there is a valid registration (DMToken is present in that
28// case) and whether and what errors occurred in the latest request.
29//
30// Note that CloudPolicyClient doesn't do any validation of policy responses
31// such as signature and time stamp checks. These happen once the policy gets
32// installed in the cloud policy cache.
33class CloudPolicyClient {
34 public:
35  // Maps a PolicyNamespaceKey to its corresponding PolicyFetchResponse.
36  typedef std::map<PolicyNamespaceKey,
37                   enterprise_management::PolicyFetchResponse*> ResponseMap;
38
39  // A callback which receives boolean status of an operation.  If the operation
40  // succeeded, |status| is true.
41  typedef base::Callback<void(bool status)> StatusCallback;
42
43  // Observer interface for state and policy changes.
44  class Observer {
45   public:
46    virtual ~Observer();
47
48    // Called when a policy fetch completes successfully. If a policy fetch
49    // triggers an error, OnClientError() will fire.
50    virtual void OnPolicyFetched(CloudPolicyClient* client) = 0;
51
52    // Called upon registration state changes. This callback is invoked for
53    // successful completion of registration and unregistration requests.
54    virtual void OnRegistrationStateChanged(CloudPolicyClient* client) = 0;
55
56    // Called when a request for device robot OAuth2 authorization tokens
57    // returns successfully. Only occurs during enrollment. Optional
58    // (default implementation is a noop).
59    virtual void OnRobotAuthCodesFetched(CloudPolicyClient* client);
60
61    // Indicates there's been an error in a previously-issued request.
62    virtual void OnClientError(CloudPolicyClient* client) = 0;
63  };
64
65  // Delegate interface for supplying status information to upload to the server
66  // as part of the policy fetch request.
67  class StatusProvider {
68   public:
69    virtual ~StatusProvider();
70
71    // Retrieves status information to send with the next policy fetch.
72    // Implementations must return true if status information was filled in.
73    virtual bool GetDeviceStatus(
74        enterprise_management::DeviceStatusReportRequest* status) = 0;
75    virtual bool GetSessionStatus(
76        enterprise_management::SessionStatusReportRequest* status) = 0;
77
78    // Called after the status information has successfully been submitted to
79    // the server.
80    virtual void OnSubmittedSuccessfully() = 0;
81  };
82
83  // |provider| and |service| are weak pointers and it's the caller's
84  // responsibility to keep them valid for the lifetime of CloudPolicyClient.
85  CloudPolicyClient(const std::string& machine_id,
86                    const std::string& machine_model,
87                    UserAffiliation user_affiliation,
88                    StatusProvider* provider,
89                    DeviceManagementService* service);
90  virtual ~CloudPolicyClient();
91
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);
97
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      const std::string& auth_token,
103      const std::string& client_id,
104      bool is_auto_enrollment,
105      const std::string& requisition);
106
107  // Sets information about a policy invalidation. Subsequent fetch operations
108  // will use the given info, and callers can use fetched_invalidation_version
109  // to determine which version of policy was fetched.
110  void SetInvalidationInfo(int64 version, const std::string& payload);
111
112  // Requests a policy fetch. The client being registered is a prerequisite to
113  // this operation and this call will CHECK if the client is not in registered
114  // state. FetchPolicy() triggers a policy fetch from the cloud. A policy
115  // change notification is reported to the observers and the new policy blob
116  // can be retrieved once the policy fetch operation completes. In case of
117  // multiple requests to fetch policy, new requests will cancel any pending
118  // requests and the latest request will eventually trigger notifications.
119  virtual void FetchPolicy();
120
121  // Requests OAuth2 auth codes for the device robot account. The client being
122  // registered is a prerequisite to this operation and this call will CHECK if
123  // the client is not in registered state.
124  virtual void FetchRobotAuthCodes(const std::string& auth_token);
125
126  // Sends an unregistration request to the server.
127  virtual void Unregister();
128
129  // Upload a device certificate to the server.  Like FetchPolicy, this method
130  // requires that the client is in a registered state.  |certificate_data| must
131  // hold the X.509 certificate data to be sent to the server.  The |callback|
132  // will be called when the operation completes.
133  virtual void UploadCertificate(const std::string& certificate_data,
134                                 const StatusCallback& callback);
135
136  // Adds an observer to be called back upon policy and state changes.
137  void AddObserver(Observer* observer);
138
139  // Removes the specified observer.
140  void RemoveObserver(Observer* observer);
141
142  void set_submit_machine_id(bool submit_machine_id) {
143    submit_machine_id_ = submit_machine_id;
144  }
145
146  void set_last_policy_timestamp(const base::Time& timestamp) {
147    last_policy_timestamp_ = timestamp;
148  }
149
150  void set_public_key_version(int public_key_version) {
151    public_key_version_ = public_key_version;
152    public_key_version_valid_ = true;
153  }
154
155  void clear_public_key_version() {
156    public_key_version_valid_ = false;
157  }
158
159  // FetchPolicy() calls will request this policy namespace.
160  void AddNamespaceToFetch(const PolicyNamespaceKey& policy_ns_key);
161
162  // FetchPolicy() calls won't request the given policy namespace anymore.
163  void RemoveNamespaceToFetch(const PolicyNamespaceKey& policy_ns_key);
164
165  // Whether the client is registered with the device management service.
166  bool is_registered() const { return !dm_token_.empty(); }
167
168  const std::string& dm_token() const { return dm_token_; }
169
170  // The device mode as received in the registration request.
171  DeviceMode device_mode() const { return device_mode_; }
172
173  // The policy responses as obtained by the last request to the cloud. These
174  // policies haven't gone through verification, so their contents cannot be
175  // trusted. Use CloudPolicyStore::policy() and CloudPolicyStore::policy_map()
176  // instead for making policy decisions.
177  const ResponseMap& responses() const {
178    return responses_;
179  }
180
181  // Returns the policy response for |policy_ns_key|, if found in |responses()|;
182  // otherwise returns NULL.
183  const enterprise_management::PolicyFetchResponse* GetPolicyFor(
184      const PolicyNamespaceKey& policy_ns_key) const;
185
186  DeviceManagementStatus status() const {
187    return status_;
188  }
189
190  const std::string& robot_api_auth_code() const {
191    return robot_api_auth_code_;
192  }
193
194  // Returns the invalidation version that was used for the last FetchPolicy.
195  // Observers can call this method from their OnPolicyFetched method to
196  // determine which at which invalidation version the policy was fetched.
197  int64 fetched_invalidation_version() const {
198    return fetched_invalidation_version_;
199  }
200
201 protected:
202  // A set of PolicyNamespaceKeys to fetch.
203  typedef std::set<PolicyNamespaceKey> NamespaceSet;
204
205  // Callback for retries of registration requests.
206  void OnRetryRegister(DeviceManagementRequestJob* job);
207
208  // Callback for registration requests.
209  void OnRegisterCompleted(
210      DeviceManagementStatus status,
211      int net_error,
212      const enterprise_management::DeviceManagementResponse& response);
213
214  // Callback for policy fetch requests.
215  void OnPolicyFetchCompleted(
216      DeviceManagementStatus status,
217      int net_error,
218      const enterprise_management::DeviceManagementResponse& response);
219
220  // Callback for robot account api authorization requests.
221  void OnFetchRobotAuthCodesCompleted(
222      DeviceManagementStatus status,
223      int net_error,
224      const enterprise_management::DeviceManagementResponse& response);
225
226  // Callback for unregistration requests.
227  void OnUnregisterCompleted(
228      DeviceManagementStatus status,
229      int net_error,
230      const enterprise_management::DeviceManagementResponse& response);
231
232  // Callback for certificate upload requests.
233  void OnCertificateUploadCompleted(
234      const StatusCallback& callback,
235      DeviceManagementStatus status,
236      int net_error,
237      const enterprise_management::DeviceManagementResponse& response);
238
239  // Observer notification helpers.
240  void NotifyPolicyFetched();
241  void NotifyRegistrationStateChanged();
242  void NotifyRobotAuthCodesFetched();
243  void NotifyClientError();
244
245  // Data necessary for constructing policy requests.
246  const std::string machine_id_;
247  const std::string machine_model_;
248  const UserAffiliation user_affiliation_;
249  NamespaceSet namespaces_to_fetch_;
250
251  std::string dm_token_;
252  DeviceMode device_mode_;
253  std::string client_id_;
254  bool submit_machine_id_;
255  base::Time last_policy_timestamp_;
256  int public_key_version_;
257  bool public_key_version_valid_;
258  std::string robot_api_auth_code_;
259
260  // Information for the latest policy invalidation received.
261  int64 invalidation_version_;
262  std::string invalidation_payload_;
263
264  // The invalidation version used for the most recent fetch operation.
265  int64 fetched_invalidation_version_;
266
267  // Used for issuing requests to the cloud.
268  DeviceManagementService* service_;
269  scoped_ptr<DeviceManagementRequestJob> request_job_;
270
271  // Status upload data is produced by |status_provider_|.
272  StatusProvider* status_provider_;
273
274  // The policy responses returned by the last policy fetch operation.
275  ResponseMap responses_;
276  DeviceManagementStatus status_;
277
278  ObserverList<Observer, true> observers_;
279
280 private:
281  DISALLOW_COPY_AND_ASSIGN(CloudPolicyClient);
282};
283
284}  // namespace policy
285
286#endif  // CHROME_BROWSER_POLICY_CLOUD_CLOUD_POLICY_CLIENT_H_
287