Home | History | Annotate | Download | only in http
      1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "net/http/http_auth_controller.h"
      6 
      7 #include "base/strings/utf_string_conversions.h"
      8 #include "net/base/net_errors.h"
      9 #include "net/base/net_log.h"
     10 #include "net/base/test_completion_callback.h"
     11 #include "net/http/http_auth_cache.h"
     12 #include "net/http/http_auth_handler_mock.h"
     13 #include "net/http/http_request_info.h"
     14 #include "net/http/http_response_headers.h"
     15 #include "net/http/http_util.h"
     16 #include "testing/gtest/include/gtest/gtest.h"
     17 
     18 namespace net {
     19 
     20 namespace {
     21 
     22 enum HandlerRunMode {
     23   RUN_HANDLER_SYNC,
     24   RUN_HANDLER_ASYNC
     25 };
     26 
     27 enum SchemeState {
     28   SCHEME_IS_DISABLED,
     29   SCHEME_IS_ENABLED
     30 };
     31 
     32 scoped_refptr<HttpResponseHeaders> HeadersFromString(const char* string) {
     33   std::string raw_string(string);
     34   std::string headers_string = HttpUtil::AssembleRawHeaders(
     35       raw_string.c_str(), raw_string.length());
     36   scoped_refptr<HttpResponseHeaders> headers(
     37       new HttpResponseHeaders(headers_string));
     38   return headers;
     39 }
     40 
     41 // Runs an HttpAuthController with a single round mock auth handler
     42 // that returns |handler_rv| on token generation.  The handler runs in
     43 // async if |run_mode| is RUN_HANDLER_ASYNC.  Upon completion, the
     44 // return value of the controller is tested against
     45 // |expected_controller_rv|.  |scheme_state| indicates whether the
     46 // auth scheme used should be disabled after this run.
     47 void RunSingleRoundAuthTest(HandlerRunMode run_mode,
     48                             int handler_rv,
     49                             int expected_controller_rv,
     50                             SchemeState scheme_state) {
     51   BoundNetLog dummy_log;
     52   HttpAuthCache dummy_auth_cache;
     53 
     54   HttpRequestInfo request;
     55   request.method = "GET";
     56   request.url = GURL("http://example.com");
     57 
     58   scoped_refptr<HttpResponseHeaders> headers(HeadersFromString(
     59       "HTTP/1.1 407\r\n"
     60       "Proxy-Authenticate: MOCK foo\r\n"
     61       "\r\n"));
     62 
     63   HttpAuthHandlerMock::Factory auth_handler_factory;
     64   HttpAuthHandlerMock* auth_handler = new HttpAuthHandlerMock();
     65   auth_handler->SetGenerateExpectation((run_mode == RUN_HANDLER_ASYNC),
     66                                        handler_rv);
     67   auth_handler_factory.AddMockHandler(auth_handler, HttpAuth::AUTH_PROXY);
     68   auth_handler_factory.set_do_init_from_challenge(true);
     69 
     70   scoped_refptr<HttpAuthController> controller(
     71       new HttpAuthController(HttpAuth::AUTH_PROXY,
     72                              GURL("http://example.com"),
     73                              &dummy_auth_cache, &auth_handler_factory));
     74   ASSERT_EQ(OK,
     75             controller->HandleAuthChallenge(headers, false, false, dummy_log));
     76   ASSERT_TRUE(controller->HaveAuthHandler());
     77   controller->ResetAuth(AuthCredentials());
     78   EXPECT_TRUE(controller->HaveAuth());
     79 
     80   TestCompletionCallback callback;
     81   EXPECT_EQ((run_mode == RUN_HANDLER_ASYNC)? ERR_IO_PENDING:
     82             expected_controller_rv,
     83             controller->MaybeGenerateAuthToken(&request, callback.callback(),
     84                                                dummy_log));
     85   if (run_mode == RUN_HANDLER_ASYNC)
     86     EXPECT_EQ(expected_controller_rv, callback.WaitForResult());
     87   EXPECT_EQ((scheme_state == SCHEME_IS_DISABLED),
     88             controller->IsAuthSchemeDisabled(HttpAuth::AUTH_SCHEME_MOCK));
     89 }
     90 
     91 }  // namespace
     92 
     93 // If an HttpAuthHandler returns an error code that indicates a
     94 // permanent error, the HttpAuthController should disable the scheme
     95 // used and retry the request.
     96 TEST(HttpAuthControllerTest, PermanentErrors) {
     97 
     98   // Run a synchronous handler that returns
     99   // ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS.  We expect a return value
    100   // of OK from the controller so we can retry the request.
    101   RunSingleRoundAuthTest(RUN_HANDLER_SYNC,
    102                          ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS,
    103                          OK, SCHEME_IS_DISABLED);
    104 
    105   // Now try an async handler that returns
    106   // ERR_MISSING_AUTH_CREDENTIALS.  Async and sync handlers invoke
    107   // different code paths in HttpAuthController when generating
    108   // tokens.
    109   RunSingleRoundAuthTest(RUN_HANDLER_ASYNC, ERR_MISSING_AUTH_CREDENTIALS, OK,
    110                          SCHEME_IS_DISABLED);
    111 
    112   // If a non-permanent error is returned by the handler, then the
    113   // controller should report it unchanged.
    114   RunSingleRoundAuthTest(RUN_HANDLER_ASYNC, ERR_INVALID_AUTH_CREDENTIALS,
    115                          ERR_INVALID_AUTH_CREDENTIALS, SCHEME_IS_ENABLED);
    116 }
    117 
    118 // If an HttpAuthHandler indicates that it doesn't allow explicit
    119 // credentials, don't prompt for credentials.
    120 TEST(HttpAuthControllerTest, NoExplicitCredentialsAllowed) {
    121   // Modified mock HttpAuthHandler for this test.
    122   class MockHandler : public HttpAuthHandlerMock {
    123    public:
    124     MockHandler(int expected_rv, HttpAuth::Scheme scheme)
    125         : expected_scheme_(scheme) {
    126       SetGenerateExpectation(false, expected_rv);
    127     }
    128 
    129    protected:
    130     virtual bool Init(HttpAuth::ChallengeTokenizer* challenge) OVERRIDE {
    131       HttpAuthHandlerMock::Init(challenge);
    132       set_allows_default_credentials(true);
    133       set_allows_explicit_credentials(false);
    134       set_connection_based(true);
    135       // Pretend to be SCHEME_BASIC so we can test failover logic.
    136       if (challenge->scheme() == "Basic") {
    137         auth_scheme_ = HttpAuth::AUTH_SCHEME_BASIC;
    138         --score_;  // Reduce score, so we rank below Mock.
    139         set_allows_explicit_credentials(true);
    140       }
    141       EXPECT_EQ(expected_scheme_, auth_scheme_);
    142       return true;
    143     }
    144 
    145     virtual int GenerateAuthTokenImpl(const AuthCredentials* credentials,
    146                                       const HttpRequestInfo* request,
    147                                       const CompletionCallback& callback,
    148                                       std::string* auth_token) OVERRIDE {
    149       int result =
    150           HttpAuthHandlerMock::GenerateAuthTokenImpl(credentials,
    151                                                      request, callback,
    152                                                      auth_token);
    153       EXPECT_TRUE(result != OK ||
    154                   !AllowsExplicitCredentials() ||
    155                   !credentials->Empty());
    156       return result;
    157     }
    158 
    159    private:
    160     HttpAuth::Scheme expected_scheme_;
    161   };
    162 
    163   BoundNetLog dummy_log;
    164   HttpAuthCache dummy_auth_cache;
    165   HttpRequestInfo request;
    166   request.method = "GET";
    167   request.url = GURL("http://example.com");
    168 
    169   HttpRequestHeaders request_headers;
    170   scoped_refptr<HttpResponseHeaders> headers(HeadersFromString(
    171       "HTTP/1.1 401\r\n"
    172       "WWW-Authenticate: Mock\r\n"
    173       "WWW-Authenticate: Basic\r\n"
    174       "\r\n"));
    175 
    176   HttpAuthHandlerMock::Factory auth_handler_factory;
    177 
    178   // Handlers for the first attempt at authentication.  AUTH_SCHEME_MOCK handler
    179   // accepts the default identity and successfully constructs a token.
    180   auth_handler_factory.AddMockHandler(
    181       new MockHandler(OK, HttpAuth::AUTH_SCHEME_MOCK), HttpAuth::AUTH_SERVER);
    182   auth_handler_factory.AddMockHandler(
    183       new MockHandler(ERR_UNEXPECTED, HttpAuth::AUTH_SCHEME_BASIC),
    184       HttpAuth::AUTH_SERVER);
    185 
    186   // Handlers for the second attempt.  Neither should be used to generate a
    187   // token.  Instead the controller should realize that there are no viable
    188   // identities to use with the AUTH_SCHEME_MOCK handler and fail.
    189   auth_handler_factory.AddMockHandler(
    190       new MockHandler(ERR_UNEXPECTED, HttpAuth::AUTH_SCHEME_MOCK),
    191       HttpAuth::AUTH_SERVER);
    192   auth_handler_factory.AddMockHandler(
    193       new MockHandler(ERR_UNEXPECTED, HttpAuth::AUTH_SCHEME_BASIC),
    194       HttpAuth::AUTH_SERVER);
    195 
    196   // Fallback handlers for the second attempt.  The AUTH_SCHEME_MOCK handler
    197   // should be discarded due to the disabled scheme, and the AUTH_SCHEME_BASIC
    198   // handler should successfully be used to generate a token.
    199   auth_handler_factory.AddMockHandler(
    200       new MockHandler(ERR_UNEXPECTED, HttpAuth::AUTH_SCHEME_MOCK),
    201       HttpAuth::AUTH_SERVER);
    202   auth_handler_factory.AddMockHandler(
    203       new MockHandler(OK, HttpAuth::AUTH_SCHEME_BASIC),
    204       HttpAuth::AUTH_SERVER);
    205   auth_handler_factory.set_do_init_from_challenge(true);
    206 
    207   scoped_refptr<HttpAuthController> controller(
    208       new HttpAuthController(HttpAuth::AUTH_SERVER,
    209                              GURL("http://example.com"),
    210                              &dummy_auth_cache, &auth_handler_factory));
    211   ASSERT_EQ(OK,
    212             controller->HandleAuthChallenge(headers, false, false, dummy_log));
    213   ASSERT_TRUE(controller->HaveAuthHandler());
    214   controller->ResetAuth(AuthCredentials());
    215   EXPECT_TRUE(controller->HaveAuth());
    216 
    217   // Should only succeed if we are using the AUTH_SCHEME_MOCK MockHandler.
    218   EXPECT_EQ(OK, controller->MaybeGenerateAuthToken(
    219       &request, CompletionCallback(), dummy_log));
    220   controller->AddAuthorizationHeader(&request_headers);
    221 
    222   // Once a token is generated, simulate the receipt of a server response
    223   // indicating that the authentication attempt was rejected.
    224   ASSERT_EQ(OK,
    225             controller->HandleAuthChallenge(headers, false, false, dummy_log));
    226   ASSERT_TRUE(controller->HaveAuthHandler());
    227   controller->ResetAuth(AuthCredentials(ASCIIToUTF16("Hello"),
    228                         base::string16()));
    229   EXPECT_TRUE(controller->HaveAuth());
    230   EXPECT_TRUE(controller->IsAuthSchemeDisabled(HttpAuth::AUTH_SCHEME_MOCK));
    231   EXPECT_FALSE(controller->IsAuthSchemeDisabled(HttpAuth::AUTH_SCHEME_BASIC));
    232 
    233   // Should only succeed if we are using the AUTH_SCHEME_BASIC MockHandler.
    234   EXPECT_EQ(OK, controller->MaybeGenerateAuthToken(
    235       &request, CompletionCallback(), dummy_log));
    236 }
    237 
    238 }  // namespace net
    239