device_oauth2_token_service.cc revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
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 : OAuth2TokenService(getter), 199 refresh_token_is_valid_(false), 200 max_refresh_token_validation_retries_(3), 201 pending_validators_(new std::set<ValidatingConsumer*>()), 202 local_state_(local_state) { 203} 204 205DeviceOAuth2TokenService::~DeviceOAuth2TokenService() { 206 STLDeleteElements(pending_validators_.get()); 207} 208 209// TODO(davidroche): if the caller deletes the returned Request while 210// the fetches are in-flight, the OAuth2TokenService class won't call 211// back into the ValidatingConsumer and we'll end up with stale values 212// in pending_validators_ until this object is deleted. Probably not a 213// big deal, but it should be resolved by returning a Request that this 214// object owns. 215scoped_ptr<OAuth2TokenService::Request> DeviceOAuth2TokenService::StartRequest( 216 const OAuth2TokenService::ScopeSet& scopes, 217 OAuth2TokenService::Consumer* consumer) { 218 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 219 220 if (refresh_token_is_valid_) { 221 return OAuth2TokenService::StartRequest(scopes, consumer).Pass(); 222 } else { 223 ValidatingConsumer* validating_consumer = new ValidatingConsumer(this, 224 consumer); 225 pending_validators_->insert(validating_consumer); 226 227 validating_consumer->StartValidation(); 228 return OAuth2TokenService::StartRequest(scopes, validating_consumer).Pass(); 229 } 230} 231 232void DeviceOAuth2TokenService::OnValidationComplete( 233 ValidatingConsumer* validator, 234 bool refresh_token_is_valid) { 235 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 236 refresh_token_is_valid_ = refresh_token_is_valid; 237 std::set<ValidatingConsumer*>::iterator iter = pending_validators_->find( 238 validator); 239 if (iter != pending_validators_->end()) { 240 delete *iter; 241 pending_validators_->erase(iter); 242 } else { 243 LOG(ERROR) << "OnValidationComplete called for unknown validator"; 244 } 245} 246 247// static 248void DeviceOAuth2TokenService::RegisterPrefs(PrefRegistrySimple* registry) { 249 registry->RegisterStringPref(prefs::kDeviceRobotAnyApiRefreshToken, 250 std::string()); 251} 252 253void DeviceOAuth2TokenService::SetAndSaveRefreshToken( 254 const std::string& refresh_token) { 255 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 256 std::string encrypted_refresh_token = 257 CryptohomeLibrary::Get()->EncryptWithSystemSalt(refresh_token); 258 259 local_state_->SetString(prefs::kDeviceRobotAnyApiRefreshToken, 260 encrypted_refresh_token); 261} 262 263std::string DeviceOAuth2TokenService::GetRefreshToken() { 264 if (refresh_token_.empty()) { 265 std::string encrypted_refresh_token = 266 local_state_->GetString(prefs::kDeviceRobotAnyApiRefreshToken); 267 268 refresh_token_ = CryptohomeLibrary::Get()->DecryptWithSystemSalt( 269 encrypted_refresh_token); 270 } 271 return refresh_token_; 272} 273 274std::string DeviceOAuth2TokenService::GetRobotAccountId() { 275 policy::BrowserPolicyConnector* connector = 276 g_browser_process->browser_policy_connector(); 277 if (connector) 278 return connector->GetDeviceCloudPolicyManager()->GetRobotAccountId(); 279 return std::string(); 280} 281 282} // namespace chromeos 283