File: transport_connect_job_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1272 lines) | stat: -rw-r--r-- 59,464 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.


#include "net/socket/transport_connect_job.h"

#include <memory>
#include <set>
#include <string>
#include <vector>

#include "base/memory/ref_counted.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "net/base/address_family.h"
#include "net/base/features.h"
#include "net/base/host_port_pair.h"
#include "net/base/ip_address.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/dns/mock_host_resolver.h"
#include "net/dns/public/secure_dns_policy.h"
#include "net/http/transport_security_state.h"
#include "net/log/net_log.h"
#include "net/socket/connect_job_test_util.h"
#include "net/socket/connection_attempts.h"
#include "net/socket/ssl_client_socket.h"
#include "net/socket/stream_socket.h"
#include "net/socket/transport_client_socket_pool_test_util.h"
#include "net/ssl/ssl_config_service.h"
#include "net/ssl/test_ssl_config_service.h"
#include "net/test/gtest_util.h"
#include "net/test/test_with_task_environment.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/scheme_host_port.h"
#include "url/url_constants.h"

namespace net {
namespace {

const char kHostName[] = "unresolvable.host.name";

IPAddress ParseIP(const std::string& ip) {
  IPAddress address;
  CHECK(address.AssignFromIPLiteral(ip));
  return address;
}

class TransportConnectJobTest : public WithTaskEnvironment,
                                public testing::Test {
 public:
  TransportConnectJobTest()
      : WithTaskEnvironment(base::test::TaskEnvironment::TimeSource::MOCK_TIME),
        client_socket_factory_(NetLog::Get()),
        common_connect_job_params_(
            &client_socket_factory_,
            &host_resolver_,
            /*http_auth_cache=*/nullptr,
            /*http_auth_handler_factory=*/nullptr,
            /*spdy_session_pool=*/nullptr,
            /*quic_supported_versions=*/nullptr,
            /*quic_session_pool=*/nullptr,
            /*proxy_delegate=*/nullptr,
            &http_user_agent_settings_,
            &ssl_client_context_,
            /*socket_performance_watcher_factory=*/nullptr,
            /*network_quality_estimator=*/nullptr,
            NetLog::Get(),
            /*websocket_endpoint_lock_manager=*/nullptr,
            /*http_server_properties=*/nullptr,
            /*alpn_protos=*/nullptr,
            /*application_settings=*/nullptr,
            /*ignore_certificate_errors=*/nullptr,
            /*early_data_enabled=*/nullptr) {}

  ~TransportConnectJobTest() override = default;

  static scoped_refptr<TransportSocketParams> DefaultParams() {
    return base::MakeRefCounted<TransportSocketParams>(
        url::SchemeHostPort(url::kHttpScheme, kHostName, 80),
        NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
        OnHostResolutionCallback(),
        /*supported_alpns=*/base::flat_set<std::string>());
  }

  static scoped_refptr<TransportSocketParams> DefaultHttpsParams() {
    return base::MakeRefCounted<TransportSocketParams>(
        url::SchemeHostPort(url::kHttpsScheme, kHostName, 443),
        NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
        OnHostResolutionCallback(),
        /*supported_alpns=*/base::flat_set<std::string>{"h2", "http/1.1"});
  }

 protected:
  MockHostResolver host_resolver_{/*default_result=*/MockHostResolverBase::
                                      RuleResolver::GetLocalhostResult()};
  MockTransportClientSocketFactory client_socket_factory_;
  TestSSLConfigService ssl_config_service_{SSLContextConfig{}};
  MockCertVerifier cert_verifier_;
  TransportSecurityState transport_security_state_;
  const StaticHttpUserAgentSettings http_user_agent_settings_ = {"*",
                                                                 "test-ua"};
  SSLClientContext ssl_client_context_{&ssl_config_service_, &cert_verifier_,
                                       &transport_security_state_,
                                       /*ssl_client_session_cache=*/nullptr,
                                       /*sct_auditing_delegate=*/nullptr};
  const CommonConnectJobParams common_connect_job_params_;
};

TEST_F(TransportConnectJobTest, HostResolutionFailure) {
  host_resolver_.rules()->AddSimulatedTimeoutFailure(kHostName);

  //  Check sync and async failures.
  for (bool host_resolution_synchronous : {false, true}) {
    host_resolver_.set_synchronous_mode(host_resolution_synchronous);
    TestConnectJobDelegate test_delegate;
    TransportConnectJob transport_connect_job(
        DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
        DefaultParams(), &test_delegate, nullptr /* net_log */);
    test_delegate.StartJobExpectingResult(&transport_connect_job,
                                          ERR_NAME_NOT_RESOLVED,
                                          host_resolution_synchronous);
    EXPECT_THAT(transport_connect_job.GetResolveErrorInfo().error,
                test::IsError(ERR_DNS_TIMED_OUT));
  }
}

TEST_F(TransportConnectJobTest, ConnectionFailure) {
  for (bool host_resolution_synchronous : {false, true}) {
    for (bool connection_synchronous : {false, true}) {
      host_resolver_.set_synchronous_mode(host_resolution_synchronous);
      client_socket_factory_.set_default_client_socket_type(
          connection_synchronous
              ? MockTransportClientSocketFactory::Type::kFailing
              : MockTransportClientSocketFactory::Type::kPendingFailing);
      TestConnectJobDelegate test_delegate;
      TransportConnectJob transport_connect_job(
          DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
          DefaultParams(), &test_delegate, nullptr /* net_log */);
      test_delegate.StartJobExpectingResult(
          &transport_connect_job, ERR_CONNECTION_FAILED,
          host_resolution_synchronous && connection_synchronous);
    }
  }
}

TEST_F(TransportConnectJobTest, HostResolutionTimeout) {
  const base::TimeDelta kTinyTime = base::Microseconds(1);

  // Make request hang.
  host_resolver_.set_ondemand_mode(true);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, nullptr /* net_log */);
  ASSERT_THAT(transport_connect_job.Connect(), test::IsError(ERR_IO_PENDING));

  // Right up until just before expiration, the job does not time out.
  FastForwardBy(TransportConnectJob::ConnectionTimeout() - kTinyTime);
  EXPECT_FALSE(test_delegate.has_result());

  // But at the exact time of expiration, the job fails.
  FastForwardBy(kTinyTime);
  EXPECT_TRUE(test_delegate.has_result());
  EXPECT_THAT(test_delegate.WaitForResult(), test::IsError(ERR_TIMED_OUT));
}

TEST_F(TransportConnectJobTest, ConnectionTimeout) {
  const base::TimeDelta kTinyTime = base::Microseconds(1);

  // Half the timeout time. In the async case, spend half the time waiting on
  // host resolution, half on connecting.
  const base::TimeDelta kFirstHalfOfTimeout =
      TransportConnectJob::ConnectionTimeout() / 2;

  const base::TimeDelta kSecondHalfOfTimeout =
      TransportConnectJob::ConnectionTimeout() - kFirstHalfOfTimeout;
  ASSERT_LE(kTinyTime, kSecondHalfOfTimeout);

  // Make connection attempts hang.
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kStalled);

  for (bool host_resolution_synchronous : {false, true}) {
    host_resolver_.set_ondemand_mode(!host_resolution_synchronous);
    TestConnectJobDelegate test_delegate;
    TransportConnectJob transport_connect_job(
        DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
        DefaultParams(), &test_delegate, nullptr /* net_log */);
    EXPECT_THAT(transport_connect_job.Connect(), test::IsError(ERR_IO_PENDING));

    // After half the timeout, connection does not timeout.
    FastForwardBy(kFirstHalfOfTimeout);
    EXPECT_FALSE(test_delegate.has_result());

    // In the async case, the host resolution completes now.
    if (!host_resolution_synchronous) {
      host_resolver_.ResolveOnlyRequestNow();
    }

    // After (almost) the second half of timeout, just before the full timeout
    // period, the ConnectJob is still live.
    FastForwardBy(kSecondHalfOfTimeout - kTinyTime);
    EXPECT_FALSE(test_delegate.has_result());

    // But at the exact timeout time, the job fails.
    FastForwardBy(kTinyTime);
    EXPECT_TRUE(test_delegate.has_result());
    EXPECT_THAT(test_delegate.WaitForResult(), test::IsError(ERR_TIMED_OUT));
  }
}

TEST_F(TransportConnectJobTest, ConnectionSuccess) {
  for (bool host_resolution_synchronous : {false, true}) {
    for (bool connection_synchronous : {false, true}) {
      host_resolver_.set_synchronous_mode(host_resolution_synchronous);
      client_socket_factory_.set_default_client_socket_type(
          connection_synchronous
              ? MockTransportClientSocketFactory::Type::kSynchronous
              : MockTransportClientSocketFactory::Type::kPending);
      TestConnectJobDelegate test_delegate;
      TransportConnectJob transport_connect_job(
          DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
          DefaultParams(), &test_delegate, nullptr /* net_log */);
      test_delegate.StartJobExpectingResult(
          &transport_connect_job, OK,
          host_resolution_synchronous && connection_synchronous);
    }
  }
}

TEST_F(TransportConnectJobTest, LoadState) {
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kStalled);
  host_resolver_.set_ondemand_mode(true);
  host_resolver_.rules()->AddIPLiteralRule(kHostName, "1:abcd::3:4:ff,1.1.1.1",
                                           std::string());

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, /*net_log=*/nullptr);
  EXPECT_THAT(transport_connect_job.Connect(), test::IsError(ERR_IO_PENDING));

  // The job is initially waiting on DNS.
  EXPECT_EQ(transport_connect_job.GetLoadState(), LOAD_STATE_RESOLVING_HOST);

  // Complete DNS. It is now waiting on a TCP connection.
  host_resolver_.ResolveOnlyRequestNow();
  RunUntilIdle();
  EXPECT_EQ(transport_connect_job.GetLoadState(), LOAD_STATE_CONNECTING);

  // Wait for the IPv4 job to start. The job is still waiting on a TCP
  // connection.
  FastForwardBy(TransportConnectJob::kIPv6FallbackTime +
                base::Milliseconds(50));
  EXPECT_EQ(transport_connect_job.GetLoadState(), LOAD_STATE_CONNECTING);
}

// TODO(crbug.com/40181080): Set up `host_resolver_` to require the expected
// scheme.
TEST_F(TransportConnectJobTest, HandlesHttpsEndpoint) {
  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      base::MakeRefCounted<TransportSocketParams>(
          url::SchemeHostPort(url::kHttpsScheme, kHostName, 80),
          NetworkAnonymizationKey(), SecureDnsPolicy::kAllow,
          OnHostResolutionCallback(),
          /*supported_alpns=*/base::flat_set<std::string>{"h2", "http/1.1"}),
      &test_delegate, nullptr /* net_log */);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        false /* expect_sync_result */);
}

// TODO(crbug.com/40181080): Set up `host_resolver_` to require the expected
// lack of scheme.
TEST_F(TransportConnectJobTest, HandlesNonStandardEndpoint) {
  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      base::MakeRefCounted<TransportSocketParams>(
          HostPortPair(kHostName, 80), NetworkAnonymizationKey(),
          SecureDnsPolicy::kAllow, OnHostResolutionCallback(),
          /*supported_alpns=*/base::flat_set<std::string>()),
      &test_delegate, nullptr /* net_log */);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        false /* expect_sync_result */);
}

TEST_F(TransportConnectJobTest, SecureDnsPolicy) {
  for (auto secure_dns_policy :
       {SecureDnsPolicy::kAllow, SecureDnsPolicy::kDisable}) {
    TestConnectJobDelegate test_delegate;
    TransportConnectJob transport_connect_job(
        DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
        base::MakeRefCounted<TransportSocketParams>(
            url::SchemeHostPort(url::kHttpScheme, kHostName, 80),
            NetworkAnonymizationKey(), secure_dns_policy,
            OnHostResolutionCallback(),
            /*supported_alpns=*/base::flat_set<std::string>{}),
        &test_delegate, nullptr /* net_log */);
    test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                          false /* expect_sync_result */);
    EXPECT_EQ(secure_dns_policy, host_resolver_.last_secure_dns_policy());
  }
}

// Test the case of the IPv6 address stalling, and falling back to the IPv4
// socket which finishes first.
TEST_F(TransportConnectJobTest, IPv6FallbackSocketIPv4FinishesFirst) {
  MockTransportClientSocketFactory::Rule rules[] = {
      // The first IPv6 attempt fails.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("1:abcd::3:4:ff"), 80)}),
      // The second IPv6 attempt stalls.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kStalled,
          std::vector{IPEndPoint(ParseIP("2:abcd::3:4:ff"), 80)}),
      // After a timeout, we try the IPv4 address.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kPending,
          std::vector{IPEndPoint(ParseIP("2.2.2.2"), 80)})};

  client_socket_factory_.SetRules(rules);

  // Resolve an AddressList with two IPv6 addresses and then a IPv4 address.
  host_resolver_.rules()->AddIPLiteralRule(
      kHostName, "1:abcd::3:4:ff,2:abcd::3:4:ff,2.2.2.2", std::string());

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, nullptr /* net_log */);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        false /* expect_sync_result */);

  IPEndPoint endpoint;
  test_delegate.socket()->GetLocalAddress(&endpoint);
  EXPECT_TRUE(endpoint.address().IsIPv4());

  // Check that the failed connection attempt is collected.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(1u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("1:abcd::3:4:ff"), 80));

  EXPECT_EQ(3, client_socket_factory_.allocation_count());
}

// Test the case of the IPv6 address being slow, thus falling back to trying to
// connect to the IPv4 address, but having the connect to the IPv6 address
// finish first.
TEST_F(TransportConnectJobTest, IPv6FallbackSocketIPv6FinishesFirst) {
  MockTransportClientSocketFactory::Rule rules[] = {
      // The first IPv6 attempt ultimately succeeds, but is delayed.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kDelayed,
          std::vector{IPEndPoint(ParseIP("2:abcd::3:4:ff"), 80)}),
      // The first IPv4 attempt fails.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("2.2.2.2"), 80)}),
      // The second IPv4 attempt stalls.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kStalled,
          std::vector{IPEndPoint(ParseIP("3.3.3.3"), 80)})};

  client_socket_factory_.SetRules(rules);
  client_socket_factory_.set_delay(TransportConnectJob::kIPv6FallbackTime +
                                   base::Milliseconds(50));

  // Resolve an AddressList with a IPv6 address first and then a IPv4 address.
  host_resolver_.rules()->AddIPLiteralRule(
      kHostName, "2:abcd::3:4:ff,2.2.2.2,3.3.3.3", std::string());

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, nullptr /* net_log */);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        false /* expect_sync_result */);

  IPEndPoint endpoint;
  test_delegate.socket()->GetLocalAddress(&endpoint);
  EXPECT_TRUE(endpoint.address().IsIPv6());

  // Check that the failed connection attempt on the fallback socket is
  // collected.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(1u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("2.2.2.2"), 80));

  EXPECT_EQ(3, client_socket_factory_.allocation_count());
}

TEST_F(TransportConnectJobTest, IPv6NoIPv4AddressesToFallbackTo) {
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kDelayed);

  // Resolve an AddressList with only IPv6 addresses.
  host_resolver_.rules()->AddIPLiteralRule(
      kHostName, "2:abcd::3:4:ff,3:abcd::3:4:ff", std::string());

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, nullptr /* net_log */);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        false /* expect_sync_result */);

  IPEndPoint endpoint;
  test_delegate.socket()->GetLocalAddress(&endpoint);
  EXPECT_TRUE(endpoint.address().IsIPv6());
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  EXPECT_EQ(0u, attempts.size());
  EXPECT_EQ(1, client_socket_factory_.allocation_count());
}

TEST_F(TransportConnectJobTest, IPv4HasNoFallback) {
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kDelayed);

  // Resolve an AddressList with only IPv4 addresses.
  host_resolver_.rules()->AddIPLiteralRule(kHostName, "1.1.1.1", std::string());

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, nullptr /* net_log */);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        false /* expect_sync_result */);

  IPEndPoint endpoint;
  test_delegate.socket()->GetLocalAddress(&endpoint);
  EXPECT_TRUE(endpoint.address().IsIPv4());
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  EXPECT_EQ(0u, attempts.size());
  EXPECT_EQ(1, client_socket_factory_.allocation_count());
}

TEST_F(TransportConnectJobTest, DnsAliases) {
  host_resolver_.set_synchronous_mode(true);
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kSynchronous);

  // Resolve an AddressList with DNS aliases.
  std::vector<std::string> aliases({"alias1", "alias2", kHostName});
  host_resolver_.rules()->AddIPLiteralRuleWithDnsAliases(kHostName, "2.2.2.2",
                                                         std::move(aliases));

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, nullptr /* net_log */);

  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        true /* expect_sync_result */);

  // Verify that the elements of the alias list are those from the
  // parameter vector.
  EXPECT_THAT(test_delegate.socket()->GetDnsAliases(),
              testing::ElementsAre("alias1", "alias2", kHostName));
}

TEST_F(TransportConnectJobTest, NoAdditionalDnsAliases) {
  host_resolver_.set_synchronous_mode(true);
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kSynchronous);

  // Resolve an AddressList without additional DNS aliases. (The parameter
  // is an empty vector.)
  std::vector<std::string> aliases;
  host_resolver_.rules()->AddIPLiteralRuleWithDnsAliases(kHostName, "2.2.2.2",
                                                         std::move(aliases));

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, nullptr /* net_log */);

  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        true /* expect_sync_result */);

  // Verify that the alias list only contains kHostName.
  EXPECT_THAT(test_delegate.socket()->GetDnsAliases(),
              testing::ElementsAre(kHostName));
}

// Test that `TransportConnectJob` will pick up options from
// `HostResolverEndpointResult`.
TEST_F(TransportConnectJobTest, EndpointResult) {
  HostResolverEndpointResult endpoint;
  endpoint.ip_endpoints = {IPEndPoint(ParseIP("1::"), 8443),
                           IPEndPoint(ParseIP("1.1.1.1"), 8443)};
  endpoint.metadata.supported_protocol_alpns = {"h2"};
  host_resolver_.rules()->AddRule(
      kHostName,
      MockHostResolverBase::RuleResolver::RuleResult(std::vector{endpoint}));

  // The first access succeeds.
  MockTransportClientSocketFactory::Rule rule(
      MockTransportClientSocketFactory::Type::kSynchronous,
      std::vector{IPEndPoint(ParseIP("1::"), 8443)});
  client_socket_factory_.SetRules(base::span_from_ref(rule));

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/false);

  IPEndPoint peer_address;
  test_delegate.socket()->GetPeerAddress(&peer_address);
  EXPECT_EQ(peer_address, IPEndPoint(ParseIP("1::"), 8443));

  EXPECT_EQ(1, client_socket_factory_.allocation_count());

  // There were no failed connection attempts to report.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  EXPECT_EQ(0u, attempts.size());
}

// Test that, given multiple `HostResolverEndpointResult` results,
// `TransportConnectJob` tries each in succession.
TEST_F(TransportConnectJobTest, MultipleRoutesFallback) {
  std::vector<HostResolverEndpointResult> endpoints(3);
  endpoints[0].ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441),
                               IPEndPoint(ParseIP("1.1.1.1"), 8441)};
  endpoints[0].metadata.supported_protocol_alpns = {"h3", "h2", "http/1.1"};
  endpoints[1].ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442),
                               IPEndPoint(ParseIP("2.2.2.2"), 8442)};
  endpoints[1].metadata.supported_protocol_alpns = {"h3"};
  endpoints[2].ip_endpoints = {IPEndPoint(ParseIP("4::"), 443),
                               IPEndPoint(ParseIP("4.4.4.4"), 443)};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(endpoints));

  MockTransportClientSocketFactory::Rule rules[] = {
      // `endpoints[0]`'s addresses each fail.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{endpoints[0].ip_endpoints[0]}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{endpoints[0].ip_endpoints[1]}),
      // `endpoints[1]` is skipped because the ALPN is not compatible.
      // `endpoints[2]`'s first address succeeds.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kSynchronous,
          std::vector{endpoints[2].ip_endpoints[0]}),
  };

  client_socket_factory_.SetRules(rules);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/false);

  IPEndPoint peer_address;
  test_delegate.socket()->GetPeerAddress(&peer_address);
  EXPECT_EQ(peer_address, IPEndPoint(ParseIP("4::"), 443));

  // Check that failed connection attempts are reported.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(2u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("1::"), 8441));
  EXPECT_THAT(attempts[1].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[1].endpoint, IPEndPoint(ParseIP("1.1.1.1"), 8441));
}

// Test that the `HostResolverEndpointResult` fallback works in combination with
// the IPv4 fallback.
TEST_F(TransportConnectJobTest, MultipleRoutesIPV4Fallback) {
  HostResolverEndpointResult endpoint1, endpoint2, endpoint3;
  endpoint1.ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441),
                            IPEndPoint(ParseIP("1.1.1.1"), 8441)};
  endpoint1.metadata.supported_protocol_alpns = {"h3", "h2", "http/1.1"};
  endpoint2.ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442),
                            IPEndPoint(ParseIP("2.2.2.2"), 8442)};
  endpoint2.metadata.supported_protocol_alpns = {"h3"};
  endpoint3.ip_endpoints = {IPEndPoint(ParseIP("3::"), 443),
                            IPEndPoint(ParseIP("3.3.3.3"), 443)};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(
                     std::vector{endpoint1, endpoint2, endpoint3}));

  MockTransportClientSocketFactory::Rule rules[] = {
      // `endpoint1`'s IPv6 address fails, but takes long enough that the IPv4
      // fallback runs.
      //
      // TODO(davidben): If the network is such that IPv6 connection attempts
      // always stall, we will never try `endpoint2`. Should Happy Eyeballs
      // logic happen before HTTPS RR. Or perhaps we should implement a more
      // Happy-Eyeballs-v2-like strategy.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kDelayedFailing,
          std::vector{IPEndPoint(ParseIP("1::"), 8441)}),

      // `endpoint1`'s IPv4 address fails immediately.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("1.1.1.1"), 8441)}),

      // `endpoint2` is skipped because the ALPN is not compatible.

      // `endpoint3`'s IPv6 address never completes.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kStalled,
          std::vector{IPEndPoint(ParseIP("3::"), 443)}),
      // `endpoint3`'s IPv4 address succeeds.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kSynchronous,
          std::vector{IPEndPoint(ParseIP("3.3.3.3"), 443)}),
  };
  client_socket_factory_.SetRules(rules);
  client_socket_factory_.set_delay(TransportConnectJob::kIPv6FallbackTime +
                                   base::Milliseconds(50));

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/false);

  IPEndPoint peer_address;
  test_delegate.socket()->GetPeerAddress(&peer_address);
  EXPECT_EQ(peer_address, IPEndPoint(ParseIP("3.3.3.3"), 443));

  // Check that failed connection attempts are reported.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(2u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("1.1.1.1"), 8441));
  EXPECT_THAT(attempts[1].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[1].endpoint, IPEndPoint(ParseIP("1::"), 8441));
}

// Test that `TransportConnectJob` will not continue trying routes given
// ERR_NETWORK_IO_SUSPENDED.
TEST_F(TransportConnectJobTest, MultipleRoutesSuspended) {
  std::vector<HostResolverEndpointResult> endpoints(2);
  endpoints[0].ip_endpoints = {IPEndPoint(ParseIP("1::"), 8443)};
  endpoints[0].metadata.supported_protocol_alpns = {"h3", "h2", "http/1.1"};
  endpoints[1].ip_endpoints = {IPEndPoint(ParseIP("2::"), 443)};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(endpoints));

  // The first connect attempt will fail with `ERR_NETWORK_IO_SUSPENDED`.
  // `TransportConnectJob` should not attempt routes after receiving this error.
  MockTransportClientSocketFactory::Rule rule(
      MockTransportClientSocketFactory::Type::kFailing,
      endpoints[0].ip_endpoints, ERR_NETWORK_IO_SUSPENDED);
  client_socket_factory_.SetRules(base::span_from_ref(rule));

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job,
                                        ERR_NETWORK_IO_SUSPENDED,
                                        /*expect_sync_result=*/false);

  // Check that failed connection attempts are reported.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(1u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_NETWORK_IO_SUSPENDED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("1::"), 8443));
}

// Test that, if `HostResolver` supports SVCB for a scheme but the caller didn't
// pass in any ALPN protocols, `TransportConnectJob` ignores all protocol
// endpoints.
TEST_F(TransportConnectJobTest, NoAlpnProtocols) {
  std::vector<HostResolverEndpointResult> endpoints(3);
  endpoints[0].ip_endpoints = {IPEndPoint(ParseIP("1::"), 8081),
                               IPEndPoint(ParseIP("1.1.1.1"), 8081)};
  endpoints[0].metadata.supported_protocol_alpns = {"foo", "bar"};
  endpoints[1].ip_endpoints = {IPEndPoint(ParseIP("2::"), 8082),
                               IPEndPoint(ParseIP("2.2.2.2"), 8082)};
  endpoints[1].metadata.supported_protocol_alpns = {"baz"};
  endpoints[2].ip_endpoints = {IPEndPoint(ParseIP("3::"), 80),
                               IPEndPoint(ParseIP("3.3.3.3"), 80)};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(endpoints));

  // `endpoints[2]`'s first address succeeds.
  MockTransportClientSocketFactory::Rule rule(
      MockTransportClientSocketFactory::Type::kSynchronous,
      std::vector{endpoints[2].ip_endpoints[0]});
  client_socket_factory_.SetRules(base::span_from_ref(rule));

  // Use `DefaultParams()`, an http scheme. That it is http is not very
  // important, but `url::SchemeHostPort` is difficult to use with unknown
  // schemes. See https://crbug.com/869291.
  scoped_refptr<TransportSocketParams> params = DefaultParams();
  ASSERT_TRUE(params->supported_alpns().empty());

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      std::move(params), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/false);

  IPEndPoint peer_address;
  test_delegate.socket()->GetPeerAddress(&peer_address);
  EXPECT_EQ(peer_address, IPEndPoint(ParseIP("3::"), 80));
}

// Test that, given multiple `HostResolverEndpointResult` results,
// `TransportConnectJob` reports failure if each one fails.
TEST_F(TransportConnectJobTest, MultipleRoutesAllFailed) {
  std::vector<HostResolverEndpointResult> endpoints(3);
  endpoints[0].ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441),
                               IPEndPoint(ParseIP("1.1.1.1"), 8441)};
  endpoints[0].metadata.supported_protocol_alpns = {"h3", "h2", "http/1.1"};
  endpoints[1].ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442),
                               IPEndPoint(ParseIP("2.2.2.2"), 8442)};
  endpoints[1].metadata.supported_protocol_alpns = {"h3"};
  endpoints[2].ip_endpoints = {IPEndPoint(ParseIP("3::"), 443),
                               IPEndPoint(ParseIP("3.3.3.3"), 443)};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(endpoints));

  MockTransportClientSocketFactory::Rule rules[] = {
      // `endpoints[0]`'s addresses each fail.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{endpoints[0].ip_endpoints[0]}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{endpoints[0].ip_endpoints[1]}),
      // `endpoints[1]` is skipped because the ALPN is not compatible.
      // `endpoints[2]`'s addresses each fail.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{endpoints[2].ip_endpoints[0]}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{endpoints[2].ip_endpoints[1]}),
  };

  client_socket_factory_.SetRules(rules);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job,
                                        ERR_CONNECTION_FAILED,
                                        /*expect_sync_result=*/false);

  // Check that failed connection attempts are reported.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(4u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("1::"), 8441));
  EXPECT_THAT(attempts[1].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[1].endpoint, IPEndPoint(ParseIP("1.1.1.1"), 8441));
  EXPECT_THAT(attempts[2].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[2].endpoint, IPEndPoint(ParseIP("3::"), 443));
  EXPECT_THAT(attempts[3].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[3].endpoint, IPEndPoint(ParseIP("3.3.3.3"), 443));
}

// Test that `TransportConnectJob` reports failure if all provided routes were
// unusable.
TEST_F(TransportConnectJobTest, NoUsableRoutes) {
  std::vector<HostResolverEndpointResult> endpoints(2);
  endpoints[0].ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441),
                               IPEndPoint(ParseIP("1.1.1.1"), 8441)};
  endpoints[0].metadata.supported_protocol_alpns = {"h3"};
  endpoints[1].ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442),
                               IPEndPoint(ParseIP("2.2.2.2"), 8442)};
  endpoints[1].metadata.supported_protocol_alpns = {"unrecognized-protocol"};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(endpoints));

  // `TransportConnectJob` should not create any sockets.
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kUnexpected);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job,
                                        ERR_NAME_NOT_RESOLVED,
                                        /*expect_sync_result=*/false);
}

// Test that, if the last route is unusable, the error from the
// previously-attempted route is preserved.
TEST_F(TransportConnectJobTest, LastRouteUnusable) {
  std::vector<HostResolverEndpointResult> endpoints(2);
  endpoints[0].ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441),
                               IPEndPoint(ParseIP("1.1.1.1"), 8441)};
  endpoints[0].metadata.supported_protocol_alpns = {"h3", "h2", "http/1.1"};
  endpoints[1].ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442),
                               IPEndPoint(ParseIP("2.2.2.2"), 8442)};
  endpoints[1].metadata.supported_protocol_alpns = {"h3"};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(endpoints));

  MockTransportClientSocketFactory::Rule rules[] = {
      // `endpoints[0]`'s addresses each fail.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{endpoints[0].ip_endpoints[0]}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{endpoints[0].ip_endpoints[1]}),
      // `endpoints[1]` is skipped because the ALPN is not compatible.
  };

  client_socket_factory_.SetRules(rules);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job,
                                        ERR_CONNECTION_FAILED,
                                        /*expect_sync_result=*/false);

  // Check that failed connection attempts are reported.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(2u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("1::"), 8441));
  EXPECT_THAT(attempts[1].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[1].endpoint, IPEndPoint(ParseIP("1.1.1.1"), 8441));
}

// `GetHostResolverEndpointResult` should surface information about the endpoint
// that was actually used.
TEST_F(TransportConnectJobTest, GetHostResolverEndpointResult) {
  std::vector<HostResolverEndpointResult> endpoints(4);
  // `endpoints[0]` will be skipped due to ALPN mismatch.
  endpoints[0].ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441)};
  endpoints[0].metadata.supported_protocol_alpns = {"h3"};
  endpoints[0].metadata.ech_config_list = {1, 2, 3, 4};
  // `endpoints[1]` will be skipped due to connection failure.
  endpoints[1].ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442)};
  endpoints[1].metadata.supported_protocol_alpns = {"http/1.1"};
  endpoints[1].metadata.ech_config_list = {5, 6, 7, 8};
  // `endpoints[2]` will succeed.
  endpoints[2].ip_endpoints = {IPEndPoint(ParseIP("3::"), 8443)};
  endpoints[2].metadata.supported_protocol_alpns = {"http/1.1"};
  endpoints[2].metadata.ech_config_list = {9, 10, 11, 12};
  // `endpoints[3]` will be not be tried because `endpoints[2]` will already
  // have succeeded.
  endpoints[3].ip_endpoints = {IPEndPoint(ParseIP("4::"), 8444)};
  endpoints[3].metadata.supported_protocol_alpns = {"http/1.1"};
  endpoints[3].metadata.ech_config_list = {13, 14, 15, 16};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(endpoints));

  MockTransportClientSocketFactory::Rule rules[] = {
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("2::"), 8442)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kSynchronous,
          std::vector{IPEndPoint(ParseIP("3::"), 8443)}),
  };
  client_socket_factory_.SetRules(rules);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/false);

  EXPECT_EQ(transport_connect_job.GetHostResolverEndpointResult(),
            endpoints[2]);
}

// If the client and server both support ECH, TransportConnectJob should switch
// to SVCB-reliant mode and disable the A/AAAA fallback.
TEST_F(TransportConnectJobTest, SvcbReliantIfEch) {
  HostResolverEndpointResult endpoint1, endpoint2, endpoint3;
  endpoint1.ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441)};
  endpoint1.metadata.supported_protocol_alpns = {"http/1.1"};
  endpoint1.metadata.ech_config_list = {1, 2, 3, 4};
  endpoint2.ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442)};
  endpoint2.metadata.supported_protocol_alpns = {"http/1.1"};
  endpoint2.metadata.ech_config_list = {1, 2, 3, 4};
  endpoint3.ip_endpoints = {IPEndPoint(ParseIP("3::"), 443)};
  // `endpoint3` has no `supported_protocol_alpns` and is thus a fallback route.
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(
                     std::vector{endpoint1, endpoint2, endpoint3}));

  // `TransportConnectJob` should not try `endpoint3`.
  MockTransportClientSocketFactory::Rule rules[] = {
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("1::"), 8441)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("2::"), 8442)}),
  };
  client_socket_factory_.SetRules(rules);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job,
                                        ERR_CONNECTION_FAILED,
                                        /*expect_sync_result=*/false);

  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(2u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("1::"), 8441));
  EXPECT_THAT(attempts[1].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[1].endpoint, IPEndPoint(ParseIP("2::"), 8442));
}

// SVCB-reliant mode should be disabled for ECH servers when ECH is disabled via
// config.
TEST_F(TransportConnectJobTest, SvcbOptionalIfEchDisabledConfig) {
  SSLContextConfig config;
  config.ech_enabled = false;
  ssl_config_service_.UpdateSSLConfigAndNotify(config);

  HostResolverEndpointResult endpoint1, endpoint2, endpoint3;
  endpoint1.ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441)};
  endpoint1.metadata.supported_protocol_alpns = {"http/1.1"};
  endpoint1.metadata.ech_config_list = {1, 2, 3, 4};
  endpoint2.ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442)};
  endpoint2.metadata.supported_protocol_alpns = {"http/1.1"};
  endpoint2.metadata.ech_config_list = {1, 2, 3, 4};
  endpoint3.ip_endpoints = {IPEndPoint(ParseIP("3::"), 443)};
  // `endpoint3` has no `supported_protocol_alpns` and is thus a fallback route.
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(
                     std::vector{endpoint1, endpoint2, endpoint3}));

  // `TransportConnectJob` should try `endpoint3`.
  MockTransportClientSocketFactory::Rule rules[] = {
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("1::"), 8441)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("2::"), 8442)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kSynchronous,
          std::vector{IPEndPoint(ParseIP("3::"), 443)}),
  };
  client_socket_factory_.SetRules(rules);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/false);
}

// SVCB-reliant mode should be disabled if not all SVCB/HTTPS records include
// ECH.
TEST_F(TransportConnectJobTest, SvcbOptionalIfEchInconsistent) {
  HostResolverEndpointResult endpoint1, endpoint2, endpoint3;
  endpoint1.ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441)};
  endpoint1.metadata.supported_protocol_alpns = {"http/1.1"};
  endpoint1.metadata.ech_config_list = {1, 2, 3, 4};
  endpoint2.ip_endpoints = {IPEndPoint(ParseIP("2::"), 8442)};
  endpoint2.metadata.supported_protocol_alpns = {"http/1.1"};
  endpoint2.metadata.ech_config_list = {};
  endpoint3.ip_endpoints = {IPEndPoint(ParseIP("3::"), 443)};
  // `endpoint3` has no `supported_protocol_alpns` and is thus a fallback route.
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(
                     std::vector{endpoint1, endpoint2, endpoint3}));

  // `TransportConnectJob` should try `endpoint3`.
  MockTransportClientSocketFactory::Rule rules[] = {
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("1::"), 8441)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("2::"), 8442)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kSynchronous,
          std::vector{IPEndPoint(ParseIP("3::"), 443)}),
  };
  client_socket_factory_.SetRules(rules);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/false);
}

// Overriding the endpoint results should skip DNS resolution.
TEST_F(TransportConnectJobTest, EndpointResultOverride) {
  // Make DNS resolution fail, to confirm we don't use the result.
  host_resolver_.rules()->AddRule(kHostName, ERR_FAILED);

  // `TransportConnectJob` should try `endpoint`.
  HostResolverEndpointResult endpoint;
  endpoint.ip_endpoints = {IPEndPoint(ParseIP("1::"), 8441)};
  endpoint.metadata.supported_protocol_alpns = {"http/1.1"};
  MockTransportClientSocketFactory::Rule rules[] = {
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kSynchronous,
          endpoint.ip_endpoints),
  };
  client_socket_factory_.SetRules(rules);

  TransportConnectJob::EndpointResultOverride override(
      endpoint, {"alias.example", kHostName});
  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr, override);
  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/true);

  // Verify information is reported from the override.
  EXPECT_EQ(transport_connect_job.GetHostResolverEndpointResult(), endpoint);
  EXPECT_THAT(test_delegate.socket()->GetDnsAliases(),
              testing::ElementsAre("alias.example", kHostName));
}

// If two `HostResolverEndpointResult`s share an IP endpoint,
// `TransportConnectJob` should not try to connect a second time.
TEST_F(TransportConnectJobTest, DedupIPEndPoints) {
  std::vector<HostResolverEndpointResult> endpoints(4);
  // Some initial IPEndPoints.
  endpoints[0].ip_endpoints = {IPEndPoint(ParseIP("1::"), 443),
                               IPEndPoint(ParseIP("1.1.1.1"), 443)};
  endpoints[0].metadata.supported_protocol_alpns = {"h2", "http/1.1"};
  // Contains a new IPEndPoint, but no common protocols.
  endpoints[1].ip_endpoints = {IPEndPoint(ParseIP("2::"), 443)};
  endpoints[1].metadata.supported_protocol_alpns = {"h3"};
  // Contains mixture of previously seen and new IPEndPoints, so we should only
  // try a subset of them.
  endpoints[2].ip_endpoints = {
      // Duplicate from `endpoints[0]`, should be filtered out.
      IPEndPoint(ParseIP("1::"), 443),
      // Same IP but new port. Should be used.
      IPEndPoint(ParseIP("1::"), 444),
      // Duplicate from `endpoints[1]`, but `endpoints[1]` was dropped, so this
      // should be used.
      IPEndPoint(ParseIP("2::"), 443),
      // Duplicate from `endpoints[0]`, should be filtered out.
      IPEndPoint(ParseIP("1.1.1.1"), 443),
      // New endpoint. Should be used.
      IPEndPoint(ParseIP("2.2.2.2"), 443)};
  endpoints[2].metadata.supported_protocol_alpns = {"h2", "http/1.1"};
  // Contains only previously seen IPEndPoints, so should be filtered out
  // entirely.
  endpoints[3].ip_endpoints = {IPEndPoint(ParseIP("1::"), 443),
                               IPEndPoint(ParseIP("1::"), 444),
                               IPEndPoint(ParseIP("2.2.2.2"), 443)};
  endpoints[3].metadata.supported_protocol_alpns = {"h2", "http/1.1"};
  host_resolver_.rules()->AddRule(
      kHostName, MockHostResolverBase::RuleResolver::RuleResult(endpoints));

  MockTransportClientSocketFactory::Rule rules[] = {
      // First, try `endpoints[0]`'s addresses.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("1::"), 443)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("1.1.1.1"), 443)}),

      // `endpoints[1]` is unusable, so it is ignored, including for purposes of
      // duplicate endpoints.

      // Only new IP endpoints from `endpoints[2]` should be considered. Note
      // different ports count as different endpoints.
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("1::"), 444)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("2::"), 443)}),
      MockTransportClientSocketFactory::Rule(
          MockTransportClientSocketFactory::Type::kFailing,
          std::vector{IPEndPoint(ParseIP("2.2.2.2"), 443)}),

      // `endpoints[3]` only contains duplicate IP endpoints and should be
      // skipped.
  };

  client_socket_factory_.SetRules(rules);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultHttpsParams(), &test_delegate, /*net_log=*/nullptr);
  test_delegate.StartJobExpectingResult(&transport_connect_job,
                                        ERR_CONNECTION_FAILED,
                                        /*expect_sync_result=*/false);

  // Check that failed connection attempts are reported.
  ConnectionAttempts attempts = transport_connect_job.GetConnectionAttempts();
  ASSERT_EQ(5u, attempts.size());
  EXPECT_THAT(attempts[0].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[0].endpoint, IPEndPoint(ParseIP("1::"), 443));
  EXPECT_THAT(attempts[1].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[1].endpoint, IPEndPoint(ParseIP("1.1.1.1"), 443));
  EXPECT_THAT(attempts[2].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[2].endpoint, IPEndPoint(ParseIP("1::"), 444));
  EXPECT_THAT(attempts[3].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[3].endpoint, IPEndPoint(ParseIP("2::"), 443));
  EXPECT_THAT(attempts[4].result, test::IsError(ERR_CONNECTION_FAILED));
  EXPECT_EQ(attempts[4].endpoint, IPEndPoint(ParseIP("2.2.2.2"), 443));
}

TEST_F(TransportConnectJobTest,
       OnDestinationDnsAliasesResolved_Skipped_IfNoAliases) {
  host_resolver_.set_synchronous_mode(true);
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kSynchronous);

  std::vector<std::string> aliases;
  host_resolver_.rules()->AddIPLiteralRuleWithDnsAliases(kHostName, "2.2.2.2",
                                                         std::move(aliases));

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, /*net_log=*/nullptr);

  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/true);

  // Ensure the delegate method is NOT invoked because no DNS aliases were
  // resolved.
  EXPECT_FALSE(test_delegate.on_dns_aliases_resolved_called());
}

TEST_F(TransportConnectJobTest,
       OnDestinationDnsAliasesResolved_Skipped_IfOnlyDestinationEndpoint) {
  std::vector<std::string> aliases({kHostName});

  host_resolver_.set_synchronous_mode(true);
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kSynchronous);

  host_resolver_.rules()->AddIPLiteralRuleWithDnsAliases(kHostName, "2.2.2.2",
                                                         std::move(aliases));

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, /*net_log=*/nullptr);

  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/true);

  // Ensure the delegate method is NOT invoked because aliases only contain the
  // destination endpoint.
  EXPECT_FALSE(test_delegate.on_dns_aliases_resolved_called());
}

TEST_F(TransportConnectJobTest,
       OnDestinationDnsAliasesResolved_Invoked_IfOneAlias) {
  std::vector<std::string> aliases({"alias1"});
  std::set<std::string> aliases_set(aliases.begin(), aliases.end());
  host_resolver_.rules()->AddIPLiteralRuleWithDnsAliases(kHostName, "2.2.2.2",
                                                         std::move(aliases));
  host_resolver_.set_synchronous_mode(true);
  client_socket_factory_.set_default_client_socket_type(
      MockTransportClientSocketFactory::Type::kSynchronous);

  TestConnectJobDelegate test_delegate;
  TransportConnectJob transport_connect_job(
      DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
      DefaultParams(), &test_delegate, /*net_log=*/nullptr);

  test_delegate.StartJobExpectingResult(&transport_connect_job, OK,
                                        /*expect_sync_result=*/true);

  // Verify that the delegate method was called when aliases are resolved.
  EXPECT_TRUE(test_delegate.on_dns_aliases_resolved_called());
  EXPECT_EQ(test_delegate.dns_aliases(), aliases_set);
}

TEST_F(TransportConnectJobTest, OnDestinationDnsAliasesResolved_Invoked_OK) {
  std::vector<std::string> aliases({"alias1", "alias2", kHostName});
  std::set<std::string> aliases_set(aliases.begin(), aliases.end());
  host_resolver_.rules()->AddIPLiteralRuleWithDnsAliases(kHostName, "2.2.2.2",
                                                         std::move(aliases));

  for (bool host_resolution_synchronous : {false, true}) {
    SCOPED_TRACE(host_resolution_synchronous);
    for (bool connection_synchronous : {false, true}) {
      SCOPED_TRACE(connection_synchronous);
      host_resolver_.set_synchronous_mode(host_resolution_synchronous);
      client_socket_factory_.set_default_client_socket_type(
          connection_synchronous
              ? MockTransportClientSocketFactory::Type::kSynchronous
              : MockTransportClientSocketFactory::Type::kPending);

      TestConnectJobDelegate test_delegate;
      TransportConnectJob transport_connect_job(
          DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
          DefaultParams(), &test_delegate, /*net_log=*/nullptr);

      test_delegate.StartJobExpectingResult(
          &transport_connect_job, OK,
          host_resolution_synchronous && connection_synchronous);

      // Verify that the delegate method was called when aliases are resolved.
      EXPECT_TRUE(test_delegate.on_dns_aliases_resolved_called());
      EXPECT_EQ(test_delegate.dns_aliases(), aliases_set);
    }
  }
}

TEST_F(TransportConnectJobTest, OnDestinationDnsAliasesResolved_Invoked_Error) {
  std::vector<std::string> aliases({"alias1", "alias2", kHostName});
  std::set<std::string> aliases_set(aliases.begin(), aliases.end());
  host_resolver_.rules()->AddIPLiteralRuleWithDnsAliases(kHostName, "2.2.2.2",
                                                         std::move(aliases));

  for (bool host_resolution_synchronous : {false, true}) {
    SCOPED_TRACE(host_resolution_synchronous);
    for (bool connection_synchronous : {false, true}) {
      SCOPED_TRACE(connection_synchronous);
      host_resolver_.set_synchronous_mode(host_resolution_synchronous);
      client_socket_factory_.set_default_client_socket_type(
          connection_synchronous
              ? MockTransportClientSocketFactory::Type::kFailing
              : MockTransportClientSocketFactory::Type::kPendingFailing);

      TestConnectJobDelegate test_delegate;
      TransportConnectJob transport_connect_job(
          DEFAULT_PRIORITY, SocketTag(), &common_connect_job_params_,
          DefaultParams(), &test_delegate, /*net_log=*/nullptr);
      test_delegate.set_error_for_on_destination_dns_aliases_resolved(
          ERR_PROXY_REQUIRED);

      test_delegate.StartJobExpectingResult(&transport_connect_job,
                                            ERR_PROXY_REQUIRED,
                                            host_resolution_synchronous);

      // Verify that the delegate method was called when aliases are resolved.
      EXPECT_TRUE(test_delegate.on_dns_aliases_resolved_called());
      EXPECT_EQ(test_delegate.dns_aliases(), aliases_set);
    }
  }
}

}  // namespace
}  // namespace net