http_auth_controller.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. #ifndef NET_HTTP_HTTP_AUTH_CONTROLLER_H_
  5. #define NET_HTTP_HTTP_AUTH_CONTROLLER_H_
  6. #include <memory>
  7. #include <set>
  8. #include <string>
  9. #include "base/memory/raw_ptr.h"
  10. #include "base/memory/ref_counted.h"
  11. #include "base/threading/thread_checker.h"
  12. #include "net/base/completion_once_callback.h"
  13. #include "net/base/net_export.h"
  14. #include "net/base/network_isolation_key.h"
  15. #include "net/http/http_auth.h"
  16. #include "net/http/http_auth_preferences.h"
  17. #include "net/log/net_log_with_source.h"
  18. #include "third_party/abseil-cpp/absl/types/optional.h"
  19. #include "url/gurl.h"
  20. #include "url/scheme_host_port.h"
  21. namespace net {
  22. class AuthChallengeInfo;
  23. class AuthCredentials;
  24. class HttpAuthHandler;
  25. class HttpAuthHandlerFactory;
  26. class HttpAuthCache;
  27. class HttpRequestHeaders;
  28. class HostResolver;
  29. class NetLogWithSource;
  30. struct HttpRequestInfo;
  31. class SSLInfo;
  32. // HttpAuthController is the main entry point for external callers into the HTTP
  33. // authentication stack. A single instance of an HttpAuthController can be used
  34. // to handle authentication to a single "target", where "target" is a HTTP
  35. // server or a proxy. During its lifetime, the HttpAuthController can make use
  36. // of multiple authentication handlers (implemented as HttpAuthHandler
  37. // subclasses), and respond to multiple challenges.
  38. //
  39. // Individual HTTP authentication schemes can have additional requirements other
  40. // than what's prescribed in RFC 7235. See HandleAuthChallenge() for details.
  41. class NET_EXPORT_PRIVATE HttpAuthController
  42. : public base::RefCounted<HttpAuthController> {
  43. public:
  44. // Construct a new HttpAuthController.
  45. //
  46. // * |target| is either PROXY or SERVER and determines the authentication
  47. // headers to use ("WWW-Authenticate"/"Authorization" vs.
  48. // "Proxy-Authenticate"/"Proxy-Authorization") and how ambient
  49. // credentials are used.
  50. //
  51. // * |auth_url| specifies the target URL. The origin of the URL identifies the
  52. // target host. The path (hierarchical part defined in RFC 3986 section
  53. // 3.3) of the URL is used by HTTP basic authentication to determine
  54. // cached credentials can be used to preemptively send an authorization
  55. // header. See RFC 7617 section 2.2 (Reusing Credentials) for details.
  56. // If |target| is PROXY, then |auth_url| should have no hierarchical
  57. // part since that is meaningless.
  58. //
  59. // * |network_isolation_key| specifies the NetworkIsolationKey associated with
  60. // the resource load. Depending on settings, credentials may be scoped
  61. // to a single NetworkIsolationKey.
  62. //
  63. // * |http_auth_cache| specifies the credentials cache to use. During
  64. // authentication if explicit (user-provided) credentials are used and
  65. // they can be cached to respond to authentication challenges in the
  66. // future, they are stored in the cache. In addition, the HTTP Digest
  67. // authentication is stateful across requests. So the |http_auth_cache|
  68. // is also used to maintain state for this authentication scheme.
  69. //
  70. // * |http_auth_handler_factory| is used to construct instances of
  71. // HttpAuthHandler subclasses to handle scheme-specific authentication
  72. // logic. The |http_auth_handler_factory| is also responsible for
  73. // determining whether the authentication stack should use a specific
  74. // authentication scheme or not.
  75. //
  76. // * |host_resolver| is used for determining the canonical hostname given a
  77. // possibly non-canonical host name. Name canonicalization is used for
  78. // NTLM and Negotiate HTTP authentication schemes.
  79. //
  80. // * |allow_default_credentials| is used for determining if the current
  81. // context allows ambient authentication using default credentials.
  82. HttpAuthController(HttpAuth::Target target,
  83. const GURL& auth_url,
  84. const NetworkIsolationKey& network_isolation_key,
  85. HttpAuthCache* http_auth_cache,
  86. HttpAuthHandlerFactory* http_auth_handler_factory,
  87. HostResolver* host_resolver);
  88. // Generate an authentication token for |target| if necessary. The return
  89. // value is a net error code. |OK| will be returned both in the case that
  90. // a token is correctly generated synchronously, as well as when no tokens
  91. // were necessary.
  92. int MaybeGenerateAuthToken(const HttpRequestInfo* request,
  93. CompletionOnceCallback callback,
  94. const NetLogWithSource& net_log);
  95. // Adds either the proxy auth header, or the origin server auth header,
  96. // as specified by |target_|.
  97. void AddAuthorizationHeader(HttpRequestHeaders* authorization_headers);
  98. // Checks for and handles HTTP status code 401 or 407.
  99. // |HandleAuthChallenge()| returns OK on success, or a network error code
  100. // otherwise. It may also populate |auth_info_|.
  101. int HandleAuthChallenge(scoped_refptr<HttpResponseHeaders> headers,
  102. const SSLInfo& ssl_info,
  103. bool do_not_send_server_auth,
  104. bool establishing_tunnel,
  105. const NetLogWithSource& net_log);
  106. // Store the supplied credentials and prepare to restart the auth.
  107. void ResetAuth(const AuthCredentials& credentials);
  108. bool HaveAuthHandler() const;
  109. bool HaveAuth() const;
  110. // Return whether the authentication scheme is incompatible with HTTP/2
  111. // and thus the server would presumably reject a request on HTTP/2 anyway.
  112. bool NeedsHTTP11() const;
  113. // Swaps the authentication challenge info into |other|.
  114. void TakeAuthInfo(absl::optional<AuthChallengeInfo>* other);
  115. bool IsAuthSchemeDisabled(HttpAuth::Scheme scheme) const;
  116. void DisableAuthScheme(HttpAuth::Scheme scheme);
  117. void DisableEmbeddedIdentity();
  118. // Called when the connection has been closed, so the current handler (which
  119. // contains state bound to the connection) should be dropped. If retrying on a
  120. // new connection, the next call to MaybeGenerateAuthToken will retry the
  121. // current auth scheme.
  122. void OnConnectionClosed();
  123. private:
  124. // Actions for InvalidateCurrentHandler()
  125. enum InvalidateHandlerAction {
  126. INVALIDATE_HANDLER_AND_CACHED_CREDENTIALS,
  127. INVALIDATE_HANDLER_AND_DISABLE_SCHEME,
  128. INVALIDATE_HANDLER
  129. };
  130. // So that we can mock this object.
  131. friend class base::RefCounted<HttpAuthController>;
  132. ~HttpAuthController();
  133. // If this controller's NetLog hasn't been created yet, creates it and
  134. // associates it with |caller_net_log|. Does nothing after the first
  135. // invocation.
  136. void BindToCallingNetLog(const NetLogWithSource& caller_net_log);
  137. // Searches the auth cache for an entry that encompasses the request's path.
  138. // If such an entry is found, updates |identity_| and |handler_| with the
  139. // cache entry's data and returns true.
  140. bool SelectPreemptiveAuth(const NetLogWithSource& caller_net_log);
  141. // Invalidates the current handler. If |action| is
  142. // INVALIDATE_HANDLER_AND_CACHED_CREDENTIALS, then also invalidate
  143. // the cached credentials used by the handler.
  144. void InvalidateCurrentHandler(InvalidateHandlerAction action);
  145. // Invalidates any auth cache entries after authentication has failed.
  146. // The identity that was rejected is |identity_|.
  147. void InvalidateRejectedAuthFromCache();
  148. // Allows reusing last used identity source. If the authentication handshake
  149. // breaks down halfway, then the controller needs to restart it from the
  150. // beginning and resue the same identity.
  151. void PrepareIdentityForReuse();
  152. // Sets |identity_| to the next identity that the transaction should try. It
  153. // chooses candidates by searching the auth cache and the URL for a
  154. // username:password. Returns true if an identity was found.
  155. bool SelectNextAuthIdentityToTry();
  156. // Populates auth_info_ with the challenge information, so that
  157. // URLRequestHttpJob can prompt for credentials.
  158. void PopulateAuthChallenge();
  159. // Handle the result of calling GenerateAuthToken on an HttpAuthHandler. The
  160. // return value of this function should be used as the return value of the
  161. // GenerateAuthToken operation.
  162. int HandleGenerateTokenResult(int result);
  163. void OnGenerateAuthTokenDone(int result);
  164. // Indicates if this handler is for Proxy auth or Server auth.
  165. HttpAuth::Target target_;
  166. // Holds the {scheme, host, port, path} for the authentication target.
  167. const GURL auth_url_;
  168. // Holds the {scheme, host, port} for the authentication target.
  169. const url::SchemeHostPort auth_scheme_host_port_;
  170. // The absolute path of the resource needing authentication.
  171. // For proxy authentication, the path is empty.
  172. const std::string auth_path_;
  173. // NetworkIsolationKey associated with the request.
  174. const NetworkIsolationKey network_isolation_key_;
  175. // |handler_| encapsulates the logic for the particular auth-scheme.
  176. // This includes the challenge's parameters. If nullptr, then there is no
  177. // associated auth handler.
  178. std::unique_ptr<HttpAuthHandler> handler_;
  179. // |identity_| holds the credentials that should be used by the handler_ to
  180. // generate challenge responses. This identity can come from a number of
  181. // places (url, cache, prompt).
  182. HttpAuth::Identity identity_;
  183. // |auth_token_| contains the opaque string to pass to the proxy or
  184. // server to authenticate the client.
  185. std::string auth_token_;
  186. // Contains information about the auth challenge.
  187. absl::optional<AuthChallengeInfo> auth_info_;
  188. // True if we've used the username:password embedded in the URL. This
  189. // makes sure we use the embedded identity only once for the transaction,
  190. // preventing an infinite auth restart loop.
  191. bool embedded_identity_used_ = false;
  192. // True if default credentials have already been tried for this transaction
  193. // in response to an HTTP authentication challenge.
  194. bool default_credentials_used_ = false;
  195. // These two are owned by the HttpNetworkSession/IOThread, which own the
  196. // objects which reference |this|. Therefore, these raw pointers are valid
  197. // for the lifetime of this object.
  198. const raw_ptr<HttpAuthCache> http_auth_cache_;
  199. const raw_ptr<HttpAuthHandlerFactory> http_auth_handler_factory_;
  200. const raw_ptr<HostResolver> host_resolver_;
  201. std::set<HttpAuth::Scheme> disabled_schemes_;
  202. CompletionOnceCallback callback_;
  203. // NetLog to be used for logging in this controller.
  204. NetLogWithSource net_log_;
  205. THREAD_CHECKER(thread_checker_);
  206. };
  207. } // namespace net
  208. #endif // NET_HTTP_HTTP_AUTH_CONTROLLER_H_