/
url_request_unittest.cc
13052 lines (11033 loc) · 492 KB
/
url_request_unittest.cc
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include <algorithm>
#include <iterator>
#include <limits>
#include <memory>
#include <utility>
// This must be before Windows headers
#include "base/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "build/build_config.h"
#include "net/dns/public/secure_dns_policy.h"
#include "net/log/net_log.h"
#include "url/url_constants.h"
#if defined(OS_WIN)
#include <objbase.h>
#include <shlobj.h>
#include <windows.h>
#include <wrl/client.h>
#endif
#include "base/base64url.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/cxx17_backports.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/format_macros.h"
#include "base/json/json_reader.h"
#include "base/location.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "build/buildflag.h"
#include "crypto/sha2.h"
#include "net/base/chunked_upload_data_stream.h"
#include "net/base/directory_listing.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/escape.h"
#include "net/base/features.h"
#include "net/base/hash_value.h"
#include "net/base/ip_address.h"
#include "net/base/ip_endpoint.h"
#include "net/base/isolation_info.h"
#include "net/base/load_flags.h"
#include "net/base/load_timing_info.h"
#include "net/base/load_timing_info_test_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_module.h"
#include "net/base/proxy_server.h"
#include "net/base/proxy_string_util.h"
#include "net/base/request_priority.h"
#include "net/base/test_completion_callback.h"
#include "net/base/transport_info.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_file_element_reader.h"
#include "net/base/url_util.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_net_fetcher.h"
#include "net/cert/crl_set.h"
#include "net/cert/ct_policy_enforcer.h"
#include "net/cert/ct_policy_status.h"
#include "net/cert/do_nothing_ct_verifier.h"
#include "net/cert/ev_root_ca_metadata.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/multi_log_ct_verifier.h"
#include "net/cert/signed_certificate_timestamp_and_status.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_util.h"
#include "net/cert_net/cert_net_fetcher_url_request.h"
#include "net/cookies/canonical_cookie_test_helpers.h"
#include "net/cookies/cookie_inclusion_status.h"
#include "net/cookies/cookie_monster.h"
#include "net/cookies/cookie_store_test_helpers.h"
#include "net/cookies/test_cookie_access_delegate.h"
#include "net/disk_cache/disk_cache.h"
#include "net/dns/mock_host_resolver.h"
#include "net/dns/public/secure_dns_policy.h"
#include "net/http/http_byte_range.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_layer.h"
#include "net/http/http_network_session.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_server_properties.h"
#include "net/http/http_transaction_test_util.h"
#include "net/http/http_util.h"
#include "net/http/transport_security_state.h"
#include "net/http/transport_security_state_source.h"
#include "net/log/file_net_log_observer.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_util.h"
#include "net/net_buildflags.h"
#include "net/proxy_resolution/configured_proxy_resolution_service.h"
#include "net/quic/mock_crypto_client_stream_factory.h"
#include "net/quic/quic_server_info.h"
#include "net/socket/read_buffering_stream_socket.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/ssl_client_socket.h"
#include "net/ssl/client_cert_identity_test_util.h"
#include "net/ssl/ssl_connection_status_flags.h"
#include "net/ssl/ssl_private_key.h"
#include "net/ssl/ssl_server_config.h"
#include "net/ssl/test_ssl_config_service.h"
#include "net/test/cert_test_util.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/gtest_util.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/test/test_data_directory.h"
#include "net/test/test_with_task_environment.h"
#include "net/test/url_request/url_request_failed_job.h"
#include "net/test/url_request/url_request_mock_http_job.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/redirect_util.h"
#include "net/url_request/referrer_policy.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_filter.h"
#include "net/url_request/url_request_http_job.h"
#include "net/url_request/url_request_interceptor.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_redirect_job.h"
#include "net/url_request/url_request_test_job.h"
#include "net/url_request/url_request_test_util.h"
#include "net/url_request/websocket_handshake_userdata_key.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/url_constants.h"
#include "url/url_util.h"
#if defined(OS_WIN)
#include "base/win/scoped_com_initializer.h"
#endif
#if defined(OS_APPLE)
#include "base/mac/mac_util.h"
#endif
#if BUILDFLAG(ENABLE_REPORTING)
#include "net/network_error_logging/network_error_logging_service.h"
#include "net/network_error_logging/network_error_logging_test_util.h"
#endif // BUILDFLAG(ENABLE_REPORTING)
#if BUILDFLAG(ENABLE_WEBSOCKETS)
#include "net/websockets/websocket_test_util.h"
#endif // BUILDFLAG(ENABLE_WEBSOCKETS)
using net::test::IsError;
using net::test::IsOk;
using net::test_server::RegisterDefaultHandlers;
using testing::_;
using testing::AnyOf;
using testing::ElementsAre;
using testing::IsEmpty;
using testing::Optional;
using testing::UnorderedElementsAre;
using base::ASCIIToUTF16;
using base::Time;
using std::string;
namespace net {
namespace {
namespace test_default {
#include "net/http/transport_security_state_static_unittest_default.h"
}
const std::u16string kChrome(u"chrome");
const std::u16string kSecret(u"secret");
const std::u16string kUser(u"user");
const base::FilePath::CharType kTestFilePath[] =
FILE_PATH_LITERAL("net/data/url_request_unittest");
// Tests load timing information in the case a fresh connection was used, with
// no proxy.
void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
int connect_timing_flags) {
EXPECT_FALSE(load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
EXPECT_FALSE(load_timing_info.request_start_time.is_null());
EXPECT_FALSE(load_timing_info.request_start.is_null());
EXPECT_LE(load_timing_info.request_start,
load_timing_info.connect_timing.connect_start);
ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
connect_timing_flags);
EXPECT_LE(load_timing_info.connect_timing.connect_end,
load_timing_info.send_start);
EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
EXPECT_LE(load_timing_info.receive_headers_start,
load_timing_info.receive_headers_end);
EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
}
// Same as above, but with proxy times.
void TestLoadTimingNotReusedWithProxy(const LoadTimingInfo& load_timing_info,
int connect_timing_flags) {
EXPECT_FALSE(load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
EXPECT_FALSE(load_timing_info.request_start_time.is_null());
EXPECT_FALSE(load_timing_info.request_start.is_null());
EXPECT_LE(load_timing_info.request_start,
load_timing_info.proxy_resolve_start);
EXPECT_LE(load_timing_info.proxy_resolve_start,
load_timing_info.proxy_resolve_end);
EXPECT_LE(load_timing_info.proxy_resolve_end,
load_timing_info.connect_timing.connect_start);
ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
connect_timing_flags);
EXPECT_LE(load_timing_info.connect_timing.connect_end,
load_timing_info.send_start);
EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
EXPECT_LE(load_timing_info.receive_headers_start,
load_timing_info.receive_headers_end);
}
// Same as above, but with a reused socket and proxy times.
void TestLoadTimingReusedWithProxy(const LoadTimingInfo& load_timing_info) {
EXPECT_TRUE(load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
EXPECT_FALSE(load_timing_info.request_start_time.is_null());
EXPECT_FALSE(load_timing_info.request_start.is_null());
ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
EXPECT_LE(load_timing_info.request_start,
load_timing_info.proxy_resolve_start);
EXPECT_LE(load_timing_info.proxy_resolve_start,
load_timing_info.proxy_resolve_end);
EXPECT_LE(load_timing_info.proxy_resolve_end, load_timing_info.send_start);
EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
EXPECT_LE(load_timing_info.receive_headers_start,
load_timing_info.receive_headers_end);
}
CookieList GetAllCookies(URLRequestContext* request_context) {
CookieList cookie_list;
base::RunLoop run_loop;
request_context->cookie_store()->GetAllCookiesAsync(
base::BindLambdaForTesting([&](const CookieList& cookies) {
cookie_list = cookies;
run_loop.Quit();
}));
run_loop.Run();
return cookie_list;
}
void TestLoadTimingCacheHitNoNetwork(const LoadTimingInfo& load_timing_info) {
EXPECT_FALSE(load_timing_info.socket_reused);
EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
EXPECT_FALSE(load_timing_info.request_start_time.is_null());
EXPECT_FALSE(load_timing_info.request_start.is_null());
ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
EXPECT_LE(load_timing_info.receive_headers_start,
load_timing_info.receive_headers_end);
EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
}
// Job that allows monitoring of its priority.
class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
public:
// The latest priority of the job is always written to |request_priority_|.
PriorityMonitoringURLRequestJob(URLRequest* request,
RequestPriority* request_priority)
: URLRequestTestJob(request), request_priority_(request_priority) {
*request_priority_ = DEFAULT_PRIORITY;
}
void SetPriority(RequestPriority priority) override {
*request_priority_ = priority;
URLRequestTestJob::SetPriority(priority);
}
private:
RequestPriority* const request_priority_;
};
// Do a case-insensitive search through |haystack| for |needle|.
bool ContainsString(const std::string& haystack, const char* needle) {
std::string::const_iterator it = std::search(
haystack.begin(), haystack.end(), needle, needle + strlen(needle),
base::CaseInsensitiveCompareASCII<char>());
return it != haystack.end();
}
std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
std::unique_ptr<UploadElementReader> reader(
new UploadBytesElementReader(data, strlen(data)));
return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
}
// Verify that the SSLInfo of a successful SSL connection has valid values.
void CheckSSLInfo(const SSLInfo& ssl_info) {
// The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
uint16_t cipher_suite =
SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
EXPECT_NE(0U, cipher_suite);
}
// A network delegate that allows the user to choose a subset of request stages
// to block in. When blocking, the delegate can do one of the following:
// * synchronously return a pre-specified error code, or
// * asynchronously return that value via an automatically called callback,
// or
// * block and wait for the user to do a callback.
// Additionally, the user may also specify a redirect URL -- then each request
// with the current URL different from the redirect target will be redirected
// to that target, in the on-before-URL-request stage, independent of whether
// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
class BlockingNetworkDelegate : public TestNetworkDelegate {
public:
// Stages in which the delegate can block.
enum Stage {
NOT_BLOCKED = 0,
ON_BEFORE_URL_REQUEST = 1 << 0,
ON_BEFORE_SEND_HEADERS = 1 << 1,
ON_HEADERS_RECEIVED = 1 << 2,
};
// Behavior during blocked stages. During other stages, just
// returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
enum BlockMode {
SYNCHRONOUS, // No callback, returns specified return values.
AUTO_CALLBACK, // |this| posts a task to run the callback using the
// specified return codes.
USER_CALLBACK, // User takes care of doing a callback. |retval_| and
// |auth_retval_| are ignored. In every blocking stage the
// message loop is quit.
};
// Creates a delegate which does not block at all.
explicit BlockingNetworkDelegate(BlockMode block_mode);
BlockingNetworkDelegate(const BlockingNetworkDelegate&) = delete;
BlockingNetworkDelegate& operator=(const BlockingNetworkDelegate&) = delete;
// Runs the message loop until the delegate blocks.
void RunUntilBlocked();
// For users to trigger a callback returning |response|.
// Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
// Only call if |block_mode_| == USER_CALLBACK.
void DoCallback(int response);
// Setters.
void set_retval(int retval) {
ASSERT_NE(USER_CALLBACK, block_mode_);
ASSERT_NE(ERR_IO_PENDING, retval);
ASSERT_NE(OK, retval);
retval_ = retval;
}
void set_redirect_url(const GURL& url) { redirect_url_ = url; }
void set_block_on(int block_on) { block_on_ = block_on; }
// Allows the user to check in which state did we block.
Stage stage_blocked_for_callback() const {
EXPECT_EQ(USER_CALLBACK, block_mode_);
return stage_blocked_for_callback_;
}
private:
void OnBlocked();
void RunCallback(int response, CompletionOnceCallback callback);
// TestNetworkDelegate implementation.
int OnBeforeURLRequest(URLRequest* request,
CompletionOnceCallback callback,
GURL* new_url) override;
int OnBeforeStartTransaction(
URLRequest* request,
const HttpRequestHeaders& headers,
OnBeforeStartTransactionCallback callback) override;
int OnHeadersReceived(
URLRequest* request,
CompletionOnceCallback callback,
const HttpResponseHeaders* original_response_headers,
scoped_refptr<HttpResponseHeaders>* override_response_headers,
const IPEndPoint& endpoint,
absl::optional<GURL>* preserve_fragment_on_redirect_url) override;
// Resets the callbacks and |stage_blocked_for_callback_|.
void Reset();
// Checks whether we should block in |stage|. If yes, returns an error code
// and optionally sets up callback based on |block_mode_|. If no, returns OK.
int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
// Configuration parameters, can be adjusted by public methods:
const BlockMode block_mode_;
// Values returned on blocking stages when mode is SYNCHRONOUS or
// AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
int retval_;
GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
int block_on_; // Bit mask: in which stages to block.
// Internal variables, not set by not the user:
// Last blocked stage waiting for user callback (unused if |block_mode_| !=
// USER_CALLBACK).
Stage stage_blocked_for_callback_;
// Callback objects stored during blocking stages.
CompletionOnceCallback callback_;
// Closure to run to exit RunUntilBlocked().
base::OnceClosure on_blocked_;
base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_{this};
};
BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
: block_mode_(block_mode),
retval_(OK),
block_on_(0),
stage_blocked_for_callback_(NOT_BLOCKED) {}
void BlockingNetworkDelegate::RunUntilBlocked() {
base::RunLoop run_loop;
on_blocked_ = run_loop.QuitClosure();
run_loop.Run();
}
void BlockingNetworkDelegate::DoCallback(int response) {
ASSERT_EQ(USER_CALLBACK, block_mode_);
ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
CompletionOnceCallback callback = std::move(callback_);
Reset();
// |callback| may trigger completion of a request, so post it as a task, so
// it will run under a subsequent TestDelegate::RunUntilComplete() loop.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
weak_factory_.GetWeakPtr(), response,
std::move(callback)));
}
void BlockingNetworkDelegate::OnBlocked() {
// If this fails due to |on_blocked_| being null then OnBlocked() was run by
// a RunLoop other than RunUntilBlocked(), indicating a bug in the calling
// test.
std::move(on_blocked_).Run();
}
void BlockingNetworkDelegate::RunCallback(int response,
CompletionOnceCallback callback) {
std::move(callback).Run(response);
}
int BlockingNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
CompletionOnceCallback callback,
GURL* new_url) {
if (redirect_url_ == request->url())
return OK; // We've already seen this request and redirected elsewhere.
// TestNetworkDelegate always completes synchronously.
CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
request, base::NullCallback(), new_url));
if (!redirect_url_.is_empty())
*new_url = redirect_url_;
return MaybeBlockStage(ON_BEFORE_URL_REQUEST, std::move(callback));
}
int BlockingNetworkDelegate::OnBeforeStartTransaction(
URLRequest* request,
const HttpRequestHeaders& headers,
OnBeforeStartTransactionCallback callback) {
// TestNetworkDelegate always completes synchronously.
CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
request, headers, base::NullCallback()));
return MaybeBlockStage(
ON_BEFORE_SEND_HEADERS,
base::BindOnce(
[](OnBeforeStartTransactionCallback callback, int result) {
std::move(callback).Run(result, absl::nullopt);
},
std::move(callback)));
}
int BlockingNetworkDelegate::OnHeadersReceived(
URLRequest* request,
CompletionOnceCallback callback,
const HttpResponseHeaders* original_response_headers,
scoped_refptr<HttpResponseHeaders>* override_response_headers,
const IPEndPoint& endpoint,
absl::optional<GURL>* preserve_fragment_on_redirect_url) {
// TestNetworkDelegate always completes synchronously.
CHECK_NE(ERR_IO_PENDING,
TestNetworkDelegate::OnHeadersReceived(
request, base::NullCallback(), original_response_headers,
override_response_headers, endpoint,
preserve_fragment_on_redirect_url));
return MaybeBlockStage(ON_HEADERS_RECEIVED, std::move(callback));
}
void BlockingNetworkDelegate::Reset() {
EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
stage_blocked_for_callback_ = NOT_BLOCKED;
callback_.Reset();
}
int BlockingNetworkDelegate::MaybeBlockStage(
BlockingNetworkDelegate::Stage stage,
CompletionOnceCallback callback) {
// Check that the user has provided callback for the previous blocked stage.
EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
if ((block_on_ & stage) == 0) {
return OK;
}
switch (block_mode_) {
case SYNCHRONOUS:
EXPECT_NE(OK, retval_);
return retval_;
case AUTO_CALLBACK:
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
weak_factory_.GetWeakPtr(), retval_,
std::move(callback)));
return ERR_IO_PENDING;
case USER_CALLBACK:
callback_ = std::move(callback);
stage_blocked_for_callback_ = stage;
// We may reach here via a callback prior to RunUntilBlocked(), so post
// a task to fetch and run the |on_blocked_| closure.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
weak_factory_.GetWeakPtr()));
return ERR_IO_PENDING;
}
NOTREACHED();
return 0;
}
class TestURLRequestContextWithProxy : public TestURLRequestContext {
public:
// Does not own |delegate|.
TestURLRequestContextWithProxy(const std::string& proxy,
NetworkDelegate* delegate,
bool delay_initialization = false)
: TestURLRequestContext(true) {
context_storage_.set_proxy_resolution_service(
ConfiguredProxyResolutionService::CreateFixed(
proxy, TRAFFIC_ANNOTATION_FOR_TESTS));
set_network_delegate(delegate);
if (!delay_initialization)
Init();
}
~TestURLRequestContextWithProxy() override = default;
};
// A mock ReportSenderInterface that just remembers the latest report
// URI and report to be sent.
class MockCertificateReportSender
: public TransportSecurityState::ReportSenderInterface {
public:
MockCertificateReportSender() = default;
~MockCertificateReportSender() override = default;
void Send(
const GURL& report_uri,
base::StringPiece content_type,
base::StringPiece report,
const NetworkIsolationKey& network_isolation_key,
base::OnceCallback<void()> success_callback,
base::OnceCallback<void(const GURL&, int, int)> error_callback) override {
latest_report_uri_ = report_uri;
latest_report_.assign(report.data(), report.size());
latest_content_type_.assign(content_type.data(), content_type.size());
latest_network_isolation_key_ = network_isolation_key;
}
const GURL& latest_report_uri() { return latest_report_uri_; }
const std::string& latest_report() { return latest_report_; }
const std::string& latest_content_type() { return latest_content_type_; }
const NetworkIsolationKey& latest_network_isolation_key() {
return latest_network_isolation_key_;
}
private:
GURL latest_report_uri_;
std::string latest_report_;
std::string latest_content_type_;
NetworkIsolationKey latest_network_isolation_key_;
};
// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
// This is needed because after the certificate failure, the URLRequest will
// retry the connection, and return a partial SSLInfo with a cached cert status.
// The partial SSLInfo does not have the OCSP information filled out.
class OCSPErrorTestDelegate : public TestDelegate {
public:
void OnSSLCertificateError(URLRequest* request,
int net_error,
const SSLInfo& ssl_info,
bool fatal) override {
ssl_info_ = ssl_info;
on_ssl_certificate_error_called_ = true;
TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
}
bool on_ssl_certificate_error_called() {
return on_ssl_certificate_error_called_;
}
SSLInfo ssl_info() { return ssl_info_; }
private:
bool on_ssl_certificate_error_called_ = false;
SSLInfo ssl_info_;
};
#if !defined(OS_IOS)
// Compute the root cert's SPKI hash on the fly, to avoid hardcoding it within
// tests.
bool GetTestRootCertSPKIHash(SHA256HashValue* root_hash) {
scoped_refptr<X509Certificate> root_cert =
ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
if (!root_cert)
return false;
base::StringPiece root_spki;
if (!asn1::ExtractSPKIFromDERCert(
x509_util::CryptoBufferAsStringPiece(root_cert->cert_buffer()),
&root_spki)) {
return false;
}
crypto::SHA256HashString(root_spki, root_hash, sizeof(SHA256HashValue));
return true;
}
#endif
} // namespace
// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
class URLRequestTest : public PlatformTest, public WithTaskEnvironment {
public:
URLRequestTest()
: job_factory_(std::make_unique<URLRequestJobFactory>()),
default_context_(std::make_unique<TestURLRequestContext>(true)) {
default_context_->set_network_delegate(&default_network_delegate_);
default_context_->set_net_log(NetLog::Get());
}
~URLRequestTest() override {
// URLRequestJobs may post clean-up tasks on destruction.
base::RunLoop().RunUntilIdle();
SetTransportSecurityStateSourceForTesting(nullptr);
}
void SetUp() override {
SetUpFactory();
default_context_->set_job_factory(job_factory_.get());
default_context_->Init();
PlatformTest::SetUp();
}
void TearDown() override { default_context_.reset(); }
virtual void SetUpFactory() {}
TestNetworkDelegate* default_network_delegate() {
return &default_network_delegate_;
}
TestURLRequestContext& default_context() const { return *default_context_; }
// Creates a temp test file and writes |data| to the file. The file will be
// deleted after the test completes.
void CreateTestFile(const char* data,
size_t data_size,
base::FilePath* test_file) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
// Get an absolute path since |temp_dir| can contain a symbolic link. As of
// now, Mac and Android bots return a path with a symbolic link.
base::FilePath absolute_temp_dir =
base::MakeAbsoluteFilePath(temp_dir_.GetPath());
ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
ASSERT_EQ(static_cast<int>(data_size),
base::WriteFile(*test_file, data, data_size));
}
protected:
RecordingNetLogObserver net_log_observer_;
TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
std::unique_ptr<URLRequestJobFactory> job_factory_;
std::unique_ptr<TestURLRequestContext> default_context_;
base::ScopedTempDir temp_dir_;
};
TEST_F(URLRequestTest, AboutBlankTest) {
TestDelegate d;
{
std::unique_ptr<URLRequest> r(
default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
&d, TRAFFIC_ANNOTATION_FOR_TESTS));
r->Start();
EXPECT_TRUE(r->is_pending());
d.RunUntilComplete();
EXPECT_TRUE(!r->is_pending());
EXPECT_FALSE(d.received_data_before_response());
EXPECT_EQ(d.bytes_received(), 0);
EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
}
}
TEST_F(URLRequestTest, InvalidUrlTest) {
TestDelegate d;
{
std::unique_ptr<URLRequest> r(
default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
&d, TRAFFIC_ANNOTATION_FOR_TESTS));
r->Start();
EXPECT_TRUE(r->is_pending());
d.RunUntilComplete();
EXPECT_TRUE(d.request_failed());
}
}
// Test that URLRequest rejects WS URLs by default.
TEST_F(URLRequestTest, WsUrlTest) {
const url::Origin kOrigin = url::Origin::Create(GURL("http://foo.test/"));
TestDelegate d;
std::unique_ptr<URLRequest> r(
default_context().CreateRequest(GURL("ws://foo.test/"), DEFAULT_PRIORITY,
&d, TRAFFIC_ANNOTATION_FOR_TESTS));
// This is not strictly necessary for this test, but used to trigger a DCHECK.
// See https://crbug.com/1245115.
r->set_isolation_info(
IsolationInfo::Create(IsolationInfo::RequestType::kMainFrame, kOrigin,
kOrigin, SiteForCookies::FromOrigin(kOrigin)));
r->Start();
d.RunUntilComplete();
EXPECT_TRUE(d.request_failed());
EXPECT_THAT(d.request_status(), IsError(ERR_UNKNOWN_URL_SCHEME));
}
// Test that URLRequest rejects WSS URLs by default.
TEST_F(URLRequestTest, WssUrlTest) {
const url::Origin kOrigin = url::Origin::Create(GURL("https://foo.test/"));
TestDelegate d;
std::unique_ptr<URLRequest> r(
default_context().CreateRequest(GURL("wss://foo.test/"), DEFAULT_PRIORITY,
&d, TRAFFIC_ANNOTATION_FOR_TESTS));
// This is not strictly necessary for this test, but used to trigger a DCHECK.
// See https://crbug.com/1245115.
r->set_isolation_info(
IsolationInfo::Create(IsolationInfo::RequestType::kMainFrame, kOrigin,
kOrigin, SiteForCookies::FromOrigin(kOrigin)));
r->Start();
d.RunUntilComplete();
EXPECT_TRUE(d.request_failed());
EXPECT_THAT(d.request_status(), IsError(ERR_UNKNOWN_URL_SCHEME));
}
TEST_F(URLRequestTest, InvalidReferrerTest) {
TestURLRequestContext context;
TestNetworkDelegate network_delegate;
network_delegate.set_cancel_request_with_policy_violating_referrer(true);
context.set_network_delegate(&network_delegate);
TestDelegate d;
std::unique_ptr<URLRequest> req(
context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
TRAFFIC_ANNOTATION_FOR_TESTS));
req->SetReferrer("https://somewhere.com/");
req->Start();
d.RunUntilComplete();
EXPECT_TRUE(d.request_failed());
}
TEST_F(URLRequestTest, RecordsSameOriginReferrerHistogram) {
TestURLRequestContext context;
TestNetworkDelegate network_delegate;
network_delegate.set_cancel_request_with_policy_violating_referrer(false);
context.set_network_delegate(&network_delegate);
TestDelegate d;
std::unique_ptr<URLRequest> req(
context.CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
TRAFFIC_ANNOTATION_FOR_TESTS));
req->SetReferrer("http://google.com");
req->set_referrer_policy(ReferrerPolicy::NEVER_CLEAR);
base::HistogramTester histograms;
req->Start();
d.RunUntilComplete();
histograms.ExpectUniqueSample(
"Net.URLRequest.ReferrerPolicyForRequest.SameOrigin",
static_cast<int>(ReferrerPolicy::NEVER_CLEAR), 1);
}
TEST_F(URLRequestTest, RecordsCrossOriginReferrerHistogram) {
TestURLRequestContext context;
TestNetworkDelegate network_delegate;
context.set_network_delegate(&network_delegate);
TestDelegate d;
std::unique_ptr<URLRequest> req(
context.CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
TRAFFIC_ANNOTATION_FOR_TESTS));
req->SetReferrer("http://origin.com");
// Set a different policy just to make sure we aren't always logging the same
// policy.
req->set_referrer_policy(
ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE);
base::HistogramTester histograms;
req->Start();
d.RunUntilComplete();
histograms.ExpectUniqueSample(
"Net.URLRequest.ReferrerPolicyForRequest.CrossOrigin",
static_cast<int>(
ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
1);
}
TEST_F(URLRequestTest, RecordsReferrerHistogramAgainOnRedirect) {
TestURLRequestContext context;
BlockingNetworkDelegate network_delegate(
BlockingNetworkDelegate::SYNCHRONOUS);
network_delegate.set_redirect_url(GURL("http://redirect.com/"));
context.set_network_delegate(&network_delegate);
TestDelegate d;
std::unique_ptr<URLRequest> req(
context.CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
TRAFFIC_ANNOTATION_FOR_TESTS));
req->SetReferrer("http://google.com");
req->set_referrer_policy(
ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE);
base::HistogramTester histograms;
req->Start();
d.RunUntilRedirect();
histograms.ExpectUniqueSample(
"Net.URLRequest.ReferrerPolicyForRequest.SameOrigin",
static_cast<int>(
ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
1);
req->FollowDeferredRedirect(/*removed_headers=*/absl::nullopt,
/*modified_headers=*/absl::nullopt);
d.RunUntilComplete();
histograms.ExpectUniqueSample(
"Net.URLRequest.ReferrerPolicyForRequest.CrossOrigin",
static_cast<int>(
ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
1);
}
TEST_F(URLRequestTest, RecordsReferrrerWithInformativePath) {
TestURLRequestContext context;
BlockingNetworkDelegate network_delegate(
BlockingNetworkDelegate::SYNCHRONOUS);
network_delegate.set_cancel_request_with_policy_violating_referrer(true);
context.set_network_delegate(&network_delegate);
network_delegate.set_redirect_url(GURL("http://redirect.com/"));
TestDelegate d;
std::unique_ptr<URLRequest> req(
context.CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
TRAFFIC_ANNOTATION_FOR_TESTS));
// Since this referrer is much more informative than the initiating origin,
// we should see the histograms' true buckets populated.
req->SetReferrer("http://google.com/very-informative-path");
base::HistogramTester histograms;
req->Start();
d.RunUntilRedirect();
histograms.ExpectUniqueSample(
"Net.URLRequest.ReferrerHasInformativePath.SameOrigin",
/* Check the count of the "true" bucket in the boolean histogram. */ true,
1);
req->FollowDeferredRedirect(/*removed_headers=*/absl::nullopt,
/*modified_headers=*/absl::nullopt);
d.RunUntilComplete();
histograms.ExpectUniqueSample(
"Net.URLRequest.ReferrerHasInformativePath.CrossOrigin", true, 1);
}
TEST_F(URLRequestTest, RecordsReferrerWithInformativeQuery) {
TestURLRequestContext context;
BlockingNetworkDelegate network_delegate(
BlockingNetworkDelegate::SYNCHRONOUS);
network_delegate.set_cancel_request_with_policy_violating_referrer(true);
context.set_network_delegate(&network_delegate);
network_delegate.set_redirect_url(GURL("http://redirect.com/"));
TestDelegate d;
std::unique_ptr<URLRequest> req(
context.CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
TRAFFIC_ANNOTATION_FOR_TESTS));
// Since this referrer is much more informative than the initiating origin,
// we should see the histograms' true buckets populated.
req->SetReferrer("http://google.com/?very-informative-query");
base::HistogramTester histograms;
req->Start();
d.RunUntilRedirect();
histograms.ExpectUniqueSample(
"Net.URLRequest.ReferrerHasInformativePath.SameOrigin",
/* Check the count of the "true" bucket in the boolean histogram. */ true,
1);
req->FollowDeferredRedirect(/*removed_headers=*/absl::nullopt,
/*modified_headers=*/absl::nullopt);
d.RunUntilComplete();
histograms.ExpectUniqueSample(
"Net.URLRequest.ReferrerHasInformativePath.CrossOrigin", true, 1);
}
TEST_F(URLRequestTest, RecordsReferrerWithoutInformativePathOrQuery) {
TestURLRequestContext context;
BlockingNetworkDelegate network_delegate(
BlockingNetworkDelegate::SYNCHRONOUS);
network_delegate.set_cancel_request_with_policy_violating_referrer(false);
context.set_network_delegate(&network_delegate);
network_delegate.set_redirect_url(GURL("http://origin.com/"));
TestDelegate d;
std::unique_ptr<URLRequest> req(
context.CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
TRAFFIC_ANNOTATION_FOR_TESTS));
// Since this referrer _isn't_ more informative than the initiating origin,
// we should see the histograms' false buckets populated.
req->SetReferrer("http://origin.com");
base::HistogramTester histograms;
req->Start();
d.RunUntilRedirect();