device_oauth2_token_service.cc revision ca12bfac764ba476d6cd062bf1dde12cc64c3f40
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/device_cloud_policy_manager_chromeos.h" 15#include "chrome/browser/policy/browser_policy_connector.h" 16#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" 17#include "chrome/common/pref_names.h" 18#include "chromeos/cryptohome/cryptohome_library.h" 19#include "content/public/browser/browser_thread.h" 20#include "google_apis/gaia/gaia_urls.h" 21#include "google_apis/gaia/google_service_auth_error.h" 22 23namespace { 24const char kServiceScopeGetUserInfo[] = 25 "https://www.googleapis.com/auth/userinfo.email"; 26} // namespace 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. 33class DeviceOAuth2TokenService::ValidatingConsumer 34 : public OAuth2TokenService::Consumer, 35 public gaia::GaiaOAuthClient::Delegate { 36 public: 37 explicit ValidatingConsumer(DeviceOAuth2TokenService* token_service, 38 Consumer* consumer); 39 virtual ~ValidatingConsumer(); 40 41 void StartValidation(); 42 43 // OAuth2TokenService::Consumer 44 virtual void OnGetTokenSuccess( 45 const Request* request, 46 const std::string& access_token, 47 const base::Time& expiration_time) OVERRIDE; 48 virtual void OnGetTokenFailure( 49 const Request* request, 50 const GoogleServiceAuthError& error) OVERRIDE; 51 52 // gaia::GaiaOAuthClient::Delegate implementation. 53 virtual void OnRefreshTokenResponse(const std::string& access_token, 54 int expires_in_seconds) OVERRIDE; 55 virtual void OnGetTokenInfoResponse(scoped_ptr<DictionaryValue> token_info) 56 OVERRIDE; 57 virtual void OnOAuthError() OVERRIDE; 58 virtual void OnNetworkError(int response_code) OVERRIDE; 59 60 private: 61 void RefreshTokenIsValid(bool is_valid); 62 void InformConsumer(); 63 64 DeviceOAuth2TokenService* token_service_; 65 Consumer* consumer_; 66 scoped_ptr<gaia::GaiaOAuthClient> gaia_oauth_client_; 67 68 // We don't know which will complete first: the validation or the token 69 // minting. So, we need to cache the results so the final callback can 70 // take action. 71 72 // RefreshTokenValidationConsumer results 73 bool token_validation_done_; 74 bool token_is_valid_; 75 76 // OAuth2TokenService::Consumer results 77 const Request* request_; 78 std::string access_token_; 79 base::Time expiration_time_; 80 scoped_ptr<GoogleServiceAuthError> error_; 81}; 82 83DeviceOAuth2TokenService::ValidatingConsumer::ValidatingConsumer( 84 DeviceOAuth2TokenService* token_service, 85 Consumer* consumer) 86 : token_service_(token_service), 87 consumer_(consumer), 88 token_validation_done_(false), 89 token_is_valid_(false), 90 request_(NULL) { 91} 92 93DeviceOAuth2TokenService::ValidatingConsumer::~ValidatingConsumer() { 94} 95 96void DeviceOAuth2TokenService::ValidatingConsumer::StartValidation() { 97 DCHECK(!gaia_oauth_client_); 98 gaia_oauth_client_.reset(new gaia::GaiaOAuthClient( 99 g_browser_process->system_request_context())); 100 101 GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); 102 gaia::OAuthClientInfo client_info; 103 client_info.client_id = gaia_urls->oauth2_chrome_client_id(); 104 client_info.client_secret = gaia_urls->oauth2_chrome_client_secret(); 105 106 gaia_oauth_client_->RefreshToken( 107 client_info, 108 token_service_->GetRefreshToken(), 109 std::vector<std::string>(1, kServiceScopeGetUserInfo), 110 token_service_->max_refresh_token_validation_retries_, 111 this); 112} 113 114void DeviceOAuth2TokenService::ValidatingConsumer::OnRefreshTokenResponse( 115 const std::string& access_token, 116 int expires_in_seconds) { 117 gaia_oauth_client_->GetTokenInfo( 118 access_token, 119 token_service_->max_refresh_token_validation_retries_, 120 this); 121} 122 123void DeviceOAuth2TokenService::ValidatingConsumer::OnGetTokenInfoResponse( 124 scoped_ptr<DictionaryValue> token_info) { 125 std::string gaia_robot_id; 126 token_info->GetString("email", &gaia_robot_id); 127 128 std::string policy_robot_id = token_service_->GetRobotAccountId(); 129 130 if (policy_robot_id == gaia_robot_id) { 131 RefreshTokenIsValid(true); 132 } else { 133 if (gaia_robot_id.empty()) { 134 LOG(WARNING) << "Device service account owner in policy is empty."; 135 } else { 136 LOG(INFO) << "Device service account owner in policy does not match " 137 << "refresh token owner \"" << gaia_robot_id << "\"."; 138 } 139 RefreshTokenIsValid(false); 140 } 141} 142 143void DeviceOAuth2TokenService::ValidatingConsumer::OnOAuthError() { 144 RefreshTokenIsValid(false); 145} 146 147void DeviceOAuth2TokenService::ValidatingConsumer::OnNetworkError( 148 int response_code) { 149 RefreshTokenIsValid(false); 150} 151 152void DeviceOAuth2TokenService::ValidatingConsumer::OnGetTokenSuccess( 153 const Request* request, 154 const std::string& access_token, 155 const base::Time& expiration_time) { 156 request_ = request; 157 access_token_ = access_token; 158 expiration_time_ = expiration_time; 159 if (token_validation_done_) 160 InformConsumer(); 161} 162 163void DeviceOAuth2TokenService::ValidatingConsumer::OnGetTokenFailure( 164 const Request* request, 165 const GoogleServiceAuthError& error) { 166 request_ = request; 167 error_.reset(new GoogleServiceAuthError(error.state())); 168 if (token_validation_done_) 169 InformConsumer(); 170} 171 172void DeviceOAuth2TokenService::ValidatingConsumer::RefreshTokenIsValid( 173 bool is_valid) { 174 token_validation_done_ = true; 175 token_is_valid_ = is_valid; 176 // If we have a request pointer, then the minting is complete. 177 if (request_) 178 InformConsumer(); 179} 180 181void DeviceOAuth2TokenService::ValidatingConsumer::InformConsumer() { 182 DCHECK(request_); 183 DCHECK(token_validation_done_); 184 if (!token_is_valid_) { 185 consumer_->OnGetTokenFailure(request_, GoogleServiceAuthError( 186 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS)); 187 } else if (error_) { 188 consumer_->OnGetTokenFailure(request_, *error_.get()); 189 } else { 190 consumer_->OnGetTokenSuccess(request_, access_token_, expiration_time_); 191 } 192 token_service_->OnValidationComplete(this, token_is_valid_); 193} 194 195DeviceOAuth2TokenService::DeviceOAuth2TokenService( 196 net::URLRequestContextGetter* getter, 197 PrefService* local_state) 198 : refresh_token_is_valid_(false), 199 max_refresh_token_validation_retries_(3), 200 pending_validators_(new std::set<ValidatingConsumer*>()), 201 url_request_context_getter_(getter), 202 local_state_(local_state) { 203} 204 205DeviceOAuth2TokenService::~DeviceOAuth2TokenService() { 206 STLDeleteElements(pending_validators_.get()); 207} 208 209net::URLRequestContextGetter* DeviceOAuth2TokenService::GetRequestContext() { 210 return url_request_context_getter_.get(); 211} 212 213 214// TODO(davidroche): if the caller deletes the returned Request while 215// the fetches are in-flight, the OAuth2TokenService class won't call 216// back into the ValidatingConsumer and we'll end up with stale values 217// in pending_validators_ until this object is deleted. Probably not a 218// big deal, but it should be resolved by returning a Request that this 219// object owns. 220scoped_ptr<OAuth2TokenService::Request> DeviceOAuth2TokenService::StartRequest( 221 const OAuth2TokenService::ScopeSet& scopes, 222 OAuth2TokenService::Consumer* consumer) { 223 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 224 225 if (refresh_token_is_valid_) { 226 return OAuth2TokenService::StartRequest(scopes, consumer).Pass(); 227 } else { 228 ValidatingConsumer* validating_consumer = new ValidatingConsumer(this, 229 consumer); 230 pending_validators_->insert(validating_consumer); 231 232 validating_consumer->StartValidation(); 233 return OAuth2TokenService::StartRequest(scopes, validating_consumer).Pass(); 234 } 235} 236 237void DeviceOAuth2TokenService::OnValidationComplete( 238 ValidatingConsumer* validator, 239 bool refresh_token_is_valid) { 240 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 241 refresh_token_is_valid_ = refresh_token_is_valid; 242 std::set<ValidatingConsumer*>::iterator iter = pending_validators_->find( 243 validator); 244 if (iter != pending_validators_->end()) { 245 delete *iter; 246 pending_validators_->erase(iter); 247 } else { 248 LOG(ERROR) << "OnValidationComplete called for unknown validator"; 249 } 250} 251 252// static 253void DeviceOAuth2TokenService::RegisterPrefs(PrefRegistrySimple* registry) { 254 registry->RegisterStringPref(prefs::kDeviceRobotAnyApiRefreshToken, 255 std::string()); 256} 257 258void DeviceOAuth2TokenService::SetAndSaveRefreshToken( 259 const std::string& refresh_token) { 260 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 261 std::string encrypted_refresh_token = 262 CryptohomeLibrary::Get()->EncryptWithSystemSalt(refresh_token); 263 264 local_state_->SetString(prefs::kDeviceRobotAnyApiRefreshToken, 265 encrypted_refresh_token); 266} 267 268std::string DeviceOAuth2TokenService::GetRefreshToken() { 269 if (refresh_token_.empty()) { 270 std::string encrypted_refresh_token = 271 local_state_->GetString(prefs::kDeviceRobotAnyApiRefreshToken); 272 273 refresh_token_ = CryptohomeLibrary::Get()->DecryptWithSystemSalt( 274 encrypted_refresh_token); 275 } 276 return refresh_token_; 277} 278 279std::string DeviceOAuth2TokenService::GetRobotAccountId() { 280 policy::BrowserPolicyConnector* connector = 281 g_browser_process->browser_policy_connector(); 282 if (connector) 283 return connector->GetDeviceCloudPolicyManager()->GetRobotAccountId(); 284 return std::string(); 285} 286 287} // namespace chromeos 288