device_oauth2_token_service.cc revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright 2013 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/settings/device_oauth2_token_service.h"
6
7#include <string>
8#include <vector>
9
10#include "base/prefs/pref_registry_simple.h"
11#include "base/prefs/pref_service.h"
12#include "base/values.h"
13#include "chrome/browser/browser_process.h"
14#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
15#include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
16#include "chrome/browser/chromeos/settings/token_encryptor.h"
17#include "chrome/common/pref_names.h"
18#include "content/public/browser/browser_thread.h"
19#include "google_apis/gaia/gaia_urls.h"
20#include "google_apis/gaia/google_service_auth_error.h"
21#include "policy/proto/device_management_backend.pb.h"
22
23namespace {
24const char kServiceScopeGetUserInfo[] =
25    "https://www.googleapis.com/auth/userinfo.email";
26}
27
28namespace chromeos {
29
30// A wrapper for the consumer passed to StartRequest, which doesn't call
31// through to the target Consumer unless the refresh token validation is
32// complete. Additionally derives from the RequestImpl, so that it
33// can be passed back to the caller and directly deleted when cancelling
34// the request.
35class DeviceOAuth2TokenService::ValidatingConsumer
36    : public OAuth2TokenService::Consumer,
37      public OAuth2TokenService::RequestImpl,
38      public gaia::GaiaOAuthClient::Delegate {
39 public:
40  explicit ValidatingConsumer(DeviceOAuth2TokenService* token_service,
41                              const std::string& account_id,
42                              Consumer* consumer);
43  virtual ~ValidatingConsumer();
44
45  void StartValidation();
46
47  // OAuth2TokenService::Consumer
48  virtual void OnGetTokenSuccess(
49      const Request* request,
50      const std::string& access_token,
51      const base::Time& expiration_time) OVERRIDE;
52  virtual void OnGetTokenFailure(
53      const Request* request,
54      const GoogleServiceAuthError& error) OVERRIDE;
55
56  // gaia::GaiaOAuthClient::Delegate implementation.
57  virtual void OnRefreshTokenResponse(const std::string& access_token,
58                                      int expires_in_seconds) OVERRIDE;
59  virtual void OnGetTokenInfoResponse(
60      scoped_ptr<base::DictionaryValue> token_info) OVERRIDE;
61  virtual void OnOAuthError() OVERRIDE;
62  virtual void OnNetworkError(int response_code) OVERRIDE;
63
64 private:
65  void RefreshTokenIsValid(bool is_valid);
66  void InformConsumer();
67
68  DeviceOAuth2TokenService* token_service_;
69  Consumer* consumer_;
70  scoped_ptr<gaia::GaiaOAuthClient> gaia_oauth_client_;
71
72  // We don't know which will complete first: the validation or the token
73  // minting.  So, we need to cache the results so the final callback can
74  // take action.
75
76  // RefreshTokenValidationConsumer results
77  bool token_validation_done_;
78  bool token_is_valid_;
79
80  // OAuth2TokenService::Consumer results
81  bool token_fetch_done_;
82  std::string access_token_;
83  base::Time expiration_time_;
84  scoped_ptr<GoogleServiceAuthError> error_;
85};
86
87DeviceOAuth2TokenService::ValidatingConsumer::ValidatingConsumer(
88    DeviceOAuth2TokenService* token_service,
89    const std::string& account_id,
90    Consumer* consumer)
91        : OAuth2TokenService::Consumer("device_token_service"),
92          OAuth2TokenService::RequestImpl(account_id, this),
93          token_service_(token_service),
94          consumer_(consumer),
95          token_validation_done_(false),
96          token_is_valid_(false),
97          token_fetch_done_(false) {
98}
99
100DeviceOAuth2TokenService::ValidatingConsumer::~ValidatingConsumer() {
101}
102
103void DeviceOAuth2TokenService::ValidatingConsumer::StartValidation() {
104  DCHECK(!gaia_oauth_client_);
105  gaia_oauth_client_.reset(new gaia::GaiaOAuthClient(
106      g_browser_process->system_request_context()));
107
108  GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
109  gaia::OAuthClientInfo client_info;
110  client_info.client_id = gaia_urls->oauth2_chrome_client_id();
111  client_info.client_secret = gaia_urls->oauth2_chrome_client_secret();
112
113  gaia_oauth_client_->RefreshToken(
114      client_info,
115      token_service_->GetRefreshToken(token_service_->GetRobotAccountId()),
116      std::vector<std::string>(1, kServiceScopeGetUserInfo),
117      token_service_->max_refresh_token_validation_retries_,
118      this);
119}
120
121void DeviceOAuth2TokenService::ValidatingConsumer::OnRefreshTokenResponse(
122    const std::string& access_token,
123    int expires_in_seconds) {
124  gaia_oauth_client_->GetTokenInfo(
125      access_token,
126      token_service_->max_refresh_token_validation_retries_,
127      this);
128}
129
130void DeviceOAuth2TokenService::ValidatingConsumer::OnGetTokenInfoResponse(
131    scoped_ptr<base::DictionaryValue> token_info) {
132  std::string gaia_robot_id;
133  token_info->GetString("email", &gaia_robot_id);
134
135  std::string policy_robot_id = token_service_->GetRobotAccountId();
136
137  if (policy_robot_id == gaia_robot_id) {
138    RefreshTokenIsValid(true);
139  } else {
140    if (gaia_robot_id.empty()) {
141      LOG(WARNING) << "Device service account owner in policy is empty.";
142    } else {
143      LOG(WARNING) << "Device service account owner in policy does not match "
144                   << "refresh token owner \"" << gaia_robot_id << "\".";
145    }
146    RefreshTokenIsValid(false);
147  }
148}
149
150void DeviceOAuth2TokenService::ValidatingConsumer::OnOAuthError() {
151  RefreshTokenIsValid(false);
152}
153
154void DeviceOAuth2TokenService::ValidatingConsumer::OnNetworkError(
155    int response_code) {
156  RefreshTokenIsValid(false);
157}
158
159void DeviceOAuth2TokenService::ValidatingConsumer::OnGetTokenSuccess(
160      const Request* request,
161      const std::string& access_token,
162      const base::Time& expiration_time) {
163  DCHECK_EQ(request, this);
164  token_fetch_done_ = true;
165  access_token_ = access_token;
166  expiration_time_ = expiration_time;
167  if (token_validation_done_)
168    InformConsumer();
169}
170
171void DeviceOAuth2TokenService::ValidatingConsumer::OnGetTokenFailure(
172      const Request* request,
173      const GoogleServiceAuthError& error) {
174  DCHECK_EQ(request, this);
175  token_fetch_done_ = true;
176  error_.reset(new GoogleServiceAuthError(error.state()));
177  if (token_validation_done_)
178    InformConsumer();
179}
180
181void DeviceOAuth2TokenService::ValidatingConsumer::RefreshTokenIsValid(
182    bool is_valid) {
183  token_validation_done_ = true;
184  token_is_valid_ = is_valid;
185  token_service_->OnValidationComplete(is_valid);
186  if (token_fetch_done_)
187    InformConsumer();
188}
189
190void DeviceOAuth2TokenService::ValidatingConsumer::InformConsumer() {
191  DCHECK(token_fetch_done_);
192  DCHECK(token_validation_done_);
193
194  // Note: this object (which is also the Request instance) may be deleted in
195  // these consumer callbacks, so the callbacks must be the last line executed.
196  // Also, make copies of the parameters passed to the consumer to avoid invalid
197  // memory accesses when the consumer deletes |this| immediately.
198  if (!token_is_valid_) {
199    consumer_->OnGetTokenFailure(this, GoogleServiceAuthError(
200        GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS));
201  } else if (error_) {
202    GoogleServiceAuthError error_copy = *error_;
203    consumer_->OnGetTokenFailure(this, error_copy);
204  } else {
205    std::string access_token_copy = access_token_;
206    base::Time expiration_time_copy = expiration_time_;
207    consumer_->OnGetTokenSuccess(this, access_token_copy, expiration_time_copy);
208  }
209}
210
211DeviceOAuth2TokenService::DeviceOAuth2TokenService(
212    net::URLRequestContextGetter* getter,
213    PrefService* local_state,
214    TokenEncryptor* token_encryptor)
215    : refresh_token_is_valid_(false),
216      max_refresh_token_validation_retries_(3),
217      url_request_context_getter_(getter),
218      local_state_(local_state),
219      token_encryptor_(token_encryptor),
220      weak_ptr_factory_(this) {
221}
222
223DeviceOAuth2TokenService::~DeviceOAuth2TokenService() {
224}
225
226void DeviceOAuth2TokenService::OnValidationComplete(
227    bool refresh_token_is_valid) {
228  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
229  refresh_token_is_valid_ = refresh_token_is_valid;
230}
231
232// static
233void DeviceOAuth2TokenService::RegisterPrefs(PrefRegistrySimple* registry) {
234  registry->RegisterStringPref(prefs::kDeviceRobotAnyApiRefreshToken,
235                               std::string());
236}
237
238bool DeviceOAuth2TokenService::SetAndSaveRefreshToken(
239    const std::string& refresh_token) {
240  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
241
242  std::string encrypted_refresh_token =
243      token_encryptor_->EncryptWithSystemSalt(refresh_token);
244  if (encrypted_refresh_token.empty()) {
245    LOG(ERROR) << "Failed to encrypt refresh token; save aborted.";
246    return false;
247  }
248
249  local_state_->SetString(prefs::kDeviceRobotAnyApiRefreshToken,
250                          encrypted_refresh_token);
251  return true;
252}
253
254std::string DeviceOAuth2TokenService::GetRefreshToken(
255    const std::string& account_id) {
256  if (refresh_token_.empty()) {
257    std::string encrypted_refresh_token =
258        local_state_->GetString(prefs::kDeviceRobotAnyApiRefreshToken);
259
260    refresh_token_ = token_encryptor_->DecryptWithSystemSalt(
261        encrypted_refresh_token);
262    if (!encrypted_refresh_token.empty() && refresh_token_.empty())
263      LOG(ERROR) << "Failed to decrypt refresh token.";
264  }
265  return refresh_token_;
266}
267
268std::string DeviceOAuth2TokenService::GetRobotAccountId() {
269  policy::BrowserPolicyConnectorChromeOS* connector =
270      g_browser_process->platform_part()->browser_policy_connector_chromeos();
271  if (connector)
272    return connector->GetDeviceCloudPolicyManager()->GetRobotAccountId();
273  return std::string();
274}
275
276net::URLRequestContextGetter* DeviceOAuth2TokenService::GetRequestContext() {
277  return url_request_context_getter_.get();
278}
279
280scoped_ptr<OAuth2TokenService::RequestImpl>
281DeviceOAuth2TokenService::CreateRequest(
282    const std::string& account_id,
283    OAuth2TokenService::Consumer* consumer) {
284  if (refresh_token_is_valid_)
285    return OAuth2TokenService::CreateRequest(account_id, consumer);
286
287  // Substitute our own consumer to wait for refresh token validation.
288  scoped_ptr<ValidatingConsumer> validating_consumer(
289      new ValidatingConsumer(this, account_id, consumer));
290  validating_consumer->StartValidation();
291  return validating_consumer.PassAs<RequestImpl>();
292}
293
294}  // namespace chromeos
295