• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "net/url_request/url_request_test_util.h"
6 
7 #include <memory>
8 #include <utility>
9 
10 #include "base/check_op.h"
11 #include "base/compiler_specific.h"
12 #include "base/location.h"
13 #include "base/run_loop.h"
14 #include "base/supports_user_data.h"
15 #include "base/task/single_thread_task_runner.h"
16 #include "base/threading/thread.h"
17 #include "net/base/host_port_pair.h"
18 #include "net/cert/cert_verifier.h"
19 #include "net/cert/ct_policy_enforcer.h"
20 #include "net/cert/do_nothing_ct_verifier.h"
21 #include "net/cookies/cookie_setting_override.h"
22 #include "net/dns/mock_host_resolver.h"
23 #include "net/http/http_network_session.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/http/http_server_properties.h"
26 #include "net/http/transport_security_state.h"
27 #include "net/proxy_resolution/configured_proxy_resolution_service.h"
28 #include "net/proxy_resolution/proxy_retry_info.h"
29 #include "net/quic/quic_context.h"
30 #include "net/url_request/static_http_user_agent_settings.h"
31 #include "net/url_request/url_request_context_builder.h"
32 #include "net/url_request/url_request_filter.h"
33 #include "net/url_request/url_request_job.h"
34 #include "net/url_request/url_request_job_factory.h"
35 #include "testing/gtest/include/gtest/gtest.h"
36 
37 namespace net {
38 
39 namespace {
40 
41 // These constants put the NetworkDelegate events of TestNetworkDelegate
42 // into an order. They are used in conjunction with
43 // |TestNetworkDelegate::next_states_| to check that we do not send
44 // events in the wrong order.
45 const int kStageBeforeURLRequest = 1 << 0;
46 const int kStageBeforeStartTransaction = 1 << 1;
47 const int kStageHeadersReceived = 1 << 2;
48 const int kStageBeforeRedirect = 1 << 3;
49 const int kStageResponseStarted = 1 << 4;
50 const int kStageCompletedSuccess = 1 << 5;
51 const int kStageCompletedError = 1 << 6;
52 const int kStageURLRequestDestroyed = 1 << 7;
53 const int kStageDestruction = 1 << 8;
54 
55 const char kTestNetworkDelegateRequestIdKey[] =
56     "TestNetworkDelegateRequestIdKey";
57 
58 class TestRequestId : public base::SupportsUserData::Data {
59  public:
TestRequestId(int id)60   explicit TestRequestId(int id) : id_(id) {}
61   ~TestRequestId() override = default;
62 
id() const63   int id() const { return id_; }
64 
65  private:
66   const int id_;
67 };
68 
69 }  // namespace
70 
CreateTestURLRequestContextBuilder()71 std::unique_ptr<URLRequestContextBuilder> CreateTestURLRequestContextBuilder() {
72   auto builder = std::make_unique<URLRequestContextBuilder>();
73   builder->set_host_resolver(std::make_unique<MockCachingHostResolver>(
74       /*cache_invalidation_num=*/0,
75       /*default_result=*/MockHostResolverBase::RuleResolver::
76           GetLocalhostResult()));
77   builder->set_proxy_resolution_service(
78       ConfiguredProxyResolutionService::CreateDirect());
79   builder->SetCertVerifier(
80       CertVerifier::CreateDefault(/*cert_net_fetcher=*/nullptr));
81   builder->set_ct_policy_enforcer(std::make_unique<DefaultCTPolicyEnforcer>());
82   builder->set_ssl_config_service(std::make_unique<SSLConfigServiceDefaults>());
83   builder->SetHttpAuthHandlerFactory(HttpAuthHandlerFactory::CreateDefault());
84   builder->SetHttpServerProperties(std::make_unique<HttpServerProperties>());
85   builder->set_quic_context(std::make_unique<QuicContext>());
86   builder->SetCookieStore(std::make_unique<CookieMonster>(/*store=*/nullptr,
87                                                           /*netlog=*/nullptr));
88   builder->set_http_user_agent_settings(
89       std::make_unique<StaticHttpUserAgentSettings>("en-us,fr", std::string()));
90   return builder;
91 }
92 
TestURLRequestContextGetter(const scoped_refptr<base::SingleThreadTaskRunner> & network_task_runner)93 TestURLRequestContextGetter::TestURLRequestContextGetter(
94     const scoped_refptr<base::SingleThreadTaskRunner>& network_task_runner)
95     : network_task_runner_(network_task_runner) {
96   DCHECK(network_task_runner_.get());
97 }
98 
TestURLRequestContextGetter(const scoped_refptr<base::SingleThreadTaskRunner> & network_task_runner,std::unique_ptr<URLRequestContext> context)99 TestURLRequestContextGetter::TestURLRequestContextGetter(
100     const scoped_refptr<base::SingleThreadTaskRunner>& network_task_runner,
101     std::unique_ptr<URLRequestContext> context)
102     : network_task_runner_(network_task_runner), context_(std::move(context)) {
103   DCHECK(network_task_runner_.get());
104 }
105 
106 TestURLRequestContextGetter::~TestURLRequestContextGetter() = default;
107 
GetURLRequestContext()108 URLRequestContext* TestURLRequestContextGetter::GetURLRequestContext() {
109   if (is_shut_down_)
110     return nullptr;
111 
112   if (!context_.get())
113     context_ = CreateTestURLRequestContextBuilder()->Build();
114   return context_.get();
115 }
116 
NotifyContextShuttingDown()117 void TestURLRequestContextGetter::NotifyContextShuttingDown() {
118   // This should happen before call to base NotifyContextShuttingDown() per that
119   // method's doc comments.
120   is_shut_down_ = true;
121 
122   URLRequestContextGetter::NotifyContextShuttingDown();
123   context_ = nullptr;
124 }
125 
126 scoped_refptr<base::SingleThreadTaskRunner>
GetNetworkTaskRunner() const127 TestURLRequestContextGetter::GetNetworkTaskRunner() const {
128   return network_task_runner_;
129 }
130 
131 const int TestDelegate::kBufferSize;
132 
TestDelegate()133 TestDelegate::TestDelegate()
134     : buf_(base::MakeRefCounted<IOBuffer>(kBufferSize)) {}
135 
136 TestDelegate::~TestDelegate() = default;
137 
RunUntilComplete()138 void TestDelegate::RunUntilComplete() {
139   use_legacy_on_complete_ = false;
140   base::RunLoop run_loop;
141   on_complete_ = run_loop.QuitClosure();
142   run_loop.Run();
143 }
144 
RunUntilRedirect()145 void TestDelegate::RunUntilRedirect() {
146   use_legacy_on_complete_ = false;
147   base::RunLoop run_loop;
148   on_redirect_ = run_loop.QuitClosure();
149   run_loop.Run();
150 }
151 
RunUntilAuthRequired()152 void TestDelegate::RunUntilAuthRequired() {
153   use_legacy_on_complete_ = false;
154   base::RunLoop run_loop;
155   on_auth_required_ = run_loop.QuitClosure();
156   run_loop.Run();
157 }
158 
OnConnected(URLRequest * request,const TransportInfo & info,CompletionOnceCallback callback)159 int TestDelegate::OnConnected(URLRequest* request,
160                               const TransportInfo& info,
161                               CompletionOnceCallback callback) {
162   transports_.push_back(info);
163 
164   if (on_connected_run_callback_) {
165     base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
166         FROM_HERE, base::BindOnce(std::move(callback), on_connected_result_));
167     return net::ERR_IO_PENDING;
168   }
169 
170   return on_connected_result_;
171 }
172 
OnReceivedRedirect(URLRequest * request,const RedirectInfo & redirect_info,bool * defer_redirect)173 void TestDelegate::OnReceivedRedirect(URLRequest* request,
174                                       const RedirectInfo& redirect_info,
175                                       bool* defer_redirect) {
176   EXPECT_TRUE(request->is_redirecting());
177 
178   redirect_info_ = redirect_info;
179 
180   received_redirect_count_++;
181   if (on_redirect_) {
182     *defer_redirect = true;
183     std::move(on_redirect_).Run();
184   } else if (cancel_in_rr_) {
185     request->Cancel();
186   }
187 }
188 
OnAuthRequired(URLRequest * request,const AuthChallengeInfo & auth_info)189 void TestDelegate::OnAuthRequired(URLRequest* request,
190                                   const AuthChallengeInfo& auth_info) {
191   auth_required_ = true;
192   if (on_auth_required_) {
193     std::move(on_auth_required_).Run();
194     return;
195   }
196   if (!credentials_.Empty()) {
197     request->SetAuth(credentials_);
198   } else {
199     request->CancelAuth();
200   }
201 }
202 
OnSSLCertificateError(URLRequest * request,int net_error,const SSLInfo & ssl_info,bool fatal)203 void TestDelegate::OnSSLCertificateError(URLRequest* request,
204                                          int net_error,
205                                          const SSLInfo& ssl_info,
206                                          bool fatal) {
207   // The caller can control whether it needs all SSL requests to go through,
208   // independent of any possible errors, or whether it wants SSL errors to
209   // cancel the request.
210   have_certificate_errors_ = true;
211   certificate_errors_are_fatal_ = fatal;
212   certificate_net_error_ = net_error;
213   if (allow_certificate_errors_)
214     request->ContinueDespiteLastError();
215   else
216     request->Cancel();
217 }
218 
OnResponseStarted(URLRequest * request,int net_error)219 void TestDelegate::OnResponseStarted(URLRequest* request, int net_error) {
220   // It doesn't make sense for the request to have IO pending at this point.
221   DCHECK_NE(ERR_IO_PENDING, net_error);
222   EXPECT_FALSE(request->is_redirecting());
223 
224   response_started_count_++;
225   request_status_ = net_error;
226   if (cancel_in_rs_) {
227     request_status_ = request->Cancel();
228     // Canceling |request| will cause OnResponseCompleted() to be called.
229   } else if (net_error != OK) {
230     request_failed_ = true;
231     OnResponseCompleted(request);
232   } else {
233     // Initiate the first read.
234     int bytes_read = request->Read(buf_.get(), kBufferSize);
235     if (bytes_read >= 0)
236       OnReadCompleted(request, bytes_read);
237     else if (bytes_read != ERR_IO_PENDING)
238       OnResponseCompleted(request);
239   }
240 }
241 
OnReadCompleted(URLRequest * request,int bytes_read)242 void TestDelegate::OnReadCompleted(URLRequest* request, int bytes_read) {
243   // It doesn't make sense for the request to have IO pending at this point.
244   DCHECK_NE(bytes_read, ERR_IO_PENDING);
245 
246   // If you've reached this, you've either called "RunUntilComplete" or are
247   // using legacy "QuitCurrent*Deprecated". If this DCHECK fails, that probably
248   // means you've run "RunUntilRedirect" or "RunUntilAuthRequired" and haven't
249   // redirected/auth-challenged
250   DCHECK(on_complete_ || use_legacy_on_complete_);
251 
252   // If the request was cancelled in a redirect, it should not signal
253   // OnReadCompleted. Note that |cancel_in_rs_| may be true due to
254   // https://crbug.com/564848.
255   EXPECT_FALSE(cancel_in_rr_);
256 
257   if (response_started_count_ == 0)
258     received_data_before_response_ = true;
259 
260   if (bytes_read >= 0) {
261     // There is data to read.
262     received_bytes_count_ += bytes_read;
263 
264     // Consume the data.
265     data_received_.append(buf_->data(), bytes_read);
266 
267     if (cancel_in_rd_) {
268       request_status_ = request->Cancel();
269       // If bytes_read is 0, won't get a notification on cancelation.
270       if (bytes_read == 0) {
271         if (use_legacy_on_complete_)
272           base::RunLoop::QuitCurrentWhenIdleDeprecated();
273         else
274           std::move(on_complete_).Run();
275       }
276       return;
277     }
278   }
279 
280   // If it was not end of stream, request to read more.
281   while (bytes_read > 0) {
282     bytes_read = request->Read(buf_.get(), kBufferSize);
283     if (bytes_read > 0) {
284       data_received_.append(buf_->data(), bytes_read);
285       received_bytes_count_ += bytes_read;
286     }
287   }
288 
289   request_status_ = bytes_read;
290   if (request_status_ != ERR_IO_PENDING)
291     OnResponseCompleted(request);
292   else if (cancel_in_rd_pending_)
293     request_status_ = request->Cancel();
294 }
295 
OnResponseCompleted(URLRequest * request)296 void TestDelegate::OnResponseCompleted(URLRequest* request) {
297   response_completed_ = true;
298   if (use_legacy_on_complete_)
299     base::RunLoop::QuitCurrentWhenIdleDeprecated();
300   else
301     std::move(on_complete_).Run();
302 }
303 
304 TestNetworkDelegate::TestNetworkDelegate() = default;
305 
~TestNetworkDelegate()306 TestNetworkDelegate::~TestNetworkDelegate() {
307   for (auto i = next_states_.begin(); i != next_states_.end(); ++i) {
308     event_order_[i->first] += "~TestNetworkDelegate\n";
309     EXPECT_TRUE(i->second & kStageDestruction) << event_order_[i->first];
310   }
311 }
312 
GetLoadTimingInfoBeforeRedirect(LoadTimingInfo * load_timing_info_before_redirect) const313 bool TestNetworkDelegate::GetLoadTimingInfoBeforeRedirect(
314     LoadTimingInfo* load_timing_info_before_redirect) const {
315   *load_timing_info_before_redirect = load_timing_info_before_redirect_;
316   return has_load_timing_info_before_redirect_;
317 }
318 
InitRequestStatesIfNew(int request_id)319 void TestNetworkDelegate::InitRequestStatesIfNew(int request_id) {
320   if (next_states_.find(request_id) == next_states_.end()) {
321     // TODO(davidben): Although the URLRequest documentation does not allow
322     // calling Cancel() before Start(), the ResourceLoader does so. URLRequest's
323     // destructor also calls Cancel. Either officially support this or fix the
324     // ResourceLoader code.
325     next_states_[request_id] = kStageBeforeURLRequest | kStageCompletedError;
326     event_order_[request_id] = "";
327   }
328 }
329 
OnBeforeURLRequest(URLRequest * request,CompletionOnceCallback callback,GURL * new_url)330 int TestNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
331                                             CompletionOnceCallback callback,
332                                             GURL* new_url) {
333   int req_id = GetRequestId(request);
334   InitRequestStatesIfNew(req_id);
335   event_order_[req_id] += "OnBeforeURLRequest\n";
336   EXPECT_TRUE(next_states_[req_id] & kStageBeforeURLRequest) <<
337       event_order_[req_id];
338   next_states_[req_id] =
339       kStageBeforeStartTransaction |
340       kStageResponseStarted |  // data: URLs do not trigger sending headers
341       kStageBeforeRedirect |   // a delegate can trigger a redirection
342       kStageCompletedError;    // request canceled by delegate
343   created_requests_++;
344   return OK;
345 }
346 
OnBeforeStartTransaction(URLRequest * request,const HttpRequestHeaders & headers,OnBeforeStartTransactionCallback callback)347 int TestNetworkDelegate::OnBeforeStartTransaction(
348     URLRequest* request,
349     const HttpRequestHeaders& headers,
350     OnBeforeStartTransactionCallback callback) {
351   if (before_start_transaction_fails_)
352     return ERR_FAILED;
353 
354   int req_id = GetRequestId(request);
355   InitRequestStatesIfNew(req_id);
356   event_order_[req_id] += "OnBeforeStartTransaction\n";
357   EXPECT_TRUE(next_states_[req_id] & kStageBeforeStartTransaction)
358       << event_order_[req_id];
359   next_states_[req_id] =
360       kStageHeadersReceived | kStageCompletedError | kStageBeforeRedirect;
361   before_start_transaction_count_++;
362   return OK;
363 }
364 
OnHeadersReceived(URLRequest * request,CompletionOnceCallback callback,const HttpResponseHeaders * original_response_headers,scoped_refptr<HttpResponseHeaders> * override_response_headers,const IPEndPoint & endpoint,absl::optional<GURL> * preserve_fragment_on_redirect_url)365 int TestNetworkDelegate::OnHeadersReceived(
366     URLRequest* request,
367     CompletionOnceCallback callback,
368     const HttpResponseHeaders* original_response_headers,
369     scoped_refptr<HttpResponseHeaders>* override_response_headers,
370     const IPEndPoint& endpoint,
371     absl::optional<GURL>* preserve_fragment_on_redirect_url) {
372   EXPECT_FALSE(preserve_fragment_on_redirect_url->has_value());
373   int req_id = GetRequestId(request);
374   bool is_first_response =
375       event_order_[req_id].find("OnHeadersReceived\n") == std::string::npos;
376   event_order_[req_id] += "OnHeadersReceived\n";
377   InitRequestStatesIfNew(req_id);
378   EXPECT_TRUE(next_states_[req_id] & kStageHeadersReceived) <<
379       event_order_[req_id];
380   next_states_[req_id] =
381       kStageBeforeRedirect |
382       kStageResponseStarted |
383       kStageCompletedError;  // e.g. proxy resolution problem
384 
385   // Basic authentication sends a second request from the URLRequestHttpJob
386   // layer before the URLRequest reports that a response has started.
387   next_states_[req_id] |= kStageBeforeStartTransaction;
388 
389   if (!redirect_on_headers_received_url_.is_empty()) {
390     *override_response_headers = base::MakeRefCounted<HttpResponseHeaders>(
391         original_response_headers->raw_headers());
392     (*override_response_headers)->ReplaceStatusLine("HTTP/1.1 302 Found");
393     (*override_response_headers)->RemoveHeader("Location");
394     (*override_response_headers)
395         ->AddHeader("Location", redirect_on_headers_received_url_.spec());
396 
397     redirect_on_headers_received_url_ = GURL();
398 
399     // Since both values are absl::optionals, can just copy this over.
400     *preserve_fragment_on_redirect_url = preserve_fragment_on_redirect_url_;
401   } else if (add_header_to_first_response_ && is_first_response) {
402     *override_response_headers = base::MakeRefCounted<HttpResponseHeaders>(
403         original_response_headers->raw_headers());
404     (*override_response_headers)
405         ->AddHeader("X-Network-Delegate", "Greetings, planet");
406   }
407 
408   headers_received_count_++;
409   return OK;
410 }
411 
OnBeforeRedirect(URLRequest * request,const GURL & new_location)412 void TestNetworkDelegate::OnBeforeRedirect(URLRequest* request,
413                                            const GURL& new_location) {
414   load_timing_info_before_redirect_ = LoadTimingInfo();
415   request->GetLoadTimingInfo(&load_timing_info_before_redirect_);
416   has_load_timing_info_before_redirect_ = true;
417   EXPECT_FALSE(load_timing_info_before_redirect_.request_start_time.is_null());
418   EXPECT_FALSE(load_timing_info_before_redirect_.request_start.is_null());
419 
420   int req_id = GetRequestId(request);
421   InitRequestStatesIfNew(req_id);
422   event_order_[req_id] += "OnBeforeRedirect\n";
423   EXPECT_TRUE(next_states_[req_id] & kStageBeforeRedirect) <<
424       event_order_[req_id];
425   next_states_[req_id] =
426       kStageBeforeURLRequest |        // HTTP redirects trigger this.
427       kStageBeforeStartTransaction |  // Redirects from the network delegate do
428                                       // not
429                                       // trigger onBeforeURLRequest.
430       kStageCompletedError;
431 
432   // A redirect can lead to a file or a data URL. In this case, we do not send
433   // headers.
434   next_states_[req_id] |= kStageResponseStarted;
435 }
436 
OnResponseStarted(URLRequest * request,int net_error)437 void TestNetworkDelegate::OnResponseStarted(URLRequest* request,
438                                             int net_error) {
439   DCHECK_NE(ERR_IO_PENDING, net_error);
440 
441   LoadTimingInfo load_timing_info;
442   request->GetLoadTimingInfo(&load_timing_info);
443   EXPECT_FALSE(load_timing_info.request_start_time.is_null());
444   EXPECT_FALSE(load_timing_info.request_start.is_null());
445 
446   int req_id = GetRequestId(request);
447   InitRequestStatesIfNew(req_id);
448   event_order_[req_id] += "OnResponseStarted\n";
449   EXPECT_TRUE(next_states_[req_id] & kStageResponseStarted)
450       << event_order_[req_id];
451   next_states_[req_id] = kStageCompletedSuccess | kStageCompletedError;
452   if (net_error == ERR_ABORTED)
453     return;
454 
455   if (net_error != OK) {
456     error_count_++;
457     last_error_ = net_error;
458   }
459 }
460 
OnCompleted(URLRequest * request,bool started,int net_error)461 void TestNetworkDelegate::OnCompleted(URLRequest* request,
462                                       bool started,
463                                       int net_error) {
464   DCHECK_NE(net_error, net::ERR_IO_PENDING);
465 
466   int req_id = GetRequestId(request);
467   InitRequestStatesIfNew(req_id);
468   event_order_[req_id] += "OnCompleted\n";
469   // Expect "Success -> (next_states_ & kStageCompletedSuccess)"
470   // is logically identical to
471   // Expect "!(Success) || (next_states_ & kStageCompletedSuccess)"
472   EXPECT_TRUE(net_error != OK ||
473               (next_states_[req_id] & kStageCompletedSuccess))
474       << event_order_[req_id];
475   EXPECT_TRUE(net_error == OK || (next_states_[req_id] & kStageCompletedError))
476       << event_order_[req_id];
477   next_states_[req_id] = kStageURLRequestDestroyed;
478   completed_requests_++;
479   if (net_error == ERR_ABORTED) {
480     canceled_requests_++;
481   } else if (net_error != OK) {
482     error_count_++;
483     last_error_ = net_error;
484   } else {
485     DCHECK_EQ(OK, net_error);
486   }
487 }
488 
OnURLRequestDestroyed(URLRequest * request)489 void TestNetworkDelegate::OnURLRequestDestroyed(URLRequest* request) {
490   int req_id = GetRequestId(request);
491   InitRequestStatesIfNew(req_id);
492   event_order_[req_id] += "OnURLRequestDestroyed\n";
493   EXPECT_TRUE(next_states_[req_id] & kStageURLRequestDestroyed) <<
494       event_order_[req_id];
495   next_states_[req_id] = kStageDestruction;
496   destroyed_requests_++;
497 }
498 
OnAnnotateAndMoveUserBlockedCookies(const URLRequest & request,const net::FirstPartySetMetadata & first_party_set_metadata,net::CookieAccessResultList & maybe_included_cookies,net::CookieAccessResultList & excluded_cookies)499 bool TestNetworkDelegate::OnAnnotateAndMoveUserBlockedCookies(
500     const URLRequest& request,
501     const net::FirstPartySetMetadata& first_party_set_metadata,
502     net::CookieAccessResultList& maybe_included_cookies,
503     net::CookieAccessResultList& excluded_cookies) {
504   RecordCookieSettingOverrides(request.cookie_setting_overrides());
505   bool allow = true;
506   if (cookie_options_bit_mask_ & NO_GET_COOKIES)
507     allow = false;
508 
509   if (!allow) {
510     blocked_annotate_cookies_count_++;
511     ExcludeAllCookies(CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
512                       maybe_included_cookies, excluded_cookies);
513   }
514 
515   return allow;
516 }
517 
OnForcePrivacyMode(const URLRequest & request) const518 NetworkDelegate::PrivacySetting TestNetworkDelegate::OnForcePrivacyMode(
519     const URLRequest& request) const {
520   RecordCookieSettingOverrides(request.cookie_setting_overrides());
521   return NetworkDelegate::PrivacySetting::kStateAllowed;
522 }
523 
OnCanSetCookie(const URLRequest & request,const net::CanonicalCookie & cookie,CookieOptions * options)524 bool TestNetworkDelegate::OnCanSetCookie(const URLRequest& request,
525                                          const net::CanonicalCookie& cookie,
526                                          CookieOptions* options) {
527   RecordCookieSettingOverrides(request.cookie_setting_overrides());
528   bool allow = true;
529   if (cookie_options_bit_mask_ & NO_SET_COOKIE)
530     allow = false;
531 
532   if (!allow) {
533     blocked_set_cookie_count_++;
534   } else {
535     set_cookie_count_++;
536   }
537 
538   return allow;
539 }
540 
OnCancelURLRequestWithPolicyViolatingReferrerHeader(const URLRequest & request,const GURL & target_url,const GURL & referrer_url) const541 bool TestNetworkDelegate::OnCancelURLRequestWithPolicyViolatingReferrerHeader(
542     const URLRequest& request,
543     const GURL& target_url,
544     const GURL& referrer_url) const {
545   return cancel_request_with_policy_violating_referrer_;
546 }
547 
548 absl::optional<FirstPartySetsCacheFilter::MatchInfo>
OnGetFirstPartySetsCacheFilterMatchInfoMaybeAsync(const SchemefulSite & request_site,base::OnceCallback<void (FirstPartySetsCacheFilter::MatchInfo)> callback) const549 TestNetworkDelegate::OnGetFirstPartySetsCacheFilterMatchInfoMaybeAsync(
550     const SchemefulSite& request_site,
551     base::OnceCallback<void(FirstPartySetsCacheFilter::MatchInfo)> callback)
552     const {
553   return fps_cache_filter_.GetMatchInfo(request_site);
554 }
555 
GetRequestId(URLRequest * request)556 int TestNetworkDelegate::GetRequestId(URLRequest* request) {
557   TestRequestId* test_request_id = reinterpret_cast<TestRequestId*>(
558       request->GetUserData(kTestNetworkDelegateRequestIdKey));
559   if (test_request_id)
560     return test_request_id->id();
561   int id = next_request_id_++;
562   request->SetUserData(kTestNetworkDelegateRequestIdKey,
563                        std::make_unique<TestRequestId>(id));
564   return id;
565 }
566 
567 FilteringTestNetworkDelegate::FilteringTestNetworkDelegate() = default;
568 FilteringTestNetworkDelegate::~FilteringTestNetworkDelegate() = default;
569 
OnCanSetCookie(const URLRequest & request,const net::CanonicalCookie & cookie,CookieOptions * options)570 bool FilteringTestNetworkDelegate::OnCanSetCookie(
571     const URLRequest& request,
572     const net::CanonicalCookie& cookie,
573     CookieOptions* options) {
574   // Filter out cookies with the same name as |cookie_name_filter_| and
575   // combine with |allowed_from_caller|.
576   bool allowed = cookie.Name() != cookie_name_filter_;
577 
578   ++set_cookie_called_count_;
579 
580   if (!allowed)
581     ++blocked_set_cookie_count_;
582 
583   // Call the nested delegate's method first to avoid a short circuit.
584   return TestNetworkDelegate::OnCanSetCookie(request, cookie, options) &&
585          allowed;
586 }
587 
588 NetworkDelegate::PrivacySetting
OnForcePrivacyMode(const URLRequest & request) const589 FilteringTestNetworkDelegate::OnForcePrivacyMode(
590     const URLRequest& request) const {
591   if (force_privacy_mode_) {
592     return partitioned_state_allowed_
593                ? NetworkDelegate::PrivacySetting::kPartitionedStateAllowedOnly
594                : NetworkDelegate::PrivacySetting::kStateDisallowed;
595   }
596 
597   return TestNetworkDelegate::OnForcePrivacyMode(request);
598 }
599 
OnAnnotateAndMoveUserBlockedCookies(const URLRequest & request,const net::FirstPartySetMetadata & first_party_set_metadata,net::CookieAccessResultList & maybe_included_cookies,net::CookieAccessResultList & excluded_cookies)600 bool FilteringTestNetworkDelegate::OnAnnotateAndMoveUserBlockedCookies(
601     const URLRequest& request,
602     const net::FirstPartySetMetadata& first_party_set_metadata,
603     net::CookieAccessResultList& maybe_included_cookies,
604     net::CookieAccessResultList& excluded_cookies) {
605   // Filter out cookies if |block_annotate_cookies_| is set and
606   // combine with |allowed_from_caller|.
607   bool allowed = !block_annotate_cookies_;
608 
609   ++annotate_cookies_called_count_;
610 
611   if (!allowed) {
612     ++blocked_annotate_cookies_count_;
613     ExcludeAllCookies(net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
614                       maybe_included_cookies, excluded_cookies);
615   }
616 
617   if (allowed && block_get_cookies_by_name_ && !cookie_name_filter_.empty()) {
618     for (auto& cookie : maybe_included_cookies) {
619       if (cookie.cookie.Name().find(cookie_name_filter_) != std::string::npos) {
620         cookie.access_result.status.AddExclusionReason(
621             net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES);
622       }
623     }
624     for (auto& cookie : excluded_cookies) {
625       if (cookie.cookie.Name().find(cookie_name_filter_) != std::string::npos) {
626         cookie.access_result.status.AddExclusionReason(
627             net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES);
628       }
629     }
630 
631     MoveExcludedCookies(maybe_included_cookies, excluded_cookies);
632   }
633 
634   // Call the nested delegate's method first to avoid a short circuit.
635   return TestNetworkDelegate::OnAnnotateAndMoveUserBlockedCookies(
636              request, first_party_set_metadata, maybe_included_cookies,
637              excluded_cookies) &&
638          allowed;
639 }
640 
641 // URLRequestInterceptor that intercepts only the first request it sees,
642 // returning the provided URLRequestJob.
643 class TestScopedURLInterceptor::TestRequestInterceptor
644     : public URLRequestInterceptor {
645  public:
TestRequestInterceptor(std::unique_ptr<URLRequestJob> intercept_job)646   explicit TestRequestInterceptor(std::unique_ptr<URLRequestJob> intercept_job)
647       : intercept_job_(std::move(intercept_job)) {}
648 
~TestRequestInterceptor()649   ~TestRequestInterceptor() override { CHECK(safe_to_delete_); }
650 
MaybeInterceptRequest(URLRequest * request) const651   std::unique_ptr<URLRequestJob> MaybeInterceptRequest(
652       URLRequest* request) const override {
653     return std::move(intercept_job_);
654   }
655 
job_used() const656   bool job_used() const { return intercept_job_.get() == nullptr; }
set_safe_to_delete()657   void set_safe_to_delete() { safe_to_delete_ = true; }
658 
659  private:
660   mutable std::unique_ptr<URLRequestJob> intercept_job_;
661   // This is used to catch chases where the TestRequestInterceptor is destroyed
662   // before the TestScopedURLInterceptor.
663   bool safe_to_delete_ = false;
664 };
665 
TestScopedURLInterceptor(const GURL & url,std::unique_ptr<URLRequestJob> intercept_job)666 TestScopedURLInterceptor::TestScopedURLInterceptor(
667     const GURL& url,
668     std::unique_ptr<URLRequestJob> intercept_job)
669     : url_(url) {
670   std::unique_ptr<TestRequestInterceptor> interceptor =
671       std::make_unique<TestRequestInterceptor>(std::move(intercept_job));
672   interceptor_ = interceptor.get();
673   URLRequestFilter::GetInstance()->AddUrlInterceptor(url_,
674                                                      std::move(interceptor));
675 }
676 
~TestScopedURLInterceptor()677 TestScopedURLInterceptor::~TestScopedURLInterceptor() {
678   DCHECK(interceptor_->job_used());
679   interceptor_->set_safe_to_delete();
680   interceptor_ = nullptr;
681   URLRequestFilter::GetInstance()->RemoveUrlHandler(url_);
682 }
683 
684 }  // namespace net
685