Pull Chrome_Elf out of the renderer process
[chromium-blink-merge.git] / google_apis / gaia / gaia_auth_fetcher.cc
blob9175bd2fc09e6561e8b30762d7ff9f8a7ba08f61
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 #include "google_apis/gaia/gaia_auth_fetcher.h"
7 #include <string>
8 #include <utility>
9 #include <vector>
11 #include "base/json/json_reader.h"
12 #include "base/json/json_writer.h"
13 #include "base/profiler/scoped_tracker.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/values.h"
18 #include "google_apis/gaia/gaia_auth_consumer.h"
19 #include "google_apis/gaia/gaia_constants.h"
20 #include "google_apis/gaia/gaia_urls.h"
21 #include "google_apis/gaia/google_service_auth_error.h"
22 #include "net/base/escape.h"
23 #include "net/base/load_flags.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/http/http_status_code.h"
26 #include "net/url_request/url_fetcher.h"
27 #include "net/url_request/url_request_context_getter.h"
28 #include "net/url_request/url_request_status.h"
30 namespace {
31 const int kLoadFlagsIgnoreCookies = net::LOAD_DO_NOT_SEND_COOKIES |
32 net::LOAD_DO_NOT_SAVE_COOKIES;
34 static bool CookiePartsContains(const std::vector<std::string>& parts,
35 const char* part) {
36 for (std::vector<std::string>::const_iterator it = parts.begin();
37 it != parts.end(); ++it) {
38 if (base::LowerCaseEqualsASCII(*it, part))
39 return true;
41 return false;
44 // From the JSON string |data|, extract the |access_token| and |expires_in_secs|
45 // both of which must exist. If the |refresh_token| is non-NULL, then it also
46 // must exist and is extraced; if it's NULL, then no extraction is attempted.
47 bool ExtractOAuth2TokenPairResponse(const std::string& data,
48 std::string* refresh_token,
49 std::string* access_token,
50 int* expires_in_secs) {
51 DCHECK(access_token);
52 DCHECK(expires_in_secs);
54 scoped_ptr<base::Value> value = base::JSONReader::Read(data);
55 if (!value.get() || value->GetType() != base::Value::TYPE_DICTIONARY)
56 return false;
58 base::DictionaryValue* dict =
59 static_cast<base::DictionaryValue*>(value.get());
61 if (!dict->GetStringWithoutPathExpansion("access_token", access_token) ||
62 !dict->GetIntegerWithoutPathExpansion("expires_in", expires_in_secs)) {
63 return false;
66 // Refresh token may not be required.
67 if (refresh_token) {
68 if (!dict->GetStringWithoutPathExpansion("refresh_token", refresh_token))
69 return false;
71 return true;
74 const char kListIdpServiceRequested[] = "list_idp";
75 const char kGetTokenResponseRequested[] = "get_token";
77 } // namespace
79 // TODO(chron): Add sourceless version of this formatter.
80 // static
81 const char GaiaAuthFetcher::kClientLoginFormat[] =
82 "Email=%s&"
83 "Passwd=%s&"
84 "PersistentCookie=%s&"
85 "accountType=%s&"
86 "source=%s&"
87 "service=%s";
88 // static
89 const char GaiaAuthFetcher::kClientLoginCaptchaFormat[] =
90 "Email=%s&"
91 "Passwd=%s&"
92 "PersistentCookie=%s&"
93 "accountType=%s&"
94 "source=%s&"
95 "service=%s&"
96 "logintoken=%s&"
97 "logincaptcha=%s";
98 // static
99 const char GaiaAuthFetcher::kIssueAuthTokenFormat[] =
100 "SID=%s&"
101 "LSID=%s&"
102 "service=%s&"
103 "Session=%s";
104 // static
105 const char GaiaAuthFetcher::kClientLoginToOAuth2URLFormat[] =
106 "?scope=%s&client_id=%s";
107 // static
108 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairBodyFormat[] =
109 "scope=%s&"
110 "grant_type=authorization_code&"
111 "client_id=%s&"
112 "client_secret=%s&"
113 "code=%s";
114 // static
115 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairDeviceIdParam[] =
116 "device_id=%s&device_type=chrome";
117 // static
118 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat[] =
119 "token=%s";
120 // static
121 const char GaiaAuthFetcher::kGetUserInfoFormat[] =
122 "LSID=%s";
123 // static
124 const char GaiaAuthFetcher::kMergeSessionFormat[] =
125 "uberauth=%s&"
126 "continue=%s&"
127 "source=%s";
128 // static
129 const char GaiaAuthFetcher::kUberAuthTokenURLFormat[] =
130 "?source=%s&"
131 "issueuberauth=1";
133 const char GaiaAuthFetcher::kOAuthLoginFormat[] = "service=%s&source=%s";
135 // static
136 const char GaiaAuthFetcher::kAccountDeletedError[] = "AccountDeleted";
137 // static
138 const char GaiaAuthFetcher::kAccountDisabledError[] = "AccountDisabled";
139 // static
140 const char GaiaAuthFetcher::kBadAuthenticationError[] = "BadAuthentication";
141 // static
142 const char GaiaAuthFetcher::kCaptchaError[] = "CaptchaRequired";
143 // static
144 const char GaiaAuthFetcher::kServiceUnavailableError[] =
145 "ServiceUnavailable";
146 // static
147 const char GaiaAuthFetcher::kErrorParam[] = "Error";
148 // static
149 const char GaiaAuthFetcher::kErrorUrlParam[] = "Url";
150 // static
151 const char GaiaAuthFetcher::kCaptchaUrlParam[] = "CaptchaUrl";
152 // static
153 const char GaiaAuthFetcher::kCaptchaTokenParam[] = "CaptchaToken";
155 // static
156 const char GaiaAuthFetcher::kCookiePersistence[] = "true";
157 // static
158 // TODO(johnnyg): When hosted accounts are supported by sync,
159 // we can always use "HOSTED_OR_GOOGLE"
160 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle[] =
161 "HOSTED_OR_GOOGLE";
162 const char GaiaAuthFetcher::kAccountTypeGoogle[] =
163 "GOOGLE";
165 // static
166 const char GaiaAuthFetcher::kSecondFactor[] = "Info=InvalidSecondFactor";
167 // static
168 const char GaiaAuthFetcher::kWebLoginRequired[] = "Info=WebLoginRequired";
170 // static
171 const char GaiaAuthFetcher::kAuthHeaderFormat[] =
172 "Authorization: GoogleLogin auth=%s";
173 // static
174 const char GaiaAuthFetcher::kOAuthHeaderFormat[] = "Authorization: OAuth %s";
175 // static
176 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat[] =
177 "Authorization: Bearer %s";
178 // static
179 const char GaiaAuthFetcher::kDeviceIdHeaderFormat[] = "X-Device-ID: %s";
180 // static
181 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure[] = "secure";
182 // static
183 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly[] =
184 "httponly";
185 // static
186 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix[] =
187 "oauth_code=";
188 // static
189 const int GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefixLength =
190 arraysize(GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix) - 1;
192 GaiaAuthFetcher::GaiaAuthFetcher(GaiaAuthConsumer* consumer,
193 const std::string& source,
194 net::URLRequestContextGetter* getter)
195 : consumer_(consumer),
196 getter_(getter),
197 source_(source),
198 client_login_gurl_(GaiaUrls::GetInstance()->client_login_url()),
199 issue_auth_token_gurl_(GaiaUrls::GetInstance()->issue_auth_token_url()),
200 oauth2_token_gurl_(GaiaUrls::GetInstance()->oauth2_token_url()),
201 oauth2_revoke_gurl_(GaiaUrls::GetInstance()->oauth2_revoke_url()),
202 get_user_info_gurl_(GaiaUrls::GetInstance()->get_user_info_url()),
203 merge_session_gurl_(GaiaUrls::GetInstance()->merge_session_url()),
204 uberauth_token_gurl_(GaiaUrls::GetInstance()->oauth1_login_url().Resolve(
205 base::StringPrintf(kUberAuthTokenURLFormat, source.c_str()))),
206 oauth_login_gurl_(GaiaUrls::GetInstance()->oauth1_login_url()),
207 list_accounts_gurl_(
208 GaiaUrls::GetInstance()->ListAccountsURLWithSource(source)),
209 logout_gurl_(GaiaUrls::GetInstance()->LogOutURLWithSource(source)),
210 get_check_connection_info_url_(
211 GaiaUrls::GetInstance()->GetCheckConnectionInfoURLWithSource(source)),
212 oauth2_iframe_url_(GaiaUrls::GetInstance()->oauth2_iframe_url()),
213 client_login_to_oauth2_gurl_(
214 GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
215 fetch_pending_(false) {
218 GaiaAuthFetcher::~GaiaAuthFetcher() {}
220 bool GaiaAuthFetcher::HasPendingFetch() {
221 return fetch_pending_;
224 void GaiaAuthFetcher::SetPendingFetch(bool pending_fetch) {
225 fetch_pending_ = pending_fetch;
228 void GaiaAuthFetcher::CancelRequest() {
229 fetcher_.reset();
230 fetch_pending_ = false;
233 void GaiaAuthFetcher::CreateAndStartGaiaFetcher(const std::string& body,
234 const std::string& headers,
235 const GURL& gaia_gurl,
236 int load_flags) {
237 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
238 fetcher_ = net::URLFetcher::Create(
239 0, gaia_gurl, body.empty() ? net::URLFetcher::GET : net::URLFetcher::POST,
240 this);
241 fetcher_->SetRequestContext(getter_);
242 fetcher_->SetUploadData("application/x-www-form-urlencoded", body);
244 DVLOG(2) << "Gaia fetcher URL: " << gaia_gurl.spec();
245 DVLOG(2) << "Gaia fetcher headers: " << headers;
246 DVLOG(2) << "Gaia fetcher body: " << body;
248 // The Gaia token exchange requests do not require any cookie-based
249 // identification as part of requests. We suppress sending any cookies to
250 // maintain a separation between the user's browsing and Chrome's internal
251 // services. Where such mixing is desired (MergeSession or OAuthLogin), it
252 // will be done explicitly.
253 fetcher_->SetLoadFlags(load_flags);
255 // Fetchers are sometimes cancelled because a network change was detected,
256 // especially at startup and after sign-in on ChromeOS. Retrying once should
257 // be enough in those cases; let the fetcher retry up to 3 times just in case.
258 // http://crbug.com/163710
259 fetcher_->SetAutomaticallyRetryOnNetworkChanges(3);
261 if (!headers.empty())
262 fetcher_->SetExtraRequestHeaders(headers);
264 fetch_pending_ = true;
265 fetcher_->Start();
268 // static
269 std::string GaiaAuthFetcher::MakeClientLoginBody(
270 const std::string& username,
271 const std::string& password,
272 const std::string& source,
273 const char* service,
274 const std::string& login_token,
275 const std::string& login_captcha,
276 HostedAccountsSetting allow_hosted_accounts) {
277 std::string encoded_username = net::EscapeUrlEncodedData(username, true);
278 std::string encoded_password = net::EscapeUrlEncodedData(password, true);
279 std::string encoded_login_token = net::EscapeUrlEncodedData(login_token,
280 true);
281 std::string encoded_login_captcha = net::EscapeUrlEncodedData(login_captcha,
282 true);
284 const char* account_type = allow_hosted_accounts == HostedAccountsAllowed ?
285 kAccountTypeHostedOrGoogle :
286 kAccountTypeGoogle;
288 if (login_token.empty() || login_captcha.empty()) {
289 return base::StringPrintf(kClientLoginFormat,
290 encoded_username.c_str(),
291 encoded_password.c_str(),
292 kCookiePersistence,
293 account_type,
294 source.c_str(),
295 service);
298 return base::StringPrintf(kClientLoginCaptchaFormat,
299 encoded_username.c_str(),
300 encoded_password.c_str(),
301 kCookiePersistence,
302 account_type,
303 source.c_str(),
304 service,
305 encoded_login_token.c_str(),
306 encoded_login_captcha.c_str());
309 // static
310 std::string GaiaAuthFetcher::MakeIssueAuthTokenBody(
311 const std::string& sid,
312 const std::string& lsid,
313 const char* const service) {
314 std::string encoded_sid = net::EscapeUrlEncodedData(sid, true);
315 std::string encoded_lsid = net::EscapeUrlEncodedData(lsid, true);
317 // All tokens should be session tokens except the gaia auth token.
318 bool session = true;
319 if (!strcmp(service, GaiaConstants::kGaiaService))
320 session = false;
322 return base::StringPrintf(kIssueAuthTokenFormat,
323 encoded_sid.c_str(),
324 encoded_lsid.c_str(),
325 service,
326 session ? "true" : "false");
329 // static
330 std::string GaiaAuthFetcher::MakeGetTokenPairBody(
331 const std::string& auth_code,
332 const std::string& device_id) {
333 std::string encoded_scope = net::EscapeUrlEncodedData(
334 GaiaConstants::kOAuth1LoginScope, true);
335 std::string encoded_client_id = net::EscapeUrlEncodedData(
336 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
337 std::string encoded_client_secret = net::EscapeUrlEncodedData(
338 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), true);
339 std::string encoded_auth_code = net::EscapeUrlEncodedData(auth_code, true);
340 std::string body = base::StringPrintf(
341 kOAuth2CodeToTokenPairBodyFormat, encoded_scope.c_str(),
342 encoded_client_id.c_str(), encoded_client_secret.c_str(),
343 encoded_auth_code.c_str());
344 if (!device_id.empty()) {
345 body += "&" + base::StringPrintf(kOAuth2CodeToTokenPairDeviceIdParam,
346 device_id.c_str());
348 return body;
351 // static
352 std::string GaiaAuthFetcher::MakeRevokeTokenBody(
353 const std::string& auth_token) {
354 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat, auth_token.c_str());
357 // static
358 std::string GaiaAuthFetcher::MakeGetUserInfoBody(const std::string& lsid) {
359 std::string encoded_lsid = net::EscapeUrlEncodedData(lsid, true);
360 return base::StringPrintf(kGetUserInfoFormat, encoded_lsid.c_str());
363 // static
364 std::string GaiaAuthFetcher::MakeMergeSessionBody(
365 const std::string& auth_token,
366 const std::string& external_cc_result,
367 const std::string& continue_url,
368 const std::string& source) {
369 std::string encoded_auth_token = net::EscapeUrlEncodedData(auth_token, true);
370 std::string encoded_continue_url = net::EscapeUrlEncodedData(continue_url,
371 true);
372 std::string encoded_source = net::EscapeUrlEncodedData(source, true);
373 std::string result = base::StringPrintf(kMergeSessionFormat,
374 encoded_auth_token.c_str(),
375 encoded_continue_url.c_str(),
376 encoded_source.c_str());
377 if (!external_cc_result.empty()) {
378 base::StringAppendF(&result, "&externalCcResult=%s",
379 net::EscapeUrlEncodedData(
380 external_cc_result, true).c_str());
383 return result;
386 // static
387 std::string GaiaAuthFetcher::MakeGetAuthCodeHeader(
388 const std::string& auth_token) {
389 return base::StringPrintf(kAuthHeaderFormat, auth_token.c_str());
392 // Helper method that extracts tokens from a successful reply.
393 // static
394 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string& data,
395 std::string* sid,
396 std::string* lsid,
397 std::string* token) {
398 using std::vector;
399 using std::pair;
400 using std::string;
401 sid->clear();
402 lsid->clear();
403 token->clear();
404 base::StringPairs tokens;
405 base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
406 for (base::StringPairs::iterator i = tokens.begin();
407 i != tokens.end(); ++i) {
408 if (i->first == "SID") {
409 sid->assign(i->second);
410 } else if (i->first == "LSID") {
411 lsid->assign(i->second);
412 } else if (i->first == "Auth") {
413 token->assign(i->second);
416 // If this was a request for uberauth token, then that's all we've got in
417 // data.
418 if (sid->empty() && lsid->empty() && token->empty())
419 token->assign(data);
422 // static
423 std::string GaiaAuthFetcher::MakeOAuthLoginBody(const std::string& service,
424 const std::string& source) {
425 std::string encoded_service = net::EscapeUrlEncodedData(service, true);
426 std::string encoded_source = net::EscapeUrlEncodedData(source, true);
427 return base::StringPrintf(kOAuthLoginFormat,
428 encoded_service.c_str(),
429 encoded_source.c_str());
432 // static
433 std::string GaiaAuthFetcher::MakeListIDPSessionsBody(
434 const std::string& scopes,
435 const std::string& domain) {
436 static const char getTokenResponseBodyFormat[] =
437 "action=listSessions&"
438 "client_id=%s&"
439 "origin=%s&"
440 "scope=%s";
441 std::string encoded_client_id = net::EscapeUrlEncodedData(
442 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
443 return base::StringPrintf(getTokenResponseBodyFormat,
444 encoded_client_id.c_str(),
445 domain.c_str(),
446 scopes.c_str());
449 std::string GaiaAuthFetcher::MakeGetTokenResponseBody(
450 const std::string& scopes,
451 const std::string& domain,
452 const std::string& login_hint) {
453 static const char getTokenResponseBodyFormat[] =
454 "action=issueToken&"
455 "client_id=%s&"
456 "login_hint=%s&"
457 "origin=%s&"
458 "response_type=token&"
459 "scope=%s";
460 std::string encoded_client_id = net::EscapeUrlEncodedData(
461 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
462 return base::StringPrintf(getTokenResponseBodyFormat,
463 encoded_client_id.c_str(),
464 login_hint.c_str(),
465 domain.c_str(),
466 scopes.c_str());
469 // static
470 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string& data,
471 std::string* error,
472 std::string* error_url,
473 std::string* captcha_url,
474 std::string* captcha_token) {
475 using std::vector;
476 using std::pair;
477 using std::string;
479 base::StringPairs tokens;
480 base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
481 for (base::StringPairs::iterator i = tokens.begin();
482 i != tokens.end(); ++i) {
483 if (i->first == kErrorParam) {
484 error->assign(i->second);
485 } else if (i->first == kErrorUrlParam) {
486 error_url->assign(i->second);
487 } else if (i->first == kCaptchaUrlParam) {
488 captcha_url->assign(i->second);
489 } else if (i->first == kCaptchaTokenParam) {
490 captcha_token->assign(i->second);
495 // static
496 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
497 const net::ResponseCookies& cookies,
498 std::string* auth_code) {
499 DCHECK(auth_code);
500 net::ResponseCookies::const_iterator iter;
501 for (iter = cookies.begin(); iter != cookies.end(); ++iter) {
502 if (ParseClientLoginToOAuth2Cookie(*iter, auth_code))
503 return true;
505 return false;
508 // static
509 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Cookie(const std::string& cookie,
510 std::string* auth_code) {
511 std::vector<std::string> parts;
512 base::SplitString(cookie, ';', &parts);
513 // Per documentation, the cookie should have Secure and HttpOnly.
514 if (!CookiePartsContains(parts, kClientLoginToOAuth2CookiePartSecure) ||
515 !CookiePartsContains(parts, kClientLoginToOAuth2CookiePartHttpOnly)) {
516 return false;
519 std::vector<std::string>::const_iterator iter;
520 for (iter = parts.begin(); iter != parts.end(); ++iter) {
521 const std::string& part = *iter;
522 if (base::StartsWithASCII(part, kClientLoginToOAuth2CookiePartCodePrefix,
523 false)) {
524 auth_code->assign(part.substr(
525 kClientLoginToOAuth2CookiePartCodePrefixLength));
526 return true;
529 return false;
532 // static
533 bool GaiaAuthFetcher::ParseListIdpSessionsResponse(const std::string& data,
534 std::string* login_hint) {
535 DCHECK(login_hint);
537 scoped_ptr<base::Value> value = base::JSONReader::Read(data);
538 if (!value.get() || value->GetType() != base::Value::TYPE_DICTIONARY)
539 return false;
541 base::DictionaryValue* dict =
542 static_cast<base::DictionaryValue*>(value.get());
544 base::ListValue* sessionsList;
545 if (!dict->GetList("sessions", &sessionsList))
546 return false;
548 // Find the first login_hint present in any session.
549 for (base::ListValue::iterator iter = sessionsList->begin();
550 iter != sessionsList->end();
551 iter++) {
552 base::DictionaryValue* sessionDictionary;
553 if (!(*iter)->GetAsDictionary(&sessionDictionary))
554 continue;
556 if (sessionDictionary->GetString("login_hint", login_hint))
557 break;
560 if (login_hint->empty())
561 return false;
562 return true;
565 void GaiaAuthFetcher::StartClientLogin(
566 const std::string& username,
567 const std::string& password,
568 const char* const service,
569 const std::string& login_token,
570 const std::string& login_captcha,
571 HostedAccountsSetting allow_hosted_accounts) {
573 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
575 // This class is thread agnostic, so be sure to call this only on the
576 // same thread each time.
577 DVLOG(1) << "Starting new ClientLogin fetch for:" << username;
579 // Must outlive fetcher_.
580 request_body_ = MakeClientLoginBody(username,
581 password,
582 source_,
583 service,
584 login_token,
585 login_captcha,
586 allow_hosted_accounts);
587 CreateAndStartGaiaFetcher(request_body_, std::string(), client_login_gurl_,
588 kLoadFlagsIgnoreCookies);
591 void GaiaAuthFetcher::StartIssueAuthToken(const std::string& sid,
592 const std::string& lsid,
593 const char* const service) {
594 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
596 DVLOG(1) << "Starting IssueAuthToken for: " << service;
597 requested_service_ = service;
598 request_body_ = MakeIssueAuthTokenBody(sid, lsid, service);
599 CreateAndStartGaiaFetcher(request_body_, std::string(),
600 issue_auth_token_gurl_, kLoadFlagsIgnoreCookies);
603 void GaiaAuthFetcher::StartRevokeOAuth2Token(const std::string& auth_token) {
604 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
606 DVLOG(1) << "Starting OAuth2 token revocation";
607 request_body_ = MakeRevokeTokenBody(auth_token);
608 CreateAndStartGaiaFetcher(request_body_, std::string(), oauth2_revoke_gurl_,
609 kLoadFlagsIgnoreCookies);
612 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchange(
613 const std::string& session_index) {
614 StartCookieForOAuthLoginTokenExchangeWithDeviceId(session_index,
615 std::string());
618 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchangeWithDeviceId(
619 const std::string& session_index,
620 const std::string& device_id) {
621 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
623 DVLOG(1) << "Starting OAuth login token fetch with cookie jar";
625 std::string encoded_scope = net::EscapeUrlEncodedData(
626 GaiaConstants::kOAuth1LoginScope, true);
627 std::string encoded_client_id = net::EscapeUrlEncodedData(
628 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
629 std::string query_string =
630 base::StringPrintf(kClientLoginToOAuth2URLFormat, encoded_scope.c_str(),
631 encoded_client_id.c_str());
632 if (!device_id.empty())
633 query_string += "&device_type=chrome";
634 if (!session_index.empty())
635 query_string += "&authuser=" + session_index;
637 std::string device_id_header;
638 if (!device_id.empty()) {
639 device_id_header =
640 base::StringPrintf(kDeviceIdHeaderFormat, device_id.c_str());
643 CreateAndStartGaiaFetcher(std::string(), device_id_header,
644 client_login_to_oauth2_gurl_.Resolve(query_string),
645 net::LOAD_NORMAL);
648 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchange(
649 const std::string& auth_code) {
650 StartAuthCodeForOAuth2TokenExchangeWithDeviceId(auth_code, std::string());
653 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchangeWithDeviceId(
654 const std::string& auth_code,
655 const std::string& device_id) {
656 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
658 DVLOG(1) << "Starting OAuth token pair fetch";
659 request_body_ = MakeGetTokenPairBody(auth_code, device_id);
660 CreateAndStartGaiaFetcher(request_body_, std::string(), oauth2_token_gurl_,
661 kLoadFlagsIgnoreCookies);
664 void GaiaAuthFetcher::StartGetUserInfo(const std::string& lsid) {
665 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
667 DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid;
668 request_body_ = MakeGetUserInfoBody(lsid);
669 CreateAndStartGaiaFetcher(request_body_, std::string(), get_user_info_gurl_,
670 kLoadFlagsIgnoreCookies);
673 void GaiaAuthFetcher::StartMergeSession(const std::string& uber_token,
674 const std::string& external_cc_result) {
675 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
677 DVLOG(1) << "Starting MergeSession with uber_token=" << uber_token;
679 // The continue URL is a required parameter of the MergeSession API, but in
680 // this case we don't actually need or want to navigate to it. Setting it to
681 // an arbitrary Google URL.
683 // In order for the new session to be merged correctly, the server needs to
684 // know what sessions already exist in the browser. The fetcher needs to be
685 // created such that it sends the cookies with the request, which is
686 // different from all other requests the fetcher can make.
687 std::string continue_url("http://www.google.com");
688 request_body_ = MakeMergeSessionBody(uber_token, external_cc_result,
689 continue_url, source_);
690 CreateAndStartGaiaFetcher(request_body_, std::string(), merge_session_gurl_,
691 net::LOAD_NORMAL);
694 void GaiaAuthFetcher::StartTokenFetchForUberAuthExchange(
695 const std::string& access_token) {
696 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
698 DVLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token="
699 << access_token;
700 std::string authentication_header =
701 base::StringPrintf(kOAuthHeaderFormat, access_token.c_str());
702 CreateAndStartGaiaFetcher(std::string(), authentication_header,
703 uberauth_token_gurl_, net::LOAD_NORMAL);
706 void GaiaAuthFetcher::StartOAuthLogin(const std::string& access_token,
707 const std::string& service) {
708 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
710 request_body_ = MakeOAuthLoginBody(service, source_);
711 std::string authentication_header =
712 base::StringPrintf(kOAuth2BearerHeaderFormat, access_token.c_str());
713 CreateAndStartGaiaFetcher(request_body_, authentication_header,
714 oauth_login_gurl_, net::LOAD_NORMAL);
717 void GaiaAuthFetcher::StartListAccounts() {
718 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
720 CreateAndStartGaiaFetcher(" ", // To force an HTTP POST.
721 "Origin: https://www.google.com",
722 list_accounts_gurl_, net::LOAD_NORMAL);
725 void GaiaAuthFetcher::StartLogOut() {
726 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
728 CreateAndStartGaiaFetcher(std::string(), std::string(), logout_gurl_,
729 net::LOAD_NORMAL);
732 void GaiaAuthFetcher::StartGetCheckConnectionInfo() {
733 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
735 CreateAndStartGaiaFetcher(std::string(), std::string(),
736 get_check_connection_info_url_,
737 kLoadFlagsIgnoreCookies);
740 void GaiaAuthFetcher::StartListIDPSessions(const std::string& scopes,
741 const std::string& domain) {
742 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
744 request_body_ = MakeListIDPSessionsBody(scopes, domain);
745 requested_service_ = kListIdpServiceRequested;
746 CreateAndStartGaiaFetcher(request_body_, std::string(), oauth2_iframe_url_,
747 net::LOAD_NORMAL);
750 void GaiaAuthFetcher::StartGetTokenResponse(const std::string& scopes,
751 const std::string& domain,
752 const std::string& login_hint) {
753 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
755 request_body_ = MakeGetTokenResponseBody(scopes, domain, login_hint);
756 requested_service_ = kGetTokenResponseRequested;
757 CreateAndStartGaiaFetcher(request_body_, std::string(), oauth2_iframe_url_,
758 net::LOAD_NORMAL);
761 // static
762 GoogleServiceAuthError GaiaAuthFetcher::GenerateAuthError(
763 const std::string& data,
764 const net::URLRequestStatus& status) {
765 if (!status.is_success()) {
766 if (status.status() == net::URLRequestStatus::CANCELED) {
767 return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED);
769 DLOG(WARNING) << "Could not reach Google Accounts servers: errno "
770 << status.error();
771 return GoogleServiceAuthError::FromConnectionError(status.error());
774 if (IsSecondFactorSuccess(data))
775 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR);
777 if (IsWebLoginRequiredSuccess(data))
778 return GoogleServiceAuthError(GoogleServiceAuthError::WEB_LOGIN_REQUIRED);
780 std::string error;
781 std::string url;
782 std::string captcha_url;
783 std::string captcha_token;
784 ParseClientLoginFailure(data, &error, &url, &captcha_url, &captcha_token);
785 DLOG(WARNING) << "ClientLogin failed with " << error;
787 if (error == kCaptchaError) {
788 return GoogleServiceAuthError::FromClientLoginCaptchaChallenge(
789 captcha_token,
790 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url)),
791 GURL(url));
793 if (error == kAccountDeletedError)
794 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED);
795 if (error == kAccountDisabledError)
796 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED);
797 if (error == kBadAuthenticationError) {
798 return GoogleServiceAuthError(
799 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
801 if (error == kServiceUnavailableError) {
802 return GoogleServiceAuthError(
803 GoogleServiceAuthError::SERVICE_UNAVAILABLE);
806 DLOG(WARNING) << "Incomprehensible response from Google Accounts servers.";
807 return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE);
810 void GaiaAuthFetcher::OnClientLoginFetched(const std::string& data,
811 const net::URLRequestStatus& status,
812 int response_code) {
813 if (status.is_success() && response_code == net::HTTP_OK) {
814 DVLOG(1) << "ClientLogin successful!";
815 std::string sid;
816 std::string lsid;
817 std::string token;
818 ParseClientLoginResponse(data, &sid, &lsid, &token);
819 consumer_->OnClientLoginSuccess(
820 GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
821 } else {
822 consumer_->OnClientLoginFailure(GenerateAuthError(data, status));
826 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
827 const std::string& data,
828 const net::URLRequestStatus& status,
829 int response_code) {
830 if (status.is_success() && response_code == net::HTTP_OK) {
831 // Only the bare token is returned in the body of this Gaia call
832 // without any padding.
833 consumer_->OnIssueAuthTokenSuccess(requested_service_, data);
834 } else {
835 consumer_->OnIssueAuthTokenFailure(requested_service_,
836 GenerateAuthError(data, status));
840 void GaiaAuthFetcher::OnClientLoginToOAuth2Fetched(
841 const std::string& data,
842 const net::ResponseCookies& cookies,
843 const net::URLRequestStatus& status,
844 int response_code) {
845 if (status.is_success() && response_code == net::HTTP_OK) {
846 std::string auth_code;
847 if (ParseClientLoginToOAuth2Response(cookies, &auth_code)) {
848 StartAuthCodeForOAuth2TokenExchange(auth_code);
849 } else {
850 GoogleServiceAuthError auth_error(
851 GoogleServiceAuthError::FromUnexpectedServiceResponse(
852 "ClientLogin response cookies didn't contain an auth code"));
853 consumer_->OnClientOAuthFailure(auth_error);
855 } else {
856 GoogleServiceAuthError auth_error(GenerateAuthError(data, status));
857 consumer_->OnClientOAuthFailure(auth_error);
861 void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
862 const std::string& data,
863 const net::URLRequestStatus& status,
864 int response_code) {
865 std::string refresh_token;
866 std::string access_token;
867 int expires_in_secs = 0;
869 bool success = false;
870 if (status.is_success() && response_code == net::HTTP_OK) {
871 success = ExtractOAuth2TokenPairResponse(data, &refresh_token,
872 &access_token, &expires_in_secs);
875 if (success) {
876 consumer_->OnClientOAuthSuccess(
877 GaiaAuthConsumer::ClientOAuthResult(refresh_token, access_token,
878 expires_in_secs));
879 } else {
880 consumer_->OnClientOAuthFailure(GenerateAuthError(data, status));
884 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
885 const std::string& data,
886 const net::URLRequestStatus& status,
887 int response_code) {
888 consumer_->OnOAuth2RevokeTokenCompleted();
891 void GaiaAuthFetcher::OnListAccountsFetched(const std::string& data,
892 const net::URLRequestStatus& status,
893 int response_code) {
894 if (status.is_success() && response_code == net::HTTP_OK) {
895 consumer_->OnListAccountsSuccess(data);
896 } else {
897 consumer_->OnListAccountsFailure(GenerateAuthError(data, status));
901 void GaiaAuthFetcher::OnLogOutFetched(const std::string& data,
902 const net::URLRequestStatus& status,
903 int response_code) {
904 if (status.is_success() && response_code == net::HTTP_OK) {
905 consumer_->OnLogOutSuccess();
906 } else {
907 consumer_->OnLogOutFailure(GenerateAuthError(data, status));
911 void GaiaAuthFetcher::OnGetUserInfoFetched(
912 const std::string& data,
913 const net::URLRequestStatus& status,
914 int response_code) {
915 if (status.is_success() && response_code == net::HTTP_OK) {
916 base::StringPairs tokens;
917 UserInfoMap matches;
918 base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
919 base::StringPairs::iterator i;
920 for (i = tokens.begin(); i != tokens.end(); ++i) {
921 matches[i->first] = i->second;
923 consumer_->OnGetUserInfoSuccess(matches);
924 } else {
925 consumer_->OnGetUserInfoFailure(GenerateAuthError(data, status));
929 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string& data,
930 const net::URLRequestStatus& status,
931 int response_code) {
932 if (status.is_success() && response_code == net::HTTP_OK) {
933 consumer_->OnMergeSessionSuccess(data);
934 } else {
935 consumer_->OnMergeSessionFailure(GenerateAuthError(data, status));
939 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string& data,
940 const net::URLRequestStatus& status,
941 int response_code) {
942 if (status.is_success() && response_code == net::HTTP_OK) {
943 consumer_->OnUberAuthTokenSuccess(data);
944 } else {
945 consumer_->OnUberAuthTokenFailure(GenerateAuthError(data, status));
949 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string& data,
950 const net::URLRequestStatus& status,
951 int response_code) {
952 if (status.is_success() && response_code == net::HTTP_OK) {
953 DVLOG(1) << "ClientLogin successful!";
954 std::string sid;
955 std::string lsid;
956 std::string token;
957 ParseClientLoginResponse(data, &sid, &lsid, &token);
958 consumer_->OnClientLoginSuccess(
959 GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
960 } else {
961 consumer_->OnClientLoginFailure(GenerateAuthError(data, status));
965 void GaiaAuthFetcher::OnGetCheckConnectionInfoFetched(
966 const std::string& data,
967 const net::URLRequestStatus& status,
968 int response_code) {
969 if (status.is_success() && response_code == net::HTTP_OK) {
970 consumer_->OnGetCheckConnectionInfoSuccess(data);
971 } else {
972 consumer_->OnGetCheckConnectionInfoError(GenerateAuthError(data, status));
976 void GaiaAuthFetcher::OnListIdpSessionsFetched(
977 const std::string& data,
978 const net::URLRequestStatus& status,
979 int response_code) {
980 if (status.is_success() && response_code == net::HTTP_OK) {
981 DVLOG(1) << "ListIdpSessions successful!";
982 std::string login_hint;
983 if (ParseListIdpSessionsResponse(data, &login_hint)) {
984 consumer_->OnListIdpSessionsSuccess(login_hint);
985 } else {
986 GoogleServiceAuthError auth_error(
987 GoogleServiceAuthError::FromUnexpectedServiceResponse(
988 "List Sessions response didn't contain a login_hint."));
989 consumer_->OnListIdpSessionsError(auth_error);
991 } else {
992 consumer_->OnListIdpSessionsError(GenerateAuthError(data, status));
996 void GaiaAuthFetcher::OnGetTokenResponseFetched(
997 const std::string& data,
998 const net::URLRequestStatus& status,
999 int response_code) {
1000 std::string access_token;
1001 int expires_in_secs = 0;
1002 bool success = false;
1003 if (status.is_success() && response_code == net::HTTP_OK) {
1004 DVLOG(1) << "GetTokenResponse successful!";
1005 success = ExtractOAuth2TokenPairResponse(data, NULL,
1006 &access_token, &expires_in_secs);
1009 if (success) {
1010 consumer_->OnGetTokenResponseSuccess(
1011 GaiaAuthConsumer::ClientOAuthResult(std::string(), access_token,
1012 expires_in_secs));
1013 } else {
1014 consumer_->OnGetTokenResponseError(GenerateAuthError(data, status));
1018 void GaiaAuthFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
1019 fetch_pending_ = false;
1020 // Some of the GAIA requests perform redirects, which results in the final
1021 // URL of the fetcher not being the original URL requested. Therefore use
1022 // the original URL when determining which OnXXX function to call.
1023 const GURL& url = source->GetOriginalURL();
1024 const net::URLRequestStatus& status = source->GetStatus();
1025 int response_code = source->GetResponseCode();
1026 std::string data;
1027 source->GetResponseAsString(&data);
1029 // Retrieve the response headers from the request. Must only be called after
1030 // the OnURLFetchComplete callback has run.
1031 #ifndef NDEBUG
1032 std::string headers;
1033 if (source->GetResponseHeaders())
1034 source->GetResponseHeaders()->GetNormalizedHeaders(&headers);
1035 DVLOG(2) << "Response " << url.spec() << ", code = " << response_code << "\n"
1036 << headers << "\n";
1037 DVLOG(2) << "data: " << data << "\n";
1038 #endif
1040 DispatchFetchedRequest(url, data, source->GetCookies(), status,
1041 response_code);
1044 void GaiaAuthFetcher::DispatchFetchedRequest(
1045 const GURL& url,
1046 const std::string& data,
1047 const net::ResponseCookies& cookies,
1048 const net::URLRequestStatus& status,
1049 int response_code) {
1050 if (url == client_login_gurl_) {
1051 OnClientLoginFetched(data, status, response_code);
1052 } else if (url == issue_auth_token_gurl_) {
1053 OnIssueAuthTokenFetched(data, status, response_code);
1054 } else if (base::StartsWithASCII(url.spec(),
1055 client_login_to_oauth2_gurl_.spec(), true)) {
1056 OnClientLoginToOAuth2Fetched(data, cookies, status, response_code);
1057 } else if (url == oauth2_token_gurl_) {
1058 OnOAuth2TokenPairFetched(data, status, response_code);
1059 } else if (url == get_user_info_gurl_) {
1060 OnGetUserInfoFetched(data, status, response_code);
1061 } else if (url == merge_session_gurl_) {
1062 OnMergeSessionFetched(data, status, response_code);
1063 } else if (url == uberauth_token_gurl_) {
1064 OnUberAuthTokenFetch(data, status, response_code);
1065 } else if (url == oauth_login_gurl_) {
1066 OnOAuthLoginFetched(data, status, response_code);
1067 } else if (url == oauth2_revoke_gurl_) {
1068 OnOAuth2RevokeTokenFetched(data, status, response_code);
1069 } else if (url == list_accounts_gurl_) {
1070 OnListAccountsFetched(data, status, response_code);
1071 } else if (url == logout_gurl_) {
1072 OnLogOutFetched(data, status, response_code);
1073 } else if (url == get_check_connection_info_url_) {
1074 OnGetCheckConnectionInfoFetched(data, status, response_code);
1075 } else if (url == oauth2_iframe_url_) {
1076 if (requested_service_ == kListIdpServiceRequested)
1077 OnListIdpSessionsFetched(data, status, response_code);
1078 else if (requested_service_ == kGetTokenResponseRequested)
1079 OnGetTokenResponseFetched(data, status, response_code);
1080 else
1081 NOTREACHED();
1082 } else {
1083 NOTREACHED();
1087 // static
1088 bool GaiaAuthFetcher::IsSecondFactorSuccess(
1089 const std::string& alleged_error) {
1090 return alleged_error.find(kSecondFactor) !=
1091 std::string::npos;
1094 // static
1095 bool GaiaAuthFetcher::IsWebLoginRequiredSuccess(
1096 const std::string& alleged_error) {
1097 return alleged_error.find(kWebLoginRequired) !=
1098 std::string::npos;