gaia_auth_fetcher_unittest.cc revision 868fa2fe829687343ffae624259930155e16dbd8
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// A complete set of unit tests for GaiaAuthFetcher.
6// Originally ported from GoogleAuthenticator tests.
7
8#include <string>
9
10#include "base/json/json_reader.h"
11#include "base/message_loop.h"
12#include "base/strings/stringprintf.h"
13#include "base/values.h"
14#include "chrome/test/base/testing_profile.h"
15#include "google_apis/gaia/gaia_auth_consumer.h"
16#include "google_apis/gaia/gaia_auth_fetcher.h"
17#include "google_apis/gaia/gaia_urls.h"
18#include "google_apis/gaia/google_service_auth_error.h"
19#include "google_apis/gaia/mock_url_fetcher_factory.h"
20#include "google_apis/google_api_keys.h"
21#include "googleurl/src/gurl.h"
22#include "net/base/load_flags.h"
23#include "net/base/net_errors.h"
24#include "net/http/http_status_code.h"
25#include "net/url_request/test_url_fetcher_factory.h"
26#include "net/url_request/url_fetcher_delegate.h"
27#include "net/url_request/url_request_status.h"
28#include "testing/gmock/include/gmock/gmock.h"
29#include "testing/gtest/include/gtest/gtest.h"
30
31using ::testing::_;
32using ::testing::Invoke;
33
34namespace {
35static const char kGetAuthCodeValidCookie[] =
36    "oauth_code=test-code; Path=/test; Secure; HttpOnly";
37static const char kGetAuthCodeCookieNoSecure[] =
38    "oauth_code=test-code; Path=/test; HttpOnly";
39static const char kGetAuthCodeCookieNoHttpOnly[] =
40    "oauth_code=test-code; Path=/test; Secure";
41static const char kGetAuthCodeCookieNoOAuthCode[] =
42    "Path=/test; Secure; HttpOnly";
43static const char kGetTokenPairValidResponse[] =
44    "{"
45    "  \"refresh_token\": \"rt1\","
46    "  \"access_token\": \"at1\","
47    "  \"expires_in\": 3600,"
48    "  \"token_type\": \"Bearer\""
49    "}";
50static const char kClientOAuthValidResponse[] =
51    "{"
52    "  \"oauth2\": {"
53    "    \"refresh_token\": \"rt1\","
54    "    \"access_token\": \"at1\","
55    "    \"expires_in\": 3600,"
56    "    \"token_type\": \"Bearer\""
57    "  }"
58    "}";
59
60}  // namespace
61
62MockFetcher::MockFetcher(bool success,
63                         const GURL& url,
64                         const std::string& results,
65                         net::URLFetcher::RequestType request_type,
66                         net::URLFetcherDelegate* d)
67    : TestURLFetcher(0, url, d) {
68  set_url(url);
69  net::URLRequestStatus::Status code;
70
71  if (success) {
72    set_response_code(net::HTTP_OK);
73    code = net::URLRequestStatus::SUCCESS;
74  } else {
75    set_response_code(net::HTTP_FORBIDDEN);
76    code = net::URLRequestStatus::FAILED;
77  }
78
79  set_status(net::URLRequestStatus(code, 0));
80  SetResponseString(results);
81}
82
83MockFetcher::MockFetcher(const GURL& url,
84                         const net::URLRequestStatus& status,
85                         int response_code,
86                         const net::ResponseCookies& cookies,
87                         const std::string& results,
88                         net::URLFetcher::RequestType request_type,
89                         net::URLFetcherDelegate* d)
90    : TestURLFetcher(0, url, d) {
91  set_url(url);
92  set_status(status);
93  set_response_code(response_code);
94  set_cookies(cookies);
95  SetResponseString(results);
96}
97
98MockFetcher::~MockFetcher() {}
99
100void MockFetcher::Start() {
101  delegate()->OnURLFetchComplete(this);
102}
103
104class GaiaAuthFetcherTest : public testing::Test {
105 public:
106  GaiaAuthFetcherTest()
107      : client_login_source_(GaiaUrls::GetInstance()->client_login_url()),
108        issue_auth_token_source_(
109            GaiaUrls::GetInstance()->issue_auth_token_url()),
110        client_login_to_oauth2_source_(
111            GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
112        oauth2_token_source_(GaiaUrls::GetInstance()->oauth2_token_url()),
113        token_auth_source_(GaiaUrls::GetInstance()->token_auth_url()),
114        merge_session_source_(GaiaUrls::GetInstance()->merge_session_url()),
115        uberauth_token_source_(base::StringPrintf(
116            "%s?source=&issueuberauth=1",
117            GaiaUrls::GetInstance()->oauth1_login_url().c_str())),
118        oauth_login_gurl_(GaiaUrls::GetInstance()->oauth1_login_url()) {}
119
120  void RunParsingTest(const std::string& data,
121                      const std::string& sid,
122                      const std::string& lsid,
123                      const std::string& token) {
124    std::string out_sid;
125    std::string out_lsid;
126    std::string out_token;
127
128    GaiaAuthFetcher::ParseClientLoginResponse(data,
129                                              &out_sid,
130                                              &out_lsid,
131                                              &out_token);
132    EXPECT_EQ(lsid, out_lsid);
133    EXPECT_EQ(sid, out_sid);
134    EXPECT_EQ(token, out_token);
135  }
136
137  void RunErrorParsingTest(const std::string& data,
138                           const std::string& error,
139                           const std::string& error_url,
140                           const std::string& captcha_url,
141                           const std::string& captcha_token) {
142    std::string out_error;
143    std::string out_error_url;
144    std::string out_captcha_url;
145    std::string out_captcha_token;
146
147    GaiaAuthFetcher::ParseClientLoginFailure(data,
148                                             &out_error,
149                                             &out_error_url,
150                                             &out_captcha_url,
151                                             &out_captcha_token);
152    EXPECT_EQ(error, out_error);
153    EXPECT_EQ(error_url, out_error_url);
154    EXPECT_EQ(captcha_url, out_captcha_url);
155    EXPECT_EQ(captcha_token, out_captcha_token);
156  }
157
158  net::ResponseCookies cookies_;
159  GURL client_login_source_;
160  GURL issue_auth_token_source_;
161  GURL client_login_to_oauth2_source_;
162  GURL oauth2_token_source_;
163  GURL token_auth_source_;
164  GURL merge_session_source_;
165  GURL uberauth_token_source_;
166  GURL oauth_login_gurl_;
167  TestingProfile profile_;
168 protected:
169  base::MessageLoop message_loop_;
170};
171
172class MockGaiaConsumer : public GaiaAuthConsumer {
173 public:
174  MockGaiaConsumer() {}
175  ~MockGaiaConsumer() {}
176
177  MOCK_METHOD1(OnClientLoginSuccess, void(const ClientLoginResult& result));
178  MOCK_METHOD2(OnIssueAuthTokenSuccess, void(const std::string& service,
179      const std::string& token));
180  MOCK_METHOD1(OnClientOAuthSuccess,
181               void(const GaiaAuthConsumer::ClientOAuthResult& result));
182  MOCK_METHOD1(OnMergeSessionSuccess, void(const std::string& data));
183  MOCK_METHOD1(OnUberAuthTokenSuccess, void(const std::string& data));
184  MOCK_METHOD1(OnClientLoginFailure,
185      void(const GoogleServiceAuthError& error));
186  MOCK_METHOD2(OnIssueAuthTokenFailure, void(const std::string& service,
187      const GoogleServiceAuthError& error));
188  MOCK_METHOD1(OnClientOAuthFailure,
189      void(const GoogleServiceAuthError& error));
190  MOCK_METHOD1(OnMergeSessionFailure, void(
191      const GoogleServiceAuthError& error));
192  MOCK_METHOD1(OnUberAuthTokenFailure, void(
193      const GoogleServiceAuthError& error));
194};
195
196#if defined(OS_WIN)
197#define MAYBE_ErrorComparator DISABLED_ErrorComparator
198#else
199#define MAYBE_ErrorComparator ErrorComparator
200#endif
201
202TEST_F(GaiaAuthFetcherTest, MAYBE_ErrorComparator) {
203  GoogleServiceAuthError expected_error =
204      GoogleServiceAuthError::FromConnectionError(-101);
205
206  GoogleServiceAuthError matching_error =
207      GoogleServiceAuthError::FromConnectionError(-101);
208
209  EXPECT_TRUE(expected_error == matching_error);
210
211  expected_error = GoogleServiceAuthError::FromConnectionError(6);
212
213  EXPECT_FALSE(expected_error == matching_error);
214
215  expected_error = GoogleServiceAuthError(GoogleServiceAuthError::NONE);
216
217  EXPECT_FALSE(expected_error == matching_error);
218
219  matching_error = GoogleServiceAuthError(GoogleServiceAuthError::NONE);
220
221  EXPECT_TRUE(expected_error == matching_error);
222}
223
224TEST_F(GaiaAuthFetcherTest, LoginNetFailure) {
225  int error_no = net::ERR_CONNECTION_RESET;
226  net::URLRequestStatus status(net::URLRequestStatus::FAILED, error_no);
227
228  GoogleServiceAuthError expected_error =
229      GoogleServiceAuthError::FromConnectionError(error_no);
230
231  MockGaiaConsumer consumer;
232  EXPECT_CALL(consumer, OnClientLoginFailure(expected_error))
233      .Times(1);
234
235  GaiaAuthFetcher auth(&consumer, std::string(),
236      profile_.GetRequestContext());
237
238  MockFetcher mock_fetcher(
239      client_login_source_, status, 0, net::ResponseCookies(), std::string(),
240      net::URLFetcher::GET, &auth);
241  auth.OnURLFetchComplete(&mock_fetcher);
242}
243
244TEST_F(GaiaAuthFetcherTest, TokenNetFailure) {
245  int error_no = net::ERR_CONNECTION_RESET;
246  net::URLRequestStatus status(net::URLRequestStatus::FAILED, error_no);
247
248  GoogleServiceAuthError expected_error =
249      GoogleServiceAuthError::FromConnectionError(error_no);
250
251  MockGaiaConsumer consumer;
252  EXPECT_CALL(consumer, OnIssueAuthTokenFailure(_, expected_error))
253      .Times(1);
254
255  GaiaAuthFetcher auth(&consumer, std::string(),
256      profile_.GetRequestContext());
257
258  MockFetcher mock_fetcher(
259      issue_auth_token_source_, status, 0, cookies_, std::string(),
260      net::URLFetcher::GET, &auth);
261  auth.OnURLFetchComplete(&mock_fetcher);
262}
263
264
265TEST_F(GaiaAuthFetcherTest, LoginDenied) {
266  std::string data("Error=BadAuthentication");
267  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
268
269  GoogleServiceAuthError expected_error(
270      GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
271
272  MockGaiaConsumer consumer;
273  EXPECT_CALL(consumer, OnClientLoginFailure(expected_error))
274      .Times(1);
275
276  GaiaAuthFetcher auth(&consumer, std::string(),
277      profile_.GetRequestContext());
278
279  MockFetcher mock_fetcher(
280      client_login_source_, status, net::HTTP_FORBIDDEN, cookies_, data,
281      net::URLFetcher::GET, &auth);
282  auth.OnURLFetchComplete(&mock_fetcher);
283}
284
285TEST_F(GaiaAuthFetcherTest, ParseRequest) {
286  RunParsingTest("SID=sid\nLSID=lsid\nAuth=auth\n", "sid", "lsid", "auth");
287  RunParsingTest("LSID=lsid\nSID=sid\nAuth=auth\n", "sid", "lsid", "auth");
288  RunParsingTest("SID=sid\nLSID=lsid\nAuth=auth", "sid", "lsid", "auth");
289  RunParsingTest("SID=sid\nAuth=auth\n", "sid", std::string(), "auth");
290  RunParsingTest("LSID=lsid\nAuth=auth\n", std::string(), "lsid", "auth");
291  RunParsingTest("\nAuth=auth\n", std::string(), std::string(), "auth");
292  RunParsingTest("SID=sid", "sid", std::string(), std::string());
293}
294
295TEST_F(GaiaAuthFetcherTest, ParseErrorRequest) {
296  RunErrorParsingTest("Url=U\n"
297                      "Error=E\n"
298                      "CaptchaToken=T\n"
299                      "CaptchaUrl=C\n", "E", "U", "C", "T");
300  RunErrorParsingTest("CaptchaToken=T\n"
301                      "Error=E\n"
302                      "Url=U\n"
303                      "CaptchaUrl=C\n", "E", "U", "C", "T");
304  RunErrorParsingTest("\n\n\nCaptchaToken=T\n"
305                      "\nError=E\n"
306                      "\nUrl=U\n"
307                      "CaptchaUrl=C\n", "E", "U", "C", "T");
308}
309
310
311TEST_F(GaiaAuthFetcherTest, OnlineLogin) {
312  std::string data("SID=sid\nLSID=lsid\nAuth=auth\n");
313
314  GaiaAuthConsumer::ClientLoginResult result;
315  result.lsid = "lsid";
316  result.sid = "sid";
317  result.token = "auth";
318  result.data = data;
319
320  MockGaiaConsumer consumer;
321  EXPECT_CALL(consumer, OnClientLoginSuccess(result))
322      .Times(1);
323
324  GaiaAuthFetcher auth(&consumer, std::string(),
325      profile_.GetRequestContext());
326  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
327  MockFetcher mock_fetcher(
328      client_login_source_, status, net::HTTP_OK, cookies_, data,
329      net::URLFetcher::GET, &auth);
330  auth.OnURLFetchComplete(&mock_fetcher);
331}
332
333TEST_F(GaiaAuthFetcherTest, WorkingIssueAuthToken) {
334  MockGaiaConsumer consumer;
335  EXPECT_CALL(consumer, OnIssueAuthTokenSuccess(_, "token"))
336      .Times(1);
337
338  GaiaAuthFetcher auth(&consumer, std::string(),
339      profile_.GetRequestContext());
340  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
341  MockFetcher mock_fetcher(
342      issue_auth_token_source_, status, net::HTTP_OK, cookies_, "token",
343      net::URLFetcher::GET, &auth);
344  auth.OnURLFetchComplete(&mock_fetcher);
345}
346
347TEST_F(GaiaAuthFetcherTest, CheckTwoFactorResponse) {
348  std::string response =
349      base::StringPrintf("Error=BadAuthentication\n%s\n",
350                         GaiaAuthFetcher::kSecondFactor);
351  EXPECT_TRUE(GaiaAuthFetcher::IsSecondFactorSuccess(response));
352}
353
354TEST_F(GaiaAuthFetcherTest, CheckNormalErrorCode) {
355  std::string response = "Error=BadAuthentication\n";
356  EXPECT_FALSE(GaiaAuthFetcher::IsSecondFactorSuccess(response));
357}
358
359TEST_F(GaiaAuthFetcherTest, TwoFactorLogin) {
360  std::string response = base::StringPrintf("Error=BadAuthentication\n%s\n",
361      GaiaAuthFetcher::kSecondFactor);
362
363  GoogleServiceAuthError error =
364      GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR);
365
366  MockGaiaConsumer consumer;
367  EXPECT_CALL(consumer, OnClientLoginFailure(error))
368      .Times(1);
369
370  GaiaAuthFetcher auth(&consumer, std::string(),
371      profile_.GetRequestContext());
372  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
373  MockFetcher mock_fetcher(
374      client_login_source_, status, net::HTTP_FORBIDDEN, cookies_, response,
375      net::URLFetcher::GET, &auth);
376  auth.OnURLFetchComplete(&mock_fetcher);
377}
378
379TEST_F(GaiaAuthFetcherTest, CaptchaParse) {
380  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
381  std::string data = "Url=http://www.google.com/login/captcha\n"
382                     "Error=CaptchaRequired\n"
383                     "CaptchaToken=CCTOKEN\n"
384                     "CaptchaUrl=Captcha?ctoken=CCTOKEN\n";
385  GoogleServiceAuthError error =
386      GaiaAuthFetcher::GenerateAuthError(data, status);
387
388  std::string token = "CCTOKEN";
389  GURL image_url("http://accounts.google.com/Captcha?ctoken=CCTOKEN");
390  GURL unlock_url("http://www.google.com/login/captcha");
391
392  EXPECT_EQ(error.state(), GoogleServiceAuthError::CAPTCHA_REQUIRED);
393  EXPECT_EQ(error.captcha().token, token);
394  EXPECT_EQ(error.captcha().image_url, image_url);
395  EXPECT_EQ(error.captcha().unlock_url, unlock_url);
396}
397
398TEST_F(GaiaAuthFetcherTest, AccountDeletedError) {
399  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
400  std::string data = "Error=AccountDeleted\n";
401  GoogleServiceAuthError error =
402      GaiaAuthFetcher::GenerateAuthError(data, status);
403  EXPECT_EQ(error.state(), GoogleServiceAuthError::ACCOUNT_DELETED);
404}
405
406TEST_F(GaiaAuthFetcherTest, AccountDisabledError) {
407  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
408  std::string data = "Error=AccountDisabled\n";
409  GoogleServiceAuthError error =
410      GaiaAuthFetcher::GenerateAuthError(data, status);
411  EXPECT_EQ(error.state(), GoogleServiceAuthError::ACCOUNT_DISABLED);
412}
413
414TEST_F(GaiaAuthFetcherTest,BadAuthenticationError) {
415  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
416  std::string data = "Error=BadAuthentication\n";
417  GoogleServiceAuthError error =
418      GaiaAuthFetcher::GenerateAuthError(data, status);
419  EXPECT_EQ(error.state(), GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
420}
421
422TEST_F(GaiaAuthFetcherTest,IncomprehensibleError) {
423  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
424  std::string data = "Error=Gobbledygook\n";
425  GoogleServiceAuthError error =
426      GaiaAuthFetcher::GenerateAuthError(data, status);
427  EXPECT_EQ(error.state(), GoogleServiceAuthError::SERVICE_UNAVAILABLE);
428}
429
430TEST_F(GaiaAuthFetcherTest,ServiceUnavailableError) {
431  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
432  std::string data = "Error=ServiceUnavailable\n";
433  GoogleServiceAuthError error =
434      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
435  EXPECT_EQ(error.state(), GoogleServiceAuthError::SERVICE_UNAVAILABLE);
436}
437
438TEST_F(GaiaAuthFetcherTest, OAuthAccountDeletedError) {
439  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
440  std::string data = "Error=adel\n";
441  GoogleServiceAuthError error =
442      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
443  EXPECT_EQ(error.state(), GoogleServiceAuthError::ACCOUNT_DELETED);
444}
445
446TEST_F(GaiaAuthFetcherTest, OAuthAccountDisabledError) {
447  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
448  std::string data = "Error=adis\n";
449  GoogleServiceAuthError error =
450      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
451  EXPECT_EQ(error.state(), GoogleServiceAuthError::ACCOUNT_DISABLED);
452}
453
454TEST_F(GaiaAuthFetcherTest, OAuthBadAuthenticationError) {
455  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
456  std::string data = "Error=badauth\n";
457  GoogleServiceAuthError error =
458      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
459  EXPECT_EQ(error.state(), GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
460}
461
462TEST_F(GaiaAuthFetcherTest, OAuthServiceUnavailableError) {
463  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
464  std::string data = "Error=ire\n";
465  GoogleServiceAuthError error =
466      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
467  EXPECT_EQ(error.state(), GoogleServiceAuthError::SERVICE_UNAVAILABLE);
468}
469
470TEST_F(GaiaAuthFetcherTest, FullLogin) {
471  MockGaiaConsumer consumer;
472  EXPECT_CALL(consumer, OnClientLoginSuccess(_))
473      .Times(1);
474
475  MockURLFetcherFactory<MockFetcher> factory;
476
477  GaiaAuthFetcher auth(&consumer, std::string(),
478      profile_.GetRequestContext());
479  auth.StartClientLogin("username",
480                        "password",
481                        "service",
482                        std::string(),
483                        std::string(),
484                        GaiaAuthFetcher::HostedAccountsAllowed);
485}
486
487TEST_F(GaiaAuthFetcherTest, FullLoginFailure) {
488  MockGaiaConsumer consumer;
489  EXPECT_CALL(consumer, OnClientLoginFailure(_))
490      .Times(1);
491
492  MockURLFetcherFactory<MockFetcher> factory;
493  factory.set_success(false);
494
495  GaiaAuthFetcher auth(&consumer, std::string(),
496      profile_.GetRequestContext());
497  auth.StartClientLogin("username",
498                        "password",
499                        "service",
500                        std::string(),
501                        std::string(),
502                        GaiaAuthFetcher::HostedAccountsAllowed);
503}
504
505TEST_F(GaiaAuthFetcherTest, ClientFetchPending) {
506  MockGaiaConsumer consumer;
507  EXPECT_CALL(consumer, OnClientLoginSuccess(_))
508      .Times(1);
509
510  net::TestURLFetcherFactory factory;
511
512  GaiaAuthFetcher auth(&consumer, std::string(),
513      profile_.GetRequestContext());
514  auth.StartClientLogin("username",
515                        "password",
516                        "service",
517                        std::string(),
518                        std::string(),
519                        GaiaAuthFetcher::HostedAccountsAllowed);
520
521  EXPECT_TRUE(auth.HasPendingFetch());
522  MockFetcher mock_fetcher(
523      client_login_source_,
524      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
525      net::HTTP_OK, cookies_, "SID=sid\nLSID=lsid\nAuth=auth\n",
526      net::URLFetcher::GET, &auth);
527  auth.OnURLFetchComplete(&mock_fetcher);
528  EXPECT_FALSE(auth.HasPendingFetch());
529}
530
531TEST_F(GaiaAuthFetcherTest, FullTokenSuccess) {
532  MockGaiaConsumer consumer;
533  EXPECT_CALL(consumer, OnIssueAuthTokenSuccess("service", "token"))
534      .Times(1);
535
536  net::TestURLFetcherFactory factory;
537  GaiaAuthFetcher auth(&consumer, std::string(),
538                       profile_.GetRequestContext());
539  auth.StartIssueAuthToken("sid", "lsid", "service");
540
541  EXPECT_TRUE(auth.HasPendingFetch());
542  MockFetcher mock_fetcher(
543      issue_auth_token_source_,
544      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
545      net::HTTP_OK, cookies_, "token",
546      net::URLFetcher::GET, &auth);
547  auth.OnURLFetchComplete(&mock_fetcher);
548  EXPECT_FALSE(auth.HasPendingFetch());
549}
550
551TEST_F(GaiaAuthFetcherTest, FullTokenFailure) {
552  MockGaiaConsumer consumer;
553  EXPECT_CALL(consumer, OnIssueAuthTokenFailure("service", _))
554      .Times(1);
555
556  net::TestURLFetcherFactory factory;
557
558  GaiaAuthFetcher auth(&consumer, std::string(),
559      profile_.GetRequestContext());
560  auth.StartIssueAuthToken("sid", "lsid", "service");
561
562  EXPECT_TRUE(auth.HasPendingFetch());
563  MockFetcher mock_fetcher(
564      issue_auth_token_source_,
565      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
566      net::HTTP_FORBIDDEN,
567      cookies_,
568      std::string(),
569      net::URLFetcher::GET,
570      &auth);
571  auth.OnURLFetchComplete(&mock_fetcher);
572  EXPECT_FALSE(auth.HasPendingFetch());
573}
574
575TEST_F(GaiaAuthFetcherTest, OAuthLoginTokenSuccess) {
576  MockGaiaConsumer consumer;
577  EXPECT_CALL(consumer, OnClientOAuthSuccess(
578      GaiaAuthConsumer::ClientOAuthResult("rt1", "at1", 3600))).Times(1);
579
580  net::TestURLFetcherFactory factory;
581  GaiaAuthFetcher auth(&consumer, std::string(),
582                       profile_.GetRequestContext());
583  auth.StartLsoForOAuthLoginTokenExchange("lso_token");
584  net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
585  EXPECT_TRUE(NULL != fetcher);
586  EXPECT_EQ(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES,
587            fetcher->GetLoadFlags());
588
589  net::ResponseCookies cookies;
590  cookies.push_back(kGetAuthCodeValidCookie);
591  EXPECT_TRUE(auth.HasPendingFetch());
592  MockFetcher mock_fetcher1(
593      client_login_to_oauth2_source_,
594      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
595      net::HTTP_OK,
596      cookies,
597      std::string(),
598      net::URLFetcher::POST,
599      &auth);
600  auth.OnURLFetchComplete(&mock_fetcher1);
601  EXPECT_TRUE(auth.HasPendingFetch());
602  MockFetcher mock_fetcher2(
603      oauth2_token_source_,
604      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
605      net::HTTP_OK, cookies_, kGetTokenPairValidResponse,
606      net::URLFetcher::POST, &auth);
607  auth.OnURLFetchComplete(&mock_fetcher2);
608  EXPECT_FALSE(auth.HasPendingFetch());
609}
610
611TEST_F(GaiaAuthFetcherTest, OAuthLoginTokenWithCookies) {
612  MockGaiaConsumer consumer;
613  net::TestURLFetcherFactory factory;
614  GaiaAuthFetcher auth(&consumer, std::string(),
615                       profile_.GetRequestContext());
616  auth.StartCookieForOAuthLoginTokenExchange("0");
617  net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
618  EXPECT_TRUE(NULL != fetcher);
619  EXPECT_EQ(net::LOAD_NORMAL, fetcher->GetLoadFlags());
620}
621
622TEST_F(GaiaAuthFetcherTest, OAuthLoginTokenClientLoginToOAuth2Failure) {
623  MockGaiaConsumer consumer;
624  EXPECT_CALL(consumer, OnClientOAuthFailure(_))
625      .Times(1);
626
627  net::TestURLFetcherFactory factory;
628  GaiaAuthFetcher auth(&consumer, std::string(),
629                       profile_.GetRequestContext());
630  auth.StartLsoForOAuthLoginTokenExchange("lso_token");
631
632  net::ResponseCookies cookies;
633  EXPECT_TRUE(auth.HasPendingFetch());
634  MockFetcher mock_fetcher(
635      client_login_to_oauth2_source_,
636      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
637      net::HTTP_FORBIDDEN,
638      cookies,
639      std::string(),
640      net::URLFetcher::POST,
641      &auth);
642  auth.OnURLFetchComplete(&mock_fetcher);
643  EXPECT_FALSE(auth.HasPendingFetch());
644}
645
646TEST_F(GaiaAuthFetcherTest, OAuthLoginTokenOAuth2TokenPairFailure) {
647  MockGaiaConsumer consumer;
648  EXPECT_CALL(consumer, OnClientOAuthFailure(_))
649      .Times(1);
650
651  net::TestURLFetcherFactory factory;
652  GaiaAuthFetcher auth(&consumer, std::string(),
653                       profile_.GetRequestContext());
654  auth.StartLsoForOAuthLoginTokenExchange("lso_token");
655
656  net::ResponseCookies cookies;
657  cookies.push_back(kGetAuthCodeValidCookie);
658  EXPECT_TRUE(auth.HasPendingFetch());
659  MockFetcher mock_fetcher1(
660      client_login_to_oauth2_source_,
661      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
662      net::HTTP_OK,
663      cookies,
664      std::string(),
665      net::URLFetcher::POST,
666      &auth);
667  auth.OnURLFetchComplete(&mock_fetcher1);
668  EXPECT_TRUE(auth.HasPendingFetch());
669  MockFetcher mock_fetcher2(
670      oauth2_token_source_,
671      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
672      net::HTTP_FORBIDDEN,
673      cookies_,
674      std::string(),
675      net::URLFetcher::POST,
676      &auth);
677  auth.OnURLFetchComplete(&mock_fetcher2);
678  EXPECT_FALSE(auth.HasPendingFetch());
679}
680
681TEST_F(GaiaAuthFetcherTest, MergeSessionSuccess) {
682  MockGaiaConsumer consumer;
683  EXPECT_CALL(consumer, OnMergeSessionSuccess("<html></html>"))
684      .Times(1);
685
686  net::TestURLFetcherFactory factory;
687
688  GaiaAuthFetcher auth(&consumer, std::string(),
689      profile_.GetRequestContext());
690  auth.StartMergeSession("myubertoken");
691
692  EXPECT_TRUE(auth.HasPendingFetch());
693  MockFetcher mock_fetcher(
694      merge_session_source_,
695      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
696      net::HTTP_OK, cookies_, "<html></html>", net::URLFetcher::GET,
697      &auth);
698  auth.OnURLFetchComplete(&mock_fetcher);
699  EXPECT_FALSE(auth.HasPendingFetch());
700}
701
702TEST_F(GaiaAuthFetcherTest, MergeSessionSuccessRedirect) {
703  MockGaiaConsumer consumer;
704  EXPECT_CALL(consumer, OnMergeSessionSuccess("<html></html>"))
705      .Times(1);
706
707  net::TestURLFetcherFactory factory;
708
709  GaiaAuthFetcher auth(&consumer, std::string(),
710      profile_.GetRequestContext());
711  auth.StartMergeSession("myubertoken");
712
713  // Make sure the fetcher created has the expected flags.  Set its url()
714  // properties to reflect a redirect.
715  net::TestURLFetcher* test_fetcher = factory.GetFetcherByID(0);
716  EXPECT_TRUE(test_fetcher != NULL);
717  EXPECT_TRUE(test_fetcher->GetLoadFlags() == net::LOAD_NORMAL);
718  EXPECT_TRUE(auth.HasPendingFetch());
719
720  GURL final_url("http://www.google.com/CheckCookie");
721  test_fetcher->set_url(final_url);
722  test_fetcher->set_status(
723      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0));
724  test_fetcher->set_response_code(net::HTTP_OK);
725  test_fetcher->set_cookies(cookies_);
726  test_fetcher->SetResponseString("<html></html>");
727
728  auth.OnURLFetchComplete(test_fetcher);
729  EXPECT_FALSE(auth.HasPendingFetch());
730}
731
732TEST_F(GaiaAuthFetcherTest, UberAuthTokenSuccess) {
733  MockGaiaConsumer consumer;
734  EXPECT_CALL(consumer, OnUberAuthTokenSuccess("uberToken"))
735      .Times(1);
736
737  net::TestURLFetcherFactory factory;
738
739  GaiaAuthFetcher auth(&consumer, std::string(),
740      profile_.GetRequestContext());
741  auth.StartTokenFetchForUberAuthExchange("myAccessToken");
742
743  EXPECT_TRUE(auth.HasPendingFetch());
744  MockFetcher mock_fetcher(
745      uberauth_token_source_,
746      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
747      net::HTTP_OK, cookies_, "uberToken", net::URLFetcher::POST,
748      &auth);
749  auth.OnURLFetchComplete(&mock_fetcher);
750  EXPECT_FALSE(auth.HasPendingFetch());
751}
752
753TEST_F(GaiaAuthFetcherTest, ParseClientLoginToOAuth2Response) {
754  {  // No cookies.
755    std::string auth_code;
756    net::ResponseCookies cookies;
757    EXPECT_FALSE(GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
758        cookies, &auth_code));
759    EXPECT_EQ("", auth_code);
760  }
761  {  // Few cookies, nothing appropriate.
762    std::string auth_code;
763    net::ResponseCookies cookies;
764    cookies.push_back(kGetAuthCodeCookieNoSecure);
765    cookies.push_back(kGetAuthCodeCookieNoHttpOnly);
766    cookies.push_back(kGetAuthCodeCookieNoOAuthCode);
767    EXPECT_FALSE(GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
768        cookies, &auth_code));
769    EXPECT_EQ("", auth_code);
770  }
771  {  // Few cookies, one of them is valid.
772    std::string auth_code;
773    net::ResponseCookies cookies;
774    cookies.push_back(kGetAuthCodeCookieNoSecure);
775    cookies.push_back(kGetAuthCodeCookieNoHttpOnly);
776    cookies.push_back(kGetAuthCodeCookieNoOAuthCode);
777    cookies.push_back(kGetAuthCodeValidCookie);
778    EXPECT_TRUE(GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
779        cookies, &auth_code));
780    EXPECT_EQ("test-code", auth_code);
781  }
782  {  // Single valid cookie (like in real responses).
783    std::string auth_code;
784    net::ResponseCookies cookies;
785    cookies.push_back(kGetAuthCodeValidCookie);
786    EXPECT_TRUE(GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
787        cookies, &auth_code));
788    EXPECT_EQ("test-code", auth_code);
789  }
790}
791
792TEST_F(GaiaAuthFetcherTest, StartOAuthLogin) {
793  // OAuthLogin returns the same as the ClientLogin endpoint, minus CAPTCHA
794  // responses.
795  std::string data("SID=sid\nLSID=lsid\nAuth=auth\n");
796
797  GaiaAuthConsumer::ClientLoginResult result;
798  result.lsid = "lsid";
799  result.sid = "sid";
800  result.token = "auth";
801  result.data = data;
802
803  MockGaiaConsumer consumer;
804  EXPECT_CALL(consumer, OnClientLoginSuccess(result))
805      .Times(1);
806
807  GaiaAuthFetcher auth(&consumer, std::string(),
808      profile_.GetRequestContext());
809  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
810  MockFetcher mock_fetcher(
811      oauth_login_gurl_, status, net::HTTP_OK, cookies_, data,
812      net::URLFetcher::GET, &auth);
813  auth.OnURLFetchComplete(&mock_fetcher);
814}
815