http_auth_controller_unittest.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. #include "net/http/http_auth_controller.h"
  5. #include <algorithm>
  6. #include <utility>
  7. #include "base/strings/utf_string_conversions.h"
  8. #include "base/test/task_environment.h"
  9. #include "net/base/net_errors.h"
  10. #include "net/base/test_completion_callback.h"
  11. #include "net/dns/mock_host_resolver.h"
  12. #include "net/http/http_auth_cache.h"
  13. #include "net/http/http_auth_challenge_tokenizer.h"
  14. #include "net/http/http_auth_handler_mock.h"
  15. #include "net/http/http_request_info.h"
  16. #include "net/http/http_response_headers.h"
  17. #include "net/http/http_util.h"
  18. #include "net/log/net_log_event_type.h"
  19. #include "net/log/net_log_with_source.h"
  20. #include "net/log/test_net_log.h"
  21. #include "net/log/test_net_log_util.h"
  22. #include "net/ssl/ssl_info.h"
  23. #include "testing/gtest/include/gtest/gtest.h"
  24. namespace net {
  25. namespace {
  26. enum HandlerRunMode {
  27. RUN_HANDLER_SYNC,
  28. RUN_HANDLER_ASYNC
  29. };
  30. enum SchemeState {
  31. SCHEME_IS_DISABLED,
  32. SCHEME_IS_ENABLED
  33. };
  34. scoped_refptr<HttpResponseHeaders> HeadersFromString(const char* string) {
  35. return base::MakeRefCounted<HttpResponseHeaders>(
  36. HttpUtil::AssembleRawHeaders(string));
  37. }
  38. // Runs an HttpAuthController with a single round mock auth handler
  39. // that returns |handler_rv| on token generation. The handler runs in
  40. // async if |run_mode| is RUN_HANDLER_ASYNC. Upon completion, the
  41. // return value of the controller is tested against
  42. // |expected_controller_rv|. |scheme_state| indicates whether the
  43. // auth scheme used should be disabled after this run.
  44. void RunSingleRoundAuthTest(
  45. HandlerRunMode run_mode,
  46. int handler_rv,
  47. int expected_controller_rv,
  48. SchemeState scheme_state,
  49. const NetLogWithSource& net_log = NetLogWithSource()) {
  50. HttpAuthCache dummy_auth_cache(
  51. false /* key_server_entries_by_network_isolation_key */);
  52. HttpRequestInfo request;
  53. request.method = "GET";
  54. request.url = GURL("http://example.com");
  55. scoped_refptr<HttpResponseHeaders> headers(HeadersFromString(
  56. "HTTP/1.1 407\r\n"
  57. "Proxy-Authenticate: MOCK foo\r\n"
  58. "\r\n"));
  59. HttpAuthHandlerMock::Factory auth_handler_factory;
  60. auto auth_handler = std::make_unique<HttpAuthHandlerMock>();
  61. auth_handler->SetGenerateExpectation((run_mode == RUN_HANDLER_ASYNC),
  62. handler_rv);
  63. auth_handler_factory.AddMockHandler(std::move(auth_handler),
  64. HttpAuth::AUTH_PROXY);
  65. auth_handler_factory.set_do_init_from_challenge(true);
  66. auto host_resolver = std::make_unique<MockHostResolver>();
  67. scoped_refptr<HttpAuthController> controller(
  68. base::MakeRefCounted<HttpAuthController>(
  69. HttpAuth::AUTH_PROXY, GURL("http://example.com"),
  70. NetworkIsolationKey(), &dummy_auth_cache, &auth_handler_factory,
  71. host_resolver.get()));
  72. SSLInfo null_ssl_info;
  73. ASSERT_EQ(OK, controller->HandleAuthChallenge(headers, null_ssl_info, false,
  74. false, net_log));
  75. ASSERT_TRUE(controller->HaveAuthHandler());
  76. controller->ResetAuth(AuthCredentials());
  77. EXPECT_TRUE(controller->HaveAuth());
  78. TestCompletionCallback callback;
  79. EXPECT_EQ(
  80. (run_mode == RUN_HANDLER_ASYNC) ? ERR_IO_PENDING : expected_controller_rv,
  81. controller->MaybeGenerateAuthToken(&request, callback.callback(),
  82. net_log));
  83. if (run_mode == RUN_HANDLER_ASYNC)
  84. EXPECT_EQ(expected_controller_rv, callback.WaitForResult());
  85. EXPECT_EQ((scheme_state == SCHEME_IS_DISABLED),
  86. controller->IsAuthSchemeDisabled(HttpAuth::AUTH_SCHEME_MOCK));
  87. }
  88. } // namespace
  89. // If an HttpAuthHandler returns an error code that indicates a
  90. // permanent error, the HttpAuthController should disable the scheme
  91. // used and retry the request.
  92. TEST(HttpAuthControllerTest, PermanentErrors) {
  93. base::test::TaskEnvironment task_environment;
  94. // Run a synchronous handler that returns
  95. // ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS. We expect a return value
  96. // of OK from the controller so we can retry the request.
  97. RunSingleRoundAuthTest(RUN_HANDLER_SYNC,
  98. ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS, OK,
  99. SCHEME_IS_DISABLED);
  100. // Now try an async handler that returns
  101. // ERR_MISSING_AUTH_CREDENTIALS. Async and sync handlers invoke
  102. // different code paths in HttpAuthController when generating
  103. // tokens.
  104. RunSingleRoundAuthTest(RUN_HANDLER_ASYNC, ERR_MISSING_AUTH_CREDENTIALS, OK,
  105. SCHEME_IS_DISABLED);
  106. // If a non-permanent error is returned by the handler, then the
  107. // controller should report it unchanged.
  108. RunSingleRoundAuthTest(RUN_HANDLER_ASYNC, ERR_UNEXPECTED, ERR_UNEXPECTED,
  109. SCHEME_IS_ENABLED);
  110. // ERR_INVALID_AUTH_CREDENTIALS is special. It's a non-permanet error, but
  111. // the error isn't propagated, nor is the auth scheme disabled. This allows
  112. // the scheme to re-attempt the authentication attempt using a different set
  113. // of credentials.
  114. RunSingleRoundAuthTest(RUN_HANDLER_ASYNC, ERR_INVALID_AUTH_CREDENTIALS, OK,
  115. SCHEME_IS_ENABLED);
  116. }
  117. // Verify that the controller logs appropriate lifetime events.
  118. TEST(HttpAuthControllerTest, Logging) {
  119. base::test::TaskEnvironment task_environment;
  120. RecordingNetLogObserver net_log_observer;
  121. RunSingleRoundAuthTest(RUN_HANDLER_SYNC, OK, OK, SCHEME_IS_ENABLED,
  122. NetLogWithSource::Make(NetLogSourceType::NONE));
  123. auto entries = net_log_observer.GetEntries();
  124. // There should be at least two events.
  125. ASSERT_GE(entries.size(), 2u);
  126. auto begin = std::find_if(
  127. entries.begin(), entries.end(), [](const NetLogEntry& e) -> bool {
  128. if (e.type != NetLogEventType::AUTH_CONTROLLER ||
  129. e.phase != NetLogEventPhase::BEGIN)
  130. return false;
  131. auto target = GetOptionalStringValueFromParams(e, "target");
  132. auto url = GetOptionalStringValueFromParams(e, "url");
  133. if (!target || !url)
  134. return false;
  135. EXPECT_EQ("proxy", *target);
  136. EXPECT_EQ("http://example.com/", *url);
  137. return true;
  138. });
  139. EXPECT_TRUE(begin != entries.end());
  140. auto end = std::find_if(++begin, entries.end(),
  141. [](const NetLogEntry& e) -> bool {
  142. return e.type == NetLogEventType::AUTH_CONTROLLER &&
  143. e.phase == NetLogEventPhase::END;
  144. });
  145. EXPECT_TRUE(end != entries.end());
  146. }
  147. // If an HttpAuthHandler indicates that it doesn't allow explicit
  148. // credentials, don't prompt for credentials.
  149. TEST(HttpAuthControllerTest, NoExplicitCredentialsAllowed) {
  150. // Modified mock HttpAuthHandler for this test.
  151. class MockHandler : public HttpAuthHandlerMock {
  152. public:
  153. MockHandler(int expected_rv, HttpAuth::Scheme scheme)
  154. : expected_scheme_(scheme) {
  155. SetGenerateExpectation(false, expected_rv);
  156. }
  157. protected:
  158. bool Init(HttpAuthChallengeTokenizer* challenge,
  159. const SSLInfo& ssl_info,
  160. const NetworkIsolationKey& network_isolation_key) override {
  161. HttpAuthHandlerMock::Init(challenge, ssl_info, network_isolation_key);
  162. set_allows_default_credentials(true);
  163. set_allows_explicit_credentials(false);
  164. set_connection_based(true);
  165. // Pretend to be SCHEME_BASIC so we can test failover logic.
  166. if (challenge->auth_scheme() == "basic") {
  167. auth_scheme_ = HttpAuth::AUTH_SCHEME_BASIC;
  168. --score_; // Reduce score, so we rank below Mock.
  169. set_allows_explicit_credentials(true);
  170. }
  171. EXPECT_EQ(expected_scheme_, auth_scheme_);
  172. return true;
  173. }
  174. int GenerateAuthTokenImpl(const AuthCredentials* credentials,
  175. const HttpRequestInfo* request,
  176. CompletionOnceCallback callback,
  177. std::string* auth_token) override {
  178. int result = HttpAuthHandlerMock::GenerateAuthTokenImpl(
  179. credentials, request, std::move(callback), auth_token);
  180. EXPECT_TRUE(result != OK ||
  181. !AllowsExplicitCredentials() ||
  182. !credentials->Empty());
  183. return result;
  184. }
  185. private:
  186. HttpAuth::Scheme expected_scheme_;
  187. };
  188. NetLogWithSource dummy_log;
  189. HttpAuthCache dummy_auth_cache(
  190. false /* key_server_entries_by_network_isolation_key */);
  191. HttpRequestInfo request;
  192. request.method = "GET";
  193. request.url = GURL("http://example.com");
  194. HttpRequestHeaders request_headers;
  195. scoped_refptr<HttpResponseHeaders> headers(HeadersFromString(
  196. "HTTP/1.1 401\r\n"
  197. "WWW-Authenticate: Mock\r\n"
  198. "WWW-Authenticate: Basic\r\n"
  199. "\r\n"));
  200. HttpAuthHandlerMock::Factory auth_handler_factory;
  201. // Handlers for the first attempt at authentication. AUTH_SCHEME_MOCK handler
  202. // accepts the default identity and successfully constructs a token.
  203. auth_handler_factory.AddMockHandler(
  204. std::make_unique<MockHandler>(OK, HttpAuth::AUTH_SCHEME_MOCK),
  205. HttpAuth::AUTH_SERVER);
  206. auth_handler_factory.AddMockHandler(
  207. std::make_unique<MockHandler>(ERR_UNEXPECTED,
  208. HttpAuth::AUTH_SCHEME_BASIC),
  209. HttpAuth::AUTH_SERVER);
  210. // Handlers for the second attempt. Neither should be used to generate a
  211. // token. Instead the controller should realize that there are no viable
  212. // identities to use with the AUTH_SCHEME_MOCK handler and fail.
  213. auth_handler_factory.AddMockHandler(
  214. std::make_unique<MockHandler>(ERR_UNEXPECTED, HttpAuth::AUTH_SCHEME_MOCK),
  215. HttpAuth::AUTH_SERVER);
  216. auth_handler_factory.AddMockHandler(
  217. std::make_unique<MockHandler>(ERR_UNEXPECTED,
  218. HttpAuth::AUTH_SCHEME_BASIC),
  219. HttpAuth::AUTH_SERVER);
  220. // Fallback handlers for the second attempt. The AUTH_SCHEME_MOCK handler
  221. // should be discarded due to the disabled scheme, and the AUTH_SCHEME_BASIC
  222. // handler should successfully be used to generate a token.
  223. auth_handler_factory.AddMockHandler(
  224. std::make_unique<MockHandler>(ERR_UNEXPECTED, HttpAuth::AUTH_SCHEME_MOCK),
  225. HttpAuth::AUTH_SERVER);
  226. auth_handler_factory.AddMockHandler(
  227. std::make_unique<MockHandler>(OK, HttpAuth::AUTH_SCHEME_BASIC),
  228. HttpAuth::AUTH_SERVER);
  229. auth_handler_factory.set_do_init_from_challenge(true);
  230. auto host_resolver = std::make_unique<MockHostResolver>();
  231. scoped_refptr<HttpAuthController> controller(
  232. base::MakeRefCounted<HttpAuthController>(
  233. HttpAuth::AUTH_SERVER, GURL("http://example.com"),
  234. NetworkIsolationKey(), &dummy_auth_cache, &auth_handler_factory,
  235. host_resolver.get()));
  236. SSLInfo null_ssl_info;
  237. ASSERT_EQ(OK, controller->HandleAuthChallenge(headers, null_ssl_info, false,
  238. false, dummy_log));
  239. ASSERT_TRUE(controller->HaveAuthHandler());
  240. controller->ResetAuth(AuthCredentials());
  241. EXPECT_TRUE(controller->HaveAuth());
  242. // Should only succeed if we are using the AUTH_SCHEME_MOCK MockHandler.
  243. EXPECT_EQ(OK, controller->MaybeGenerateAuthToken(
  244. &request, CompletionOnceCallback(), dummy_log));
  245. controller->AddAuthorizationHeader(&request_headers);
  246. // Once a token is generated, simulate the receipt of a server response
  247. // indicating that the authentication attempt was rejected.
  248. ASSERT_EQ(OK, controller->HandleAuthChallenge(headers, null_ssl_info, false,
  249. false, dummy_log));
  250. ASSERT_TRUE(controller->HaveAuthHandler());
  251. controller->ResetAuth(AuthCredentials(u"Hello", std::u16string()));
  252. EXPECT_TRUE(controller->HaveAuth());
  253. EXPECT_TRUE(controller->IsAuthSchemeDisabled(HttpAuth::AUTH_SCHEME_MOCK));
  254. EXPECT_FALSE(controller->IsAuthSchemeDisabled(HttpAuth::AUTH_SCHEME_BASIC));
  255. // Should only succeed if we are using the AUTH_SCHEME_BASIC MockHandler.
  256. EXPECT_EQ(OK, controller->MaybeGenerateAuthToken(
  257. &request, CompletionOnceCallback(), dummy_log));
  258. }
  259. } // namespace net