gaia_auth_fetcher_unittest.cc revision 7dbb3d5cf0c15f500944d211057644d6a2f37371
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 "google_apis/gaia/gaia_auth_consumer.h"
15#include "google_apis/gaia/gaia_auth_fetcher.h"
16#include "google_apis/gaia/gaia_urls.h"
17#include "google_apis/gaia/google_service_auth_error.h"
18#include "google_apis/gaia/mock_url_fetcher_factory.h"
19#include "google_apis/google_api_keys.h"
20#include "net/base/load_flags.h"
21#include "net/base/net_errors.h"
22#include "net/http/http_status_code.h"
23#include "net/url_request/test_url_fetcher_factory.h"
24#include "net/url_request/url_fetcher_delegate.h"
25#include "net/url_request/url_request_status.h"
26#include "net/url_request/url_request_test_util.h"
27#include "testing/gmock/include/gmock/gmock.h"
28#include "testing/gtest/include/gtest/gtest.h"
29#include "url/gurl.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
168 protected:
169  net::TestURLRequestContextGetter* GetRequestContext() {
170    if (!request_context_getter_) {
171      request_context_getter_ = new net::TestURLRequestContextGetter(
172          message_loop_.message_loop_proxy());
173    }
174    return request_context_getter_;
175  }
176
177  base::MessageLoop message_loop_;
178  scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_;
179};
180
181class MockGaiaConsumer : public GaiaAuthConsumer {
182 public:
183  MockGaiaConsumer() {}
184  ~MockGaiaConsumer() {}
185
186  MOCK_METHOD1(OnClientLoginSuccess, void(const ClientLoginResult& result));
187  MOCK_METHOD2(OnIssueAuthTokenSuccess, void(const std::string& service,
188      const std::string& token));
189  MOCK_METHOD1(OnClientOAuthSuccess,
190               void(const GaiaAuthConsumer::ClientOAuthResult& result));
191  MOCK_METHOD1(OnMergeSessionSuccess, void(const std::string& data));
192  MOCK_METHOD1(OnUberAuthTokenSuccess, void(const std::string& data));
193  MOCK_METHOD1(OnClientLoginFailure,
194      void(const GoogleServiceAuthError& error));
195  MOCK_METHOD2(OnIssueAuthTokenFailure, void(const std::string& service,
196      const GoogleServiceAuthError& error));
197  MOCK_METHOD1(OnClientOAuthFailure,
198      void(const GoogleServiceAuthError& error));
199  MOCK_METHOD1(OnMergeSessionFailure, void(
200      const GoogleServiceAuthError& error));
201  MOCK_METHOD1(OnUberAuthTokenFailure, void(
202      const GoogleServiceAuthError& error));
203};
204
205#if defined(OS_WIN)
206#define MAYBE_ErrorComparator DISABLED_ErrorComparator
207#else
208#define MAYBE_ErrorComparator ErrorComparator
209#endif
210
211TEST_F(GaiaAuthFetcherTest, MAYBE_ErrorComparator) {
212  GoogleServiceAuthError expected_error =
213      GoogleServiceAuthError::FromConnectionError(-101);
214
215  GoogleServiceAuthError matching_error =
216      GoogleServiceAuthError::FromConnectionError(-101);
217
218  EXPECT_TRUE(expected_error == matching_error);
219
220  expected_error = GoogleServiceAuthError::FromConnectionError(6);
221
222  EXPECT_FALSE(expected_error == matching_error);
223
224  expected_error = GoogleServiceAuthError(GoogleServiceAuthError::NONE);
225
226  EXPECT_FALSE(expected_error == matching_error);
227
228  matching_error = GoogleServiceAuthError(GoogleServiceAuthError::NONE);
229
230  EXPECT_TRUE(expected_error == matching_error);
231}
232
233TEST_F(GaiaAuthFetcherTest, LoginNetFailure) {
234  int error_no = net::ERR_CONNECTION_RESET;
235  net::URLRequestStatus status(net::URLRequestStatus::FAILED, error_no);
236
237  GoogleServiceAuthError expected_error =
238      GoogleServiceAuthError::FromConnectionError(error_no);
239
240  MockGaiaConsumer consumer;
241  EXPECT_CALL(consumer, OnClientLoginFailure(expected_error))
242      .Times(1);
243
244  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
245
246  MockFetcher mock_fetcher(
247      client_login_source_, status, 0, net::ResponseCookies(), std::string(),
248      net::URLFetcher::GET, &auth);
249  auth.OnURLFetchComplete(&mock_fetcher);
250}
251
252TEST_F(GaiaAuthFetcherTest, TokenNetFailure) {
253  int error_no = net::ERR_CONNECTION_RESET;
254  net::URLRequestStatus status(net::URLRequestStatus::FAILED, error_no);
255
256  GoogleServiceAuthError expected_error =
257      GoogleServiceAuthError::FromConnectionError(error_no);
258
259  MockGaiaConsumer consumer;
260  EXPECT_CALL(consumer, OnIssueAuthTokenFailure(_, expected_error))
261      .Times(1);
262
263  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
264
265  MockFetcher mock_fetcher(
266      issue_auth_token_source_, status, 0, cookies_, std::string(),
267      net::URLFetcher::GET, &auth);
268  auth.OnURLFetchComplete(&mock_fetcher);
269}
270
271
272TEST_F(GaiaAuthFetcherTest, LoginDenied) {
273  std::string data("Error=BadAuthentication");
274  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
275
276  GoogleServiceAuthError expected_error(
277      GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
278
279  MockGaiaConsumer consumer;
280  EXPECT_CALL(consumer, OnClientLoginFailure(expected_error))
281      .Times(1);
282
283  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
284
285  MockFetcher mock_fetcher(
286      client_login_source_, status, net::HTTP_FORBIDDEN, cookies_, data,
287      net::URLFetcher::GET, &auth);
288  auth.OnURLFetchComplete(&mock_fetcher);
289}
290
291TEST_F(GaiaAuthFetcherTest, ParseRequest) {
292  RunParsingTest("SID=sid\nLSID=lsid\nAuth=auth\n", "sid", "lsid", "auth");
293  RunParsingTest("LSID=lsid\nSID=sid\nAuth=auth\n", "sid", "lsid", "auth");
294  RunParsingTest("SID=sid\nLSID=lsid\nAuth=auth", "sid", "lsid", "auth");
295  RunParsingTest("SID=sid\nAuth=auth\n", "sid", std::string(), "auth");
296  RunParsingTest("LSID=lsid\nAuth=auth\n", std::string(), "lsid", "auth");
297  RunParsingTest("\nAuth=auth\n", std::string(), std::string(), "auth");
298  RunParsingTest("SID=sid", "sid", std::string(), std::string());
299}
300
301TEST_F(GaiaAuthFetcherTest, ParseErrorRequest) {
302  RunErrorParsingTest("Url=U\n"
303                      "Error=E\n"
304                      "CaptchaToken=T\n"
305                      "CaptchaUrl=C\n", "E", "U", "C", "T");
306  RunErrorParsingTest("CaptchaToken=T\n"
307                      "Error=E\n"
308                      "Url=U\n"
309                      "CaptchaUrl=C\n", "E", "U", "C", "T");
310  RunErrorParsingTest("\n\n\nCaptchaToken=T\n"
311                      "\nError=E\n"
312                      "\nUrl=U\n"
313                      "CaptchaUrl=C\n", "E", "U", "C", "T");
314}
315
316
317TEST_F(GaiaAuthFetcherTest, OnlineLogin) {
318  std::string data("SID=sid\nLSID=lsid\nAuth=auth\n");
319
320  GaiaAuthConsumer::ClientLoginResult result;
321  result.lsid = "lsid";
322  result.sid = "sid";
323  result.token = "auth";
324  result.data = data;
325
326  MockGaiaConsumer consumer;
327  EXPECT_CALL(consumer, OnClientLoginSuccess(result))
328      .Times(1);
329
330  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
331  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
332  MockFetcher mock_fetcher(
333      client_login_source_, status, net::HTTP_OK, cookies_, data,
334      net::URLFetcher::GET, &auth);
335  auth.OnURLFetchComplete(&mock_fetcher);
336}
337
338TEST_F(GaiaAuthFetcherTest, WorkingIssueAuthToken) {
339  MockGaiaConsumer consumer;
340  EXPECT_CALL(consumer, OnIssueAuthTokenSuccess(_, "token"))
341      .Times(1);
342
343  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
344  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
345  MockFetcher mock_fetcher(
346      issue_auth_token_source_, status, net::HTTP_OK, cookies_, "token",
347      net::URLFetcher::GET, &auth);
348  auth.OnURLFetchComplete(&mock_fetcher);
349}
350
351TEST_F(GaiaAuthFetcherTest, CheckTwoFactorResponse) {
352  std::string response =
353      base::StringPrintf("Error=BadAuthentication\n%s\n",
354                         GaiaAuthFetcher::kSecondFactor);
355  EXPECT_TRUE(GaiaAuthFetcher::IsSecondFactorSuccess(response));
356}
357
358TEST_F(GaiaAuthFetcherTest, CheckNormalErrorCode) {
359  std::string response = "Error=BadAuthentication\n";
360  EXPECT_FALSE(GaiaAuthFetcher::IsSecondFactorSuccess(response));
361}
362
363TEST_F(GaiaAuthFetcherTest, TwoFactorLogin) {
364  std::string response = base::StringPrintf("Error=BadAuthentication\n%s\n",
365      GaiaAuthFetcher::kSecondFactor);
366
367  GoogleServiceAuthError error =
368      GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR);
369
370  MockGaiaConsumer consumer;
371  EXPECT_CALL(consumer, OnClientLoginFailure(error))
372      .Times(1);
373
374  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
375  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
376  MockFetcher mock_fetcher(
377      client_login_source_, status, net::HTTP_FORBIDDEN, cookies_, response,
378      net::URLFetcher::GET, &auth);
379  auth.OnURLFetchComplete(&mock_fetcher);
380}
381
382TEST_F(GaiaAuthFetcherTest, CaptchaParse) {
383  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
384  std::string data = "Url=http://www.google.com/login/captcha\n"
385                     "Error=CaptchaRequired\n"
386                     "CaptchaToken=CCTOKEN\n"
387                     "CaptchaUrl=Captcha?ctoken=CCTOKEN\n";
388  GoogleServiceAuthError error =
389      GaiaAuthFetcher::GenerateAuthError(data, status);
390
391  std::string token = "CCTOKEN";
392  GURL image_url("http://accounts.google.com/Captcha?ctoken=CCTOKEN");
393  GURL unlock_url("http://www.google.com/login/captcha");
394
395  EXPECT_EQ(error.state(), GoogleServiceAuthError::CAPTCHA_REQUIRED);
396  EXPECT_EQ(error.captcha().token, token);
397  EXPECT_EQ(error.captcha().image_url, image_url);
398  EXPECT_EQ(error.captcha().unlock_url, unlock_url);
399}
400
401TEST_F(GaiaAuthFetcherTest, AccountDeletedError) {
402  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
403  std::string data = "Error=AccountDeleted\n";
404  GoogleServiceAuthError error =
405      GaiaAuthFetcher::GenerateAuthError(data, status);
406  EXPECT_EQ(error.state(), GoogleServiceAuthError::ACCOUNT_DELETED);
407}
408
409TEST_F(GaiaAuthFetcherTest, AccountDisabledError) {
410  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
411  std::string data = "Error=AccountDisabled\n";
412  GoogleServiceAuthError error =
413      GaiaAuthFetcher::GenerateAuthError(data, status);
414  EXPECT_EQ(error.state(), GoogleServiceAuthError::ACCOUNT_DISABLED);
415}
416
417TEST_F(GaiaAuthFetcherTest,BadAuthenticationError) {
418  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
419  std::string data = "Error=BadAuthentication\n";
420  GoogleServiceAuthError error =
421      GaiaAuthFetcher::GenerateAuthError(data, status);
422  EXPECT_EQ(error.state(), GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
423}
424
425TEST_F(GaiaAuthFetcherTest,IncomprehensibleError) {
426  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
427  std::string data = "Error=Gobbledygook\n";
428  GoogleServiceAuthError error =
429      GaiaAuthFetcher::GenerateAuthError(data, status);
430  EXPECT_EQ(error.state(), GoogleServiceAuthError::SERVICE_UNAVAILABLE);
431}
432
433TEST_F(GaiaAuthFetcherTest,ServiceUnavailableError) {
434  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
435  std::string data = "Error=ServiceUnavailable\n";
436  GoogleServiceAuthError error =
437      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
438  EXPECT_EQ(error.state(), GoogleServiceAuthError::SERVICE_UNAVAILABLE);
439}
440
441TEST_F(GaiaAuthFetcherTest, OAuthAccountDeletedError) {
442  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
443  std::string data = "Error=adel\n";
444  GoogleServiceAuthError error =
445      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
446  EXPECT_EQ(error.state(), GoogleServiceAuthError::ACCOUNT_DELETED);
447}
448
449TEST_F(GaiaAuthFetcherTest, OAuthAccountDisabledError) {
450  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
451  std::string data = "Error=adis\n";
452  GoogleServiceAuthError error =
453      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
454  EXPECT_EQ(error.state(), GoogleServiceAuthError::ACCOUNT_DISABLED);
455}
456
457TEST_F(GaiaAuthFetcherTest, OAuthBadAuthenticationError) {
458  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
459  std::string data = "Error=badauth\n";
460  GoogleServiceAuthError error =
461      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
462  EXPECT_EQ(error.state(), GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
463}
464
465TEST_F(GaiaAuthFetcherTest, OAuthServiceUnavailableError) {
466  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
467  std::string data = "Error=ire\n";
468  GoogleServiceAuthError error =
469      GaiaAuthFetcher::GenerateOAuthLoginError(data, status);
470  EXPECT_EQ(error.state(), GoogleServiceAuthError::SERVICE_UNAVAILABLE);
471}
472
473TEST_F(GaiaAuthFetcherTest, FullLogin) {
474  MockGaiaConsumer consumer;
475  EXPECT_CALL(consumer, OnClientLoginSuccess(_))
476      .Times(1);
477
478  MockURLFetcherFactory<MockFetcher> factory;
479
480  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
481  auth.StartClientLogin("username",
482                        "password",
483                        "service",
484                        std::string(),
485                        std::string(),
486                        GaiaAuthFetcher::HostedAccountsAllowed);
487}
488
489TEST_F(GaiaAuthFetcherTest, FullLoginFailure) {
490  MockGaiaConsumer consumer;
491  EXPECT_CALL(consumer, OnClientLoginFailure(_))
492      .Times(1);
493
494  MockURLFetcherFactory<MockFetcher> factory;
495  factory.set_success(false);
496
497  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
498  auth.StartClientLogin("username",
499                        "password",
500                        "service",
501                        std::string(),
502                        std::string(),
503                        GaiaAuthFetcher::HostedAccountsAllowed);
504}
505
506TEST_F(GaiaAuthFetcherTest, ClientFetchPending) {
507  MockGaiaConsumer consumer;
508  EXPECT_CALL(consumer, OnClientLoginSuccess(_))
509      .Times(1);
510
511  net::TestURLFetcherFactory factory;
512
513  GaiaAuthFetcher auth(&consumer, std::string(), 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(), GetRequestContext());
538  auth.StartIssueAuthToken("sid", "lsid", "service");
539
540  EXPECT_TRUE(auth.HasPendingFetch());
541  MockFetcher mock_fetcher(
542      issue_auth_token_source_,
543      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
544      net::HTTP_OK, cookies_, "token",
545      net::URLFetcher::GET, &auth);
546  auth.OnURLFetchComplete(&mock_fetcher);
547  EXPECT_FALSE(auth.HasPendingFetch());
548}
549
550TEST_F(GaiaAuthFetcherTest, FullTokenFailure) {
551  MockGaiaConsumer consumer;
552  EXPECT_CALL(consumer, OnIssueAuthTokenFailure("service", _))
553      .Times(1);
554
555  net::TestURLFetcherFactory factory;
556
557  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
558  auth.StartIssueAuthToken("sid", "lsid", "service");
559
560  EXPECT_TRUE(auth.HasPendingFetch());
561  MockFetcher mock_fetcher(
562      issue_auth_token_source_,
563      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
564      net::HTTP_FORBIDDEN,
565      cookies_,
566      std::string(),
567      net::URLFetcher::GET,
568      &auth);
569  auth.OnURLFetchComplete(&mock_fetcher);
570  EXPECT_FALSE(auth.HasPendingFetch());
571}
572
573TEST_F(GaiaAuthFetcherTest, OAuthLoginTokenSuccess) {
574  MockGaiaConsumer consumer;
575  EXPECT_CALL(consumer, OnClientOAuthSuccess(
576      GaiaAuthConsumer::ClientOAuthResult("rt1", "at1", 3600))).Times(1);
577
578  net::TestURLFetcherFactory factory;
579  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
580  auth.StartLsoForOAuthLoginTokenExchange("lso_token");
581  net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
582  EXPECT_TRUE(NULL != fetcher);
583  EXPECT_EQ(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES,
584            fetcher->GetLoadFlags());
585
586  net::ResponseCookies cookies;
587  cookies.push_back(kGetAuthCodeValidCookie);
588  EXPECT_TRUE(auth.HasPendingFetch());
589  MockFetcher mock_fetcher1(
590      client_login_to_oauth2_source_,
591      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
592      net::HTTP_OK,
593      cookies,
594      std::string(),
595      net::URLFetcher::POST,
596      &auth);
597  auth.OnURLFetchComplete(&mock_fetcher1);
598  EXPECT_TRUE(auth.HasPendingFetch());
599  MockFetcher mock_fetcher2(
600      oauth2_token_source_,
601      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
602      net::HTTP_OK, cookies_, kGetTokenPairValidResponse,
603      net::URLFetcher::POST, &auth);
604  auth.OnURLFetchComplete(&mock_fetcher2);
605  EXPECT_FALSE(auth.HasPendingFetch());
606}
607
608TEST_F(GaiaAuthFetcherTest, OAuthLoginTokenWithCookies) {
609  MockGaiaConsumer consumer;
610  net::TestURLFetcherFactory factory;
611  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
612  auth.StartCookieForOAuthLoginTokenExchange("0");
613  net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
614  EXPECT_TRUE(NULL != fetcher);
615  EXPECT_EQ(net::LOAD_NORMAL, fetcher->GetLoadFlags());
616}
617
618TEST_F(GaiaAuthFetcherTest, OAuthLoginTokenClientLoginToOAuth2Failure) {
619  MockGaiaConsumer consumer;
620  EXPECT_CALL(consumer, OnClientOAuthFailure(_))
621      .Times(1);
622
623  net::TestURLFetcherFactory factory;
624  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
625  auth.StartLsoForOAuthLoginTokenExchange("lso_token");
626
627  net::ResponseCookies cookies;
628  EXPECT_TRUE(auth.HasPendingFetch());
629  MockFetcher mock_fetcher(
630      client_login_to_oauth2_source_,
631      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
632      net::HTTP_FORBIDDEN,
633      cookies,
634      std::string(),
635      net::URLFetcher::POST,
636      &auth);
637  auth.OnURLFetchComplete(&mock_fetcher);
638  EXPECT_FALSE(auth.HasPendingFetch());
639}
640
641TEST_F(GaiaAuthFetcherTest, OAuthLoginTokenOAuth2TokenPairFailure) {
642  MockGaiaConsumer consumer;
643  EXPECT_CALL(consumer, OnClientOAuthFailure(_))
644      .Times(1);
645
646  net::TestURLFetcherFactory factory;
647  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
648  auth.StartLsoForOAuthLoginTokenExchange("lso_token");
649
650  net::ResponseCookies cookies;
651  cookies.push_back(kGetAuthCodeValidCookie);
652  EXPECT_TRUE(auth.HasPendingFetch());
653  MockFetcher mock_fetcher1(
654      client_login_to_oauth2_source_,
655      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
656      net::HTTP_OK,
657      cookies,
658      std::string(),
659      net::URLFetcher::POST,
660      &auth);
661  auth.OnURLFetchComplete(&mock_fetcher1);
662  EXPECT_TRUE(auth.HasPendingFetch());
663  MockFetcher mock_fetcher2(
664      oauth2_token_source_,
665      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
666      net::HTTP_FORBIDDEN,
667      cookies_,
668      std::string(),
669      net::URLFetcher::POST,
670      &auth);
671  auth.OnURLFetchComplete(&mock_fetcher2);
672  EXPECT_FALSE(auth.HasPendingFetch());
673}
674
675TEST_F(GaiaAuthFetcherTest, MergeSessionSuccess) {
676  MockGaiaConsumer consumer;
677  EXPECT_CALL(consumer, OnMergeSessionSuccess("<html></html>"))
678      .Times(1);
679
680  net::TestURLFetcherFactory factory;
681
682  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
683  auth.StartMergeSession("myubertoken");
684
685  EXPECT_TRUE(auth.HasPendingFetch());
686  MockFetcher mock_fetcher(
687      merge_session_source_,
688      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
689      net::HTTP_OK, cookies_, "<html></html>", net::URLFetcher::GET,
690      &auth);
691  auth.OnURLFetchComplete(&mock_fetcher);
692  EXPECT_FALSE(auth.HasPendingFetch());
693}
694
695TEST_F(GaiaAuthFetcherTest, MergeSessionSuccessRedirect) {
696  MockGaiaConsumer consumer;
697  EXPECT_CALL(consumer, OnMergeSessionSuccess("<html></html>"))
698      .Times(1);
699
700  net::TestURLFetcherFactory factory;
701
702  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
703  auth.StartMergeSession("myubertoken");
704
705  // Make sure the fetcher created has the expected flags.  Set its url()
706  // properties to reflect a redirect.
707  net::TestURLFetcher* test_fetcher = factory.GetFetcherByID(0);
708  EXPECT_TRUE(test_fetcher != NULL);
709  EXPECT_TRUE(test_fetcher->GetLoadFlags() == net::LOAD_NORMAL);
710  EXPECT_TRUE(auth.HasPendingFetch());
711
712  GURL final_url("http://www.google.com/CheckCookie");
713  test_fetcher->set_url(final_url);
714  test_fetcher->set_status(
715      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0));
716  test_fetcher->set_response_code(net::HTTP_OK);
717  test_fetcher->set_cookies(cookies_);
718  test_fetcher->SetResponseString("<html></html>");
719
720  auth.OnURLFetchComplete(test_fetcher);
721  EXPECT_FALSE(auth.HasPendingFetch());
722}
723
724TEST_F(GaiaAuthFetcherTest, UberAuthTokenSuccess) {
725  MockGaiaConsumer consumer;
726  EXPECT_CALL(consumer, OnUberAuthTokenSuccess("uberToken"))
727      .Times(1);
728
729  net::TestURLFetcherFactory factory;
730
731  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
732  auth.StartTokenFetchForUberAuthExchange("myAccessToken");
733
734  EXPECT_TRUE(auth.HasPendingFetch());
735  MockFetcher mock_fetcher(
736      uberauth_token_source_,
737      net::URLRequestStatus(net::URLRequestStatus::SUCCESS, 0),
738      net::HTTP_OK, cookies_, "uberToken", net::URLFetcher::POST,
739      &auth);
740  auth.OnURLFetchComplete(&mock_fetcher);
741  EXPECT_FALSE(auth.HasPendingFetch());
742}
743
744TEST_F(GaiaAuthFetcherTest, ParseClientLoginToOAuth2Response) {
745  {  // No cookies.
746    std::string auth_code;
747    net::ResponseCookies cookies;
748    EXPECT_FALSE(GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
749        cookies, &auth_code));
750    EXPECT_EQ("", auth_code);
751  }
752  {  // Few cookies, nothing appropriate.
753    std::string auth_code;
754    net::ResponseCookies cookies;
755    cookies.push_back(kGetAuthCodeCookieNoSecure);
756    cookies.push_back(kGetAuthCodeCookieNoHttpOnly);
757    cookies.push_back(kGetAuthCodeCookieNoOAuthCode);
758    EXPECT_FALSE(GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
759        cookies, &auth_code));
760    EXPECT_EQ("", auth_code);
761  }
762  {  // Few cookies, one of them is valid.
763    std::string auth_code;
764    net::ResponseCookies cookies;
765    cookies.push_back(kGetAuthCodeCookieNoSecure);
766    cookies.push_back(kGetAuthCodeCookieNoHttpOnly);
767    cookies.push_back(kGetAuthCodeCookieNoOAuthCode);
768    cookies.push_back(kGetAuthCodeValidCookie);
769    EXPECT_TRUE(GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
770        cookies, &auth_code));
771    EXPECT_EQ("test-code", auth_code);
772  }
773  {  // Single valid cookie (like in real responses).
774    std::string auth_code;
775    net::ResponseCookies cookies;
776    cookies.push_back(kGetAuthCodeValidCookie);
777    EXPECT_TRUE(GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
778        cookies, &auth_code));
779    EXPECT_EQ("test-code", auth_code);
780  }
781}
782
783TEST_F(GaiaAuthFetcherTest, StartOAuthLogin) {
784  // OAuthLogin returns the same as the ClientLogin endpoint, minus CAPTCHA
785  // responses.
786  std::string data("SID=sid\nLSID=lsid\nAuth=auth\n");
787
788  GaiaAuthConsumer::ClientLoginResult result;
789  result.lsid = "lsid";
790  result.sid = "sid";
791  result.token = "auth";
792  result.data = data;
793
794  MockGaiaConsumer consumer;
795  EXPECT_CALL(consumer, OnClientLoginSuccess(result))
796      .Times(1);
797
798  GaiaAuthFetcher auth(&consumer, std::string(), GetRequestContext());
799  net::URLRequestStatus status(net::URLRequestStatus::SUCCESS, 0);
800  MockFetcher mock_fetcher(
801      oauth_login_gurl_, status, net::HTTP_OK, cookies_, data,
802      net::URLFetcher::GET, &auth);
803  auth.OnURLFetchComplete(&mock_fetcher);
804}
805