xref: /aosp_15_r20/external/cronet/net/socket/transport_client_socket_pool_unittest.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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/socket/transport_client_socket_pool.h"
6 
7 #include <memory>
8 #include <optional>
9 #include <utility>
10 
11 #include "base/functional/bind.h"
12 #include "base/functional/callback.h"
13 #include "base/functional/callback_helpers.h"
14 #include "base/memory/raw_ptr.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/run_loop.h"
17 #include "base/test/bind.h"
18 #include "base/test/scoped_feature_list.h"
19 #include "base/threading/platform_thread.h"
20 #include "build/build_config.h"
21 #include "net/base/completion_once_callback.h"
22 #include "net/base/features.h"
23 #include "net/base/ip_endpoint.h"
24 #include "net/base/load_timing_info.h"
25 #include "net/base/load_timing_info_test_util.h"
26 #include "net/base/net_errors.h"
27 #include "net/base/network_anonymization_key.h"
28 #include "net/base/privacy_mode.h"
29 #include "net/base/proxy_chain.h"
30 #include "net/base/proxy_server.h"
31 #include "net/base/proxy_string_util.h"
32 #include "net/base/schemeful_site.h"
33 #include "net/base/test_completion_callback.h"
34 #include "net/cert/mock_cert_verifier.h"
35 #include "net/dns/mock_host_resolver.h"
36 #include "net/dns/public/secure_dns_policy.h"
37 #include "net/http/http_network_session.h"
38 #include "net/http/http_proxy_connect_job.h"
39 #include "net/http/transport_security_state.h"
40 #include "net/log/net_log.h"
41 #include "net/log/net_log_with_source.h"
42 #include "net/log/test_net_log.h"
43 #include "net/proxy_resolution/configured_proxy_resolution_service.h"
44 #include "net/socket/client_socket_handle.h"
45 #include "net/socket/connect_job.h"
46 #include "net/socket/socket_tag.h"
47 #include "net/socket/socket_test_util.h"
48 #include "net/socket/socks_connect_job.h"
49 #include "net/socket/ssl_connect_job.h"
50 #include "net/socket/stream_socket.h"
51 #include "net/socket/transport_client_socket_pool.h"
52 #include "net/socket/transport_client_socket_pool_test_util.h"
53 #include "net/socket/transport_connect_job.h"
54 #include "net/spdy/spdy_test_util_common.h"
55 #include "net/ssl/ssl_config_service.h"
56 #include "net/test/embedded_test_server/embedded_test_server.h"
57 #include "net/test/gtest_util.h"
58 #include "net/test/test_with_task_environment.h"
59 #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
60 #include "testing/gmock/include/gmock/gmock.h"
61 #include "testing/gtest/include/gtest/gtest.h"
62 #include "url/gurl.h"
63 #include "url/scheme_host_port.h"
64 #include "url/url_constants.h"
65 
66 using net::test::IsError;
67 using net::test::IsOk;
68 
69 namespace net {
70 
71 namespace {
72 
73 const int kMaxSockets = 32;
74 const int kMaxSocketsPerGroup = 6;
75 constexpr base::TimeDelta kUnusedIdleSocketTimeout = base::Seconds(10);
76 const RequestPriority kDefaultPriority = LOW;
77 
78 class SOCKS5MockData {
79  public:
SOCKS5MockData(IoMode mode)80   explicit SOCKS5MockData(IoMode mode) {
81     writes_ = std::make_unique<MockWrite[]>(2);
82     writes_[0] =
83         MockWrite(mode, kSOCKS5GreetRequest, kSOCKS5GreetRequestLength);
84     writes_[1] = MockWrite(mode, kSOCKS5OkRequest, kSOCKS5OkRequestLength);
85 
86     reads_ = std::make_unique<MockRead[]>(2);
87     reads_[0] =
88         MockRead(mode, kSOCKS5GreetResponse, kSOCKS5GreetResponseLength);
89     reads_[1] = MockRead(mode, kSOCKS5OkResponse, kSOCKS5OkResponseLength);
90 
91     data_ = std::make_unique<StaticSocketDataProvider>(
92         base::make_span(reads_.get(), 2u), base::make_span(writes_.get(), 2u));
93   }
94 
data_provider()95   SocketDataProvider* data_provider() { return data_.get(); }
96 
97  private:
98   std::unique_ptr<StaticSocketDataProvider> data_;
99   std::unique_ptr<MockWrite[]> writes_;
100   std::unique_ptr<MockRead[]> reads_;
101 };
102 
103 class TransportClientSocketPoolTest : public ::testing::Test,
104                                       public WithTaskEnvironment {
105  public:
106   TransportClientSocketPoolTest(const TransportClientSocketPoolTest&) = delete;
107   TransportClientSocketPoolTest& operator=(
108       const TransportClientSocketPoolTest&) = delete;
109 
110  protected:
111   // Constructor that allows mocking of the time.
TransportClientSocketPoolTest(base::test::TaskEnvironment::TimeSource time_source=base::test::TaskEnvironment::TimeSource::DEFAULT)112   explicit TransportClientSocketPoolTest(
113       base::test::TaskEnvironment::TimeSource time_source =
114           base::test::TaskEnvironment::TimeSource::DEFAULT)
115       : WithTaskEnvironment(time_source),
116         connect_backup_jobs_enabled_(
117             TransportClientSocketPool::set_connect_backup_jobs_enabled(true)),
118         group_id_(url::SchemeHostPort(url::kHttpScheme, "www.google.com", 80),
119                   PrivacyMode::PRIVACY_MODE_DISABLED,
120                   NetworkAnonymizationKey(),
121                   SecureDnsPolicy::kAllow,
122                   /*disable_cert_network_fetches=*/false),
123         params_(ClientSocketPool::SocketParams::CreateForHttpForTesting()),
124         client_socket_factory_(NetLog::Get()) {
125     std::unique_ptr<MockCertVerifier> cert_verifier =
126         std::make_unique<MockCertVerifier>();
127     cert_verifier->set_default_result(OK);
128     session_deps_.cert_verifier = std::move(cert_verifier);
129 
130     http_network_session_ =
131         SpdySessionDependencies::SpdyCreateSession(&session_deps_);
132 
133     common_connect_job_params_ = std::make_unique<CommonConnectJobParams>(
134         http_network_session_->CreateCommonConnectJobParams());
135     common_connect_job_params_->client_socket_factory = &client_socket_factory_;
136     pool_ = std::make_unique<TransportClientSocketPool>(
137         kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
138         ProxyChain::Direct(), /*is_for_websockets=*/false,
139         common_connect_job_params_.get());
140 
141     tagging_common_connect_job_params_ =
142         std::make_unique<CommonConnectJobParams>(
143             http_network_session_->CreateCommonConnectJobParams());
144     tagging_common_connect_job_params_->client_socket_factory =
145         &tagging_client_socket_factory_;
146     tagging_pool_ = std::make_unique<TransportClientSocketPool>(
147         kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
148         ProxyChain::Direct(), /*is_for_websockets=*/false,
149         tagging_common_connect_job_params_.get());
150 
151     common_connect_job_params_for_real_sockets_ =
152         std::make_unique<CommonConnectJobParams>(
153             http_network_session_->CreateCommonConnectJobParams());
154     common_connect_job_params_for_real_sockets_->client_socket_factory =
155         ClientSocketFactory::GetDefaultFactory();
156     pool_for_real_sockets_ = std::make_unique<TransportClientSocketPool>(
157         kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
158         ProxyChain::Direct(), /*is_for_websockets=*/false,
159         common_connect_job_params_for_real_sockets_.get());
160   }
161 
~TransportClientSocketPoolTest()162   ~TransportClientSocketPoolTest() override {
163     TransportClientSocketPool::set_connect_backup_jobs_enabled(
164         connect_backup_jobs_enabled_);
165   }
166 
StartRequest(const std::string & host_name,RequestPriority priority)167   int StartRequest(const std::string& host_name, RequestPriority priority) {
168     ClientSocketPool::GroupId group_id(
169         url::SchemeHostPort(url::kHttpScheme, host_name, 80),
170         PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
171         SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
172     return test_base_.StartRequestUsingPool(
173         pool_.get(), group_id, priority,
174         ClientSocketPool::RespectLimits::ENABLED,
175         ClientSocketPool::SocketParams::CreateForHttpForTesting());
176   }
177 
GetOrderOfRequest(size_t index)178   int GetOrderOfRequest(size_t index) {
179     return test_base_.GetOrderOfRequest(index);
180   }
181 
ReleaseOneConnection(ClientSocketPoolTest::KeepAlive keep_alive)182   bool ReleaseOneConnection(ClientSocketPoolTest::KeepAlive keep_alive) {
183     return test_base_.ReleaseOneConnection(keep_alive);
184   }
185 
ReleaseAllConnections(ClientSocketPoolTest::KeepAlive keep_alive)186   void ReleaseAllConnections(ClientSocketPoolTest::KeepAlive keep_alive) {
187     test_base_.ReleaseAllConnections(keep_alive);
188   }
189 
requests()190   std::vector<std::unique_ptr<TestSocketRequest>>* requests() {
191     return test_base_.requests();
192   }
completion_count() const193   size_t completion_count() const { return test_base_.completion_count(); }
194 
195   bool connect_backup_jobs_enabled_;
196 
197   // |group_id_| and |params_| correspond to the same group.
198   const ClientSocketPool::GroupId group_id_;
199   scoped_refptr<ClientSocketPool::SocketParams> params_;
200 
201   MockTransportClientSocketFactory client_socket_factory_;
202   MockTaggingClientSocketFactory tagging_client_socket_factory_;
203 
204   // None of these tests check SPDY behavior, but this is a convenient way to
205   // create most objects needed by the socket pools, as well as a SpdySession
206   // pool, which is required by HttpProxyConnectJobs when using an HTTPS proxy.
207   SpdySessionDependencies session_deps_;
208   // As with |session_deps_|, this is a convenient way to construct objects
209   // these tests depend on.
210   std::unique_ptr<HttpNetworkSession> http_network_session_;
211 
212   std::unique_ptr<CommonConnectJobParams> common_connect_job_params_;
213   std::unique_ptr<TransportClientSocketPool> pool_;
214 
215   // Just like |pool_|, except it uses a real MockTaggingClientSocketFactory
216   // instead of MockTransportClientSocketFactory.
217   std::unique_ptr<CommonConnectJobParams> tagging_common_connect_job_params_;
218   std::unique_ptr<TransportClientSocketPool> tagging_pool_;
219 
220   // Just like |pool_|, except it uses a real ClientSocketFactory instead of
221   // |client_socket_factory_|.
222   std::unique_ptr<CommonConnectJobParams>
223       common_connect_job_params_for_real_sockets_;
224   std::unique_ptr<TransportClientSocketPool> pool_for_real_sockets_;
225 
226   ClientSocketPoolTest test_base_;
227 };
228 
TEST_F(TransportClientSocketPoolTest,Basic)229 TEST_F(TransportClientSocketPoolTest, Basic) {
230   TestCompletionCallback callback;
231   ClientSocketHandle handle;
232   int rv =
233       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
234                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
235                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
236                   pool_.get(), NetLogWithSource());
237   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
238   EXPECT_FALSE(handle.is_initialized());
239   EXPECT_FALSE(handle.socket());
240 
241   EXPECT_THAT(callback.WaitForResult(), IsOk());
242   EXPECT_TRUE(handle.is_initialized());
243   EXPECT_TRUE(handle.socket());
244   TestLoadTimingInfoConnectedNotReused(handle);
245   EXPECT_EQ(0u, handle.connection_attempts().size());
246 }
247 
248 // Make sure that TransportConnectJob passes on its priority to its
249 // HostResolver request on Init.
TEST_F(TransportClientSocketPoolTest,SetResolvePriorityOnInit)250 TEST_F(TransportClientSocketPoolTest, SetResolvePriorityOnInit) {
251   for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
252     RequestPriority priority = static_cast<RequestPriority>(i);
253     TestCompletionCallback callback;
254     ClientSocketHandle handle;
255     EXPECT_EQ(
256         ERR_IO_PENDING,
257         handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
258                     priority, SocketTag(),
259                     ClientSocketPool::RespectLimits::ENABLED,
260                     callback.callback(), ClientSocketPool::ProxyAuthCallback(),
261                     pool_.get(), NetLogWithSource()));
262     EXPECT_EQ(priority, session_deps_.host_resolver->last_request_priority());
263   }
264 }
265 
TEST_F(TransportClientSocketPoolTest,SetSecureDnsPolicy)266 TEST_F(TransportClientSocketPoolTest, SetSecureDnsPolicy) {
267   for (auto secure_dns_policy :
268        {SecureDnsPolicy::kAllow, SecureDnsPolicy::kDisable}) {
269     TestCompletionCallback callback;
270     ClientSocketHandle handle;
271     ClientSocketPool::GroupId group_id(
272         url::SchemeHostPort(url::kHttpScheme, "www.google.com", 80),
273         PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
274         secure_dns_policy, /*disable_cert_network_fetches=*/false);
275     EXPECT_EQ(
276         ERR_IO_PENDING,
277         handle.Init(group_id, params_, std::nullopt /* proxy_annotation_tag */,
278                     LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
279                     callback.callback(), ClientSocketPool::ProxyAuthCallback(),
280                     pool_.get(), NetLogWithSource()));
281     EXPECT_EQ(secure_dns_policy,
282               session_deps_.host_resolver->last_secure_dns_policy());
283   }
284 }
285 
TEST_F(TransportClientSocketPoolTest,ReprioritizeRequests)286 TEST_F(TransportClientSocketPoolTest, ReprioritizeRequests) {
287   session_deps_.host_resolver->set_ondemand_mode(true);
288 
289   TestCompletionCallback callback1;
290   ClientSocketHandle handle1;
291   int rv1 =
292       handle1.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
293                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
294                    callback1.callback(), ClientSocketPool::ProxyAuthCallback(),
295                    pool_.get(), NetLogWithSource());
296   EXPECT_THAT(rv1, IsError(ERR_IO_PENDING));
297 
298   TestCompletionCallback callback2;
299   ClientSocketHandle handle2;
300   int rv2 = handle2.Init(
301       group_id_, params_, std::nullopt /* proxy_annotation_tag */, HIGHEST,
302       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
303       callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
304       NetLogWithSource());
305   EXPECT_THAT(rv2, IsError(ERR_IO_PENDING));
306 
307   TestCompletionCallback callback3;
308   ClientSocketHandle handle3;
309   int rv3 = handle3.Init(
310       group_id_, params_, std::nullopt /* proxy_annotation_tag */, LOWEST,
311       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
312       callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
313       NetLogWithSource());
314   EXPECT_THAT(rv3, IsError(ERR_IO_PENDING));
315 
316   TestCompletionCallback callback4;
317   ClientSocketHandle handle4;
318   int rv4 = handle4.Init(
319       group_id_, params_, std::nullopt /* proxy_annotation_tag */, MEDIUM,
320       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
321       callback4.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
322       NetLogWithSource());
323   EXPECT_THAT(rv4, IsError(ERR_IO_PENDING));
324 
325   TestCompletionCallback callback5;
326   ClientSocketHandle handle5;
327   int rv5 = handle5.Init(
328       group_id_, params_, std::nullopt /* proxy_annotation_tag */, HIGHEST,
329       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
330       callback5.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
331       NetLogWithSource());
332   EXPECT_THAT(rv5, IsError(ERR_IO_PENDING));
333 
334   TestCompletionCallback callback6;
335   ClientSocketHandle handle6;
336   int rv6 =
337       handle6.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
338                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
339                    callback6.callback(), ClientSocketPool::ProxyAuthCallback(),
340                    pool_.get(), NetLogWithSource());
341   EXPECT_THAT(rv6, IsError(ERR_IO_PENDING));
342 
343   // New jobs are created for each of the first 6 requests with the
344   // corresponding priority.
345   //
346   // Queue of pending requests:
347   // Request  Job  Priority
348   // =======  ===  ========
349   //    2      2   HIGHEST
350   //    5      5   HIGHEST
351   //    4      4   MEDIUM
352   //    1      1   LOW
353   //    6      6   LOW
354   //    3      3   LOWEST
355   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
356   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(2));
357   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(3));
358   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
359   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(5));
360   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(6));
361 
362   // Inserting a highest-priority request steals the job from the lowest
363   // priority request and reprioritizes it to match the new request.
364   TestCompletionCallback callback7;
365   ClientSocketHandle handle7;
366   int rv7 = handle7.Init(
367       group_id_, params_, std::nullopt /* proxy_annotation_tag */, HIGHEST,
368       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
369       callback7.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
370       NetLogWithSource());
371   EXPECT_THAT(rv7, IsError(ERR_IO_PENDING));
372   // Request  Job  Priority
373   // =======  ===  ========
374   //    2      2   HIGHEST
375   //    5      5   HIGHEST
376   //    7      3   HIGHEST
377   //    4      4   MEDIUM
378   //    1      1   LOW
379   //    6      6   LOW
380   //    3          LOWEST
381   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
382   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(2));
383   EXPECT_EQ(HIGHEST,
384             session_deps_.host_resolver->request_priority(3));  // reprioritized
385   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
386   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(5));
387   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(6));
388 
389   TestCompletionCallback callback8;
390   ClientSocketHandle handle8;
391   int rv8 = handle8.Init(
392       group_id_, params_, std::nullopt /* proxy_annotation_tag */, HIGHEST,
393       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
394       callback8.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(),
395       NetLogWithSource());
396   EXPECT_THAT(rv8, IsError(ERR_IO_PENDING));
397   // Request  Job  Priority
398   // =======  ===  ========
399   //    2      2   HIGHEST
400   //    5      5   HIGHEST
401   //    7      3   HIGHEST
402   //    8      6   HIGHEST
403   //    4      4   MEDIUM
404   //    1      1   LOW
405   //    6          LOW
406   //    3          LOWEST
407   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
408   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(2));
409   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(3));
410   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
411   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(5));
412   EXPECT_EQ(HIGHEST,
413             session_deps_.host_resolver->request_priority(6));  // reprioritized
414 
415   // A request completes, then the socket is returned to the socket pool and
416   // goes to the highest remaining request. The job from the highest request
417   // should then be reassigned to the first request without a job.
418   session_deps_.host_resolver->ResolveNow(2);
419   EXPECT_THAT(callback2.WaitForResult(), IsOk());
420   EXPECT_TRUE(handle2.is_initialized());
421   EXPECT_TRUE(handle2.socket());
422   handle2.Reset();
423   EXPECT_THAT(callback5.WaitForResult(), IsOk());
424   EXPECT_TRUE(handle5.is_initialized());
425   EXPECT_TRUE(handle5.socket());
426   // Request  Job  Priority
427   // =======  ===  ========
428   //    7      3   HIGHEST
429   //    8      6   HIGHEST
430   //    4      4   MEDIUM
431   //    1      1   LOW
432   //    6      5   LOW
433   //    3          LOWEST
434   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
435   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(3));
436   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
437   EXPECT_EQ(LOW,
438             session_deps_.host_resolver->request_priority(5));  // reprioritized
439   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6));
440 
441   // Cancelling a request with a job reassigns the job to a lower request.
442   handle7.Reset();
443   // Request  Job  Priority
444   // =======  ===  ========
445   //    8      6   HIGHEST
446   //    4      4   MEDIUM
447   //    1      1   LOW
448   //    6      5   LOW
449   //    3      3   LOWEST
450   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
451   EXPECT_EQ(LOWEST,
452             session_deps_.host_resolver->request_priority(3));  // reprioritized
453   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(4));
454   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
455   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6));
456 
457   // Reprioritizing a request changes its job's priority.
458   pool_->SetPriority(group_id_, &handle4, LOWEST);
459   // Request  Job  Priority
460   // =======  ===  ========
461   //    8      6   HIGHEST
462   //    1      1   LOW
463   //    6      5   LOW
464   //    3      3   LOWEST
465   //    4      4   LOWEST
466   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
467   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(3));
468   EXPECT_EQ(LOWEST,
469             session_deps_.host_resolver->request_priority(4));  // reprioritized
470   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
471   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6));
472 
473   pool_->SetPriority(group_id_, &handle3, MEDIUM);
474   // Request  Job  Priority
475   // =======  ===  ========
476   //    8      6   HIGHEST
477   //    3      3   MEDIUM
478   //    1      1   LOW
479   //    6      5   LOW
480   //    4      4   LOWEST
481   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
482   EXPECT_EQ(MEDIUM,
483             session_deps_.host_resolver->request_priority(3));  // reprioritized
484   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(4));
485   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
486   EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6));
487 
488   // Host resolution finishes for a lower-down request. The highest request
489   // should get the socket and its job should be reassigned to the lower
490   // request.
491   session_deps_.host_resolver->ResolveNow(1);
492   EXPECT_THAT(callback8.WaitForResult(), IsOk());
493   EXPECT_TRUE(handle8.is_initialized());
494   EXPECT_TRUE(handle8.socket());
495   // Request  Job  Priority
496   // =======  ===  ========
497   //    3      3   MEDIUM
498   //    1      6   LOW
499   //    6      5   LOW
500   //    4      4   LOWEST
501   EXPECT_EQ(MEDIUM, session_deps_.host_resolver->request_priority(3));
502   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(4));
503   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
504   EXPECT_EQ(LOW,
505             session_deps_.host_resolver->request_priority(6));  // reprioritized
506 
507   // Host resolution finishes for the highest request. Nothing gets
508   // reprioritized.
509   session_deps_.host_resolver->ResolveNow(3);
510   EXPECT_THAT(callback3.WaitForResult(), IsOk());
511   EXPECT_TRUE(handle3.is_initialized());
512   EXPECT_TRUE(handle3.socket());
513   // Request  Job  Priority
514   // =======  ===  ========
515   //    1      6   LOW
516   //    6      5   LOW
517   //    4      4   LOWEST
518   EXPECT_EQ(LOWEST, session_deps_.host_resolver->request_priority(4));
519   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5));
520   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(6));
521 
522   session_deps_.host_resolver->ResolveAllPending();
523   EXPECT_THAT(callback1.WaitForResult(), IsOk());
524   EXPECT_TRUE(handle1.is_initialized());
525   EXPECT_TRUE(handle1.socket());
526   EXPECT_THAT(callback4.WaitForResult(), IsOk());
527   EXPECT_TRUE(handle4.is_initialized());
528   EXPECT_TRUE(handle4.socket());
529   EXPECT_THAT(callback6.WaitForResult(), IsOk());
530   EXPECT_TRUE(handle6.is_initialized());
531   EXPECT_TRUE(handle6.socket());
532 }
533 
TEST_F(TransportClientSocketPoolTest,RequestIgnoringLimitsIsReprioritized)534 TEST_F(TransportClientSocketPoolTest, RequestIgnoringLimitsIsReprioritized) {
535   TransportClientSocketPool pool(
536       kMaxSockets, 1, kUnusedIdleSocketTimeout, ProxyChain::Direct(),
537       /*is_for_websockets=*/false, common_connect_job_params_.get());
538 
539   // Creates a job which ignores limits whose priority is MAXIMUM_PRIORITY.
540   TestCompletionCallback callback1;
541   ClientSocketHandle handle1;
542   int rv1 = handle1.Init(
543       group_id_, params_, std::nullopt /* proxy_annotation_tag */,
544       MAXIMUM_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::DISABLED,
545       callback1.callback(), ClientSocketPool::ProxyAuthCallback(), &pool,
546       NetLogWithSource());
547   EXPECT_THAT(rv1, IsError(ERR_IO_PENDING));
548 
549   EXPECT_EQ(MAXIMUM_PRIORITY, session_deps_.host_resolver->request_priority(1));
550 
551   TestCompletionCallback callback2;
552   ClientSocketHandle handle2;
553   int rv2 =
554       handle2.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
555                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
556                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
557                    &pool, NetLogWithSource());
558   EXPECT_THAT(rv2, IsError(ERR_IO_PENDING));
559 
560   // |handle2| gets assigned the job, which is reprioritized.
561   handle1.Reset();
562   EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(1));
563 }
564 
TEST_F(TransportClientSocketPoolTest,InitHostResolutionFailure)565 TEST_F(TransportClientSocketPoolTest, InitHostResolutionFailure) {
566   session_deps_.host_resolver->rules()->AddSimulatedTimeoutFailure(
567       group_id_.destination().host());
568   TestCompletionCallback callback;
569   ClientSocketHandle handle;
570   EXPECT_EQ(
571       ERR_IO_PENDING,
572       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
573                   kDefaultPriority, SocketTag(),
574                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
575                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
576                   NetLogWithSource()));
577   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_NAME_NOT_RESOLVED));
578   EXPECT_THAT(handle.resolve_error_info().error, IsError(ERR_DNS_TIMED_OUT));
579   ASSERT_EQ(1u, handle.connection_attempts().size());
580   EXPECT_TRUE(handle.connection_attempts()[0].endpoint.address().empty());
581   EXPECT_THAT(handle.connection_attempts()[0].result,
582               IsError(ERR_NAME_NOT_RESOLVED));
583 }
584 
TEST_F(TransportClientSocketPoolTest,InitConnectionFailure)585 TEST_F(TransportClientSocketPoolTest, InitConnectionFailure) {
586   client_socket_factory_.set_default_client_socket_type(
587       MockTransportClientSocketFactory::Type::kFailing);
588   TestCompletionCallback callback;
589   ClientSocketHandle handle;
590   EXPECT_EQ(
591       ERR_IO_PENDING,
592       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
593                   kDefaultPriority, SocketTag(),
594                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
595                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
596                   NetLogWithSource()));
597   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED));
598   ASSERT_EQ(1u, handle.connection_attempts().size());
599   EXPECT_EQ("127.0.0.1:80",
600             handle.connection_attempts()[0].endpoint.ToString());
601   EXPECT_THAT(handle.connection_attempts()[0].result,
602               IsError(ERR_CONNECTION_FAILED));
603 
604   // Make the host resolutions complete synchronously this time.
605   session_deps_.host_resolver->set_synchronous_mode(true);
606   EXPECT_EQ(
607       ERR_CONNECTION_FAILED,
608       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
609                   kDefaultPriority, SocketTag(),
610                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
611                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
612                   NetLogWithSource()));
613   ASSERT_EQ(1u, handle.connection_attempts().size());
614   EXPECT_EQ("127.0.0.1:80",
615             handle.connection_attempts()[0].endpoint.ToString());
616   EXPECT_THAT(handle.connection_attempts()[0].result,
617               IsError(ERR_CONNECTION_FAILED));
618 }
619 
TEST_F(TransportClientSocketPoolTest,PendingRequests)620 TEST_F(TransportClientSocketPoolTest, PendingRequests) {
621   // First request finishes asynchronously.
622   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
623   EXPECT_THAT((*requests())[0]->WaitForResult(), IsOk());
624 
625   // Make all subsequent host resolutions complete synchronously.
626   session_deps_.host_resolver->set_synchronous_mode(true);
627 
628   // Rest of them finish synchronously, until we reach the per-group limit.
629   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
630   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
631   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
632   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
633   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
634 
635   // The rest are pending since we've used all active sockets.
636   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
637   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
638   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
639   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
640   EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING));
641   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
642   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
643   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
644   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
645   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
646 
647   ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE);
648 
649   EXPECT_EQ(kMaxSocketsPerGroup, client_socket_factory_.allocation_count());
650 
651   // One initial asynchronous request and then 10 pending requests.
652   EXPECT_EQ(11U, completion_count());
653 
654   // First part of requests, all with the same priority, finishes in FIFO order.
655   EXPECT_EQ(1, GetOrderOfRequest(1));
656   EXPECT_EQ(2, GetOrderOfRequest(2));
657   EXPECT_EQ(3, GetOrderOfRequest(3));
658   EXPECT_EQ(4, GetOrderOfRequest(4));
659   EXPECT_EQ(5, GetOrderOfRequest(5));
660   EXPECT_EQ(6, GetOrderOfRequest(6));
661 
662   // Make sure that rest of the requests complete in the order of priority.
663   EXPECT_EQ(7, GetOrderOfRequest(7));
664   EXPECT_EQ(14, GetOrderOfRequest(8));
665   EXPECT_EQ(15, GetOrderOfRequest(9));
666   EXPECT_EQ(10, GetOrderOfRequest(10));
667   EXPECT_EQ(13, GetOrderOfRequest(11));
668   EXPECT_EQ(8, GetOrderOfRequest(12));
669   EXPECT_EQ(16, GetOrderOfRequest(13));
670   EXPECT_EQ(11, GetOrderOfRequest(14));
671   EXPECT_EQ(12, GetOrderOfRequest(15));
672   EXPECT_EQ(9, GetOrderOfRequest(16));
673 
674   // Make sure we test order of all requests made.
675   EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds, GetOrderOfRequest(17));
676 }
677 
TEST_F(TransportClientSocketPoolTest,PendingRequests_NoKeepAlive)678 TEST_F(TransportClientSocketPoolTest, PendingRequests_NoKeepAlive) {
679   // First request finishes asynchronously.
680   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
681   EXPECT_THAT((*requests())[0]->WaitForResult(), IsOk());
682 
683   // Make all subsequent host resolutions complete synchronously.
684   session_deps_.host_resolver->set_synchronous_mode(true);
685 
686   // Rest of them finish synchronously, until we reach the per-group limit.
687   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
688   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
689   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
690   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
691   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
692 
693   // The rest are pending since we've used all active sockets.
694   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
695   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
696   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
697   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
698   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
699 
700   ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE);
701 
702   // The pending requests should finish successfully.
703   EXPECT_THAT((*requests())[6]->WaitForResult(), IsOk());
704   EXPECT_THAT((*requests())[7]->WaitForResult(), IsOk());
705   EXPECT_THAT((*requests())[8]->WaitForResult(), IsOk());
706   EXPECT_THAT((*requests())[9]->WaitForResult(), IsOk());
707   EXPECT_THAT((*requests())[10]->WaitForResult(), IsOk());
708 
709   EXPECT_EQ(static_cast<int>(requests()->size()),
710             client_socket_factory_.allocation_count());
711 
712   // First asynchronous request, and then last 5 pending requests.
713   EXPECT_EQ(6U, completion_count());
714 }
715 
716 // This test will start up a RequestSocket() and then immediately Cancel() it.
717 // The pending host resolution will eventually complete, and destroy the
718 // ClientSocketPool which will crash if the group was not cleared properly.
TEST_F(TransportClientSocketPoolTest,CancelRequestClearGroup)719 TEST_F(TransportClientSocketPoolTest, CancelRequestClearGroup) {
720   TestCompletionCallback callback;
721   ClientSocketHandle handle;
722   EXPECT_EQ(
723       ERR_IO_PENDING,
724       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
725                   kDefaultPriority, SocketTag(),
726                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
727                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
728                   NetLogWithSource()));
729   handle.Reset();
730 }
731 
TEST_F(TransportClientSocketPoolTest,TwoRequestsCancelOne)732 TEST_F(TransportClientSocketPoolTest, TwoRequestsCancelOne) {
733   ClientSocketHandle handle;
734   TestCompletionCallback callback;
735   ClientSocketHandle handle2;
736   TestCompletionCallback callback2;
737 
738   EXPECT_EQ(
739       ERR_IO_PENDING,
740       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
741                   kDefaultPriority, SocketTag(),
742                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
743                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
744                   NetLogWithSource()));
745   EXPECT_EQ(
746       ERR_IO_PENDING,
747       handle2.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
748                    kDefaultPriority, SocketTag(),
749                    ClientSocketPool::RespectLimits::ENABLED,
750                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
751                    pool_.get(), NetLogWithSource()));
752 
753   handle.Reset();
754 
755   EXPECT_THAT(callback2.WaitForResult(), IsOk());
756   handle2.Reset();
757 }
758 
TEST_F(TransportClientSocketPoolTest,ConnectCancelConnect)759 TEST_F(TransportClientSocketPoolTest, ConnectCancelConnect) {
760   client_socket_factory_.set_default_client_socket_type(
761       MockTransportClientSocketFactory::Type::kPending);
762   ClientSocketHandle handle;
763   TestCompletionCallback callback;
764   EXPECT_EQ(
765       ERR_IO_PENDING,
766       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
767                   kDefaultPriority, SocketTag(),
768                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
769                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
770                   NetLogWithSource()));
771 
772   handle.Reset();
773 
774   TestCompletionCallback callback2;
775   EXPECT_EQ(
776       ERR_IO_PENDING,
777       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
778                   kDefaultPriority, SocketTag(),
779                   ClientSocketPool::RespectLimits::ENABLED,
780                   callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
781                   pool_.get(), NetLogWithSource()));
782 
783   session_deps_.host_resolver->set_synchronous_mode(true);
784   // At this point, handle has two ConnectingSockets out for it.  Due to the
785   // setting the mock resolver into synchronous mode, the host resolution for
786   // both will return in the same loop of the MessageLoop.  The client socket
787   // is a pending socket, so the Connect() will asynchronously complete on the
788   // next loop of the MessageLoop.  That means that the first
789   // ConnectingSocket will enter OnIOComplete, and then the second one will.
790   // If the first one is not cancelled, it will advance the load state, and
791   // then the second one will crash.
792 
793   EXPECT_THAT(callback2.WaitForResult(), IsOk());
794   EXPECT_FALSE(callback.have_result());
795 
796   handle.Reset();
797 }
798 
TEST_F(TransportClientSocketPoolTest,CancelRequest)799 TEST_F(TransportClientSocketPoolTest, CancelRequest) {
800   // First request finishes asynchronously.
801   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
802   EXPECT_THAT((*requests())[0]->WaitForResult(), IsOk());
803 
804   // Make all subsequent host resolutions complete synchronously.
805   session_deps_.host_resolver->set_synchronous_mode(true);
806 
807   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
808   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
809   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
810   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
811   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk());
812 
813   // Reached per-group limit, queue up requests.
814   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
815   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
816   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
817   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
818   EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
819   EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING));
820   EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING));
821   EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING));
822   EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING));
823   EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING));
824 
825   // Cancel a request.
826   size_t index_to_cancel = kMaxSocketsPerGroup + 2;
827   EXPECT_FALSE((*requests())[index_to_cancel]->handle()->is_initialized());
828   (*requests())[index_to_cancel]->handle()->Reset();
829 
830   ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE);
831 
832   EXPECT_EQ(kMaxSocketsPerGroup,
833             client_socket_factory_.allocation_count());
834   EXPECT_EQ(requests()->size() - kMaxSocketsPerGroup, completion_count());
835 
836   EXPECT_EQ(1, GetOrderOfRequest(1));
837   EXPECT_EQ(2, GetOrderOfRequest(2));
838   EXPECT_EQ(3, GetOrderOfRequest(3));
839   EXPECT_EQ(4, GetOrderOfRequest(4));
840   EXPECT_EQ(5, GetOrderOfRequest(5));
841   EXPECT_EQ(6, GetOrderOfRequest(6));
842   EXPECT_EQ(14, GetOrderOfRequest(7));
843   EXPECT_EQ(7, GetOrderOfRequest(8));
844   EXPECT_EQ(ClientSocketPoolTest::kRequestNotFound,
845             GetOrderOfRequest(9));  // Canceled request.
846   EXPECT_EQ(9, GetOrderOfRequest(10));
847   EXPECT_EQ(10, GetOrderOfRequest(11));
848   EXPECT_EQ(11, GetOrderOfRequest(12));
849   EXPECT_EQ(8, GetOrderOfRequest(13));
850   EXPECT_EQ(12, GetOrderOfRequest(14));
851   EXPECT_EQ(13, GetOrderOfRequest(15));
852   EXPECT_EQ(15, GetOrderOfRequest(16));
853 
854   // Make sure we test order of all requests made.
855   EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds, GetOrderOfRequest(17));
856 }
857 
858 class RequestSocketCallback : public TestCompletionCallbackBase {
859  public:
RequestSocketCallback(const ClientSocketPool::GroupId & group_id,scoped_refptr<ClientSocketPool::SocketParams> socket_params,ClientSocketHandle * handle,TransportClientSocketPool * pool)860   RequestSocketCallback(
861       const ClientSocketPool::GroupId& group_id,
862       scoped_refptr<ClientSocketPool::SocketParams> socket_params,
863       ClientSocketHandle* handle,
864       TransportClientSocketPool* pool)
865       : group_id_(group_id),
866         socket_params_(socket_params),
867         handle_(handle),
868         pool_(pool) {}
869 
870   RequestSocketCallback(const RequestSocketCallback&) = delete;
871   RequestSocketCallback& operator=(const RequestSocketCallback&) = delete;
872 
873   ~RequestSocketCallback() override = default;
874 
callback()875   CompletionOnceCallback callback() {
876     return base::BindOnce(&RequestSocketCallback::OnComplete,
877                           base::Unretained(this));
878   }
879 
880  private:
OnComplete(int result)881   void OnComplete(int result) {
882     SetResult(result);
883     ASSERT_THAT(result, IsOk());
884 
885     if (!within_callback_) {
886       // Don't allow reuse of the socket.  Disconnect it and then release it and
887       // run through the MessageLoop once to get it completely released.
888       handle_->socket()->Disconnect();
889       handle_->Reset();
890       base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle();
891       within_callback_ = true;
892       int rv = handle_->Init(
893           group_id_, socket_params_, std::nullopt /* proxy_annotation_tag */,
894           LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
895           callback(), ClientSocketPool::ProxyAuthCallback(), pool_,
896           NetLogWithSource());
897       EXPECT_THAT(rv, IsOk());
898     }
899   }
900 
901   const ClientSocketPool::GroupId group_id_;
902   scoped_refptr<ClientSocketPool::SocketParams> socket_params_;
903   const raw_ptr<ClientSocketHandle> handle_;
904   const raw_ptr<TransportClientSocketPool> pool_;
905   bool within_callback_ = false;
906 };
907 
TEST_F(TransportClientSocketPoolTest,RequestTwice)908 TEST_F(TransportClientSocketPoolTest, RequestTwice) {
909   ClientSocketHandle handle;
910   RequestSocketCallback callback(group_id_, params_, &handle, pool_.get());
911   int rv =
912       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
913                   LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
914                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
915                   pool_.get(), NetLogWithSource());
916   ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
917 
918   // The callback is going to request "www.google.com". We want it to complete
919   // synchronously this time.
920   session_deps_.host_resolver->set_synchronous_mode(true);
921 
922   EXPECT_THAT(callback.WaitForResult(), IsOk());
923 
924   handle.Reset();
925 }
926 
927 // Make sure that pending requests get serviced after active requests get
928 // cancelled.
TEST_F(TransportClientSocketPoolTest,CancelActiveRequestWithPendingRequests)929 TEST_F(TransportClientSocketPoolTest, CancelActiveRequestWithPendingRequests) {
930   client_socket_factory_.set_default_client_socket_type(
931       MockTransportClientSocketFactory::Type::kPending);
932 
933   // Queue up all the requests
934   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
935   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
936   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
937   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
938   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
939   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
940   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
941   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
942   EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
943 
944   // Now, kMaxSocketsPerGroup requests should be active.  Let's cancel them.
945   ASSERT_LE(kMaxSocketsPerGroup, static_cast<int>(requests()->size()));
946   for (int i = 0; i < kMaxSocketsPerGroup; i++)
947     (*requests())[i]->handle()->Reset();
948 
949   // Let's wait for the rest to complete now.
950   for (size_t i = kMaxSocketsPerGroup; i < requests()->size(); ++i) {
951     EXPECT_THAT((*requests())[i]->WaitForResult(), IsOk());
952     (*requests())[i]->handle()->Reset();
953   }
954 
955   EXPECT_EQ(requests()->size() - kMaxSocketsPerGroup, completion_count());
956 }
957 
958 // Make sure that pending requests get serviced after active requests fail.
TEST_F(TransportClientSocketPoolTest,FailingActiveRequestWithPendingRequests)959 TEST_F(TransportClientSocketPoolTest, FailingActiveRequestWithPendingRequests) {
960   client_socket_factory_.set_default_client_socket_type(
961       MockTransportClientSocketFactory::Type::kPendingFailing);
962 
963   const int kNumRequests = 2 * kMaxSocketsPerGroup + 1;
964   ASSERT_LE(kNumRequests, kMaxSockets);  // Otherwise the test will hang.
965 
966   // Queue up all the requests
967   for (int i = 0; i < kNumRequests; i++)
968     EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING));
969 
970   for (int i = 0; i < kNumRequests; i++)
971     EXPECT_THAT((*requests())[i]->WaitForResult(),
972                 IsError(ERR_CONNECTION_FAILED));
973 }
974 
TEST_F(TransportClientSocketPoolTest,IdleSocketLoadTiming)975 TEST_F(TransportClientSocketPoolTest, IdleSocketLoadTiming) {
976   TestCompletionCallback callback;
977   ClientSocketHandle handle;
978   int rv =
979       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
980                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
981                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
982                   pool_.get(), NetLogWithSource());
983   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
984   EXPECT_FALSE(handle.is_initialized());
985   EXPECT_FALSE(handle.socket());
986 
987   EXPECT_THAT(callback.WaitForResult(), IsOk());
988   EXPECT_TRUE(handle.is_initialized());
989   EXPECT_TRUE(handle.socket());
990   TestLoadTimingInfoConnectedNotReused(handle);
991 
992   handle.Reset();
993   // Need to run all pending to release the socket back to the pool.
994   base::RunLoop().RunUntilIdle();
995 
996   // Now we should have 1 idle socket.
997   EXPECT_EQ(1, pool_->IdleSocketCount());
998 
999   rv = handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
1000                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1001                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1002                    pool_.get(), NetLogWithSource());
1003   EXPECT_THAT(rv, IsOk());
1004   EXPECT_EQ(0, pool_->IdleSocketCount());
1005   TestLoadTimingInfoConnectedReused(handle);
1006 }
1007 
TEST_F(TransportClientSocketPoolTest,CloseIdleSocketsOnIPAddressChange)1008 TEST_F(TransportClientSocketPoolTest, CloseIdleSocketsOnIPAddressChange) {
1009   TestCompletionCallback callback;
1010   ClientSocketHandle handle;
1011   int rv =
1012       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
1013                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1014                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1015                   pool_.get(), NetLogWithSource());
1016   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1017   EXPECT_FALSE(handle.is_initialized());
1018   EXPECT_FALSE(handle.socket());
1019 
1020   EXPECT_THAT(callback.WaitForResult(), IsOk());
1021   EXPECT_TRUE(handle.is_initialized());
1022   EXPECT_TRUE(handle.socket());
1023 
1024   handle.Reset();
1025 
1026   // Need to run all pending to release the socket back to the pool.
1027   base::RunLoop().RunUntilIdle();
1028 
1029   // Now we should have 1 idle socket.
1030   EXPECT_EQ(1, pool_->IdleSocketCount());
1031 
1032   // After an IP address change, we should have 0 idle sockets.
1033   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1034   base::RunLoop().RunUntilIdle();  // Notification happens async.
1035 
1036   EXPECT_EQ(0, pool_->IdleSocketCount());
1037 }
1038 
TEST(TransportClientSocketPoolStandaloneTest,DontCleanupOnIPAddressChange)1039 TEST(TransportClientSocketPoolStandaloneTest, DontCleanupOnIPAddressChange) {
1040   // This test manually sets things up in the same way
1041   // TransportClientSocketPoolTest does, but it creates a
1042   // TransportClientSocketPool with cleanup_on_ip_address_changed = false. Since
1043   // this is the only test doing this, it's not worth extending
1044   // TransportClientSocketPoolTest to support this scenario.
1045   base::test::SingleThreadTaskEnvironment task_environment;
1046   std::unique_ptr<MockCertVerifier> cert_verifier =
1047       std::make_unique<MockCertVerifier>();
1048   SpdySessionDependencies session_deps;
1049   session_deps.cert_verifier = std::move(cert_verifier);
1050   std::unique_ptr<HttpNetworkSession> http_network_session =
1051       SpdySessionDependencies::SpdyCreateSession(&session_deps);
1052   auto common_connect_job_params = std::make_unique<CommonConnectJobParams>(
1053       http_network_session->CreateCommonConnectJobParams());
1054   MockTransportClientSocketFactory client_socket_factory(NetLog::Get());
1055   common_connect_job_params->client_socket_factory = &client_socket_factory;
1056 
1057   scoped_refptr<ClientSocketPool::SocketParams> params(
1058       ClientSocketPool::SocketParams::CreateForHttpForTesting());
1059   auto pool = std::make_unique<TransportClientSocketPool>(
1060       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
1061       ProxyChain::Direct(), /*is_for_websockets=*/false,
1062       common_connect_job_params.get(),
1063       /*cleanup_on_ip_address_change=*/false);
1064   const ClientSocketPool::GroupId group_id(
1065       url::SchemeHostPort(url::kHttpScheme, "www.google.com", 80),
1066       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
1067       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1068   TestCompletionCallback callback;
1069   ClientSocketHandle handle;
1070   int rv =
1071       handle.Init(group_id, params, std::nullopt /* proxy_annotation_tag */,
1072                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1073                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1074                   pool.get(), NetLogWithSource());
1075   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1076   EXPECT_FALSE(handle.is_initialized());
1077   EXPECT_FALSE(handle.socket());
1078 
1079   EXPECT_THAT(callback.WaitForResult(), IsOk());
1080   EXPECT_TRUE(handle.is_initialized());
1081   EXPECT_TRUE(handle.socket());
1082 
1083   handle.Reset();
1084   // Need to run all pending to release the socket back to the pool.
1085   base::RunLoop().RunUntilIdle();
1086   // Now we should have 1 idle socket.
1087   EXPECT_EQ(1, pool->IdleSocketCount());
1088 
1089   // Since we set cleanup_on_ip_address_change = false, we should still have 1
1090   // idle socket after an IP address change.
1091   NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1092   base::RunLoop().RunUntilIdle();  // Notification happens async.
1093   EXPECT_EQ(1, pool->IdleSocketCount());
1094 }
1095 
TEST_F(TransportClientSocketPoolTest,SSLCertError)1096 TEST_F(TransportClientSocketPoolTest, SSLCertError) {
1097   StaticSocketDataProvider data;
1098   tagging_client_socket_factory_.AddSocketDataProvider(&data);
1099   SSLSocketDataProvider ssl(ASYNC, ERR_CERT_COMMON_NAME_INVALID);
1100   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl);
1101 
1102   const url::SchemeHostPort kEndpoint(url::kHttpsScheme, "ssl.server.test",
1103                                       443);
1104 
1105   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1106       base::MakeRefCounted<ClientSocketPool::SocketParams>(
1107           /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
1108 
1109   ClientSocketHandle handle;
1110   TestCompletionCallback callback;
1111   int rv =
1112       handle.Init(ClientSocketPool::GroupId(
1113                       kEndpoint, PrivacyMode::PRIVACY_MODE_DISABLED,
1114                       NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
1115                       /*disable_cert_network_fetches=*/false),
1116                   socket_params, std::nullopt /* proxy_annotation_tag */,
1117                   MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1118                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1119                   tagging_pool_.get(), NetLogWithSource());
1120   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1121   EXPECT_FALSE(handle.is_initialized());
1122   EXPECT_FALSE(handle.socket());
1123 
1124   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CERT_COMMON_NAME_INVALID));
1125   EXPECT_TRUE(handle.is_initialized());
1126   EXPECT_TRUE(handle.socket());
1127 }
1128 
1129 namespace {
1130 class TransportClientSocketPoolSSLConfigChangeTest
1131     : public TransportClientSocketPoolTest,
1132       public ::testing::WithParamInterface<
1133           SSLClientContext::SSLConfigChangeType> {
1134  public:
SimulateChange()1135   void SimulateChange() {
1136     switch (GetParam()) {
1137       case SSLClientContext::SSLConfigChangeType::kSSLConfigChanged:
1138         session_deps_.ssl_config_service->NotifySSLContextConfigChange();
1139         break;
1140       case SSLClientContext::SSLConfigChangeType::kCertDatabaseChanged:
1141         // TODO(mattm): For more realistic testing this should call
1142         // `CertDatabase::GetInstance()->NotifyObserversCertDBChanged()`,
1143         // however that delivers notifications asynchronously, and running
1144         // the message loop to allow the notification to be delivered allows
1145         // other parts of the tested code to advance, breaking the test
1146         // expectations.
1147         pool_->OnSSLConfigChanged(GetParam());
1148         break;
1149       case SSLClientContext::SSLConfigChangeType::kCertVerifierChanged:
1150         session_deps_.cert_verifier->SimulateOnCertVerifierChanged();
1151         break;
1152     }
1153   }
1154 
ExpectedMessage()1155   const char* ExpectedMessage() {
1156     switch (GetParam()) {
1157       case SSLClientContext::SSLConfigChangeType::kSSLConfigChanged:
1158         return TransportClientSocketPool::kNetworkChanged;
1159       case SSLClientContext::SSLConfigChangeType::kCertDatabaseChanged:
1160         return TransportClientSocketPool::kCertDatabaseChanged;
1161       case SSLClientContext::SSLConfigChangeType::kCertVerifierChanged:
1162         return TransportClientSocketPool::kCertVerifierChanged;
1163     }
1164   }
1165 };
1166 }  // namespace
1167 
TEST_P(TransportClientSocketPoolSSLConfigChangeTest,GracefulConfigChange)1168 TEST_P(TransportClientSocketPoolSSLConfigChangeTest, GracefulConfigChange) {
1169   // Create a request and finish connection of the socket, and release the
1170   // handle.
1171   {
1172     TestCompletionCallback callback;
1173     ClientSocketHandle handle1;
1174     int rv =
1175         handle1.Init(group_id_, params_, /*proxy_annotation_tag=*/std::nullopt,
1176                      LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1177                      callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1178                      pool_.get(), NetLogWithSource());
1179     EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1180     EXPECT_FALSE(handle1.is_initialized());
1181     EXPECT_FALSE(handle1.socket());
1182 
1183     EXPECT_THAT(callback.WaitForResult(), IsOk());
1184     EXPECT_TRUE(handle1.is_initialized());
1185     EXPECT_TRUE(handle1.socket());
1186     EXPECT_EQ(0, handle1.group_generation());
1187     EXPECT_EQ(0, pool_->IdleSocketCount());
1188 
1189     handle1.Reset();
1190   }
1191 
1192   // Need to run all pending to release the socket back to the pool.
1193   base::RunLoop().RunUntilIdle();
1194 
1195   // Now we should have 1 idle socket.
1196   EXPECT_EQ(1, pool_->IdleSocketCount());
1197 
1198   // Create another request and finish connection of the socket, but hold on to
1199   // the handle until later in the test.
1200   ClientSocketHandle handle2;
1201   {
1202     ClientSocketPool::GroupId group_id2(
1203         url::SchemeHostPort(url::kHttpScheme, "bar.example.com", 80),
1204         PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
1205         SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1206     TestCompletionCallback callback;
1207     int rv =
1208         handle2.Init(group_id2, params_, /*proxy_annotation_tag=*/std::nullopt,
1209                      LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1210                      callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1211                      pool_.get(), NetLogWithSource());
1212     EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1213     EXPECT_FALSE(handle2.is_initialized());
1214     EXPECT_FALSE(handle2.socket());
1215 
1216     EXPECT_THAT(callback.WaitForResult(), IsOk());
1217     EXPECT_TRUE(handle2.is_initialized());
1218     EXPECT_TRUE(handle2.socket());
1219     EXPECT_EQ(0, handle2.group_generation());
1220   }
1221 
1222   // Still only have 1 idle socket since handle2 is still alive.
1223   base::RunLoop().RunUntilIdle();
1224   EXPECT_EQ(1, pool_->IdleSocketCount());
1225 
1226   // Create a pending request but don't finish connection.
1227   ClientSocketPool::GroupId group_id3(
1228       url::SchemeHostPort(url::kHttpScheme, "foo.example.com", 80),
1229       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
1230       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1231   TestCompletionCallback callback3;
1232   ClientSocketHandle handle3;
1233   int rv =
1234       handle3.Init(group_id3, params_, /*proxy_annotation_tag=*/std::nullopt,
1235                    LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1236                    callback3.callback(), ClientSocketPool::ProxyAuthCallback(),
1237                    pool_.get(), NetLogWithSource());
1238   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1239   EXPECT_FALSE(handle3.is_initialized());
1240   EXPECT_FALSE(handle3.socket());
1241 
1242   // Do a configuration change.
1243   RecordingNetLogObserver net_log_observer;
1244   SimulateChange();
1245 
1246   // Allow handle3 to advance.
1247   base::RunLoop().RunUntilIdle();
1248   // After a configuration change, we should have 0 idle sockets. The first
1249   // idle socket should have been closed, and handle2 and handle3 are still
1250   // alive.
1251   EXPECT_EQ(0, pool_->IdleSocketCount());
1252 
1253   // Verify the netlog messages recorded the correct reason for closing the
1254   // idle sockets.
1255   auto events = net_log_observer.GetEntriesWithType(
1256       NetLogEventType::SOCKET_POOL_CLOSING_SOCKET);
1257   ASSERT_EQ(events.size(), 1u);
1258   std::string* reason = events[0].params.FindString("reason");
1259   ASSERT_TRUE(reason);
1260   EXPECT_EQ(*reason, ExpectedMessage());
1261 
1262   // The pending request for handle3 should have succeeded under the new
1263   // generation since it didn't start until after the change.
1264   EXPECT_THAT(callback3.WaitForResult(), IsOk());
1265   EXPECT_TRUE(handle3.is_initialized());
1266   EXPECT_TRUE(handle3.socket());
1267   EXPECT_EQ(1, handle3.group_generation());
1268 
1269   // After releasing handle2, it does not become an idle socket since it was
1270   // part of the first generation.
1271   handle2.Reset();
1272   base::RunLoop().RunUntilIdle();
1273   EXPECT_EQ(0, pool_->IdleSocketCount());
1274 
1275   // After releasing handle3, there is now one idle socket, since that socket
1276   // was connected during the new generation.
1277   handle3.Reset();
1278   base::RunLoop().RunUntilIdle();
1279   EXPECT_EQ(1, pool_->IdleSocketCount());
1280 }
1281 
1282 INSTANTIATE_TEST_SUITE_P(
1283     All,
1284     TransportClientSocketPoolSSLConfigChangeTest,
1285     testing::Values(
1286         SSLClientContext::SSLConfigChangeType::kSSLConfigChanged,
1287         SSLClientContext::SSLConfigChangeType::kCertDatabaseChanged,
1288         SSLClientContext::SSLConfigChangeType::kCertVerifierChanged));
1289 
TEST_F(TransportClientSocketPoolTest,BackupSocketConnect)1290 TEST_F(TransportClientSocketPoolTest, BackupSocketConnect) {
1291   // Case 1 tests the first socket stalling, and the backup connecting.
1292   MockTransportClientSocketFactory::Rule rules1[] = {
1293       // The first socket will not connect.
1294       MockTransportClientSocketFactory::Rule(
1295           MockTransportClientSocketFactory::Type::kStalled),
1296       // The second socket will connect more quickly.
1297       MockTransportClientSocketFactory::Rule(
1298           MockTransportClientSocketFactory::Type::kSynchronous),
1299   };
1300 
1301   // Case 2 tests the first socket being slow, so that we start the
1302   // second connect, but the second connect stalls, and we still
1303   // complete the first.
1304   MockTransportClientSocketFactory::Rule rules2[] = {
1305       // The first socket will connect, although delayed.
1306       MockTransportClientSocketFactory::Rule(
1307           MockTransportClientSocketFactory::Type::kDelayed),
1308       // The second socket will not connect.
1309       MockTransportClientSocketFactory::Rule(
1310           MockTransportClientSocketFactory::Type::kStalled),
1311   };
1312 
1313   base::span<const MockTransportClientSocketFactory::Rule> cases[2] = {rules1,
1314                                                                        rules2};
1315 
1316   for (auto rules : cases) {
1317     client_socket_factory_.SetRules(rules);
1318 
1319     EXPECT_EQ(0, pool_->IdleSocketCount());
1320 
1321     TestCompletionCallback callback;
1322     ClientSocketHandle handle;
1323     int rv =
1324         handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
1325                     LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1326                     callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1327                     pool_.get(), NetLogWithSource());
1328     EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1329     EXPECT_FALSE(handle.is_initialized());
1330     EXPECT_FALSE(handle.socket());
1331 
1332     // Create the first socket, set the timer.
1333     base::RunLoop().RunUntilIdle();
1334 
1335     // Wait for the backup socket timer to fire.
1336     base::PlatformThread::Sleep(
1337         base::Milliseconds(ClientSocketPool::kMaxConnectRetryIntervalMs + 50));
1338 
1339     // Let the appropriate socket connect.
1340     base::RunLoop().RunUntilIdle();
1341 
1342     EXPECT_THAT(callback.WaitForResult(), IsOk());
1343     EXPECT_TRUE(handle.is_initialized());
1344     EXPECT_TRUE(handle.socket());
1345 
1346     // One socket is stalled, the other is active.
1347     EXPECT_EQ(0, pool_->IdleSocketCount());
1348     handle.Reset();
1349 
1350     // Close all pending connect jobs and existing sockets.
1351     pool_->FlushWithError(ERR_NETWORK_CHANGED, "Network changed");
1352   }
1353 }
1354 
1355 // Test the case where a socket took long enough to start the creation
1356 // of the backup socket, but then we cancelled the request after that.
TEST_F(TransportClientSocketPoolTest,BackupSocketCancel)1357 TEST_F(TransportClientSocketPoolTest, BackupSocketCancel) {
1358   client_socket_factory_.set_default_client_socket_type(
1359       MockTransportClientSocketFactory::Type::kStalled);
1360 
1361   enum { CANCEL_BEFORE_WAIT, CANCEL_AFTER_WAIT };
1362 
1363   for (int index = CANCEL_BEFORE_WAIT; index < CANCEL_AFTER_WAIT; ++index) {
1364     EXPECT_EQ(0, pool_->IdleSocketCount());
1365 
1366     TestCompletionCallback callback;
1367     ClientSocketHandle handle;
1368     int rv =
1369         handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
1370                     LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1371                     callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1372                     pool_.get(), NetLogWithSource());
1373     EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1374     EXPECT_FALSE(handle.is_initialized());
1375     EXPECT_FALSE(handle.socket());
1376 
1377     // Create the first socket, set the timer.
1378     base::RunLoop().RunUntilIdle();
1379 
1380     if (index == CANCEL_AFTER_WAIT) {
1381       // Wait for the backup socket timer to fire.
1382       base::PlatformThread::Sleep(
1383           base::Milliseconds(ClientSocketPool::kMaxConnectRetryIntervalMs));
1384     }
1385 
1386     // Let the appropriate socket connect.
1387     base::RunLoop().RunUntilIdle();
1388 
1389     handle.Reset();
1390 
1391     EXPECT_FALSE(callback.have_result());
1392     EXPECT_FALSE(handle.is_initialized());
1393     EXPECT_FALSE(handle.socket());
1394 
1395     // One socket is stalled, the other is active.
1396     EXPECT_EQ(0, pool_->IdleSocketCount());
1397   }
1398 }
1399 
1400 // Test the case where a socket took long enough to start the creation
1401 // of the backup socket and never completes, and then the backup
1402 // connection fails.
TEST_F(TransportClientSocketPoolTest,BackupSocketFailAfterStall)1403 TEST_F(TransportClientSocketPoolTest, BackupSocketFailAfterStall) {
1404   MockTransportClientSocketFactory::Rule rules[] = {
1405       // The first socket will not connect.
1406       MockTransportClientSocketFactory::Rule(
1407           MockTransportClientSocketFactory::Type::kStalled),
1408       // The second socket will fail immediately.
1409       MockTransportClientSocketFactory::Rule(
1410           MockTransportClientSocketFactory::Type::kFailing),
1411   };
1412 
1413   client_socket_factory_.SetRules(rules);
1414 
1415   EXPECT_EQ(0, pool_->IdleSocketCount());
1416 
1417   TestCompletionCallback callback;
1418   ClientSocketHandle handle;
1419   int rv =
1420       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
1421                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1422                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1423                   pool_.get(), NetLogWithSource());
1424   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1425   EXPECT_FALSE(handle.is_initialized());
1426   EXPECT_FALSE(handle.socket());
1427 
1428   // Create the first socket, set the timer.
1429   base::RunLoop().RunUntilIdle();
1430 
1431   // Wait for the backup socket timer to fire.
1432   base::PlatformThread::Sleep(
1433       base::Milliseconds(ClientSocketPool::kMaxConnectRetryIntervalMs));
1434 
1435   // Let the second connect be synchronous. Otherwise, the emulated
1436   // host resolution takes an extra trip through the message loop.
1437   session_deps_.host_resolver->set_synchronous_mode(true);
1438 
1439   // Let the appropriate socket connect.
1440   base::RunLoop().RunUntilIdle();
1441 
1442   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED));
1443   EXPECT_FALSE(handle.is_initialized());
1444   EXPECT_FALSE(handle.socket());
1445   ASSERT_EQ(1u, handle.connection_attempts().size());
1446   EXPECT_THAT(handle.connection_attempts()[0].result,
1447               IsError(ERR_CONNECTION_FAILED));
1448   EXPECT_EQ(0, pool_->IdleSocketCount());
1449   handle.Reset();
1450 }
1451 
1452 // Test the case where a socket took long enough to start the creation
1453 // of the backup socket and eventually completes, but the backup socket
1454 // fails.
TEST_F(TransportClientSocketPoolTest,BackupSocketFailAfterDelay)1455 TEST_F(TransportClientSocketPoolTest, BackupSocketFailAfterDelay) {
1456   MockTransportClientSocketFactory::Rule rules[] = {
1457       // The first socket will connect, although delayed.
1458       MockTransportClientSocketFactory::Rule(
1459           MockTransportClientSocketFactory::Type::kDelayed),
1460       // The second socket will not connect.
1461       MockTransportClientSocketFactory::Rule(
1462           MockTransportClientSocketFactory::Type::kFailing),
1463   };
1464 
1465   client_socket_factory_.SetRules(rules);
1466   client_socket_factory_.set_delay(base::Seconds(5));
1467 
1468   EXPECT_EQ(0, pool_->IdleSocketCount());
1469 
1470   TestCompletionCallback callback;
1471   ClientSocketHandle handle;
1472   int rv =
1473       handle.Init(group_id_, params_, std::nullopt /* proxy_annotation_tag */,
1474                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1475                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
1476                   pool_.get(), NetLogWithSource());
1477   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
1478   EXPECT_FALSE(handle.is_initialized());
1479   EXPECT_FALSE(handle.socket());
1480 
1481   // Create the first socket, set the timer.
1482   base::RunLoop().RunUntilIdle();
1483 
1484   // Wait for the backup socket timer to fire.
1485   base::PlatformThread::Sleep(
1486       base::Milliseconds(ClientSocketPool::kMaxConnectRetryIntervalMs));
1487 
1488   // Let the second connect be synchronous. Otherwise, the emulated
1489   // host resolution takes an extra trip through the message loop.
1490   session_deps_.host_resolver->set_synchronous_mode(true);
1491 
1492   // Let the appropriate socket connect.
1493   base::RunLoop().RunUntilIdle();
1494 
1495   EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED));
1496   EXPECT_FALSE(handle.is_initialized());
1497   EXPECT_FALSE(handle.socket());
1498   ASSERT_EQ(1u, handle.connection_attempts().size());
1499   EXPECT_THAT(handle.connection_attempts()[0].result,
1500               IsError(ERR_CONNECTION_FAILED));
1501   handle.Reset();
1502 }
1503 
1504 // Test the case that SOCKSSocketParams are provided.
TEST_F(TransportClientSocketPoolTest,SOCKS)1505 TEST_F(TransportClientSocketPoolTest, SOCKS) {
1506   const url::SchemeHostPort kDestination(url::kHttpScheme, "host", 80);
1507 
1508   TransportClientSocketPool proxy_pool(
1509       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
1510       ProxyUriToProxyChain("socks5://foopy",
1511                            /*default_scheme=*/ProxyServer::SCHEME_HTTP),
1512       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
1513 
1514   for (IoMode socket_io_mode : {SYNCHRONOUS, ASYNC}) {
1515     scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1516         ClientSocketPool::SocketParams::CreateForHttpForTesting();
1517 
1518     SOCKS5MockData data(socket_io_mode);
1519     data.data_provider()->set_connect_data(MockConnect(socket_io_mode, OK));
1520     tagging_client_socket_factory_.AddSocketDataProvider(data.data_provider());
1521     ClientSocketHandle handle;
1522     TestCompletionCallback callback;
1523     int rv = handle.Init(
1524         ClientSocketPool::GroupId(
1525             kDestination, PrivacyMode::PRIVACY_MODE_DISABLED,
1526             NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
1527             /*disable_cert_network_fetches=*/false),
1528         socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1529         ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1530         ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
1531     EXPECT_THAT(callback.GetResult(rv), IsOk());
1532     EXPECT_TRUE(handle.is_initialized());
1533     EXPECT_TRUE(handle.socket());
1534     EXPECT_TRUE(data.data_provider()->AllReadDataConsumed());
1535     EXPECT_TRUE(data.data_provider()->AllWriteDataConsumed());
1536   }
1537 }
1538 
1539 // Make sure there's no crash when an auth challenge is received over HTTP2
1540 // and there are two pending Requests to the socket pool, with a single
1541 // ConnectJob.
1542 //
1543 // See https://crbug.com/940848
TEST_F(TransportClientSocketPoolTest,SpdyOneConnectJobTwoRequestsError)1544 TEST_F(TransportClientSocketPoolTest, SpdyOneConnectJobTwoRequestsError) {
1545   const url::SchemeHostPort kEndpoint(url::kHttpsScheme,
1546                                       "unresolvable.host.name", 443);
1547 
1548   session_deps_.host_resolver->set_synchronous_mode(true);
1549 
1550   // Create a socket pool which only allows a single connection at a time.
1551   TransportClientSocketPool pool(
1552       1, 1, kUnusedIdleSocketTimeout,
1553       ProxyUriToProxyChain("https://unresolvable.proxy.name",
1554                            /*default_scheme=*/ProxyServer::SCHEME_HTTP),
1555       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
1556 
1557   // First connection attempt will get an error after creating the SpdyStream.
1558 
1559   SpdyTestUtil spdy_util;
1560   spdy::SpdySerializedFrame connect(spdy_util.ConstructSpdyConnect(
1561       nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
1562       HostPortPair::FromSchemeHostPort(kEndpoint)));
1563 
1564   MockWrite writes[] = {
1565       CreateMockWrite(connect, 0, ASYNC),
1566       MockWrite(SYNCHRONOUS, ERR_IO_PENDING, 2),
1567   };
1568 
1569   MockRead reads[] = {
1570       MockRead(ASYNC, ERR_FAILED, 1),
1571   };
1572 
1573   SequencedSocketData socket_data(MockConnect(SYNCHRONOUS, OK), reads, writes);
1574   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data);
1575   SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK);
1576   ssl_data.next_proto = kProtoHTTP2;
1577   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
1578 
1579   // Second connection also fails.  Not a vital part of this test, but allows
1580   // waiting for the second request to complete without too much extra code.
1581   SequencedSocketData socket_data2(
1582       MockConnect(SYNCHRONOUS, ERR_CONNECTION_TIMED_OUT),
1583       base::span<const MockRead>(), base::span<const MockWrite>());
1584   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data2);
1585   SSLSocketDataProvider ssl_data2(SYNCHRONOUS, OK);
1586   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data2);
1587 
1588   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1589       base::MakeRefCounted<ClientSocketPool::SocketParams>(
1590           /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
1591 
1592   ClientSocketPool::GroupId group_id(
1593       kEndpoint, PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
1594       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1595 
1596   // Start the first connection attempt.
1597   TestCompletionCallback callback1;
1598   ClientSocketHandle handle1;
1599   int rv1 = handle1.Init(
1600       group_id, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, HIGHEST,
1601       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1602       callback1.callback(), ClientSocketPool::ProxyAuthCallback(), &pool,
1603       NetLogWithSource());
1604   ASSERT_THAT(rv1, IsError(ERR_IO_PENDING));
1605 
1606   // Create a second request with a lower priority.
1607   TestCompletionCallback callback2;
1608   ClientSocketHandle handle2;
1609   int rv2 = handle2.Init(
1610       group_id, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOWEST,
1611       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1612       callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool,
1613       NetLogWithSource());
1614   ASSERT_THAT(rv2, IsError(ERR_IO_PENDING));
1615 
1616   // First connection fails after creating a SpdySession and a SpdyStream on
1617   // that session. The SpdyStream will be destroyed under the
1618   // SpdyProxyClientSocket. The failure will result in temporarily assigning the
1619   // failed ConnectJob to the second request, which results in an unneeded
1620   // reprioritization, which should not dereference the null SpdyStream.
1621   //
1622   // TODO(mmenke): Avoid that temporary reassignment.
1623   ASSERT_THAT(callback1.WaitForResult(), IsError(ERR_FAILED));
1624 
1625   // Second connection fails, getting a connection error.
1626   ASSERT_THAT(callback2.WaitForResult(), IsError(ERR_PROXY_CONNECTION_FAILED));
1627 }
1628 
1629 // Make sure there's no crash when an auth challenge is received over HTTP2
1630 // and there are two pending Requests to the socket pool, with a single
1631 // ConnectJob.
1632 //
1633 // See https://crbug.com/940848
TEST_F(TransportClientSocketPoolTest,SpdyAuthOneConnectJobTwoRequests)1634 TEST_F(TransportClientSocketPoolTest, SpdyAuthOneConnectJobTwoRequests) {
1635   const url::SchemeHostPort kEndpoint(url::kHttpsScheme,
1636                                       "unresolvable.host.name", 443);
1637   const HostPortPair kProxy("unresolvable.proxy.name", 443);
1638 
1639   session_deps_.host_resolver->set_synchronous_mode(true);
1640 
1641   // Create a socket pool which only allows a single connection at a time.
1642   TransportClientSocketPool pool(
1643       1, 1, kUnusedIdleSocketTimeout,
1644       ProxyUriToProxyChain("https://unresolvable.proxy.name",
1645                            /*default_scheme=*/ProxyServer::SCHEME_HTTP),
1646       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
1647 
1648   SpdyTestUtil spdy_util;
1649   spdy::SpdySerializedFrame connect(spdy_util.ConstructSpdyConnect(
1650       nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
1651       HostPortPair::FromSchemeHostPort(kEndpoint)));
1652 
1653   MockWrite writes[] = {
1654       CreateMockWrite(connect, 0, ASYNC),
1655       MockWrite(SYNCHRONOUS, ERR_IO_PENDING, 4),
1656   };
1657 
1658   // The proxy responds to the connect with a 407, and them an
1659   // ERROR_CODE_HTTP_1_1_REQUIRED.
1660 
1661   const char kAuthStatus[] = "407";
1662   const char* const kAuthChallenge[] = {
1663       "proxy-authenticate",
1664       "NTLM",
1665   };
1666   spdy::SpdySerializedFrame connect_auth_resp(spdy_util.ConstructSpdyReplyError(
1667       kAuthStatus, kAuthChallenge, std::size(kAuthChallenge) / 2, 1));
1668   spdy::SpdySerializedFrame reset(
1669       spdy_util.ConstructSpdyRstStream(1, spdy::ERROR_CODE_HTTP_1_1_REQUIRED));
1670   MockRead reads[] = {
1671       CreateMockRead(connect_auth_resp, 1, ASYNC),
1672       CreateMockRead(reset, 2, SYNCHRONOUS),
1673       MockRead(SYNCHRONOUS, ERR_IO_PENDING, 3),
1674   };
1675 
1676   SequencedSocketData socket_data(MockConnect(SYNCHRONOUS, OK), reads, writes);
1677   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data);
1678   SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK);
1679   ssl_data.next_proto = kProtoHTTP2;
1680   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
1681 
1682   // Second connection fails, and gets a different error.  Not a vital part of
1683   // this test, but allows waiting for the second request to complete without
1684   // too much extra code.
1685   SequencedSocketData socket_data2(
1686       MockConnect(SYNCHRONOUS, ERR_CONNECTION_TIMED_OUT),
1687       base::span<const MockRead>(), base::span<const MockWrite>());
1688   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data2);
1689   SSLSocketDataProvider ssl_data2(SYNCHRONOUS, OK);
1690   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data2);
1691 
1692   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1693       base::MakeRefCounted<ClientSocketPool::SocketParams>(
1694           /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
1695 
1696   ClientSocketPool::GroupId group_id(
1697       kEndpoint, PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
1698       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1699 
1700   // Start the first connection attempt.
1701   TestCompletionCallback callback1;
1702   ClientSocketHandle handle1;
1703   base::RunLoop run_loop;
1704   int rv1 = handle1.Init(group_id, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS,
1705                          HIGHEST, SocketTag(),
1706                          ClientSocketPool::RespectLimits::ENABLED,
1707                          callback1.callback(),
1708                          base::BindLambdaForTesting(
1709                              [&](const HttpResponseInfo& response,
1710                                  HttpAuthController* auth_controller,
1711                                  base::OnceClosure restart_with_auth_callback) {
1712                                run_loop.Quit();
1713                              }),
1714                          &pool, NetLogWithSource());
1715   ASSERT_THAT(rv1, IsError(ERR_IO_PENDING));
1716 
1717   // Create a second request with a lower priority.
1718   TestCompletionCallback callback2;
1719   ClientSocketHandle handle2;
1720   int rv2 = handle2.Init(
1721       group_id, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOWEST,
1722       SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
1723       callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool,
1724       NetLogWithSource());
1725   ASSERT_THAT(rv2, IsError(ERR_IO_PENDING));
1726 
1727   // The ConnectJob connection sees the auth challenge and HTTP2 error, which
1728   // causes the SpdySession to be destroyed, as well as the SpdyStream. Then the
1729   // ConnectJob is bound to the first request. Binding the request will result
1730   // in temporarily assigning the ConnectJob to the second request, which
1731   // results in an unneeded reprioritization, which should not dereference the
1732   // null SpdyStream.
1733   //
1734   // TODO(mmenke): Avoid that temporary reassignment.
1735   run_loop.Run();
1736 
1737   // Just tear down everything without continuing - there are other tests for
1738   // auth over HTTP2.
1739 }
1740 
TEST_F(TransportClientSocketPoolTest,HttpTunnelSetupRedirect)1741 TEST_F(TransportClientSocketPoolTest, HttpTunnelSetupRedirect) {
1742   const url::SchemeHostPort kEndpoint(url::kHttpsScheme, "host.test", 443);
1743 
1744   const std::string kRedirectTarget = "https://some.other.host.test/";
1745 
1746   const std::string kResponseText =
1747       "HTTP/1.1 302 Found\r\n"
1748       "Location: " +
1749       kRedirectTarget +
1750       "\r\n"
1751       "Set-Cookie: foo=bar\r\n"
1752       "\r\n";
1753 
1754   for (IoMode io_mode : {SYNCHRONOUS, ASYNC}) {
1755     SCOPED_TRACE(io_mode);
1756     session_deps_.host_resolver->set_synchronous_mode(io_mode == SYNCHRONOUS);
1757 
1758     for (bool use_https_proxy : {false, true}) {
1759       SCOPED_TRACE(use_https_proxy);
1760 
1761       TransportClientSocketPool proxy_pool(
1762           kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
1763           ProxyUriToProxyChain(
1764               use_https_proxy ? "https://proxy.test" : "http://proxy.test",
1765               /*default_scheme=*/ProxyServer::SCHEME_HTTP),
1766           /*is_for_websockets=*/false,
1767           tagging_common_connect_job_params_.get());
1768 
1769       MockWrite writes[] = {
1770           MockWrite(ASYNC, 0,
1771                     "CONNECT host.test:443 HTTP/1.1\r\n"
1772                     "Host: host.test:443\r\n"
1773                     "Proxy-Connection: keep-alive\r\n\r\n"),
1774       };
1775       MockRead reads[] = {
1776           MockRead(ASYNC, 1, kResponseText.c_str()),
1777       };
1778 
1779       SequencedSocketData data(reads, writes);
1780       tagging_client_socket_factory_.AddSocketDataProvider(&data);
1781       SSLSocketDataProvider ssl(ASYNC, OK);
1782       tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl);
1783 
1784       ClientSocketHandle handle;
1785       TestCompletionCallback callback;
1786 
1787       scoped_refptr<ClientSocketPool::SocketParams> socket_params =
1788           base::MakeRefCounted<ClientSocketPool::SocketParams>(
1789               /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
1790 
1791       int rv = handle.Init(
1792           ClientSocketPool::GroupId(
1793               kEndpoint, PrivacyMode::PRIVACY_MODE_DISABLED,
1794               NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
1795               /*disable_cert_network_fetches=*/false),
1796           socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1797           ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1798           ClientSocketPool::ProxyAuthCallback(), &proxy_pool,
1799           NetLogWithSource());
1800       rv = callback.GetResult(rv);
1801 
1802       // We don't trust 302 responses to CONNECT.
1803       EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
1804       EXPECT_FALSE(handle.is_initialized());
1805     }
1806   }
1807 }
1808 
TEST_F(TransportClientSocketPoolTest,NetworkAnonymizationKey)1809 TEST_F(TransportClientSocketPoolTest, NetworkAnonymizationKey) {
1810   const SchemefulSite kSite(GURL("https://foo.test/"));
1811   const auto kNetworkAnonymizationKey =
1812       NetworkAnonymizationKey::CreateSameSite(kSite);
1813   const char kHost[] = "bar.test";
1814 
1815   base::test::ScopedFeatureList scoped_feature_list;
1816   scoped_feature_list.InitWithFeatures(
1817       // enabled_features
1818       {features::kPartitionConnectionsByNetworkIsolationKey,
1819        features::kSplitHostCacheByNetworkIsolationKey},
1820       // disabled_features
1821       {});
1822 
1823   session_deps_.host_resolver->set_ondemand_mode(true);
1824 
1825   TransportClientSocketPool::GroupId group_id(
1826       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
1827       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey,
1828       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1829   ClientSocketHandle handle;
1830   TestCompletionCallback callback;
1831   EXPECT_THAT(
1832       handle.Init(group_id,
1833                   ClientSocketPool::SocketParams::CreateForHttpForTesting(),
1834                   TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1835                   ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1836                   ClientSocketPool::ProxyAuthCallback(), pool_.get(),
1837                   NetLogWithSource()),
1838       IsError(ERR_IO_PENDING));
1839 
1840   ASSERT_EQ(1u, session_deps_.host_resolver->last_id());
1841   EXPECT_EQ(kHost, session_deps_.host_resolver->request_host(1));
1842   EXPECT_EQ(kNetworkAnonymizationKey,
1843             session_deps_.host_resolver->request_network_anonymization_key(1));
1844 }
1845 
TEST_F(TransportClientSocketPoolTest,NetworkAnonymizationKeySsl)1846 TEST_F(TransportClientSocketPoolTest, NetworkAnonymizationKeySsl) {
1847   const SchemefulSite kSite(GURL("https://foo.test/"));
1848   const auto kNetworkAnonymizationKey =
1849       NetworkAnonymizationKey::CreateSameSite(kSite);
1850   const char kHost[] = "bar.test";
1851 
1852   base::test::ScopedFeatureList scoped_feature_list;
1853   scoped_feature_list.InitWithFeatures(
1854       // enabled_features
1855       {features::kPartitionConnectionsByNetworkIsolationKey,
1856        features::kSplitHostCacheByNetworkIsolationKey},
1857       // disabled_features
1858       {});
1859 
1860   session_deps_.host_resolver->set_ondemand_mode(true);
1861 
1862   TransportClientSocketPool::GroupId group_id(
1863       url::SchemeHostPort(url::kHttpsScheme, kHost, 443),
1864       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey,
1865       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1866   ClientSocketHandle handle;
1867   TestCompletionCallback callback;
1868   EXPECT_THAT(
1869       handle.Init(
1870           group_id,
1871           base::MakeRefCounted<ClientSocketPool::SocketParams>(
1872               /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>()),
1873           TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1874           ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
1875           ClientSocketPool::ProxyAuthCallback(), pool_.get(),
1876           NetLogWithSource()),
1877       IsError(ERR_IO_PENDING));
1878 
1879   ASSERT_EQ(1u, session_deps_.host_resolver->last_id());
1880   EXPECT_EQ(kHost, session_deps_.host_resolver->request_host(1));
1881   EXPECT_EQ(kNetworkAnonymizationKey,
1882             session_deps_.host_resolver->request_network_anonymization_key(1));
1883 }
1884 
1885 // Test that, in the case of an HTTP proxy, the same transient
1886 // NetworkAnonymizationKey is reused for resolving the proxy's host, regardless
1887 // of input NAK.
TEST_F(TransportClientSocketPoolTest,NetworkAnonymizationKeyHttpProxy)1888 TEST_F(TransportClientSocketPoolTest, NetworkAnonymizationKeyHttpProxy) {
1889   const SchemefulSite kSite1(GURL("https://foo.test/"));
1890   const auto kNetworkAnonymizationKey1 =
1891       NetworkAnonymizationKey::CreateSameSite(kSite1);
1892   const SchemefulSite kSite2(GURL("https://bar.test/"));
1893   const auto kNetworkAnonymizationKey2 =
1894       NetworkAnonymizationKey::CreateSameSite(kSite2);
1895   const char kHost[] = "bar.test";
1896   const ProxyChain kProxyChain = ProxyUriToProxyChain(
1897       "http://proxy.test", /*default_scheme=*/ProxyServer::SCHEME_HTTP);
1898 
1899   base::test::ScopedFeatureList scoped_feature_list;
1900   scoped_feature_list.InitWithFeatures(
1901       // enabled_features
1902       {features::kPartitionConnectionsByNetworkIsolationKey,
1903        features::kSplitHostCacheByNetworkIsolationKey},
1904       // disabled_features
1905       {});
1906 
1907   session_deps_.host_resolver->set_ondemand_mode(true);
1908 
1909   TransportClientSocketPool proxy_pool(
1910       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, kProxyChain,
1911       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
1912 
1913   TransportClientSocketPool::GroupId group_id1(
1914       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
1915       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey1,
1916       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1917   ClientSocketHandle handle1;
1918   TestCompletionCallback callback1;
1919   EXPECT_THAT(
1920       handle1.Init(group_id1,
1921                    ClientSocketPool::SocketParams::CreateForHttpForTesting(),
1922                    TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1923                    ClientSocketPool::RespectLimits::ENABLED,
1924                    callback1.callback(), ClientSocketPool::ProxyAuthCallback(),
1925                    &proxy_pool, NetLogWithSource()),
1926       IsError(ERR_IO_PENDING));
1927 
1928   TransportClientSocketPool::GroupId group_id2(
1929       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
1930       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey2,
1931       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1932   ClientSocketHandle handle2;
1933   TestCompletionCallback callback2;
1934   EXPECT_THAT(
1935       handle2.Init(group_id2,
1936                    ClientSocketPool::SocketParams::CreateForHttpForTesting(),
1937                    TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1938                    ClientSocketPool::RespectLimits::ENABLED,
1939                    callback1.callback(), ClientSocketPool::ProxyAuthCallback(),
1940                    &proxy_pool, NetLogWithSource()),
1941       IsError(ERR_IO_PENDING));
1942 
1943   ASSERT_EQ(2u, session_deps_.host_resolver->last_id());
1944   EXPECT_EQ(kProxyChain.First().host_port_pair().host(),
1945             session_deps_.host_resolver->request_host(1));
1946   EXPECT_EQ(kProxyChain.First().host_port_pair().host(),
1947             session_deps_.host_resolver->request_host(2));
1948   EXPECT_TRUE(session_deps_.host_resolver->request_network_anonymization_key(1)
1949                   .IsTransient());
1950   EXPECT_EQ(session_deps_.host_resolver->request_network_anonymization_key(1),
1951             session_deps_.host_resolver->request_network_anonymization_key(2));
1952 }
1953 
1954 // Test that, in the case of an HTTPS proxy, the same transient
1955 // NetworkAnonymizationKey is reused for resolving the proxy's host, regardless
1956 // of input NAK.
TEST_F(TransportClientSocketPoolTest,NetworkAnonymizationKeyHttpsProxy)1957 TEST_F(TransportClientSocketPoolTest, NetworkAnonymizationKeyHttpsProxy) {
1958   const SchemefulSite kSite1(GURL("https://foo.test/"));
1959   const auto kNetworkAnonymizationKey1 =
1960       NetworkAnonymizationKey::CreateSameSite(kSite1);
1961   const SchemefulSite kSite2(GURL("https://bar.test/"));
1962   const auto kNetworkAnonymizationKey2 =
1963       NetworkAnonymizationKey::CreateSameSite(kSite2);
1964   const char kHost[] = "bar.test";
1965   const ProxyChain kProxyChain = ProxyUriToProxyChain(
1966       "https://proxy.test", /*default_scheme=*/ProxyServer::SCHEME_HTTP);
1967 
1968   base::test::ScopedFeatureList scoped_feature_list;
1969   scoped_feature_list.InitWithFeatures(
1970       // enabled_features
1971       {features::kPartitionConnectionsByNetworkIsolationKey,
1972        features::kSplitHostCacheByNetworkIsolationKey},
1973       // disabled_features
1974       {});
1975 
1976   session_deps_.host_resolver->set_ondemand_mode(true);
1977 
1978   TransportClientSocketPool proxy_pool(
1979       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, kProxyChain,
1980       false /* is_for_websockets */, tagging_common_connect_job_params_.get());
1981 
1982   TransportClientSocketPool::GroupId group_id1(
1983       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
1984       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey1,
1985       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
1986   ClientSocketHandle handle1;
1987   TestCompletionCallback callback1;
1988   EXPECT_THAT(
1989       handle1.Init(group_id1,
1990                    ClientSocketPool::SocketParams::CreateForHttpForTesting(),
1991                    TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
1992                    ClientSocketPool::RespectLimits::ENABLED,
1993                    callback1.callback(), ClientSocketPool::ProxyAuthCallback(),
1994                    &proxy_pool, NetLogWithSource()),
1995       IsError(ERR_IO_PENDING));
1996 
1997   TransportClientSocketPool::GroupId group_id2(
1998       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
1999       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey2,
2000       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2001   ClientSocketHandle handle2;
2002   TestCompletionCallback callback2;
2003   EXPECT_THAT(
2004       handle2.Init(group_id2,
2005                    ClientSocketPool::SocketParams::CreateForHttpForTesting(),
2006                    TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
2007                    ClientSocketPool::RespectLimits::ENABLED,
2008                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2009                    &proxy_pool, NetLogWithSource()),
2010       IsError(ERR_IO_PENDING));
2011 
2012   ASSERT_EQ(2u, session_deps_.host_resolver->last_id());
2013   EXPECT_EQ(kProxyChain.First().host_port_pair().host(),
2014             session_deps_.host_resolver->request_host(1));
2015   EXPECT_EQ(kProxyChain.First().host_port_pair().host(),
2016             session_deps_.host_resolver->request_host(2));
2017   EXPECT_TRUE(session_deps_.host_resolver->request_network_anonymization_key(1)
2018                   .IsTransient());
2019   EXPECT_EQ(session_deps_.host_resolver->request_network_anonymization_key(1),
2020             session_deps_.host_resolver->request_network_anonymization_key(2));
2021 }
2022 
2023 // Test that, in the case of a SOCKS5 proxy, the passed in
2024 // NetworkAnonymizationKey is used for the destination DNS lookup, and the same
2025 // transient NetworkAnonymizationKey is reused for resolving the proxy's host,
2026 // regardless of input NAK.
TEST_F(TransportClientSocketPoolTest,NetworkAnonymizationKeySocks4Proxy)2027 TEST_F(TransportClientSocketPoolTest, NetworkAnonymizationKeySocks4Proxy) {
2028   const SchemefulSite kSite1(GURL("https://foo.test/"));
2029   const auto kNetworkAnonymizationKey1 =
2030       NetworkAnonymizationKey::CreateSameSite(kSite1);
2031   const SchemefulSite kSite2(GURL("https://bar.test/"));
2032   const auto kNetworkAnonymizationKey2 =
2033       NetworkAnonymizationKey::CreateSameSite(kSite2);
2034   const char kHost[] = "bar.test";
2035   const ProxyChain kProxyChain = ProxyUriToProxyChain(
2036       "socks4://proxy.test", /*default_scheme=*/ProxyServer::SCHEME_HTTP);
2037 
2038   base::test::ScopedFeatureList scoped_feature_list;
2039   scoped_feature_list.InitWithFeatures(
2040       // enabled_features
2041       {features::kPartitionConnectionsByNetworkIsolationKey,
2042        features::kSplitHostCacheByNetworkIsolationKey},
2043       // disabled_features
2044       {});
2045 
2046   session_deps_.host_resolver->set_ondemand_mode(true);
2047 
2048   // Test will establish two connections, but never use them to transfer data,
2049   // since thet stall on the followup DNS lookups.
2050   StaticSocketDataProvider data1;
2051   data1.set_connect_data(MockConnect(SYNCHRONOUS, OK));
2052   tagging_client_socket_factory_.AddSocketDataProvider(&data1);
2053   StaticSocketDataProvider data2;
2054   data2.set_connect_data(MockConnect(SYNCHRONOUS, OK));
2055   tagging_client_socket_factory_.AddSocketDataProvider(&data2);
2056 
2057   TransportClientSocketPool proxy_pool(
2058       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, kProxyChain,
2059       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
2060 
2061   TransportClientSocketPool::GroupId group_id1(
2062       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
2063       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey1,
2064       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2065   ClientSocketHandle handle1;
2066   TestCompletionCallback callback1;
2067   EXPECT_THAT(
2068       handle1.Init(group_id1,
2069                    ClientSocketPool::SocketParams::CreateForHttpForTesting(),
2070                    TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
2071                    ClientSocketPool::RespectLimits::ENABLED,
2072                    callback1.callback(), ClientSocketPool::ProxyAuthCallback(),
2073                    &proxy_pool, NetLogWithSource()),
2074       IsError(ERR_IO_PENDING));
2075 
2076   TransportClientSocketPool::GroupId group_id2(
2077       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
2078       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey2,
2079       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2080   ClientSocketHandle handle2;
2081   TestCompletionCallback callback2;
2082   EXPECT_THAT(
2083       handle2.Init(group_id2,
2084                    ClientSocketPool::SocketParams::CreateForHttpForTesting(),
2085                    TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
2086                    ClientSocketPool::RespectLimits::ENABLED,
2087                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2088                    &proxy_pool, NetLogWithSource()),
2089       IsError(ERR_IO_PENDING));
2090 
2091   // First two lookups are for the proxy's hostname, and should use the same
2092   // transient NAK.
2093   ASSERT_EQ(2u, session_deps_.host_resolver->last_id());
2094   EXPECT_EQ(kProxyChain.First().host_port_pair().host(),
2095             session_deps_.host_resolver->request_host(1));
2096   EXPECT_EQ(kProxyChain.First().host_port_pair().host(),
2097             session_deps_.host_resolver->request_host(2));
2098   EXPECT_TRUE(session_deps_.host_resolver->request_network_anonymization_key(1)
2099                   .IsTransient());
2100   EXPECT_EQ(session_deps_.host_resolver->request_network_anonymization_key(1),
2101             session_deps_.host_resolver->request_network_anonymization_key(2));
2102 
2103   // First two lookups completes, starting the next two, which should be for the
2104   // destination's hostname, and should use the passed in NAKs.
2105   session_deps_.host_resolver->ResolveNow(1);
2106   session_deps_.host_resolver->ResolveNow(2);
2107   ASSERT_EQ(4u, session_deps_.host_resolver->last_id());
2108   EXPECT_EQ(kHost, session_deps_.host_resolver->request_host(3));
2109   EXPECT_EQ(kNetworkAnonymizationKey1,
2110             session_deps_.host_resolver->request_network_anonymization_key(3));
2111   EXPECT_EQ(kHost, session_deps_.host_resolver->request_host(4));
2112   EXPECT_EQ(kNetworkAnonymizationKey2,
2113             session_deps_.host_resolver->request_network_anonymization_key(4));
2114 }
2115 
2116 // Test that, in the case of a SOCKS5 proxy, the same transient
2117 // NetworkAnonymizationKey is reused for resolving the proxy's host, regardless
2118 // of input NAK.
TEST_F(TransportClientSocketPoolTest,NetworkAnonymizationKeySocks5Proxy)2119 TEST_F(TransportClientSocketPoolTest, NetworkAnonymizationKeySocks5Proxy) {
2120   const SchemefulSite kSite1(GURL("https://foo.test/"));
2121   const auto kNetworkAnonymizationKey1 =
2122       NetworkAnonymizationKey::CreateSameSite(kSite1);
2123   const SchemefulSite kSite2(GURL("https://bar.test/"));
2124   const auto kNetworkAnonymizationKey2 =
2125       NetworkAnonymizationKey::CreateSameSite(kSite2);
2126   const char kHost[] = "bar.test";
2127   const ProxyChain kProxyChain = ProxyUriToProxyChain(
2128       "socks5://proxy.test", /*default_scheme=*/ProxyServer::SCHEME_HTTP);
2129 
2130   base::test::ScopedFeatureList scoped_feature_list;
2131   scoped_feature_list.InitWithFeatures(
2132       // enabled_features
2133       {features::kPartitionConnectionsByNetworkIsolationKey,
2134        features::kSplitHostCacheByNetworkIsolationKey},
2135       // disabled_features
2136       {});
2137 
2138   session_deps_.host_resolver->set_ondemand_mode(true);
2139 
2140   TransportClientSocketPool proxy_pool(
2141       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout, kProxyChain,
2142       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
2143 
2144   TransportClientSocketPool::GroupId group_id1(
2145       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
2146       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey1,
2147       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2148   ClientSocketHandle handle1;
2149   TestCompletionCallback callback1;
2150   EXPECT_THAT(
2151       handle1.Init(group_id1,
2152                    ClientSocketPool::SocketParams::CreateForHttpForTesting(),
2153                    TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
2154                    ClientSocketPool::RespectLimits::ENABLED,
2155                    callback1.callback(), ClientSocketPool::ProxyAuthCallback(),
2156                    &proxy_pool, NetLogWithSource()),
2157       IsError(ERR_IO_PENDING));
2158 
2159   TransportClientSocketPool::GroupId group_id2(
2160       url::SchemeHostPort(url::kHttpScheme, kHost, 80),
2161       PrivacyMode::PRIVACY_MODE_DISABLED, kNetworkAnonymizationKey2,
2162       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2163   ClientSocketHandle handle2;
2164   TestCompletionCallback callback2;
2165   EXPECT_THAT(
2166       handle2.Init(group_id2,
2167                    ClientSocketPool::SocketParams::CreateForHttpForTesting(),
2168                    TRAFFIC_ANNOTATION_FOR_TESTS, LOW, SocketTag(),
2169                    ClientSocketPool::RespectLimits::ENABLED,
2170                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2171                    &proxy_pool, NetLogWithSource()),
2172       IsError(ERR_IO_PENDING));
2173 
2174   ASSERT_EQ(2u, session_deps_.host_resolver->last_id());
2175   EXPECT_EQ(kProxyChain.First().host_port_pair().host(),
2176             session_deps_.host_resolver->request_host(1));
2177   EXPECT_EQ(kProxyChain.First().host_port_pair().host(),
2178             session_deps_.host_resolver->request_host(2));
2179   EXPECT_TRUE(session_deps_.host_resolver->request_network_anonymization_key(1)
2180                   .IsTransient());
2181   EXPECT_EQ(session_deps_.host_resolver->request_network_anonymization_key(1),
2182             session_deps_.host_resolver->request_network_anonymization_key(2));
2183 }
2184 
TEST_F(TransportClientSocketPoolTest,HasActiveSocket)2185 TEST_F(TransportClientSocketPoolTest, HasActiveSocket) {
2186   const url::SchemeHostPort kEndpoint1(url::kHttpScheme, "host1.test", 80);
2187   const url::SchemeHostPort kEndpoint2(url::kHttpScheme, "host2.test", 80);
2188 
2189   ClientSocketHandle handle;
2190   ClientSocketPool::GroupId group_id1(
2191       kEndpoint1, PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
2192       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2193   ClientSocketPool::GroupId group_id2(
2194       kEndpoint2, PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
2195       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2196 
2197   // HasActiveSocket() must return false before creating a socket.
2198   EXPECT_FALSE(pool_->HasActiveSocket(group_id1));
2199 
2200   TestCompletionCallback callback1;
2201   int rv1 =
2202       handle.Init(group_id1, params_, std::nullopt /* proxy_annotation_tag */,
2203                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
2204                   callback1.callback(), ClientSocketPool::ProxyAuthCallback(),
2205                   pool_.get(), NetLogWithSource());
2206   EXPECT_THAT(rv1, IsError(ERR_IO_PENDING));
2207 
2208   // HasActiveSocket() must return true while connecting.
2209   EXPECT_TRUE(pool_->HasActiveSocket(group_id1));
2210   EXPECT_FALSE(handle.is_initialized());
2211   EXPECT_FALSE(handle.socket());
2212 
2213   EXPECT_THAT(callback1.WaitForResult(), IsOk());
2214 
2215   // HasActiveSocket() must return true after handed out.
2216   EXPECT_TRUE(pool_->HasActiveSocket(group_id1));
2217   EXPECT_TRUE(handle.is_initialized());
2218   EXPECT_TRUE(handle.socket());
2219 
2220   handle.Reset();
2221 
2222   // HasActiveSocket returns true for the idle socket.
2223   EXPECT_TRUE(pool_->HasActiveSocket(group_id1));
2224   // Now we should have 1 idle socket.
2225   EXPECT_EQ(1, pool_->IdleSocketCount());
2226 
2227   // HasActiveSocket() for group_id2 must still return false.
2228   EXPECT_FALSE(pool_->HasActiveSocket(group_id2));
2229 
2230   TestCompletionCallback callback2;
2231   int rv2 =
2232       handle.Init(group_id2, params_, std::nullopt /* proxy_annotation_tag */,
2233                   LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
2234                   callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2235                   pool_.get(), NetLogWithSource());
2236   EXPECT_THAT(rv2, IsError(ERR_IO_PENDING));
2237 
2238   // HasActiveSocket(group_id2) must return true while connecting.
2239   EXPECT_TRUE(pool_->HasActiveSocket(group_id2));
2240 
2241   // HasActiveSocket(group_id1) must still return true.
2242   EXPECT_TRUE(pool_->HasActiveSocket(group_id2));
2243 
2244   // Close the sockets.
2245   pool_->FlushWithError(ERR_NETWORK_CHANGED, "Network changed");
2246 
2247   // HasActiveSocket() must return false after closing the socket.
2248   EXPECT_FALSE(pool_->HasActiveSocket(group_id1));
2249   EXPECT_FALSE(pool_->HasActiveSocket(group_id2));
2250 }
2251 
2252 // Test that SocketTag passed into TransportClientSocketPool is applied to
2253 // returned sockets.
2254 #if BUILDFLAG(IS_ANDROID)
TEST_F(TransportClientSocketPoolTest,Tag)2255 TEST_F(TransportClientSocketPoolTest, Tag) {
2256   if (!CanGetTaggedBytes()) {
2257     DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
2258     return;
2259   }
2260 
2261   // Start test server.
2262   EmbeddedTestServer test_server;
2263   test_server.AddDefaultHandlers(base::FilePath());
2264   ASSERT_TRUE(test_server.Start());
2265 
2266   ClientSocketHandle handle;
2267   int32_t tag_val1 = 0x12345678;
2268   SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
2269   int32_t tag_val2 = 0x87654321;
2270   SocketTag tag2(getuid(), tag_val2);
2271 
2272   // Test socket is tagged before connected.
2273   uint64_t old_traffic = GetTaggedBytes(tag_val1);
2274   const ClientSocketPool::GroupId kGroupId(
2275       url::SchemeHostPort(test_server.base_url()),
2276       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
2277       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2278   scoped_refptr<ClientSocketPool::SocketParams> params =
2279       ClientSocketPool::SocketParams::CreateForHttpForTesting();
2280   TestCompletionCallback callback;
2281   int rv =
2282       handle.Init(kGroupId, params, std::nullopt /* proxy_annotation_tag */,
2283                   LOW, tag1, ClientSocketPool::RespectLimits::ENABLED,
2284                   callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2285                   pool_for_real_sockets_.get(), NetLogWithSource());
2286   EXPECT_THAT(callback.GetResult(rv), IsOk());
2287   EXPECT_TRUE(handle.socket());
2288   EXPECT_TRUE(handle.socket()->IsConnected());
2289   EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
2290 
2291   // Test reused socket is retagged.
2292   StreamSocket* socket = handle.socket();
2293   handle.Reset();
2294   old_traffic = GetTaggedBytes(tag_val2);
2295   rv = handle.Init(kGroupId, params, std::nullopt /* proxy_annotation_tag */,
2296                    LOW, tag2, ClientSocketPool::RespectLimits::ENABLED,
2297                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2298                    pool_for_real_sockets_.get(), NetLogWithSource());
2299   EXPECT_THAT(rv, IsOk());
2300   EXPECT_TRUE(handle.socket());
2301   EXPECT_TRUE(handle.socket()->IsConnected());
2302   EXPECT_EQ(handle.socket(), socket);
2303   const char kRequest[] = "GET / HTTP/1.0\n\n";
2304   scoped_refptr<IOBuffer> write_buffer =
2305       base::MakeRefCounted<StringIOBuffer>(kRequest);
2306   rv =
2307       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2308                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
2309   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2310   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2311   // Disconnect socket to prevent reuse.
2312   handle.socket()->Disconnect();
2313   handle.Reset();
2314 
2315   // Test connect jobs that are orphaned and then adopted, appropriately apply
2316   // new tag. Request socket with |tag1|.
2317   TestCompletionCallback callback2;
2318   rv = handle.Init(kGroupId, params, std::nullopt /* proxy_annotation_tag */,
2319                    LOW, tag1, ClientSocketPool::RespectLimits::ENABLED,
2320                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2321                    pool_for_real_sockets_.get(), NetLogWithSource());
2322   EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv;
2323   // Abort and request socket with |tag2|.
2324   handle.Reset();
2325   rv = handle.Init(kGroupId, params, std::nullopt /* proxy_annotation_tag */,
2326                    LOW, tag2, ClientSocketPool::RespectLimits::ENABLED,
2327                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2328                    pool_for_real_sockets_.get(), NetLogWithSource());
2329   EXPECT_THAT(callback.GetResult(rv), IsOk());
2330   EXPECT_TRUE(handle.socket());
2331   EXPECT_TRUE(handle.socket()->IsConnected());
2332   // Verify socket has |tag2| applied.
2333   old_traffic = GetTaggedBytes(tag_val2);
2334   rv =
2335       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2336                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
2337   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2338   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2339   // Disconnect socket to prevent reuse.
2340   handle.socket()->Disconnect();
2341   handle.Reset();
2342   // Eat the left over connect job from the second request.
2343   // TODO(pauljensen): remove when crbug.com/800731 fixed.
2344   rv = handle.Init(kGroupId, params, std::nullopt /* proxy_annotation_tag */,
2345                    LOW, tag1, ClientSocketPool::RespectLimits::ENABLED,
2346                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2347                    pool_for_real_sockets_.get(), NetLogWithSource());
2348   EXPECT_THAT(rv, IsOk());
2349   // Disconnect socket to prevent reuse.
2350   handle.socket()->Disconnect();
2351   handle.Reset();
2352 
2353   // Test two connect jobs of differing priorities. Start the lower priority one
2354   // first but expect its socket to get vended to the higher priority request.
2355   ClientSocketHandle handle_high_pri;
2356   TestCompletionCallback callback_high_pri;
2357   rv = handle.Init(kGroupId, params, std::nullopt /* proxy_annotation_tag */,
2358                    LOW, tag1, ClientSocketPool::RespectLimits::ENABLED,
2359                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2360                    pool_for_real_sockets_.get(), NetLogWithSource());
2361   EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv;
2362   int rv_high_pri = handle_high_pri.Init(
2363       kGroupId, params, std::nullopt /* proxy_annotation_tag */, HIGHEST, tag2,
2364       ClientSocketPool::RespectLimits::ENABLED, callback_high_pri.callback(),
2365       ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2366       NetLogWithSource());
2367   EXPECT_THAT(callback_high_pri.GetResult(rv_high_pri), IsOk());
2368   EXPECT_TRUE(handle_high_pri.socket());
2369   EXPECT_TRUE(handle_high_pri.socket()->IsConnected());
2370   EXPECT_THAT(callback.GetResult(rv), IsOk());
2371   EXPECT_TRUE(handle.socket());
2372   EXPECT_TRUE(handle.socket()->IsConnected());
2373   // Verify |handle_high_pri| has |tag2| applied.
2374   old_traffic = GetTaggedBytes(tag_val2);
2375   rv = handle_high_pri.socket()->Write(write_buffer.get(), strlen(kRequest),
2376                                        callback.callback(),
2377                                        TRAFFIC_ANNOTATION_FOR_TESTS);
2378   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2379   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2380   // Verify |handle| has |tag1| applied.
2381   old_traffic = GetTaggedBytes(tag_val1);
2382   rv =
2383       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2384                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
2385   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2386   EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
2387 }
2388 
TEST_F(TransportClientSocketPoolTest,TagSOCKSProxy)2389 TEST_F(TransportClientSocketPoolTest, TagSOCKSProxy) {
2390   session_deps_.host_resolver->set_synchronous_mode(true);
2391 
2392   TransportClientSocketPool proxy_pool(
2393       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
2394       ProxyUriToProxyChain("socks5://proxy",
2395                            /*default_scheme=*/ProxyServer::SCHEME_HTTP),
2396       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
2397 
2398   SocketTag tag1(SocketTag::UNSET_UID, 0x12345678);
2399   SocketTag tag2(getuid(), 0x87654321);
2400   const url::SchemeHostPort kDestination(url::kHttpScheme, "host", 80);
2401   const ClientSocketPool::GroupId kGroupId(
2402       kDestination, PrivacyMode::PRIVACY_MODE_DISABLED,
2403       NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
2404       /*disable_cert_network_fetches=*/false);
2405   scoped_refptr<ClientSocketPool::SocketParams> socks_params =
2406       ClientSocketPool::SocketParams::CreateForHttpForTesting();
2407 
2408   // Test socket is tagged when created synchronously.
2409   SOCKS5MockData data_sync(SYNCHRONOUS);
2410   data_sync.data_provider()->set_connect_data(MockConnect(SYNCHRONOUS, OK));
2411   tagging_client_socket_factory_.AddSocketDataProvider(
2412       data_sync.data_provider());
2413   ClientSocketHandle handle;
2414   int rv = handle.Init(
2415       kGroupId, socks_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag1,
2416       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2417       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2418   EXPECT_THAT(rv, IsOk());
2419   EXPECT_TRUE(handle.is_initialized());
2420   EXPECT_TRUE(handle.socket());
2421   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2422             tag1);
2423   EXPECT_TRUE(tagging_client_socket_factory_.GetLastProducedTCPSocket()
2424                   ->tagged_before_connected());
2425 
2426   // Test socket is tagged when reused synchronously.
2427   StreamSocket* socket = handle.socket();
2428   handle.Reset();
2429   rv = handle.Init(
2430       kGroupId, socks_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag2,
2431       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2432       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2433   EXPECT_THAT(rv, IsOk());
2434   EXPECT_TRUE(handle.socket());
2435   EXPECT_TRUE(handle.socket()->IsConnected());
2436   EXPECT_EQ(handle.socket(), socket);
2437   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2438             tag2);
2439   handle.socket()->Disconnect();
2440   handle.Reset();
2441 
2442   // Test socket is tagged when created asynchronously.
2443   SOCKS5MockData data_async(ASYNC);
2444   tagging_client_socket_factory_.AddSocketDataProvider(
2445       data_async.data_provider());
2446   TestCompletionCallback callback;
2447   rv = handle.Init(kGroupId, socks_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW,
2448                    tag1, ClientSocketPool::RespectLimits::ENABLED,
2449                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2450                    &proxy_pool, NetLogWithSource());
2451   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2452   EXPECT_THAT(callback.WaitForResult(), IsOk());
2453   EXPECT_TRUE(handle.is_initialized());
2454   EXPECT_TRUE(handle.socket());
2455   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2456             tag1);
2457   EXPECT_TRUE(tagging_client_socket_factory_.GetLastProducedTCPSocket()
2458                   ->tagged_before_connected());
2459 
2460   // Test socket is tagged when reused after being created asynchronously.
2461   socket = handle.socket();
2462   handle.Reset();
2463   rv = handle.Init(
2464       kGroupId, socks_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag2,
2465       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2466       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2467   EXPECT_THAT(rv, IsOk());
2468   EXPECT_TRUE(handle.socket());
2469   EXPECT_TRUE(handle.socket()->IsConnected());
2470   EXPECT_EQ(handle.socket(), socket);
2471   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2472             tag2);
2473 }
2474 
TEST_F(TransportClientSocketPoolTest,TagSSLDirect)2475 TEST_F(TransportClientSocketPoolTest, TagSSLDirect) {
2476   if (!CanGetTaggedBytes()) {
2477     DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
2478     return;
2479   }
2480 
2481   // Start test server.
2482   EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
2483   test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig());
2484   test_server.AddDefaultHandlers(base::FilePath());
2485   ASSERT_TRUE(test_server.Start());
2486 
2487   TestCompletionCallback callback;
2488   ClientSocketHandle handle;
2489   int32_t tag_val1 = 0x12345678;
2490   SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
2491   int32_t tag_val2 = 0x87654321;
2492   SocketTag tag2(getuid(), tag_val2);
2493   const ClientSocketPool::GroupId kGroupId(
2494       url::SchemeHostPort(test_server.base_url()),
2495       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
2496       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2497 
2498   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2499       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2500           /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
2501 
2502   // Test socket is tagged before connected.
2503   uint64_t old_traffic = GetTaggedBytes(tag_val1);
2504   int rv = handle.Init(
2505       kGroupId, socket_params, std::nullopt /* proxy_annotation_tag */, LOW,
2506       tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2507       ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2508       NetLogWithSource());
2509   EXPECT_THAT(callback.GetResult(rv), IsOk());
2510   EXPECT_TRUE(handle.socket());
2511   EXPECT_TRUE(handle.socket()->IsConnected());
2512   EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
2513 
2514   // Test reused socket is retagged.
2515   StreamSocket* socket = handle.socket();
2516   handle.Reset();
2517   old_traffic = GetTaggedBytes(tag_val2);
2518   TestCompletionCallback callback2;
2519   rv = handle.Init(kGroupId, socket_params,
2520                    std::nullopt /* proxy_annotation_tag */, LOW, tag2,
2521                    ClientSocketPool::RespectLimits::ENABLED,
2522                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2523                    pool_for_real_sockets_.get(), NetLogWithSource());
2524   EXPECT_THAT(rv, IsOk());
2525   EXPECT_TRUE(handle.socket());
2526   EXPECT_TRUE(handle.socket()->IsConnected());
2527   EXPECT_EQ(handle.socket(), socket);
2528   const char kRequest[] = "GET / HTTP/1.1\r\n\r\n";
2529   scoped_refptr<IOBuffer> write_buffer =
2530       base::MakeRefCounted<StringIOBuffer>(kRequest);
2531   rv =
2532       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2533                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
2534   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2535   scoped_refptr<IOBufferWithSize> read_buffer =
2536       base::MakeRefCounted<IOBufferWithSize>(1);
2537   rv = handle.socket()->Read(read_buffer.get(), read_buffer->size(),
2538                              callback.callback());
2539   EXPECT_EQ(read_buffer->size(), callback.GetResult(rv));
2540   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2541   // Disconnect socket to prevent reuse.
2542   handle.socket()->Disconnect();
2543   handle.Reset();
2544 }
2545 
TEST_F(TransportClientSocketPoolTest,TagSSLDirectTwoSockets)2546 TEST_F(TransportClientSocketPoolTest, TagSSLDirectTwoSockets) {
2547   if (!CanGetTaggedBytes()) {
2548     DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
2549     return;
2550   }
2551 
2552   // Start test server.
2553   EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
2554   test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig());
2555   test_server.AddDefaultHandlers(base::FilePath());
2556   ASSERT_TRUE(test_server.Start());
2557 
2558   ClientSocketHandle handle;
2559   int32_t tag_val1 = 0x12345678;
2560   SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
2561   int32_t tag_val2 = 0x87654321;
2562   SocketTag tag2(getuid(), tag_val2);
2563   const ClientSocketPool::GroupId kGroupId(
2564       url::SchemeHostPort(test_server.base_url()),
2565       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
2566       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2567   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2568       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2569           /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
2570 
2571   // Test connect jobs that are orphaned and then adopted, appropriately apply
2572   // new tag. Request socket with |tag1|.
2573   TestCompletionCallback callback;
2574   int rv = handle.Init(
2575       kGroupId, socket_params, std::nullopt /* proxy_annotation_tag */, LOW,
2576       tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2577       ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2578       NetLogWithSource());
2579   EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv;
2580   // Abort and request socket with |tag2|.
2581   handle.Reset();
2582   TestCompletionCallback callback2;
2583   rv = handle.Init(kGroupId, socket_params,
2584                    std::nullopt /* proxy_annotation_tag */, LOW, tag2,
2585                    ClientSocketPool::RespectLimits::ENABLED,
2586                    callback2.callback(), ClientSocketPool::ProxyAuthCallback(),
2587                    pool_for_real_sockets_.get(), NetLogWithSource());
2588   EXPECT_THAT(callback2.GetResult(rv), IsOk());
2589   EXPECT_TRUE(handle.socket());
2590   EXPECT_TRUE(handle.socket()->IsConnected());
2591   // Verify socket has |tag2| applied.
2592   uint64_t old_traffic = GetTaggedBytes(tag_val2);
2593   const char kRequest[] = "GET / HTTP/1.1\r\n\r\n";
2594   scoped_refptr<IOBuffer> write_buffer =
2595       base::MakeRefCounted<StringIOBuffer>(kRequest);
2596   rv = handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2597                               callback2.callback(),
2598                               TRAFFIC_ANNOTATION_FOR_TESTS);
2599   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback2.GetResult(rv));
2600   scoped_refptr<IOBufferWithSize> read_buffer =
2601       base::MakeRefCounted<IOBufferWithSize>(1);
2602   rv = handle.socket()->Read(read_buffer.get(), read_buffer->size(),
2603                              callback2.callback());
2604   EXPECT_EQ(read_buffer->size(), callback2.GetResult(rv));
2605   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2606 }
2607 
TEST_F(TransportClientSocketPoolTest,TagSSLDirectTwoSocketsFullPool)2608 TEST_F(TransportClientSocketPoolTest, TagSSLDirectTwoSocketsFullPool) {
2609   if (!CanGetTaggedBytes()) {
2610     DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
2611     return;
2612   }
2613 
2614   // Start test server.
2615   EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
2616   test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig());
2617   test_server.AddDefaultHandlers(base::FilePath());
2618   ASSERT_TRUE(test_server.Start());
2619 
2620   TestCompletionCallback callback;
2621   ClientSocketHandle handle;
2622   int32_t tag_val1 = 0x12345678;
2623   SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
2624   int32_t tag_val2 = 0x87654321;
2625   SocketTag tag2(getuid(), tag_val2);
2626   const ClientSocketPool::GroupId kGroupId(
2627       url::SchemeHostPort(test_server.base_url()),
2628       PrivacyMode::PRIVACY_MODE_DISABLED, NetworkAnonymizationKey(),
2629       SecureDnsPolicy::kAllow, /*disable_cert_network_fetches=*/false);
2630   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2631       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2632           /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
2633 
2634   // Test that sockets paused by a full underlying socket pool are properly
2635   // connected and tagged when underlying pool is freed up.
2636   // Fill up all slots in TCP pool.
2637   ClientSocketHandle tcp_handles[kMaxSocketsPerGroup];
2638   int rv;
2639   for (auto& tcp_handle : tcp_handles) {
2640     rv = tcp_handle.Init(
2641         kGroupId, socket_params, std::nullopt /* proxy_annotation_tag */, LOW,
2642         tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2643         ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2644         NetLogWithSource());
2645     EXPECT_THAT(callback.GetResult(rv), IsOk());
2646     EXPECT_TRUE(tcp_handle.socket());
2647     EXPECT_TRUE(tcp_handle.socket()->IsConnected());
2648   }
2649   // Request two SSL sockets.
2650   ClientSocketHandle handle_to_be_canceled;
2651   rv = handle_to_be_canceled.Init(
2652       kGroupId, socket_params, std::nullopt /* proxy_annotation_tag */, LOW,
2653       tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2654       ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(),
2655       NetLogWithSource());
2656   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2657   rv = handle.Init(kGroupId, socket_params,
2658                    std::nullopt /* proxy_annotation_tag */, LOW, tag2,
2659                    ClientSocketPool::RespectLimits::ENABLED,
2660                    callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2661                    pool_for_real_sockets_.get(), NetLogWithSource());
2662   EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
2663   // Cancel first request.
2664   handle_to_be_canceled.Reset();
2665   // Disconnect a TCP socket to free up a slot.
2666   tcp_handles[0].socket()->Disconnect();
2667   tcp_handles[0].Reset();
2668   // Verify |handle| gets a valid tagged socket.
2669   EXPECT_THAT(callback.WaitForResult(), IsOk());
2670   EXPECT_TRUE(handle.socket());
2671   EXPECT_TRUE(handle.socket()->IsConnected());
2672   uint64_t old_traffic = GetTaggedBytes(tag_val2);
2673   const char kRequest[] = "GET / HTTP/1.1\r\n\r\n";
2674   scoped_refptr<IOBuffer> write_buffer =
2675       base::MakeRefCounted<StringIOBuffer>(kRequest);
2676   rv =
2677       handle.socket()->Write(write_buffer.get(), strlen(kRequest),
2678                              callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS);
2679   EXPECT_EQ(static_cast<int>(strlen(kRequest)), callback.GetResult(rv));
2680   scoped_refptr<IOBufferWithSize> read_buffer =
2681       base::MakeRefCounted<IOBufferWithSize>(1);
2682   EXPECT_EQ(handle.socket()->Read(read_buffer.get(), read_buffer->size(),
2683                                   callback.callback()),
2684             ERR_IO_PENDING);
2685   EXPECT_THAT(callback.WaitForResult(), read_buffer->size());
2686   EXPECT_GT(GetTaggedBytes(tag_val2), old_traffic);
2687 }
2688 
TEST_F(TransportClientSocketPoolTest,TagHttpProxyNoTunnel)2689 TEST_F(TransportClientSocketPoolTest, TagHttpProxyNoTunnel) {
2690   SocketTag tag1(SocketTag::UNSET_UID, 0x12345678);
2691   SocketTag tag2(getuid(), 0x87654321);
2692 
2693   TransportClientSocketPool proxy_pool(
2694       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
2695       ProxyUriToProxyChain("http://proxy",
2696                            /*default_scheme=*/ProxyServer::SCHEME_HTTP),
2697       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
2698 
2699   session_deps_.host_resolver->set_synchronous_mode(true);
2700   SequencedSocketData socket_data;
2701   socket_data.set_connect_data(MockConnect(SYNCHRONOUS, OK));
2702   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data);
2703 
2704   const url::SchemeHostPort kDestination(url::kHttpScheme, "www.google.com",
2705                                          80);
2706   const ClientSocketPool::GroupId kGroupId(
2707       kDestination, PrivacyMode::PRIVACY_MODE_DISABLED,
2708       NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
2709       /*disable_cert_network_fetches=*/false);
2710   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2711       ClientSocketPool::SocketParams::CreateForHttpForTesting();
2712 
2713   // Verify requested socket is tagged properly.
2714   ClientSocketHandle handle;
2715   int rv = handle.Init(
2716       kGroupId, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag1,
2717       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2718       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2719   EXPECT_THAT(rv, IsOk());
2720   EXPECT_TRUE(handle.is_initialized());
2721   ASSERT_TRUE(handle.socket());
2722   EXPECT_TRUE(handle.socket()->IsConnected());
2723   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2724             tag1);
2725   EXPECT_TRUE(tagging_client_socket_factory_.GetLastProducedTCPSocket()
2726                   ->tagged_before_connected());
2727 
2728   // Verify reused socket is retagged properly.
2729   StreamSocket* socket = handle.socket();
2730   handle.Reset();
2731   rv = handle.Init(
2732       kGroupId, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag2,
2733       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2734       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2735   EXPECT_THAT(rv, IsOk());
2736   EXPECT_TRUE(handle.socket());
2737   EXPECT_TRUE(handle.socket()->IsConnected());
2738   EXPECT_EQ(handle.socket(), socket);
2739   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2740             tag2);
2741   handle.socket()->Disconnect();
2742   handle.Reset();
2743 }
2744 
2745 // This creates a tunnel without SSL on top of it - something not normally done,
2746 // though some non-HTTP consumers use this path to create tunnels for other
2747 // uses.
TEST_F(TransportClientSocketPoolTest,TagHttpProxyTunnel)2748 TEST_F(TransportClientSocketPoolTest, TagHttpProxyTunnel) {
2749   SocketTag tag1(SocketTag::UNSET_UID, 0x12345678);
2750   SocketTag tag2(getuid(), 0x87654321);
2751 
2752   TransportClientSocketPool proxy_pool(
2753       kMaxSockets, kMaxSocketsPerGroup, kUnusedIdleSocketTimeout,
2754       ProxyUriToProxyChain("http://proxy",
2755                            /*default_scheme=*/ProxyServer::SCHEME_HTTP),
2756       /*is_for_websockets=*/false, tagging_common_connect_job_params_.get());
2757 
2758   session_deps_.host_resolver->set_synchronous_mode(true);
2759 
2760   std::string request =
2761       "CONNECT www.google.com:443 HTTP/1.1\r\n"
2762       "Host: www.google.com:443\r\n"
2763       "Proxy-Connection: keep-alive\r\n\r\n";
2764   MockWrite writes[] = {
2765       MockWrite(SYNCHRONOUS, 0, request.c_str()),
2766   };
2767   MockRead reads[] = {
2768       MockRead(SYNCHRONOUS, 1, "HTTP/1.1 200 Connection Established\r\n\r\n"),
2769   };
2770 
2771   SequencedSocketData socket_data(MockConnect(SYNCHRONOUS, OK), reads, writes);
2772   tagging_client_socket_factory_.AddSocketDataProvider(&socket_data);
2773   SSLSocketDataProvider ssl_data(SYNCHRONOUS, OK);
2774   tagging_client_socket_factory_.AddSSLSocketDataProvider(&ssl_data);
2775 
2776   const url::SchemeHostPort kDestination(url::kHttpsScheme, "www.google.com",
2777                                          443);
2778   const ClientSocketPool::GroupId kGroupId(
2779       kDestination, PrivacyMode::PRIVACY_MODE_DISABLED,
2780       NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
2781       /*disable_cert_network_fetches=*/false);
2782 
2783   scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2784       base::MakeRefCounted<ClientSocketPool::SocketParams>(
2785           /*allowed_bad_certs=*/std::vector<SSLConfig::CertAndStatus>());
2786 
2787   // Verify requested socket is tagged properly.
2788   ClientSocketHandle handle;
2789   int rv = handle.Init(
2790       kGroupId, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag1,
2791       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2792       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2793   EXPECT_THAT(rv, IsOk());
2794   EXPECT_TRUE(handle.is_initialized());
2795   ASSERT_TRUE(handle.socket());
2796   EXPECT_TRUE(handle.socket()->IsConnected());
2797   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2798             tag1);
2799   EXPECT_TRUE(tagging_client_socket_factory_.GetLastProducedTCPSocket()
2800                   ->tagged_before_connected());
2801 
2802   // Verify reused socket is retagged properly.
2803   StreamSocket* socket = handle.socket();
2804   handle.Reset();
2805   rv = handle.Init(
2806       kGroupId, socket_params, TRAFFIC_ANNOTATION_FOR_TESTS, LOW, tag2,
2807       ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(),
2808       ClientSocketPool::ProxyAuthCallback(), &proxy_pool, NetLogWithSource());
2809   EXPECT_THAT(rv, IsOk());
2810   EXPECT_TRUE(handle.socket());
2811   EXPECT_TRUE(handle.socket()->IsConnected());
2812   EXPECT_EQ(handle.socket(), socket);
2813   EXPECT_EQ(tagging_client_socket_factory_.GetLastProducedTCPSocket()->tag(),
2814             tag2);
2815   handle.socket()->Disconnect();
2816   handle.Reset();
2817 }
2818 
2819 #endif  // BUILDFLAG(IS_ANDROID)
2820 
2821 // Class that enables tests to set mock time.
2822 class TransportClientSocketPoolMockNowSourceTest
2823     : public TransportClientSocketPoolTest {
2824  public:
2825   TransportClientSocketPoolMockNowSourceTest(
2826       const TransportClientSocketPoolMockNowSourceTest&) = delete;
2827   TransportClientSocketPoolMockNowSourceTest& operator=(
2828       const TransportClientSocketPoolMockNowSourceTest&) = delete;
2829 
2830  protected:
TransportClientSocketPoolMockNowSourceTest()2831   TransportClientSocketPoolMockNowSourceTest()
2832       : TransportClientSocketPoolTest(
2833             base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
2834 };
2835 
2836 // Tests that changing the idle unused socket timeout using the experiment
2837 // works. The test first sets the value of timeout duration for idle sockets.
2838 // Next, it opens |kNumIdleSockets| sockets. To trigger the cleanup of idle
2839 // sockets that may have timedout, it then opens one more socket. This is
2840 // required since requesting a new socket triggers cleanup of idle timedout
2841 // sockets. Next, the test verifies the count of idle timed-out sockets.
TEST_F(TransportClientSocketPoolMockNowSourceTest,IdleUnusedSocketTimeout)2842 TEST_F(TransportClientSocketPoolMockNowSourceTest, IdleUnusedSocketTimeout) {
2843   const url::SchemeHostPort kSchemeHostPort1(url::kHttpScheme, "www.foo.com",
2844                                              80);
2845   const url::SchemeHostPort kSchemeHostPort2(url::kHttpScheme, "www.bar.com",
2846                                              80);
2847 
2848   const struct {
2849     bool use_first_socket;
2850     int fast_forward_seconds;
2851     int unused_idle_socket_timeout_seconds;
2852     bool expect_idle_socket;
2853   } kTests[] = {
2854       // When the clock is fast forwarded by a duration longer than
2855       // |unused_idle_socket_timeout_seconds|, the first unused idle socket is
2856       // expected to be timedout, and cleared.
2857       {false, 0, 0, false},
2858       {false, 9, 10, true},
2859       {false, 11, 10, false},
2860       {false, 19, 20, true},
2861       {false, 21, 20, false},
2862       // If |use_first_socket| is true, then the test would write some data to
2863       // the socket, thereby marking it as "used". Thereafter, this idle socket
2864       // should be timedout based on used idle socket timeout, and changing
2865       // |unused_idle_socket_timeout_seconds| should not affect the
2866       // |expected_idle_sockets|.
2867       {true, 0, 0, true},
2868       {true, 9, 10, true},
2869       {true, 11, 10, true},
2870       {true, 19, 20, true},
2871       {true, 21, 20, true},
2872   };
2873 
2874   for (const auto& test : kTests) {
2875     SpdySessionDependencies session_deps(
2876         ConfiguredProxyResolutionService::CreateDirect());
2877     std::unique_ptr<HttpNetworkSession> session(
2878         SpdySessionDependencies::SpdyCreateSession(&session_deps));
2879 
2880     base::test::ScopedFeatureList scoped_feature_list_;
2881     std::map<std::string, std::string> parameters;
2882     parameters["unused_idle_socket_timeout_seconds"] =
2883         base::NumberToString(test.unused_idle_socket_timeout_seconds);
2884     scoped_feature_list_.InitAndEnableFeatureWithParameters(
2885         net::features::kNetUnusedIdleSocketTimeout, parameters);
2886 
2887     const char kWriteData[] = "1";
2888     const MockWrite kWrites[] = {MockWrite(SYNCHRONOUS, kWriteData)};
2889 
2890     SequencedSocketData provider_socket_1(MockConnect(ASYNC, OK),
2891                                           base::span<MockRead>(), kWrites);
2892     {
2893       // Create 1 socket.
2894       scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2895           ClientSocketPool::SocketParams::CreateForHttpForTesting();
2896       session_deps.socket_factory->AddSocketDataProvider(&provider_socket_1);
2897       ClientSocketHandle connection;
2898       TestCompletionCallback callback;
2899       int rv = connection.Init(
2900           ClientSocketPool::GroupId(
2901               kSchemeHostPort1, PrivacyMode::PRIVACY_MODE_DISABLED,
2902               NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
2903               /*disable_cert_network_fetches=*/false),
2904           ClientSocketPool::SocketParams::CreateForHttpForTesting(),
2905           /*proxy_annotation_tag=*/std::nullopt, MEDIUM, SocketTag(),
2906           ClientSocketPool::RespectLimits::ENABLED, callback.callback(),
2907           ClientSocketPool::ProxyAuthCallback(),
2908           session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
2909                                  ProxyChain::Direct()),
2910           NetLogWithSource());
2911       EXPECT_THAT(callback.GetResult(rv), IsOk());
2912       EXPECT_FALSE(connection.socket()->WasEverUsed());
2913 
2914       // Writing some data to the socket should set WasEverUsed.
2915       if (test.use_first_socket) {
2916         // Generate |socket_write_data| from kMockWriteData by appending null
2917         // character to the latter.
2918         auto write_buffer = base::MakeRefCounted<StringIOBuffer>(kWriteData);
2919         TestCompletionCallback write_callback;
2920         rv = connection.socket()->Write(
2921             write_buffer.get(), write_buffer->size(), write_callback.callback(),
2922             TRAFFIC_ANNOTATION_FOR_TESTS);
2923         EXPECT_EQ(rv, 1);
2924         EXPECT_TRUE(connection.socket()->WasEverUsed());
2925       }
2926     }
2927 
2928     EXPECT_EQ(1, session
2929                      ->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
2930                                      ProxyChain::Direct())
2931                      ->IdleSocketCount());
2932 
2933     // Moving the clock forward may cause the idle socket to be timedout.
2934     FastForwardBy(base::Seconds(test.fast_forward_seconds));
2935 
2936     {
2937       // Request a new socket to trigger cleanup of idle timedout sockets.
2938       scoped_refptr<ClientSocketPool::SocketParams> socket_params =
2939           ClientSocketPool::SocketParams::CreateForHttpForTesting();
2940       SequencedSocketData provider_socket_2(MockConnect(ASYNC, OK),
2941                                             base::span<MockRead>(),
2942                                             base::span<MockWrite>());
2943       session_deps.socket_factory->AddSocketDataProvider(&provider_socket_2);
2944       ClientSocketHandle connection;
2945       TestCompletionCallback callback;
2946       int rv = connection.Init(
2947           ClientSocketPool::GroupId(
2948               kSchemeHostPort2, PrivacyMode::PRIVACY_MODE_DISABLED,
2949               NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
2950               /*disable_cert_network_fetches=*/false),
2951           socket_params, /*proxy_annotation_tag=*/std::nullopt, MEDIUM,
2952           SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
2953           callback.callback(), ClientSocketPool::ProxyAuthCallback(),
2954           session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
2955                                  ProxyChain::Direct()),
2956           NetLogWithSource());
2957       EXPECT_THAT(callback.GetResult(rv), IsOk());
2958       connection.socket()->Disconnect();
2959     }
2960 
2961     EXPECT_EQ(test.expect_idle_socket ? 1 : 0,
2962               session
2963                   ->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
2964                                   ProxyChain::Direct())
2965                   ->IdleSocketCount());
2966   }
2967 }
2968 
2969 }  // namespace
2970 
2971 }  // namespace net
2972