1 // Copyright 2012 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ 6 #define NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ 7 8 #include <stdint.h> 9 #include <stdlib.h> 10 11 #include <map> 12 #include <memory> 13 #include <optional> 14 #include <string> 15 #include <utility> 16 #include <vector> 17 18 #include "base/compiler_specific.h" 19 #include "base/memory/raw_ptr.h" 20 #include "base/memory/scoped_refptr.h" 21 #include "base/path_service.h" 22 #include "base/strings/string_util.h" 23 #include "base/strings/utf_string_conversions.h" 24 #include "base/task/single_thread_task_runner.h" 25 #include "net/base/io_buffer.h" 26 #include "net/base/load_timing_info.h" 27 #include "net/base/net_errors.h" 28 #include "net/base/network_delegate_impl.h" 29 #include "net/base/request_priority.h" 30 #include "net/base/transport_info.h" 31 #include "net/cert/cert_verifier.h" 32 #include "net/cookies/cookie_inclusion_status.h" 33 #include "net/cookies/cookie_monster.h" 34 #include "net/cookies/cookie_setting_override.h" 35 #include "net/cookies/cookie_util.h" 36 #include "net/disk_cache/disk_cache.h" 37 #include "net/first_party_sets/first_party_set_metadata.h" 38 #include "net/http/http_auth_handler_factory.h" 39 #include "net/http/http_cache.h" 40 #include "net/http/http_network_layer.h" 41 #include "net/http/http_network_session.h" 42 #include "net/http/http_request_headers.h" 43 #include "net/ssl/ssl_config_service_defaults.h" 44 #include "net/test/embedded_test_server/default_handlers.h" 45 #include "net/test/embedded_test_server/embedded_test_server.h" 46 #include "net/test/embedded_test_server/embedded_test_server_connection_listener.h" 47 #include "net/url_request/redirect_info.h" 48 #include "net/url_request/url_request.h" 49 #include "net/url_request/url_request_context.h" 50 #include "net/url_request/url_request_context_getter.h" 51 #include "net/url_request/url_request_interceptor.h" 52 #include "url/url_util.h" 53 54 namespace net { 55 56 class URLRequestContextBuilder; 57 58 //----------------------------------------------------------------------------- 59 60 // Creates a URLRequestContextBuilder with some members configured for the 61 // testing purpose. 62 std::unique_ptr<URLRequestContextBuilder> CreateTestURLRequestContextBuilder(); 63 64 //----------------------------------------------------------------------------- 65 // Used to return a dummy context, which lives on the message loop 66 // given in the constructor. 67 class TestURLRequestContextGetter : public URLRequestContextGetter { 68 public: 69 // |network_task_runner| must not be NULL. 70 explicit TestURLRequestContextGetter( 71 const scoped_refptr<base::SingleThreadTaskRunner>& network_task_runner); 72 73 // Use to pass a pre-initialized |context|. 74 TestURLRequestContextGetter( 75 const scoped_refptr<base::SingleThreadTaskRunner>& network_task_runner, 76 std::unique_ptr<URLRequestContext> context); 77 78 // URLRequestContextGetter implementation. 79 URLRequestContext* GetURLRequestContext() override; 80 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner() 81 const override; 82 83 // see NotifyContextShuttingDown() in the base class. 84 void NotifyContextShuttingDown(); 85 86 protected: 87 ~TestURLRequestContextGetter() override; 88 89 private: 90 const scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_; 91 std::unique_ptr<URLRequestContext> context_; 92 bool is_shut_down_ = false; 93 }; 94 95 //----------------------------------------------------------------------------- 96 97 class TestDelegate : public URLRequest::Delegate { 98 public: 99 TestDelegate(); 100 ~TestDelegate() override; 101 102 // Helpers to create a RunLoop, set |on_<event>| from it, then Run() it. 103 void RunUntilComplete(); 104 void RunUntilRedirect(); 105 // Enables quitting the message loop in response to auth requests, as opposed 106 // to returning credentials or cancelling the request. 107 void RunUntilAuthRequired(); 108 109 // Sets the closure to be run on completion, for tests which need more fine- 110 // grained control than RunUntilComplete(). set_on_complete(base::OnceClosure on_complete)111 void set_on_complete(base::OnceClosure on_complete) { 112 on_complete_ = std::move(on_complete); 113 } 114 115 // Sets the result returned by subsequent calls to OnConnected(). set_on_connected_result(int result)116 void set_on_connected_result(int result) { on_connected_result_ = result; } 117 set_cancel_in_received_redirect(bool val)118 void set_cancel_in_received_redirect(bool val) { cancel_in_rr_ = val; } set_cancel_in_response_started(bool val)119 void set_cancel_in_response_started(bool val) { cancel_in_rs_ = val; } set_cancel_in_received_data(bool val)120 void set_cancel_in_received_data(bool val) { cancel_in_rd_ = val; } set_cancel_in_received_data_pending(bool val)121 void set_cancel_in_received_data_pending(bool val) { 122 cancel_in_rd_pending_ = val; 123 } 124 set_allow_certificate_errors(bool val)125 void set_allow_certificate_errors(bool val) { 126 allow_certificate_errors_ = val; 127 } set_credentials(const AuthCredentials & credentials)128 void set_credentials(const AuthCredentials& credentials) { 129 credentials_ = credentials; 130 } 131 132 // If true, the delegate will asynchronously run the callback passed in from 133 // URLRequest with `on_connected_result_` set_on_connected_run_callback(bool run_callback)134 void set_on_connected_run_callback(bool run_callback) { 135 on_connected_run_callback_ = run_callback; 136 } 137 138 // Returns the list of arguments with which OnConnected() was called. 139 // The arguments are listed in the same order as the calls were received. transports()140 const std::vector<TransportInfo>& transports() const { return transports_; } 141 142 // query state data_received()143 const std::string& data_received() const { return data_received_; } bytes_received()144 int bytes_received() const { return static_cast<int>(data_received_.size()); } response_started_count()145 int response_started_count() const { return response_started_count_; } received_bytes_count()146 int received_bytes_count() const { return received_bytes_count_; } received_redirect_count()147 int received_redirect_count() const { return received_redirect_count_; } received_data_before_response()148 bool received_data_before_response() const { 149 return received_data_before_response_; 150 } redirect_info()151 RedirectInfo redirect_info() { return redirect_info_; } request_failed()152 bool request_failed() const { return request_failed_; } have_certificate_errors()153 bool have_certificate_errors() const { return have_certificate_errors_; } certificate_errors_are_fatal()154 bool certificate_errors_are_fatal() const { 155 return certificate_errors_are_fatal_; 156 } certificate_net_error()157 int certificate_net_error() const { return certificate_net_error_; } auth_required_called()158 bool auth_required_called() const { return auth_required_; } response_completed()159 bool response_completed() const { return response_completed_; } request_status()160 int request_status() const { return request_status_; } 161 162 // URLRequest::Delegate: 163 int OnConnected(URLRequest* request, 164 const TransportInfo& info, 165 CompletionOnceCallback callback) override; 166 void OnReceivedRedirect(URLRequest* request, 167 const RedirectInfo& redirect_info, 168 bool* defer_redirect) override; 169 void OnAuthRequired(URLRequest* request, 170 const AuthChallengeInfo& auth_info) override; 171 // NOTE: |fatal| causes |certificate_errors_are_fatal_| to be set to true. 172 // (Unit tests use this as a post-condition.) But for policy, this method 173 // consults |allow_certificate_errors_|. 174 void OnSSLCertificateError(URLRequest* request, 175 int net_error, 176 const SSLInfo& ssl_info, 177 bool fatal) override; 178 void OnResponseStarted(URLRequest* request, int net_error) override; 179 void OnReadCompleted(URLRequest* request, int bytes_read) override; 180 181 private: 182 static const int kBufferSize = 4096; 183 184 virtual void OnResponseCompleted(URLRequest* request); 185 186 // options for controlling behavior 187 int on_connected_result_ = OK; 188 bool cancel_in_rr_ = false; 189 bool cancel_in_rs_ = false; 190 bool cancel_in_rd_ = false; 191 bool cancel_in_rd_pending_ = false; 192 bool allow_certificate_errors_ = false; 193 AuthCredentials credentials_; 194 195 // Used to register RunLoop quit closures, to implement the Until*() closures. 196 base::OnceClosure on_complete_; 197 base::OnceClosure on_redirect_; 198 base::OnceClosure on_auth_required_; 199 200 // tracks status of callbacks 201 std::vector<TransportInfo> transports_; 202 int response_started_count_ = 0; 203 int received_bytes_count_ = 0; 204 int received_redirect_count_ = 0; 205 bool received_data_before_response_ = false; 206 bool request_failed_ = false; 207 bool have_certificate_errors_ = false; 208 bool certificate_errors_are_fatal_ = false; 209 int certificate_net_error_ = 0; 210 bool auth_required_ = false; 211 std::string data_received_; 212 bool response_completed_ = false; 213 214 // tracks status of request 215 int request_status_ = ERR_IO_PENDING; 216 217 // our read buffer 218 scoped_refptr<IOBuffer> buf_; 219 220 RedirectInfo redirect_info_; 221 222 bool on_connected_run_callback_ = false; 223 }; 224 225 //----------------------------------------------------------------------------- 226 227 class TestNetworkDelegate : public NetworkDelegateImpl { 228 public: 229 enum Options { 230 NO_GET_COOKIES = 1 << 0, 231 NO_SET_COOKIE = 1 << 1, 232 }; 233 234 TestNetworkDelegate(); 235 ~TestNetworkDelegate() override; 236 237 // Writes the LoadTimingInfo during the most recent call to OnBeforeRedirect. 238 bool GetLoadTimingInfoBeforeRedirect( 239 LoadTimingInfo* load_timing_info_before_redirect) const; 240 241 // Will redirect once to the given URL when the next set of headers are 242 // received. set_redirect_on_headers_received_url(GURL redirect_on_headers_received_url)243 void set_redirect_on_headers_received_url( 244 GURL redirect_on_headers_received_url) { 245 redirect_on_headers_received_url_ = redirect_on_headers_received_url; 246 } 247 248 // Adds a X-Network-Delegate header to the first OnHeadersReceived call, but 249 // not subsequent ones. set_add_header_to_first_response(bool add_header_to_first_response)250 void set_add_header_to_first_response(bool add_header_to_first_response) { 251 add_header_to_first_response_ = add_header_to_first_response; 252 } 253 set_preserve_fragment_on_redirect_url(const std::optional<GURL> & preserve_fragment_on_redirect_url)254 void set_preserve_fragment_on_redirect_url( 255 const std::optional<GURL>& preserve_fragment_on_redirect_url) { 256 preserve_fragment_on_redirect_url_ = preserve_fragment_on_redirect_url; 257 } 258 set_cookie_options(int o)259 void set_cookie_options(int o) {cookie_options_bit_mask_ = o; } 260 last_error()261 int last_error() const { return last_error_; } error_count()262 int error_count() const { return error_count_; } created_requests()263 int created_requests() const { return created_requests_; } destroyed_requests()264 int destroyed_requests() const { return destroyed_requests_; } completed_requests()265 int completed_requests() const { return completed_requests_; } canceled_requests()266 int canceled_requests() const { return canceled_requests_; } blocked_annotate_cookies_count()267 int blocked_annotate_cookies_count() const { 268 return blocked_annotate_cookies_count_; 269 } blocked_set_cookie_count()270 int blocked_set_cookie_count() const { return blocked_set_cookie_count_; } set_cookie_count()271 int set_cookie_count() const { return set_cookie_count_; } 272 set_cancel_request_with_policy_violating_referrer(bool val)273 void set_cancel_request_with_policy_violating_referrer(bool val) { 274 cancel_request_with_policy_violating_referrer_ = val; 275 } 276 before_start_transaction_count()277 int before_start_transaction_count() const { 278 return before_start_transaction_count_; 279 } 280 headers_received_count()281 int headers_received_count() const { return headers_received_count_; } 282 set_before_start_transaction_fails()283 void set_before_start_transaction_fails() { 284 before_start_transaction_fails_ = true; 285 } 286 cookie_setting_overrides_records()287 const std::vector<CookieSettingOverrides>& cookie_setting_overrides_records() 288 const { 289 return cookie_setting_overrides_records_; 290 } 291 set_storage_access_status(std::optional<cookie_util::StorageAccessStatus> status)292 void set_storage_access_status( 293 std::optional<cookie_util::StorageAccessStatus> status) { 294 storage_access_status_ = status; 295 } 296 set_is_storage_access_header_enabled(bool enabled)297 void set_is_storage_access_header_enabled(bool enabled) { 298 is_storage_access_header_enabled_ = enabled; 299 } 300 301 protected: 302 // NetworkDelegate: 303 int OnBeforeURLRequest(URLRequest* request, 304 CompletionOnceCallback callback, 305 GURL* new_url) override; 306 int OnBeforeStartTransaction( 307 URLRequest* request, 308 const HttpRequestHeaders& headers, 309 OnBeforeStartTransactionCallback callback) override; 310 int OnHeadersReceived( 311 URLRequest* request, 312 CompletionOnceCallback callback, 313 const HttpResponseHeaders* original_response_headers, 314 scoped_refptr<HttpResponseHeaders>* override_response_headers, 315 const IPEndPoint& endpoint, 316 std::optional<GURL>* preserve_fragment_on_redirect_url) override; 317 void OnBeforeRedirect(URLRequest* request, const GURL& new_location) override; 318 void OnBeforeRetry(URLRequest* request) override; 319 void OnResponseStarted(URLRequest* request, int net_error) override; 320 void OnCompleted(URLRequest* request, bool started, int net_error) override; 321 void OnURLRequestDestroyed(URLRequest* request) override; 322 bool OnAnnotateAndMoveUserBlockedCookies( 323 const URLRequest& request, 324 const net::FirstPartySetMetadata& first_party_set_metadata, 325 net::CookieAccessResultList& maybe_included_cookies, 326 net::CookieAccessResultList& excluded_cookies) override; 327 NetworkDelegate::PrivacySetting OnForcePrivacyMode( 328 const URLRequest& request) const override; 329 bool OnCanSetCookie( 330 const URLRequest& request, 331 const net::CanonicalCookie& cookie, 332 CookieOptions* options, 333 const net::FirstPartySetMetadata& first_party_set_metadata, 334 CookieInclusionStatus* inclusion_status) override; 335 bool OnCancelURLRequestWithPolicyViolatingReferrerHeader( 336 const URLRequest& request, 337 const GURL& target_url, 338 const GURL& referrer_url) const override; 339 std::optional<cookie_util::StorageAccessStatus> OnGetStorageAccessStatus( 340 const URLRequest& request, 341 base::optional_ref<const RedirectInfo> redirect_info) const override; 342 bool OnIsStorageAccessHeaderEnabled(const url::Origin* top_frame_origin, 343 const GURL& url) const override; 344 345 void InitRequestStatesIfNew(int request_id); 346 347 // Gets a request ID if it already has one, assigns a new one and returns that 348 // if not. 349 int GetRequestId(URLRequest* request); 350 RecordCookieSettingOverrides(CookieSettingOverrides overrides)351 void RecordCookieSettingOverrides(CookieSettingOverrides overrides) const { 352 cookie_setting_overrides_records_.push_back(overrides); 353 } 354 355 GURL redirect_on_headers_received_url_; 356 // URL to mark as retaining its fragment if redirected to at the 357 // OnHeadersReceived() stage. 358 std::optional<GURL> preserve_fragment_on_redirect_url_; 359 360 int last_error_ = 0; 361 int error_count_ = 0; 362 int created_requests_ = 0; 363 int destroyed_requests_ = 0; 364 int completed_requests_ = 0; 365 int canceled_requests_ = 0; 366 int cookie_options_bit_mask_ = 0; 367 int blocked_annotate_cookies_count_ = 0; 368 int blocked_set_cookie_count_ = 0; 369 int set_cookie_count_ = 0; 370 int before_start_transaction_count_ = 0; 371 int headers_received_count_ = 0; 372 373 // NetworkDelegate callbacks happen in a particular order (e.g. 374 // OnBeforeURLRequest is always called before OnBeforeStartTransaction). 375 // This bit-set indicates for each request id (key) what events may be sent 376 // next. 377 std::map<int, int> next_states_; 378 379 // A log that records for each request id (key) the order in which On... 380 // functions were called. 381 std::map<int, std::string> event_order_; 382 383 LoadTimingInfo load_timing_info_before_redirect_; 384 bool has_load_timing_info_before_redirect_ = false; 385 386 bool cancel_request_with_policy_violating_referrer_ = 387 false; // false by default 388 bool before_start_transaction_fails_ = false; 389 bool add_header_to_first_response_ = false; 390 int next_request_id_ = 0; 391 392 mutable std::vector<CookieSettingOverrides> cookie_setting_overrides_records_; 393 394 std::optional<cookie_util::StorageAccessStatus> storage_access_status_ = 395 std::nullopt; 396 397 bool is_storage_access_header_enabled_ = false; 398 }; 399 400 // ---------------------------------------------------------------------------- 401 402 class FilteringTestNetworkDelegate : public TestNetworkDelegate { 403 public: 404 FilteringTestNetworkDelegate(); 405 ~FilteringTestNetworkDelegate() override; 406 407 bool OnCanSetCookie( 408 const URLRequest& request, 409 const net::CanonicalCookie& cookie, 410 CookieOptions* options, 411 const net::FirstPartySetMetadata& first_party_set_metadata, 412 CookieInclusionStatus* inclusion_status) override; 413 SetCookieFilter(std::string filter)414 void SetCookieFilter(std::string filter) { 415 cookie_name_filter_ = std::move(filter); 416 } 417 set_cookie_called_count()418 int set_cookie_called_count() { return set_cookie_called_count_; } 419 blocked_set_cookie_count()420 int blocked_set_cookie_count() { return blocked_set_cookie_count_; } 421 ResetSetCookieCalledCount()422 void ResetSetCookieCalledCount() { set_cookie_called_count_ = 0; } 423 ResetBlockedSetCookieCount()424 void ResetBlockedSetCookieCount() { blocked_set_cookie_count_ = 0; } 425 426 bool OnAnnotateAndMoveUserBlockedCookies( 427 const URLRequest& request, 428 const net::FirstPartySetMetadata& first_party_set_metadata, 429 net::CookieAccessResultList& maybe_included_cookies, 430 net::CookieAccessResultList& excluded_cookies) override; 431 432 NetworkDelegate::PrivacySetting OnForcePrivacyMode( 433 const URLRequest& request) const override; 434 set_block_annotate_cookies()435 void set_block_annotate_cookies() { block_annotate_cookies_ = true; } 436 unset_block_annotate_cookies()437 void unset_block_annotate_cookies() { block_annotate_cookies_ = false; } 438 annotate_cookies_called_count()439 int annotate_cookies_called_count() const { 440 return annotate_cookies_called_count_; 441 } 442 blocked_annotate_cookies_count()443 int blocked_annotate_cookies_count() const { 444 return blocked_annotate_cookies_count_; 445 } 446 ResetAnnotateCookiesCalledCount()447 void ResetAnnotateCookiesCalledCount() { annotate_cookies_called_count_ = 0; } 448 ResetBlockedAnnotateCookiesCount()449 void ResetBlockedAnnotateCookiesCount() { 450 blocked_annotate_cookies_count_ = 0; 451 } 452 set_block_get_cookies_by_name(bool block)453 void set_block_get_cookies_by_name(bool block) { 454 block_get_cookies_by_name_ = block; 455 } 456 set_force_privacy_mode(bool enabled)457 void set_force_privacy_mode(bool enabled) { force_privacy_mode_ = enabled; } 458 set_partitioned_state_allowed(bool allowed)459 void set_partitioned_state_allowed(bool allowed) { 460 partitioned_state_allowed_ = allowed; 461 } 462 463 private: 464 std::string cookie_name_filter_ = ""; 465 int set_cookie_called_count_ = 0; 466 int blocked_set_cookie_count_ = 0; 467 468 bool block_annotate_cookies_ = false; 469 int annotate_cookies_called_count_ = 0; 470 int blocked_annotate_cookies_count_ = 0; 471 bool block_get_cookies_by_name_ = false; 472 473 bool force_privacy_mode_ = false; 474 bool partitioned_state_allowed_ = false; 475 }; 476 477 // ---------------------------------------------------------------------------- 478 479 // Less verbose way of running a simple testserver. 480 class HttpTestServer : public EmbeddedTestServer { 481 public: HttpTestServer(const base::FilePath & document_root)482 explicit HttpTestServer(const base::FilePath& document_root) { 483 AddDefaultHandlers(document_root); 484 } 485 HttpTestServer()486 HttpTestServer() { RegisterDefaultHandlers(this); } 487 }; 488 //----------------------------------------------------------------------------- 489 490 class TestScopedURLInterceptor { 491 public: 492 // Sets up a URLRequestInterceptor that intercepts a single request for |url|, 493 // returning the provided job. 494 // 495 // On destruction, cleans makes sure the job was removed, and cleans up the 496 // interceptor. Other interceptors for the same URL may not be created until 497 // the interceptor is deleted. 498 TestScopedURLInterceptor(const GURL& url, 499 std::unique_ptr<URLRequestJob> intercept_job); 500 ~TestScopedURLInterceptor(); 501 502 private: 503 class TestRequestInterceptor; 504 505 GURL url_; 506 507 // This is owned by the URLFilter. 508 raw_ptr<TestRequestInterceptor> interceptor_ = nullptr; 509 }; 510 511 } // namespace net 512 513 #endif // NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ 514